code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
/* * Copyright (c) 2010-2011 Brigham Young University * * This file is part of the BYU RapidSmith Tools. * * BYU RapidSmith Tools is free software: you may 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 of * the License, or (at your option) any later version. * * BYU RapidSmith Tools 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. * * A copy of the GNU General Public License is included with the BYU * RapidSmith Tools. It can be found at doc/gpl2.txt. You may also * get a copy of the license at <http://www.gnu.org/licenses/>. * */ package edu.byu.ece.rapidSmith.bitstreamTools.bitstream.test; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class XilinxPartgenDescription { public XilinxPartgenDescription(List<String> partNames, List<List<String>> validPackages, List<List<String>> validSpeedGrades) { _partNames = new ArrayList<String>(partNames); _validPackages = new LinkedHashMap<String, List<String>>(); _validSpeedGrades = new LinkedHashMap<String, List<String>>(); int i = 0; for (String partName : _partNames) { _validPackages.put(partName, new ArrayList<String>(validPackages.get(i))); _validSpeedGrades.put(partName, new ArrayList<String>(validSpeedGrades.get(i))); i++; } } public List<String> getPartNames() { return new ArrayList<String>(_partNames); } public List<String> getValidPackagesForPart(String partName) { List<String> result = null; List<String> packages = _validPackages.get(partName); if (packages != null) { result = new ArrayList<String>(packages); } return result; } public List<String> getValidSpeedGradesForPart(String partName) { List<String> result = null; List<String> speedGrades = _validSpeedGrades.get(partName); if (speedGrades != null) { result = new ArrayList<String>(speedGrades); } return result; } protected List<String> _partNames; protected Map<String, List<String>> _validPackages; protected Map<String, List<String>> _validSpeedGrades; }
ComputerArchitectureGroupPWr/JGenerilo
src/main/java/edu/byu/ece/rapidSmith/bitstreamTools/bitstream/test/XilinxPartgenDescription.java
Java
mit
2,516
package uk.joshiejack.gastronomy.tile.base; import com.google.common.collect.Lists; import uk.joshiejack.gastronomy.api.Appliance; import uk.joshiejack.gastronomy.api.ItemCookedEvent; import uk.joshiejack.gastronomy.client.renderer.tile.SpecialRenderDataCooking; import uk.joshiejack.gastronomy.cooking.Cooker; import uk.joshiejack.gastronomy.cooking.Ingredient; import uk.joshiejack.gastronomy.cooking.Recipe; import uk.joshiejack.gastronomy.GastronomyConfig; import uk.joshiejack.gastronomy.item.GastronomyItems; import uk.joshiejack.gastronomy.network.PacketSyncCooking; import uk.joshiejack.penguinlib.data.holder.HolderMeta; import uk.joshiejack.penguinlib.network.PenguinNetwork; import uk.joshiejack.penguinlib.tile.inventory.TileInventoryRotatable; import uk.joshiejack.penguinlib.client.renderer.tile.SpecialRenderData; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumHand; import net.minecraft.util.NonNullList; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.items.ItemHandlerHelper; import javax.annotation.Nonnull; import java.util.LinkedList; import java.util.List; import static uk.joshiejack.penguinlib.util.handlers.ValidatedStackHandler.NO_SLOT_FOUND; public class TileCooking extends TileInventoryRotatable { public static final String IN_UTENSIL = "InUtensil"; public static final int FINISH_SLOT = 20; protected static final int COOK_TIMER = 100; protected LinkedList<Integer> last = new LinkedList<>(); private final SpecialRenderData render = createRenderData(); public final Appliance appliance; protected final int timeRequired; private boolean cooking; protected int cookTimer; public enum PlaceIngredientResult { SUCCESS, FAILURE, MISSING_OVEN, MISSING_COUNTER } //Slot id 20 is for the result item public TileCooking(Appliance appliance) { this(appliance, COOK_TIMER); } public TileCooking(Appliance appliance, int timeRequired) { super(21); this.timeRequired = timeRequired; this.appliance = appliance; } public SpecialRenderData createRenderData() { return new SpecialRenderDataCooking(); } public SpecialRenderData getRenderData() { return render; } public boolean isCooking() { return cooking; } public void setCooking(boolean cooking, int cookTimer) { this.cooking = cooking; this.cookTimer = cookTimer; } @Override public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity packet) { super.onDataPacket(net, packet); if (last.size() > 0) { render.doRenderUpdate(world, pos, last.peekLast()); } } @Override public void handleUpdateTag(@Nonnull NBTTagCompound tag) { super.handleUpdateTag(tag); if (last.size() > 0) { render.doRenderUpdate(world, pos, last.peekLast()); } } @Override //Only allow one item in each slot public boolean isStackValidForInsertion(int slot, ItemStack stack) { return handler.getStackInSlot(FINISH_SLOT).isEmpty() && !Ingredient.registry.getValue(stack).isNone() && handler.getStackInSlot(slot).isEmpty(); } @Override public boolean isSlotValidForExtraction(int slot, int amount) { return !handler.getStackInSlot(FINISH_SLOT).isEmpty(); } @SuppressWarnings("ConstantConditions") @Override public boolean onRightClicked(EntityPlayer player, EnumHand hand) { //If we've got a finished item in the finish slot, then take it out ItemStack result = handler.getStackInSlot(FINISH_SLOT); ItemStack held = player.getHeldItem(hand); if (!result.isEmpty() && held.getItem() != GastronomyItems.UTENSIL) { Recipe recipe = Recipe.RECIPE_BY_STACK.get(new HolderMeta(result)); if (GastronomyConfig.enableDishRequirement && recipe != null && !recipe.getDish().isEmpty()) { if (held.getItem() == recipe.getDish().getItem() && held.getItemDamage() == recipe.getDish().getItemDamage() && held.getCount() >= result.getCount()) { held.shrink(result.getCount()); //Reduce the held item return giveToPlayer(player, result, FINISH_SLOT); } else { //TODO: Display error in chat that we don't have the right dish equipped return false; } } else return giveToPlayer(player, result, FINISH_SLOT); } else { if (!held.isEmpty()) { if (cooking && held.getItem() == GastronomyItems.UTENSIL && appliance == Appliance.COUNTER) { if (result.isEmpty()) { updateTick(); //Call on both sides, to allow for particles if neccessary } return true; } if (handleFluids(player, hand, held)) { cookTimer = 0; cooking = true; markDirty(); return true; } if (addIngredient(held)) return true; } //Since we haven't chopped, removed finished or inserted, attempt to remove the last stack int lastSlot = last.size() > 0 ? last.pollLast() : NO_SLOT_FOUND; if (lastSlot != NO_SLOT_FOUND) { ItemStack stack = handler.getStackInSlot(lastSlot); if (!stack.isEmpty()) { Cooker.removeUtensilTag(stack); return giveToPlayer(player, stack, lastSlot); } } } return false; } protected boolean handleFluids(EntityPlayer player, EnumHand hand, ItemStack held) { return false; } public boolean addIngredient(ItemStack stack) { if (hasPrereqs() != PlaceIngredientResult.SUCCESS) return false; Ingredient ingredient = Ingredient.registry.getValue(stack); if (!ingredient.isNone()) { int slot = handler.findEmptySlot(FINISH_SLOT); if (slot != NO_SLOT_FOUND) { if (!world.isRemote) { ItemStack copy = stack.copy(); copy.setCount(1); if (!copy.hasTagCompound()) { copy.setTagCompound(new NBTTagCompound()); } copy.getTagCompound().setBoolean(IN_UTENSIL, true); handler.setStackInSlot(slot, copy); stack.shrink(1); } last.add(slot); if (world.isRemote) { render.doRenderUpdate(world, pos, last.peekLast()); } cookTimer = 0; cooking = true; markDirty(); return true; } } return false; } protected boolean giveToPlayer(EntityPlayer player, ItemStack result, int slot) { if (!world.isRemote) { MinecraftForge.EVENT_BUS.post(new ItemCookedEvent(player, result, appliance)); ItemHandlerHelper.giveItemToPlayer(player, result); handler.setStackInSlot(slot, ItemStack.EMPTY); } return true; } @Override //Do cooking stuff public void updateTick() { if (cooking) { cookTimer++; if (world.isRemote) { animate(); //Animate } else { if (last.size() == 0) { cooking = false; markDirty(); } else if (cookTimer >= timeRequired) { NonNullList<ItemStack> stacks = NonNullList.create(); for (int i = 0; i < FINISH_SLOT; i++) { ItemStack stack = handler.getStackInSlot(i); if (!stack.isEmpty()) stacks.add(stack); handler.setStackInSlot(i, ItemStack.EMPTY); } handler.setStackInSlot(FINISH_SLOT, Cooker.cook(appliance, stacks, getFluids())); cooking = false; cookTimer = 0; markDirty(); onFinished(); } if (hasPrereqs() != PlaceIngredientResult.SUCCESS) { cooking = false; markDirty(); } } } } @Override public void markDirty() { super.markDirty(); if (!world.isRemote) { PenguinNetwork.sendToNearby(this, new PacketSyncCooking(pos, cooking, cookTimer)); } } public void onFinished() {} public List<FluidStack> getFluids() { return Lists.newArrayList(); } public PlaceIngredientResult hasPrereqs() { return PlaceIngredientResult.SUCCESS; } boolean isAbove(Appliance appliance) { TileEntity tile = world.getTileEntity(pos.down()); return tile instanceof TileCooking && ((TileCooking)tile).appliance == appliance; } @SideOnly(Side.CLIENT) public void animate() { render.rotate(world); //Rotate stuff } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); cooking = nbt.getBoolean("Cooking"); cookTimer = nbt.getInteger("CookTimer"); for (int l: nbt.getIntArray("Last")) { last.add(l); } } @Nonnull @Override public NBTTagCompound writeToNBT(NBTTagCompound nbt) { nbt.setBoolean("Cooking", cooking); nbt.setInteger("CookTimer", cookTimer); nbt.setIntArray("Last", last.stream().mapToInt(i->i).toArray()); return super.writeToNBT(nbt); } }
joshiejack/Harvest-Festival
src/main/java/uk/joshiejack/gastronomy/tile/base/TileCooking.java
Java
mit
10,191
/** * Class description goes here. * * @author [email protected] * @since Sep 20, 2015 * @version 1.0 * @see */ public class Test { public static void main(String[] args) { String a = "a"; String b = "a"; System.out.println(a == b); System.out.println(a.equals(b)); } }
nickevin/WebCollection
src/main/java/Test.java
Java
mit
320
package generated.zcsclient.admin; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for moveMailboxRequest complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="moveMailboxRequest"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="account" type="{urn:zimbraAdmin}moveMailboxInfo"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "moveMailboxRequest", propOrder = { "account" }) public class testMoveMailboxRequest { @XmlElement(required = true) protected testMoveMailboxInfo account; /** * Gets the value of the account property. * * @return * possible object is * {@link testMoveMailboxInfo } * */ public testMoveMailboxInfo getAccount() { return account; } /** * Sets the value of the account property. * * @param value * allowed object is * {@link testMoveMailboxInfo } * */ public void setAccount(testMoveMailboxInfo value) { this.account = value; } }
nico01f/z-pec
ZimbraSoap/src/wsdl-test/generated/zcsclient/admin/testMoveMailboxRequest.java
Java
mit
1,495
/** */ package CIM.IEC61970.Informative.InfERPSupport.impl; import CIM.IEC61968.Assets.Asset; import CIM.IEC61968.Assets.AssetsPackage; import CIM.IEC61968.Common.Status; import CIM.IEC61970.Core.impl.IdentifiedObjectImpl; import CIM.IEC61970.Informative.InfERPSupport.ErpItemMaster; import CIM.IEC61970.Informative.InfERPSupport.InfERPSupportPackage; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Erp Item Master</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link CIM.IEC61970.Informative.InfERPSupport.impl.ErpItemMasterImpl#getStatus <em>Status</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfERPSupport.impl.ErpItemMasterImpl#getAsset <em>Asset</em>}</li> * </ul> * * @generated */ public class ErpItemMasterImpl extends IdentifiedObjectImpl implements ErpItemMaster { /** * The cached value of the '{@link #getStatus() <em>Status</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStatus() * @generated * @ordered */ protected Status status; /** * The cached value of the '{@link #getAsset() <em>Asset</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getAsset() * @generated * @ordered */ protected Asset asset; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ErpItemMasterImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return InfERPSupportPackage.Literals.ERP_ITEM_MASTER; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Status getStatus() { if (status != null && status.eIsProxy()) { InternalEObject oldStatus = (InternalEObject)status; status = (Status)eResolveProxy(oldStatus); if (status != oldStatus) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, InfERPSupportPackage.ERP_ITEM_MASTER__STATUS, oldStatus, status)); } } return status; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Status basicGetStatus() { return status; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setStatus(Status newStatus) { Status oldStatus = status; status = newStatus; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, InfERPSupportPackage.ERP_ITEM_MASTER__STATUS, oldStatus, status)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Asset getAsset() { if (asset != null && asset.eIsProxy()) { InternalEObject oldAsset = (InternalEObject)asset; asset = (Asset)eResolveProxy(oldAsset); if (asset != oldAsset) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, InfERPSupportPackage.ERP_ITEM_MASTER__ASSET, oldAsset, asset)); } } return asset; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Asset basicGetAsset() { return asset; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetAsset(Asset newAsset, NotificationChain msgs) { Asset oldAsset = asset; asset = newAsset; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, InfERPSupportPackage.ERP_ITEM_MASTER__ASSET, oldAsset, newAsset); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setAsset(Asset newAsset) { if (newAsset != asset) { NotificationChain msgs = null; if (asset != null) msgs = ((InternalEObject)asset).eInverseRemove(this, AssetsPackage.ASSET__ERP_ITEM_MASTER, Asset.class, msgs); if (newAsset != null) msgs = ((InternalEObject)newAsset).eInverseAdd(this, AssetsPackage.ASSET__ERP_ITEM_MASTER, Asset.class, msgs); msgs = basicSetAsset(newAsset, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, InfERPSupportPackage.ERP_ITEM_MASTER__ASSET, newAsset, newAsset)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case InfERPSupportPackage.ERP_ITEM_MASTER__ASSET: if (asset != null) msgs = ((InternalEObject)asset).eInverseRemove(this, AssetsPackage.ASSET__ERP_ITEM_MASTER, Asset.class, msgs); return basicSetAsset((Asset)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case InfERPSupportPackage.ERP_ITEM_MASTER__ASSET: return basicSetAsset(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case InfERPSupportPackage.ERP_ITEM_MASTER__STATUS: if (resolve) return getStatus(); return basicGetStatus(); case InfERPSupportPackage.ERP_ITEM_MASTER__ASSET: if (resolve) return getAsset(); return basicGetAsset(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case InfERPSupportPackage.ERP_ITEM_MASTER__STATUS: setStatus((Status)newValue); return; case InfERPSupportPackage.ERP_ITEM_MASTER__ASSET: setAsset((Asset)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case InfERPSupportPackage.ERP_ITEM_MASTER__STATUS: setStatus((Status)null); return; case InfERPSupportPackage.ERP_ITEM_MASTER__ASSET: setAsset((Asset)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case InfERPSupportPackage.ERP_ITEM_MASTER__STATUS: return status != null; case InfERPSupportPackage.ERP_ITEM_MASTER__ASSET: return asset != null; } return super.eIsSet(featureID); } } //ErpItemMasterImpl
georghinkel/ttc2017smartGrids
solutions/ModelJoin/src/main/java/CIM/IEC61970/Informative/InfERPSupport/impl/ErpItemMasterImpl.java
Java
mit
7,139
package com.clockwise.tworcy.configuration.security; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl; import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; import com.clockwise.tworcy.controllers.Games; import com.clockwise.tworcy.model.account.AccountService; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { private @Autowired AccountService accounts; private @Autowired DataSource dataSource; private static final Logger logger = Logger.getLogger(SecurityConfiguration.class); public @Autowired void configureGlobalSecurity( AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(accounts).passwordEncoder(new BCryptPasswordEncoder()); } public @Override void configure(WebSecurity webSecurity) throws Exception { webSecurity.ignoring().antMatchers("/resources/**"); } protected @Override void configure(HttpSecurity http) throws Exception { // @formatter:off http.authorizeRequests() // Admins .antMatchers("/admin/**") .access("hasRole('ADMIN')") // Database admins .antMatchers("/db/**") .access("hasRole('ADMIN') and hasRole('DBA')") .and() // Login form settings .formLogin().loginPage("/account/login").loginProcessingUrl("/account/login") .usernameParameter("name") .passwordParameter("password") .and().csrf().and() // Remember me settings .rememberMe().rememberMeParameter("remember-me") .tokenRepository(persistentTokenRepository()) .tokenValiditySeconds(86400).and().csrf() .and() .exceptionHandling().accessDeniedPage("/Access_Denied").accessDeniedHandler(accessDeniedHandler()); /*/ Logged in .antMatchers( "/news/edit/", "/news/edit/**", "/game/edit/", "/game/edit/**") .access("hasRole('NORMAL')") .antMatchers(HttpMethod.POST, "/news/edit/", "/news/edit/**", "/game/edit/", "/game/edit/**") .access("hasRole('NORMAL')") // Admins .antMatchers("/admin/**") .access("hasRole('ADMIN')") // Database admins .antMatchers("/db/**") .access("hasRole('ADMIN') and hasRole('DBA')")*/ // @formatter:on } private AccessDeniedHandler accessDeniedHandler() { return new AccessDeniedHandler() { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { logger.error(this.getClass().getSimpleName()+".accessDeniedHandler\n"+accessDeniedException.getMessage()); // response.setStatus(HttpStatus.FORBIDDEN.value()); } }; } public @Bean PersistentTokenRepository persistentTokenRepository() { JdbcTokenRepositoryImpl tokenRepositoryImpl = new JdbcTokenRepositoryImpl(); tokenRepositoryImpl.setDataSource(dataSource); return tokenRepositoryImpl; } }
ghandhikus/TworcyGierStrona
src/main/java/com/clockwise/tworcy/configuration/security/SecurityConfiguration.java
Java
mit
4,137
package com.main; import java.awt.EventQueue; import com.lac.ui.mainscreens.MainFrame; public class BarberiaMain { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MainFrame frame = new MainFrame(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } }
LAC-UNC/ChimpStudyCases
Barberia/src/com/main/BarberiaMain.java
Java
mit
382
/* * The MIT License * * Copyright 2016 gburdell. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package laol.ast; import java.util.List; /** * * @author gburdell */ public class SassPrimary extends Item { public SassPrimary(final laol.parser.apfe.SassPrimary decl) { super(decl); m_contents = zeroOrMore(2, 0); } private final List<SassContent> m_contents; }
gburdell/laol
src/laol/ast/SassPrimary.java
Java
mit
1,432
package org.gw4e.eclipse.handlers; /*- * #%L * gw4e * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2017 gw4e-project * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; import org.gw4e.eclipse.facade.GraphWalkerContextManager; import org.gw4e.eclipse.facade.ResourceManager; /** * A Command handler to call GW4E Synchronization between java file and * build policies when selection fits * * @see org.eclipse.core.commands.IHandler * @see org.eclipse.core.commands.AbstractHandler */ public class SynchronizeBuildPoliciesHandler extends AbstractHandler { /** * The constructor. */ public SynchronizeBuildPoliciesHandler() { } public Object execute(ExecutionEvent event) throws ExecutionException { boolean autoBuilding = ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding(); IWorkbenchWindow aww = HandlerUtil.getActiveWorkbenchWindow(event); ISelection sel = HandlerUtil.getCurrentSelection(event); if (sel.isEmpty()) return null; if (sel instanceof IStructuredSelection) { IStructuredSelection selection = (IStructuredSelection) sel; if (selection != null) { Object obj = selection.getFirstElement(); if (obj != null) { try { IResource selectedResource = null; if (obj instanceof IJavaProject) { IJavaProject jp = (IJavaProject) obj; selectedResource = jp.getProject(); } if (obj instanceof IPackageFragmentRoot) { IPackageFragmentRoot pfr = (IPackageFragmentRoot) obj; selectedResource = pfr.getCorrespondingResource(); } if (obj instanceof IPackageFragment) { IPackageFragment pf = (IPackageFragment) obj; selectedResource = pf.getCorrespondingResource(); } if (selectedResource != null && !selectedResource.exists()) return null; // This is where the synchronization is done ... ResourceManager.setAutoBuilding(false); GraphWalkerContextManager.synchronizeBuildPolicies(selectedResource, aww); } catch (Exception e) { ResourceManager.logException(e); } finally { ResourceManager.setAutoBuilding(autoBuilding); } } } } return null; } }
gw4e/gw4e.project
bundles/gw4e-eclipse-plugin/src/org/gw4e/eclipse/handlers/SynchronizeBuildPoliciesHandler.java
Java
mit
3,768
package json.gson; import java.util.List; import com.google.gson.annotations.SerializedName; public class TestYesNoQuestion extends TestQuestion { @SerializedName("exact_answer") private String exactAnswer; protected TestYesNoQuestion(String id, String body, QuestionType type, List<String> documents, List<Snippet> snippets, List<String> concepts, List<Triple> triples, String idealAnswer, String exactAnswer) { super(id, body, type, documents, snippets, concepts, triples, idealAnswer); this.exactAnswer = exactAnswer; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((exactAnswer == null) ? 0 : exactAnswer.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; TestYesNoQuestion other = (TestYesNoQuestion) obj; if (exactAnswer == null) { if (other.exactAnswer != null) return false; } else if (!exactAnswer.equals(other.exactAnswer)) return false; return true; } public String getExactAnswer() { return exactAnswer; } }
junanita/project-team05
project-team05/src/main/java/json/gson/TestYesNoQuestion.java
Java
mit
1,276
package acceptableLosses.systems; import acceptableLosses.components.Citizen; import acceptableLosses.components.Position; import acceptableLosses.screens.GameScreen; import com.artemis.Aspect; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.annotations.Wire; import com.artemis.systems.EntityProcessingSystem; import com.badlogic.gdx.graphics.g2d.SpriteBatch; public class CitizenRenderSystem extends EntityProcessingSystem { @Wire ComponentMapper<Citizen> cm; @Wire ComponentMapper<Position> pm; private GameScreen gameScreen; private SpriteBatch spriteBatch; public CitizenRenderSystem(GameScreen gameScreen, SpriteBatch spriteBatch) { super(Aspect.getAspectForAll(Citizen.class, Position.class)); this.gameScreen = gameScreen; this.spriteBatch = spriteBatch; } @Override protected void process(Entity e) { Position position = pm.get(e); if (position.z != gameScreen.zLevel) { // TODO: check to see if we are on screen horizontally, no sense drawing stuff off screen. return; } Citizen citizen = cm.get(e); // BODY if (citizen.skinColor != null) { spriteBatch.setColor(citizen.skinColor.color); } else { spriteBatch.setColor(1, 1, 1, 1); } spriteBatch.draw(citizen.bodyShape.texture, position.x, position.y, 1, 1); // GARMENT spriteBatch.setColor(citizen.garmentColor.r, citizen.garmentColor.g, citizen.garmentColor.b, 1); if (citizen.garment != null) { spriteBatch.draw(citizen.garment.texture, position.x, position.y, 1, 1); } //HAIR or HAT spriteBatch.setColor(citizen.hatColor.r, citizen.hatColor.g, citizen.hatColor.b, 1); if (citizen.hat != null) { spriteBatch.draw(citizen.hat.texture, position.x, position.y, 1, 1); } else if (citizen.hairStyle != null && citizen.hairStyle.texture != null) { if (citizen.hairColor != null) { spriteBatch.setColor(citizen.hairColor.color); } else spriteBatch.setColor(1, 1, 1, 1); spriteBatch.draw(citizen.hairStyle.texture, position.x, position.y, 1, 1); } } }
stewsters/acceptableLosses
core/src/acceptableLosses/systems/CitizenRenderSystem.java
Java
mit
2,311
package com.github.games647.fastlogin.core; public enum PremiumStatus { PREMIUM("Premium"), CRACKED("Cracked"), UNKNOWN("Unknown"); private final String readableName; PremiumStatus(String readableName) { this.readableName = readableName; } public String getReadableName() { return readableName; } }
sgdc3/FastLogin
core/src/main/java/com/github/games647/fastlogin/core/PremiumStatus.java
Java
mit
354
package com.futurose.embeddedjvm; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; public class EmbeddedJvmOutputStream extends OutputStream { public EmbeddedJvmOutputStream(String tag) { nativeOpen(tag); } @Override public void write(int b) throws IOException { byte[] bytes = new byte[1]; bytes[0] = (byte)b; nativeWrite(bytes, 0, 1); } @Override public void write(byte[] b) throws IOException { nativeWrite(b, 0, b.length); } @Override public void write(byte[] b, int off, int len) throws IOException { nativeWrite(b, off, len); } @Override public void flush() throws IOException { nativeFlush(); } @Override public void close() throws IOException { nativeClose(); } static void redirectStandardStreams() throws Exception { System.setOut(new PrintStream(new EmbeddedJvmOutputStream("out"))); System.setErr(new PrintStream(new EmbeddedJvmOutputStream("err"))); } native void nativeWrite(byte[] bytes, int off, int len); native void nativeOpen(String name); native void nativeClose(); native void nativeFlush(); }
esorf/EmbeddedJvm
Java/src/main/java/com/futurose/embeddedjvm/EmbeddedJvmOutputStream.java
Java
mit
1,107
/* * The MIT License (MIT) * * Copyright (c) 2016 Jakob Hendeß * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.xlrnet.metadict.api.engine; /** * Abstract implementation of {@link SearchEngineProvider} which can already be used as an injectable Guice module. */ public abstract class AbstractSearchEngineProvider implements SearchEngineProvider { }
jhendess/metadict
metadict-api/src/main/java/org/xlrnet/metadict/api/engine/AbstractSearchEngineProvider.java
Java
mit
1,400
package net.minecraft.src.nucleareal.animalcrossing; import java.util.ArrayList; import java.util.List; import java.util.Random; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.src.nucleareal.UtilMinecraft; import net.minecraft.src.nucleareal.animalcrossing.entity.EntityInukichi; import net.minecraft.src.nucleareal.animalcrossing.inukichi.InukichiShopStructure; import net.minecraft.src.nucleareal.animalcrossing.inukichi.InukichiValue; import net.minecraft.src.nucleareal.animalcrossing.maplesisters.EntityMapleAkaha; import net.minecraft.src.nucleareal.animalcrossing.maplesisters.EntityMapleKiyo; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.chunk.IChunkProvider; import cpw.mods.fml.common.IWorldGenerator; public class GeneratorInukichiShop implements IWorldGenerator { private List<Integer> canGenerateBiomeList; { canGenerateBiomeList = new ArrayList<Integer>(); canGenerateBiomeList.add(BiomeGenBase.plains.biomeID); canGenerateBiomeList.add(BiomeGenBase.desert.biomeID); canGenerateBiomeList.add(BiomeGenBase.icePlains.biomeID); canGenerateBiomeList.add(BiomeGenBase.forest.biomeID); canGenerateBiomeList.add(BiomeGenBase.river.biomeID); } @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { if(isGenerated || random.nextInt(512) != 0) return; BiomeGenBase base = world.getBiomeGenForCoordsBody(chunkX << 4, chunkZ << 4); if(canGenerateBiomeList.contains(Integer.valueOf(base.biomeID))) { generateShop(world, chunkX << 4, world.getActualHeight()-1, chunkZ << 4, random); } } private void generateShop(World world, int x, int y, int z, Random random) { int i; for(i = 0; world.isAirBlock(x, y-i, z) && world.isAirBlock(x+13, y-i, z) && world.isAirBlock(x, y-i, z+13) && world.isAirBlock(x+13, y-i, z+13); i++); i--; y -= i; isGenerated = true; generatedX = x; generatedX = y; generatedX = z; addWorldOriginalPosition(world, x, y, z); InukichiShopStructure.generate(world, x, y, z); EntityInukichi entity = new EntityInukichi(world); entity.setPosition(x+7, y, z+4); world.spawnEntityInWorld(entity); EntityMapleAkaha entityAkaha = new EntityMapleAkaha(world); entityAkaha.setPosition(x+6, y+4, z+4); world.spawnEntityInWorld(entityAkaha); EntityMapleKiyo entityKiyo = new EntityMapleKiyo(world); entityKiyo.setPosition(x+8, y+4, z+4); world.spawnEntityInWorld(entityKiyo); } private static final String ss = "ShopSpace"; private void addWorldOriginalPosition(World world, int x, int y, int z) { AnimalCrossing.NBT.setWorldOriginalValue(world, ss, getPositionFormat(x, y, z)); } private String getPositionFormat(int x, int y, int z) { return String.format("%d,%d,%d", x, y, z); } public static void onWorldChanged(EntityPlayer player) { isGenerated = false; String value = AnimalCrossing.NBT.getWorldOriginalValue(player.worldObj, ss); if(value != null) { isGenerated = true; String[] values = value.split(","); try { generatedX = Integer.valueOf(values[0]); generatedY = Integer.valueOf(values[1]); generatedZ = Integer.valueOf(values[2]); } catch(Exception e) { isGenerated = false; } } } public static void removeWall(int level) { World world = UtilMinecraft.getWorldAndPlayer("").getV1(); switch(level) { default: break; case 1: InukichiShopStructure.removeLevel(world, generatedX, generatedY, generatedZ, InukichiValue.L1Wall); break; case 2: InukichiShopStructure.removeLevel(world, generatedX, generatedY, generatedZ, InukichiValue.L2Wall); break; case 3: InukichiShopStructure.removeLevel(world, generatedX, generatedY, generatedZ, InukichiValue.L3Wall); break; } } public static synchronized boolean getIsGenerated() { return isGenerated; } private static volatile boolean isGenerated; public static int generatedX; public static int generatedY; public static int generatedZ; }
Nucleareal/nucleareal
animalcrossing/GeneratorInukichiShop.java
Java
mit
4,075
package com.shcem.configCenter.model; public class DefaultOptions { public final static boolean USE_REMOTE_CONFIG=true; public final static int CHECK_ZK_LIVE_INTERVAL_MINUTES=1; }
judypol/jshcem
common/src/main/java/com/shcem/configCenter/model/DefaultOptions.java
Java
mit
192
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.datasource; import com.facebook.common.internal.Preconditions; import java.util.Map; /** Settable {@link DataSource}. */ public class SimpleDataSource<T> extends AbstractDataSource<T> { private SimpleDataSource() {} /** Creates a new {@link SimpleDataSource}. */ public static <T> SimpleDataSource<T> create() { return new SimpleDataSource<T>(); } /** * Sets the result to {@code value}. * * <p>This method will return {@code true} if the value was successfully set, or {@code false} if * the data source has already been set, failed or closed. * * <p>If the value was successfully set and {@code isLast} is {@code true}, state of the data * source will be set to {@link AbstractDataSource.DataSourceStatus#SUCCESS}. * * <p>This will also notify the subscribers if the value was successfully set. * * @param value the value to be set * @param isLast whether or not the value is last. * @return true if the value was successfully set. */ @Override public boolean setResult(T value, boolean isLast, Map<String, Object> extras) { return super.setResult(Preconditions.checkNotNull(value), isLast, extras); } /** * Sets the value as the last result. * * <p>See {@link #setResult(T value, boolean isLast)}. */ public boolean setResult(T value) { return super.setResult(Preconditions.checkNotNull(value), /* isLast */ true, null); } /** * Sets the failure. * * <p>This method will return {@code true} if the failure was successfully set, or {@code false} * if the data source has already been set, failed or closed. * * <p>If the failure was successfully set, state of the data source will be set to {@link * AbstractDataSource.DataSourceStatus#FAILURE}. * * <p>This will also notify the subscribers if the failure was successfully set. * * @param throwable the failure cause to be set. * @return true if the failure was successfully set. */ @Override public boolean setFailure(Throwable throwable) { return super.setFailure(Preconditions.checkNotNull(throwable)); } /** * Sets the progress. * * @param progress the progress in range [0, 1] to be set. * @return true if the progress was successfully set. */ @Override public boolean setProgress(float progress) { return super.setProgress(progress); } }
facebook/fresco
fbcore/src/main/java/com/facebook/datasource/SimpleDataSource.java
Java
mit
2,582
package com.hal9000.solver; import org.junit.Test; import com.hal9000.data.TSPInstance; import com.hal9000.env.Environment; import com.hal9000.solver.Solution; import com.hal9000.solver.move.*; import java.util.ArrayList; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /*/* * Created by mis on 15.11.15. */ public class City2OptTest { private Opt mover; private ArrayList<Integer> sequence; private Solution solution; private int dim = 10; private TSPInstance problem; public void setUp() { mover = new City2Opt(); setUpSequence(); solution = mock(Solution.class); problem = mock(TSPInstance.class); when(solution.getSolution()).thenReturn(sequence); when(solution.getProblem()).thenReturn(problem); } @Test public void testMove() { for (int i = 0; i < dim; i++) { for (int j = i + 1; j < dim; j++) { testMove(i, j); } } } private void testMove(int i, int j) { setUp(); ArrayList<Integer> expected = new ArrayList<>(); for (int k = 0; k < i; k++) { expected.add(k); } expected.add(j); for (int k = i + 1; k < j; k++) { expected.add(k); } expected.add(i); for (int k = j + 1; k < dim; k++) { expected.add(k); } mover.move(i, j, solution); assertArrayEquals(expected.toArray(), solution.getSolution().toArray()); } @Test public void testGetMoveDeltaWhenN_0_last() throws Exception { setUp(); when(problem.getDistance(0, dim-1)).thenReturn(10.0); when(problem.getDistance(dim-1, 0)).thenReturn(10.0); when(problem.getDistance(0, 1)).thenReturn(50.0); when(problem.getDistance(dim-1, dim-2)).thenReturn(22.0); when(problem.getDistance(dim-1, 1)).thenReturn(15.0); when(problem.getDistance(0, dim-2)).thenReturn(393.0); assertEquals(-22.0 - 50.0 + 393.0 + 15.0, mover.getMoveDelta(0, dim-1, solution), Environment.eps); } @Test public void testGetMoveDeltaWhenN_0_1() throws Exception { setUp(); when(problem.getDistance(0, 1)).thenReturn(10.0); when(problem.getDistance(1, 0)).thenReturn(10.0); when(problem.getDistance(0, dim-1)).thenReturn(50.0); when(problem.getDistance(1, dim-1)).thenReturn(22.0); when(problem.getDistance(1, 2)).thenReturn(15.0); when(problem.getDistance(0, 2)).thenReturn(393.0); assertEquals(-50.0 - 15.0 + 22.0 + 393.0, mover.getMoveDelta(0, 1, solution), Environment.eps); } @Test public void testGetMoveDeltaWhenN_1_4() throws Exception { setUp(); when(problem.getDistance(1, 0)).thenReturn(10.0); when(problem.getDistance(1, 2)).thenReturn(121.0); when(problem.getDistance(4, 5)).thenReturn(50.0); when(problem.getDistance(4, 3)).thenReturn(23.0); when(problem.getDistance(4, 0)).thenReturn(76.0); when(problem.getDistance(4, 2)).thenReturn(8.0); when(problem.getDistance(1, 3)).thenReturn(89.0); when(problem.getDistance(1, 5)).thenReturn(142.0); assertEquals(-10.0 - 121.0 - 50.0 - 23.0 + 76.0 + 8.0 + 89.0 +142.0, mover.getMoveDelta(1, 4, solution), Environment.eps); } private void setUpSequence() { sequence = new ArrayList<>(); for (int i = 0; i < dim; i++) { sequence.add(i); } } }
m87/tsp-miob
tsp/src/test/java/com/hal9000/solver/City2OptTest.java
Java
mit
3,574
package org.innovateuk.ifs.interview.builder; import org.innovateuk.ifs.BaseBuilder; import org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions; import org.innovateuk.ifs.file.domain.FileEntry; import org.innovateuk.ifs.interview.domain.InterviewAssignmentMessageOutcome; import java.time.ZonedDateTime; import java.util.List; import java.util.function.BiConsumer; import static java.util.Collections.emptyList; public class InterviewAssignmentMessageOutcomeBuilder extends BaseBuilder<InterviewAssignmentMessageOutcome, InterviewAssignmentMessageOutcomeBuilder> { private InterviewAssignmentMessageOutcomeBuilder(List<BiConsumer<Integer, InterviewAssignmentMessageOutcome>> multiActions) { super(multiActions); } public static InterviewAssignmentMessageOutcomeBuilder newInterviewAssignmentMessageOutcome() { return new InterviewAssignmentMessageOutcomeBuilder(emptyList()); } @Override protected InterviewAssignmentMessageOutcomeBuilder createNewBuilderWithActions(List<BiConsumer<Integer, InterviewAssignmentMessageOutcome>> actions) { return new InterviewAssignmentMessageOutcomeBuilder(actions); } @Override protected InterviewAssignmentMessageOutcome createInitial() { return new InterviewAssignmentMessageOutcome(); } public InterviewAssignmentMessageOutcomeBuilder withId(Long... ids) { return withArray(BaseBuilderAmendFunctions::setId, ids); } public InterviewAssignmentMessageOutcomeBuilder withSubject(String... subjects) { return withArray((subject, assessmentInterviewPanelMessageOutcome) -> assessmentInterviewPanelMessageOutcome.setSubject(subject), subjects); } public InterviewAssignmentMessageOutcomeBuilder withMessage(String... messages) { return withArray((message, assessmentInterviewPanelMessageOutcome) -> assessmentInterviewPanelMessageOutcome.setMessage(message), messages); } public InterviewAssignmentMessageOutcomeBuilder withFeedback(FileEntry... feedbacks) { return withArray((feedback, assessmentInterviewPanelMessageOutcome) -> assessmentInterviewPanelMessageOutcome.setFeedback(feedback), feedbacks); } public InterviewAssignmentMessageOutcomeBuilder withCreatedOn(ZonedDateTime... createdOns) { return withArraySetFieldByReflection("createdOn", createdOns); } public InterviewAssignmentMessageOutcomeBuilder withModifiedOn(ZonedDateTime... modifiedOns) { return withArraySetFieldByReflection("modifiedOn", modifiedOns); } }
InnovateUKGitHub/innovation-funding-service
ifs-data-layer/ifs-data-service/src/test/java/org/innovateuk/ifs/interview/builder/InterviewAssignmentMessageOutcomeBuilder.java
Java
mit
2,545
package com.javarush.task.task19.task1928; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /* Исправить ошибку. Классы и интерфейсы Программа содержит всего 1 логическую ошибку. Найди и исправь ее. */ public class Solution { { System.out.println("it's Solution class"); } public static void main(String... args) throws IOException { try ( FileOutputStream outputStream = new FileOutputStream("c:/file.txt"); InputStream is = Solution.class.getClassLoader().getResourceAsStream("/tst/lena.jpg"); ) { ; byte[] b = new byte[is.available()]; outputStream.write(is.read(b)); int value = 123_456_789; System.out.println(value); Example result = null; String s = "a"; switch (s) { case "a": { result = new Solution().new A(); break; } case "b": { result = new Solution().new B(); break; } case "c": { result = new Solution().new C(); break; } } if (result instanceof C) { C p = (C) result; System.out.println(p.getClass().getSimpleName()); } } catch (IOException e) { } } interface Example { } class A implements Example { { System.out.println("it's A class"); } } class B implements Example { { System.out.println("it's B class"); } } class C extends A { { System.out.println("it's C class"); } } }
avedensky/JavaRushTasks
2.JavaCore/src/com/javarush/task/task19/task1928/Solution.java
Java
mit
1,917
package seedu.Tdoo.testutil; import seedu.Tdoo.model.task.*; import seedu.Tdoo.model.task.attributes.*; /** * A mutable task object. For testing only. */ // @@author A0132157M public class TestEvent implements ReadOnlyTask { // private Event event; private Name name; private StartDate startDate; private String endDate; private String startTime; private String endTime; private String done; public TestEvent() { super(); // tags = new UniqueTagList(); } public void setName(Name name) { this.name = name; } public void setStartDate(StartDate date) { this.startDate = date; } public void setEndDate(String date) { this.endDate = date; } public void setDone(String done) { this.done = done; } public void setStartTime(String st) { this.startTime = st; } public void setEndTime(String et) { this.endTime = et; } // @Override public String getStartTime() { return startTime; } @Override public Name getName() { return name; } @Override public StartDate getStartDate() { return startDate; } public String getEndDate() { return endDate; } public String getEndTime() { return endTime; } public String getDone() { return done; } public String getAddCommand() { StringBuilder sb = new StringBuilder(); sb.append("add " + this.getName().name + " "); sb.append("from/01-01-2017 ");// + this.getStartDate().toString() + " // "); sb.append("to/" + this.getEndDate().toString() + " "); sb.append("at/" + this.getStartTime().toString() + " "); sb.append("to/" + this.getEndTime().toString()); // this.getTags().getInternalList().stream().forEach(s -> sb.append("t/" // + s.tagName + " ")); return sb.toString(); } }
CS2103AUG2016-T14-C1/main
src/test/java/seedu/Tdoo/testutil/TestEvent.java
Java
mit
1,717
package joshie.harvest.animals.entity; import io.netty.buffer.ByteBuf; import joshie.harvest.animals.HFAnimals; import joshie.harvest.animals.entity.ai.EntityAIEatLivestock; import joshie.harvest.animals.entity.ai.EntityAIFindShelterOrSun; import joshie.harvest.animals.item.ItemAnimalTool.Tool; import joshie.harvest.api.HFApi; import joshie.harvest.api.animals.AnimalAction; import joshie.harvest.api.animals.AnimalStats; import joshie.harvest.api.animals.AnimalTest; import joshie.harvest.api.animals.IAnimalHandler.AnimalType; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.*; import net.minecraft.entity.passive.EntityCow; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.pathfinding.PathNodeType; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.SoundEvent; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.fml.common.network.ByteBufUtils; import net.minecraftforge.fml.common.registry.IEntityAdditionalSpawnData; import javax.annotation.Nonnull; import javax.annotation.Nullable; import static joshie.harvest.api.animals.IAnimalHandler.ANIMAL_STATS_CAPABILITY; import static joshie.harvest.core.helpers.InventoryHelper.ITEM; import static joshie.harvest.core.helpers.InventoryHelper.ITEM_STACK; public class EntityHarvestCow extends EntityCow implements IEntityAdditionalSpawnData { private final AnimalStats<NBTTagCompound> stats = HFApi.animals.newStats(AnimalType.MILKABLE); private static ItemStack[] stacks; public EntityHarvestCow(World world) { super(world); setSize(1.4F, 1.4F); setPathPriority(PathNodeType.WATER, 0.0F); } @Override protected void initEntityAI() { tasks.addTask(0, new EntityAISwimming(this)); tasks.addTask(1, new EntityAIPanic(this, 2.0D)); tasks.addTask(2, new EntityAITempt(this, 1.25D, Items.WHEAT, false)); tasks.addTask(3, new EntityAIFollowParent(this, 1.25D)); tasks.addTask(4, new EntityAIEatLivestock(this)); tasks.addTask(5, new EntityAIFindShelterOrSun(this)); tasks.addTask(6, new EntityAIWander(this, 1.0D)); tasks.addTask(7, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F)); tasks.addTask(8, new EntityAILookIdle(this)); } @Override protected void applyEntityAttributes() { super.applyEntityAttributes(); getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(50.0D); } private static ItemStack[] getStacks() { if (stacks != null) return stacks; stacks = new ItemStack[] { HFAnimals.TOOLS.getStackFromEnum(Tool.BRUSH), HFAnimals.TOOLS.getStackFromEnum(Tool.MILKER), HFAnimals.TOOLS.getStackFromEnum(Tool.MEDICINE), HFAnimals.TOOLS.getStackFromEnum(Tool.MIRACLE_POTION) }; return stacks; } @Override public boolean processInteract(@Nullable EntityPlayer player, @Nullable EnumHand hand, ItemStack stack) { if (player == null) return false; boolean special = ITEM_STACK.matchesAny(stack, getStacks()) || ITEM.matchesAny(stack, HFAnimals.TREATS); if (stack == null || !special) { if (!stats.performTest(AnimalTest.BEEN_LOVED)) { stats.performAction(world, null, AnimalAction.PETTED); //Love <3 SoundEvent s = getAmbientSound(); if (s != null) { playSound(s, 2F, getSoundPitch()); } return true; } else return false; } else return false; } @Override @Nonnull public EntityCow createChild(EntityAgeable ageable) { return new EntityHarvestCow(this.world); } @Override @SuppressWarnings("ConstantConditions") public boolean hasCapability(@Nonnull Capability<?> capability, EnumFacing facing) { return capability == ANIMAL_STATS_CAPABILITY || super.hasCapability(capability, facing); } @Override @SuppressWarnings("unchecked, ConstantConditions") @Nonnull public <T> T getCapability(@Nonnull Capability<T> capability, EnumFacing facing) { return capability == ANIMAL_STATS_CAPABILITY ? (T) stats : super.getCapability(capability, facing); } @Override public void writeEntityToNBT(NBTTagCompound compound) { super.writeEntityToNBT(compound); compound.setTag("Stats", stats.serializeNBT()); } @Override public void readEntityFromNBT(NBTTagCompound compound) { super.readEntityFromNBT(compound); if (compound.hasKey("Stats")) stats.deserializeNBT(compound.getCompoundTag("Stats")); //TODO: Remove in 0.7+ else if (compound.hasKey("CurrentLifespan")) stats.deserializeNBT(compound); } @Override public void writeSpawnData(ByteBuf buffer) { ByteBufUtils.writeTag(buffer, stats.serializeNBT()); } @Override public void readSpawnData(ByteBuf buffer) { stats.setEntity(this); stats.deserializeNBT(ByteBufUtils.readTag(buffer)); } }
PenguinSquad/Harvest-Festival
src/main/java/joshie/harvest/animals/entity/EntityHarvestCow.java
Java
mit
5,356
package com.countmein.countmein.eventBus; import com.squareup.otto.Bus; import org.androidannotations.annotations.EBean; @EBean(scope = EBean.Scope.Singleton) public class OttoBus extends Bus { }
ivanazivi/CountMeIn
CountMeIn/app/src/main/java/com/countmein/countmein/eventBus/OttoBus.java
Java
mit
200
package com.almasb.chat; import java.io.Serializable; /** * @author Almas Baimagambetov ([email protected]) */ public class DataPacket implements Serializable { private byte[] rawBytes; public DataPacket(byte[] rawBytes) { this.rawBytes = rawBytes; } public byte[] getRawBytes() { return rawBytes; } }
AlmasB/FXTutorials
src/main/java/com/almasb/chat/DataPacket.java
Java
mit
346
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.apimanagement.implementation; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.apimanagement.fluent.NetworkStatusClient; import com.azure.resourcemanager.apimanagement.fluent.models.NetworkStatusContractByLocationInner; import com.azure.resourcemanager.apimanagement.fluent.models.NetworkStatusContractInner; import com.azure.resourcemanager.apimanagement.models.NetworkStatus; import com.azure.resourcemanager.apimanagement.models.NetworkStatusContract; import com.azure.resourcemanager.apimanagement.models.NetworkStatusContractByLocation; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public final class NetworkStatusImpl implements NetworkStatus { @JsonIgnore private final ClientLogger logger = new ClientLogger(NetworkStatusImpl.class); private final NetworkStatusClient innerClient; private final com.azure.resourcemanager.apimanagement.ApiManagementManager serviceManager; public NetworkStatusImpl( NetworkStatusClient innerClient, com.azure.resourcemanager.apimanagement.ApiManagementManager serviceManager) { this.innerClient = innerClient; this.serviceManager = serviceManager; } public List<NetworkStatusContractByLocation> listByService(String resourceGroupName, String serviceName) { List<NetworkStatusContractByLocationInner> inner = this.serviceClient().listByService(resourceGroupName, serviceName); if (inner != null) { return Collections .unmodifiableList( inner .stream() .map(inner1 -> new NetworkStatusContractByLocationImpl(inner1, this.manager())) .collect(Collectors.toList())); } else { return Collections.emptyList(); } } public Response<List<NetworkStatusContractByLocation>> listByServiceWithResponse( String resourceGroupName, String serviceName, Context context) { Response<List<NetworkStatusContractByLocationInner>> inner = this.serviceClient().listByServiceWithResponse(resourceGroupName, serviceName, context); if (inner != null) { return new SimpleResponse<>( inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), inner .getValue() .stream() .map(inner1 -> new NetworkStatusContractByLocationImpl(inner1, this.manager())) .collect(Collectors.toList())); } else { return null; } } public NetworkStatusContract listByLocation(String resourceGroupName, String serviceName, String locationName) { NetworkStatusContractInner inner = this.serviceClient().listByLocation(resourceGroupName, serviceName, locationName); if (inner != null) { return new NetworkStatusContractImpl(inner, this.manager()); } else { return null; } } public Response<NetworkStatusContract> listByLocationWithResponse( String resourceGroupName, String serviceName, String locationName, Context context) { Response<NetworkStatusContractInner> inner = this.serviceClient().listByLocationWithResponse(resourceGroupName, serviceName, locationName, context); if (inner != null) { return new SimpleResponse<>( inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), new NetworkStatusContractImpl(inner.getValue(), this.manager())); } else { return null; } } private NetworkStatusClient serviceClient() { return this.innerClient; } private com.azure.resourcemanager.apimanagement.ApiManagementManager manager() { return this.serviceManager; } }
Azure/azure-sdk-for-java
sdk/apimanagement/azure-resourcemanager-apimanagement/src/main/java/com/azure/resourcemanager/apimanagement/implementation/NetworkStatusImpl.java
Java
mit
4,325
/* * $Id: Yytoken.java,v 1.1 2006/04/15 14:10:48 platform Exp $ * Created on 2006-4-15 */ package org.json.simple.parser; /** * @author FangYidong<[email protected]> */ public class Yytoken { public static final int TYPE_VALUE=0;//JSON primitive value: string,number,boolean,null public static final int TYPE_LEFT_BRACE=1; public static final int TYPE_RIGHT_BRACE=2; public static final int TYPE_LEFT_SQUARE=3; public static final int TYPE_RIGHT_SQUARE=4; public static final int TYPE_COMMA=5; public static final int TYPE_COLON=6; public static final int TYPE_EOF=-1;//end of file public int type=0; public Object value=null; public Yytoken(int type,Object value){ this.type=type; this.value=value; } @Override public String toString(){ StringBuffer sb = new StringBuffer(); switch(type){ case TYPE_VALUE: sb.append("VALUE(").append(value).append(")"); break; case TYPE_LEFT_BRACE: sb.append("LEFT BRACE({)"); break; case TYPE_RIGHT_BRACE: sb.append("RIGHT BRACE(})"); break; case TYPE_LEFT_SQUARE: sb.append("LEFT SQUARE([)"); break; case TYPE_RIGHT_SQUARE: sb.append("RIGHT SQUARE(])"); break; case TYPE_COMMA: sb.append("COMMA(,)"); break; case TYPE_COLON: sb.append("COLON(:)"); break; case TYPE_EOF: sb.append("END OF FILE"); break; } return sb.toString(); } }
fr31b3u73r/JodelAPI
src/org/json/simple/parser/Yytoken.java
Java
mit
1,435
package io.jenkins.blueocean.service.embedded.rest; import hudson.scm.ChangeLogSet; import hudson.scm.ChangeLogSet.Entry; import hudson.scm.RepositoryBrowser; import io.jenkins.blueocean.rest.Reachable; import io.jenkins.blueocean.rest.factory.BlueIssueFactory; import io.jenkins.blueocean.rest.hal.Link; import io.jenkins.blueocean.rest.model.BlueChangeSetEntry; import io.jenkins.blueocean.rest.model.BlueIssue; import io.jenkins.blueocean.rest.model.BlueOrganization; import io.jenkins.blueocean.rest.model.BlueRun; import io.jenkins.blueocean.rest.model.BlueUser; import org.kohsuke.stapler.export.ExportedBean; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Collection; /** * Represents a single commit as a REST resource. * * <p> * Mostly we just let {@link ChangeLogSet.Entry} serve its properties, * except a few places where we are more specific. * * @author Vivek Pandey */ @ExportedBean public class ChangeSetResource extends BlueChangeSetEntry { private final ChangeLogSet.Entry changeSet; private final Reachable parent; private final BlueOrganization organization; public ChangeSetResource(@Nonnull BlueOrganization organization, Entry changeSet, Reachable parent) { this.organization = organization; this.changeSet = changeSet; this.parent = parent; } @Override public BlueUser getAuthor() { return new UserImpl(organization, changeSet.getAuthor()); } @Override public String getTimestamp(){ if(changeSet.getTimestamp() > 0) { return AbstractRunImpl.DATE_FORMAT.print(changeSet.getTimestamp()); }else{ return null; } } @Override public String getUrl() { RepositoryBrowser browser = changeSet.getParent().getBrowser(); if(browser != null) { try { URL url = browser.getChangeSetLink(changeSet); return url == null ? null : url.toExternalForm(); } catch (IOException e) { return null; } } return null; } @Override public String getCommitId() { return changeSet.getCommitId(); } @Override public String getMsg() { return changeSet.getMsg(); } @Override public Collection<String> getAffectedPaths() { return changeSet.getAffectedPaths(); } @Nullable @Override public Collection<BlueIssue> getIssues() { return BlueIssueFactory.resolve(changeSet); } @Override public Link getLink() { return parent.getLink().rel("changeset/"+getCommitId()); } }
kzantow/blueocean-plugin
blueocean-rest-impl/src/main/java/io/jenkins/blueocean/service/embedded/rest/ChangeSetResource.java
Java
mit
2,756
package com.chifanla.queuecall.domain; import java.util.Date; public class CallQueueHandleLogEntity { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column e_callqueue_handlelog.callqueue_handlelog_id * * @mbggenerated */ private Long callqueueHandlelogId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column e_callqueue_handlelog.callqueue_handlelog_callqueueid * * @mbggenerated */ private Long callqueueHandlelogCallqueueid; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column e_callqueue_handlelog.callqueue_handlelog_orderid * * @mbggenerated */ private String callqueueHandlelogOrderid; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column e_callqueue_handlelog.callqueue_handlelog_content * * @mbggenerated */ private String callqueueHandlelogContent; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column e_callqueue_handlelog.callqueue_handlelog_remark * * @mbggenerated */ private String callqueueHandlelogRemark; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column e_callqueue_handlelog.callqueue_handlelog_createuser_unionid * * @mbggenerated */ private String callqueueHandlelogCreateuserUnionid; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column e_callqueue_handlelog.callqueue_handlelog_createdate * * @mbggenerated */ private Date callqueueHandlelogCreatedate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column e_callqueue_handlelog.callqueue_handlelog_modifyuser_unionid * * @mbggenerated */ private String callqueueHandlelogModifyuserUnionid; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column e_callqueue_handlelog.callqueue_handlelog_modefydate * * @mbggenerated */ private Date callqueueHandlelogModefydate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column e_callqueue_handlelog.callqueue_handlelog_status * * @mbggenerated */ private Byte callqueueHandlelogStatus; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column e_callqueue_handlelog.callqueue_handlelog_id * * @return the value of e_callqueue_handlelog.callqueue_handlelog_id * * @mbggenerated */ public Long getCallqueueHandlelogId() { return callqueueHandlelogId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column e_callqueue_handlelog.callqueue_handlelog_id * * @param callqueueHandlelogId the value for e_callqueue_handlelog.callqueue_handlelog_id * * @mbggenerated */ public void setCallqueueHandlelogId(Long callqueueHandlelogId) { this.callqueueHandlelogId = callqueueHandlelogId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column e_callqueue_handlelog.callqueue_handlelog_callqueueid * * @return the value of e_callqueue_handlelog.callqueue_handlelog_callqueueid * * @mbggenerated */ public Long getCallqueueHandlelogCallqueueid() { return callqueueHandlelogCallqueueid; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column e_callqueue_handlelog.callqueue_handlelog_callqueueid * * @param callqueueHandlelogCallqueueid the value for e_callqueue_handlelog.callqueue_handlelog_callqueueid * * @mbggenerated */ public void setCallqueueHandlelogCallqueueid(Long callqueueHandlelogCallqueueid) { this.callqueueHandlelogCallqueueid = callqueueHandlelogCallqueueid; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column e_callqueue_handlelog.callqueue_handlelog_orderid * * @return the value of e_callqueue_handlelog.callqueue_handlelog_orderid * * @mbggenerated */ public String getCallqueueHandlelogOrderid() { return callqueueHandlelogOrderid; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column e_callqueue_handlelog.callqueue_handlelog_orderid * * @param callqueueHandlelogOrderid the value for e_callqueue_handlelog.callqueue_handlelog_orderid * * @mbggenerated */ public void setCallqueueHandlelogOrderid(String callqueueHandlelogOrderid) { this.callqueueHandlelogOrderid = callqueueHandlelogOrderid == null ? null : callqueueHandlelogOrderid.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column e_callqueue_handlelog.callqueue_handlelog_content * * @return the value of e_callqueue_handlelog.callqueue_handlelog_content * * @mbggenerated */ public String getCallqueueHandlelogContent() { return callqueueHandlelogContent; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column e_callqueue_handlelog.callqueue_handlelog_content * * @param callqueueHandlelogContent the value for e_callqueue_handlelog.callqueue_handlelog_content * * @mbggenerated */ public void setCallqueueHandlelogContent(String callqueueHandlelogContent) { this.callqueueHandlelogContent = callqueueHandlelogContent == null ? null : callqueueHandlelogContent.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column e_callqueue_handlelog.callqueue_handlelog_remark * * @return the value of e_callqueue_handlelog.callqueue_handlelog_remark * * @mbggenerated */ public String getCallqueueHandlelogRemark() { return callqueueHandlelogRemark; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column e_callqueue_handlelog.callqueue_handlelog_remark * * @param callqueueHandlelogRemark the value for e_callqueue_handlelog.callqueue_handlelog_remark * * @mbggenerated */ public void setCallqueueHandlelogRemark(String callqueueHandlelogRemark) { this.callqueueHandlelogRemark = callqueueHandlelogRemark == null ? null : callqueueHandlelogRemark.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column e_callqueue_handlelog.callqueue_handlelog_createuser_unionid * * @return the value of e_callqueue_handlelog.callqueue_handlelog_createuser_unionid * * @mbggenerated */ public String getCallqueueHandlelogCreateuserUnionid() { return callqueueHandlelogCreateuserUnionid; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column e_callqueue_handlelog.callqueue_handlelog_createuser_unionid * * @param callqueueHandlelogCreateuserUnionid the value for e_callqueue_handlelog.callqueue_handlelog_createuser_unionid * * @mbggenerated */ public void setCallqueueHandlelogCreateuserUnionid(String callqueueHandlelogCreateuserUnionid) { this.callqueueHandlelogCreateuserUnionid = callqueueHandlelogCreateuserUnionid == null ? null : callqueueHandlelogCreateuserUnionid.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column e_callqueue_handlelog.callqueue_handlelog_createdate * * @return the value of e_callqueue_handlelog.callqueue_handlelog_createdate * * @mbggenerated */ public Date getCallqueueHandlelogCreatedate() { return callqueueHandlelogCreatedate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column e_callqueue_handlelog.callqueue_handlelog_createdate * * @param callqueueHandlelogCreatedate the value for e_callqueue_handlelog.callqueue_handlelog_createdate * * @mbggenerated */ public void setCallqueueHandlelogCreatedate(Date callqueueHandlelogCreatedate) { this.callqueueHandlelogCreatedate = callqueueHandlelogCreatedate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column e_callqueue_handlelog.callqueue_handlelog_modifyuser_unionid * * @return the value of e_callqueue_handlelog.callqueue_handlelog_modifyuser_unionid * * @mbggenerated */ public String getCallqueueHandlelogModifyuserUnionid() { return callqueueHandlelogModifyuserUnionid; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column e_callqueue_handlelog.callqueue_handlelog_modifyuser_unionid * * @param callqueueHandlelogModifyuserUnionid the value for e_callqueue_handlelog.callqueue_handlelog_modifyuser_unionid * * @mbggenerated */ public void setCallqueueHandlelogModifyuserUnionid(String callqueueHandlelogModifyuserUnionid) { this.callqueueHandlelogModifyuserUnionid = callqueueHandlelogModifyuserUnionid == null ? null : callqueueHandlelogModifyuserUnionid.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column e_callqueue_handlelog.callqueue_handlelog_modefydate * * @return the value of e_callqueue_handlelog.callqueue_handlelog_modefydate * * @mbggenerated */ public Date getCallqueueHandlelogModefydate() { return callqueueHandlelogModefydate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column e_callqueue_handlelog.callqueue_handlelog_modefydate * * @param callqueueHandlelogModefydate the value for e_callqueue_handlelog.callqueue_handlelog_modefydate * * @mbggenerated */ public void setCallqueueHandlelogModefydate(Date callqueueHandlelogModefydate) { this.callqueueHandlelogModefydate = callqueueHandlelogModefydate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column e_callqueue_handlelog.callqueue_handlelog_status * * @return the value of e_callqueue_handlelog.callqueue_handlelog_status * * @mbggenerated */ public Byte getCallqueueHandlelogStatus() { return callqueueHandlelogStatus; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column e_callqueue_handlelog.callqueue_handlelog_status * * @param callqueueHandlelogStatus the value for e_callqueue_handlelog.callqueue_handlelog_status * * @mbggenerated */ public void setCallqueueHandlelogStatus(Byte callqueueHandlelogStatus) { this.callqueueHandlelogStatus = callqueueHandlelogStatus; } }
HAPPYSCA/queuecall
src/main/java/com/chifanla/queuecall/domain/CallQueueHandleLogEntity.java
Java
mit
11,802
package com.adben.testdatabuilder.entity.datamodel; import java.sql.Timestamp; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; /** * */ @StaticMetamodel(Actor.class) public class Actor_ { public static volatile SingularAttribute<Actor, Short> actorId; public static volatile SingularAttribute<Actor, String> firstName; public static volatile SingularAttribute<Actor, String> lastName; public static volatile SingularAttribute<Actor, Timestamp> lastUpdate; }
adben002/test-data-builder
entity/src/test/java/com/adben/testdatabuilder/entity/datamodel/Actor_.java
Java
mit
529
package com.xmomen.module.base.model; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; import lombok.Data; public @Data class UpdateContract implements Serializable { /** * 合同名称 */ private String contractName; /** * 合同编号 */ private String contractCode; /** * 合同价的客户 */ private Integer cdMemberId; /** * 合同价的单位 */ private Integer cdCompanyId; /** * 1-部分产品,2-全部产品 */ private Integer scope; /** * 仅当适用范围为全部产品时适用 */ private BigDecimal contractPrice; /** * 合同开始时间 */ private Date beginTime; /** * 合同结束时间 */ private Date endTime; /** * 0-未审核,1-审核 */ private Integer isAuditor; /** * 合同明细 */ private List<CreateContractItem> contractItemList; }
xmomen/dms-webapp
src/main/java/com/xmomen/module/base/model/UpdateContract.java
Java
mit
1,001
/******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.compiler.codegen; //import checkers.inference.ownership.quals.*;; public interface AttributeNamesConstants { final char[] SyntheticName = "Synthetic".toCharArray(); //$NON-NLS-1$ final char[] ConstantValueName = "ConstantValue".toCharArray(); //$NON-NLS-1$ final char[] LineNumberTableName = "LineNumberTable".toCharArray(); //$NON-NLS-1$ final char[] LocalVariableTableName = "LocalVariableTable".toCharArray(); //$NON-NLS-1$ final char[] InnerClassName = "InnerClasses".toCharArray(); //$NON-NLS-1$ final char[] CodeName = "Code".toCharArray(); //$NON-NLS-1$ final char[] ExceptionsName = "Exceptions".toCharArray(); //$NON-NLS-1$ final char[] SourceName = "SourceFile".toCharArray(); //$NON-NLS-1$ final char[] DeprecatedName = "Deprecated".toCharArray(); //$NON-NLS-1$ final char[] SignatureName = "Signature".toCharArray(); //$NON-NLS-1$ final char[] LocalVariableTypeTableName = "LocalVariableTypeTable".toCharArray(); //$NON-NLS-1$ final char[] EnclosingMethodName = "EnclosingMethod".toCharArray(); //$NON-NLS-1$ final char[] AnnotationDefaultName = "AnnotationDefault".toCharArray(); //$NON-NLS-1$ final char[] RuntimeInvisibleAnnotationsName = "RuntimeInvisibleAnnotations".toCharArray(); //$NON-NLS-1$ final char[] RuntimeVisibleAnnotationsName = "RuntimeVisibleAnnotations".toCharArray(); //$NON-NLS-1$ final char[] RuntimeInvisibleParameterAnnotationsName = "RuntimeInvisibleParameterAnnotations".toCharArray(); //$NON-NLS-1$ final char[] RuntimeVisibleParameterAnnotationsName = "RuntimeVisibleParameterAnnotations".toCharArray(); //$NON-NLS-1$ }
kcsl/immutability-benchmark
benchmark-applications/reiminfer-oopsla-2012/source/ejc/src/org/eclipse/jdt/internal/compiler/codegen/AttributeNamesConstants.java
Java
mit
2,153
package com.zepp.www.openglespractice.render; import android.content.Context; import android.opengl.GLES20; import com.zepp.www.openglespractice.R; import com.zepp.www.openglespractice.util.TextureResourceReader; import javax.microedition.khronos.opengles.GL10; import static android.opengl.GLES20.glUniformMatrix4fv; import static android.opengl.Matrix.orthoM; /** * Created by xubinggui on 5/2/16. * // _ooOoo_ * // o8888888o * // 88" . "88 * // (| -_- |) * // O\ = /O * // ____/`---'\____ * // . ' \\| |// `. * // / \\||| : |||// \ * // / _||||| -:- |||||- \ * // | | \\\ - /// | | * // | \_| ''\---/'' | | * // \ .-\__ `-` ___/-. / * // ___`. .' /--.--\ `. . __ * // ."" '< `.___\_<|>_/___.' >'"". * // | | : `- \`.;`\ _ /`;.`/ - ` : | | * // \ \ `-. \_ __\ /__ _/ .-` / / * // ======`-.____`-.___\_____/___.-`____.-'====== * // `=---=' * // * // ............................................. * // 佛祖镇楼 BUG辟易 */ public class AirHockeyOrthoRender extends BaseHockeyRender { private static final String U_MATRIX = "u_Matrix"; protected final float[] projectionMatrix = new float[16]; private int uMatrixLocation; public AirHockeyOrthoRender(Context context) { super(context); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { super.onSurfaceChanged(gl, width, height); final float aspectRatio = width > height ? (float) width / (float) height : (float) height / (float) width; if (width > height) { orthoM(projectionMatrix, 0, -aspectRatio, aspectRatio, -1f, 1f, -1f, 1f); } else { orthoM(projectionMatrix, 0, -1f, 1f, -aspectRatio, aspectRatio, -1f, 1f); } } protected void doSomeAfterClear() { glUniformMatrix4fv(uMatrixLocation, 1, false, projectionMatrix, 0); } @Override protected String readVertexShader() { return TextureResourceReader.readTextFileFromResource(mContext, R.raw.simple_vertex_shader_ortho); } @Override protected String readFragmentShader() { return TextureResourceReader.readTextFileFromResource(mContext, R.raw.simple_fragment_shader); } @Override protected void getMatrixPosition() { uMatrixLocation = GLES20.glGetUniformLocation(program, U_MATRIX); } }
xu6148152/binea_project_for_android
OpenglEsPractice/app/src/main/java/com/zepp/www/openglespractice/render/AirHockeyOrthoRender.java
Java
mit
2,880
package dux.network; public interface INetworkProtocol { public INetworkProtocolEncoder getEncoder(); public INetworkProtocolDecoder getDecoder(); }
Jire/Vinitello-Dux
src/dux/network/INetworkProtocol.java
Java
mit
153
package lib.cards.utilities; public class Point { public Point() { this(0, 0); } public Point(double x, double y) { this.x = x; this.y = y; } public double x; public double y; }
michanto/AndroSol
src/lib/cards/utilities/Point.java
Java
mit
231
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2018.06.05 at 08:50:12 PM SAMT // package ru.fsrar.wegais.actwriteoffshop_v2; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; import ru.fsrar.wegais.commonenum.TypeWriteOff; /** * Акт списания * * <p>Java class for ActWriteOffShopType_v2 complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ActWriteOffShopType_v2"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Identity" type="{http://fsrar.ru/WEGAIS/Common}IdentityType" minOccurs="0"/> * &lt;element name="Header"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;all> * &lt;element name="ActNumber" type="{http://fsrar.ru/WEGAIS/Common}NoEmptyString50"/> * &lt;element name="ActDate" type="{http://fsrar.ru/WEGAIS/Common}DateNoTime"/> * &lt;element name="TypeWriteOff" type="{http://fsrar.ru/WEGAIS/CommonEnum}TypeWriteOff"/> * &lt;element name="Note" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;maxLength value="500"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/all> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="Content"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Position" type="{http://fsrar.ru/WEGAIS/ActWriteOffShop_v2}ActWriteOffShopPositionType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ActWriteOffShopType_v2", propOrder = { "identity", "header", "content" }) public class ActWriteOffShopTypeV2 { @XmlElement(name = "Identity") protected String identity; @XmlElement(name = "Header", required = true) protected ActWriteOffShopTypeV2 .Header header; @XmlElement(name = "Content", required = true) protected ActWriteOffShopTypeV2 .Content content; /** * Gets the value of the identity property. * * @return * possible object is * {@link String } * */ public String getIdentity() { return identity; } /** * Sets the value of the identity property. * * @param value * allowed object is * {@link String } * */ public void setIdentity(String value) { this.identity = value; } /** * Gets the value of the header property. * * @return * possible object is * {@link ActWriteOffShopTypeV2 .Header } * */ public ActWriteOffShopTypeV2 .Header getHeader() { return header; } /** * Sets the value of the header property. * * @param value * allowed object is * {@link ActWriteOffShopTypeV2 .Header } * */ public void setHeader(ActWriteOffShopTypeV2 .Header value) { this.header = value; } /** * Gets the value of the content property. * * @return * possible object is * {@link ActWriteOffShopTypeV2 .Content } * */ public ActWriteOffShopTypeV2 .Content getContent() { return content; } /** * Sets the value of the content property. * * @param value * allowed object is * {@link ActWriteOffShopTypeV2 .Content } * */ public void setContent(ActWriteOffShopTypeV2 .Content value) { this.content = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Position" type="{http://fsrar.ru/WEGAIS/ActWriteOffShop_v2}ActWriteOffShopPositionType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "position" }) public static class Content { @XmlElement(name = "Position", required = true) protected List<ActWriteOffShopPositionType> position; /** * Gets the value of the position property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the position property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPosition().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ActWriteOffShopPositionType } * * */ public List<ActWriteOffShopPositionType> getPosition() { if (position == null) { position = new ArrayList<ActWriteOffShopPositionType>(); } return this.position; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;all> * &lt;element name="ActNumber" type="{http://fsrar.ru/WEGAIS/Common}NoEmptyString50"/> * &lt;element name="ActDate" type="{http://fsrar.ru/WEGAIS/Common}DateNoTime"/> * &lt;element name="TypeWriteOff" type="{http://fsrar.ru/WEGAIS/CommonEnum}TypeWriteOff"/> * &lt;element name="Note" minOccurs="0"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;maxLength value="500"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/all> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { }) public static class Header { @XmlElement(name = "ActNumber", required = true) protected String actNumber; @XmlElement(name = "ActDate", required = true) @XmlSchemaType(name = "date") protected XMLGregorianCalendar actDate; @XmlElement(name = "TypeWriteOff", required = true) @XmlSchemaType(name = "string") protected TypeWriteOff typeWriteOff; @XmlElement(name = "Note") protected String note; /** * Gets the value of the actNumber property. * * @return * possible object is * {@link String } * */ public String getActNumber() { return actNumber; } /** * Sets the value of the actNumber property. * * @param value * allowed object is * {@link String } * */ public void setActNumber(String value) { this.actNumber = value; } /** * Gets the value of the actDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getActDate() { return actDate; } /** * Sets the value of the actDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setActDate(XMLGregorianCalendar value) { this.actDate = value; } /** * Gets the value of the typeWriteOff property. * * @return * possible object is * {@link TypeWriteOff } * */ public TypeWriteOff getTypeWriteOff() { return typeWriteOff; } /** * Sets the value of the typeWriteOff property. * * @param value * allowed object is * {@link TypeWriteOff } * */ public void setTypeWriteOff(TypeWriteOff value) { this.typeWriteOff = value; } /** * Gets the value of the note property. * * @return * possible object is * {@link String } * */ public String getNote() { return note; } /** * Sets the value of the note property. * * @param value * allowed object is * {@link String } * */ public void setNote(String value) { this.note = value; } } }
ytimesru/kkm-pc-client
src/main/java/ru/fsrar/wegais/actwriteoffshop_v2/ActWriteOffShopTypeV2.java
Java
mit
10,814
package com.epi; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class SimpleWebServer { // @include public static class SingleThreadWebServer { public static final int PORT = 8080; public static void main(String[] args) throws IOException { ServerSocket serversock = new ServerSocket(PORT); for (;;) { Socket sock = serversock.accept(); processReq(sock); } } // @exclude static void processReq(Socket sock) { return; } // @include } // @exclude }
adnanaziz/epicode
java/src/main/java/com/epi/SimpleWebServer.java
Java
mit
557
public class Solution { static class State { int step; LinkedList<String> prevList = new LinkedList<String>(); public State (int step) { this.step = step; } } HashMap<String, State> vis; ArrayList<ArrayList<String>> findSeqList (String cur) { State curState = vis.get(cur); if (curState.prevList.isEmpty()) return new ArrayList<ArrayList<String>>(Arrays.asList(new ArrayList<String>(Arrays.asList(cur)))); ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>(); for (String prev : curState.prevList) { for (ArrayList<String> seq : findSeqList(prev)) { seq.add(cur); ret.add(seq); } } return ret; } public ArrayList<ArrayList<String>> findLadders (String start, String end, HashSet<String> dict) { if (start == null || end == null || dict == null) return null; if (!dict.contains(start)) return new ArrayList<ArrayList<String>>(); if (start.equals(end)) return new ArrayList<ArrayList<String>>(Arrays.asList(new ArrayList<String>(Arrays.asList(start)))); LinkedList<String> queue = new LinkedList<String>(); vis = new HashMap<String, State>(); queue.add(start); vis.put(start, new State(1)); while (!queue.isEmpty()) { String cur = queue.remove(); State curState = vis.get(cur); if (cur.equals(end)) return findSeqList(cur); char[] buffer = cur.toCharArray(); for (int i = 0; i < cur.length(); ++i) { for (char c = 'a'; c <= 'z'; ++c) { if (c == cur.charAt(i)) continue; buffer[i] = c; String next = new String(buffer); if (!dict.contains(next)) continue; if (!vis.containsKey(next)) { vis.put(next, new State(curState.step + 1)); queue.add(next); } State nextState = vis.get(next); if (curState.step + 1 == nextState.step) { nextState.prevList.add(cur); } } buffer[i] = cur.charAt(i); } } return new ArrayList<ArrayList<String>>(); } }
starforever/leetcode
126/Solution.java
Java
mit
2,184
package com.github.ddth.id.cassandra; import java.io.IOException; import java.text.MessageFormat; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.datastax.driver.core.ConsistencyLevel; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import com.datastax.driver.core.exceptions.QueryConsistencyException; import com.datastax.driver.core.exceptions.WriteTimeoutException; import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy; import com.datastax.driver.core.policies.DefaultRetryPolicy; import com.datastax.driver.core.policies.LoggingRetryPolicy; import com.github.ddth.cql.CqlUtils; import com.github.ddth.cql.SessionManager; import com.github.ddth.id.SerialIdGenerator; import com.github.ddth.id.utils.IdException; /** * This id generator utilizes Cassandra to generate serial IDs. * * <p> * Persistency: IDs generated by this id-generator are persistent (backed by * Cassandra). * </p> * * @author Thanh Nguyen <[email protected]> * @since 0.5.0 */ public class CassandraIdGenerator extends SerialIdGenerator { private static Logger LOGGER = LoggerFactory.getLogger(CassandraIdGenerator.class); private SessionManager sessionManager; private boolean myOwnSessionManager = true; private String hostsAndPorts, keyspace, user, password; private String tableName; private String colName = "id_name"; private String colValue = "id_value"; private ConsistencyLevel consistencyLevelGetValue = ConsistencyLevel.LOCAL_QUORUM; private ConsistencyLevel consistencyLevelGetForSet = ConsistencyLevel.LOCAL_ONE; private ConsistencyLevel consistencyLevelSetValue = ConsistencyLevel.LOCAL_QUORUM; private PreparedStatement stmGetValue, stmInsertNew, stmSetExisting, stmUpdateExisting; public SessionManager getSessionManager() { return sessionManager; } public CassandraIdGenerator setSessionManager(SessionManager sessionManager) { if (this.sessionManager != null && myOwnSessionManager) { try { sessionManager.close(); } catch (IOException e) { LOGGER.warn(e.getMessage(), e); } } this.sessionManager = sessionManager; myOwnSessionManager = false; return this; } /** * * @return */ public String getHostsAndPorts() { return this.hostsAndPorts; } /** * * @param hostsAndPorts * @return */ public CassandraIdGenerator setHostsAndPorts(String hostsAndPorts) { this.hostsAndPorts = hostsAndPorts; return this; } /** * * @return */ public String getKeyspace() { return this.keyspace; } /** * * @param keyspace * @return */ public CassandraIdGenerator setKeyspace(String keyspace) { this.keyspace = keyspace; return this; } /** * * @return */ public String getUser() { return this.user; } /** * * @param user * @return */ public CassandraIdGenerator setUser(String user) { this.user = user; return this; } /** * * @return */ public String getPassword() { return this.password; } /** * * @param password * @return */ public CassandraIdGenerator setPassword(String password) { this.password = password; return this; } public String getTableName() { return tableName; } public CassandraIdGenerator setTableName(String tableName) { this.tableName = tableName; return this; } public String getTableColumnName() { return colName; } public CassandraIdGenerator setTableColumnName(String colName) { this.colName = colName; return this; } public String getTableColumnValue() { return colValue; } public CassandraIdGenerator setTableColumnValue(String colValue) { this.colValue = colValue; return this; } public ConsistencyLevel getConsistencyLevelGetValue() { return consistencyLevelGetValue; } public CassandraIdGenerator setConsistencyLevelGetValue(ConsistencyLevel consistencyLevel) { this.consistencyLevelGetValue = consistencyLevel; return this; } public ConsistencyLevel getConsistencyLevelGetForSet() { return consistencyLevelGetForSet; } public CassandraIdGenerator setConsistencyLevelGetForSet(ConsistencyLevel consistencyLevel) { this.consistencyLevelGetForSet = consistencyLevel; return this; } public ConsistencyLevel getConsistencyLevelSetValue() { return consistencyLevelSetValue; } public CassandraIdGenerator setConsistencyLevelSetValue(ConsistencyLevel consistencyLevel) { this.consistencyLevelSetValue = consistencyLevel; return this; } protected Session getSession() { try { return sessionManager.getSession(hostsAndPorts, user, password, keyspace); } catch (Exception e) { throw e instanceof IdException ? (IdException) e : new IdException(e); } } /** * Creates a {@link SessionManager} instance. Sub-class my override this * method to customized its own {@link SessionManager}. * * @return */ protected SessionManager createSessionManager() { SessionManager sm = new SessionManager(); // sm.setRetryPolicy(new // LoggingRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE)); sm.setRetryPolicy(new LoggingRetryPolicy(DefaultRetryPolicy.INSTANCE)); sm.setSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(10000, 3)); sm.init(); return sm; } /** * {@inheritDoc} */ @Override public CassandraIdGenerator init() { if (sessionManager == null) { sessionManager = createSessionManager(); myOwnSessionManager = true; } super.init(); Session session = getSession(); String cql; cql = "SELECT {0} FROM {1} WHERE {2}=?"; stmGetValue = CqlUtils.prepareStatement(session, MessageFormat.format(cql, colValue, tableName, colName)); cql = "INSERT INTO {0} ({1}, {2}) VALUES (?, ?) IF NOT EXISTS"; stmInsertNew = CqlUtils.prepareStatement(session, MessageFormat.format(cql, tableName, colName, colValue)); stmInsertNew.setIdempotent(true); cql = "UPDATE {0} SET {1}=? WHERE {2}=? IF EXISTS"; stmSetExisting = CqlUtils.prepareStatement(session, MessageFormat.format(cql, tableName, colValue, colName)); stmSetExisting.setIdempotent(true); cql = "UPDATE {0} SET {1}=? WHERE {2}=? IF {3}=?"; stmUpdateExisting = CqlUtils.prepareStatement(session, MessageFormat.format(cql, tableName, colValue, colName, colValue)); stmUpdateExisting.setIdempotent(true); return this; } /** * {@inheritDoc} */ @Override public void destroy() { try { super.destroy(); } catch (Exception e) { LOGGER.warn(e.getMessage(), e); } if (myOwnSessionManager && sessionManager != null) { try { sessionManager.destroy(); } catch (Exception e) { LOGGER.warn(e.getMessage(), e); } finally { sessionManager = null; } } } private boolean _setValue(Session session, String namespace, long newValue, long currentValue) { ResultSet result; if (currentValue < 0) { result = CqlUtils.execute(session, stmInsertNew, consistencyLevelSetValue, namespace, newValue); } else { result = CqlUtils.execute(session, stmUpdateExisting, consistencyLevelSetValue, newValue, namespace, currentValue); } return result != null ? result.wasApplied() : false; } private long _nextId(Session session, String namespace, boolean ignoreTimeout) { try { while (true) { Row row = CqlUtils.executeOne(session, stmGetValue, consistencyLevelGetForSet, namespace); long currentValue = row != null ? row.getLong(colValue) : -1; if (currentValue < 0) { try { if (_setValue(session, namespace, 1, currentValue)) { return 1; } } catch (WriteTimeoutException e) { if (ignoreTimeout && e.getReceivedAcknowledgements() > 0) { return 1; } } } else { try { if (_setValue(session, namespace, currentValue + 1, currentValue)) { return currentValue + 1; } } catch (WriteTimeoutException e) { if (ignoreTimeout && e.getReceivedAcknowledgements() > 0) { return currentValue + 1; } } } } } catch (QueryConsistencyException e) { if (ignoreTimeout) { return -2; } else { throw new IdException.OperationTimeoutException(e); } } } /** * {@inheritDoc} */ @Override public long nextId(String namespace) { return _nextId(getSession(), namespace, false); } /** * {@inheritDoc} */ @Override public long nextIdWithRetries(String namespace, long timeout, TimeUnit timeoutUnit) { Session session = getSession(); long timestamp = System.currentTimeMillis(); long timeoutMs = timeoutUnit.toMillis(timeout); long nextId = _nextId(session, namespace, true); while (nextId < 0 && System.currentTimeMillis() - timestamp <= timeoutMs) { nextId = _nextId(session, namespace, true); } return nextId; } /** * Fetches namespace's current value. * * @param session * @param namespace * @return current id value, or {@code -1} if namespace does not exist, or * {@code -2} if timed-out */ private long _currentId(Session session, String namespace, boolean ignoreTimeout) { try { Row row = CqlUtils.executeOne(session, stmGetValue, consistencyLevelGetValue, namespace); return row != null ? row.getLong(colValue) : -1; } catch (QueryConsistencyException e) { if (ignoreTimeout) { return -2; } else { throw e; } } } /** * {@inheritDoc} */ @Override public long currentId(String namespace) { try { long result = _currentId(getSession(), namespace, false); return result >= 0 ? result : (result == -1 ? 0 : -2); } catch (QueryConsistencyException e) { throw new IdException.OperationTimeoutException(e); } } /** * {@inheritDoc} */ @Override public long currentIdWithRetries(String namespace, long timeout, TimeUnit timeoutUnit) { Session session = getSession(); long timestamp = System.currentTimeMillis(); long timeoutMs = timeoutUnit.toMillis(timeout); long currentId = _currentId(session, namespace, true); while (currentId < -1 && System.currentTimeMillis() - timestamp <= timeoutMs) { currentId = _currentId(session, namespace, true); } return currentId >= 0 ? currentId : (currentId == -1 ? 0 : -2); } private boolean _setValue(Session session, String namespace, long newValue, boolean ignoreTimeout) { try { ResultSet result; result = CqlUtils.execute(session, stmSetExisting, consistencyLevelSetValue, newValue, namespace); if (result == null || !result.wasApplied()) { result = CqlUtils.execute(session, stmInsertNew, consistencyLevelSetValue, namespace, newValue); } return result != null ? result.wasApplied() : false; } catch (QueryConsistencyException e) { if (ignoreTimeout) { return false; } else { throw e; } } } /** * {@inheritDoc} */ @Override public boolean setValue(String namespace, long value) { if (value < 0) { throw new IdException("Id value must be greater or equal to 0!"); } try { return _setValue(getSession(), namespace, value, false); } catch (QueryConsistencyException e) { throw new IdException.OperationTimeoutException(e); } } /** * {@inheritDoc} */ @Override public boolean setValueWithRetries(String namespace, long value, long timeout, TimeUnit timeoutUnit) { Session session = getSession(); long timestamp = System.currentTimeMillis(); long timeoutMs = timeoutUnit.toMillis(timeout); boolean result = _setValue(session, namespace, value, true); while (!result && System.currentTimeMillis() - timestamp <= timeoutMs) { result = _setValue(session, namespace, value, true); } return result; } }
DDTH/ddth-id
ddth-id-core/src/main/java/com/github/ddth/id/cassandra/CassandraIdGenerator.java
Java
mit
13,928
package ie.dit; import java.util.ArrayList; import ddf.minim.Minim; import processing.core.*; public class Sub extends GameObject { public Sub(Main _main) { super(_main); unit = main.loadImage("2.png"); //this scales the units to fit any screen size int w = unit.width * main.width/2560; int h = unit.height * main.height/1440; unit.resize(w,h); pos = new PVector(); mouseBox = new PVector(); easing = .7f; madeMove = false; initialHealth = 30; currentHealth = 30; clicks = 0; } public void update() { if (move == 0) { float targetX = main.mouseX; float dx = targetX - pos.x; pos.x += dx * easing; float targetY = main.mouseY; float dy = targetY - pos.y; pos.y += dy * easing; }//end if 0 if (move == 1) { for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { if (pos.x < (main.cPosX[i] + main.width / w + 1) && pos.x > main.cPosX[i] && pos.y < (main.cPosY[j] + main.height / hplus1 + 1) && pos.y > main.cPosY[j]) { main.visited[i][j]= true; pos.x = main.cPosX[i] + main.width / 64; pos.y = main.cPosY[j] + main.height / 36; break; }//end if }//end for }//end for }//end if 1 if (move == 2) { for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { if (pos.x < (main.cPosX[i] + main.width / w + 1) && pos.x > main.cPosX[i] && pos.y < (main.cPosY[j] + main.height / hplus1 + 1) && pos.y > main.cPosY[j]) { pos.x = main.cPosX[i] + main.width / 64; pos.y = main.cPosY[j] + main.height / 36; }//end if if (main.mouseX < (main.cPosX[i] + main.width / w) && main.mouseX > main.cPosX[i] && main.mouseY < (main.cPosY[j] + main.height / hplus1) && main.mouseY > main.cPosY[j]) { mouseBox.x = main.cPosX[i] + main.width / 64; mouseBox.y = main.cPosY[j] + main.height / 36; }//end if if (main.mousePressed && main.release2 && validTiles()) { if(enemy == true) { main.cannon.play(); main.cannon.rewind(); if(pos.dist(main.enemyUnits.get(enemyIndex).pos) < main.battlefield.size*2) { currentHealth -= (int)random(20,30); } main.enemyUnits.get(enemyIndex).currentHealth -= (int)(random(150,180)); enemy = false; clicks++; } else { pos.x = mouseBox.x; pos.y = mouseBox.y; validTile = false; madeMove = true; //only move once per turn }//end else if(clicks > 0) { move = 1; nextTurn = false; //main.active = false; }//end if main.release2 = false; }//end if if(pos.dist(mouseBox) < main.width/6) { main.battlefield.colourGreen = true; main.fog.colourGreen = true; } else { main.battlefield.colourRed = true; main.fog.colourRed = true; } }//end for }//end for }//end if 2 }//end update() //this function checks to see if the mouse is within two boxes up, down, left or right of the unit public boolean validTiles() { //the subs can travel 1/6 of the map each turn if(pos.dist(mouseBox) < main.width/6) { validTile = checkPos(mouseBox); } return validTile; }//end validTiles() boolean enemy= false; //checks the position of every other ship public boolean checkPos(PVector mouse) { boolean valid = true; for(int i = 0; i < main.units.size(); i++) { //change the position to the centre mouse = main.centerPos(mouse); GameObject go = main.units.get(i); float size = main.battlefield.size/2; //if the position is the same as any unit other than itself then you cannot place it if(mouse.x == go.pos.x && mouse.y == go.pos.y) { valid = false; }//end if }//end for for(int i = 0; i < main.enemyUnits.size(); i++) { //change the position to the centre mouse = main.centerPos(mouse); GameObject go = main.enemyUnits.get(i); float size = main.battlefield.size/2; //if the position is the same as any unit other than itself then you cannot place it if(mouse.x == go.pos.x && mouse.y == go.pos.y) { enemy = true; enemyIndex = i; }//end if }//end for return valid; }//end checkPos public void render() { switch(move) { case 0: { main.pushMatrix(); main.translate(main.mouseX, main.mouseY); main.imageMode(CENTER); main.image(unit, 0, 0); main.popMatrix(); break; }//end case 0 case 1: { main.pushMatrix(); main.translate(pos.x, pos.y); main.imageMode(CENTER); main.image(unit, 0, 0); main.popMatrix(); break; }//end case 1 case 2: { main.pushMatrix(); angle = atan2(-(pos.x - mouseBox.x), -(pos.y - mouseBox.y)); main.translate(pos.x, pos.y); main.rotate(-angle+PI); main.imageMode(CENTER); main.image(unit, 0, 0); main.popMatrix(); break; }//end case 2 }//end switch }//end render }
NeutralMilk/Assignment_3
src/ie/dit/Sub.java
Java
mit
6,948
package mcjty.xnet.api.gui; import mcjty.xnet.api.channels.RSMode; import net.minecraft.item.ItemStack; public interface IEditorGui { /// This returns true if we are editing an advanced connector boolean isAdvanced(); IEditorGui move(int x, int y); IEditorGui move(int x); IEditorGui shift(int x); IEditorGui label(String txt); IEditorGui text(String tag, String tooltip, String value, int width); IEditorGui integer(String tag, String tooltip, Integer value, int width, Integer maximum); IEditorGui integer(String tag, String tooltip, Integer value, int width); IEditorGui real(String tag, String tooltip, Double value, int width); IEditorGui toggle(String tag, String tooltip, boolean value); IEditorGui toggleText(String tag, String tooltip, String text, boolean value); IEditorGui colors(String tag, String tooltip, Integer current, Integer... colors); IEditorGui choices(String tag, String tooltip, String current, String... values); <T extends Enum<T>> IEditorGui choices(String tag, String tooltip, T current, T... values); IEditorGui redstoneMode(String tag, RSMode current); IEditorGui ghostSlot(String tag, ItemStack slot); IEditorGui nl(); }
McJty/XNet
src/main/java/mcjty/xnet/api/gui/IEditorGui.java
Java
mit
1,244
package com.therandomlabs.utils.systemproperty; import static com.therandomlabs.utils.logging.Logging.getLogger; public class BooleanProperty extends SystemProperty<Boolean> { public BooleanProperty(String key) { this(key, false); } public BooleanProperty(String key, boolean editable) { super(key, editable); } @Override public Boolean get() { final String raw = getRaw(); if(raw == null || "false".equals(raw)) { return false; } if("true".equals(raw)) { return true; } getLogger().printStackTrace(new IllegalArgumentException("Invalid boolean: " + raw)); return false; } }
TheRandomLabs/TRLUtils
src/main/java/com/therandomlabs/utils/systemproperty/BooleanProperty.java
Java
mit
614
package com.gelvt.gofdp.builder; /** * Desc: 消息头名称枚举 * Author: Elvin Zeng * Date: 17-6-25. */ public enum MessageHeaderName { /** * 消息内容是否已经被加密 */ IS_CONTENT_ENCRYPTED("IS_CONTENT_ENCRYPTED"), /** * 消息内容加密算法 */ ENCRYPTION_ALGORITHM("ENCRYPTION_ALGORITHM"), /** * 消息的内容MIME类型 */ CONTENT_TYPE("CONTENT_TYPE"), /** * 消息接收人的用户ID */ RECIPIENT_ID("RECIPIENT_ID"), /** * 消息发送人ID */ SENDER_ID("SENDER_ID") ; private String value; MessageHeaderName(String value){ this.value = value; } public String getValue() { return value; } }
elvinzeng/java-design-pattern-samples
builder/src/main/java/com/gelvt/gofdp/builder/MessageHeaderName.java
Java
mit
752
public class Solution { public int findMaxForm(String[] strs, int m, int n) { int matrix[][] = new int[m + 1][n + 1], result = 0; for (String s : strs) { int zero = countZero(s), one = s.length() - zero; for (int i = m - zero; i >= 0; i--) { for (int j = n - one; j >= 0; j--) { matrix[i + zero][j + one] = Math.max(matrix[i][j] + 1, matrix[i + zero][j + one]); result = Math.max(matrix[i + zero][j + one], result); } } } return result; } private int countZero(String s) { int result = 0; for (char c : s.toCharArray()) { if (c == '0') result++; } return result; } }
liupangzi/codekata
leetcode/Algorithms/474.OnesAndZeroes/Solution.java
Java
mit
768
package org.schors.flibot; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import java.util.ArrayList; import java.util.List; public class SendMessageList { private List<StringBuilder> list = new ArrayList<>(); private int max = 2048; private StringBuilder current = new StringBuilder(); public SendMessageList() { } public SendMessageList(int max) { this.max = max; } public SendMessageList append(String msg) { if ((current.length() + msg.length()) > max) { updateList(); } current.append(msg); return this; } public List<SendMessage> getMessages() { updateList(); List<SendMessage> res = new ArrayList<>(); for (StringBuilder sb : list) { SendMessage sendMessage = new SendMessage(); sendMessage.setText(sb.toString()); sendMessage.enableHtml(true); res.add(sendMessage); } return res; } private void updateList() { list.add(current); current = new StringBuilder(); } }
flicus/flibot
src/main/java/org/schors/flibot/SendMessageList.java
Java
mit
1,111
package com.inbravo.hadoop.utils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URISyntaxException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.log4j.Logger; import com.inbravo.log.LogFactory; /** * * @author amit.dixit * */ public final class HDFSUtils { /** The Constant LOG. */ private static final Logger logger = LogFactory.getLogger(HDFSUtils.class); /** The hdfs file system class */ private static FileSystem fs = null; static { try { initialize(); } catch (final Exception e) { logger.error("=*=Error in HDFSUtils.initialize", e); } } /** * Initialize. * * @throws IOException Signals that an I/O exception has occurred. * @throws URISyntaxException */ public static final void initialize() throws IOException, URISyntaxException { final Configuration conf = new Configuration(); conf.addResource("core-site.xml"); conf.addResource("hdfs-site.xml"); conf.addResource("mapred-site.xml"); fs = FileSystem.get(new java.net.URI("hdfs://localhost:9000"), conf); } /** * Read file from hdfs. * * @param inFilePath the in file path * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public static final String readFileFromHDFS(final String inFilePath) throws IOException { String strLine = ""; final StringBuffer data = new StringBuffer(); final Path inFile = new Path(inFilePath); final FSDataInputStream in = fs.open(inFile); if (!fs.exists(inFile)) { return strLine; } final BufferedReader br1 = new BufferedReader(new InputStreamReader(in)); /* Read File Line By Line */ while ((strLine = br1.readLine()) != null) { data.append(strLine); } in.close(); return data.toString(); } /** * Write local file to hdfs. * * @param inputLocalFilePath the input local file path * @param outFilePath the out file path * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public static String writeLocalFileToHDFS(String inputLocalFilePath, String outFilePath) throws IOException { Path outFile = null; String strLine = null; BufferedWriter br = null; BufferedReader br1 = null; DataInputStream in = null; FSDataOutputStream out = null; FileInputStream fstream = null; if (inputLocalFilePath == null || outFilePath == null || inputLocalFilePath.trim().length() < 1 || outFilePath.trim().length() < 1) { return null; } outFile = new Path(outFilePath); out = fs.create(outFile); br = new BufferedWriter(new OutputStreamWriter(fs.create(outFile, true))); /* To append data to a file, use fs.append(Path f) */ try { fstream = new FileInputStream(inputLocalFilePath); in = new DataInputStream(fstream); br1 = new BufferedReader(new InputStreamReader(in)); while ((strLine = br1.readLine()) != null) { br.write(strLine + "\n"); } } catch (final Exception e) { logger.error(e); } finally { fstream.close(); br1.close(); in.close(); br.close(); out.close(); } return outFilePath; } /** * * @param paramFilePath * @return * @throws IOException */ public static final boolean removeFileStructureFromHDFS(final String paramFilePath) throws IOException { final Path pathToBeRemoved = new Path(paramFilePath); return fs.delete(pathToBeRemoved, true); } /** * * @param args * @throws IOException */ public static final void main(final String args) throws IOException { System.out.println(removeFileStructureFromHDFS("/users/output-spark")); } }
inbravo/java-src
src/main/java/com/inbravo/hadoop/utils/HDFSUtils.java
Java
mit
4,109
package org.jnius; public class VariableArgConstructors { public int constructorUsed; public VariableArgConstructors(int arg1, String arg2, int arg3, Object arg4, int... arg5) { constructorUsed = 1; } public VariableArgConstructors(int arg1, String arg2, Object arg3, int... arg4) { constructorUsed = 2; } }
kivy/pyjnius
tests/java-src/org/jnius/VariableArgConstructors.java
Java
mit
329
package com.hockeyhurd.hcorelib.api.worldgen; import net.minecraft.block.Block; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.IChunkGenerator; import net.minecraft.world.gen.feature.WorldGenMinable; import net.minecraftforge.fml.common.IWorldGenerator; import java.util.Random; /** * Abstract class used for generic template for generating block, * such as ore, in any given dimension. * * @author hockeyhurd * @version Nov 12, 2014 */ public class AbstractWorldgen implements IWorldGenerator { protected final int CHUNK_SIZE = 16; protected final int CHANCE_OF_SPAWN; protected final int CHANCE_OF_SPAWN_NETHER; protected final int MIN_VEIN_SIZE, MAX_VEIN_SIZE; protected final int MIN_Y, MAX_Y; protected final Block BLOCK_TO_SPAWN, BLOCK_TO_SPAWN_NETHER; /** * Complete constructor for full control over all generation needs. * @param blockToSpawn = block to spawn in overworld. * @param blockToSpawnNether = block to spawn in nether. * @param chanceOfSpawn = chance of spawn in overworld. * @param chanceOfSpawnNether = chance of spawn in nether. * @param minVeinSize = min vein size. * @param maxVeinSize = max vein size. * @param minY = min y level. * @param maxY = max y level. */ public AbstractWorldgen(Block blockToSpawn, Block blockToSpawnNether, int chanceOfSpawn, int chanceOfSpawnNether, int minVeinSize, int maxVeinSize, int minY, int maxY) { this.BLOCK_TO_SPAWN = blockToSpawn; this.BLOCK_TO_SPAWN_NETHER = blockToSpawnNether; this.CHANCE_OF_SPAWN = chanceOfSpawn; this.CHANCE_OF_SPAWN_NETHER = chanceOfSpawnNether; this.MIN_VEIN_SIZE = minVeinSize; this.MAX_VEIN_SIZE = maxVeinSize; this.MIN_Y = minY; this.MAX_Y = maxY; } /** * Simplified constructor if only dealing with overworld worldgen. * @param blockToSpawn = block to spawn in world. * @param chanceOfSpawn = chance of spawning in world. * @param minVeinSize = min vein size. * @param maxVeinSize = max vein size. * @param minY = min y level. * @param maxY = max y level. */ public AbstractWorldgen(Block blockToSpawn, int chanceOfSpawn, int minVeinSize, int maxVeinSize, int minY, int maxY) { this(blockToSpawn, null, chanceOfSpawn, -1, minVeinSize, maxVeinSize, minY, maxY); } /* * (non-Javadoc) * @see cpw.mods.fml.common.IWorldGenerator#generate(java.util.Random, int, int, net.minecraft.world.World, net.minecraft.world.chunk.IChunkProvider, net.minecraft.world.chunk.IChunkProvider) */ @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) { switch (world.provider.getDimension()) { case -1 : generateNether(world, random, chunkX * CHUNK_SIZE, chunkZ * CHUNK_SIZE); break; case 0 : generateOverworld(world, random, chunkX * CHUNK_SIZE, chunkZ * CHUNK_SIZE); break; case 1 : generateEnd(world, random, chunkX * CHUNK_SIZE, chunkZ * CHUNK_SIZE); break; default: generateOverworld(world, random, chunkX * CHUNK_SIZE, chunkZ * CHUNK_SIZE); break; } } /** * handles ore generation in nether. * @param world = world object. * @param random = random chance object. * @param blockX = block posX. * @param blockZ = block posZ. */ private void generateNether(World world, Random random, int blockX, int blockZ) { if (this.BLOCK_TO_SPAWN_NETHER == null || this.CHANCE_OF_SPAWN_NETHER <= 0) return; int veinSize = this.MIN_VEIN_SIZE + random.nextInt(this.MAX_VEIN_SIZE - this.MIN_VEIN_SIZE); addOreSpawn(this.BLOCK_TO_SPAWN_NETHER, world, random, blockX, blockZ, this.CHUNK_SIZE, this.CHUNK_SIZE, veinSize, this.CHANCE_OF_SPAWN_NETHER, this.MIN_Y, this.MAX_Y); } /** * handles ore generation in overworld. * @param world = world object. * @param random = random chance object. * @param blockX = block posX. * @param blockZ = block posZ. */ private void generateOverworld(World world, Random random, int blockX, int blockZ) { if (this.BLOCK_TO_SPAWN == null || this.CHANCE_OF_SPAWN <= 0) return; int veinSize = this.MIN_VEIN_SIZE + random.nextInt(this.MAX_VEIN_SIZE - this.MIN_VEIN_SIZE); addOreSpawn(this.BLOCK_TO_SPAWN, world, random, blockX, blockZ, this.CHUNK_SIZE, this.CHUNK_SIZE, veinSize, this.CHANCE_OF_SPAWN, this.MIN_Y, this.MAX_Y); } /** * Currently set to deprecated as unused and incomplete. * @param world = world object. * @param random = random chance object. * @param blockX = block posX. * @param blockZ = block posZ. */ @Deprecated() private void generateEnd(World world, Random random, int blockX, int blockZ) { } /** * Handles all looping operation when actually generating the ore. * @param block = block to spawn. * @param world = world object. * @param random = random object. * @param blockXPos = block x-position. * @param blockZPos = block z-position. * @param maxX = max x-position to spawn. * @param maxZ = max z-position to spawn. * @param maxVeinSize = max size of vein. * @param minY = minimum y-level to spawn. * @param maxY = maximum y-level to spawn. */ public void addOreSpawn(Block block, World world, Random random, int blockXPos, int blockZPos, int maxX, int maxZ, int maxVeinSize, int chanceOfSpawn, int minY, int maxY) { for (int i = 0; i < chanceOfSpawn; i++) { int posX = blockXPos + random.nextInt(maxX); int posY = minY + random.nextInt(maxY - minY); int posZ = blockZPos + random.nextInt(maxZ); new WorldGenMinable(block.getDefaultState(), maxVeinSize).generate(world, random, new BlockPos(posX, posY, posZ)); } } }
hockeyhurd/HCoreLib
com/hockeyhurd/hcorelib/api/worldgen/AbstractWorldgen.java
Java
mit
5,690
package pThree; public class ThingCountRunner { public static void main(String[] args) { ThingCount one = new ThingCount(); ThingCount two = new ThingCount('A', 5); System.out.println(one); System.out.println(two); ThingCount three = new ThingCount("hello", 7); System.out.println(three); System.out.println(three.getCount()); three.setCount(22); three.setThing(54.12); System.out.println(three); System.out.println(three.equals(two)); two.setCount(22); two.setThing(54.12); System.out.println(two.equals(three)); } }
mRabitsky/RIPmrHorn
RIP Mr Horn/src/pThree/ThingCountRunner.java
Java
mit
573
package org.innovateuk.ifs.application.forms.controller; import org.innovateuk.ifs.BaseControllerMockMVCTest; import org.innovateuk.ifs.application.ApplicationUrlHelper; import org.innovateuk.ifs.application.resource.ApplicationResource; import org.innovateuk.ifs.application.service.ApplicationRestService; import org.innovateuk.ifs.application.service.SectionRestService; import org.innovateuk.ifs.form.resource.SectionResource; import org.innovateuk.ifs.form.resource.SectionType; import org.innovateuk.ifs.user.resource.ProcessRoleResource; import org.innovateuk.ifs.user.service.ProcessRoleRestService; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import java.util.Optional; import static java.util.Collections.singletonList; import static org.innovateuk.ifs.application.builder.ApplicationResourceBuilder.newApplicationResource; import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess; import static org.innovateuk.ifs.form.builder.SectionResourceBuilder.newSectionResource; import static org.innovateuk.ifs.form.resource.SectionType.PROJECT_LOCATION; import static org.innovateuk.ifs.user.builder.ProcessRoleResourceBuilder.newProcessRoleResource; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; @RunWith(org.mockito.junit.MockitoJUnitRunner.Silent.class) public class ApplicationSectionControllerTest extends BaseControllerMockMVCTest<ApplicationSectionController> { private static final long APPLICATION_ID = 1L; private static final long COMPETITION_ID = 2L; private static final long SECTION_ID = 3L; private static final long ORGANISATION_ID = 4L; private static final SectionType SECTION_TYPE = PROJECT_LOCATION; private static final ApplicationResource APPLICATION = newApplicationResource().withId(APPLICATION_ID).withCompetition(COMPETITION_ID).build(); private static final SectionResource SECTION = newSectionResource().withId(SECTION_ID).withCompetition(COMPETITION_ID).withType(SECTION_TYPE).build(); private static final ProcessRoleResource PROCESS_ROLE = newProcessRoleResource().withApplication(APPLICATION_ID).withOrganisation(ORGANISATION_ID).build(); @Mock private ProcessRoleRestService processRoleRestService; @Mock private ApplicationUrlHelper applicationUrlHelper; @Mock private SectionRestService sectionRestService; @Mock private ApplicationRestService applicationRestService; @Override protected ApplicationSectionController supplyControllerUnderTest() { return new ApplicationSectionController(); } @Test public void redirectToSectionManagement() throws Exception { when(applicationRestService.getApplicationById(APPLICATION_ID)).thenReturn(restSuccess(APPLICATION)); when(sectionRestService.getSectionsByCompetitionIdAndType(COMPETITION_ID, SECTION_TYPE)).thenReturn(restSuccess(singletonList(SECTION))); when(applicationUrlHelper.getSectionUrl(SECTION_TYPE, SECTION_ID, APPLICATION_ID, ORGANISATION_ID, COMPETITION_ID)).thenReturn(Optional.of("redirectUrl")); mockMvc.perform(get("/application/{applicationId}/form/{sectionType}/{organisationId}", APPLICATION_ID, SECTION_TYPE.name(), ORGANISATION_ID)) .andExpect(redirectedUrl("redirectUrl")); } @Test public void redirectToSection() throws Exception { when(applicationRestService.getApplicationById(APPLICATION_ID)).thenReturn(restSuccess(APPLICATION)); when(sectionRestService.getSectionsByCompetitionIdAndType(COMPETITION_ID, SECTION_TYPE)).thenReturn(restSuccess(singletonList(SECTION))); when(processRoleRestService.findProcessRole(loggedInUser.getId(), APPLICATION_ID)).thenReturn(restSuccess(PROCESS_ROLE)); when(applicationUrlHelper.getSectionUrl(SECTION_TYPE, SECTION_ID, APPLICATION_ID, ORGANISATION_ID, COMPETITION_ID)).thenReturn(Optional.of("redirectUrl")); mockMvc.perform(get("/application/{applicationId}/form/{sectionType}", APPLICATION_ID, PROJECT_LOCATION.name())) .andExpect(redirectedUrl("redirectUrl")); } @Test public void getSectionApplicant() throws Exception { when(applicationRestService.getApplicationById(APPLICATION_ID)).thenReturn(restSuccess(APPLICATION)); when(sectionRestService.getById(SECTION_ID)).thenReturn(restSuccess(SECTION)); when(processRoleRestService.findProcessRole(loggedInUser.getId(), APPLICATION_ID)).thenReturn(restSuccess(PROCESS_ROLE)); when(applicationUrlHelper.getSectionUrl(SECTION_TYPE, SECTION_ID, APPLICATION_ID, ORGANISATION_ID, COMPETITION_ID)).thenReturn(Optional.of("redirectUrl")); mockMvc.perform(get("/application/{applicationId}/form/section/{sectionId}", APPLICATION_ID, SECTION_ID)) .andExpect(redirectedUrl("redirectUrl")); } @Test public void getSectionInternalUser() throws Exception { when(applicationRestService.getApplicationById(APPLICATION_ID)).thenReturn(restSuccess(APPLICATION)); when(sectionRestService.getById(SECTION_ID)).thenReturn(restSuccess(SECTION)); when(processRoleRestService.findProcessRole(loggedInUser.getId(), APPLICATION_ID)).thenReturn(restSuccess(PROCESS_ROLE)); when(applicationUrlHelper.getSectionUrl(SECTION_TYPE, SECTION_ID, APPLICATION_ID, ORGANISATION_ID, COMPETITION_ID)).thenReturn(Optional.of("redirectUrl")); mockMvc.perform(get("/application/{applicationId}/form/section/{sectionId}/{organisationId}", APPLICATION_ID, SECTION_ID, ORGANISATION_ID)) .andExpect(redirectedUrl("redirectUrl")); } }
InnovateUKGitHub/innovation-funding-service
ifs-web-service/ifs-application-service/src/test/java/org/innovateuk/ifs/application/forms/controller/ApplicationSectionControllerTest.java
Java
mit
5,777
package com.cezarykluczynski.stapi.model.page.service; import com.cezarykluczynski.stapi.model.page.entity.Page; import com.cezarykluczynski.stapi.model.page.entity.PageAware; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.commons.lang3.tuple.Pair; import java.util.Collection; import java.util.List; import java.util.Map; abstract class AbstractPreSavePageAwareFilter { Map<Long, List<Pair<Page, PageAware>>> flattenPages(Collection<PageAware> pageAwareList) { Map<Long, List<Pair<Page, PageAware>>> map = Maps.newHashMap(); pageAwareList.forEach(pageAware -> { Long pageId = pageAware.getPage().getPageId(); if (!map.containsKey(pageId)) { map.put(pageId, Lists.newArrayList()); } map.get(pageId).add(Pair.of(pageAware.getPage(), pageAware)); }); return map; } }
cezarykluczynski/stapi
model/src/main/java/com/cezarykluczynski/stapi/model/page/service/AbstractPreSavePageAwareFilter.java
Java
mit
847
public class Main { static { // Load "gojni.dll" on Windows // Load "libgojni.so" on Linux // Load "libgojni.jnilib" on Mac System.loadLibrary("gojni"); } private static native void test(); private static void test2() { System.out.println("Hello, world from Java method!"); } private static void test3(String s) { System.out.println(s); } public static void main(String[] args) { test(); } }
asukakenji/go
jni/demo/Main.java
Java
mit
421
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.phonegap.helloworld; public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; public static final int screen=0x7f020001; } public static final class string { public static final int app_name=0x7f040000; } public static final class xml { public static final int config=0x7f030000; } }
andreyluiz/ortho-colorful-android
platforms/android/ant-gen/com/phonegap/helloworld/R.java
Java
mit
645
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.resourcehealth.implementation; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.resourcehealth.fluent.EmergingIssuesClient; import com.azure.resourcemanager.resourcehealth.fluent.models.EmergingIssuesGetResultInner; import com.azure.resourcemanager.resourcehealth.models.EmergingIssues; import com.azure.resourcemanager.resourcehealth.models.EmergingIssuesGetResult; import com.fasterxml.jackson.annotation.JsonIgnore; public final class EmergingIssuesImpl implements EmergingIssues { @JsonIgnore private final ClientLogger logger = new ClientLogger(EmergingIssuesImpl.class); private final EmergingIssuesClient innerClient; private final com.azure.resourcemanager.resourcehealth.ResourceHealthManager serviceManager; public EmergingIssuesImpl( EmergingIssuesClient innerClient, com.azure.resourcemanager.resourcehealth.ResourceHealthManager serviceManager) { this.innerClient = innerClient; this.serviceManager = serviceManager; } public EmergingIssuesGetResult get() { EmergingIssuesGetResultInner inner = this.serviceClient().get(); if (inner != null) { return new EmergingIssuesGetResultImpl(inner, this.manager()); } else { return null; } } public Response<EmergingIssuesGetResult> getWithResponse(Context context) { Response<EmergingIssuesGetResultInner> inner = this.serviceClient().getWithResponse(context); if (inner != null) { return new SimpleResponse<>( inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), new EmergingIssuesGetResultImpl(inner.getValue(), this.manager())); } else { return null; } } public PagedIterable<EmergingIssuesGetResult> list() { PagedIterable<EmergingIssuesGetResultInner> inner = this.serviceClient().list(); return Utils.mapPage(inner, inner1 -> new EmergingIssuesGetResultImpl(inner1, this.manager())); } public PagedIterable<EmergingIssuesGetResult> list(Context context) { PagedIterable<EmergingIssuesGetResultInner> inner = this.serviceClient().list(context); return Utils.mapPage(inner, inner1 -> new EmergingIssuesGetResultImpl(inner1, this.manager())); } private EmergingIssuesClient serviceClient() { return this.innerClient; } private com.azure.resourcemanager.resourcehealth.ResourceHealthManager manager() { return this.serviceManager; } }
Azure/azure-sdk-for-java
sdk/resourcehealth/azure-resourcemanager-resourcehealth/src/main/java/com/azure/resourcemanager/resourcehealth/implementation/EmergingIssuesImpl.java
Java
mit
2,934
/* * Copyright (c) 2014-present Martin Paljak * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package apdu4j.pcsc; import apdu4j.core.CommandAPDU; import apdu4j.core.ResponseAPDU; import apdu4j.core.*; import apdu4j.pcsc.terminals.LoggingCardTerminal; import jnasmartcardio.Smartcardio; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.smartcardio.*; import javax.smartcardio.CardTerminals.State; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; /** * Facilitates working with javax.smartcardio TerminalFactory/CardTerminals * <p> * Also knows about an alternative implementation, jnasmartcardio */ public final class TerminalManager { private static final Logger logger = LoggerFactory.getLogger(TerminalManager.class); public static final String LIB_PROP = "sun.security.smartcardio.library"; private static final String debian64_path = "/usr/lib/x86_64-linux-gnu/libpcsclite.so.1"; private static final String ubuntu_path = "/lib/libpcsclite.so.1"; private static final String ubuntu32_path = "/lib/i386-linux-gnu/libpcsclite.so.1"; private static final String ubuntu64_path = "/lib/x86_64-linux-gnu/libpcsclite.so.1"; private static final String freebsd_path = "/usr/local/lib/libpcsclite.so"; private static final String fedora64_path = "/usr/lib64/libpcsclite.so.1"; private static final String raspbian_path = "/usr/lib/arm-linux-gnueabihf/libpcsclite.so.1"; private final TerminalFactory factory; // TODO: this whole threadlocal stuff should end up in jnasmartcardio? // it is not static as it is tied to factory instance of this class private ThreadLocal<CardTerminals> threadLocalTerminals = ThreadLocal.withInitial(() -> null); public static TerminalManager getDefault() { return new TerminalManager(getTerminalFactory()); } public TerminalManager(TerminalFactory factory) { this.factory = factory; } public CardTerminals terminals() { return terminals(false); } public CardTerminals terminals(boolean fresh) { CardTerminals terms = threadLocalTerminals.get(); // Explicity release the old context if using jnasmartcardio if (terms != null && fresh && terms instanceof Smartcardio.JnaCardTerminals) { try { ((Smartcardio.JnaCardTerminals) terms).close(); } catch (Smartcardio.JnaPCSCException e) { logger.warn("Could not release context: {}", SCard.getExceptionMessage(e), e); } } if (terms == null || fresh) { terms = factory.terminals(); threadLocalTerminals.set(terms); } return terms; } public TerminalFactory getFactory() { return factory; } // Makes sure the associated context would be thread-local for jnasmartcardio and Linux public CardTerminal getTerminal(String name) { return terminals().getTerminal(name); } public static boolean isEnabled(String feature, boolean def) { return Boolean.parseBoolean(System.getProperty(feature, System.getenv().getOrDefault("_" + feature.toUpperCase().replace(".", "_"), Boolean.toString(def)))); } // SunPCSC needs to have the path to the loadable library to work, for whatever reasons. public static String detectLibraryPath() { // Would be nice to use Files.exists instead. final String os = System.getProperty("os.name"); // Set necessary parameters for seamless PC/SC access. // http://ludovicrousseau.blogspot.com.es/2013/03/oracle-javaxsmartcardio-failures.html if (os.equalsIgnoreCase("Linux")) { // Only try loading 64b paths if JVM can use them. if (System.getProperty("os.arch").contains("64")) { if (new File(debian64_path).exists()) { return debian64_path; } else if (new File(fedora64_path).exists()) { return fedora64_path; } else if (new File(ubuntu64_path).exists()) { return ubuntu64_path; } } else if (new File(ubuntu_path).exists()) { return ubuntu_path; } else if (new File(ubuntu32_path).exists()) { return ubuntu32_path; } else if (new File(raspbian_path).exists()) { return raspbian_path; } else { // XXX: dlopen() works properly on Debian OpenJDK 7 // System.err.println("Hint: pcsc-lite probably missing."); } } else if (os.equalsIgnoreCase("FreeBSD")) { if (new File(freebsd_path).exists()) { return freebsd_path; } else { System.err.println("Hint: pcsc-lite is missing. pkg install devel/libccid"); } } else if (os.equalsIgnoreCase("Mac OS X")) { // XXX: research/document this return "/System/Library/Frameworks/PCSC.framework/PCSC"; } return null; } /** * Locates PC/SC shared library on the system and automagically sets system properties so that SunPCSC * could find the smart card service. Call this before acquiring your TerminalFactory. */ public static void fixPlatformPaths() { Optional<String> lib = Optional.ofNullable(detectLibraryPath()); if (System.getProperty(LIB_PROP) == null && lib.isPresent()) { System.setProperty(LIB_PROP, lib.get()); } } // Utility function to return a "Good terminal factory" (JNA) public static TerminalFactory getTerminalFactory() { try { return TerminalFactory.getInstance("PC/SC", null, new Smartcardio()); } catch (NoSuchAlgorithmException e) { logger.error("jnasmartcardio not bundled or pcsc-lite not available"); // Should result in NoneProvider return TerminalFactory.getDefault(); } } /** * Return a list of CardTerminal-s that contain a card with one of the specified ATR-s. * The returned reader might be unusable (in use in exclusive mode). * * @param terminals List of CardTerminal-s to use * @param atrs Collection of ATR-s to match * @return list of CardTerminal-s */ public static List<CardTerminal> byATR(List<CardTerminal> terminals, Collection<byte[]> atrs) { return terminals.stream().filter(t -> { try { if (t.isCardPresent()) { Card c = t.connect("DIRECT"); byte[] atr = c.getATR().getBytes(); c.disconnect(false); return atrs.stream().anyMatch(a -> Arrays.equals(a, atr)); } else { return false; } } catch (CardException e) { logger.debug("Failed to get ATR: " + e.getMessage(), e); return false; } }).collect(Collectors.toList()); } public static List<CardTerminal> byATR(CardTerminals terminals, Collection<byte[]> atrs) throws CardException { List<CardTerminal> tl = terminals.list(State.ALL); return byATR(tl, atrs); } public static List<CardTerminal> byFilter(List<CardTerminal> terminals, Function<BIBO, Boolean> f) { return terminals.stream().filter(t -> { try { if (t.isCardPresent()) { try (BIBO b = CardBIBO.wrap(t.connect("*"))) { return f.apply(b); } } else { return false; } } catch (CardException e) { // FIXME: handle exclusive mode logger.debug("Failed to detect card: " + e.getMessage(), e); return false; } }).collect(Collectors.toList()); } // Useful function for byFilter public static Function<BIBO, Boolean> hasAID(Collection<byte[]> aidlist) { return bibo -> { APDUBIBO b = new APDUBIBO(bibo); for (byte[] aid : aidlist) { // Try to select the AID CommandAPDU s = new CommandAPDU(0x00, 0xA4, 0x04, 0x00, aid, 256); ResponseAPDU r = b.transmit(s); if (r.getSW() == 0x9000) { logger.debug("matched for AID {}", HexUtils.bin2hex(aid)); return true; } } return false; }; } // Locate a terminal by AID public static List<CardTerminal> byAID(List<CardTerminal> terminals, Collection<byte[]> aidlist) { return byFilter(terminals, hasAID(aidlist)); } public static List<CardTerminal> byAID(Collection<byte[]> aidlist) throws NoSuchAlgorithmException, CardException { TerminalFactory tf = TerminalFactory.getInstance("PC/SC", null, new jnasmartcardio.Smartcardio()); CardTerminals ts = tf.terminals(); return byAID(ts.list(), aidlist); } // Returns CalVer+git of the utility public static String getVersion() { Properties prop = new Properties(); try (InputStream versionfile = TerminalManager.class.getResourceAsStream("git.properties")) { prop.load(versionfile); return prop.getProperty("git.commit.id.describe", "unknown-development"); } catch (IOException e) { return "unknown-error"; } } // DWIM magic. See if we can pick the interesting reader automagically public static <T> Optional<T> toSingleton(Collection<T> collection, Predicate<T> filter) { List<T> result = collection.stream().filter(filter).limit(2).collect(Collectors.toList()); if (result.size() == 1) return Optional.of(result.get(0)); return Optional.empty(); } public static Optional<String> hintMatchesExactlyOne(String hint, List<String> hay) { if (hint == null) return Optional.empty(); return toSingleton(hay, n -> fragmentMatches(hint, n)); } private static boolean fragmentMatches(String fragment, String longer) { return longer.toLowerCase().contains(fragment.toLowerCase()); } // Returns true if the reader contains fragments to ignore (given as semicolon separated string) public static boolean ignoreReader(String ignoreHints, String readerName) { if (ignoreHints != null) { String reader = readerName.toLowerCase(); String[] names = ignoreHints.toLowerCase().split(";"); return Arrays.stream(names).anyMatch(reader::contains); } return false; } // Fetch what is a combination of CardTerminal + Card data and handle all the weird errors of PC/SC public static List<PCSCReader> listPCSC(List<CardTerminal> terminals, OutputStream logStream, boolean probePinpad) throws CardException { ArrayList<PCSCReader> result = new ArrayList<>(); for (CardTerminal t : terminals) { if (logStream != null) { t = LoggingCardTerminal.getInstance(t, logStream); } try { final String name = t.getName(); boolean present = t.isCardPresent(); boolean exclusive = false; String vmd = null; byte[] atr = null; if (present) { Card c = null; // Try to connect in shared mode, also detects EXCLUSIVE try { c = t.connect("*"); // If successful, we get the protocol and ATR atr = c.getATR().getBytes(); if (probePinpad) vmd = PinPadTerminal.getVMD(t, c); } catch (CardException e) { String err = SCard.getExceptionMessage(e); if (err.equals(SCard.SCARD_W_UNPOWERED_CARD)) { logger.warn("Unpowered card. Contact card inserted wrong way or card mute?"); // We don't present such cards, as for contactless this is a no-case TODO: reconsider ? present = false; } else if (err.equals(SCard.SCARD_E_SHARING_VIOLATION)) { exclusive = true; // macOS allows to connect to reader in DIRECT mode when device is in EXCLUSIVE try { c = t.connect("DIRECT"); atr = c.getATR().getBytes(); if (probePinpad) vmd = PinPadTerminal.getVMD(t, c); } catch (CardException e2) { String err2 = SCard.getExceptionMessage(e); if (probePinpad) if (err2.equals(SCard.SCARD_E_SHARING_VIOLATION)) { vmd = "???"; } else { vmd = "EEE"; logger.debug("Unexpected error: {}", err2, e2); } } } else { if (probePinpad) vmd = "EEE"; logger.debug("Unexpected error: {}", err, e); } } finally { if (c != null) c.disconnect(false); } } else { // Not present if (probePinpad) { Card c = null; // Try to connect in DIRECT mode try { c = t.connect("DIRECT"); vmd = PinPadTerminal.getVMD(t, c); } catch (CardException e) { vmd = "EEE"; String err = SCard.getExceptionMessage(e); logger.debug("Could not connect to reader in direct mode: {}", err, e); } finally { if (c != null) c.disconnect(false); } } } result.add(new PCSCReader(name, atr, present, exclusive, vmd)); } catch (CardException e) { String err = SCard.getExceptionMessage(e); logger.debug("Unexpected PC/SC error: {}", err, e); } } return result; } // Set the preferred and ignored flags on a reader list, based on hints. Returns the same list public static List<PCSCReader> dwimify(List<PCSCReader> readers, String preferHint, String ignoreHints) { logger.debug("Processing {} readers with {} as preferred and {} as ignored", readers.size(), preferHint, ignoreHints); final ReaderAliases aliases = ReaderAliases.getDefault().apply(readers.stream().map(PCSCReader::getName).collect(Collectors.toList())); final List<String> aliasedNames = readers.stream().map(r -> aliases.extended(r.getName())).collect(Collectors.toList()); // No readers if (readers.size() == 0) return readers; Optional<String> pref = Optional.empty(); // DWIM 1: small digit hint means reader index if (preferHint != null && preferHint.matches("\\d{1,2}")) { int index = Integer.parseInt(preferHint); if (index >= 1 && index <= readers.size()) { pref = Optional.of(readers.get(index - 1).getName()); logger.debug("Chose {} by index {}", pref.get(), index); } else { logger.warn("Reader index out of bounds: {} vs {}", index, readers.size()); } } else if (preferHint != null) { pref = TerminalManager.hintMatchesExactlyOne(preferHint, aliasedNames); } else if (readers.size() == 1) { // One reader readers.get(0).setPreferred(true); return readers; } logger.debug("Preferred reader: " + pref); // Loop all readers, amending as necessary. for (PCSCReader r : readers) { if (pref.isPresent() && pref.get().toLowerCase().contains(r.getName().toLowerCase())) { r.setPreferred(true); // preference overrides ignores continue; } if (TerminalManager.ignoreReader(ignoreHints, r.getName())) { r.setIgnore(true); continue; } } // "if no preferred, but just a single reader of un-ignored readers contains a card - use it //logger.info("Readers after dwimify"); //for (PCSCReader r : readers) { // logger.info("{}", r); //} return readers; } public static Optional<CardTerminal> getLucky(List<PCSCReader> readers, CardTerminals terminals) { Optional<PCSCReader> preferred = toSingleton(readers, e -> e.isPreferred()); Optional<PCSCReader> lucky = toSingleton(readers, e -> !e.isIgnore() && e.isPresent()); Optional<PCSCReader> chosen = preferred.or(() -> lucky); if (chosen.isPresent()) { return Optional.ofNullable(terminals.getTerminal(chosen.get().getName())); } return Optional.empty(); } public static boolean isMacOS() { return System.getProperty("os.name").equalsIgnoreCase("mac os x"); } public static boolean isWindows() { return System.getProperty("os.name").toLowerCase().startsWith("windows"); } }
martinpaljak/apdu4j
pcsc/src/main/java/apdu4j/pcsc/TerminalManager.java
Java
mit
19,173
package com.gmalmquist.tpm.util; import com.gmalmquist.tpm.Main; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileInputStream; import java.io.PrintStream; import java.math.BigInteger; /** * Cache for external calls. */ public class ExternalCache { private static File cacheDir = new File(System.getProperty("user.home") + File.separator + ".tpm-cache"); private ExternalCache() { } public static String getCachePath(String externalCall) { try { return cacheDir + File.separator + String.format("%x", new BigInteger(1, externalCall.getBytes("UTF-8"))) + ".extcall"; } catch (Exception ex) { System.err.println(ex); return null; } } public static boolean hasCache(String externalCall) { if (Main.FLAGS.contains("nocache")) { return false; } return new File(getCachePath(externalCall)).exists(); } public static String getCacheData(String externalCall) { if (Main.FLAGS.contains("nocache")) { return null; } BufferedReader in = null; try { in = new BufferedReader( new InputStreamReader( new FileInputStream(getCachePath(externalCall)))); } catch (IOException ex) { return null; } StringBuffer sb = new StringBuffer(128); String line = null; do { try { line = in.readLine(); } catch (IOException ex) { break; } if (line != null) { if (sb.length() > 0) { sb.append("\n"); } sb.append(line); } } while (line != null); return sb.toString(); } public static boolean setCacheData(String externalCall, String data) { if (!cacheDir.exists() && !cacheDir.mkdirs()) { return false; } String path = getCachePath(externalCall); PrintStream out = null; try { out = new PrintStream(new File(path)); } catch (Exception ex) { return false; } out.print(data); out.flush(); out.close(); return true; } }
gmalmquist/too-powerful-macros
src/java/com/gmalmquist/tpm/util/ExternalCache.java
Java
mit
2,088
package net.iponweb.disthene.reader.graphite.functions; import net.iponweb.disthene.reader.beans.TimeSeries; import net.iponweb.disthene.reader.exceptions.EvaluationException; import net.iponweb.disthene.reader.exceptions.InvalidArgumentException; import net.iponweb.disthene.reader.exceptions.TimeSeriesNotAlignedException; import net.iponweb.disthene.reader.graphite.PathTarget; import net.iponweb.disthene.reader.graphite.Target; import net.iponweb.disthene.reader.graphite.evaluation.TargetEvaluator; import net.iponweb.disthene.reader.utils.CollectionUtils; import net.iponweb.disthene.reader.utils.DateTimeUtils; import net.iponweb.disthene.reader.utils.TimeSeriesUtils; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * @author Andrei Ivanov */ public class StdevFunction extends DistheneFunction { public StdevFunction(String text) { super(text, "stdev"); } @Override public List<TimeSeries> evaluate(TargetEvaluator evaluator) throws EvaluationException { List<TimeSeries> processedArguments = new ArrayList<>(); processedArguments.addAll(evaluator.eval((Target) arguments.get(0))); if (processedArguments.size() == 0) return new ArrayList<>(); if (!TimeSeriesUtils.checkAlignment(processedArguments)) { throw new TimeSeriesNotAlignedException(); } int length = processedArguments.get(0).getValues().length; int step = processedArguments.get(0).getStep(); // need to get window in number of data points long window; if (arguments.get(1) instanceof Double) { window = ((Double) arguments.get(1)).longValue(); } else { long offset = Math.abs(DateTimeUtils.parseTimeOffset((String) arguments.get(1))); window = offset / step; } for (TimeSeries ts : processedArguments) { Queue<Double> queue = new LinkedList<>(); Double[] values = new Double[length]; for (int i = 0; i < length; i++) { if (queue.size() == 0) { values[i] = 0.; } else { values[i] = CollectionUtils.stdev(queue); } if (ts.getValues()[i] != null) { queue.offer(ts.getValues()[i]); } if (queue.size() > window) { queue.remove(); } } ts.setValues(values); ts.setName("stdev(" + ts.getName() + "," + window + ")"); } return processedArguments; } @Override public void checkArguments() throws InvalidArgumentException { if (arguments.size() != 2) throw new InvalidArgumentException("stdev: number of arguments is " + arguments.size() + ". Must be two."); if (!(arguments.get(0) instanceof PathTarget)) throw new InvalidArgumentException("stdev: argument is " + arguments.get(0).getClass().getName() + ". Must be series"); if (!(arguments.get(1) instanceof Double) && !(arguments.get(1) instanceof String)) throw new InvalidArgumentException("stdev: argument is " + arguments.get(1).getClass().getName() + ". Must be a number or a string"); } }
EinsamHauer/disthene-reader
src/main/java/net/iponweb/disthene/reader/graphite/functions/StdevFunction.java
Java
mit
3,284
package androidapp.smartshopper.smartshopper; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.json.JSONObject; /** * A simple {@link Fragment} subclass. */ public class AccCreateFragment extends Fragment { private Context context; private EditText idField; private EditText passField; private EditText passConfirmField; private Button create; private String newId; private String newPw; private String pwConf; public AccCreateFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_acc_create, container, false); idField = (EditText) view.findViewById(R.id.id); passField = (EditText) view.findViewById(R.id.pw); passConfirmField = (EditText) view.findViewById(R.id.new_pw_confirm); create = (Button) view.findViewById(R.id.create_button); create.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { newId = idField.getText().toString(); newPw = passField.getText().toString(); pwConf = passConfirmField.getText().toString(); if(newPw.equals(pwConf)) { String accCreateReq = new RequestBuilder().buildAccountCreatReq(newId, newPw); try { String jsonResponse = new SendAccCreateRequest().execute(accCreateReq).get(); JSONObject respJSON = new JSONObject(jsonResponse); String created = respJSON.getString("status"); if(created.equals("failed")) Toast.makeText(getActivity(), "Account Already Exists", Toast.LENGTH_SHORT).show(); else { Toast.makeText(getActivity(), "Accoutn Has Been Created", Toast.LENGTH_SHORT).show(); getActivity().onBackPressed(); } } catch (Exception e) { e.printStackTrace(); Toast.makeText(getActivity(), "Something Went Wrong", Toast.LENGTH_SHORT).show(); return; } } else { Toast.makeText(getActivity(), "Password Confirmation is Wrong", Toast.LENGTH_SHORT).show(); } } }); return view; } private class SendAccCreateRequest extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... request) { SmartShopClient client = new SmartShopClient(); if(client.getStatus()) return client.sendRequest(request[0]); else return "Connection Not Established"; } @Override protected void onPostExecute(String request) { super.onPostExecute(request); } } }
BenjaminLang/cpen_321
Android/SmartShopper/app/src/main/java/androidapp/smartshopper/smartshopper/AccCreateFragment.java
Java
mit
3,420
package sword.langbook3.android.models; import sword.collections.ImmutableIntList; public final class Progress { private final ImmutableIntList amountPerScore; private final int answeredQuestionsCount; private final int numberOfQuestions; public Progress(ImmutableIntList amountPerScore, int numberOfQuestions) { final int answeredQuestions = amountPerScore.sum(); if (answeredQuestions > numberOfQuestions) { throw new IllegalArgumentException(); } this.amountPerScore = amountPerScore; this.answeredQuestionsCount = answeredQuestions; this.numberOfQuestions = numberOfQuestions; } public ImmutableIntList getAmountPerScore() { return amountPerScore; } public int getAnsweredQuestionsCount() { return answeredQuestionsCount; } public int getNumberOfQuestions() { return numberOfQuestions; } }
carlos-sancho-ramirez/android-java-langbook
dbManager/src/main/java/sword/langbook3/android/models/Progress.java
Java
mit
930
package commands; public class Commands { public static void main(String[] args) { System.out.printf("How are you?: %s", "OK"); //This line was fine System.out.println("Nice to \"meet\", you"); //Moved the comma and make the word "meet" in qoutes(I was not shure what to repair else comma sign, because after that code work well) System.out.println("\\\"////"); //Remove one of the '\' sign to make line working again not shure if this was the only problem to repair. System.out.println("\"public\" is a reserved word in Java"); //Replaic '/' with '\' System.out.println("\n" + "2 / 2 = " + "1\n"); //This line works well } }
diyanbogdanov/Java
СУ - УП Java/07.03.2016/Домашно/Бърза Проверка на знанията/Commands/src/commands/Commands.java
Java
mit
681
package redes3.proyecto.nagiosalert; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.lang.reflect.*; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import android.view.View; import android.widget.ListView; import android.widget.Toast; import android.app.Activity; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.os.StrictMode; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; public class ServiceActivity extends ListActivity { String stringJson; String[] servicios; ArrayList<servicio>[] listaServicios ; envio hostService; int position; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); buscarEstructuras(); } /* * Metodo que trae las estructuras del viejo activity * */ public void buscarEstructuras(){ MyApplication state = ((MyApplication) getApplicationContext()); position = state.getPosition(); hostService = state.getEnvio(position); leerServicios(); } public void leerServicios(){ ArrayList<servicio> s = hostService.getServicios(); servicios = new String[s.size()]; int i = 0; while(i<s.size()) { servicios[i] = s.get(i).getNombre(); //System.out.println("PRUEBA"+s.get(i).getNombre()); i++; } crearLista(); } public void crearLista(){ setListAdapter(new ServiceArrayAdapter(this,servicios, hostService)); } /* * Metodo que se encarga de crear el listView para un Servicio especifico * * */ @Override protected void onListItemClick(ListView l, View v, int position, long id) { //get selected items String selectedValue = (String) getListAdapter().getItem(position); Intent i = new Intent(ServiceActivity.this, InfoServiceActivity.class); servicio s = hostService.getServicios().get(position); i.putExtra( "nombre", s.getNombre()); i.putExtra( "status", s.getStatus()); i.putExtra( "duracion", s.getDuracion()); i.putExtra( "revision", s.getRevision()); i.putExtra( "info", s.getInfo()); startActivity(i); } }
caat91/NagiosAlert
NagiosAlert-App/src/redes3/proyecto/nagiosalert/ServiceActivity.java
Java
mit
2,524
package palleteRobotCommunication.domain; import jade.content.Concept; public class Pallete implements Concept { private static final long serialVersionUID = 6518481924822268777L; private int maxCapacity; private int capacity; public int getCapacity() { return capacity; } public void setCapacity(int capacity) { this.capacity = capacity; } public int getMaxCapacity() { return maxCapacity; } public void setMaxCapacity(int maxCapacity) { this.maxCapacity = maxCapacity; } }
gseteamproject/Examples
examples/src/main/java/palleteRobotCommunication/domain/Pallete.java
Java
mit
502
package com.merapar.graphql.executor; import graphql.GraphQLException; import lombok.val; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import java.util.LinkedHashMap; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(SpringRunner.class) @ContextConfiguration(classes = GraphQlExecutorImplTestConfiguration.class) public class GraphQlExecutorImplTest { @Autowired private GraphQlExecutor graphQlExecutor; @Test public void processRequest_invalidVariablesJson_shouldThrowException() { // Given val request = new LinkedHashMap<String, Object>(); request.put("query", "dummy"); request.put("operationName", "dummy"); request.put("variables", "no JSON object"); // When val exception = assertThatThrownBy(() -> graphQlExecutor.executeRequest(request)); // Then exception.isExactlyInstanceOf(GraphQLException.class).hasMessage("Cannot parse variables"); } @Test public void processRequest_invalidVariablesType_shouldThrowException() { // Given val request = new LinkedHashMap<String, Object>(); request.put("query", "dummy"); request.put("operationName", "dummy"); request.put("variables", 1234); // When val exception = assertThatThrownBy(() -> graphQlExecutor.executeRequest(request)); // Then exception.isExactlyInstanceOf(GraphQLException.class).hasMessage("Incorrect variables"); } @Test public void processRequestWithoutVariables_shouldExecuteProcess() { // Given val request = new LinkedHashMap<String, Object>(); request.put("query", "dummy"); request.put("operationName", "dummy"); // When val result = graphQlExecutor.executeRequest(request); // Then assertThat(result).isNotNull(); } @Test public void processRequestWithEmptyString_shouldExecuteProcess() { // Given val request = new LinkedHashMap<String, Object>(); request.put("query", "dummy"); request.put("operationName", "dummy"); request.put("variables", ""); // When val result = graphQlExecutor.executeRequest(request); // Then assertThat(result).isNotNull(); } }
merapar/spring-boot-starter-graphql
graphql-core/src/test/java/com/merapar/graphql/executor/GraphQlExecutorImplTest.java
Java
mit
2,560
/* * Copyright (c) 2017. Hanlin He * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import org.junit.Test; import java.util.ArrayList; import java.util.List; public class L078 { @Test public void subsetsBitwise() throws Exception { Solution solution = new Solution(); int[] s = {11, 22, 33, 44, 55}; System.out.println(solution.subsetsBitwise(s)); } @Test public void subsetsIntuitive() throws Exception { Solution solution = new Solution(); int[] s = {11, 22, 33, 44, 55}; System.out.println(solution.subsetsIntuitive(s)); } @Test public void subsets() throws Exception { } class Solution { /** * Intuitive solution following the previous problem 077.Combination. The union of all * combinations are the subsets. The previous solution compute all the index (actually * index+1), then after the union, change each value the actual value in the corresponding * index. Actual running time is slow. * * @param nums : List to be compute. * @return : List of all subset. */ public List<List<Integer>> subsetsIntuitive(int[] nums) { L077.Solution c = new L077.Solution(); List<List<Integer>> ret = new ArrayList<>(); for (int i = 0; i <= nums.length; i++) ret.addAll(c.combine(nums.length, i)); for (List<Integer> l : ret) { l.replaceAll(i -> nums[i - 1]); } return ret; } /** * Bitwise solution. Since a subset can be represented as a bit string of length n, like * '00010000101', and total number of possible subset is 2^n. We can just iterate from 1 to * 2^n, for each number, generate a subset based on the corresponding bit string. A trick to * extract specific bit from a bit string is simply bitwise AND with another specific bit * string, for example '00000001'. * * @param nums : List to be compute. * @return : List of all subset. */ public List<List<Integer>> subsetsBitwise(int[] nums) { int size = ((int) Math.pow(2, nums.length)); List<List<Integer>> ret = new ArrayList<>(size); List<Integer> subset; for (int i = 0; i < size; i++) { subset = new ArrayList<>(); for (int j = i, k = 0; j > 0; j >>= 1, k++) { if ((j & 1) == 1) subset.add(nums[k]); } ret.add(subset); } return ret; } } }
hanlin-he/UTD
leetcode/java/L078.java
Java
mit
3,714
package de.saarland.hamming; /** * @author Almer Bolatov * Date: 11/22/13 * Time: 3:40 PM */ public class Query { private Node node; private int start; private int k; public Query() {} public Node getNode() { return node; } public void setNode(Node n) { this.node = n; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getK() { return k; } public void setK(int k) { this.k = k; } }
bolatov/string-matching
src/de/saarland/hamming/Query.java
Java
mit
497
package graphql.sql.core.config; import com.healthmarketscience.sqlbuilder.dbspec.basic.DbForeignKeyConstraint; import graphql.sql.core.config.domain.Entity; import graphql.sql.core.config.domain.EntityField; import graphql.sql.core.config.domain.ReferenceType; public interface NameProvider { String getEntityName(String tableName); String getFieldName(String columnName); String getLinkName(DbForeignKeyConstraint constraint, Entity from, Entity to, ReferenceType type); String getFieldListName(EntityField entityField); }
zvorygin/graphql-over-sql
graphql-common/src/main/java/graphql/sql/core/config/NameProvider.java
Java
mit
546
package fr.adbonnin.shalltear.utils.date; public final class TimeUtils { public static final int MILLIS_PER_SECOND = 1000; public static final int MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND; public static final int MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE; public static final int MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR; private TimeUtils() { /* Cannot be instantiated */ } }
adbonnin/shalltear
shalltear-core/src/main/java/fr/adbonnin/shalltear/utils/date/TimeUtils.java
Java
mit
406
package org.uma.jmetal.experimental.componentbasedalgorithm.catalogue.selection.impl; import org.uma.jmetal.experimental.componentbasedalgorithm.catalogue.selection.MatingPoolSelection; import org.uma.jmetal.operator.selection.impl.NaryTournamentSelection; import org.uma.jmetal.solution.Solution; import org.uma.jmetal.experimental.componentbasedalgorithm.util.Preference; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class NaryTournamentMatingPoolSelection<S extends Solution<?>> implements MatingPoolSelection<S> { private NaryTournamentSelection<S> selectionOperator; private int matingPoolSize; private Preference<S> preference; public NaryTournamentMatingPoolSelection(NaryTournamentSelection<S> selection, int matingPoolSize) { this.matingPoolSize = matingPoolSize ; this.selectionOperator = selection ; } public NaryTournamentMatingPoolSelection( int tournamentSize, int matingPoolSize, Comparator<S> comparator) { selectionOperator = new NaryTournamentSelection<>(tournamentSize, comparator); this.matingPoolSize = matingPoolSize; preference = null ; } public NaryTournamentMatingPoolSelection( int tournamentSize, int matingPoolSize, Preference<S> preference) { this.preference = preference ; this.selectionOperator = new NaryTournamentSelection<>(tournamentSize, preference.getComparator()); this.matingPoolSize = matingPoolSize; } public List<S> select(List<S> solutionList) { if (null != preference) { preference.recompute(solutionList) ; } List<S> matingPool = new ArrayList<>(matingPoolSize); while (matingPool.size() < matingPoolSize) { matingPool.add(selectionOperator.execute(solutionList)); } return matingPool; } }
matthieu-vergne/jMetal
jmetal-experimental/src/main/java/org/uma/jmetal/experimental/componentbasedalgorithm/catalogue/selection/impl/NaryTournamentMatingPoolSelection.java
Java
mit
1,793
/* * The MIT License (MIT) * * Copyright (c) 2015 Oembedler Inc. and Contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.cybozu.labs.langdetect.util; import java.lang.Character.UnicodeBlock; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Cut out N-gram from text. * Users don't use this class directly. * @author Nakatani Shuyo */ public class NGram { private static final String LATIN1_EXCLUDED = Messages.getString("NGram.LATIN1_EXCLUDE"); public final static int N_GRAM = 3; public static HashMap<Character, Character> cjk_map; private StringBuffer grams_; private boolean capitalword_; /** * Constructor. */ public NGram() { grams_ = new StringBuffer(" "); capitalword_ = false; } public void addChar(char ch) { ch = normalize(ch); char lastchar = grams_.charAt(grams_.length() - 1); if (lastchar == ' ') { grams_ = new StringBuffer(" "); capitalword_ = false; if (ch==' ') return; } else if (grams_.length() >= N_GRAM) { grams_.deleteCharAt(0); } grams_.append(ch); if (Character.isUpperCase(ch)){ if (Character.isUpperCase(lastchar)) capitalword_ = true; } else { capitalword_ = false; } } public String get(int n) { if (capitalword_) return null; int len = grams_.length(); if (n < 1 || n > 3 || len < n) return null; if (n == 1) { char ch = grams_.charAt(len - 1); if (ch == ' ') return null; return Character.toString(ch); } else { return grams_.substring(len - n, len); } } static public char normalize(char ch) { Character.UnicodeBlock block = Character.UnicodeBlock.of(ch); if (block == UnicodeBlock.BASIC_LATIN) { if (ch<'A' || (ch<'a' && ch >'Z') || ch>'z') ch = ' '; } else if (block == UnicodeBlock.LATIN_1_SUPPLEMENT) { if (LATIN1_EXCLUDED.indexOf(ch)>=0) ch = ' '; } else if (block == UnicodeBlock.LATIN_EXTENDED_B) { // normalization for Romanian if (ch == '\u0219') ch = '\u015f'; // Small S with comma below => with cedilla if (ch == '\u021b') ch = '\u0163'; // Small T with comma below => with cedilla } else if (block == UnicodeBlock.GENERAL_PUNCTUATION) { ch = ' '; } else if (block == UnicodeBlock.ARABIC) { if (ch == '\u06cc') ch = '\u064a'; // Farsi yeh => Arabic yeh } else if (block == UnicodeBlock.LATIN_EXTENDED_ADDITIONAL) { if (ch >= '\u1ea0') ch = '\u1ec3'; } else if (block == UnicodeBlock.HIRAGANA) { ch = '\u3042'; } else if (block == UnicodeBlock.KATAKANA) { ch = '\u30a2'; } else if (block == UnicodeBlock.BOPOMOFO || block == UnicodeBlock.BOPOMOFO_EXTENDED) { ch = '\u3105'; } else if (block == UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS) { if (cjk_map.containsKey(ch)) ch = cjk_map.get(ch); } else if (block == UnicodeBlock.HANGUL_SYLLABLES) { ch = '\uac00'; } return ch; } public static String normalize_vi(String text) { Matcher m = ALPHABET_WITH_DMARK.matcher(text); StringBuffer buf = new StringBuffer(); while (m.find()) { int alphabet = TO_NORMALIZE_VI_CHARS.indexOf(m.group(1)); int dmark = DMARK_CLASS.indexOf(m.group(2)); // Diacritical Mark m.appendReplacement(buf, NORMALIZED_VI_CHARS[dmark].substring(alphabet, alphabet + 1)); } if (buf.length() == 0) return text; m.appendTail(buf); return buf.toString(); } private static final String[] NORMALIZED_VI_CHARS = { Messages.getString("NORMALIZED_VI_CHARS_0300"), Messages.getString("NORMALIZED_VI_CHARS_0301"), Messages.getString("NORMALIZED_VI_CHARS_0303"), Messages.getString("NORMALIZED_VI_CHARS_0309"), Messages.getString("NORMALIZED_VI_CHARS_0323") }; private static final String TO_NORMALIZE_VI_CHARS = Messages.getString("TO_NORMALIZE_VI_CHARS"); private static final String DMARK_CLASS = Messages.getString("DMARK_CLASS"); private static final Pattern ALPHABET_WITH_DMARK = Pattern.compile("([" + TO_NORMALIZE_VI_CHARS + "])([" + DMARK_CLASS + "])"); /** * CJK Kanji Normalization Mapping */ static final String[] CJK_CLASS = { Messages.getString("NGram.KANJI_1_0"), Messages.getString("NGram.KANJI_1_2"), Messages.getString("NGram.KANJI_1_4"), Messages.getString("NGram.KANJI_1_8"), Messages.getString("NGram.KANJI_1_11"), Messages.getString("NGram.KANJI_1_12"), Messages.getString("NGram.KANJI_1_13"), Messages.getString("NGram.KANJI_1_14"), Messages.getString("NGram.KANJI_1_16"), Messages.getString("NGram.KANJI_1_18"), Messages.getString("NGram.KANJI_1_22"), Messages.getString("NGram.KANJI_1_27"), Messages.getString("NGram.KANJI_1_29"), Messages.getString("NGram.KANJI_1_31"), Messages.getString("NGram.KANJI_1_35"), Messages.getString("NGram.KANJI_2_0"), Messages.getString("NGram.KANJI_2_1"), Messages.getString("NGram.KANJI_2_4"), Messages.getString("NGram.KANJI_2_9"), Messages.getString("NGram.KANJI_2_10"), Messages.getString("NGram.KANJI_2_11"), Messages.getString("NGram.KANJI_2_12"), Messages.getString("NGram.KANJI_2_13"), Messages.getString("NGram.KANJI_2_15"), Messages.getString("NGram.KANJI_2_16"), Messages.getString("NGram.KANJI_2_18"), Messages.getString("NGram.KANJI_2_21"), Messages.getString("NGram.KANJI_2_22"), Messages.getString("NGram.KANJI_2_23"), Messages.getString("NGram.KANJI_2_28"), Messages.getString("NGram.KANJI_2_29"), Messages.getString("NGram.KANJI_2_30"), Messages.getString("NGram.KANJI_2_31"), Messages.getString("NGram.KANJI_2_32"), Messages.getString("NGram.KANJI_2_35"), Messages.getString("NGram.KANJI_2_36"), Messages.getString("NGram.KANJI_2_37"), Messages.getString("NGram.KANJI_2_38"), Messages.getString("NGram.KANJI_3_1"), Messages.getString("NGram.KANJI_3_2"), Messages.getString("NGram.KANJI_3_3"), Messages.getString("NGram.KANJI_3_4"), Messages.getString("NGram.KANJI_3_5"), Messages.getString("NGram.KANJI_3_8"), Messages.getString("NGram.KANJI_3_9"), Messages.getString("NGram.KANJI_3_11"), Messages.getString("NGram.KANJI_3_12"), Messages.getString("NGram.KANJI_3_13"), Messages.getString("NGram.KANJI_3_15"), Messages.getString("NGram.KANJI_3_16"), Messages.getString("NGram.KANJI_3_18"), Messages.getString("NGram.KANJI_3_19"), Messages.getString("NGram.KANJI_3_22"), Messages.getString("NGram.KANJI_3_23"), Messages.getString("NGram.KANJI_3_27"), Messages.getString("NGram.KANJI_3_29"), Messages.getString("NGram.KANJI_3_30"), Messages.getString("NGram.KANJI_3_31"), Messages.getString("NGram.KANJI_3_32"), Messages.getString("NGram.KANJI_3_35"), Messages.getString("NGram.KANJI_3_36"), Messages.getString("NGram.KANJI_3_37"), Messages.getString("NGram.KANJI_3_38"), Messages.getString("NGram.KANJI_4_0"), Messages.getString("NGram.KANJI_4_9"), Messages.getString("NGram.KANJI_4_10"), Messages.getString("NGram.KANJI_4_16"), Messages.getString("NGram.KANJI_4_17"), Messages.getString("NGram.KANJI_4_18"), Messages.getString("NGram.KANJI_4_22"), Messages.getString("NGram.KANJI_4_24"), Messages.getString("NGram.KANJI_4_28"), Messages.getString("NGram.KANJI_4_34"), Messages.getString("NGram.KANJI_4_39"), Messages.getString("NGram.KANJI_5_10"), Messages.getString("NGram.KANJI_5_11"), Messages.getString("NGram.KANJI_5_12"), Messages.getString("NGram.KANJI_5_13"), Messages.getString("NGram.KANJI_5_14"), Messages.getString("NGram.KANJI_5_18"), Messages.getString("NGram.KANJI_5_26"), Messages.getString("NGram.KANJI_5_29"), Messages.getString("NGram.KANJI_5_34"), Messages.getString("NGram.KANJI_5_39"), Messages.getString("NGram.KANJI_6_0"), Messages.getString("NGram.KANJI_6_3"), Messages.getString("NGram.KANJI_6_9"), Messages.getString("NGram.KANJI_6_10"), Messages.getString("NGram.KANJI_6_11"), Messages.getString("NGram.KANJI_6_12"), Messages.getString("NGram.KANJI_6_16"), Messages.getString("NGram.KANJI_6_18"), Messages.getString("NGram.KANJI_6_20"), Messages.getString("NGram.KANJI_6_21"), Messages.getString("NGram.KANJI_6_22"), Messages.getString("NGram.KANJI_6_23"), Messages.getString("NGram.KANJI_6_25"), Messages.getString("NGram.KANJI_6_28"), Messages.getString("NGram.KANJI_6_29"), Messages.getString("NGram.KANJI_6_30"), Messages.getString("NGram.KANJI_6_32"), Messages.getString("NGram.KANJI_6_34"), Messages.getString("NGram.KANJI_6_35"), Messages.getString("NGram.KANJI_6_37"), Messages.getString("NGram.KANJI_6_39"), Messages.getString("NGram.KANJI_7_0"), Messages.getString("NGram.KANJI_7_3"), Messages.getString("NGram.KANJI_7_6"), Messages.getString("NGram.KANJI_7_7"), Messages.getString("NGram.KANJI_7_9"), Messages.getString("NGram.KANJI_7_11"), Messages.getString("NGram.KANJI_7_12"), Messages.getString("NGram.KANJI_7_13"), Messages.getString("NGram.KANJI_7_16"), Messages.getString("NGram.KANJI_7_18"), Messages.getString("NGram.KANJI_7_19"), Messages.getString("NGram.KANJI_7_20"), Messages.getString("NGram.KANJI_7_21"), Messages.getString("NGram.KANJI_7_23"), Messages.getString("NGram.KANJI_7_25"), Messages.getString("NGram.KANJI_7_28"), Messages.getString("NGram.KANJI_7_29"), Messages.getString("NGram.KANJI_7_32"), Messages.getString("NGram.KANJI_7_33"), Messages.getString("NGram.KANJI_7_35"), Messages.getString("NGram.KANJI_7_37"), }; static { cjk_map = new HashMap<Character, Character>(); for (String cjk_list : CJK_CLASS) { char representative = cjk_list.charAt(0); for (int i=0;i<cjk_list.length();++i) { cjk_map.put(cjk_list.charAt(i), representative); } } } }
clajder/language-detect
src/main/java/com/cybozu/labs/langdetect/util/NGram.java
Java
mit
12,008
/* * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.nativecode; import static com.facebook.imagepipeline.transcoder.JpegTranscoderUtils.DEFAULT_JPEG_QUALITY; import static com.facebook.imagepipeline.transcoder.JpegTranscoderUtils.INVERTED_EXIF_ORIENTATIONS; import static com.facebook.imagepipeline.transcoder.JpegTranscoderUtils.MAX_QUALITY; import static com.facebook.imagepipeline.transcoder.JpegTranscoderUtils.MAX_SCALE_NUMERATOR; import static com.facebook.imagepipeline.transcoder.JpegTranscoderUtils.MIN_QUALITY; import static com.facebook.imagepipeline.transcoder.JpegTranscoderUtils.MIN_SCALE_NUMERATOR; import static com.facebook.imagepipeline.transcoder.JpegTranscoderUtils.SCALE_DENOMINATOR; import android.media.ExifInterface; import com.facebook.common.internal.Closeables; import com.facebook.common.internal.DoNotStrip; import com.facebook.common.internal.Preconditions; import com.facebook.common.internal.VisibleForTesting; import com.facebook.imageformat.ImageFormat; import com.facebook.imagepipeline.common.ResizeOptions; import com.facebook.imagepipeline.common.RotationOptions; import com.facebook.imagepipeline.image.EncodedImage; import com.facebook.imagepipeline.producers.DownsampleUtil; import com.facebook.imagepipeline.transcoder.ImageTranscodeResult; import com.facebook.imagepipeline.transcoder.ImageTranscoder; import com.facebook.imagepipeline.transcoder.JpegTranscoderUtils; import com.facebook.imagepipeline.transcoder.TranscodeStatus; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.annotation.Nullable; /** Transcoder for jpeg images, using native code and libjpeg-turbo library. */ @DoNotStrip public class NativeJpegTranscoder implements ImageTranscoder { public static final String TAG = "NativeJpegTranscoder"; private boolean mResizingEnabled; private int mMaxBitmapSize; private boolean mUseDownsamplingRatio; static { ImagePipelineNativeLoader.load(); } public NativeJpegTranscoder( final boolean resizingEnabled, final int maxBitmapSize, final boolean useDownsamplingRatio) { mResizingEnabled = resizingEnabled; mMaxBitmapSize = maxBitmapSize; mUseDownsamplingRatio = useDownsamplingRatio; } @Override public boolean canResize( EncodedImage encodedImage, @Nullable RotationOptions rotationOptions, @Nullable ResizeOptions resizeOptions) { if (rotationOptions == null) { rotationOptions = RotationOptions.autoRotate(); } return JpegTranscoderUtils.getSoftwareNumerator( rotationOptions, resizeOptions, encodedImage, mResizingEnabled) < JpegTranscoderUtils.SCALE_DENOMINATOR; } @Override public String getIdentifier() { return TAG; } @Override public ImageTranscodeResult transcode( final EncodedImage encodedImage, final OutputStream outputStream, @Nullable RotationOptions rotationOptions, @Nullable final ResizeOptions resizeOptions, @Nullable ImageFormat outputFormat, @Nullable Integer quality) throws IOException { if (quality == null) { quality = DEFAULT_JPEG_QUALITY; } if (rotationOptions == null) { rotationOptions = RotationOptions.autoRotate(); } final int downsampleRatio = DownsampleUtil.determineSampleSize( rotationOptions, resizeOptions, encodedImage, mMaxBitmapSize); InputStream is = null; try { final int softwareNumerator = JpegTranscoderUtils.getSoftwareNumerator( rotationOptions, resizeOptions, encodedImage, mResizingEnabled); final int downsampleNumerator = JpegTranscoderUtils.calculateDownsampleNumerator(downsampleRatio); final int numerator; if (mUseDownsamplingRatio) { numerator = downsampleNumerator; } else { numerator = softwareNumerator; } is = encodedImage.getInputStream(); if (INVERTED_EXIF_ORIENTATIONS.contains(encodedImage.getExifOrientation())) { // Use exif orientation to rotate since we can't use the rotation angle for // inverted exif orientations final int exifOrientation = JpegTranscoderUtils.getForceRotatedInvertedExifOrientation( rotationOptions, encodedImage); transcodeJpegWithExifOrientation(is, outputStream, exifOrientation, numerator, quality); } else { // Use actual rotation angle in degrees to rotate final int rotationAngle = JpegTranscoderUtils.getRotationAngle(rotationOptions, encodedImage); transcodeJpeg(is, outputStream, rotationAngle, numerator, quality); } } finally { Closeables.closeQuietly(is); } return new ImageTranscodeResult( downsampleRatio == DownsampleUtil.DEFAULT_SAMPLE_SIZE ? TranscodeStatus.TRANSCODING_NO_RESIZING : TranscodeStatus.TRANSCODING_SUCCESS); } /** * Transcodes an image to match the specified rotation angle and the scale factor. * * @param inputStream The {@link InputStream} of the image that will be transcoded. * @param outputStream The {@link OutputStream} where the newly created image is written to. * @param rotationAngle 0, 90, 180 or 270 * @param scaleNumerator 1 - 16, image will be scaled using scaleNumerator/8 factor * @param quality 1 - 100 */ @VisibleForTesting public static void transcodeJpeg( final InputStream inputStream, final OutputStream outputStream, final int rotationAngle, final int scaleNumerator, final int quality) throws IOException { Preconditions.checkArgument(scaleNumerator >= MIN_SCALE_NUMERATOR); Preconditions.checkArgument(scaleNumerator <= MAX_SCALE_NUMERATOR); Preconditions.checkArgument(quality >= MIN_QUALITY); Preconditions.checkArgument(quality <= MAX_QUALITY); Preconditions.checkArgument(JpegTranscoderUtils.isRotationAngleAllowed(rotationAngle)); Preconditions.checkArgument( scaleNumerator != SCALE_DENOMINATOR || rotationAngle != 0, "no transformation requested"); nativeTranscodeJpeg( Preconditions.checkNotNull(inputStream), Preconditions.checkNotNull(outputStream), rotationAngle, scaleNumerator, quality); } @DoNotStrip private static native void nativeTranscodeJpeg( InputStream inputStream, OutputStream outputStream, int rotationAngle, int scaleNominator, int quality) throws IOException; /** * Transcodes an image to match the specified exif orientation and the scale factor. * * @param inputStream The {@link InputStream} of the image that will be transcoded. * @param outputStream The {@link OutputStream} where the newly created image is written to. * @param exifOrientation 0, 90, 180 or 270 * @param scaleNumerator 1 - 16, image will be scaled using scaleNumerator/8 factor * @param quality 1 - 100 */ @VisibleForTesting public static void transcodeJpegWithExifOrientation( final InputStream inputStream, final OutputStream outputStream, final int exifOrientation, final int scaleNumerator, final int quality) throws IOException { Preconditions.checkArgument(scaleNumerator >= MIN_SCALE_NUMERATOR); Preconditions.checkArgument(scaleNumerator <= MAX_SCALE_NUMERATOR); Preconditions.checkArgument(quality >= MIN_QUALITY); Preconditions.checkArgument(quality <= MAX_QUALITY); Preconditions.checkArgument(JpegTranscoderUtils.isExifOrientationAllowed(exifOrientation)); Preconditions.checkArgument( scaleNumerator != SCALE_DENOMINATOR || exifOrientation != ExifInterface.ORIENTATION_NORMAL, "no transformation requested"); nativeTranscodeJpegWithExifOrientation( Preconditions.checkNotNull(inputStream), Preconditions.checkNotNull(outputStream), exifOrientation, scaleNumerator, quality); } @DoNotStrip private static native void nativeTranscodeJpegWithExifOrientation( InputStream inputStream, OutputStream outputStream, int exifOrientation, int scaleNominator, int quality) throws IOException; }
xjy2061/NovaImageLoader
imagepipeline/src/main/java/com/facebook/imagepipeline/nativecode/NativeJpegTranscoder.java
Java
mit
8,388
// This file is automatically generated. package adila.db; /* * Vivo Y31 * * DEVICE: PD1505 * MODEL: vivo Y31 */ final class pd1505_vivo20y31 { public static final String DATA = "Vivo|Y31|"; }
karim/adila
database/src/main/java/adila/db/pd1505_vivo20y31.java
Java
mit
204
package com.sabertazimi.tao.analysis.node; import java.io.PrintStream; import com.sabertazimi.tao.analysis.AnalysisNode; public abstract class LoopChunkNode extends AnalysisNode { public ExpressionNode condition; public boolean isWhile; public ChunkNode chunk; @Override public void print(int retractNum, PrintStream out) { if(isWhile) { out.print("while "); condition.print(retractNum, out); out.print(" do\n"); if(chunk != null) { chunk.print(retractNum + 1, out); } printRetract(retractNum, out); out.print("end"); } else { out.print("begin"); out.print("\n"); if(chunk != null) { chunk.print(retractNum + 1, out); } printRetract(retractNum, out); out.print("until "); condition.print(retractNum, out); } } }
sabertazimi/hust-lab
compilers/tao/src/main/java/com/sabertazimi/tao/analysis/node/LoopChunkNode.java
Java
mit
1,011
/* * The MIT License (MIT) * * Copyright (c) 2015 The MsgCodec Authors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.cinnober.msgcodec.examples; import com.cinnober.msgcodec.examples.messages.Carpenter; import com.cinnober.msgcodec.examples.messages.Hello; import com.cinnober.msgcodec.examples.messages.Numbers; import com.cinnober.msgcodec.examples.messages.Person; import com.cinnober.msgcodec.util.ObjectDispatcher; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.logging.Level; import java.util.logging.Logger; /** * Example that shows how message dispatching using the {@link ObjectDispatcher} can be done. * * @author mikael.brannstrom */ public class MessageDispatching { private static final Logger log = Logger.getLogger(MessageDispatching.class.getName()); private final ObjectDispatcher dispatcher; public MessageDispatching() { Collection<Object> delegates = Arrays.asList(new MyService(), new ErrorHandler()); dispatcher = new ObjectDispatcher(delegates, new Class<?>[]{MessageContext.class}); } /** * Typical parse message loop. */ public void parseLoop() { for (;;) { Object msg = readObject(); if (msg == null) { break; } MessageContext context = new MessageContext(); dispatchObject(msg, context); } } /** * Dispatch a message to the service method that should handle it. * * @param message the message to be dispatched, not null. * @param context the message context, capturing e.g. which channel it was received on etc. */ public void dispatchObject(Object message, MessageContext context) { try { dispatcher.dispatch(message, context); } catch (InvocationTargetException e) { log.log(Level.WARNING, "Service throwed an exception", e.getTargetException()); } catch (NoSuchMethodException e) { throw new Error("Bug", e); // the ErrorHandler should capture the "any" case } } public static void main(String... args) { MessageDispatching dispatcher = new MessageDispatching(); dispatcher.parseLoop(); } public static class MessageContext { } /** * Example service. */ public static class MyService { public void onPerson(Person person, MessageContext ctx) { System.out.format("%s is here!\n", person.name); } public void onHello(Hello hello, MessageContext ctx) { System.out.format("Someone says \"%s\"\n", hello.greeting); } } /** * Error handler service. */ public static class ErrorHandler { public void onUnhandled(Object message, MessageContext ctx) { System.out.format("Oh no! Unhandled message: %s\n", message); } } private final LinkedList<Object> messages = initMessages(); private static LinkedList<Object> initMessages() { LinkedList<Object> list = new LinkedList<>(); Person alice = new Person(); alice.name = "Alice"; list.add(alice); Hello hello = new Hello("I'm home!"); list.add(hello); Carpenter bob = new Carpenter(); bob.name = "Bob"; bob.tools = new String[] {"hammer", "screwdriver"}; list.add(bob); Numbers numbers = new Numbers(); numbers.bigIntReq = BigInteger.TEN.pow(30); numbers.signedReq = -1; numbers.unsignedReq = -1; // 2^32 - 1 numbers.decimal = BigDecimal.valueOf(123456, 3); // 123.456 list.add(numbers); return list; } public Object readObject() { if (messages.isEmpty()) { return null; } else { return messages.removeFirst(); } } }
cinnober/msgcodec
msgcodec-examples/src/main/java/com/cinnober/msgcodec/examples/MessageDispatching.java
Java
mit
5,050
/* * Pore * Copyright (c) 2014-2015, Lapis <https://github.com/LapisBlue> * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package blue.lapis.pore.impl.metadata; import org.apache.commons.lang.NotImplementedException; import org.bukkit.metadata.MetadataStore; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; import java.util.List; // TODO: Bridge // TODO: Bridge public class PoreMetadataStore<T> implements MetadataStore<T> { @Override public void setMetadata(T subject, String metadataKey, MetadataValue newMetadataValue) { } @Override public List<MetadataValue> getMetadata(T subject, String metadataKey) { throw new NotImplementedException(); } @Override public boolean hasMetadata(T subject, String metadataKey) { throw new NotImplementedException(); } @Override public void removeMetadata(T subject, String metadataKey, Plugin owningPlugin) { throw new NotImplementedException(); } @Override public void invalidateAll(Plugin owningPlugin) { throw new NotImplementedException(); } }
phase/Pore
src/main/java/blue/lapis/pore/impl/metadata/PoreMetadataStore.java
Java
mit
2,173
package modularmachines.common.energy; import net.minecraft.nbt.NBTTagCompound; import modularmachines.api.modules.energy.IKineticSource; public class KineticBuffer implements IKineticSource { protected double kineticEnergy; protected final double capacity; protected final double maxExtract; protected final double maxReceive; public KineticBuffer(double capacity, double maxTransfer) { this(capacity, maxTransfer, maxTransfer); } public KineticBuffer(double capacity, double maxReceive, double maxExtract) { this.capacity = capacity; this.maxReceive = maxReceive; this.maxExtract = maxExtract; } public NBTTagCompound writeToNBT(NBTTagCompound compound) { compound.setDouble("kineticEnergy", kineticEnergy); return compound; } public void readFromNBT(NBTTagCompound compound) { kineticEnergy = compound.getDouble("kineticEnergy"); } @Override public double extractKineticEnergy(double maxExtract, boolean simulate) { double energyExtracted = Math.min(kineticEnergy, Math.min(this.maxExtract, maxExtract)); if (!simulate) { kineticEnergy -= energyExtracted; } return energyExtracted; } @Override public double receiveKineticEnergy(double maxReceive, boolean simulate) { double energyReceived = Math.min(capacity - kineticEnergy, Math.min(this.maxReceive, maxReceive)); if (!simulate) { kineticEnergy += energyReceived; } return energyReceived; } @Override public void increaseKineticEnergy(double kineticModifier) { if (kineticEnergy == capacity) { return; } double step = 0.1D; double change = step + (((capacity - kineticEnergy) / capacity) * step * kineticModifier); kineticEnergy += change; kineticEnergy = Math.min(kineticEnergy, capacity); } @Override public void reduceKineticEnergy(double kineticModifier) { if (kineticEnergy == 0) { return; } double step = 0.01D; double change = step + ((kineticEnergy / capacity) * step * kineticModifier); kineticEnergy -= change; kineticEnergy = Math.max(kineticEnergy, 0); } @Override public double getCapacity() { return capacity; } @Override public double getStored() { return kineticEnergy; } }
Nedelosk/Modular-Machines
src/main/java/modularmachines/common/energy/KineticBuffer.java
Java
mit
2,171
package tk.mybatis.mapper.common; /** * 标记接口,继承该接口的接口,在MapperScannerConfigurer#setMarkerInterface时,会自动注册到通用Mapper * * @author liuzh * @since 3.2.2 */ public interface Marker { }
forestqqqq/Mapper
src/main/java/tk/mybatis/mapper/common/Marker.java
Java
mit
235
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class InverseBWT { class FastScanner { StringTokenizer tok = new StringTokenizer(""); BufferedReader in; FastScanner() { in = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (!tok.hasMoreElements()) tok = new StringTokenizer(in.readLine()); return tok.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } } String inverseBWT(String bwt) { StringBuilder result = new StringBuilder(); // write your code here return result.toString(); } static public void main(String[] args) throws IOException { new InverseBWT().run(); } public void run() throws IOException { FastScanner scanner = new FastScanner(); String bwt = scanner.next(); System.out.println(inverseBWT(bwt)); } }
manparvesh/coursera-ds-algorithms
4. String Algorithms/Programming-Assignment-2/bwtinverse/InverseBWT.java
Java
mit
1,140
package com.s0lder.droplets; import org.bukkit.Server; public abstract class Droplet { public void onEnable() {}; public void onDisable() {}; public abstract String getName(); protected DropletsPlugin getPlugin() { return DropletsPlugin.instance; } protected Server getServer() { return DropletsPlugin.instance.getServer(); } protected DropletManager getDropletManager() { return DropletsPlugin.instance.getDropletManager(); } }
s0lder/Droplets
src/com/s0lder/droplets/Droplet.java
Java
mit
519
package org.schors.lopds.json; public class CheckStatusRes extends Response { private String status; public CheckStatusRes() { } public CheckStatusRes(String status) { this.status = status; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return "CheckStatusRes{" + "status='" + status + '\'' + '}'; } }
flicus/lopds
src/org/schors/lopds/json/CheckStatusRes.java
Java
mit
521
package br.com.xunfos.persistence; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; /**** * * Simple persistence class to access the local postgre instance. * * @author Renato */ public class DatabasePersistence { private static final EntityManagerFactory emFactory = buildFactory(); /****** * Builds the entitymanagerfactory. It's a quite simple implementation, and * it should be tweaked if needed. * * The db connection string is located in the persistence.xml, and the * database script is in the project root. * * @return the emFactory * @throws ExceptionInInitializerError */ private static EntityManagerFactory buildFactory() throws ExceptionInInitializerError { try { return Persistence.createEntityManagerFactory("POSTGRE_SQL"); } catch (Exception ex) { System.err.println("Error initializing the entity manager factory"); throw new ExceptionInInitializerError(ex); } } /**** * private getter for the emFactory * * @return */ public static EntityManagerFactory getEmFactory() { return emFactory; } }
renatomrcosta/VaadSale
vaadsale/src/main/java/br/com/xunfos/persistence/DatabasePersistence.java
Java
mit
1,111
package io.miti.codeman.util; import java.awt.Component; import javax.swing.DefaultListCellRenderer; import javax.swing.JLabel; import javax.swing.JList; import java.awt.Color; public final class StripeRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = 1L; private static final Color colorEvenRows = new Color(230, 230, 255); private static final Color colorOddRows = new Color(255, 255, 255); private static final Color colorSelected = new Color(0, 204, 102); public StripeRenderer() { super(); } @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); // Check the conditions before setting the label's background color if (isSelected) { // The row is selected label.setBackground(colorSelected); } else if (index % 2 == 0) { // This is an even-numbered row label.setBackground(colorEvenRows); } else { // This is an odd-numbered row label.setBackground(colorOddRows); } return label; } }
argonium/codeman
src/io/miti/codeman/util/StripeRenderer.java
Java
mit
1,375
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.07.27 at 08:11:57 PM EEST // package uk.org.ifopt.ifopt; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.datatype.XMLGregorianCalendar; /** * Type for a versioned reference to an administrative area. * * <p>Java class for AdministrativeAreaVersionedRefStructure complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="AdministrativeAreaVersionedRefStructure"> * &lt;simpleContent> * &lt;extension base="&lt;http://www.ifopt.org.uk/ifopt>AdministrativeAreaCodeType"> * &lt;attGroup ref="{http://www.ifopt.org.uk/ifopt}ModificationDetailsGroup"/> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AdministrativeAreaVersionedRefStructure", propOrder = { "value" }) public class AdministrativeAreaVersionedRefStructure { @XmlValue @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String value; @XmlAttribute(name = "created") @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar created; @XmlAttribute(name = "lastUpdated") @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar lastUpdated; @XmlAttribute(name = "modification") protected ModificationEnumeration modification; @XmlAttribute(name = "version") protected BigInteger version; @XmlAttribute(name = "status") protected StatusEnumeration status; /** * Type for Unique Identifier of Administrative Area. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } /** * Gets the value of the created property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getCreated() { return created; } /** * Sets the value of the created property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setCreated(XMLGregorianCalendar value) { this.created = value; } /** * Gets the value of the lastUpdated property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getLastUpdated() { return lastUpdated; } /** * Sets the value of the lastUpdated property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setLastUpdated(XMLGregorianCalendar value) { this.lastUpdated = value; } /** * Gets the value of the modification property. * * @return * possible object is * {@link ModificationEnumeration } * */ public ModificationEnumeration getModification() { if (modification == null) { return ModificationEnumeration.NEW; } else { return modification; } } /** * Sets the value of the modification property. * * @param value * allowed object is * {@link ModificationEnumeration } * */ public void setModification(ModificationEnumeration value) { this.modification = value; } /** * Gets the value of the version property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getVersion() { return version; } /** * Sets the value of the version property. * * @param value * allowed object is * {@link BigInteger } * */ public void setVersion(BigInteger value) { this.version = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link StatusEnumeration } * */ public StatusEnumeration getStatus() { if (status == null) { return StatusEnumeration.ACTIVE; } else { return status; } } /** * Sets the value of the status property. * * @param value * allowed object is * {@link StatusEnumeration } * */ public void setStatus(StatusEnumeration value) { this.status = value; } }
ITSFactory/itsfactory.siri.bindings.v13
src/main/java/uk/org/ifopt/ifopt/AdministrativeAreaVersionedRefStructure.java
Java
mit
5,501
/* * The MIT License (MIT) * * Copyright (c) 2013 Milad Naseri. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mmnaseri.couteau.reflection.convert; /** * This enum abstracts a decision at conversion time. * * @author Milad Naseri ([email protected]) * @since 1.0 (7/13/13, 7:32 AM) */ public enum ConversionDecision { /** * This means that the item being contemplated should be passed to the target object * as-is, without any conversion */ PASS, /** * This means that the item being contemplated should be dropped and not included in the * target object */ IGNORE, /** * This means that a deep conversion should be queued for the given object */ CONVERT }
agileapes/couteau
couteau-reflection/src/main/java/com/mmnaseri/couteau/reflection/convert/ConversionDecision.java
Java
mit
1,781
package de.ronnyfriedland.knowledgebase.resource; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.apache.commons.collections.KeyValue; import org.apache.commons.lang.builder.ToStringBuilder; /** * @author ronnyfriedland */ @XmlRootElement(name = "repository") public class RepositoryMetadata implements Serializable { /** the serialVersionUID */ private static final long serialVersionUID = 3898017953412626058L; @XmlElement private String id; @XmlElement private Collection<RepositoryMetadata> children = new HashSet<RepositoryMetadata>(); @XmlElement(name = "text") private String name; @XmlElement private Collection<MetadataKeyValue> metadata = new HashSet<>(); public void setId(final String id) { this.id = id; } public void setName(final String name) { this.name = name; } public void setChildren(final Collection<RepositoryMetadata> children) { this.children = children; } public void addChildren(final RepositoryMetadata children) { this.children.add(children); } public void setMetadata(final Collection<MetadataKeyValue> metadata) { this.metadata = metadata; } public void addMetadata(final MetadataKeyValue value) { this.metadata.add(value); } /** * {@inheritDoc} */ @Override public String toString() { return ToStringBuilder.reflectionToString(this); } public static class MetadataKeyValue implements KeyValue { @XmlElement private String key; @XmlElement private String value; public MetadataKeyValue() { } public MetadataKeyValue(final String key, final String value) { this.key = key; this.value = value; } public void setKey(final String key) { this.key = key; } @Override public Object getKey() { return key; } public void setValue(final String value) { this.value = value; } @Override public Object getValue() { return value; } } }
ronnyfriedland/Knowledgebase-2.0
src/main/java/de/ronnyfriedland/knowledgebase/resource/RepositoryMetadata.java
Java
mit
2,314
package breadth_first_search; import public_class.TreeNode; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class Q297SerializeAndDeserializeBinaryTree { //TAG: Google //TAG: Facebook //TAG: Microsoft //TAG: Amazon //TAG: Uber //TAG: LinkedIn //TAG: Breadth first search //Difficulty: Hard /** * 297. Serialize and Deserialize Binary Tree * Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. For example, you may serialize the following tree 1 / \ 2 3 / \ 4 5 as "[1,2,3,null,null,4,5]", just the same as how legacy_code OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless. Credits: Special thanks to @Louis1992 for adding this problem and creating all test cases. */ /** Use Breadth first search for Serialize and Deserialize */ public class Codec { private Queue<TreeNode> queue; private List<String> list; public Codec() { queue = new LinkedList<>(); list = new ArrayList<>(); } // Encodes a tree to a single string. public String serialize(TreeNode root) { if (root == null) return ""; queue.add(root); list.add(String.valueOf(root.val)); while (!queue.isEmpty()) { TreeNode poll = queue.poll(); if (poll.left != null) { queue.offer(poll.left); list.add(String.valueOf(poll.left.val)); } else list.add("null"); if (poll.right != null) { queue.offer(poll.right); list.add(String.valueOf(poll.right.val)); } else list.add("null"); } StringBuilder builder = new StringBuilder(); for (String str: list) { builder.append(str); builder.append(","); } builder.deleteCharAt(builder.length() - 1); return builder.toString(); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if (data.length() == 0) return null; String[] strs = data.split(","); TreeNode root = new TreeNode(Integer.parseInt(strs[0])); TreeNode res = root; int index = 1; queue.offer(root); while (!queue.isEmpty()) { TreeNode poll = queue.poll(); if (!strs[index].equals("null")) { poll.left = new TreeNode(Integer.parseInt(strs[index])); queue.offer(poll.left); } index++; if (!strs[index].equals("null")) { poll.right = new TreeNode(Integer.parseInt(strs[index])); queue.offer(poll.right); } index++; } return res; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.deserialize(codec.serialize(root)); }
StevenUpForever/LeetCode_Java
src/breadth_first_search/Q297SerializeAndDeserializeBinaryTree.java
Java
mit
3,945
package cn.berserker.model; import cn.berserker.utils.MD5; public class UserInfo { //device's unique id. String uuid = ""; // user unique id. String uid = ""; // user register type int regType = -1; // user name. String userName = ""; // user's password String passWord = ""; // who could link to him. String linkId = ""; // user's mobile. String mobile = ""; // user's nickname. String nickName = ""; // user's current token id. String tokenId = ""; // check whether is vistor mode. boolean isVisitor = false; public UserInfo(DeviceInfo device) { this.uuid = setUuid(device); } public String getUuid() { return this.uuid; } public String getUid() { return this.uid; } public int getRegType() { return this.regType; } public String getUserName() { return this.userName; } public String getPassWord() { return this.passWord; } public String getLinkId() { return this.linkId; } public String getMobile() { return this.mobile; } public String getNickName() { return this.nickName; } public String getTokenId() { return this.tokenId; } public boolean isVisitor() { return this.isVisitor; } public void setUid(String Uid) { uid = Uid; } public void setUserName(String UserName) { userName = UserName; } public void setPassWord(String PassWord) { passWord = PassWord; } public void setLinkId(String LinkId) { linkId = LinkId; } public void setMobile(String Mobile) { mobile = Mobile; } public void setRegType(int RegType) { regType = RegType; } public void setNickName(String Name) { nickName = Name; } public void setTokenId(String Token) { tokenId = Token; } public void setVisitor(boolean visitor) { isVisitor = visitor; } //we use wifimac, cpuid, imei, fix string to make uuid. private String setUuid(DeviceInfo device) { StringBuilder sb = new StringBuilder(); sb.append(device.getWifiMac()); sb.append("&" + device.getCpuId()); sb.append("&" + device.getImei()); sb.append("&" + "vilota"); return MD5.getMD5(sb.toString()); } // this should not public to others. public String toString() { StringBuilder sb = new StringBuilder(); sb.append(uuid +"\t&uid:"); sb.append(uid+"\t&regType:"); sb.append(regType+"\t&userName:"); sb.append(userName+"\t&passWord:"); sb.append(passWord+"\t&linkId:"); sb.append(linkId+"\t&mobile:"); sb.append(mobile+"\t&nickName:"); sb.append(nickName+"\t&tokenId:"); sb.append(tokenId); return sb.toString(); } public static class RegisterType { public static final int NO_REG = 1; public static final int SELF_REG = 2; public static final int OTH_REG = 3; } }
michael-destiny/PaymentPlatform
PaymentPlatform/src/cn/berserker/model/UserInfo.java
Java
mit
2,594
package ch.sama.sql.query.helper; import ch.sama.sql.query.base.IQueryRenderer; import ch.sama.sql.query.base.check.Identifier; import ch.sama.sql.query.exception.IllegalIdentifierException; public class Value { private Object source; private String value; private String alias; public Value(String value) { this.source = value; this.value = value; } public Value(Object o, String value) { this.source = o; this.value = value; } public String getValue() { return value; } public String getString(IQueryRenderer renderer) { return renderer.render(this); } public String getAlias() { return alias; } public Object getSource() { return source; } public Value as(String alias) { if (alias == null) { return this; } if (!Identifier.test(alias)) { throw new IllegalIdentifierException(alias); } Value clone = new Value(source, value); clone.alias = alias; return clone; } }
Phyrra/javasql
src/main/java/ch/sama/sql/query/helper/Value.java
Java
mit
1,151
package ServiceTests; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.env.Environment; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import shop.main.config.AppContextConfig; import shop.main.data.entity.Product; import shop.main.data.entity.Review; import shop.main.data.service.ProductService; import shop.main.data.service.ReviewService; import shop.main.utils.sqltracker.AssertSqlCount; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { AppContextConfig.class }) @WebAppConfiguration @Sql({ "classpath:delete_test_data.sql", "classpath:categories.sql", "classpath:options.sql", "classpath:products.sql" }) public class TestProductService { private final String PRODUCT_NAME = "DRACULAURA"; private final String PRODUCT_SKU = "PI90870"; private final String PRODUCT_URL = "draculaura"; private final String PRODUCT_SEARCH_NAME = "drac"; private final String PRODUCT_SEARCH_URL = "drac"; private final String DUMMY_STRING = "DUMMY_STRING"; private final BigDecimal DUMMY_NUMBER = new BigDecimal(99.99); private final Integer CURRENT = 0; private final Integer PAGE_SIZE = 10; private Pageable pageable; private final List<Long> filterIds = Arrays.asList(new Long[] { 1L, 2L }), listOfCategories = Arrays.asList(new Long[] { 5L, 6L }); private static final Logger LOGGER = LoggerFactory.getLogger(TestProductService.class); @Autowired private Environment environment; @Autowired @Qualifier("productService") private ProductService productService; @Autowired @Qualifier("reviewService") private ReviewService reviewService; @Before public void before() { AssertSqlCount.reset(); pageable = new PageRequest(CURRENT, PAGE_SIZE); } @Test public void findPageableQueryCount() { LOGGER.info("***"); LOGGER.info("*" + environment.getProperty("totest")); List<Product> products = productService.findPageable(PRODUCT_SEARCH_NAME, PRODUCT_SEARCH_URL, "", pageable); AssertSqlCount.assertSelectCount(1); } @Test public void findPageableValidateResult() { List<Product> products = productService.findPageable(PRODUCT_SEARCH_NAME, PRODUCT_SEARCH_URL, "", pageable); AssertSqlCount.assertSelectCount(1); Assert.assertEquals(products.get(0).getName(), PRODUCT_NAME); Assert.assertEquals(products.get(0).getUrl(), PRODUCT_URL); Assert.assertEquals(1, products.size()); } @Test public void countPageable() { long result = productService.countPageable(PRODUCT_SEARCH_NAME, PRODUCT_SEARCH_URL, ""); AssertSqlCount.assertSelectCount(1); Assert.assertEquals(1, result); } @Test public void saveProduct() { Product p = new Product(); p.setSku(DUMMY_STRING); p.setUrl(DUMMY_STRING); p.setCategory(null); p.setName(DUMMY_STRING); p.setPrice(DUMMY_NUMBER); productService.saveProduct(p); Product saved = productService.findProductBySKU(DUMMY_STRING); Assert.assertEquals(DUMMY_STRING, saved.getUrl()); } @Test public void deleteProduct() { Product saved = productService.findProductById(1); productService.deleteProduct(saved); Product found = productService.findProductById(1); Assert.assertNull(found); } @Test public void deleteProductById() { productService.deleteProductById(1); Product found = productService.findProductById(1); Assert.assertNull(found); } @Test public void findProductById() { Product found = productService.findProductById(1); Assert.assertEquals(new Long(1), found.getId()); } @Test public void findProductByUrl() { Product p = new Product(); p.setSku(DUMMY_STRING); p.setUrl(DUMMY_STRING); p.setCategory(null); p.setName(DUMMY_STRING); p.setPrice(DUMMY_NUMBER); productService.saveProduct(p); Product saved = productService.findProductByUrl(DUMMY_STRING); Assert.assertEquals(DUMMY_STRING, saved.getSku()); } @Test public void findProductBySKU() { Product p = new Product(); p.setSku(DUMMY_STRING); p.setUrl(DUMMY_STRING); p.setCategory(null); p.setName(DUMMY_STRING); p.setPrice(DUMMY_NUMBER); productService.saveProduct(p); Product saved = productService.findProductBySKU(DUMMY_STRING); Assert.assertEquals(DUMMY_STRING, saved.getUrl()); } @Test public void checkUniqueURL() { Product p = new Product(); p.setUrl(PRODUCT_URL); boolean unique = productService.checkUniqueURL(p); Assert.assertFalse(unique); } @Test public void checkUniqueSKU() { Product p = new Product(); p.setSku(PRODUCT_SKU); boolean unique = productService.checkUniqueSKU(p); Assert.assertFalse(unique); } @Test public void findAllFeatured() { List<Product> products = productService.findAllFeatured(); Assert.assertEquals(3, products.size());// according to sql in test // start } @Test public void countFilteredProductsInCategory() { long result = productService.countFilteredProductsInCategory(filterIds, listOfCategories); AssertSqlCount.assertSelectCount(1); Assert.assertEquals(2, result); } @Test public void findFilteredProductsInCategoryQueryCount() { List<Product> products = productService.findFilteredProductsInCategory(filterIds, listOfCategories, pageable); // query count, and if not null query data AssertSqlCount.assertSelectCount(1); } @Test public void findFilteredProductsInCategoryValidateResult() { List<Product> products = productService.findFilteredProductsInCategory(filterIds, listOfCategories, pageable); Assert.assertEquals(2, products.size()); } @Test public void updateRating() { LOGGER.info("updateRating"); Long productId = 1L; Product product = productService.findProductById(productId); Review r = new Review(DUMMY_STRING, DUMMY_STRING, DUMMY_STRING, 5, product); reviewService.save(r); productService.updateRating(productId); long rating = productService.findProductById(productId).getRating(); Assert.assertEquals(5, rating); } }
spacerovka/jShop
src/test/java/ServiceTests/TestProductService.java
Java
mit
6,487
/* * 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. */ /* * $Id: RealType.java 468649 2006-10-28 07:00:55Z minchau $ */ package org.apache.xalan.xsltc.compiler.util; import org.apache.bcel.generic.BranchHandle; import org.apache.bcel.generic.CHECKCAST; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.DLOAD; import org.apache.bcel.generic.DSTORE; import org.apache.bcel.generic.GOTO; import org.apache.bcel.generic.IFEQ; import org.apache.bcel.generic.IFNE; import org.apache.bcel.generic.INVOKESPECIAL; import org.apache.bcel.generic.INVOKESTATIC; import org.apache.bcel.generic.INVOKEVIRTUAL; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InstructionConstants; import org.apache.bcel.generic.InstructionList; import org.apache.bcel.generic.LocalVariableGen; import org.apache.bcel.generic.NEW; import org.apache.xalan.xsltc.compiler.Constants; import org.apache.xalan.xsltc.compiler.FlowList; /** * @author Jacek Ambroziak * @author Santiago Pericas-Geertsen */ public final class RealType extends NumberType { protected RealType() {} public String toString() { return "real"; } public boolean identicalTo(Type other) { return this == other; } public String toSignature() { return "D"; } public org.apache.bcel.generic.Type toJCType() { return org.apache.bcel.generic.Type.DOUBLE; } /** * @see org.apache.xalan.xsltc.compiler.util.Type#distanceTo */ public int distanceTo(Type type) { if (type == this) { return 0; } else if (type == Type.Int) { return 1; } else { return Integer.MAX_VALUE; } } /** * Translates a real into an object of internal type <code>type</code>. The * translation to int is undefined since reals are never converted to ints. * * @see org.apache.xalan.xsltc.compiler.util.Type#translateTo */ public void translateTo(ClassGenerator classGen, MethodGenerator methodGen, Type type) { if (type == Type.String) { translateTo(classGen, methodGen, (StringType) type); } else if (type == Type.Boolean) { translateTo(classGen, methodGen, (BooleanType) type); } else if (type == Type.Reference) { translateTo(classGen, methodGen, (ReferenceType) type); } else if (type == Type.Int) { translateTo(classGen, methodGen, (IntType) type); } else { ErrorMsg err = new ErrorMsg(ErrorMsg.DATA_CONVERSION_ERR, toString(), type.toString()); classGen.getParser().reportError(Constants.FATAL, err); } } /** * Expects a real on the stack and pushes its string value by calling * <code>Double.toString(double d)</code>. * * @see org.apache.xalan.xsltc.compiler.util.Type#translateTo */ public void translateTo(ClassGenerator classGen, MethodGenerator methodGen, StringType type) { final ConstantPoolGen cpg = classGen.getConstantPool(); final InstructionList il = methodGen.getInstructionList(); il.append(new INVOKESTATIC(cpg.addMethodref(BASIS_LIBRARY_CLASS, "realToString", "(D)" + STRING_SIG))); } /** * Expects a real on the stack and pushes a 0 if that number is 0.0 and * a 1 otherwise. * * @see org.apache.xalan.xsltc.compiler.util.Type#translateTo */ public void translateTo(ClassGenerator classGen, MethodGenerator methodGen, BooleanType type) { final InstructionList il = methodGen.getInstructionList(); FlowList falsel = translateToDesynthesized(classGen, methodGen, type); il.append(ICONST_1); final BranchHandle truec = il.append(new GOTO(null)); falsel.backPatch(il.append(ICONST_0)); truec.setTarget(il.append(NOP)); } /** * Expects a real on the stack and pushes a truncated integer value * * @see org.apache.xalan.xsltc.compiler.util.Type#translateTo */ public void translateTo(ClassGenerator classGen, MethodGenerator methodGen, IntType type) { final ConstantPoolGen cpg = classGen.getConstantPool(); final InstructionList il = methodGen.getInstructionList(); il.append(new INVOKESTATIC(cpg.addMethodref(BASIS_LIBRARY_CLASS, "realToInt","(D)I"))); } /** * Translates a real into a non-synthesized boolean. It does not push a * 0 or a 1 but instead returns branchhandle list to be appended to the * false list. A NaN must be converted to "false". * * @see org.apache.xalan.xsltc.compiler.util.Type#translateToDesynthesized */ public FlowList translateToDesynthesized(ClassGenerator classGen, MethodGenerator methodGen, BooleanType type) { LocalVariableGen local; final FlowList flowlist = new FlowList(); final ConstantPoolGen cpg = classGen.getConstantPool(); final InstructionList il = methodGen.getInstructionList(); // Store real into a local variable il.append(DUP2); local = methodGen.addLocalVariable("real_to_boolean_tmp", org.apache.bcel.generic.Type.DOUBLE, null, null); local.setStart(il.append(new DSTORE(local.getIndex()))); // Compare it to 0.0 il.append(DCONST_0); il.append(DCMPG); flowlist.add(il.append(new IFEQ(null))); //!!! call isNaN // Compare it to itself to see if NaN il.append(new DLOAD(local.getIndex())); local.setEnd(il.append(new DLOAD(local.getIndex()))); il.append(DCMPG); flowlist.add(il.append(new IFNE(null))); // NaN != NaN return flowlist; } /** * Expects a double on the stack and pushes a boxed double. Boxed * double are represented by an instance of <code>java.lang.Double</code>. * * @see org.apache.xalan.xsltc.compiler.util.Type#translateTo */ public void translateTo(ClassGenerator classGen, MethodGenerator methodGen, ReferenceType type) { final ConstantPoolGen cpg = classGen.getConstantPool(); final InstructionList il = methodGen.getInstructionList(); il.append(new NEW(cpg.addClass(DOUBLE_CLASS))); il.append(DUP_X2); il.append(DUP_X2); il.append(POP); il.append(new INVOKESPECIAL(cpg.addMethodref(DOUBLE_CLASS, "<init>", "(D)V"))); } /** * Translates a real into the Java type denoted by <code>clazz</code>. * Expects a real on the stack and pushes a number of the appropriate * type after coercion. */ public void translateTo(ClassGenerator classGen, MethodGenerator methodGen, final Class clazz) { final InstructionList il = methodGen.getInstructionList(); if (clazz == Character.TYPE) { il.append(D2I); il.append(I2C); } else if (clazz == Byte.TYPE) { il.append(D2I); il.append(I2B); } else if (clazz == Short.TYPE) { il.append(D2I); il.append(I2S); } else if (clazz == Integer.TYPE) { il.append(D2I); } else if (clazz == Long.TYPE) { il.append(D2L); } else if (clazz == Float.TYPE) { il.append(D2F); } else if (clazz == Double.TYPE) { il.append(NOP); } // Is Double <: clazz? I.e. clazz in { Double, Number, Object } else if (clazz.isAssignableFrom(java.lang.Double.class)) { translateTo(classGen, methodGen, Type.Reference); } else { ErrorMsg err = new ErrorMsg(ErrorMsg.DATA_CONVERSION_ERR, toString(), clazz.getName()); classGen.getParser().reportError(Constants.FATAL, err); } } /** * Translates an external (primitive) Java type into a real. Expects a java * object on the stack and pushes a real (i.e., a double). */ public void translateFrom(ClassGenerator classGen, MethodGenerator methodGen, Class clazz) { InstructionList il = methodGen.getInstructionList(); if (clazz == Character.TYPE || clazz == Byte.TYPE || clazz == Short.TYPE || clazz == Integer.TYPE) { il.append(I2D); } else if (clazz == Long.TYPE) { il.append(L2D); } else if (clazz == Float.TYPE) { il.append(F2D); } else if (clazz == Double.TYPE) { il.append(NOP); } else { ErrorMsg err = new ErrorMsg(ErrorMsg.DATA_CONVERSION_ERR, toString(), clazz.getName()); classGen.getParser().reportError(Constants.FATAL, err); } } /** * Translates an object of this type to its boxed representation. */ public void translateBox(ClassGenerator classGen, MethodGenerator methodGen) { translateTo(classGen, methodGen, Type.Reference); } /** * Translates an object of this type to its unboxed representation. */ public void translateUnBox(ClassGenerator classGen, MethodGenerator methodGen) { final ConstantPoolGen cpg = classGen.getConstantPool(); final InstructionList il = methodGen.getInstructionList(); il.append(new CHECKCAST(cpg.addClass(DOUBLE_CLASS))); il.append(new INVOKEVIRTUAL(cpg.addMethodref(DOUBLE_CLASS, DOUBLE_VALUE, DOUBLE_VALUE_SIG))); } public Instruction ADD() { return InstructionConstants.DADD; } public Instruction SUB() { return InstructionConstants.DSUB; } public Instruction MUL() { return InstructionConstants.DMUL; } public Instruction DIV() { return InstructionConstants.DDIV; } public Instruction REM() { return InstructionConstants.DREM; } public Instruction NEG() { return InstructionConstants.DNEG; } public Instruction LOAD(int slot) { return new DLOAD(slot); } public Instruction STORE(int slot) { return new DSTORE(slot); } public Instruction POP() { return POP2; } public Instruction CMP(boolean less) { return less ? InstructionConstants.DCMPG : InstructionConstants.DCMPL; } public Instruction DUP() { return DUP2; } }
kcsl/immutability-benchmark
benchmark-applications/reiminfer-oopsla-2012/source/Xalan/src/org/apache/xalan/xsltc/compiler/util/RealType.java
Java
mit
10,738
package hu.bme.mit.inf.gs.workflow.genius.helpers; import java.io.BufferedReader; import java.io.StringReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(namespace="http://schemas.datacontract.org/2004/07/AppRepository", name="ApplicationVersionBoundaryEntity") public class ApplicationVersionBoundaryEntity { private Integer acceptanceResult; private Integer applicationVersionID; private String timestamp; private String versionString; @XmlElement(namespace="http://schemas.datacontract.org/2004/07/AppRepository") public Integer getAcceptanceResult() { return acceptanceResult; } public void setAcceptanceResult(Integer acceptanceResult) { this.acceptanceResult = acceptanceResult; } @XmlElement(namespace="http://schemas.datacontract.org/2004/07/AppRepository") public Integer getApplicationVersionID() { return applicationVersionID; } public void setApplicationVersionID(Integer applicationVersionID) { this.applicationVersionID = applicationVersionID; } @XmlElement(namespace="http://schemas.datacontract.org/2004/07/AppRepository") public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } @XmlElement(namespace="http://schemas.datacontract.org/2004/07/AppRepository") public String getVersionString() { return versionString; } public void setVersionString(String versionString) { this.versionString = versionString; } public static ApplicationVersionBoundaryEntity readFromXML(String xml) throws JAXBException { JAXBContext context = JAXBContext.newInstance(ApplicationVersionBoundaryEntity.class); Unmarshaller un = context.createUnmarshaller(); return (ApplicationVersionBoundaryEntity)un.unmarshal(new BufferedReader(new StringReader(xml))); } }
darvasd/gsoaarchitect
hu.bme.mit.inf.gs.workflow.model/src/main/java/hu/bme/mit/inf/gs/workflow/genius/helpers/ApplicationVersionBoundaryEntity.java
Java
mit
2,018
/** */ package simple; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; /** * <!-- begin-user-doc --> * The <b>Package</b> for the model. * It contains accessors for the meta objects to represent * <ul> * <li>each class,</li> * <li>each feature of each class,</li> * <li>each operation of each class,</li> * <li>each enum,</li> * <li>and each data type</li> * </ul> * <!-- end-user-doc --> * @see simple.SimpleFactory * @model kind="package" * @generated */ public interface SimplePackage extends EPackage { /** * The package name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String eNAME = "simple"; /** * The package namespace URI. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String eNS_URI = "http://DynEMF/simple/1.0"; /** * The package namespace name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String eNS_PREFIX = ""; /** * The singleton instance of the package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ SimplePackage eINSTANCE = simple.impl.SimplePackageImpl.init(); /** * The meta object id for the '{@link simple.impl.AImpl <em>A</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see simple.impl.AImpl * @see simple.impl.SimplePackageImpl#getA() * @generated */ int A = 0; /** * The feature id for the '<em><b>A</b></em>' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int A__A = 0; /** * The feature id for the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int A__NAME = 1; /** * The number of structural features of the '<em>A</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int A_FEATURE_COUNT = 2; /** * The number of operations of the '<em>A</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int A_OPERATION_COUNT = 0; /** * Returns the meta object for class '{@link simple.A <em>A</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>A</em>'. * @see simple.A * @generated */ EClass getA(); /** * Returns the meta object for the containment reference list '{@link simple.A#getA <em>A</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference list '<em>A</em>'. * @see simple.A#getA() * @see #getA() * @generated */ EReference getA_A(); /** * Returns the meta object for the attribute '{@link simple.A#getName <em>Name</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Name</em>'. * @see simple.A#getName() * @see #getA() * @generated */ EAttribute getA_Name(); /** * Returns the factory that creates the instances of the model. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the factory that creates the instances of the model. * @generated */ SimpleFactory getSimpleFactory(); /** * <!-- begin-user-doc --> * Defines literals for the meta objects that represent * <ul> * <li>each class,</li> * <li>each feature of each class,</li> * <li>each operation of each class,</li> * <li>each enum,</li> * <li>and each data type</li> * </ul> * <!-- end-user-doc --> * @generated */ interface Literals { /** * The meta object literal for the '{@link simple.impl.AImpl <em>A</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see simple.impl.AImpl * @see simple.impl.SimplePackageImpl#getA() * @generated */ EClass A = eINSTANCE.getA(); /** * The meta object literal for the '<em><b>A</b></em>' containment reference list feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference A__A = eINSTANCE.getA_A(); /** * The meta object literal for the '<em><b>Name</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute A__NAME = eINSTANCE.getA_Name(); } } //SimplePackage
aranega/dynemf
src/test/java/simple/SimplePackage.java
Java
mit
4,391
package utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /** * Reads from an input stream * For use ONLY on streams which are guaranteed to be small in size relative to available ram * * @author Jason Harrison * @version v1.00 05/04/2014 */ public class IO { public IO() { //static functions - no constructor needed } /** * Reads a stream into a byte array * @param stream * @return byte[] from the InputStream stream * @throws IOException */ public static byte[] ReadStreamToByteArray(InputStream stream) throws IOException { ByteArrayOutputStream bo = new ByteArrayOutputStream(); int i; // 4096 is a typical NTFS cluster size to read less than this would just be a waste of processor cycles and/or HDD access // and 4096 not so big as to waste a large chunk of ram byte[] byteBuffer = new byte[4096]; while ((i = stream.read(byteBuffer)) != -1) { bo.write(byteBuffer, 0, i); } bo.flush(); return bo.toByteArray(); } /** * Reads a stream to a UTF-8 string * @param stream * @return String from the InputStream stream in UTF-8 * @throws IOException */ public static String ReadStreamToString(InputStream stream) throws IOException { return new String(ReadStreamToByteArray(stream), "UTF-8"); } /** * Reads a stream to a UTF-16 string * @param stream * @return String from the InputString in UTF-16 * @throws IOException */ public static String ReadStreamToUnicodeString(InputStream stream) throws IOException { return new String(ReadStreamToByteArray(stream), "UTF-16"); } }
alexluckett/AirportSimulator
src/utils/IO.java
Java
mit
1,626
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.clients.commerce.catalog.admin; import java.util.List; import java.util.ArrayList; import com.mozu.api.MozuClient; import com.mozu.api.MozuClientFactory; import com.mozu.api.MozuUrl; import com.mozu.api.Headers; import org.joda.time.DateTime; import com.mozu.api.AsyncCallback; import java.util.concurrent.CountDownLatch; import com.mozu.api.security.AuthTicket; import org.apache.commons.lang.StringUtils; import com.mozu.api.DataViewMode; /** <summary> * Define and manage discounts to apply to products, product categories, or orders. The discounts can be a specified amount off the price, percentage off the price, or for free shipping. Create a coupon code that shoppers can use to redeem the discount. * </summary> */ public class DiscountClient { /** * Retrieves a list of discounts according to any specified filter criteria and sort options. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.DiscountCollection> mozuClient=GetDiscountsClient(dataViewMode); * client.setBaseAddress(url); * client.executeRequest(); * DiscountCollection discountCollection = client.Result(); * </code></pre></p> * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.DiscountCollection> * @see com.mozu.api.contracts.productadmin.DiscountCollection */ public static MozuClient<com.mozu.api.contracts.productadmin.DiscountCollection> getDiscountsClient(com.mozu.api.DataViewMode dataViewMode) throws Exception { return getDiscountsClient(dataViewMode, null, null, null, null, null); } /** * Retrieves a list of discounts according to any specified filter criteria and sort options. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.DiscountCollection> mozuClient=GetDiscountsClient(dataViewMode, startIndex, pageSize, sortBy, filter, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * DiscountCollection discountCollection = client.Result(); * </code></pre></p> * @param filter A set of expressions that consist of a field, operator, and value and represent search parameter syntax when filtering results of a query. Valid operators include equals (eq), does not equal (ne), greater than (gt), less than (lt), greater than or equal to (ge), less than or equal to (le), starts with (sw), or contains (cont). For example - "filter=IsDisplayed+eq+true" * @param pageSize The number of results to display on each page when creating paged results from a query. The maximum value is 200. * @param responseFields Use this field to include those fields which are not included by default. * @param sortBy * @param startIndex * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.DiscountCollection> * @see com.mozu.api.contracts.productadmin.DiscountCollection */ public static MozuClient<com.mozu.api.contracts.productadmin.DiscountCollection> getDiscountsClient(com.mozu.api.DataViewMode dataViewMode, Integer startIndex, Integer pageSize, String sortBy, String filter, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.DiscountUrl.getDiscountsUrl(filter, pageSize, responseFields, sortBy, startIndex); String verb = "GET"; Class<?> clz = com.mozu.api.contracts.productadmin.DiscountCollection.class; MozuClient<com.mozu.api.contracts.productadmin.DiscountCollection> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.DiscountCollection>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.addHeader(Headers.X_VOL_DATAVIEW_MODE ,dataViewMode.toString()); return mozuClient; } /** * Retrieves the localized content specified for the specified discount. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.DiscountLocalizedContent> mozuClient=GetDiscountContentClient(dataViewMode, discountId); * client.setBaseAddress(url); * client.executeRequest(); * DiscountLocalizedContent discountLocalizedContent = client.Result(); * </code></pre></p> * @param discountId discountId parameter description DOCUMENT_HERE * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.DiscountLocalizedContent> * @see com.mozu.api.contracts.productadmin.DiscountLocalizedContent */ public static MozuClient<com.mozu.api.contracts.productadmin.DiscountLocalizedContent> getDiscountContentClient(com.mozu.api.DataViewMode dataViewMode, Integer discountId) throws Exception { return getDiscountContentClient(dataViewMode, discountId, null); } /** * Retrieves the localized content specified for the specified discount. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.DiscountLocalizedContent> mozuClient=GetDiscountContentClient(dataViewMode, discountId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * DiscountLocalizedContent discountLocalizedContent = client.Result(); * </code></pre></p> * @param discountId discountId parameter description DOCUMENT_HERE * @param responseFields Use this field to include those fields which are not included by default. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.DiscountLocalizedContent> * @see com.mozu.api.contracts.productadmin.DiscountLocalizedContent */ public static MozuClient<com.mozu.api.contracts.productadmin.DiscountLocalizedContent> getDiscountContentClient(com.mozu.api.DataViewMode dataViewMode, Integer discountId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.DiscountUrl.getDiscountContentUrl(discountId, responseFields); String verb = "GET"; Class<?> clz = com.mozu.api.contracts.productadmin.DiscountLocalizedContent.class; MozuClient<com.mozu.api.contracts.productadmin.DiscountLocalizedContent> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.DiscountLocalizedContent>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.addHeader(Headers.X_VOL_DATAVIEW_MODE ,dataViewMode.toString()); return mozuClient; } /** * Retrieves the details of a single discount. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.Discount> mozuClient=GetDiscountClient(dataViewMode, discountId); * client.setBaseAddress(url); * client.executeRequest(); * Discount discount = client.Result(); * </code></pre></p> * @param discountId discountId parameter description DOCUMENT_HERE * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.Discount> * @see com.mozu.api.contracts.productadmin.Discount */ public static MozuClient<com.mozu.api.contracts.productadmin.Discount> getDiscountClient(com.mozu.api.DataViewMode dataViewMode, Integer discountId) throws Exception { return getDiscountClient(dataViewMode, discountId, null); } /** * Retrieves the details of a single discount. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.Discount> mozuClient=GetDiscountClient(dataViewMode, discountId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * Discount discount = client.Result(); * </code></pre></p> * @param discountId discountId parameter description DOCUMENT_HERE * @param responseFields Use this field to include those fields which are not included by default. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.Discount> * @see com.mozu.api.contracts.productadmin.Discount */ public static MozuClient<com.mozu.api.contracts.productadmin.Discount> getDiscountClient(com.mozu.api.DataViewMode dataViewMode, Integer discountId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.DiscountUrl.getDiscountUrl(discountId, responseFields); String verb = "GET"; Class<?> clz = com.mozu.api.contracts.productadmin.Discount.class; MozuClient<com.mozu.api.contracts.productadmin.Discount> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.Discount>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.addHeader(Headers.X_VOL_DATAVIEW_MODE ,dataViewMode.toString()); return mozuClient; } /** * Generates a random code for a coupon. * <p><pre><code> * MozuClient<String> mozuClient=GenerateRandomCouponClient(); * client.setBaseAddress(url); * client.executeRequest(); * string string = client.Result(); * </code></pre></p> * @return Mozu.Api.MozuClient <string> * @see string */ public static MozuClient<String> generateRandomCouponClient() throws Exception { return generateRandomCouponClient( null); } /** * Generates a random code for a coupon. * <p><pre><code> * MozuClient<String> mozuClient=GenerateRandomCouponClient( responseFields); * client.setBaseAddress(url); * client.executeRequest(); * string string = client.Result(); * </code></pre></p> * @param responseFields Use this field to include those fields which are not included by default. * @return Mozu.Api.MozuClient <string> * @see string */ public static MozuClient<String> generateRandomCouponClient(String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.DiscountUrl.generateRandomCouponUrl(responseFields); String verb = "GET"; Class<?> clz = String.class; MozuClient<String> mozuClient = (MozuClient<String>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); return mozuClient; } /** * Creates a new discount or coupon to apply to a product, category, order, or shipping. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.Discount> mozuClient=CreateDiscountClient( discount); * client.setBaseAddress(url); * client.executeRequest(); * Discount discount = client.Result(); * </code></pre></p> * @param discount Name of the discount added and applied to a shopping cart and order for a shopper's purchase. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.Discount> * @see com.mozu.api.contracts.productadmin.Discount * @see com.mozu.api.contracts.productadmin.Discount */ public static MozuClient<com.mozu.api.contracts.productadmin.Discount> createDiscountClient(com.mozu.api.contracts.productadmin.Discount discount) throws Exception { return createDiscountClient( discount, null); } /** * Creates a new discount or coupon to apply to a product, category, order, or shipping. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.Discount> mozuClient=CreateDiscountClient( discount, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * Discount discount = client.Result(); * </code></pre></p> * @param responseFields Use this field to include those fields which are not included by default. * @param discount Name of the discount added and applied to a shopping cart and order for a shopper's purchase. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.Discount> * @see com.mozu.api.contracts.productadmin.Discount * @see com.mozu.api.contracts.productadmin.Discount */ public static MozuClient<com.mozu.api.contracts.productadmin.Discount> createDiscountClient(com.mozu.api.contracts.productadmin.Discount discount, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.DiscountUrl.createDiscountUrl(responseFields); String verb = "POST"; Class<?> clz = com.mozu.api.contracts.productadmin.Discount.class; MozuClient<com.mozu.api.contracts.productadmin.Discount> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.Discount>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(discount); return mozuClient; } /** * Updates the localizable content for the specified discount or rename the discount without modifying its other properties. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.DiscountLocalizedContent> mozuClient=UpdateDiscountContentClient( content, discountId); * client.setBaseAddress(url); * client.executeRequest(); * DiscountLocalizedContent discountLocalizedContent = client.Result(); * </code></pre></p> * @param discountId discountId parameter description DOCUMENT_HERE * @param content The container for the language-specific name of the discount. A container exists for each supported language (LocaleCode). This parameter enables you to display the discount name in multiple languages yet manage it as a single discount internally. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.DiscountLocalizedContent> * @see com.mozu.api.contracts.productadmin.DiscountLocalizedContent * @see com.mozu.api.contracts.productadmin.DiscountLocalizedContent */ public static MozuClient<com.mozu.api.contracts.productadmin.DiscountLocalizedContent> updateDiscountContentClient(com.mozu.api.contracts.productadmin.DiscountLocalizedContent content, Integer discountId) throws Exception { return updateDiscountContentClient( content, discountId, null); } /** * Updates the localizable content for the specified discount or rename the discount without modifying its other properties. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.DiscountLocalizedContent> mozuClient=UpdateDiscountContentClient( content, discountId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * DiscountLocalizedContent discountLocalizedContent = client.Result(); * </code></pre></p> * @param discountId discountId parameter description DOCUMENT_HERE * @param responseFields Use this field to include those fields which are not included by default. * @param content The container for the language-specific name of the discount. A container exists for each supported language (LocaleCode). This parameter enables you to display the discount name in multiple languages yet manage it as a single discount internally. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.DiscountLocalizedContent> * @see com.mozu.api.contracts.productadmin.DiscountLocalizedContent * @see com.mozu.api.contracts.productadmin.DiscountLocalizedContent */ public static MozuClient<com.mozu.api.contracts.productadmin.DiscountLocalizedContent> updateDiscountContentClient(com.mozu.api.contracts.productadmin.DiscountLocalizedContent content, Integer discountId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.DiscountUrl.updateDiscountContentUrl(discountId, responseFields); String verb = "PUT"; Class<?> clz = com.mozu.api.contracts.productadmin.DiscountLocalizedContent.class; MozuClient<com.mozu.api.contracts.productadmin.DiscountLocalizedContent> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.DiscountLocalizedContent>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(content); return mozuClient; } /** * Updates one or more properties of a defined discount. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.Discount> mozuClient=UpdateDiscountClient( discount, discountId); * client.setBaseAddress(url); * client.executeRequest(); * Discount discount = client.Result(); * </code></pre></p> * @param discountId discountId parameter description DOCUMENT_HERE * @param discount Name of the discount added and applied to a shopping cart and order for a shopper's purchase. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.Discount> * @see com.mozu.api.contracts.productadmin.Discount * @see com.mozu.api.contracts.productadmin.Discount */ public static MozuClient<com.mozu.api.contracts.productadmin.Discount> updateDiscountClient(com.mozu.api.contracts.productadmin.Discount discount, Integer discountId) throws Exception { return updateDiscountClient( discount, discountId, null); } /** * Updates one or more properties of a defined discount. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.Discount> mozuClient=UpdateDiscountClient( discount, discountId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * Discount discount = client.Result(); * </code></pre></p> * @param discountId discountId parameter description DOCUMENT_HERE * @param responseFields Use this field to include those fields which are not included by default. * @param discount Name of the discount added and applied to a shopping cart and order for a shopper's purchase. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.Discount> * @see com.mozu.api.contracts.productadmin.Discount * @see com.mozu.api.contracts.productadmin.Discount */ public static MozuClient<com.mozu.api.contracts.productadmin.Discount> updateDiscountClient(com.mozu.api.contracts.productadmin.Discount discount, Integer discountId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.DiscountUrl.updateDiscountUrl(discountId, responseFields); String verb = "PUT"; Class<?> clz = com.mozu.api.contracts.productadmin.Discount.class; MozuClient<com.mozu.api.contracts.productadmin.Discount> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.Discount>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(discount); return mozuClient; } /** * Deletes a discount specified by its discount ID. * <p><pre><code> * MozuClient mozuClient=DeleteDiscountClient( discountId); * client.setBaseAddress(url); * client.executeRequest(); * </code></pre></p> * @param discountId discountId parameter description DOCUMENT_HERE * @return Mozu.Api.MozuClient */ public static MozuClient deleteDiscountClient(Integer discountId) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.DiscountUrl.deleteDiscountUrl(discountId); String verb = "DELETE"; MozuClient mozuClient = (MozuClient) MozuClientFactory.getInstance(); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); return mozuClient; } }
lakshmi-nair/mozu-java
mozu-javaasync-core/src/main/java/com/mozu/api/clients/commerce/catalog/admin/DiscountClient.java
Java
mit
18,512
/* * Copyright (C) 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.client.android; import com.google.zxing.ResultPoint; import com.google.zxing.client.android.camera.CameraManager; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; import java.util.ArrayList; import java.util.List; /** * This view is overlaid on top of the camera preview. It adds the viewfinder rectangle and partial * transparency outside it, as well as the laser scanner animation and result points. * * @author [email protected] (Daniel Switkin) */ public final class ViewfinderView extends View { private static final int[] SCANNER_ALPHA = {0, 64, 128, 192, 255, 192, 128, 64}; private static final long ANIMATION_DELAY = 80L; private static final int CURRENT_POINT_OPACITY = 0xA0; private static final int MAX_RESULT_POINTS = 20; private static final int POINT_SIZE = 6; private CameraManager cameraManager; private final Paint paint; private Bitmap resultBitmap; private final int maskColor; private final int resultColor; private final int laserColor; private final int resultPointColor; private int scannerAlpha; private List<ResultPoint> possibleResultPoints; private List<ResultPoint> lastPossibleResultPoints; // This constructor is used when the class is built from an XML resource. public ViewfinderView(Context context, AttributeSet attrs) { super(context, attrs); // Initialize these once for performance rather than calling them every time in onDraw(). paint = new Paint(Paint.ANTI_ALIAS_FLAG); Resources resources = getResources(); maskColor = resources.getColor(R.color.viewfinder_mask); resultColor = resources.getColor(R.color.result_view); laserColor = resources.getColor(R.color.viewfinder_laser); resultPointColor = resources.getColor(R.color.possible_result_points); scannerAlpha = 0; possibleResultPoints = new ArrayList<ResultPoint>(5); lastPossibleResultPoints = null; } public void setCameraManager(CameraManager cameraManager) { this.cameraManager = cameraManager; } @SuppressLint("DrawAllocation") @Override public void onDraw(Canvas canvas) { if (cameraManager == null) { return; // not ready yet, early draw before done configuring } Rect frame = cameraManager.getFramingRect(); Rect previewFrame = cameraManager.getFramingRectInPreview(); if (frame == null || previewFrame == null) { return; } int width = canvas.getWidth(); int height = canvas.getHeight(); // Draw the exterior (i.e. outside the framing rect) darkened paint.setColor(resultBitmap != null ? resultColor : maskColor); canvas.drawRect(0, 0, width, frame.top, paint); canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint); canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint); canvas.drawRect(0, frame.bottom + 1, width, height, paint); if (resultBitmap != null) { // Draw the opaque result bitmap over the scanning rectangle paint.setAlpha(CURRENT_POINT_OPACITY); canvas.drawBitmap(resultBitmap, null, frame, paint); } else { // Draw a red "laser scanner" line through the middle to show decoding is active paint.setColor(laserColor); paint.setAlpha(SCANNER_ALPHA[scannerAlpha]); scannerAlpha = (scannerAlpha + 1) % SCANNER_ALPHA.length; int middle = frame.height() / 2 + frame.top; canvas.drawRect(frame.left + 2, middle - 1, frame.right - 1, middle + 2, paint); float scaleX = frame.width() / (float) previewFrame.width(); float scaleY = frame.height() / (float) previewFrame.height(); List<ResultPoint> currentPossible = possibleResultPoints; List<ResultPoint> currentLast = lastPossibleResultPoints; int frameLeft = frame.left; int frameTop = frame.top; if (currentPossible.isEmpty()) { lastPossibleResultPoints = null; } else { possibleResultPoints = new ArrayList<ResultPoint>(5); lastPossibleResultPoints = currentPossible; paint.setAlpha(CURRENT_POINT_OPACITY); paint.setColor(resultPointColor); synchronized (currentPossible) { for (ResultPoint point : currentPossible) { canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX), frameTop + (int) (point.getY() * scaleY), POINT_SIZE, paint); } } } if (currentLast != null) { paint.setAlpha(CURRENT_POINT_OPACITY / 2); paint.setColor(resultPointColor); synchronized (currentLast) { float radius = POINT_SIZE / 2.0f; for (ResultPoint point : currentLast) { canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX), frameTop + (int) (point.getY() * scaleY), radius, paint); } } } // Request another update at the animation interval, but only repaint the laser line, // not the entire viewfinder mask. postInvalidateDelayed(ANIMATION_DELAY, frame.left - POINT_SIZE, frame.top - POINT_SIZE, frame.right + POINT_SIZE, frame.bottom + POINT_SIZE); } } public void drawViewfinder() { Bitmap resultBitmap = this.resultBitmap; this.resultBitmap = null; if (resultBitmap != null) { resultBitmap.recycle(); } invalidate(); } public void addPossibleResultPoint(ResultPoint point) { List<ResultPoint> points = possibleResultPoints; synchronized (points) { points.add(point); int size = points.size(); if (size > MAX_RESULT_POINTS) { // trim it points.subList(0, size - MAX_RESULT_POINTS / 2).clear(); } } } }
wtghby/app
zxing-android/zxing-lib/src/com/google/zxing/client/android/ViewfinderView.java
Java
mit
7,225
// This is a generated file. Not intended for manual editing. package io.github.josehsantos.hack.lang.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static io.github.josehsantos.hack.lang.psi.HackTypes.*; import io.github.josehsantos.hack.lang.psi.*; public class HackTupleTypeImpl extends HackTypeImpl implements HackTupleType { public HackTupleTypeImpl(ASTNode node) { super(node); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof HackVisitor) ((HackVisitor)visitor).visitTupleType(this); else super.accept(visitor); } @Override @NotNull public List<HackType> getTypeList() { return PsiTreeUtil.getChildrenOfTypeAsList(this, HackType.class); } }
jhsx/hacklang-idea
gen/io/github/josehsantos/hack/lang/psi/impl/HackTupleTypeImpl.java
Java
mit
903
package com.wrapper.spotify; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpEntity; import java.io.*; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.logging.Level; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class TestUtil { private static final String FIXTURE_DIR = "src/test/fixtures/"; private static String readTestData(String fileName) throws IOException { return readFromFile(new File(FIXTURE_DIR, fileName)); } private static String readFromFile(File file) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); StringBuilder out = new StringBuilder(); String line; while ((line = in.readLine()) != null) { out.append(line); } in.close(); return out.toString(); } protected static String readFromFileTry(File file) { try { return readFromFile(file); } catch (IOException e) { SpotifyApi.LOGGER.log( Level.SEVERE, "IOException while trying to read from file \"" + file.getName() + "\""); return null; } } public static class MockedHttpManager { public static IHttpManager returningJson(String jsonFixtureFileName) throws Exception { // Mocked HTTP Manager to get predictable responses final IHttpManager mockedHttpManager = mock(IHttpManager.class); String fixture = null; if (jsonFixtureFileName != null) { fixture = readTestData(jsonFixtureFileName); } when(mockedHttpManager.get(any(URI.class), any(Header[].class))).thenReturn(fixture); when(mockedHttpManager.post(any(URI.class), any(Header[].class), any(HttpEntity.class))).thenReturn(fixture); when(mockedHttpManager.put(any(URI.class), any(Header[].class), any(HttpEntity.class))).thenReturn(fixture); when(mockedHttpManager.delete(any(URI.class), any(Header[].class), any(HttpEntity.class))).thenReturn(fixture); return mockedHttpManager; } } }
thelinmichael/spotify-web-api-java
src/test/java/com/wrapper/spotify/TestUtil.java
Java
mit
2,130
package oose.dea.services.local; import oose.dea.dao.FakeItemDAO; import oose.dea.dao.ItemDAO; import oose.dea.domain.Item; import oose.dea.services.ItemService; import javax.inject.Inject; import javax.inject.Named; import java.util.List; @Named("localItemService") public class LocalItemService implements ItemService { @Inject private ItemDAO itemDAO; @Override public List<Item> findAll() { return itemDAO.list(); } }
StenKoning/dea-code-examples
exercises/cdi/src/main/java/oose/dea/services/local/LocalItemService.java
Java
mit
454
package exts; /** +------------------------------------------------------------------------------<br /> * 分页导航 通用类 暂时提供了5中通用的分页方法;<br /> * 用法:Link link = new Link('当第几页', '总数据量', '分页的url', '每页显示的数据数', '每次显示的页数');<br /> * 类初始化后:String linkstr = link->show(3);<br /> * by 木頭, 从ePHP Link.class移植过来<br /> +------------------------------------------------------------------------------<br /> * @version 2.6 * @author WangXian * @email [email protected] * @creation_date 2008.12.22 * @last_modified 2014-02-06 */ public class Link { /** * 当前页码 */ private int cpage = 1; /** * ?page=xx前面的部分 */ private String url; /** * 每次显示的页码数, 有些分页样式无效。 */ private int opage; /** * 总页数 */ private int totalpage; /** * 分页 * @param cpage 当前页码 * @param totaldata 总数据数 * @param url 当前页码 * @param pagenum 每页数据数 * @param opage 每次显示的页码数, 有些分页样式无效。 */ public Link(int cpage, int totaldata, String url, double pagenum, int opage) { this.cpage = cpage; this.totalpage = (int) (totaldata > 0 ? Math.ceil( totaldata / pagenum ) : 1); if(url.contains("?")) this.url = url; else this.url = url + "?"; this.opage = opage; } /** * 显示翻页样式<br /> * 1 : 最简单的上一页 下一页<br /> * 2 : 一次翻翻N页<br /> * 3 : 滑动滚动分页<br /> * 4 : wap2.0 分页样式<br /> * 5 : wap1.2 分页样式<br /> * @param style 可选:1,2,3,4,5 */ public String show(int style) { switch (style) { case 1 : // 最简单的上一页 下一些 return this.f1(); case 2 : // 一次翻翻N页的 Link return this.f2(); case 3 : // 滑动滚动分页 return this.f3(); case 4 : // wap2.0 return this.f4(); case 5 : // wap1.2 return this.f5(); default: return this.f1(); } } private String url(int tpage) { if(tpage>0) return this.url + "&page=" + tpage; else return ""; } /** 普通的上一页,下一页方式 */ private String f1() { String _linkstr = "\n<p class=\"links\">\n"; //begin if (this.totalpage < 2) { // int nextpage = this.cpage + 1; _linkstr += "<span class=\"disabled\">首页</span>" + " \n"; _linkstr += "<span class=\"disabled\">上一页</span> \n"; _linkstr += "<span class=\"disabled\">下一页</span> \n"; _linkstr += "<span class=\"disabled\">尾页</span> \n"; } else if (this.cpage < 2) { //首页 int nextpage = this.cpage + 1; _linkstr += "<span class=\"disabled\">首页</span>" + " \n"; _linkstr += "<span class=\"disabled\">上一页</span> \n"; _linkstr += "<a href=\"" + this.url( nextpage ) + "\">下一页</a> \n"; _linkstr += "<a href=\"" + this.url ( this.totalpage ) + "\">尾页</a> \n"; } else if (this.cpage >= this.totalpage) { //=尾页 int prepage = this.cpage - 1; _linkstr += "<a href=\"" + this.url( 1 ) +"\">首页</a>\n"; _linkstr += "<a href=\"" + this.url( prepage ) +"\">上一页</a>\n"; _linkstr += "\n<span class=\"disabled\">下一页</span>\n"; _linkstr += "<span class=\"disabled\">尾页</span>\n"; } else { //正常 int prepage = this.cpage - 1; int nextpage = this.cpage + 1; _linkstr += "<a href=\""+ this.url( 1 ) +"\">首页</a>\n"; _linkstr += "<a href=\""+ this.url( prepage ) +"\">上一页</a>\n"; _linkstr += "\n<a href=\""+ this.url( nextpage ) +"\">下一页</a>\n"; _linkstr += "<a href=\""+ this.url( this.totalpage ) +"\">尾页</a>\n"; } _linkstr += "</p>\n"; //end div return _linkstr; } /** 一次翻N页的 Link */ private String f2() { int p1 = (int)(Math.ceil( (this.cpage - this.opage) / this.opage )); //计算开始页 结束页 int beginpage = p1 * (this.opage) + 1; int endpage = (p1 + 1) * (this.opage); if (endpage > this.totalpage) { // 最后一页 大于总页数 endpage = this.totalpage; } // 前后滚10页 int preopage = (beginpage - this.opage > 0) ? beginpage - this.opage : 0; // 上一个N页码 int nextopage = (beginpage + this.opage < this.totalpage) ? beginpage + this.opage : 0; // 下一个N页码 String _linkstr = "\n<p class=\"links\">\n"; // begin // 分页 _linkstr += "<span class=\"disabled\">分页:"+ this.cpage +"/"+ this.totalpage +"</span>\n"; // 前滚10页码 if (preopage > 0) _linkstr += "<a href=\"" + this.url ( preopage ) + "\">上"+ this.opage +"页</a>\n"; else _linkstr += "<span class=\"disabled\">上"+ this.opage +"页</span>\n"; // 主要的数字分页 页码 for(int i = beginpage; i <= endpage; i++) { if (this.cpage != i) _linkstr += "<a href=\""+ this.url(i) +"\">" + i + "</a>\n"; else _linkstr += "<span class=\"current\">"+i+"</span>\n"; } //后滚10页码 if (nextopage > 0) _linkstr += "<a href=\""+ this.url(nextopage) +"\">下"+ this.opage +"页</a>\n"; else _linkstr += "<span class=\"disabled\">下"+ this.opage +"页</span>\n"; _linkstr += "</p>\n"; //end div return _linkstr; } /** 中间滑动滚动 */ private String f3() { // 计算开始页 结束页 int beginpage, endpage; if (this.cpage > Math.ceil( (this.opage) / 2 )) { beginpage = (int) (this.cpage - Math.floor( (this.opage) / 2 )); endpage = (int) (this.cpage + Math.floor( (this.opage) / 2 )); } else { beginpage = 1; endpage = this.opage; } // 限制末页 if (endpage > this.totalpage) endpage = this.totalpage; String _linkstr = "\n<p class=\"links\">\n"; // begin // 分页 _linkstr += "<span class=\"disabled\">分页:"+ this.cpage +"/"+ this.totalpage +"</span>\n"; // 首页 if (this.cpage > 1) { _linkstr += "<a href=\""+ this.url(1) +"\">首页</a> \n"; _linkstr += "<a href=\"" + this.url( this.cpage - 1 ) +"\">上一页</a> \n"; } else { _linkstr += "<span class=\"disabled\">首页</span>" +" \n"; _linkstr += "<span class=\"disabled\">上一页</span>" +" \n"; } //main num. Link for(int i = beginpage; i <= endpage; i++) { if (this.cpage != i) _linkstr += "<a href=\""+this.url(i) +"\">" + i + "</a> \n"; else _linkstr += "<span class=\"current\">"+ i +"</span> \n"; } //尾页 if (this.cpage == this.totalpage || this.totalpage == 0) { _linkstr += "<span class=\"disabled\">下一页</span> \n"; _linkstr += "<span class=\"disabled\">尾页</span> \n"; } else { _linkstr += "<a href=\"" + this.url ( this.cpage + 1 ) + "\">下一页</a> \n"; _linkstr += "<a href=\"" + this.url ( this.totalpage ) + "\">尾页</a> \n"; } _linkstr += "</p>\n"; //end div return _linkstr; } /** wap2.0分页 */ private String f4() { if(this.cpage > this.totalpage) this.cpage = 1; String out = "<form method=\"post\" action=\""+ this.url( this.cpage ) +"\">"; out += "<p class=\"links\">"; // 上一页 if (this.cpage > 1) out += "<a href=\""+ this.url(this.cpage - 1) +"\">上页</a>&nbsp;"; // 下一页 if ( this.cpage < this.totalpage ) out += "<a href=\""+ this.url(this.cpage + 1) +"\">下页</a>&nbsp;\n"; out += "&nbsp;&nbsp;<input type=\"text\" name=\"page\" size=\"2\" value=\""+ this.cpage +"\" />"; out += "<input type=\"submit\" name=\"pagego\" value=\"跳转\" />"; out += "&nbsp;&nbsp;"+ this.cpage +'/'+ this.totalpage +"页\n"; out += "</p>"; out += "</form>"; return out; } /** wap1.2分页 */ private String f5() { String _linkstr = "\n<p class=\"links\">\n"; //begin //下一页 尾页 if (this.cpage == this.totalpage || this.totalpage == 0) _linkstr += "<span class=\"disabled\">下一页</span> \n"; else _linkstr += "<a href=\""+ this.url ( this.cpage + 1 ) + "\">下一页</a> \n"; _linkstr +=" / "; // 首页 if (this.cpage > 1) _linkstr += "<a href=\"" + this.url ( this.cpage - 1 ) + "\">上一页</a>\n"; else _linkstr += "<span class=\"disabled\">上一页</span>\n"; _linkstr +="<br />"; // 数字分页 if(this.totalpage<7) { for(int i=1;i<this.totalpage+1;i++) { if(this.cpage == i) _linkstr += "<span class=\"current\">"+ i+ "</span>\n"; else _linkstr += "<a href=\""+ this.url(i) +"\">"+ i +"</a> \n"; } } else if(this.cpage < 4 && this.totalpage>7) { for(int i=1;i<5;i++) { if(this.cpage == i) _linkstr += "<span class=\"current\">i</span>\n"; else _linkstr += "<a href=\""+ this.url(i) +"\">{i}</a>\n"; } _linkstr += " ... "; _linkstr += "<a href=\""+ this.url(this.totalpage) +"\">"+ this.totalpage +"</a>\n"; } else if(this.cpage >= 4 && this.totalpage > this.cpage + 4) { // int beginpage = (int) (this.cpage - Math.ceil ( (this.opage) / 2 )); for(int i=this.cpage - 2;i<=this.cpage+1;i++) { if(this.cpage == i) _linkstr += "<span class=\"current\">"+ i +"</span>\n"; else _linkstr += "<a href=\""+ this.url(i) +"\">"+i+"</a>\n"; } _linkstr += " ... "; _linkstr += "<a href=\""+ this.url(this.totalpage) +"\">"+ this.totalpage +"</a>\n"; } else if(this.totalpage <= this.cpage + 4) { // int beginpage = (int) (this.cpage - Math.ceil ( (this.opage) / 2 )); for(int i=this.totalpage-7;i<=this.totalpage;i++) { if(this.cpage == i) _linkstr += "<span class=\"current\">"+ i +"</span>\n"; else _linkstr += "<a href=\""+ this.url(i) +"\">{i}</a> \n"; } } _linkstr += "到<input name=\"goPageNo\" format=\"*N\" size=\"2\" value=\"\" maxlength=\"3\" emptyok=\"true\"/>页"+ "<anchor>"+ "<go href=\""+ this.url(0) +"\" method=\"post\" sendreferer=\"true\">"+ "<postfield name=\"page\" value=\"goPageNo\"/>"+ "</go>跳转"+ "</anchor>"; _linkstr += "</p>\n"; //end div return _linkstr; } public static void main(String[] args) { Link link = new Link(11, 200, "/user/list?key=wx", 15, 5); System.out.println(link.show(3)); } }
wangxian/jianyibao
src/main/java/exts/Link.java
Java
mit
10,053
package dxat.appserver.manager.pojos; public class OrgFlow { public String identifier; private String name; private String srcOTidentifier; private String dstOTidentifier; private short srcPort; private short dstPort; private int qos; private double bandwidth; private String protocol; private String assignedOrgId; private boolean active; public String getAssignedOrgId() { return assignedOrgId; } public void setAssignedOrgId(String assignedOrgId) { this.assignedOrgId = assignedOrgId; } public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSrcOTidentifier() { return srcOTidentifier; } public void setSrcOTidentifier(String srcOTidentifier) { this.srcOTidentifier = srcOTidentifier; } public String getDstOTidentifier() { return dstOTidentifier; } public void setDstOTidentifier(String dstOTidentifier) { this.dstOTidentifier = dstOTidentifier; } public short getSrcPort() { return srcPort; } public void setSrcPort(short srcPort) { this.srcPort = srcPort; } public short getDstPort() { return dstPort; } public void setDstPort(short dstPort) { this.dstPort = dstPort; } public int getQos() { return qos; } public void setQos(int qos) { this.qos = qos; } public double getBandwidth() { return bandwidth; } public void setBandwidth(double bandwidth) { this.bandwidth = bandwidth; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } }
gerardcl/SDN-OAM-project
project/AppServer/src/main/java/dxat/appserver/manager/pojos/OrgFlow.java
Java
mit
1,809
package de.marcusschiesser.dbpendler.server.utils; import static com.google.appengine.api.urlfetch.FetchOptions.Builder.*; import static com.google.appengine.api.urlfetch.HTTPMethod.POST; import static com.google.appengine.api.urlfetch.URLFetchServiceFactory.getURLFetchService; import java.io.IOException; import java.net.URL; import java.util.Collection; import java.util.List; import java.util.logging.Logger; import com.google.appengine.api.urlfetch.HTTPHeader; import com.google.appengine.api.urlfetch.HTTPRequest; import com.google.appengine.api.urlfetch.HTTPResponse; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; public class HTTPSession { private final Logger log = Logger.getLogger(HTTPSession.class.getName()); private HTTPHeader cookie; private String sessionParam; private static final String RESPONSE_CONTENT_ENCODING = "ISO-8859-1"; public HTTPSession() { cookie = null; sessionParam = null; } public HTTPSession(String ld, String i) { // this defines an anonymous session sessionParam = "ld=" + ld + "&i=" + i; } private void updateCookies(HTTPResponse resp) { if(sessionParam!=null) return; // don't use cookies with anonymous sessions List<HTTPHeader> headers = resp.getHeaders(); Collection<HTTPHeader> cookies = Collections2.filter(headers, new Predicate<HTTPHeader>() { @Override public boolean apply(HTTPHeader header) { return header.getName().equalsIgnoreCase("Set-Cookie"); } }); if(!cookies.isEmpty()) { logCookies(cookies); HTTPHeader setcookie = cookies.iterator().next(); String[] values = setcookie.getValue().split(";"); if(values.length>0) { String value = values[0]; if(value.split("=")[0].equalsIgnoreCase("jsessionid")) { // only update jsessionid cookies cookie = new HTTPHeader("Cookie", value); } } } } private void logCookies(Collection<HTTPHeader> cookies) { for(HTTPHeader cookie: cookies) { log.finer("Server returned cookie: " + cookie.getName() + "=" + cookie.getValue()); } } public String getMethod(URL url) throws IOException { log.finer("Calling GET on " + url); HTTPRequest req = new HTTPRequest(url); if(cookie!=null) req.setHeader(cookie); HTTPResponse resp = getURLFetchService().fetch(req); updateCookies(resp); int responseCode = -1; if (resp != null) { responseCode = resp.getResponseCode(); if (responseCode == 200) { String response = new String(resp.getContent(), RESPONSE_CONTENT_ENCODING); log.finer("GET returns: " + response); return response; } } throw new IOException("Problem calling GET on: " + url.toString() + " response: " + responseCode); } public String postMethod(URL url, String params) throws IOException { log.finer("Calling POST on " + url + " with params: " + params); HTTPRequest req = new HTTPRequest(url, POST, followRedirects()); //.withDeadline(10.0)); //req.setHeader(new HTTPHeader("x-header-one", "some header")); if(cookie!=null) req.setHeader(cookie); if(sessionParam!=null) params = sessionParam + "&" + params; req.setPayload(params.getBytes(RESPONSE_CONTENT_ENCODING)); HTTPResponse resp = getURLFetchService().fetch(req); updateCookies(resp); int responseCode = -1; if (resp != null) { responseCode = resp.getResponseCode(); if (responseCode == 200) { // List<HTTPHeader> headers = resp.getHeaders(); String response = new String(resp.getContent(), RESPONSE_CONTENT_ENCODING); log.finer("POST returns: " + response); return response; } } throw new IOException("Problem calling GET on: " + url.toString() + " response: " + responseCode); } }
marcusschiesser/openbahn-api
openbahn-api/src/de/marcusschiesser/dbpendler/server/utils/HTTPSession.java
Java
mit
3,796
package com.birdcopy.BirdCopyApp.DataManager.ActiveDAO; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import de.greenrobot.dao.AbstractDao; import de.greenrobot.dao.Property; import de.greenrobot.dao.internal.DaoConfig; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * DAO for table BE__TASK__WORD. */ public class BE_TASK_WORDDao extends AbstractDao<BE_TASK_WORD, Long> { public static final String TABLENAME = "BE__TASK__WORD"; /** * Properties of entity BE_TASK_WORD.<br/> * Can be used for QueryBuilder and for referencing column names. */ public static class Properties { public final static Property Id = new Property(0, Long.class, "id", true, "_id"); public final static Property BEUSERID = new Property(1, String.class, "BEUSERID", false, "BEUSERID"); public final static Property BEWORD = new Property(2, String.class, "BEWORD", false, "BEWORD"); public final static Property BESENTENCEID = new Property(3, String.class, "BESENTENCEID", false, "BESENTENCEID"); public final static Property BELESSONID = new Property(4, String.class, "BELESSONID", false, "BELESSONID"); public final static Property BETIME = new Property(5, Integer.class, "BETIME", false, "BETIME"); }; public BE_TASK_WORDDao(DaoConfig config) { super(config); } public BE_TASK_WORDDao(DaoConfig config, DaoSession daoSession) { super(config, daoSession); } /** Creates the underlying database table. */ public static void createTable(SQLiteDatabase db, boolean ifNotExists) { String constraint = ifNotExists? "IF NOT EXISTS ": ""; db.execSQL("CREATE TABLE " + constraint + "'BE__TASK__WORD' (" + // "'_id' INTEGER PRIMARY KEY ," + // 0: id "'BEUSERID' TEXT NOT NULL ," + // 1: BEUSERID "'BEWORD' TEXT NOT NULL ," + // 2: BEWORD "'BESENTENCEID' TEXT," + // 3: BESENTENCEID "'BELESSONID' TEXT," + // 4: BELESSONID "'BETIME' INTEGER);"); // 5: BETIME } /** Drops the underlying database table. */ public static void dropTable(SQLiteDatabase db, boolean ifExists) { String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'BE__TASK__WORD'"; db.execSQL(sql); } /** @inheritdoc */ @Override protected void bindValues(SQLiteStatement stmt, BE_TASK_WORD entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } stmt.bindString(2, entity.getBEUSERID()); stmt.bindString(3, entity.getBEWORD()); String BESENTENCEID = entity.getBESENTENCEID(); if (BESENTENCEID != null) { stmt.bindString(4, BESENTENCEID); } String BELESSONID = entity.getBELESSONID(); if (BELESSONID != null) { stmt.bindString(5, BELESSONID); } Integer BETIME = entity.getBETIME(); if (BETIME != null) { stmt.bindLong(6, BETIME); } } /** @inheritdoc */ @Override public Long readKey(Cursor cursor, int offset) { return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0); } /** @inheritdoc */ @Override public BE_TASK_WORD readEntity(Cursor cursor, int offset) { BE_TASK_WORD entity = new BE_TASK_WORD( // cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id cursor.getString(offset + 1), // BEUSERID cursor.getString(offset + 2), // BEWORD cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // BESENTENCEID cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // BELESSONID cursor.isNull(offset + 5) ? null : cursor.getInt(offset + 5) // BETIME ); return entity; } /** @inheritdoc */ @Override public void readEntity(Cursor cursor, BE_TASK_WORD entity, int offset) { entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); entity.setBEUSERID(cursor.getString(offset + 1)); entity.setBEWORD(cursor.getString(offset + 2)); entity.setBESENTENCEID(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3)); entity.setBELESSONID(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4)); entity.setBETIME(cursor.isNull(offset + 5) ? null : cursor.getInt(offset + 5)); } /** @inheritdoc */ @Override protected Long updateKeyAfterInsert(BE_TASK_WORD entity, long rowId) { entity.setId(rowId); return rowId; } /** @inheritdoc */ @Override public Long getKey(BE_TASK_WORD entity) { if(entity != null) { return entity.getId(); } else { return null; } } /** @inheritdoc */ @Override protected boolean isEntityUpdateable() { return true; } }
birdcopy/Android-Birdcopy-Application
app/src/main/java/com/birdcopy/BirdCopyApp/DataManager/ActiveDAO/BE_TASK_WORDDao.java
Java
mit
5,115