text
stringlengths
10
2.72M
package com.infernostats; import com.google.common.collect.ImmutableSet; import com.google.inject.Provides; import com.infernostats.specialweapon.SpecialWeapon; import com.infernostats.specialweapon.SpecialWeaponStats; import com.infernostats.wavehistory.*; import lombok.AccessLevel; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import net.runelite.api.*; import net.runelite.api.coords.WorldPoint; import net.runelite.api.events.*; import net.runelite.client.chat.ChatColorType; import net.runelite.client.chat.ChatMessageBuilder; import net.runelite.client.chat.ChatMessageManager; import net.runelite.client.chat.QueuedMessage; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.events.ConfigChanged; import net.runelite.client.game.ItemManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.ui.ClientToolbar; import net.runelite.client.ui.NavigationButton; import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.client.ui.overlay.infobox.InfoBoxManager; import net.runelite.client.util.ImageUtil; import org.apache.commons.lang3.ArrayUtils; import javax.inject.Inject; import java.awt.image.BufferedImage; import java.time.Duration; import java.time.Instant; import java.util.Set; import java.util.regex.Matcher; import static net.runelite.api.Skill.HITPOINTS; import static net.runelite.api.Skill.PRAYER; import static net.runelite.api.ItemID.INFERNAL_CAPE; @PluginDescriptor( name = "Inferno Stats", description = "Track restoration specials during an inferno attempt.", tags = {"combat", "npcs", "overlay"}, enabledByDefault = false ) @Slf4j public class InfernoStatsPlugin extends Plugin { private boolean prevMorUlRek; private int specialPercentage; private Actor lastSpecTarget; private int lastSpecTick; private WaveTimer waveTimer; private WaveHistory waveHistory; private WaveHistoryWriter waveHistoryWriter; private WaveSplits waveSplits; private SpecialWeapon specialWeapon; private static final String CONFIG_GROUP = "infernostats"; private static final String HIDE_KEY = "hide"; private static final String TIMER_KEY = "showWaveTimer"; private static final String SPECIAL_KEY = "showSpecialCounter"; private static final String OVERLAY_KEY = "showStatsOverlay"; // Prayer points on every tick private int currPrayer; // HP and Prayer points on the spec's current tick private int currSpecHealth, currSpecPrayer; // HP and Prayer points on the spec's previous tick private int prevSpecHealth, prevSpecPrayer; private static final int INFERNO_REGION_ID = 9043; private static final Set<Integer> VOID_REGION_IDS = ImmutableSet.of( 13135, 13136, 13137, 13391, 13392, 13393, 13647, 13648, 13649 ); private static final Set<Integer> MOR_UL_REK_REGION_IDS = ImmutableSet.of( 9806, 9807, 9808, 9809, 10063, 10064, 10065, 10319, 10320, 10321 ); public static final SpecialWeaponStats[] specialCounter = new SpecialWeaponStats[SpecialWeapon.values().length]; @Inject private Client client; @Inject private ChatMessageManager chatMessageManager; @Inject private ClientToolbar clientToolbar; @Inject private InfernoStatsConfig config; @Inject private InfoBoxManager infoBoxManager; @Inject private ItemManager itemManager; @Inject private OverlayManager overlayManager; @Inject private InfernoStatsOverlay statsOverlay; @Getter(AccessLevel.PACKAGE) private WaveHistoryPanel panel; @Getter(AccessLevel.PACKAGE) private NavigationButton navButton; @Provides InfernoStatsConfig getConfig(ConfigManager configManager) { return configManager.getConfig(InfernoStatsConfig.class); } @Override protected void startUp() { specialPercentage = -1; prevMorUlRek = false; waveHistory = new WaveHistory(); waveHistoryWriter = new WaveHistoryWriter(); waveSplits = new WaveSplits(config); panel = injector.getInstance(WaveHistoryPanel.class); final BufferedImage icon = ImageUtil.loadImageResource(getClass(), "/blob-square.png"); navButton = NavigationButton.builder() .tooltip("Inferno Stats") .icon(icon) .priority(6) .panel(panel) .build(); if (isInInferno() || !config.hide()) { clientToolbar.addNavigation(navButton); } if (config.statsOverlay()) { overlayManager.add(statsOverlay); } } @Override protected void shutDown() { removeCounters(); overlayManager.remove(statsOverlay); clientToolbar.removeNavigation(navButton); } @Subscribe public void onGameStateChanged(GameStateChanged event) { GameState gameState = event.getGameState(); if (gameState == GameState.HOPPING || gameState == GameState.LOGIN_SCREEN) { if (waveTimer != null && !waveTimer.IsPaused()) { waveTimer.Pause(); } Wave wave = GetCurrentWave(); // User force-logged or hopped before finishing the wave if (wave != null && wave.stopTime == null) { wave.Pause(); } } if (gameState != GameState.LOGGED_IN && gameState != GameState.LOADING) { return; } final boolean inVoid = isInVoid(); final boolean inInferno = isInInferno(); final boolean inMorUlRek = isInMorUlRek(); if (!inVoid && !inInferno) { removeWaveTimer(); } if (inInferno || !config.hide()) { clientToolbar.addNavigation(navButton); } else { clientToolbar.removeNavigation(navButton); } if (inVoid) { // The user has logged in, but is placed into a temporary void. // This is a holding area before being placed into the inferno instance. log.debug("User logged out and back in, and is now in the void."); } else if (inMorUlRek) { // The user is currently in Mor-Ul-Rek. prevMorUlRek = true; } else if (inInferno && prevMorUlRek == true) { // The user jumped into the inferno from Mor-Ul-Rek. Clear any existing infoboxes. waveHistory.ClearWaves(); panel.ClearWaves(); removeCounters(); removeWaveTimer(); prevMorUlRek = false; } else if (inInferno && prevMorUlRek == false) { // For completeness, the user was moved from the void to the inferno. log.debug("User has been moved from the void to an inferno instance."); } else if (!inInferno && !inMorUlRek) { // The user is neither in the inferno, nor in Mor-Ul-Rek. Clear any existing infoboxes. removeCounters(); } } @Subscribe public void onInteractingChanged(InteractingChanged event) { Actor source = event.getSource(); Actor target = event.getTarget(); if (lastSpecTick != client.getTickCount() || source != client.getLocalPlayer() || target == null) { return; } lastSpecTarget = target; } @Subscribe public void onGameTick(GameTick event) { if (!isInInferno()) { return; } Wave wave = GetCurrentWave(); if (wave != null) { panel.updateWave(wave); } currPrayer = client.getBoostedSkillLevel(PRAYER); if (lastSpecTick != client.getTickCount()) { return; } currSpecHealth = client.getBoostedSkillLevel(HITPOINTS); currSpecPrayer = client.getBoostedSkillLevel(PRAYER); } @Subscribe public void onVarbitChanged(VarbitChanged event) { int specialPercentage = client.getVar(VarPlayer.SPECIAL_ATTACK_PERCENT); if (this.specialPercentage == -1 || specialPercentage >= this.specialPercentage) { this.specialPercentage = specialPercentage; return; } this.specialPercentage = specialPercentage; this.specialWeapon = usedSpecialWeapon(); lastSpecTarget = client.getLocalPlayer().getInteracting(); lastSpecTick = client.getTickCount(); prevSpecPrayer = client.getBoostedSkillLevel(Skill.PRAYER); prevSpecHealth = client.getBoostedSkillLevel(Skill.HITPOINTS); } @Subscribe public void onStatChanged(StatChanged event) { if (!isInInferno()) { return; } Wave wave = GetCurrentWave(); if (wave == null) { return; } if (event.getSkill() == PRAYER) { final int prayer = event.getBoostedLevel(); if (prayer == currPrayer - 1) { wave.prayerDrain += 1; } } } @Subscribe public void onHitsplatApplied(HitsplatApplied event) { Actor target = event.getActor(); Hitsplat hitsplat = event.getHitsplat(); if (!isInInferno()) { return; } if (!hitsplat.isMine()) { return; } Wave wave = GetCurrentWave(); if (target == client.getLocalPlayer()) { // NPC did damage to the player if (hitsplat.getHitsplatType() == Hitsplat.HitsplatType.DAMAGE_ME) { wave.damageTaken += hitsplat.getAmount(); } return; } else { // Player did damage to an NPC if (hitsplat.getHitsplatType() == Hitsplat.HitsplatType.DAMAGE_ME) { wave.damageDealt += hitsplat.getAmount(); } } if (lastSpecTarget != null && lastSpecTarget != target) { return; } if (!(target instanceof NPC)) { return; } // BP spec hits 2 (bp speed) + 1 (delay) ticks after varbit changes if (specialWeapon == SpecialWeapon.TOXIC_BLOWPIPE) { if (client.getTickCount() != lastSpecTick + 3) { return; } } boolean wasSpec = lastSpecTarget != null; lastSpecTarget = null; if (wasSpec && specialWeapon != null) { UpdateCounter(specialWeapon, hitsplat.getAmount()); } } @Subscribe public void onNpcSpawned(NpcSpawned event) { final NPC npc = event.getNpc(); final Actor npcActor = event.getActor(); final WorldPoint spawnTile = npcActor.getWorldLocation(); final int npcId = npc.getId(); if (!isInInferno()) { return; } // ROCKY_SUPPORT is the normal pillar id; ROCKY_SUPPORT_7710 spawns as a pillar falls if (npcId == NpcID.ROCKY_SUPPORT || npcId == NpcID.ROCKY_SUPPORT_7710) { return; } // We'll ignore nibblers and jads, and zuk spawns off the map if (npcId == NpcID.JALNIB || npcId == NpcID.JALTOKJAD || npcId == NpcID.TZKALZUK) { return; } // We only want the original wave spawn, not minions or mager respawns if (GetCurrentWave().WaveTime() > 1 * 1000) { return; } waveHistory.AddSpawn(spawnTile, npc); } @Subscribe public void onChatMessage(ChatMessage event) { Matcher matcher; final String message = event.getMessage(); if (event.getType() != ChatMessageType.SPAM && event.getType() != ChatMessageType.GAMEMESSAGE) { return; } if (!isInInferno()) { return; } Wave wave = GetCurrentWave(); if (WaveTimer.DEFEATED_MESSAGE.matcher(message).matches()) { waveTimer.Pause(); removeWaveTimer(); wave.Finished(true); panel.updateWave(wave); if (config.saveWaveTimes()) { waveHistoryWriter.toFile( client.getLocalPlayer().getName(), waveHistory.CSVName(false), waveHistory.ToCSV(false) ); } if (config.saveSplitTimes()) { waveHistoryWriter.toFile( client.getLocalPlayer().getName(), waveHistory.CSVName(true), waveHistory.ToCSV(true) ); } return; } matcher = WaveTimer.COMPLETE_MESSAGE.matcher(message); if (matcher.find()) { // In case we ever update the filename (or anything else) to use KC int killCount = Integer.parseInt(matcher.group(1)); log.debug("Parsed Killcount: {}", killCount); waveTimer.Pause(); removeWaveTimer(); wave.Finished(false); panel.updateWave(wave); if (config.saveWaveTimes()) { waveHistoryWriter.toFile( client.getLocalPlayer().getName(), waveHistory.CSVName(false), waveHistory.ToCSV(false) ); } if (config.saveSplitTimes()) { waveHistoryWriter.toFile( client.getLocalPlayer().getName(), waveHistory.CSVName(true), waveHistory.ToCSV(true) ); } return; } if (WaveTimer.PAUSED_MESSAGE.matcher(message).find()) { waveTimer.Pause(); wave.Finished(false); return; } if (WaveTimer.WAVE_COMPLETE_MESSAGE.matcher(message).find()) { wave.Finished(false); if (config.waveTimes()) { final String waveMessage = new ChatMessageBuilder() .append(ChatColorType.HIGHLIGHT) .append("Wave Completed in: " + wave.WaveTimeString()) .build(); chatMessageManager.queue( QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(waveMessage) .build()); } } matcher = WaveTimer.WAVE_MESSAGE.matcher(message); if (matcher.find()) { int waveId = Integer.parseInt(matcher.group(1)); // TODO: Does the in-game timer reset to 6 seconds if you force log on wave 1? if (waveId == 1 || waveTimer == null) { createWaveTimer(); } else if (waveTimer != null && waveTimer.IsPaused()) { waveTimer.Resume(); if (wave.forceReset) { wave.ReinitWave(); return; } } waveHistory.NewWave(waveId, waveTimer.SplitTime()); wave = GetCurrentWave(); panel.addWave(wave); if (config.splitTimes() && wave.IsSplit()) { final ChatMessageBuilder chatMessageBuilder = new ChatMessageBuilder() .append(ChatColorType.HIGHLIGHT) .append("Wave Split: " + waveTimer.GetTime()); if (config.showTargetSplitTimes()) { chatMessageBuilder.append(waveSplits.GoalDifference(wave)); } final String splitMessage = chatMessageBuilder.build(); chatMessageManager.queue( QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(splitMessage) .build()); } if (config.predictedCompletionTime() && wave.IsSplit()) { wave.predictedTime = waveSplits.PredictedTime(wave); final String predictedMessage = new ChatMessageBuilder() .append(ChatColorType.HIGHLIGHT) .append("Predicted Time: " + wave.PredictedTimeString()) .build(); chatMessageManager.queue( QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(predictedMessage) .build()); } } } @Subscribe public void onConfigChanged(ConfigChanged event) { if (!event.getGroup().equals(CONFIG_GROUP)) { return; } if (event.getKey().equals(HIDE_KEY)) { if (isInInferno() || !config.hide()) { clientToolbar.addNavigation(navButton); } else { clientToolbar.removeNavigation(navButton); } } if (event.getKey().equals(TIMER_KEY)) { if (config.waveTimer() && waveTimer != null) { infoBoxManager.addInfoBox(waveTimer); } else { infoBoxManager.removeInfoBox(waveTimer); } } if (event.getKey().equals(SPECIAL_KEY)) { if (config.specialCounter()) { for (SpecialWeaponStats counter : specialCounter) { if (counter != null) { infoBoxManager.addInfoBox(counter); } } } else { for (SpecialWeaponStats counter : specialCounter) { if (counter != null) { infoBoxManager.removeInfoBox(counter); } } } } if (event.getKey().equals(OVERLAY_KEY)) { if (config.statsOverlay()) { overlayManager.add(statsOverlay); } else { overlayManager.remove(statsOverlay); } } waveSplits.UpdateTargetSplits(); } public Wave GetCurrentWave() { if (waveHistory.waves.isEmpty()) { return null; } return waveHistory.CurrentWave(); } private SpecialWeapon usedSpecialWeapon() { ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT); if (equipment == null) { return null; } Item weapon = equipment.getItem(EquipmentInventorySlot.WEAPON.getSlotIdx()); if (weapon == null) { return null; } for (SpecialWeapon specialWeapon : SpecialWeapon.values()) { if (specialWeapon.getItemID() == weapon.getId()) { return specialWeapon; } } return null; } private void UpdateCounter(SpecialWeapon specialWeapon, int hit) { SpecialWeaponStats counter = specialCounter[specialWeapon.ordinal()]; if (counter == null) { counter = new SpecialWeaponStats(client, itemManager.getImage(specialWeapon.getItemID()), this, specialWeapon); specialCounter[specialWeapon.ordinal()] = counter; if (config.specialCounter()) { infoBoxManager.addInfoBox(counter); } } counter.addHits(hit, prevSpecHealth, currSpecHealth, prevSpecPrayer, currSpecPrayer, config.effectiveRestoration()); } private void removeCounters() { for (int i = 0; i < specialCounter.length; ++i) { SpecialWeaponStats counter = specialCounter[i]; if (counter != null) { infoBoxManager.removeInfoBox(counter); specialCounter[i] = null; } } } private void createWaveTimer() { // The first wave message of the inferno comes six seconds after the in-game timer starts counting waveTimer = new WaveTimer( itemManager.getImage(INFERNAL_CAPE), this, Instant.now().minus(Duration.ofSeconds(6)), null ); if (config.waveTimer()) { infoBoxManager.addInfoBox(waveTimer); } } private void removeWaveTimer() { infoBoxManager.removeInfoBox(waveTimer); } public boolean isInInferno() { return client.getMapRegions() != null && ArrayUtils.contains(client.getMapRegions(), INFERNO_REGION_ID); } public boolean isInMorUlRek() { if (client.getMapRegions() == null) { return false; } int[] currentMapRegions = client.getMapRegions(); // Verify that all regions exist in MOR_UL_REK_REGIONS for (int region : currentMapRegions) { if (!MOR_UL_REK_REGION_IDS.contains(region)) { return false; } } return true; } public boolean isInVoid() { if (client.getMapRegions() == null) { return false; } int[] currentMapRegions = client.getMapRegions(); for (int region : currentMapRegions) { if (!VOID_REGION_IDS.contains(region)) { return false; } } return true; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package legaltime.view.model; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.event.TableModelEvent; import javax.swing.table.AbstractTableModel; import legaltime.LegalTimeApp; import legaltime.model.ClientBean; import legaltime.model.FollowupBean; import legaltime.model.FollowupManager; import legaltime.model.exception.DAOException; import legaltime.modelsafe.EasyLog; /** * * @author bmartin */ public class FollowupTableModelAbbrev extends AbstractTableModel { private String[] columnNames ={"Due Date", "Description"}; private Class[] columnTypes={java.util.Date.class, String.class}; private boolean[] isEditable ={false,false}; //TODO makeDate editiable by adding effective Date to private FollowupManager followupManager; private FollowupBean[] followupBeans; private EasyLog easyLog; private LegalTimeApp legalTimeApp; public Object getValueAt(int row, int col) { if (followupBeans.length ==0){ return null; } switch (col){ //TODDO add effective Date to ClientAccount Register case 0: return followupBeans[row].getDueDt(); case 1: return followupBeans[row].getDescription(); default: return ""; } } public void setList(FollowupBean[] followupBeans_){ followupBeans=followupBeans_; } public FollowupTableModelAbbrev(){ followupManager = FollowupManager.getInstance(); easyLog = EasyLog.getInstance(); legalTimeApp = (LegalTimeApp) LegalTimeApp.getInstance(); } public int getRowCount() { try{ return followupBeans.length; }catch (Exception e){ return 0; } } public int getColumnCount() { return columnNames.length; } @Override public String getColumnName(int colIndex){ return columnNames[colIndex]; } @Override public Class getColumnClass(int col){ return columnTypes[col]; } @Override public boolean isCellEditable(int row, int col){ return isEditable[col]; } // @Override // public void setValueAt(Object value, int row, int col) { // try{ // switch(col){ // case 0: followupBeans[row].setDueDt((java.util.Date)value); // break; // case 1: followupBeans[row].setClientId(((ClientBean)value).getClientId()); // break; // case 2: followupBeans[row].setDescription(value.toString()); // break; // case 3: followupBeans[row].setOpenedDate((java.util.Date)value); // break; // case 4: followupBeans[row].setClosedDt((java.util.Date)value); // break; // default: System.err.println("Out of bounds" + getClass().getName()); // } // try { // followupManager.save(followupBeans[row]); // legalTimeApp.setLastActionText("Updated Followup Item Register"); // // } catch (DAOException ex) { // Logger.getLogger(FollowupTableModelAbbrev.class.getName()).log(Level.SEVERE, null, ex); // easyLog.addEntry(EasyLog.SEVERE,"Error Updating Client Account Register" // ,getClass().getName(),ex); // } // fireTableChanged(new TableModelEvent(this)); // }catch(Exception e){ // easyLog.addEntry(EasyLog.SEVERE,"Error Updating Client Account Register" // ,getClass().getName(),e); // } // // } /** * @return the FollowupBeans */ public FollowupBean[] getFollowupBeans() { return followupBeans; } public int getFollowupId(int row_) { try{ return followupBeans[row_].getFollowupId(); }catch(NullPointerException e){ return -1; } } public FollowupBean getBeanByRow(int row){ return followupBeans[row]; } /** * @return the billRates */ }
package server; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; import com.github.mustachejava.MustacheFactory; import util.HttpStatus; /** * * Inspired by HttpServletResponse with an additional method: sendView * which allows to render views server side as a replacement for JSPs * Rendering is done using mustache templating engine. * */ public class HttpResponse { private PrintWriter writer; private boolean setHeaderIgnore; private boolean setStatusIgnore; public HttpResponse(OutputStream os) { writer = new PrintWriter(os,false); setHeaderIgnore = false; } private void setFirstLine(int status) { writer.println("HTTP/1.0 "+ status + " " + new HttpStatus().getText(status)); writer.flush(); setStatusIgnore = true; } public void sendError(int sc) { if(!setStatusIgnore) setFirstLine(sc); else System.out.println("warning: cannot send error code after setting status or header"); } public void setHeader(String name, String value) { if(!setStatusIgnore) { setFirstLine(200); // default : 200 OK } if(! setHeaderIgnore) { writer.println(name + ":" + " " + value); }else { System.out.println("warning: cannot set header after writing to body"); } } public void setStatus(int statusCode) { if(!setStatusIgnore) setFirstLine(statusCode); } public PrintWriter getWriter() { setFirstLine(200); setHeaderIgnore = true; writer.println(""); // end header return writer; } /** * * renders a view server side and then sends it in the response body * * @param name: the name of the view to be rendered, by default the view will be searched in the * web-content directory * @param o: parameter passed to the view * @throws IOException * */ public void sendView(String name, Object o) throws IOException { setHeader("Content-Type", "text/html"); MustacheFactory mf = new DefaultMustacheFactory(); Mustache mustache = mf.compile(Config.TEMPLATES_PATH + "/" + name); mustache.execute(getWriter(), o).flush(); } }
/* * Created on Aug 16, 2012 */ package com.mattwhitlock.ognl; /** * @author Matt Whitlock */ public class IllegalAssignmentException extends OgnlException { private static final long serialVersionUID = 1L; public IllegalAssignmentException(Expression expression, String message) { super(expression, message); } public IllegalAssignmentException(Expression expression, Throwable cause) { super(expression, cause); } public IllegalAssignmentException(Expression expression, String message, Throwable cause) { super(expression, message, cause); } }
package com.bytedance.sandboxapp.c.a.b.h; import com.bytedance.sandboxapp.a.a.c.k; import com.bytedance.sandboxapp.c.a.b; import com.bytedance.sandboxapp.protocol.service.h.c; import d.f.b.l; public final class a extends k { public a(b paramb, com.bytedance.sandboxapp.a.a.d.a parama) { super(paramb, parama); } public final void handleApi(com.bytedance.sandboxapp.protocol.service.api.entity.a parama) { l.b(parama, "apiInvokeInfo"); ((c)((com.bytedance.sandboxapp.c.a.a.a)this).context.getService(c.class)).loginHostApp(new a(this)); } public static final class a implements c.a { a(a param1a) {} public final void a() { this.a.callbackOk(); } public final void a(String param1String) { l.b(param1String, "failReason"); this.a.a(param1String); } public final void b() { this.a.callbackAppInBackground(); } public final void c() { this.a.callbackFeatureNotSupport(); } } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\bytedance\sandboxapp\c\a\b\h\a.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.mahesh.android; import java.util.ArrayList; import java.util.concurrent.CopyOnWriteArrayList; import org.andengine.engine.camera.Camera; import org.andengine.engine.handler.IUpdateHandler; import org.andengine.engine.options.EngineOptions; import org.andengine.engine.options.ScreenOrientation; import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.andengine.entity.primitive.Rectangle; import org.andengine.entity.scene.CameraScene; import org.andengine.entity.scene.IOnAreaTouchListener; import org.andengine.entity.scene.IOnSceneTouchListener; import org.andengine.entity.scene.ITouchArea; import org.andengine.entity.scene.Scene; import org.andengine.entity.scene.background.Background; import org.andengine.entity.scene.menu.MenuScene; import org.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener; import org.andengine.entity.scene.menu.item.IMenuItem; import org.andengine.entity.scene.menu.item.SpriteMenuItem; import org.andengine.entity.shape.Shape; import org.andengine.entity.sprite.AnimatedSprite; import org.andengine.entity.sprite.Sprite; import org.andengine.entity.sprite.batch.SpriteBatch; import org.andengine.entity.util.FPSLogger; import org.andengine.extension.physics.box2d.PhysicsConnector; import org.andengine.extension.physics.box2d.PhysicsFactory; import org.andengine.extension.physics.box2d.PhysicsWorld; import org.andengine.extension.physics.box2d.util.Vector2Pool; import org.andengine.input.sensor.acceleration.AccelerationData; import org.andengine.input.sensor.acceleration.IAccelerationListener; import org.andengine.input.touch.TouchEvent; import org.andengine.opengl.texture.TextureOptions; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.andengine.opengl.texture.bitmap.BitmapTexture; import org.andengine.opengl.texture.region.ITextureRegion; import org.andengine.opengl.texture.region.TiledTextureRegion; import org.andengine.opengl.vbo.VertexBufferObjectManager; import org.andengine.ui.activity.SimpleBaseGameActivity; import org.andengine.util.time.TimeConstants; import android.content.Intent; import android.hardware.SensorManager; import android.opengl.GLES20; import android.os.AsyncTask; import android.util.Log; import android.view.KeyEvent; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; public class CalliardsActivity extends SimpleBaseGameActivity implements IAccelerationListener, IOnSceneTouchListener, IOnAreaTouchListener, IOnMenuItemClickListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 360; private static final int CAMERA_HEIGHT = 240; private final float MAX_DISTANCE_FLING = 40f; private final float MAX_VELOCITY_CONST = 250f; private final float DEFAULT_VELOCITY = 50f; private static final int MAX_KILLER_COINS = 50; protected static final int MENU_RESET = 0; protected static final int MENU_QUIT = MENU_RESET + 1; protected static final int MENU_PAUSE = MENU_RESET + 2; // =========================================================== // Fields // =========================================================== protected Camera mCamera; protected boolean mGameRunning; private static Sprite face; private static Body body; private static CopyOnWriteArrayList<Shape> coinSprites = new CopyOnWriteArrayList<Shape>(); private static CopyOnWriteArrayList<Shape> killerCoinSprites = new CopyOnWriteArrayList<Shape>(); private BitmapTextureAtlas mBitmapTextureAtlas; private BitmapTexture mBitmapTexture; private ITextureRegion mBoxFaceTextureRegion; private ITextureRegion mCoin1TextureRegion; private ITextureRegion mCoin2TextureRegion; private ITextureRegion mCoin3TextureRegion; private ITextureRegion mCoin4TextureRegion; private ITextureRegion mCoin5TextureRegion; private ITextureRegion mCoin6TextureRegion; private ITextureRegion mCoin7TextureRegion; private ITextureRegion mCoin8TextureRegion; private ITextureRegion mCoin9TextureRegion; private ITextureRegion kCoinTextureRegion; private ArrayList<ITextureRegion> mCircleFaceTextureRegion = new ArrayList<ITextureRegion>(); private int mFaceCount = 0; private int mCoinCount = 0; private PhysicsWorld mPhysicsWorld; private float mGravityX; private float mGravityY; private Scene mScene; protected MenuScene mMenuScene; private CameraScene mPauseScene; private BitmapTextureAtlas mMenuTexture; protected ITextureRegion mMenuResetTextureRegion; protected ITextureRegion mMenuQuitTextureRegion; protected ITextureRegion mPausedTextureRegion; protected IUpdateHandler mHandler; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public EngineOptions onCreateEngineOptions() { Toast.makeText(this, "Touch the screen to add Stryker. Swipe to give direction.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera); } @Override public void onCreateResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 32, 320, TextureOptions.BILINEAR); //3rd param should correspond to number of sprites.. 2nd param is width of sprite. this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); // 64x32 this.mCoin1TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_circle_0.png", 0, 32); // 64x32 this.mCoin2TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_circle_1.png", 0, 64); // 64x32 this.mCoin3TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_circle_2.png", 0, 96); // 64x32 this.mCoin4TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_circle_3.png", 0, 128); // 64x32 this.kCoinTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "killer.png", 0, 160); // 64x32 this.mCoin5TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_circle_4.png", 0, 192); // 64x32 this.mCoin6TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_circle_5.png", 0, 224); // 64x32 this.mCoin7TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_circle_6.png", 0, 256); // 64x32 this.mCoin8TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_circle_7.png", 0, 288); // 64x32 //this.mCoin9TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_circle_8.png", 0, 320); // 64x32 this.mBitmapTextureAtlas.load(); this.mCircleFaceTextureRegion.add(mCoin1TextureRegion); this.mCircleFaceTextureRegion.add(mCoin2TextureRegion); this.mCircleFaceTextureRegion.add(mCoin3TextureRegion); this.mCircleFaceTextureRegion.add(mCoin4TextureRegion); this.mCircleFaceTextureRegion.add(mCoin5TextureRegion); this.mCircleFaceTextureRegion.add(mCoin6TextureRegion); this.mCircleFaceTextureRegion.add(mCoin7TextureRegion); this.mCircleFaceTextureRegion.add(mCoin8TextureRegion); //this.mCircleFaceTextureRegion.add(mCoin9TextureRegion); this.mMenuTexture = new BitmapTextureAtlas(this.getTextureManager(), 256, 192, TextureOptions.BILINEAR); this.mMenuResetTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mMenuTexture, this, "menu_reset.png", 0, 0); this.mMenuQuitTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mMenuTexture, this, "menu_quit.png", 0, 50); this.mPausedTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mMenuTexture, this, "home.png", 0, 100); this.mMenuTexture.load(); } @Override public Scene onCreateScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.createMenuScene(); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); this.mScene = new Scene(); this.mScene.setBackground(new Background(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); final VertexBufferObjectManager vertexBufferObjectManager = this.getVertexBufferObjectManager(); final Rectangle ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2, vertexBufferObjectManager); final Rectangle roof = new Rectangle(0, 0, CAMERA_WIDTH, 2, vertexBufferObjectManager); final Rectangle left = new Rectangle(0, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager); final Rectangle right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); this.mScene.setOnAreaTouchListener(this); this.mGameRunning = true; /* Important when re-launching Game play. * */ if(face!=null){ this.mScene.detachChild(face); face.dispose(); face = null; } if(coinSprites.size() > 0) coinSprites.removeAll(coinSprites); if(killerCoinSprites.size() > 0) coinSprites.removeAll(killerCoinSprites); //************************************* // Add numbered coins. addCoins(); /* The actual collision-checking. */ this.mHandler = new IUpdateHandler() { @Override public void reset() { } @Override public void onUpdate(final float pSecondsElapsed) { int index = 0; for(final Shape spriteA : coinSprites){ if(spriteA.collidesWith(face) ) { if(index==0){ //Toast.makeText(CalliardsActivity.this, "Collision Detected with chld:", Toast.LENGTH_LONG).show(); Log.i("Collision","Collision Detected:"+pSecondsElapsed); removeCoin((Sprite)spriteA); coinSprites.remove(spriteA); if(mCoinCount > 0) mCoinCount--; } else { //Add Killer coin and restrict it to MAX 50. if(killerCoinSprites.size() < MAX_KILLER_COINS){ FixtureDef objectFixtureDef3 = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); Sprite killer_coin = new Sprite(200, 200, kCoinTextureRegion, CalliardsActivity.this.getVertexBufferObjectManager()); Body body = PhysicsFactory.createBoxBody(CalliardsActivity.this.mPhysicsWorld, killer_coin, BodyType.DynamicBody, objectFixtureDef3); CalliardsActivity.this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(killer_coin, body, true, true)); //face.animate(new long[]{200,200}, 0, 1, true); killer_coin.setUserData(body); CalliardsActivity.this.mScene.registerTouchArea(killer_coin); CalliardsActivity.this.mScene.attachChild(killer_coin); killerCoinSprites.add(killer_coin); } } } index++; } /* for(final Shape spriteK : killerCoinSprites){ if(!face.isDisposed() ){ Log.i("CalliardsActivity","Face is not null"); if(spriteK.collidesWith(face)){ Log.i("CalliardsActivity","Striker collision"); CalliardsActivity.this.mGameRunning = false; break; } } } */ } }; this.mScene.registerUpdateHandler(this.mHandler); return this.mScene; } @Override public boolean onAreaTouched( final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea,final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { /* final AnimatedSprite face = (AnimatedSprite) pTouchArea; Vector2 touchVector = new Vector2(pTouchAreaLocalX, pTouchAreaLocalY); //this.jumpFace(face,touchVector); float distance = getDistance(Xlocal, Ylocal, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); long timeUp = System.currentTimeMillis(); //shootBall(face,pSceneTouchEvent.getX(),pSceneTouchEvent.getY(),distance,(float) (timeUp - timeDown) / TimeConstants.MILLISECONDS_PER_SECOND); return true; */ } return false; } private float Xlocal = 0.0f; private float Ylocal = 0.0f; private long timeDown = 0; @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); Xlocal = pSceneTouchEvent.getX(); Ylocal = pSceneTouchEvent.getY(); return true; } else if (pSceneTouchEvent.isActionUp()) { float X = (pSceneTouchEvent.getX() - Xlocal); float Y = (pSceneTouchEvent.getY() - Ylocal); float distance = getDistance(Xlocal, Ylocal, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); if( distance >= MAX_DISTANCE_FLING){ long timeUp = System.currentTimeMillis(); System.out.println("Time up is "+timeUp); Log.i("Coin Count","c:"+this.mCoinCount+"sc:"+coinSprites.size()); // shootBall(face,X, Y, distance, (float) (timeUp - timeDown) / TimeConstants.MILLISECONDS_PER_SECOND); shootBall(face,X, Y, distance, (float) (timeUp - timeDown) / TimeConstants.SECONDS_PER_MINUTE); } } } return false; } @Override public void onAccelerationAccuracyChanged(final AccelerationData pAccelerationData) { } @Override public void onAccelerationChanged(final AccelerationData pAccelerationData) { this.mGravityX = pAccelerationData.getX(); this.mGravityY = pAccelerationData.getY(); final Vector2 gravity = Vector2Pool.obtain(this.mGravityX, this.mGravityY); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerationSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerationSensor(); } @Override public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) { if(pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) { if(this.mScene.hasChildScene()) { /* Remove the menu and reset it. */ this.mMenuScene.back(); } else { /* Attach the menu. */ this.mScene.setChildScene(this.mMenuScene, false, true, true); } return true; } else { return super.onKeyDown(pKeyCode, pEvent); } } @Override public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) { switch(pMenuItem.getID()) { case MENU_RESET: /* Restart the animation. */ this.mScene.reset(); /* Remove the menu and reset it. */ this.mScene.clearChildScene(); this.mMenuScene.reset(); return true; case MENU_QUIT: /* End Activity. */ finish(); return true; case MENU_PAUSE: /* Return to Main Activity */ Intent intent = new Intent(); intent.setClass(CalliardsActivity.this, MainActivity.class); startActivity(intent); return true; default: return false; } } // =========================================================== // Methods // =========================================================== protected void createMenuScene() { this.mMenuScene = new MenuScene(this.mCamera); final SpriteMenuItem resetMenuItem = new SpriteMenuItem(MENU_RESET, this.mMenuResetTextureRegion, this.getVertexBufferObjectManager()); resetMenuItem.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); this.mMenuScene.addMenuItem(resetMenuItem); final SpriteMenuItem quitMenuItem = new SpriteMenuItem(MENU_QUIT, this.mMenuQuitTextureRegion, this.getVertexBufferObjectManager()); quitMenuItem.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); this.mMenuScene.addMenuItem(quitMenuItem); final SpriteMenuItem pauseMenuItem = new SpriteMenuItem(MENU_PAUSE, this.mPausedTextureRegion, this.getVertexBufferObjectManager()); quitMenuItem.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); this.mMenuScene.addMenuItem(pauseMenuItem); this.mMenuScene.buildAnimations(); this.mMenuScene.setBackgroundEnabled(false); this.mMenuScene.setOnMenuItemClickListener(this); } private void addFace(final float pX, final float pY) { this.mFaceCount++; final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); if(this.mFaceCount <= 1){ face = new Sprite(pX, pY, this.mBoxFaceTextureRegion, this.getVertexBufferObjectManager()); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); //face.animate(new long[]{200,200}, 0, 1, true); face.setUserData(body); this.mScene.registerTouchArea(face); this.mScene.attachChild(face); } } private void addCoins() { FixtureDef objectFixtureDef2 = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); for(int i=0;i<this.mCircleFaceTextureRegion.size();i++){ this.mCoinCount++; float pX = (float )Math.random() * (250 - 20) + 20; float pY = (float )Math.random() * (300 - 20) + 20; pX = CAMERA_WIDTH/2; pY = CAMERA_HEIGHT/2; Log.i("Coords:"," x:"+pX+" y:"+pY +mCircleFaceTextureRegion.size()); Sprite coin_face = new Sprite(pX, pY, this.mCircleFaceTextureRegion.get(i), this.getVertexBufferObjectManager()); Body body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, coin_face, BodyType.DynamicBody, objectFixtureDef2); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(coin_face, body, true, true)); //face.animate(new long[]{200,200}, 0, 1, true); coin_face.setUserData(body); this.mScene.registerTouchArea(coin_face); this.mScene.attachChild(coin_face); coinSprites.add(coin_face); } } private boolean removeCoin(Sprite coin){ if(coin == null) { return false; } this.mScene.detachChild(coin); coin.dispose(); this.mPhysicsWorld.destroyBody((Body)coin.getUserData()); // Remove from Physics world. coin = null; Log.i("Count of bodies:",""+this.mPhysicsWorld.getBodyCount()); return true; } private void jumpFace(final AnimatedSprite face,Vector2 newPos) { /* final Body faceBody = (Body)face.getUserData(); final Vector2 velocity = Vector2Pool.obtain(this.mGravityX * -50, this.mGravityY * -50); faceBody.setLinearVelocity(velocity); Vector2Pool.recycle(velocity); */ final Body faceBody = (Body)face.getUserData(); Vector2 curPos = faceBody.getWorldCenter(); Vector2 diff = newPos.sub(curPos); final float theta = (float)(diff.len() + Math.PI/2); final float r = 1; final float deltax = (float) (r*Math.cos(theta)); final float deltay = (float) (r*Math.sin(theta)); final Vector2 velocity = Vector2Pool.obtain(deltax * 20, deltay * 20); faceBody.setLinearVelocity(velocity); Vector2Pool.recycle(velocity); } private void shootBall(final Sprite face,final float pX, final float pY, final float pDistance, final float pTime) { System.out.println("Time Final seconds "+pTime); final Body faceBody = (Body)face.getUserData(); float angleRad =(float)Math.atan2(pY, pX); float velocity =(float) ((float) this.getVelocity(pTime) * 0.3);//(pDistance * 12.5f) / 100f; if(faceBody != null){ float Vx = velocity * (float)Math.cos(angleRad); float Vy = velocity * (float)Math.sin(angleRad); faceBody.applyLinearImpulse(new Vector2(Vx,Vy), faceBody.getWorldCenter()); faceBody.setAngularDamping(0.8f); //to decrease velocity slowly. no linear no floaty :) faceBody.setLinearDamping(0.5f); faceBody.applyTorque(100f); } } private float getDistance(float x1, float y1, float x2, float y2){ float X2_ = (float)Math.pow(x2 - x1, 2); float Y2_ = (float)Math.pow(y2 - y1, 2); float distance = (float)Math.sqrt(X2_ + Y2_); return distance; } private float getVelocity(float pTime) { float velocity = MAX_VELOCITY_CONST - (pTime * 100f); if (velocity < DEFAULT_VELOCITY) { velocity = DEFAULT_VELOCITY; } System.out.println("velocity "+velocity); return velocity; } private void gameOver(){ //Toast.makeText(CalliardsActivity.this, "Game Over! Better luck next time!", Toast.LENGTH_SHORT).show(); //this.mScene.clearEntityModifiers(); //this.mEngine.clearUpdateHandlers(); finish(); } @Override public void onDestroy(){ super.onDestroy(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
package com.aplayer.hardwareencode; import android.media.MediaCodec; import android.os.Build; import com.aplayer.aplayerandroid.Log; import com.aplayer.hardwareencode.VideoEncoder.COLOR_FORMAT; import com.aplayer.hardwareencode.module.RawFrame; import com.aplayer.hardwareencode.utils.EncodeUtils; import java.io.IOException; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.aplayer.hardwareencode.Muxer.MUXER_FORMAT.MUXER_MP4; import static com.aplayer.hardwareencode.module.EncoderConstant.*; /** * Created by LZ on 2016/10/21. */ public class HardwareEncoder { private static final String TAG = "APlayerAndroid"; private String mEncodeOutpath; private Muxer.MUXER_FORMAT mMuxerFmt; private Muxer mMuxer = null; private Map<Integer, EncoderBase> mExternalIDToEncoderMap = new HashMap<Integer, EncoderBase>(); private int mTrackAllocID = 0; private double mVideoFrameRate = 25; private int mVideoBitRate = 2000 * 1000; private int mIFrameInterval = 5; // 秒 private boolean mEncoding = false; private Object mLock = new Object(); private int mVideoWidth = 0; private int mVideoHeight = 0; public HardwareEncoder(){ this.mMuxerFmt = MUXER_MP4; } public int start(){ Log.i(TAG,"encoder start"); if(null != mMuxer){ Log.e(TAG, "encode is running..."); return -1; } if(!initMuxer()){ Log.e(TAG, "muxer init failed"); return -1; } for (Map.Entry<Integer, EncoderBase> entry : mExternalIDToEncoderMap.entrySet()) { EncoderBase encoder = entry.getValue(); if (null == encoder) { continue; } encoder.start(); } mEncoding = true; return 1; } public int close(){ Log.i(TAG,"encoder stop"); synchronized (mLock){ mEncoding = false; for (Map.Entry<Integer, EncoderBase> entry : mExternalIDToEncoderMap.entrySet()) { EncoderBase encoder = entry.getValue(); if (null == encoder) { continue; } encoder.stopEncode(); } mExternalIDToEncoderMap.clear(); Log.i(TAG,"encoder releaseMuxer s"); releaseMuxer(); Log.i(TAG,"encoder stop leave"); } mVideoWidth = 0; mVideoHeight = 0; mVideoBitRate = 1024 * 1024; return 1; } public int setOutFileName(String outFileName){ mEncodeOutpath = outFileName; return 1; } public int addVideoTrack(int width,int height, int encodeFmt, double frameRate){ int videoWidth = width; int videoHeight = height; if(COLOR_FORMAT.COLOR_FormatSurface == encodeFmt && mVideoWidth != 0){ videoWidth = mVideoWidth; videoHeight = videoWidth * height / width; } // else{ // return _addVideoTrack(VideoEncoder.ENCODE_FORMAT.VIDEO_ACV,COLOR_FORMAT.YUV420P,width,height,mVideoFrameRate,mVideoBitRate,mIFrameInterval); // } mVideoFrameRate = frameRate; return _addVideoTrack(VideoEncoder.ENCODE_FORMAT.VIDEO_ACV,encodeFmt,videoWidth,videoHeight,mVideoFrameRate,mVideoBitRate,mIFrameInterval); } public int addVideoTrack(int width,int height,int encodeFmt, double frameRate, int bitRate){ mVideoFrameRate = frameRate; mVideoBitRate = bitRate; return _addVideoTrack(VideoEncoder.ENCODE_FORMAT.VIDEO_ACV, encodeFmt,width,height,frameRate,bitRate,mIFrameInterval); } public int addAudioTrack(int channelCount, int sampleRate, int bitRate){ bitRate = 48000; return _addAudioTrack(AudioEncoder.ENCODE_FORMAT.AUDIO_AAC,channelCount,sampleRate,bitRate); } public int addSubTrack(){ return 0; } public int putRawData(int texture,long presentationTime){ Log.i(TAG,"putRawData enter trackIndex " + " presentationTime " + presentationTime); synchronized (mLock){ if(!mEncoding){ return ENCODE_NOT_STARTING; } VideoEncoderSurfaceInput videoEncoderSurface = getVideoSurfaceEncoder(); if(videoEncoderSurface == null){ return -1; } return videoEncoderSurface.renderTexture(texture,presentationTime)? 0 : -1; } } public int putRawData(int trackIndex, ByteBuffer rawData, int pts){ Log.i(TAG,"putRawData enter trackIndex " + trackIndex + " rawData size " + rawData.limit() + " pts " + pts); if(!mEncoding){ return ENCODE_NOT_STARTING; } EncoderBase encoder = mExternalIDToEncoderMap.get(trackIndex); if(null == encoder) { return TRACK_INDEX_INVALIDATE; } byte[] copyData = null; if(null != rawData && rawData.limit() > 0){ copyData = new byte[rawData.limit()]; rawData.get(copyData); } return encoder.feedRewData(new RawFrame(copyData,pts * 1000L,trackIndex)); } public int setVideoWidth(int width){ if(mEncoding){ return 0; } mVideoWidth = width; return 1; } public int setVideoHeight(int height){ if(mEncoding){ return 0; } mVideoHeight = height; return 1; } public int setVideoBitRate(int bitRate){ if(mEncoding){ return 0; } mVideoBitRate = bitRate * 1024; return 1; } public boolean isEncoding(){ return mEncoding; } public Object getVideoEncodeCapability(){ // for (Map.Entry<Integer, EncoderBase> entry : mExternalIDToEncoderMap.entrySet()) { // EncoderBase encoder = entry.getValue(); // if (null == encoder) { // continue; // } // // if(encoder instanceof VideoEncoder){ // return ((VideoEncoder) encoder).getEncodeCapability(); // } // } // return null; if(Build.VERSION.SDK_INT < 18) { return null; } String mime = VideoEncoder.ENCODE_FORMAT.VIDEO_ACV.getValue(); MediaCodec mediaCodec = null; try { mediaCodec = EncodeUtils.createMediaCodecEncoder(mime); } catch (IOException e) { e.printStackTrace(); } if(null == mediaCodec) { return null; } else { return EncodeUtils.getEncodVieoeCapability(mediaCodec, mime); } } protected void putEncoderData(EncoderBase encoder,List<EncoderBase.EncodeFrame> encodeFrames){ if(mMuxer != null){ mMuxer.putMuxData(encoder,encodeFrames); } } protected int getTrackNum(){ synchronized (mExternalIDToEncoderMap){ return mExternalIDToEncoderMap.size(); } } private int _addVideoTrack(VideoEncoder.ENCODE_FORMAT encodeFormat, int colorFormat, int width, int height, double frameRate, int bitrate , int IFrameInterval){ EncoderBase videoEncoder = null; if(colorFormat == COLOR_FORMAT.COLOR_FormatSurface){ videoEncoder = new VideoEncoderSurfaceInput(this,encodeFormat,width,height,frameRate,bitrate,IFrameInterval); }else{ videoEncoder = new VideoEncoder(this,encodeFormat,colorFormat,width,height,frameRate,bitrate,IFrameInterval); } if(videoEncoder.init()){ return addTrack(videoEncoder); } return -1; } private int _addAudioTrack(AudioEncoder.ENCODE_FORMAT encodeFormat, int channelCount, int sampleRate, int bitRate){ AudioEncoder audioEncoder = new AudioEncoder(this,encodeFormat, channelCount, sampleRate,bitRate); if(audioEncoder.init()){ return addTrack(audioEncoder); } return -1; } private int addTrack(EncoderBase encoder) { int trackID = -1; synchronized (this) { if(null != encoder && !mExternalIDToEncoderMap.containsValue(encoder)) { trackID = mTrackAllocID; mExternalIDToEncoderMap.put(trackID, encoder); mTrackAllocID++; } } return trackID; } public VideoEncoderSurfaceInput getVideoSurfaceEncoder(){ for (Map.Entry<Integer, EncoderBase> entry : mExternalIDToEncoderMap.entrySet()) { EncoderBase encoder = entry.getValue(); if (null == encoder) { continue; } if(encoder instanceof VideoEncoderSurfaceInput){ return (VideoEncoderSurfaceInput) encoder; } } return null; } private boolean initMuxer(){ if(mEncodeOutpath == null){ Log.e(TAG, "initMuxer: outpath is null"); return false; } mMuxer = new Muxer(this,mEncodeOutpath, mMuxerFmt); if(mMuxer.init()){ mMuxer.start(); return true; } return false; } private void releaseMuxer(){ if(null != mMuxer){ mMuxer.stopMux(); mMuxer = null; } } }
package com.github.emailtohl.integration.web.service.chat; import java.io.Serializable; import com.github.emailtohl.integration.web.cluster.ClusterEvent; /** * 聊天相关的事件 * @author HeLei */ public class ChatEvent extends ClusterEvent { private static final long serialVersionUID = -1620174996342472535L; private Chat chat; public ChatEvent(Serializable source) { super(source); } public ChatEvent(Serializable source, Chat chat) { super(source); this.chat = chat; } public Chat getChat() { return chat; } public void setChat(Chat chat) { this.chat = chat; } }
package com.kgitbank.spring.domain.account.controller; import java.sql.Date; import java.util.List; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import com.kgitbank.spring.domain.account.dto.Sessionkey; import com.kgitbank.spring.domain.account.service.AccountService; import com.kgitbank.spring.domain.account.service.GetIp; import com.kgitbank.spring.domain.account.service.LoginService; import com.kgitbank.spring.domain.follow.FollowDto; import com.kgitbank.spring.domain.follow.service.FollowService; import com.kgitbank.spring.domain.model.FollowVO; import com.kgitbank.spring.domain.model.LoginVO; import com.kgitbank.spring.domain.model.MemberVO; import com.kgitbank.spring.domain.myprofile.dto.ProfileDto; import com.kgitbank.spring.global.config.SessionConfig; import com.kgitbank.spring.global.util.SecurityPwEncoder; import lombok.extern.log4j.Log4j; @Controller @Log4j public class LoginController { @Autowired LoginService service; @Autowired SecurityPwEncoder encoder; @Autowired GetIp getip; @Autowired AccountService accService; @Autowired FollowService followService; @GetMapping(value = "/") public String main(HttpServletRequest req, HttpServletResponse rep, HttpSession session, Model model) { MemberVO loginMember = null; String doubleLogin = ""; Cookie[] cookies = req.getCookies(); String sessionId; // 로그인 세션이 있다면 home으로 이동시킴 String loginId = (String) session.getAttribute("user"); if(loginId != null) { System.out.println("이미 로그인한 상태!!"); int loginSeqId = accService.selectMemberById(loginId).getSeqId(); model.addAttribute("follows", followService.selectProfileOfFollow(loginSeqId)); List<FollowDto> topFiveFollows = followService.selectTop5Follows(); FollowVO vo = new FollowVO(); vo.setFollowerId(loginSeqId); for(FollowDto f : topFiveFollows) { vo.setFollowId(f.getSeqId()); f.setFollowed(followService.checkFollow(vo)); } log.info(topFiveFollows); model.addAttribute("topFiveFollows", topFiveFollows); return"/main/home"; } if(cookies != null) { for(Cookie cookie : cookies) { if(cookie.getName().equals("loginCookie") && cookie.getValue() != null) { sessionId=cookie.getValue(); System.out.println(sessionId); loginMember = service.checkUserWithSessionkey(sessionId); System.out.println(loginMember); if(loginMember != null) { doubleLogin = SessionConfig.getSessionidCheck("user", loginMember.getId()); session.setAttribute("user", loginMember.getId()); session.setAttribute("userProfile", loginMember.getImgPath()); // 프로필 이미지도 세션 영역에 추가 session.setAttribute("name", loginMember.getName()); LoginVO logvo = new LoginVO(); logvo.setMemberSeqId(loginMember.getSeqId()); logvo.setIp(getip.getIp(req)); service.loginHistory(logvo); if(doubleLogin != "") { Date sessionLimit = new Date(System.currentTimeMillis()); Sessionkey key = new Sessionkey(); key.setEmail(loginMember.getEmail()); key.setSessionId(session.getId()); key.setNext(sessionLimit); service.keepLogin(key); } model.addAttribute("follows", followService.selectProfileOfFollow(loginMember.getSeqId())); List<FollowDto> topFiveFollows = followService.selectTop5Follows(); FollowVO vo = new FollowVO(); vo.setFollowerId(loginMember.getSeqId()); for(FollowDto f : topFiveFollows) { vo.setFollowId(f.getSeqId()); f.setFollowed(followService.checkFollow(vo)); } log.info(topFiveFollows); model.addAttribute("topFiveFollows", topFiveFollows); return "/main/home"; } } } } return "account/login"; } @PostMapping(value = "/") public String mainsignin(MemberVO member, HttpSession session, Model model, HttpServletRequest req, HttpServletResponse rep) { String doubleLogin = ""; MemberVO loginMember = null; if(session.getAttribute("user") != null)session.removeAttribute("user"); loginMember = service.getLogin(member); if(loginMember != null) { if(!(encoder.matches(member.getPw(), loginMember.getPw()))) { loginMember = null; req.setAttribute("loginFailMsg", "입력한 아이디와 비밀번호가 일치하지 않습니다. <br>아이디 또는 비밀번호를 다시 한번 입력해 주세요."); } }else { req.setAttribute("loginFailId", "해당 아이디가 없습니다."); } log.info(loginMember); if(loginMember != null) { System.out.println("다시로그인??"); System.out.println("현재 세션 아이디" + session.getId()); doubleLogin = SessionConfig.getSessionidCheck("user", loginMember.getId()); session.setAttribute("user", loginMember.getId()); session.setAttribute("userProfile", loginMember.getImgPath()); // 프로필 이미지도 세션 영역에 추가 session.setAttribute("userName", loginMember.getName()); System.out.println(getip.getIp(req)); LoginVO logvo = new LoginVO(); logvo.setMemberSeqId(loginMember.getSeqId()); logvo.setIp(getip.getIp(req)); log.info(logvo); service.loginHistory(logvo); String check = req.getParameter("remember"); if(check != null) { Cookie newCookie = new Cookie("loginCookie", session.getId()); newCookie.setPath("/"); int amount = 60 * 60 * 24 * 7; newCookie.setMaxAge(amount); rep.addCookie(newCookie); Date sessionLimit = new Date(System.currentTimeMillis() + (1000*amount)); Sessionkey key = new Sessionkey(); key.setEmail(loginMember.getEmail()); key.setSessionId(session.getId()); key.setNext(sessionLimit); service.keepLogin(key); } if(doubleLogin != "") { Date sessionLimit = new Date(System.currentTimeMillis()); Sessionkey key = new Sessionkey(); key.setEmail(loginMember.getEmail()); key.setSessionId(session.getId()); key.setNext(sessionLimit); service.keepLogin(key); } model.addAttribute("follows", followService.selectProfileOfFollow(loginMember.getSeqId())); List<FollowDto> topFiveFollows = followService.selectTop5Follows(); FollowVO vo = new FollowVO(); vo.setFollowerId(loginMember.getSeqId()); for(FollowDto f : topFiveFollows) { vo.setFollowId(f.getSeqId()); f.setFollowed(followService.checkFollow(vo)); } log.info(topFiveFollows); model.addAttribute("topFiveFollows", topFiveFollows); return "main/home"; }else { System.out.println("로그인실패"); } return "account/login"; } @PostMapping(value = "/logout") public String logout(HttpSession session, HttpServletRequest req, HttpServletResponse rep) { session.invalidate(); Cookie[] cookies = req.getCookies(); if(cookies != null) { for (int i = 0; i < cookies.length; i++) { System.out.println(cookies[i].getName() + " : " + cookies[i].getValue()); cookies[i].setValue(null); cookies[i].setPath("/"); cookies[i].setMaxAge(0); rep.addCookie(cookies[i]); } } return "redirect:/"; } @PostMapping(value = "/sessiondel") public String sessiondel(HttpSession session) { session.invalidate(); return "redirect:/"; } }
package com.snab.tachkit.databaseRealm.structureTableDatabase; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; /** * Created by chybakut2004 on 08.06.15. * * Количество осей */ public class AxleCount extends RealmObject { @PrimaryKey private int id_axle_count; // id private int axle_count_value; // значение private int axle_count_active; private int axle_count_order; public int getId_axle_count() { return id_axle_count; } public void setId_axle_count(int id_axle_count) { this.id_axle_count = id_axle_count; } public int getAxle_count_order() { return axle_count_order; } public void setAxle_count_order(int axle_count_order) { this.axle_count_order = axle_count_order; } public int getAxle_count_active() { return axle_count_active; } public void setAxle_count_active(int axle_count_active) { this.axle_count_active = axle_count_active; } public int getAxle_count_value() { return axle_count_value; } public void setAxle_count_value(int axle_count_value) { this.axle_count_value = axle_count_value; } }
import java.util.ArrayList; //Work out the Mean (the simple average of the numbers) //Then for each number: subtract the Mean and square the result (the squared difference). //Then work out the average of those squared differences. (Why Square?) public class Variance { // Copy here sum from exercise 63 public static int sum(ArrayList<Integer> list) { Integer sum = 0; for (Integer num:list) { sum+=num; } return sum; } // Copy here average from exercise 64 public static double average(ArrayList<Integer> list) { Integer total = sum(list); double avg = (double)total/list.size(); return avg; } public static double variance(ArrayList<Integer> list) { double mean = average(list); Integer size = list.size(); double differences = 0.00; for (Integer number:list) { differences += Math.pow((number-mean), 2); } return differences / (size-1); } public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(3); list.add(2); list.add(7); list.add(2); System.out.println("The variance is: " + variance(list)); } }
package com.mimi.mimigroup.model; public class DM_TreeStages { Integer stagesId; Integer treeId; String stagesCode; String stagesName; public DM_TreeStages() { } public DM_TreeStages(Integer stagesId, Integer treeId, String stagesCode, String stagesName) { this.stagesId = stagesId; this.treeId = treeId; this.stagesCode = stagesCode; this.stagesName = stagesName; } public Integer getStagesId() { return stagesId; } public void setStagesId(Integer stagesId) { this.stagesId = stagesId; } public Integer getTreeId() { return treeId; } public void setTreeId(Integer treeId) { this.treeId = treeId; } public String getStagesCode() { return stagesCode; } public void setStagesCode(String stagesCode) { this.stagesCode = stagesCode; } public String getStagesName() { return stagesName; } public void setStagesName(String stagesName) { this.stagesName = stagesName; } }
package com.briup.apps.zhaopin.bean.extend; import com.briup.apps.zhaopin.bean.Employment; import com.briup.apps.zhaopin.bean.EmploymentJobhunter; import com.briup.apps.zhaopin.bean.Jobhunter; /** * @program: EmploymentJobhunter * @description: 求职信息 * @author: CC * @create: 2019/9/27 9:13 */ public class EmploymentJobhunterExtend extends EmploymentJobhunter { private Employment employment; public Employment getEmployment() { return employment; } public void setEmployment(Employment employment) { this.employment = employment; } private Jobhunter jobhunter; public Jobhunter getJobhunter() { return jobhunter; } public void setJobhunter(Jobhunter jobhunter) { this.jobhunter = jobhunter; } }
package example.comparableAndComparator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; class a implements Comparator<a>{ public String s; a(String s){ this.s = s; } @Override public int compare(a o1, a o2) { return o1.s.compareTo(o2.s); } } public class comparatorPrad { public static void main(String[] args) { ArrayList<a> s = new ArrayList<>(); s.add(new a("Trushil")); s.add(new a("Harshil")); s.add(new a("Sangita")); s.add(new a("Prahlad")); s.add(new a("Mahendra")); Collections.sort(s, new a("hello")); for(a A: s){ System.out.println(A.s); } } }
package pl.ark.chr.buginator.aggregator.util; import pl.ark.chr.buginator.aggregator.domain.Aggregator; import pl.ark.chr.buginator.domain.core.Error; /** * Validation util for Error and Aggregator */ public final class AggregatorSenderValidator { static boolean checkErrorSeverityDoesNotMatch(Aggregator aggregator, Error error) { return !aggregator.getErrorSeverity().equals(error.getSeverity()); } static boolean checkErrorCountLessThanAggregator(Aggregator aggregator, Error error) { return error.getCount() < aggregator.getCount(); } public static boolean contractNotMatch(Aggregator aggregator, Error error) { return checkErrorSeverityDoesNotMatch(aggregator, error) || checkErrorCountLessThanAggregator(aggregator, error); } }
package com.example.graphBak2; /* * DFS:深度搜索遍历 * */ public class Graph { private final int MAX_SIZE = 10; private Vertex[] vertexList; private int nVerts;// 表示当前数组中元素的个数 private int[][] adjMatrix; private Stack stack;// 保存已访问顶点的下标 public Graph() { vertexList = new Vertex[MAX_SIZE]; nVerts = 0; adjMatrix = new int[MAX_SIZE][MAX_SIZE]; for (int i = 0; i < MAX_SIZE; i++) { for (int j = 0; j < MAX_SIZE; j++) { adjMatrix[i][j] = 0; } } stack = new Stack(); } // 添加顶点 public void addVertex(char label) { Vertex vertex = new Vertex(label); vertexList[nVerts++] = vertex; } // 添加顶点和顶点之间的边 public void addEdge(int start, int end) { adjMatrix[start][end] = 1; adjMatrix[end][start] = 1; } // 显示顶点元素信息 public void displayVertex(int vertexIndex) { System.out.print(vertexList[vertexIndex].label + " "); } // DFS public void dfs() { vertexList[0].isVisited = true; displayVertex(0); stack.push(0); while (!stack.isEmpty()) { int vertexIndex = stack.peek(); int adjVertex = getUnVisitedAdjVertex(vertexIndex); if (adjVertex != -1) { vertexList[adjVertex].isVisited = true; displayVertex(adjVertex); stack.push(adjVertex); } else { stack.pop(); } } } private int getUnVisitedAdjVertex(int vertexIndex) { for (int j = 0; j < nVerts; j++) { if (adjMatrix[vertexIndex][j] == 1 && vertexList[j].isVisited == false) { return j; } } return -1; } // MST:最小生成树 public void mst() { vertexList[0].isVisited = true; stack.push(0); while (!stack.isEmpty()) { int vertexIndex = stack.peek(); int adjVertex = getUnVisitedAdjVertex(vertexIndex); if (adjVertex != -1) { vertexList[adjVertex].isVisited = true; stack.push(adjVertex); displayVertex(vertexIndex); displayVertex(adjVertex); System.out.printf(" "); } else { stack.pop(); } } } }
package com.vietmedia365.voaapp.job; import android.app.DownloadManager; import android.content.Context; import android.net.Uri; import android.os.Environment; import com.path.android.jobqueue.Job; import com.path.android.jobqueue.Params; import com.vietmedia365.voaapp.NewsApp; import com.vietmedia365.voaapp.model.Article; import org.apache.commons.io.FilenameUtils; import java.io.File; public class DownloadJob extends Job { private Article article; public DownloadJob(Article article) { super(new Params(Priority.MID).requireNetwork().persist().groupBy("download")); this.article = article; } @Override public void onAdded() { File direct = new File(Environment.getExternalStorageDirectory() + "/Android/data/com.tthlab.voalearningapp/files"); if (!direct.exists()) { direct.mkdirs(); } DownloadManager mgr = (DownloadManager) NewsApp.getInstance().getBaseContext().getSystemService(Context.DOWNLOAD_SERVICE); Uri downloadUri = Uri.parse(article.getLinkAudio()); String baseName = FilenameUtils.getBaseName(downloadUri.getPath()); String extension = FilenameUtils.getExtension(downloadUri.getPath()); DownloadManager.Request request = new DownloadManager.Request(downloadUri); //String fileName = UUID.randomUUID() + ".mp3"; String fileName = baseName + "." + extension; request.setAllowedNetworkTypes( DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE) .setAllowedOverRoaming(false).setTitle(article.getTitle()) .setDescription(article.getTitle()) .setDestinationInExternalPublicDir("/Android/data/com.vietmedia365.voalearningapp/files", fileName); long queue = mgr.enqueue(request); article.setDownloaded(false); article.setDownloadId(queue); article.setDownloadUrl(Environment.getExternalStorageDirectory() + "/Android/data/com.vietmedia365.voalearningapp/files/" + fileName); NewsApp.getDbHandlerInstance().addSaved(article); } @Override public void onRun() throws Throwable { } @Override protected void onCancel() { } @Override protected boolean shouldReRunOnThrowable(Throwable throwable) { return false; } }
import java.util.*; class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int T = sc.nextInt(); int[] answer = new int[T]; for(int t =0;t<T;t++){ int N = sc.nextInt(); HashMap<String, Integer> hash = new HashMap<>(); for(int i=0;i<N;i++){ String name = sc.next(); String pur = sc.next(); if(hash.containsKey(pur)){ hash.put(pur,hash.get(pur)+1); }else{ hash.put(pur,1); } } int count=1; for(int i:hash.values()){ count*=(i+1); } answer[t] = count-1; } for(int i=0;i<T;i++){ System.out.println(answer[i]); } } }
package com.github.limboc.sample.utils; import android.content.Context; import android.widget.Toast; import com.github.limboc.sample.App; public class T { public static Context context; public static void showShort(int resId) { Toast.makeText(App.context, resId, Toast.LENGTH_SHORT).show(); } public static void showShort(String message) { Toast.makeText(App.context, message, Toast.LENGTH_SHORT).show(); } }
package com.tencent.mm.plugin.subapp.c; import com.tencent.mm.g.a.nx; import com.tencent.mm.model.au; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.bd; class d$5 extends c<nx> { final /* synthetic */ d orm; d$5(d dVar) { this.orm = dVar; this.sFo = nx.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { int i = (int) ((nx) bVar).bYT.bGS.field_msgId; au.HU(); bd dW = com.tencent.mm.model.c.FT().dW((long) i); if (!(dW.field_msgId == 0 || dW.field_imgPath == null || bi.oW(dW.field_imgPath))) { g Ok = h.Ok(dW.field_imgPath); if (!(Ok == null || bi.oW(Ok.field_filename))) { Ok.field_status = 3; Ok.field_offset = 0; Ok.field_createtime = System.currentTimeMillis() / 1000; Ok.field_lastmodifytime = System.currentTimeMillis() / 1000; Ok.bWA = 16840; h.a(Ok); x.d("MicroMsg.VoiceRemindLogic", " file:" + Ok.field_filename + " msgid:" + Ok.field_msglocalid + " stat:" + Ok.field_status); if (Ok.field_msglocalid == 0 || bi.oW(Ok.field_user)) { x.e("MicroMsg.VoiceRemindLogic", " failed msg id:" + Ok.field_msglocalid + " user:" + Ok.field_user); } else { dW.setStatus(1); au.HU(); com.tencent.mm.model.c.FT().a(dW.field_msgId, dW); d.bGu().run(); } } } return false; } }
/* * Copyright (C) 2020-2023 Hedera Hashgraph, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hedera.mirror.importer.parser.balance; import static com.hedera.mirror.importer.migration.ErrataMigrationTest.BAD_TIMESTAMP1; import static org.assertj.core.api.Assertions.assertThat; import com.hedera.mirror.common.domain.balance.AccountBalance; import com.hedera.mirror.common.domain.balance.AccountBalanceFile; import com.hedera.mirror.common.domain.balance.TokenBalance; import com.hedera.mirror.importer.IntegrationTest; import com.hedera.mirror.importer.MirrorProperties; import com.hedera.mirror.importer.parser.StreamFileParser; import com.hedera.mirror.importer.repository.AccountBalanceFileRepository; import com.hedera.mirror.importer.repository.AccountBalanceRepository; import com.hedera.mirror.importer.repository.TokenBalanceRepository; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @RequiredArgsConstructor(onConstructor = @__(@Autowired)) class AccountBalanceFileParserTest extends IntegrationTest { private final AccountBalanceBuilder accountBalanceBuilder; private final AccountBalanceFileBuilder accountBalanceFileBuilder; private final StreamFileParser<AccountBalanceFile> accountBalanceFileParser; private final AccountBalanceFileRepository accountBalanceFileRepository; private final AccountBalanceRepository accountBalanceRepository; private final TokenBalanceRepository tokenBalanceRepository; private final BalanceParserProperties parserProperties; private final MirrorProperties mirrorProperties; @BeforeEach void setup() { parserProperties.setEnabled(true); } @Test void disabled() { // given parserProperties.setEnabled(false); var accountBalanceFile = accountBalanceFile(1); var items = accountBalanceFile.getItems().collectList().block(); // when accountBalanceFileParser.parse(accountBalanceFile); // then assertAccountBalanceFileWhenSkipped(accountBalanceFile, items); } @Test void success() { // given var accountBalanceFile = accountBalanceFile(1); var items = accountBalanceFile.getItems().collectList().block(); // when accountBalanceFileParser.parse(accountBalanceFile); // then assertAccountBalanceFile(accountBalanceFile, items); assertThat(accountBalanceFile.getTimeOffset()).isZero(); } @Test void multipleBatches() { // given int batchSize = parserProperties.getBatchSize(); parserProperties.setBatchSize(2); var accountBalanceFile = accountBalanceFile(1); var items = accountBalanceFile.getItems().collectList().block(); // when accountBalanceFileParser.parse(accountBalanceFile); // then assertAccountBalanceFile(accountBalanceFile, items); parserProperties.setBatchSize(batchSize); } @Test void duplicateFile() { // given var accountBalanceFile = accountBalanceFile(1); var duplicate = accountBalanceFile(1); var items = accountBalanceFile.getItems().collectList().block(); // when accountBalanceFileParser.parse(accountBalanceFile); accountBalanceFileParser.parse(duplicate); // Will be ignored // then assertThat(accountBalanceFileRepository.count()).isEqualTo(1L); assertAccountBalanceFile(accountBalanceFile, items); } @Test void beforeStartDate() { // given var accountBalanceFile = accountBalanceFile(-1L); var items = accountBalanceFile.getItems().collectList().block(); // when accountBalanceFileParser.parse(accountBalanceFile); // then assertAccountBalanceFileWhenSkipped(accountBalanceFile, items); } @Test void errata() { // given var network = mirrorProperties.getNetwork(); mirrorProperties.setNetwork(MirrorProperties.HederaNetwork.MAINNET); AccountBalanceFile accountBalanceFile = accountBalanceFile(BAD_TIMESTAMP1); List<AccountBalance> items = accountBalanceFile.getItems().collectList().block(); // when accountBalanceFileParser.parse(accountBalanceFile); // then assertAccountBalanceFile(accountBalanceFile, items); assertThat(accountBalanceFile.getTimeOffset()).isEqualTo(-1); mirrorProperties.setNetwork(network); } void assertAccountBalanceFile(AccountBalanceFile accountBalanceFile, List<AccountBalance> accountBalances) { Map<TokenBalance.Id, TokenBalance> tokenBalances = accountBalances.stream() .map(AccountBalance::getTokenBalances) .flatMap(Collection::stream) .collect(Collectors.toMap(TokenBalance::getId, t -> t, (previous, current) -> previous)); assertThat(accountBalanceFile.getBytes()).isNotNull(); assertThat(accountBalanceFile.getItems().collectList().block()).containsExactlyElementsOf(accountBalances); assertThat(accountBalanceRepository.findAll()).containsExactlyInAnyOrderElementsOf(accountBalances); assertThat(tokenBalanceRepository.findAll()).containsExactlyInAnyOrderElementsOf(tokenBalances.values()); if (parserProperties.isEnabled()) { assertThat(accountBalanceFileRepository.findAll()) .hasSize(1) .first() .matches(a -> a.getLoadEnd() != null) .usingRecursiveComparison() .usingOverriddenEquals() .ignoringFields("bytes", "items", "loadEnd") .isEqualTo(accountBalanceFile); } } void assertAccountBalanceFileWhenSkipped( AccountBalanceFile accountBalanceFile, List<AccountBalance> accountBalances) { assertThat(accountBalanceFile.getBytes()).isNotNull(); assertThat(accountBalanceFile.getItems().collectList().block()).containsExactlyElementsOf(accountBalances); assertThat(accountBalanceRepository.count()).isZero(); assertThat(tokenBalanceRepository.count()).isZero(); if (parserProperties.isEnabled()) { assertThat(accountBalanceFileRepository.findAll()) .hasSize(1) .first() .matches(a -> a.getLoadEnd() != null) .usingRecursiveComparison() .usingOverriddenEquals() .ignoringFields("bytes", "items", "loadEnd") .isEqualTo(accountBalanceFile); } } private AccountBalanceFile accountBalanceFile(long timestamp) { return accountBalanceFileBuilder .accountBalanceFile(timestamp) .accountBalance(accountBalanceBuilder .accountBalance(timestamp) .accountId(1000L) .balance(1000L) .tokenBalance(1, 10000L) .tokenBalance(1, 10000L) // duplicate token balance rows should be filtered by parser .build()) .accountBalance(accountBalanceBuilder .accountBalance(timestamp) .accountId(2000L) .balance(2000L) .tokenBalance(2, 20000L) .tokenBalance(2, 20000L) .build()) .accountBalance(accountBalanceBuilder .accountBalance(timestamp) .accountId(3000L) .balance(3000L) .tokenBalance(3, 30000L) .tokenBalance(3, 30000L) .build()) .build(); } }
package com.walkerwang.algorithm.huaweioj; import java.util.Scanner; public class StringChMatch { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str1 = scanner.nextLine(); String str2 = scanner.nextLine(); System.out.println(boolIsAllCharExist(str1, str2)); } /** *短字符串str1中的所有字符出现在长字符串str2中即可,不需要连续 */ static boolean boolIsAllCharExist(String str1, String str2){ boolean result = true; for(int i=0; i<str1.length(); i++){ char ch = str1.charAt(i); if(str2.indexOf(ch) < 0){ result = false; break; } } return result; } }
package com.philschatz.checklist; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.Toolbar; import android.support.v7.widget.helper.ItemTouchHelper; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.appindexing.Thing; import com.google.android.gms.common.api.GoogleApiClient; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.Query; /* Notes for what needs to be worked on: - [ ] support multiple lists - [ ] support multiple item types (for counting calories) - [ ] store lastUpdated times - [ ] create a log of changes (for export later) - [ ] allow sharing lists - [ ] reorder items - [ ] add snooze button for homescreen reminder */ public class ToDoListActivity extends AppCompatActivity { public static final String SHARED_PREF_DATA_SET_CHANGED = "com.philschatz.checklist.datasetchanged"; public static final String CHANGE_OCCURED = "com.philschatz.checklist.changeoccured"; public static final String THEME_PREFERENCES = "com.philschatz.checklist.themepref"; public static final String THEME_SAVED = "com.philschatz.checklist.savedtheme"; public static final String DARKTHEME = "com.philschatz.checklist.darktheme"; public static final String LIGHTTHEME = "com.philschatz.checklist.lighttheme"; public static final int REQUEST_ID_TODO_ITEM = 100; private static final String TAG = ToDoListActivity.class.getSimpleName(); private static final int REQUEST_ID_EDIT_LIST = 101; private Toolbar mToolbar; private String mListKey; private ToDoList mList; public ItemTouchHelper itemTouchHelper; private RecyclerViewEmptySupport mRecyclerView; private FloatingActionButton mAddToDoItemFAB; CoordinatorLayout mCoordLayout; private CustomRecyclerScrollViewListener customRecyclerScrollViewListener; private int mTheme = -1; private String theme = "name_of_the_theme"; AnalyticsApplication app; private String[] testStrings = {"Clean my room", "Water the plants", "Get car washed", "Get my dry cleaning" }; private DatabaseReference databaseReference; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; protected void onCreate(Bundle savedInstanceState) { //We recover the theme we've set and setTheme accordingly theme = getSharedPreferences(THEME_PREFERENCES, MODE_PRIVATE).getString(THEME_SAVED, LIGHTTHEME); if (theme.equals(LIGHTTHEME)) { mTheme = R.style.CustomStyle_LightTheme; } else { mTheme = R.style.CustomStyle_DarkTheme; } this.setTheme(mTheme); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_DATA_SET_CHANGED, MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(CHANGE_OCCURED, false); editor.apply(); Intent i = getIntent(); mListKey = i.getStringExtra(Const.TODOLISTKEY); mList = (ToDoList) i.getSerializableExtra(Const.TODOLISTSNAPSHOT); databaseReference = MainActivity.getListItemsReference(mListKey); mToolbar = (Toolbar) findViewById(R.id.toolbar); mToolbar.setTitle(mList.getTitle()); mToolbar.setBackgroundColor(mList.getColor()); setSupportActionBar(mToolbar); mCoordLayout = (CoordinatorLayout) findViewById(R.id.myCoordinatorLayout); mAddToDoItemFAB = (FloatingActionButton) findViewById(R.id.addToDoItemFAB); mAddToDoItemFAB.setOnClickListener(new View.OnClickListener() { @SuppressWarnings("deprecation") @Override public void onClick(View v) { // app.send(this, "Action", "FAB pressed"); Intent newTodo = new Intent(ToDoListActivity.this, AddToDoItemActivity.class); ToDoItem item = new ToDoItem(); item.setTitle(""); // This way the editor will start up blank newTodo.putExtra(Const.TODOITEMSNAPSHOT, item); // new items do not have a Firebase id yet TODO PHIL Maybe this should be the point when they get an id newTodo.putExtra(Const.TODOITEMKEY, databaseReference.push().getKey()); newTodo.putExtra(Const.TODOLISTKEY, mListKey); startActivityForResult(newTodo, REQUEST_ID_TODO_ITEM); } }); mRecyclerView = (RecyclerViewEmptySupport) findViewById(R.id.toDoRecyclerView); if (theme.equals(LIGHTTHEME)) { mRecyclerView.setBackgroundColor(getResources().getColor(R.color.primary_lightest)); } mRecyclerView.setEmptyView(findViewById(R.id.toDoEmptyView)); mRecyclerView.setHasFixedSize(true); mRecyclerView.setItemAnimator(new DefaultItemAnimator()); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); // Note: Set this to an instance variable so it can be destroyed later customRecyclerScrollViewListener = new FABRecyclerScrollViewListener(mAddToDoItemFAB); mRecyclerView.addOnScrollListener(customRecyclerScrollViewListener); // TODO: Checkout android.R.layout.two_line_list_item instead // TODO: Try to sort & filter the list : https://stackoverflow.com/questions/30398247/how-to-filter-a-recyclerview-with-a-searchview#30429439 Query sortedItems = databaseReference.orderByChild("completedAt"); ToDoItemAdapter mAdapter = new ToDoItemAdapter(this, mList, mListKey, sortedItems); mRecyclerView.setAdapter(mAdapter); ItemTouchHelper.Callback callback = new ItemTouchHelperClass(mAdapter); itemTouchHelper = new ItemTouchHelper(callback); itemTouchHelper.attachToRecyclerView(mRecyclerView); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } // public void addThemeToSharedPreferences(String theme) { // SharedPreferences sharedPreferences = getSharedPreferences(THEME_PREFERENCES, MODE_PRIVATE); // SharedPreferences.Editor editor = sharedPreferences.edit(); // editor.putString(THEME_SAVED, theme); // editor.apply(); // } // @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.aboutMeMenuItem: Intent i = new Intent(this, AboutActivity.class); startActivity(i); return true; // case R.id.switch_themes: // if(mTheme == R.style.CustomStyle_DarkTheme){ // addThemeToSharedPreferences(LIGHTTHEME); // } // else{ // addThemeToSharedPreferences(DARKTHEME); // } // //// if(mTheme == R.style.CustomStyle_DarkTheme){ //// mTheme = R.style.CustomStyle_LightTheme; //// } //// else{ //// mTheme = R.style.CustomStyle_DarkTheme; //// } // this.recreate(); // return true; case R.id.preferences: Intent intent = new Intent(this, AddToDoListActivity.class); intent.putExtra(Const.TODOLISTKEY, mListKey); intent.putExtra(Const.TODOLISTSNAPSHOT, mList); startActivityForResult(intent, REQUEST_ID_EDIT_LIST); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (resultCode != RESULT_CANCELED && requestCode == REQUEST_ID_TODO_ITEM) { // ToDoItem item = (ToDoItem) data.getSerializableExtra(Const.TODOITEMSNAPSHOT); // String itemKey = data.getStringExtra(Const.TODOITEMKEY); // // TODO: Use the list key here // MainActivity.getListItemReference(mListKey, itemKey).setValue(item); // } if (resultCode != RESULT_CANCELED && requestCode == REQUEST_ID_EDIT_LIST) { mList = (ToDoList) data.getSerializableExtra(Const.TODOLISTSNAPSHOT); // update the toolbar mToolbar.setTitle(mList.getTitle()); mToolbar.setBackgroundColor(mList.getColor()); } } /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ public Action getIndexApiAction() { Thing object = new Thing.Builder() .setName("Main Page") // TODO: Define a title for the content shown. // TODO: Make sure this auto-generated URL is correct. .setUrl(Uri.parse("http://philschatz.com")) .build(); return new Action.Builder(Action.TYPE_VIEW) .setObject(object) .setActionStatus(Action.STATUS_TYPE_COMPLETED) .build(); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. AppIndex.AppIndexApi.end(client, getIndexApiAction()); client.disconnect(); } @Override protected void onDestroy() { super.onDestroy(); mRecyclerView.removeOnScrollListener(customRecyclerScrollViewListener); } }
package org.aion.kernel; import org.aion.avm.core.types.InternalTransaction; import org.aion.avm.core.util.Helpers; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class TransactionResult { private enum CodeType { SUCCESS, REJECTED, FAILED } public enum Code { /** * The transaction was executed successfully. */ SUCCESS(CodeType.SUCCESS), // rejected transactions should not be included on chain. /** * This transaction was rejected. */ REJECTED(CodeType.REJECTED), /** * Insufficient balance to conduct the transaction. */ REJECTED_INSUFFICIENT_BALANCE(CodeType.REJECTED), /** * The transaction nonce does not match the account nonce. */ REJECTED_INVALID_NONCE(CodeType.REJECTED), // failed transaction can be included on chain, but energy charge will apply. /** * A failure occurred during the execution of the transaction. */ FAILED(CodeType.FAILED), /** * The transaction data is malformed, for internal tx only. */ FAILED_INVALID_DATA(CodeType.FAILED), /** * Transaction failed due to out of energy. */ FAILED_OUT_OF_ENERGY(CodeType.FAILED), /** * Transaction failed due to stack overflow. */ FAILED_OUT_OF_STACK(CodeType.FAILED), /** * Transaction failed due to exceeding the internal call depth limit. */ FAILED_CALL_DEPTH_LIMIT_EXCEEDED(CodeType.FAILED), /** * Transaction failed due to a REVERT operation. */ FAILED_REVERT(CodeType.FAILED), /** * Transaction failed due to an INVALID operation. */ FAILED_INVALID(CodeType.FAILED), /** * Transaction failed due to an uncaught exception. */ FAILED_EXCEPTION(CodeType.FAILED), /** * CREATE transaction failed due to a rejected of the user-provided classes. */ FAILED_REJECTED(CodeType.FAILED), /** * Transaction failed due to an early abort. */ FAILED_ABORT(CodeType.FAILED); private CodeType type; Code(CodeType type) { this.type = type; } public boolean isSuccess() { return type == CodeType.SUCCESS; } public boolean isRejected() { return type == CodeType.REJECTED; } public boolean isFailed() { return type == CodeType.FAILED; } } /** * Any uncaught exception that flows to the AVM. */ private Throwable uncaughtException; /** * The status code. */ private Code statusCode; /** * The return data. */ private byte[] returnData; /** * The cumulative energy used. */ private long energyUsed; /** * The storage root hash of the target account, after the transaction. * Note that this is only set on SUCCESS. * This is just a proof-of-concept for issue-246 and will change in the future. */ private int storageRootHash; /** * The logs emitted during execution. */ private List<Log> logs = new ArrayList<>(); /** * The internal transactions created during execution. */ private List<InternalTransaction> internalTransactions = new ArrayList<>(); /** * The external transactional kernel generated by execution. */ private KernelInterface externalTransactionalKernel; public void merge(TransactionResult other) { internalTransactions.addAll(other.getInternalTransactions()); if (other.statusCode == Code.SUCCESS) { logs.addAll(other.getLogs()); } } public void addLog(Log log) { this.logs.add(log); } public void addInternalTransaction(InternalTransaction tx) { this.internalTransactions.add(tx); } /** * Creates an empty result, where statusCode = SUCCESS and energyUsed = 0. */ public TransactionResult() { this.statusCode = Code.SUCCESS; this.energyUsed = 0; } public Code getStatusCode() { return statusCode; } public void setStatusCode(Code statusCode) { this.statusCode = statusCode; } public byte[] getReturnData() { return returnData; } public void setReturnData(byte[] returnData) { this.returnData = returnData; } public long getEnergyUsed() { return energyUsed; } public void setEnergyUsed(long energyUsed) { this.energyUsed = energyUsed; } public int getStorageRootHash() { return this.storageRootHash; } public void setStorageRootHash(int storageRootHash) { this.storageRootHash = storageRootHash; } public List<Log> getLogs() { return logs; } public List<InternalTransaction> getInternalTransactions() { return internalTransactions; } public void clearLogs() { this.logs.clear(); } public void rejectInternalTransactions() { this.internalTransactions.forEach(InternalTransaction::markAsRejected); } public Throwable getUncaughtException() { return uncaughtException; } public void setUncaughtException(Throwable uncaughtException) { this.uncaughtException = uncaughtException; } public void setExternalTransactionalKernel(KernelInterface externalTransactionalKernel) { this.externalTransactionalKernel = externalTransactionalKernel; } public KernelInterface getExternalTransactionalKernel() { return externalTransactionalKernel; } @Override public String toString() { return "TransactionResult{" + "statusCode=" + statusCode + ", returnData=" + (returnData == null ? "NULL" : Helpers.bytesToHexString(returnData)) + ", energyUsed=" + energyUsed + ", logs=[" + logs.stream().map(Log::toString).collect(Collectors.joining(",")) + "]" + '}'; } }
package com.takshine.wxcrm.domain; import com.takshine.wxcrm.model.TagModel; /** * 销售方法论 * @author 刘淋 * */ public class Tag extends TagModel{ private String modelType; private String modelId; private String tagName; private int total; public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public String getModelType() { return modelType; } public void setModelType(String modelType) { this.modelType = modelType; } public String getModelId() { return modelId; } public void setModelId(String modelId) { this.modelId = modelId; } public String getTagName() { return tagName; } public void setTagName(String tagName) { this.tagName = tagName; } }
package it.polimi.ingsw.GC_21.GAMECOMPONENTS; import it.polimi.ingsw.GC_21.EFFECT.DontCheckMP; import it.polimi.ingsw.GC_21.EFFECT.DontSpend3Coins; import it.polimi.ingsw.GC_21.EFFECT.Effect; import it.polimi.ingsw.GC_21.EFFECT.Permanent; import it.polimi.ingsw.GC_21.PLAYER.Player; public class PermanentLeaderCard extends LeaderCard{ private Permanent permanentEffect; @Override public void callEffect(Player player) { Effect effectToAdd = (Effect) permanentEffect; if (effectToAdd instanceof DontSpend3Coins || effectToAdd instanceof DontCheckMP){ effectToAdd.activateEffect(player, null); } else{ player.getMyPersonalBoard().addPermanentEffect(effectToAdd); } } public PermanentLeaderCard(String ID, String name, int numberOfVenturesRequired, int numberOfCharactersRequired, int numberOfBuildingRequired, int numberOfTerritoryRequired, Possession requirements, boolean played, Permanent permanentEffect) { super(ID, name, numberOfVenturesRequired, numberOfCharactersRequired, numberOfBuildingRequired, numberOfTerritoryRequired, requirements, played); this.permanentEffect = permanentEffect; } public String getName() { return name; } public int getNumberOfVenturesRequired() { return numberOfVenturesRequired; } public void setNumberOfVenturesRequired(int numberOfVenturesRequired) { this.numberOfVenturesRequired = numberOfVenturesRequired; } public int getNumberOfCharactersRequired() { return numberOfCharactersRequired; } public void setNumberOfCharactersRequired(int numberOfCharactersRequired) { this.numberOfCharactersRequired = numberOfCharactersRequired; } public int getNumberOfBuildingRequired() { return numberOfBuildingRequired; } public void setNumberOfBuildingRequired(int numberOfBuildingRequired) { this.numberOfBuildingRequired = numberOfBuildingRequired; } public int getNumberOfTerritoryRequired() { return numberOfTerritoryRequired; } public void setNumberOfTerritoryRequired(int numberOfTerritoryRequired) { this.numberOfTerritoryRequired = numberOfTerritoryRequired; } public Permanent getPermanentEffect() { return permanentEffect; } public void setPermanentEffect(Permanent permanentEffect) { this.permanentEffect = permanentEffect; } }
package com.semantyca.nb.core.dataengine.jpa.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.semantyca.nb.core.dataengine.jpa.util.NamingCustomizer; import org.eclipse.persistence.annotations.Customizer; import javax.persistence.*; import java.util.List; @Embeddable @Customizer(NamingCustomizer.class) public class EntityAttachment { private String fileName; @Column(length = 32) private String extension; private long size; private boolean hasThumbnail; private String comment; @JsonIgnore @Lob @Basic(fetch = FetchType.LAZY) @Column(columnDefinition = "bytea") private byte[] file; public String getFileName() { return fileName; } public void setFileName(String realFileName) { // file extension int lastDotIndex = realFileName.lastIndexOf("."); if (lastDotIndex != -1) { extension = realFileName.substring(lastDotIndex + 1).toLowerCase(); } else { extension = ""; } // this.fileName = realFileName; } public String getExtension() { return extension; } public void setExtension(String extension) { this.extension = extension; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } public byte[] getFile() { return file; } public void setFile(byte[] file) { this.file = file; if (file != null) { size = file.length; } else { size = 0; } } public boolean isHasThumbnail() { return hasThumbnail; } public void setHasThumbnail(boolean hasThumbnail) { this.hasThumbnail = hasThumbnail; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public List<EntityAttachment> getAttachments() { return null; } }
package com.example.zhangtuo.myapplication; /** * Created by zhangtuo on 2017/6/6. */ public class MyClass { //TODO //测试合并嘞。。。。 }
package com.youthchina.repository; import com.youthchina.dao.tianjian.CommunityMapper; import com.youthchina.domain.tianjian.ComEssay; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.sql.Timestamp; /** * Created by zhongyangwu on 4/14/19. */ @Component public class EssayRepository implements BaseRepository<Integer, ComEssay> { private CommunityMapper communityMapper; @Autowired public EssayRepository(CommunityMapper communityMapper) { this.communityMapper = communityMapper; } @Override public ComEssay get(Integer id) { return communityMapper.getEssay(id); } @Override @Transactional public void delete(ComEssay entity) { communityMapper.deleteEssay(entity.getId(), new Timestamp(System.currentTimeMillis())); } }
package com.cts.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cts.model.Users; import com.cts.repository.UserRepository; @Service public class UserService { Users user; @Autowired UserRepository repo; public List<Users> getAllUsers() { // TODO Auto-generated method stub return (List<Users>) repo.findAll(); } public void addUser(Users user) { repo.save(user); } public Optional<Users> getUserDetailsById(int id) { return repo.findById(id); } }
package com.example.park4me; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String[] bairros = new String[] {"Botafogo", "Copacabana/Leme", "Flamengo/Laranjeiras", "Ipanema", "Leblon", "Região Central", "Sair"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1 , bairros); setListAdapter(adapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id){ Intent intent; switch(position){ case 0: //botafogo intent = new Intent(this, map.class); intent.putExtra("lat", -22.954339); intent.putExtra("lng", -43.1909142); startActivity(intent); break; case 1: //copacabana/leme // intent = new Intent(this, map.class); // intent.putExtra("lat", -22.9732708); // intent.putExtra("lng", -43.1857553); // startActivity(intent); iniciaMapaNaRegiao(-22.9732708,-43.1857553); break; case 2: //flamengo intent = new Intent(this, map.class); intent.putExtra("lat", -22.9356357); intent.putExtra("lng", -43.1813744); startActivity(intent); break; case 3: //ipanema intent = new Intent(this, map.class); intent.putExtra("lat", -22.9849889); intent.putExtra("lng", -43.2044715); startActivity(intent); break; case 4: //leblon intent = new Intent(this, map.class); intent.putExtra("lat", -22.9840451); intent.putExtra("lng", -43.2247083); startActivity(intent); break; case 5: //regiao central intent = new Intent(this, map.class); intent.putExtra("lat", -22.9053526); intent.putExtra("lng", -43.1781185); startActivity(intent); break; // case 6: // // intent = new Intent(this, map.class); // intent.putExtra("lat", -22.9873758); // intent.putExtra("lng", -43.1237373); // startActivity(intent); // break; default: finish(); } } private void iniciaMapaNaRegiao(double latitude, double longitude) { Intent intent = new Intent(this, map.class); intent = new Intent(this, map.class); intent.putExtra("lat", latitude); intent.putExtra("lng", longitude); startActivity(intent); } } //public class MainActivity extends Activity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // // } // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.main, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // // Handle action bar item clicks here. The action bar will // // automatically handle clicks on the Home/Up button, so long // // as you specify a parent activity in AndroidManifest.xml. // int id = item.getItemId(); // if (id == R.id.action_settings) { // return true; // } // return super.onOptionsItemSelected(item); // } //}
public class EachPositionPrinting { public void process(int no) { for(int i=0;i<=no;i++){ for(int j=0;j<=no;j++){ if(i==j){ System.out.print(i+" "); } else System.out.print(0+" "); } System.out.println(); } } }
package com.tencent.mm.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.tencent.mm.protocal.b.a.a; class j$7 implements OnClickListener { final /* synthetic */ j tjf; final /* synthetic */ a tjk; final /* synthetic */ int val$id; j$7(j jVar, int i, a aVar) { this.tjf = jVar; this.val$id = i; this.tjk = aVar; } public final void onClick(DialogInterface dialogInterface, int i) { j.a(this.tjf, this.val$id, this.tjk.actionType, this.tjk.id, this.tjk.qXX); dialogInterface.dismiss(); } }
package com.dathanwong.relationships.services; import org.springframework.stereotype.Service; import com.dathanwong.relationships.models.License; import com.dathanwong.relationships.repositories.LicenseRepository; @Service public class LicenseService { private final LicenseRepository repo; public LicenseService(LicenseRepository repo) { this.repo = repo; } public License createLicense(License license) { //Create license number by converting id to string and padding zeros in front Long number = license.getPerson().getId(); System.out.println(number); int numLength = String.valueOf(number).length(); System.out.println("Length:" + numLength); int numZeros = 6-numLength; String licenseNumber = ""; for(int i = 0; i < numZeros; i++) { licenseNumber = licenseNumber + "0"; } System.out.println(licenseNumber); licenseNumber = licenseNumber + String.valueOf(number); license.setNumber(licenseNumber); return repo.save(license); } }
package it.bad_request.hackaton.certificami.repository; import org.springframework.data.jpa.repository.JpaRepository; import it.bad_request.hackaton.certificami.entity.Certificazione; import it.bad_request.hackaton.certificami.entity.Motivazione; public interface MotivazioneRepository extends JpaRepository<Motivazione, Long>{ }
package net.liuzd.spring.boot.v2.config.enums; import java.io.IOException; import javax.annotation.Nonnull; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import net.liuzd.spring.boot.v2.common.Enumerable; public class EnumSerializer extends StdSerializer<Enumerable> { public EnumSerializer(@Nonnull Class<Enumerable> type) { super(type); } @Override public void serialize(Enumerable enumerable, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeStartObject(); jsonGenerator.writeNumberField("value", enumerable.getValue()); jsonGenerator.writeStringField("text", enumerable.getKey()); jsonGenerator.writeEndObject(); } }
package com.jawspeak.unifier.spike; import static com.google.classpath.RegExpResourceFilter.*; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Stack; import org.junit.BeforeClass; import org.junit.Test; import org.objectweb.asm.ClassAdapter; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import com.google.classpath.ClassPath; import com.google.classpath.ClassPathFactory; import com.google.classpath.RegExpResourceFilter; import com.google.common.collect.Lists; public class ReadJarWriteJarTest { private ClassPath classPath; private static final String GENERATED_BYTECODE = "target/test-generated-bytecode"; @BeforeClass public static void setUpOnce() { File toDelete = new File(GENERATED_BYTECODE); // System.out.println(toDelete + " exists? " + toDelete.exists()); // stackDelete(toDelete); recursiveDelete(toDelete); // System.out.println(toDelete + " exists? " + toDelete.exists()); } // this is a spike, so hey, I can implement this just for fun private static void stackDelete(File file) { Stack<File> toDelete = new Stack<File>(); toDelete.add(file); while (!toDelete.isEmpty()) { File f = toDelete.peek(); if (f.isDirectory() && f.listFiles().length == 0) { // empty directory toDelete.pop().delete(); } else if (f.isDirectory()) { // full directory for (File listing : f.listFiles()) { toDelete.push(listing); } } else { // file toDelete.pop().delete(); } } } private static void recursiveDelete(File file) { if (file.isDirectory()) { for (File listing : file.listFiles()) { recursiveDelete(listing); } file.delete(); } else { file.delete(); } } @Test public void differenceBetweenInternalAndDescriptorName() throws Exception { String descriptor = Type.getDescriptor(String.class); String internalName = Type.getInternalName(String.class); assertEquals(descriptor, "L" + internalName + ";"); } @Test public void readsAndThenWritesJar() throws Exception { classPath = new ClassPathFactory().createFromPath("src/test/resources/single-class-in-jar.jar"); String[] resources = classPath.findResources("", new RegExpResourceFilter(ANY, ENDS_WITH_CLASS)); assertEquals("[com/jawspeak/unifier/dummy/DoNothingClass1.class]", Arrays.deepToString(resources)); assertFalse("no dots in path", classPath.isPackage(".")); assertFalse(classPath.isPackage("com.jawspeak.unifier.dummy")); assertTrue(classPath.isPackage("/")); assertTrue(classPath.isPackage("/com")); assertTrue(classPath.isPackage("com")); assertTrue(classPath.isPackage("com/jawspeak/unifier/dummy")); assertTrue(classPath.isPackage("com/jawspeak/unifier/dummy/")); assertTrue(classPath.isResource("com/jawspeak/unifier/dummy/DoNothingClass1.class")); String generatedBytecodeDir = GENERATED_BYTECODE + "/read-then-write-jar/"; writeOutDirectFiles(generatedBytecodeDir, resources); classPath = new ClassPathFactory().createFromPath(generatedBytecodeDir); assertTrue(classPath.isPackage("/")); assertTrue(classPath.isPackage("/com")); assertTrue(classPath.isPackage("com")); assertTrue(classPath.isPackage("com/jawspeak/unifier/dummy")); assertTrue(classPath.isPackage("com/jawspeak/unifier/dummy/")); assertTrue(classPath.isResource("com/jawspeak/unifier/dummy/DoNothingClass1.class")); } @Test public void readsPassesThroughAsmThenWritesJar() throws Exception { classPath = new ClassPathFactory().createFromPath("src/test/resources/single-class-in-jar.jar"); String[] resources = classPath.findResources("", new RegExpResourceFilter(ANY, ENDS_WITH_CLASS)); assertEquals("[com/jawspeak/unifier/dummy/DoNothingClass1.class]", Arrays.deepToString(resources)); assertFalse("no dots in path", classPath.isPackage(".")); assertFalse(classPath.isPackage("com.jawspeak.unifier.dummy")); assertTrue(classPath.isPackage("/")); assertTrue(classPath.isPackage("/com")); assertTrue(classPath.isPackage("com")); assertTrue(classPath.isPackage("com/jawspeak/unifier/dummy")); assertTrue(classPath.isPackage("com/jawspeak/unifier/dummy/")); assertTrue(classPath.isResource("com/jawspeak/unifier/dummy/DoNothingClass1.class")); final byte[] originalClassBytes = readInputStream(classPath.getResourceAsStream("com/jawspeak/unifier/dummy/DoNothingClass1.class")).toByteArray(); String generatedBytecodeDir = GENERATED_BYTECODE + "/read-then-asm-passthrough-write-jar/"; writeOutAsmFiles(generatedBytecodeDir, resources); classPath = new ClassPathFactory().createFromPath(generatedBytecodeDir); assertTrue(classPath.isPackage("/")); assertTrue(classPath.isPackage("/com")); assertTrue(classPath.isPackage("com")); assertTrue(classPath.isPackage("com/jawspeak/unifier/dummy")); assertTrue(classPath.isPackage("com/jawspeak/unifier/dummy/")); assertTrue(classPath.isResource("com/jawspeak/unifier/dummy/DoNothingClass1.class")); final byte[] newBytes = readInputStream(classPath.getResourceAsStream("com/jawspeak/unifier/dummy/DoNothingClass1.class")).toByteArray(); assertTrue(newBytes.length > 0); class MyClassLoader extends ClassLoader { Class<?> clazz; } MyClassLoader originalClassLoader = new MyClassLoader() {{ clazz = defineClass("com.jawspeak.unifier.dummy.DoNothingClass1", originalClassBytes, 0, originalClassBytes.length); }}; MyClassLoader newClassLoader = new MyClassLoader() {{ clazz = defineClass("com.jawspeak.unifier.dummy.DoNothingClass1", newBytes, 0, newBytes.length); }}; // load from both classloaders, and the methods should be the same. Could test more, but this // proves the spike of reading from asm and writing back out. Class<?> originalClass = originalClassLoader.clazz; Class<?> newClass = newClassLoader.clazz; Method[] originalMethods = originalClass.getMethods(); Method[] newMethods = newClass.getMethods(); assertEquals(originalMethods.length, newMethods.length); for (int i = 0; i < originalMethods.length; i++) { assertEquals(originalMethods[i].toString(), newMethods[i].toString()); } // Create a new jar from the newly asm-generated classes String command = "jar cf " + GENERATED_BYTECODE + "/single-class-in-jar-asm-modified.jar -C " + generatedBytecodeDir + " ."; Process process = Runtime.getRuntime().exec(command); process.waitFor(); String stdout = new String(readInputStream(process.getInputStream()).toByteArray()); String stderr = new String(readInputStream(process.getErrorStream()).toByteArray()); assertEquals("", stdout); assertEquals("", stderr); assertTrue(new File(GENERATED_BYTECODE + "/single-class-in-jar-asm-modified.jar").exists()); // Then we should be able to read back out the new jar, with all the same resources. classPath = new ClassPathFactory().createFromPath(GENERATED_BYTECODE + "/single-class-in-jar-asm-modified.jar"); assertTrue(classPath.isPackage("/")); assertTrue(classPath.isPackage("/com")); assertTrue(classPath.isPackage("com")); assertTrue(classPath.isPackage("com/jawspeak/unifier/dummy")); assertTrue(classPath.isPackage("com/jawspeak/unifier/dummy/")); assertTrue(classPath.isResource("com/jawspeak/unifier/dummy/DoNothingClass1.class")); } static class ShimMethod { private String name; private List<Class<?>> parameters; private Class<?> returnClazz; private final String thisClassDesc; private boolean isStatic; // TODO don't push this on local variables part, if it is static public ShimMethod(String name, String thisClassDesc, Class<?> returnClazz, Class<?>... parameters) { super(); this.name = name; this.thisClassDesc = thisClassDesc; this.parameters = Lists.newArrayList(parameters); this.returnClazz = returnClazz; } } static class AddingClassAdapter extends ClassAdapter { private final ShimClass newClass; public AddingClassAdapter(ClassVisitor writer, ShimClass newClass) { super(writer); this.newClass = newClass; } // TODO: I think we just need to call lots of different visitors in here. VIsit field, visit method, visit etc. @Override public void visit(int arg0, int arg1, String arg2, String arg3, String arg4, String[] arg5) { // TODO Auto-generated method stub super.visit(arg0, arg1, arg2, arg3, arg4, arg5); } } static class ModifyingClassAdapter extends ClassAdapter { private ShimMethod newMethod; // could be a list private ShimField newField; public ModifyingClassAdapter(ClassVisitor writer, ShimMethod newMethod, ShimField newField) { super(writer); this.newMethod = newMethod; this.newField = newField; } @Override public void visitEnd() { if (newField != null) { // Just this will add the field, but not set it to the default value. Thus it'll let compilation work, but may fail with runtime. (NPE) FieldVisitor fv = super.visitField(newField.access, newField.name, newField.desc, null, null); fv.visitEnd(); } // could also have a List<Runnable> like Misko did and record what i want to do in here, then execute it at end. if (newMethod != null) { // TODO handle these params via helper classes / the ShimClass's methods. // I created this code with the ASMifier eclipse plugin tool. MethodVisitor mv = super.visitMethod(Opcodes.ACC_PUBLIC, newMethod.name, "()V", null, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); mv.visitTypeInsn(Opcodes.NEW, "java/lang/UnsupportedOperationException"); mv.visitInsn(Opcodes.DUP); mv.visitLdcInsn("Operation added to unify interfaces for compile time, but should not be called."); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/UnsupportedOperationException", "<init>", "(Ljava/lang/String;)V"); mv.visitInsn(Opcodes.ATHROW); Label l1 = new Label(); mv.visitLabel(l1); mv.visitLocalVariable("this", newMethod.thisClassDesc, null, l0, l1, 0); mv.visitEnd(); mv.visitMaxs(3, 1); } super.visitEnd(); } } @Test public void readsAsmAddsMethod() throws Exception { classPath = new ClassPathFactory().createFromPath("src/test/resources/single-class-in-jar.jar"); String[] resources = classPath.findResources("", new RegExpResourceFilter(ANY, ENDS_WITH_CLASS)); final byte[] originalClassBytes = readInputStream(classPath.getResourceAsStream("com/jawspeak/unifier/dummy/DoNothingClass1.class")).toByteArray(); String generatedBytecodeDir = GENERATED_BYTECODE + "/read-then-asm-adds-method/"; ShimMethod newMethod = new ShimMethod("myNewMethod", "Lcom/jawspeak/unifier/dummy/DoNothingClass1;", void.class); writeOutAsmFilesWithNewMethod(generatedBytecodeDir, resources, newMethod); classPath = new ClassPathFactory().createFromPath(generatedBytecodeDir); final byte[] newBytes = readInputStream(classPath.getResourceAsStream("com/jawspeak/unifier/dummy/DoNothingClass1.class")).toByteArray(); assertTrue(newBytes.length > 0); class MyClassLoader extends ClassLoader { Class<?> clazz; } MyClassLoader originalClassLoader = new MyClassLoader() {{ clazz = defineClass("com.jawspeak.unifier.dummy.DoNothingClass1", originalClassBytes, 0, originalClassBytes.length); }}; MyClassLoader newClassLoader = new MyClassLoader() {{ clazz = defineClass("com.jawspeak.unifier.dummy.DoNothingClass1", newBytes, 0, newBytes.length); }}; Class<?> originalClass = originalClassLoader.clazz; Class<?> newClass = newClassLoader.clazz; Method[] originalMethods = originalClass.getMethods(); Method[] newMethods = newClass.getMethods(); assertEquals(10, originalMethods.length); assertEquals(11, newMethods.length); newClass.getMethod("method1", String.class).invoke(newClass.newInstance(), ""); // should not have any exceptions try { newClass.getMethod("myNewMethod").invoke(newClass.newInstance()); fail("Expected Exception: Should have thrown exception in new method we just generated"); } catch (InvocationTargetException expected) { UnsupportedOperationException cause = (UnsupportedOperationException) expected.getCause(); assertEquals("Operation added to unify interfaces for compile time, but should not be called.", cause.getMessage()); } } class ShimField { String name; String desc; int access; public ShimField(String fieldName, String desc, int access) { this.name = fieldName; this.desc = desc; this.access = access; } } @Test public void readsAsmAddsField() throws Exception { classPath = new ClassPathFactory().createFromPath("src/test/resources/single-class-in-jar.jar"); String[] resources = classPath.findResources("", new RegExpResourceFilter(ANY, ENDS_WITH_CLASS)); final byte[] originalClassBytes = readInputStream(classPath.getResourceAsStream("com/jawspeak/unifier/dummy/DoNothingClass1.class")).toByteArray(); String generatedBytecodeDir = GENERATED_BYTECODE + "/read-then-asm-adds-field/"; ShimField newField = new ShimField("myString", Type.getDescriptor(String.class), Opcodes.ACC_PUBLIC); writeOutAsmFilesWithNewField(generatedBytecodeDir, resources, newField); classPath = new ClassPathFactory().createFromPath(generatedBytecodeDir); final byte[] newBytes = readInputStream(classPath.getResourceAsStream("com/jawspeak/unifier/dummy/DoNothingClass1.class")).toByteArray(); assertTrue(newBytes.length > 0); class MyClassLoader extends ClassLoader { Class<?> clazz; } MyClassLoader originalClassLoader = new MyClassLoader() {{ clazz = defineClass("com.jawspeak.unifier.dummy.DoNothingClass1", originalClassBytes, 0, originalClassBytes.length); }}; MyClassLoader newClassLoader = new MyClassLoader() {{ clazz = defineClass("com.jawspeak.unifier.dummy.DoNothingClass1", newBytes, 0, newBytes.length); }}; Class<?> originalClass = originalClassLoader.clazz; Class<?> newClass = newClassLoader.clazz; Field[] originalFields = originalClass.getFields(); Field[] newFields = newClass.getFields(); assertEquals(1, originalFields.length); assertEquals(2, newFields.length); assertNotNull(newClass.getField("myString")); assertNull(newClass.getField("myString").get(newClass.newInstance())); } static class ShimClass { private final String name; private final ShimField field; private final List<ShimMethod> methods; private final int version = Opcodes.V1_5; private final int access = Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER; // private final String signature = null; TODO later private final String superName; private final String[] interfaces; ShimClass(String name, List<ShimMethod> methods, ShimField field, String superName, String... interfaces) { this.name = name; this.methods = methods; // make plural this.field = field; // make plural this.superName = superName; this.interfaces = interfaces; } } @Test public void readsAsmAddsNewClass() throws Exception { String generatedBytecodeDir = GENERATED_BYTECODE + "/asm-adds-class/"; ShimField newField = new ShimField("myString", Type.getDescriptor(String.class), Opcodes.ACC_PUBLIC); ShimMethod newMethodInit = new ShimMethod("<init>", "Lcom/jawspeak/unifier/dummy/DoNothingClass1;", void.class); ShimMethod newMethod1 = new ShimMethod("method1", "Lcom/jawspeak/unifier/dummy/DoNothingClass1;", void.class); ShimClass shimClass = new ShimClass("com/jawspeak/unifier/dummy/DoNothingClass1", Lists.newArrayList(newMethodInit, newMethod1), newField, "java/lang/Object"); writeOutAsmFilesWithNewClass(generatedBytecodeDir, shimClass); classPath = new ClassPathFactory().createFromPath(generatedBytecodeDir); final byte[] newBytes = readInputStream(classPath.getResourceAsStream("com/jawspeak/unifier/dummy/DoNothingClass1.class")).toByteArray(); assertTrue(newBytes.length > 0); class MyClassLoader extends ClassLoader { Class<?> clazz; } MyClassLoader newClassLoader = new MyClassLoader() {{ clazz = defineClass("com.jawspeak.unifier.dummy.DoNothingClass1", newBytes, 0, newBytes.length); }}; Class<?> newClass = newClassLoader.clazz; assertEquals(1, newClass.getFields().length); Method[] methods = newClass.getMethods(); Constructor[] constructors = newClass.getConstructors(); try { newClass.newInstance(); fail("expected exception"); } catch (UnsupportedOperationException expected) { assertTrue(expected.getMessage().contains("Operation added to unify interfaces for compile time, but should not be called.")); } assertEquals(2 + 8, newClass.getMethods().length); assertEquals(1, newClass.getConstructors().length); assertNotNull(newClass.getField("myString")); assertNotNull(newClass.getMethod("method1")); } private void writeOutDirectFiles(String outputDir, String[] resources) throws IOException { File outputBase = new File(outputDir); outputBase.mkdir(); for (String resource : resources) { String[] pathAndFile = splitResourceToPathAndFile(resource); File output = new File(outputBase, pathAndFile[0]); output.mkdirs(); InputStream is = classPath.getResourceAsStream(resource); ByteArrayOutputStream baos = readInputStream(is); FileOutputStream os = new FileOutputStream(new File(output, pathAndFile[1])); os.write(baos.toByteArray()); os.close(); } } private void writeOutAsmFiles(String outputBaseDir, String[] resources) throws IOException { File outputBase = new File(outputBaseDir); outputBase.mkdir(); for (String resource : resources) { String[] pathAndFile = splitResourceToPathAndFile(resource); File packageDir = new File(outputBase, pathAndFile[0]); packageDir.mkdirs(); InputStream is = classPath.getResourceAsStream(resource); // Here's the key: read from the old bytes and write to the new ones. // Ends up just copying the byte array, but next we'll look at inserting something // interesting in between them. ClassReader reader = new ClassReader(is); ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_FRAMES); reader.accept(writer, 0); FileOutputStream os = new FileOutputStream(new File(packageDir, pathAndFile[1])); os.write(writer.toByteArray()); os.close(); } } private void writeOutAsmFilesWithNewMethod(String outputBaseDir, String[] resources, ShimMethod newMethod) throws IOException { File outputBase = new File(outputBaseDir); outputBase.mkdir(); for (String resource : resources) { String[] pathAndFile = splitResourceToPathAndFile(resource); File packageDir = new File(outputBase, pathAndFile[0]); packageDir.mkdirs(); InputStream is = classPath.getResourceAsStream(resource); ClassReader reader = new ClassReader(is); ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_FRAMES); // The key: insert an adapter in here, as discussed in 2.2.4 of asm guide pdf. ModifyingClassAdapter adapter = new ModifyingClassAdapter(writer, newMethod, null); reader.accept(adapter, 0); FileOutputStream os = new FileOutputStream(new File(packageDir, pathAndFile[1])); os.write(writer.toByteArray()); os.close(); } } private void writeOutAsmFilesWithNewField(String outputBaseDir, String[] resources, ShimField newField) throws IOException { File outputBase = new File(outputBaseDir); outputBase.mkdir(); for (String resource : resources) { String[] pathAndFile = splitResourceToPathAndFile(resource); File packageDir = new File(outputBase, pathAndFile[0]); packageDir.mkdirs(); InputStream is = classPath.getResourceAsStream(resource); ClassReader reader = new ClassReader(is); ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_FRAMES); // The key: insert an adapter in here, as discussed in 2.2.4 of asm guide pdf. ModifyingClassAdapter adapter = new ModifyingClassAdapter(writer, null, newField); reader.accept(adapter, 0); FileOutputStream os = new FileOutputStream(new File(packageDir, pathAndFile[1])); os.write(writer.toByteArray()); os.close(); } } private void writeOutAsmFilesWithNewClass(String outputBaseDir, ShimClass newClass) throws IOException { File outputBase = new File(outputBaseDir); outputBase.mkdir(); String[] pathAndFile = splitResourceToPathAndFile(newClass.name); File packageDir = new File(outputBase, pathAndFile[0]); packageDir.mkdirs(); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES); writer.visit(newClass.version, newClass.access, newClass.name, null, newClass.superName, newClass.interfaces); if (newClass.field != null) { ShimField newField = newClass.field; // Just this will add the field, but not set it to the default value. Thus it'll let compilation work, but may fail with runtime. (NPE) FieldVisitor fv = writer.visitField(newField.access, newField.name, newField.desc, null, null); fv.visitEnd(); } for (ShimMethod newMethod : newClass.methods) { // could also have a List<Runnable> like Misko did and record what i want to do in here, then execute it at end. if (newMethod != null) { // TODO handle these params via helper classes / the ShimClass's methods. // I created this code with the ASMifier eclipse plugin tool. MethodVisitor mv = writer.visitMethod(Opcodes.ACC_PUBLIC, newMethod.name, "()V", null, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); mv.visitTypeInsn(Opcodes.NEW, "java/lang/UnsupportedOperationException"); mv.visitInsn(Opcodes.DUP); mv.visitLdcInsn("Operation added to unify interfaces for compile time, but should not be called."); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/UnsupportedOperationException", "<init>", "(Ljava/lang/String;)V"); mv.visitInsn(Opcodes.ATHROW); Label l1 = new Label(); mv.visitLabel(l1); mv.visitLocalVariable("this", newMethod.thisClassDesc, null, l0, l1, 0); mv.visitMaxs(3, 1); mv.visitEnd(); } } writer.visitEnd(); FileOutputStream os = new FileOutputStream(new File(packageDir, pathAndFile[1] + ".class")); os.write(writer.toByteArray()); os.close(); } private ByteArrayOutputStream readInputStream(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int toRead; int offset = 0; while((toRead = is.available()) > 0) { byte[] buf = new byte[toRead]; is.read(buf, offset, toRead); baos.write(buf); offset += toRead; } is.close(); return baos; } private String[] splitResourceToPathAndFile(String resource) { int lastSlash = resource.lastIndexOf("/"); if (lastSlash == -1) { return new String[] {"", resource}; } return new String[] {resource.substring(0, lastSlash), resource.substring(lastSlash, resource.length())}; } }
package com.days.moment.miniboard.config; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @MapperScan(basePackages = "com.days.moment.miniboard.mapper") @ComponentScan(basePackages = "com.days.moment.miniboard.service") @Import(MiniAOPConfig.class) public class MiniRootConfig { }
package com.tencent.mm.ui.chatting; import com.tencent.mm.ui.LauncherUI; import com.tencent.mm.ui.conversation.BaseConversationUI; class y$8 implements Runnable { final /* synthetic */ y tMm; y$8(y yVar) { this.tMm = yVar; } public final void run() { boolean z = true; if (this.tMm.isCurrentActivity) { y.k(this.tMm); } else if (this.tMm.thisActivity() instanceof LauncherUI) { LauncherUI launcherUI = (LauncherUI) this.tMm.thisActivity(); if (launcherUI != null) { if (this.tMm.isSupportNavigationSwipeBack()) { z = false; } launcherUI.closeChatting(z); } } else if (this.tMm.thisActivity() instanceof BaseConversationUI) { BaseConversationUI baseConversationUI = (BaseConversationUI) this.tMm.thisActivity(); if (baseConversationUI != null) { if (this.tMm.isSupportNavigationSwipeBack()) { z = false; } baseConversationUI.closeChatting(z); } } } }
package java00; import java.util.Scanner; public class java0005 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scn = new Scanner(System.in); int n = 10; int m = 10; int data[][] = new int[n][m]; for (int i = 0; i <= 9; i++) { for (int j = 0; j <= 9; j++) { int b = (int) (Math.random() * 10+1); data[i][j] = b; } int a = (int) (Math.random() * 10+1); } for (int x = 0; x <= 9; x++) { for (int y = 0; y <= 9; y++) { System.out.print(data[x][y] + "\t"); } System.out.println(""); } } }
package com.tencent.mm.plugin.appbrand.appcache; import android.widget.Toast; import com.tencent.mm.plugin.appbrand.appcache.an.b; import com.tencent.mm.plugin.appbrand.s.j; import com.tencent.mm.plugin.appbrand.task.e; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.bi; class an$b$1 implements Runnable { final /* synthetic */ String bAj; final /* synthetic */ int fhP; final /* synthetic */ String fhQ; final /* synthetic */ b fhR; an$b$1(b bVar, String str, int i, String str2) { this.fhR = bVar; this.bAj = str; this.fhP = i; this.fhQ = str2; } public final void run() { e.aN(this.bAj, this.fhP); Toast.makeText(ad.getContext(), ad.getContext().getString(j.app_brand_pkg_updated_should_reboot, new Object[]{bi.aG(this.fhQ, this.bAj)}), 1).show(); } }
package lesson3.preIntermediate; /** * Created by Angelina on 22.01.2017. */ public class Task7 { public static void main(String[] args) { Task7 t7 = new Task7(); t7.maxMinMult2(); } int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int tempMin = arr[0]; int tempMax = arr[0]; public void maxMinMult2() { System.out.println("Given an array of integers. Write a method which finds max and min elements in it and multiplies them by 2"); for (int i = 0; i < arr.length; i++) { if (arr[i] > tempMax) { tempMax = arr[i]; } else if (arr[i] < tempMin) { tempMin = arr[i]; } } tempMax = tempMax * 2; tempMin = tempMin * 2; System.out.println("max * 2 = " + tempMax + '\n' + "min * 2 = " + tempMin); } }
package com.eb.dto; public class SubBoardDTO { }
package com.tt.miniapp.storage.path; public class AppbrandCpTempPath extends AbsAppbrandPath { public boolean canRead() { return true; } public boolean canWrite() { return false; } public boolean isCleanable() { return true; } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\storage\path\AppbrandCpTempPath.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.apri.test.service.impl; import com.apri.test.dao.MahasiswaDAO; import com.apri.test.entity.Mahasiswa; import com.apri.test.service.MahasiswaService; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MahasiswaServiceImpl implements MahasiswaService { @Autowired private MahasiswaDAO mahasiswaDAO; @Override public List<Mahasiswa> findByMahasiswa(Mahasiswa param) { return mahasiswaDAO.findByMahasiswa(param); } @Override public Mahasiswa findByNim(int nim) { return mahasiswaDAO.findByNim(nim); } @Override public Mahasiswa save(Mahasiswa param) { return mahasiswaDAO.save(param); } @Override public Mahasiswa update(Mahasiswa param) { return mahasiswaDAO.update(param); } @Override public int delete(Mahasiswa param) { return mahasiswaDAO.delete(param); } @Override public Mahasiswa findById(int id) { return mahasiswaDAO.findById(id); } @Override public List<Mahasiswa> findAll() { return mahasiswaDAO.findAll(); } }
package Task07; import java.util.Scanner; public class Task07 { public static void main(String args[]) { Scanner keyboard = new Scanner(System.in); double number, sum; sum = 0; for (int i = 1; i <= 5; i++) { System.out.print("Type a number: "); number = keyboard.nextDouble(); if (number > sum) { sum = number; } } System.out.println("The sum of the numbers is: " + sum); keyboard.close(); } }
/* * GNUnetWebUI - A Web User Interface for P2P networks. <https://gitorious.org/gnunet-webui> * Copyright 2013 Sébastien Moratinos <sebastien.moratinos@gmail.com> * * * This file is part of GNUnetWebUI. * * GNUnetWebUI is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GNUnetWebUI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with GNUnetWebUI. If not, see <http://www.gnu.org/licenses/>. */ package org.gnunet.integration.fs; import static akka.pattern.Patterns.ask; import java.util.Date; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.gnunet.integration.internal.actorsystem.MsgCreator; import org.gnunet.integration.internal.execute.CLISearchMsg; import org.gnunet.integration.internal.models.Search; import org.gnunet.integration.internal.persistor.SearchEntity; import org.gnunet.integration.internal.persistor.SearchFoundEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.concurrent.Await; import scala.concurrent.duration.Duration; import akka.actor.ActorRef; import akka.actor.Props; import akka.actor.UntypedActor; /** * Worker which search content. * Search with the executor initialized. * Doesn't send result to the initial sender of the search command. * Send the result to the notifier initialized. * Each searchMsg and SearchResult is persisted by the persitor initialized * * * @author smoratinos * */ @MsgCreator public class PersistAndNotifySearcherWorker extends UntypedActor { private final static Logger log = LoggerFactory.getLogger(PersistAndNotifySearcherWorker.class); public final static String MSG_PREFIX = "dse_"; private final static AtomicLong msgCount = new AtomicLong(0); private final ActorRef notifier; private final ActorRef persistorWorker; private final ActorRef executor; public static Props mkProps(final ActorRef notifier, final ActorRef persistorWorker, final ActorRef executor) { return Props.create(PersistAndNotifySearcherWorker.class, notifier, persistorWorker, executor); } public PersistAndNotifySearcherWorker(final ActorRef notifier, final ActorRef persistorWorker, final ActorRef executor) { super(); this.notifier = notifier; this.persistorWorker = persistorWorker; this.executor = executor; } @Override public void preStart() { log.info("Starting DefaultSearcherWorker instance # {} {}", self().hashCode(), self().path()); } /** * {@link SearchMsg} : * - First : {@link #persit(SearchEntity)} * - Next : send the model to {@link #executor} and {@link #notifier} * {@link SearchResultMsg} : * - First : {@link #persit(SearchFoundEntity)} * - send the model to {@link #notifier} * other message : * {@link akka.actor.UntypedActor#unhandled(Object)}. */ @Override public void onReceive(final Object message) throws Exception { log.debug("message={}", message); if (message instanceof SearchMsg) { SearchMsg form = (SearchMsg) message; log.debug("receive CLISearchMsg by " + form.getUsername()); SearchEntity entity = extractEntity(form); // TODO persistor can return a PersistorViolationsMsg if search is not valid SearchEntity entityWithId = persit(entity); log.debug("saved searchWithId=" + entityWithId); Search model = extractModel(entity); CLISearchMsg cmd = new CLISearchMsg(MSG_PREFIX + msgCount.incrementAndGet(), ((SearchMsg) message).getMsgId(), entityWithId.id, null, model); executor.tell(cmd, self()); notifier.tell(cmd, self()); } else if (message instanceof SearchResultMsg) { SearchResultMsg sResult = (SearchResultMsg) message; log.debug("receive SearchResultMsg " + sResult); SearchFoundEntity found = SearchFoundEntity.fromSearchResult(sResult.getDate(), sResult.getOutputFileName(), sResult.getUri().getBytes(), sResult.getCommand().getId()); log.debug("SearchFoundEntity " + found); found = persit(found); log.debug("saved found=" + found); notifier.tell(sResult, self()); } else { log.warn("unhandled {}", message); unhandled(message); } } private Search extractModel(final SearchEntity entity) { return new Search(entity.getUsername(), entity.getAskDate(), entity.getKeywords(), entity.getAnonymity(), entity.getRemote(), entity.getMaxResult(), entity.getTimeout()); } protected SearchEntity persit(final SearchEntity search) throws Exception { return (SearchEntity) Await.result(ask(persistorWorker, search, 10000), Duration.create(5, TimeUnit.SECONDS)); } protected SearchFoundEntity persit(final SearchFoundEntity found) throws Exception { return (SearchFoundEntity) Await.result(ask(persistorWorker, found, 10000), Duration.create(5, TimeUnit.SECONDS)); } private SearchEntity extractEntity(final SearchMsg sCommand) { SearchEntity search = new SearchEntity(sCommand.getUsername(), new Date(), sCommand.getKeywords()); search.anonymity = sCommand.getAnonymity(); search.executorPath = executor.path().name(); search.inProgress = true; search.maxResult = sCommand.getMaxResult(); search.remote = sCommand.getRemote(); search.searcherPath = self().path().name(); search.timeout = sCommand.getTimeout(); return search; } @Override public void postStop() { log.info("Stopping DefaultSearcherWorker instance # {} {}", self().hashCode(), self().path()); } }
package com.everis.service.dao.util; /** * @author gbritoch * */ public class UserLogViewerDAOConstants { public static final String CPF_CNPJ_FILTER = "cpfcnpj"; public static final String DATA_HORA_FILTER = "datahora"; public static final String CLASS_FILTER = "class"; public static final String ORIGEM_FILTER = "origem"; public static final String STATUS_FILTER = "status"; public static final String KEYWORD_STRING = "keyword"; public static final String DATE1_STRING = "date1"; public static final String DATE2_STRING = "date2"; public static final String ID_STRING = "id"; }
package Manufacturing.ProductLine.Producer; import Presentation.Protocol.IOManager; /** * 细加工生产方式类. * * @author 孟繁霖 * @date 2021-10-12 8:55 */ public class FineProducer implements ProduceManner { @Override public void produce() { IOManager.getInstance().print( "细加工:切块去核->冰糖小火熬制->加入添加剂->大火熬制->出锅密封保存", "細加工:切塊去核->冰糖小火熬製->加入添加劑->大火熬製->出鍋密封保存", "Fine processing: cut into pieces and remove core -> rock sugar boiled on low fire -> added additives -> boiled on high fire -> sealed and stored out of the pot" ); } }
package itis; import com.fasterxml.jackson.core.JsonProcessingException; public interface MessageI { Object getBody() throws JsonProcessingException; void accepted(); void completed(); }
package br.com.fiap.trabalho.rm78856; import android.app.ActivityOptions; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import java.util.List; public class CardapioActivity extends AppCompatActivity { Database db; Toolbar toolbar; ListView lstPizzas; List<Pizza> pizzas; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cardapio); db = new Database(this); toolbar = findViewById(R.id.toolbar_main); toolbar.setTitle("Cardápio"); setSupportActionBar( toolbar ); lstPizzas = findViewById(R.id.lstPizzas); pizzas = GeraListaPizzas.geraPizzas(); PizzasAdapter adapter = new PizzasAdapter(this, pizzas); lstPizzas.setAdapter(adapter); lstPizzas.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent it = new Intent(CardapioActivity.this, DetalhesActivity.class); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(CardapioActivity.this); it.putExtra("id", position); startActivity(it, options.toBundle()); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.mniConfig){ Intent it = new Intent(CardapioActivity.this, ConfigActivity.class); startActivity(it); } else if(item.getItemId() == R.id.mniSair) { Intent it = new Intent(CardapioActivity.this, LoginActivity.class); startActivity(it); finish(); } return super.onOptionsItemSelected(item); } @Override protected void onStart() { super.onStart(); Log log = new Log(); log.setDescricao( "CardapioActivity" ); log.setData( System.currentTimeMillis() ); db.criarLog(log); } }
package com.csc214.rvandyke.assignment6application.model; import android.support.annotation.NonNull; import java.util.Date; import java.util.UUID; /** * Rebecca Van Dyke * rvandyke@u.rochester.edu * CSC 214 Assignment 6 * TA:Julian Weiss */ public class BhangraTeam implements Comparable<BhangraTeam>{ private String mName; private String mTown; private int mDateFounded; //founding year private String mDescription; private UUID mId; public BhangraTeam(String name, String town, String description, int founding){ mName = name; mTown = town; mDateFounded = founding; mDescription = description; mId = UUID.randomUUID(); } public String getName(){ return mName; } public String getTown(){ return mTown; } public String getDescription(){ return mDescription; } public int getDateFounded(){ return mDateFounded; } public UUID getId(){ return mId; } @Override public String toString(){ return getName() + ", founded in " + getDateFounded() + " in " + getTown(); } @Override public int compareTo(@NonNull BhangraTeam o) { if(o.getName().equals(this.getName())){ return 0; } if(o.getName().compareTo(this.getName()) < 0){ return -1; } else{ return 1; } } } //end class
package menus; import java.awt.Color; import java.awt.Dimension; import javax.swing.JColorChooser; import javax.swing.JOptionPane; import frames.ResizeFrame; import main.GConstants; import main.GConstants.ELineDot; import main.GConstants.ELineThick; import main.GConstants.EShapeMenu; import main.GConstants.IMenu; import shape.GShape; public class GShapeMenu extends GMenu { // attributes private static final long serialVersionUID = GConstants.serialVersionUID; // components public GShapeMenu(String name) { super(name); } public void initialize() { } // method public void fillC() { Color originColor = gPanelArea.getCurrentPanel().getFillColor(); Color newColor = JColorChooser.showDialog(null, "Color Selection", originColor); if (newColor != null) { gPanelArea.getCurrentPanel().setFillColor(newColor); } } public void lineC() { Color originColor = gPanelArea.getCurrentPanel().getFillColor(); Color newColor = JColorChooser.showDialog(null, "Color Selection", originColor); if (newColor != null) { gPanelArea.getCurrentPanel().setLineColor(newColor); } } public void lineThick() { Object[] list = new Object[ELineThick.values().length]; for (int i = 0; i < list.length; i++) { list[i] = ELineThick.values()[i].getValue(); } Object selected = JOptionPane.showInputDialog(null, "테두리의 두께를 선택하세요", "선 두께 변경", JOptionPane.QUESTION_MESSAGE, null, list, gPanelArea.getCurrentPanel().getLineThick()); if (selected != null) { gPanelArea.getCurrentPanel().setLineThick((int) selected); } } public void lineDot() { Object[] list = new Object[ELineDot.values().length]; for (int i = 0; i < list.length; i++) { list[i] = ELineDot.values()[i].getSecond(); } Object selected = JOptionPane.showInputDialog(null, "점선 스타일을 선택하세요", "점선 스타일 변경", JOptionPane.QUESTION_MESSAGE, null, list, gPanelArea.getCurrentPanel().getLineDot()); if (selected != null) { gPanelArea.getCurrentPanel().setLineDot((float) selected); } } public void horizontalFlip() { gPanelArea.getCurrentPanel().setFlip(0, 1); } public void verticalFlip() { gPanelArea.getCurrentPanel().setFlip(1, 0); } public void resize() { GShape shapes = gPanelArea.getCurrentPanel().getSelectedShape(); if (shapes != null) { Dimension d = new Dimension(); d.setSize(shapes.getBounds().getWidth(), shapes.getBounds().getHeight()); new ResizeFrame(d, gPanelArea, "resizeShape", "너비", "높이"); } } public void rotate() { if (gPanelArea.getCurrentPanel().getSelectedShape() != null) { String stringDegree = JOptionPane.showInputDialog("각도(정수)를 입력하세요(0~360, 단위 없이)"); try { int intDegree = Integer.parseInt(stringDegree); if (intDegree > 360 || intDegree < 0) { JOptionPane.showMessageDialog(null, "범위 외의 값이 입력되었습니다.", "입력 오류", JOptionPane.ERROR_MESSAGE); } else { gPanelArea.setShapeRotate(intDegree); } } catch (NumberFormatException format) { JOptionPane.showMessageDialog(null, "정수가 아닌 값이 입력되었습니다.", "형식 오류", JOptionPane.ERROR_MESSAGE); } } } public void move() { GShape shapes = gPanelArea.getCurrentPanel().getSelectedShape(); if (shapes != null) { Dimension d = new Dimension(); d.setSize(shapes.getBounds().getX(), shapes.getBounds().getY()); new ResizeFrame(d, gPanelArea, "changeLocation", "X좌표", "Y좌표"); } } public void shapeUp() { gPanelArea.getCurrentPanel().shapeUp(); } public void shapeDown() { gPanelArea.getCurrentPanel().shapeDown(); } public void shapeLeft() { gPanelArea.getCurrentPanel().shapeLeft(); } public void shapeRight() { gPanelArea.getCurrentPanel().shapeRight(); } @Override public IMenu[] values() { return EShapeMenu.values(); } }
package com.javakg.stroistat.repository; public interface RoleRepository { }
package com.tencent.mm.plugin.appbrand.config; public class WxaExposedParams$a { public String appId = ""; public int bJu = 0; public String bVs = ""; public int fih = -1; public int fii = -1; public String fso = ""; public String fsp = ""; public String iconUrl = ""; public String nickname = ""; public String username = ""; public final WxaExposedParams aeo() { return new WxaExposedParams(this, (byte) 0); } }
package com.forsrc.utils; import java.io.*; import java.nio.charset.Charset; import java.text.MessageFormat; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * The type File utils. */ public class FileUtils { /** * The constant LOCK. */ public static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock(); /** * The constant READ_LOCK. */ public static final Lock READ_LOCK = LOCK.readLock(); /** * The constant WRITE_LOCK. */ public static final Lock WRITE_LOCK = LOCK.writeLock(); private static final int BUFFER_SIZE = 1024 * 512; private static final Charset CHARSET = Charset.forName("UTF-8"); /** * The constant isDebug. */ public static boolean isDebug = false; /** * Read line. * * @param file the file * @param adapter the adapter * @param isUseLock the is use lock * @throws IOException the io exception */ public static void readLine(File file, FileReadLineAdapter adapter, boolean isUseLock) throws IOException { if (!isUseLock) { readLine(file, adapter); return; } READ_LOCK.lock(); try { readLine(file, adapter); } finally { READ_LOCK.unlock(); } } /** * Read line. * * @param file the file * @param adapter the adapter * @throws IOException the io exception */ public static void readLine(File file, FileReadLineAdapter adapter) throws IOException { if (file == null) { throw new IllegalArgumentException("File is null."); } if (!file.exists()) { throw new IllegalArgumentException("File is not exists: " + file); } long startTime = System.currentTimeMillis(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream( file)), BUFFER_SIZE); String line = null; long index = 0; while ((line = br.readLine()) != null) { index++; adapter.todo(index, line); } } catch (FileNotFoundException e) { throw e; } catch (IOException e) { throw e; } finally { closeQuietly(br); } if (isDebug) { LogUtils.LOGGER.debug(String.format("%s readLine: %.3f s", Thread .currentThread().getName(), (System.currentTimeMillis() - startTime) / 1000f)); } } /** * Random access file read line. * * @param file the file * @param start the start * @param length the length * @param adapter the adapter * @param isUseLock the is use lock * @throws IOException the io exception */ public static void randomAccessFileReadLine(File file, long start, long length, FileReadLineAdapter adapter, boolean isUseLock) throws IOException { if (!isUseLock) { randomAccessFileReadLine(file, start, length, adapter); return; } READ_LOCK.lock(); try { randomAccessFileReadLine(file, start, length, adapter); } finally { READ_LOCK.unlock(); } } /** * Random access file read line. * * @param file the file * @param start the start * @param length the length * @param adapter the adapter * @throws IOException the io exception */ public static void randomAccessFileReadLine(File file, long start, long length, FileReadLineAdapter adapter) throws IOException { if (file == null) { throw new IllegalArgumentException("File is null."); } if (!file.exists()) { throw new IllegalArgumentException("File is not exists: " + file); } long startTime = System.currentTimeMillis(); RandomAccessFile raf = null; try { raf = new RandomAccessFile(file, "r"); String line = null; long index = -1; while ((line = raf.readLine()) != null) { index++; if (index < start) { continue; } if (index - start >= length) { break; } adapter.todo(index, line); } } catch (FileNotFoundException e) { throw e; } catch (IOException e) { throw e; } finally { closeQuietly(raf); } if (isDebug) { LogUtils.LOGGER.debug(String.format("randomAccessFileReadLine: %.3f s", (System.currentTimeMillis() - startTime) / 1000f)); } } /** * Scanner read line. * * @param file the file * @param adapter the adapter * @param isUseLock the is use lock * @throws IOException the io exception */ public static void scannerReadLine(File file, FileReadLineAdapter adapter, boolean isUseLock) throws IOException { if (!isUseLock) { scannerReadLine(file, adapter); return; } READ_LOCK.lock(); try { scannerReadLine(file, adapter); } finally { READ_LOCK.unlock(); } } /** * Scanner read line. * * @param file the file * @param adapter the adapter * @throws FileNotFoundException the file not found exception */ public static void scannerReadLine(File file, FileReadLineAdapter adapter) throws FileNotFoundException { if (file == null) { throw new IllegalArgumentException("File is null."); } if (!file.exists()) { throw new IllegalArgumentException("File is not exists: " + file); } long startTime = System.currentTimeMillis(); Scanner scanner = null; try { scanner = new Scanner(file); } catch (FileNotFoundException e) { throw e; } long index = 0; while (scanner.hasNext()) { index++; String line = scanner.next(); adapter.todo(index, line); } if (scanner != null) { scanner.close(); } if (isDebug) { LogUtils.LOGGER.debug(String.format("scannerReadLine: %.3f s", (System.currentTimeMillis() - startTime) / 1000f)); } } /** * Read line. * * @param file the file * @param start the start * @param length the length * @param adapter the adapter * @param isUseLock the is use lock * @throws IOException the io exception */ public static void readLine(final File file, final long start, final long length, FileReadLineAdapter adapter, boolean isUseLock) throws IOException { if (!isUseLock) { readLine(file, start, length, adapter); return; } READ_LOCK.lock(); try { readLine(file, start, length, adapter); } finally { READ_LOCK.unlock(); } } /** * Read line. * * @param file the file * @param start the start * @param length the length * @param adapter the adapter * @throws IOException the io exception */ public static void readLine(final File file, final long start, final long length, FileReadLineAdapter adapter) throws IOException { if (file == null) { throw new IllegalArgumentException("File is null."); } if (!file.exists()) { throw new IllegalArgumentException("File is not exists: " + file); } if (start >= file.length()) { throw new IllegalArgumentException(String.format( "The start(%s) >= file(%s) length(%s)", start, file, file.length())); } long readLength = length <= 0 ? file.length() : length; long readStart = start <= 0 ? 0 : start; long startTime = System.currentTimeMillis(); BufferedReader br = null; FileInputStream is = null; try { is = new FileInputStream(file); br = new BufferedReader(new InputStreamReader(is), BUFFER_SIZE); is.getChannel().position(readStart); String line = null; long index = 0; long pos = is.getChannel().position(); for (long i = pos; i >= 0; i--) { is.getChannel().position(i); int c = is.read(); if (c == '\n') { readStart = i + 1; break; } } readLength = readStart + readLength > file.length() ? file.length() - readStart : readLength; is.getChannel().position(readStart); pos = readStart; while ((line = br.readLine()) != null) { index++; pos += line.getBytes(CHARSET).length + 2; if (pos > readStart + readLength) { break; } if (adapter != null) { adapter.todo(index, line); } } } catch (FileNotFoundException e) { throw e; } catch (IOException e) { throw e; } finally { closeQuietly(is); closeQuietly(br); } if (isDebug) { LogUtils.LOGGER.debug(String.format("%s readLine: %.3f s", Thread .currentThread().getName(), (System.currentTimeMillis() - startTime) / 1000f)); } } /** * Rewrite line. * * @param file the file * @param saveFile the save file * @param start the start * @param length the length * @param adapter the adapter * @param isUseLock the is use lock * @throws IOException the io exception */ public static void rewriteLine(final File file, final File saveFile, final long start, final long length, FileWriteReadLineAdapter adapter, boolean isUseLock) throws IOException { if (!isUseLock) { rewriteLine(file, saveFile, start, length, adapter); return; } WRITE_LOCK.lock(); try { rewriteLine(file, saveFile, start, length, adapter); } finally { WRITE_LOCK.unlock(); } } /** * Rewrite line. * * @param file the file * @param saveFile the save file * @param start the start * @param length the length * @param adapter the adapter * @throws IOException the io exception */ public static void rewriteLine(final File file, final File saveFile, final long start, final long length, FileWriteReadLineAdapter adapter) throws IOException { if (file == null) { throw new IllegalArgumentException("File is null."); } if (saveFile == null) { throw new IllegalArgumentException("SaveFile is null."); } if (!file.exists()) { throw new IllegalArgumentException("File is not exists: " + file); } if (start >= file.length()) { LogUtils.LOGGER.debug(MessageFormat.format( "[SKIP] The start({0}) >= file({1}) length({2})", start, file, file.length())); return; } long readLength = length <= 0 ? file.length() : length; long readStart = start <= 0 ? 0 : start; long startTime = System.currentTimeMillis(); BufferedReader br = null; BufferedWriter bw = null; FileInputStream is = null; try { is = new FileInputStream(file); br = new BufferedReader(new InputStreamReader(is), BUFFER_SIZE); bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(saveFile, false)), BUFFER_SIZE); is.getChannel().position(readStart); String line = null; long index = 0; long pos = is.getChannel().position(); for (long i = pos; i >= 0; i--) { is.getChannel().position(i); int c = is.read(); if (c == '\n') { readStart = i + 1; break; } } readLength = readStart + readLength > file.length() ? file.length() - readStart : readLength; is.getChannel().position(readStart); pos = readStart; while ((line = br.readLine()) != null) { index++; pos += line.getBytes(CHARSET).length + 2; if (pos > readStart + readLength) { break; } if (adapter != null) { line = adapter.todo(index, line); } bw.write(line); bw.newLine(); } } catch (FileNotFoundException e) { throw e; } catch (IOException e) { throw e; } finally { closeQuietly(is); closeQuietly(br); closeQuietly(bw); } if (isDebug) { LogUtils.LOGGER.debug(String.format( "%s rewriteLine(%s, %s, %s, %s, %s): %.3f s", Thread .currentThread().getName(), file, saveFile, start, length, adapter, (System.currentTimeMillis() - startTime) / 1000f)); } } /** * Cut file. * * @param file the file * @param length the length * @throws IOException the io exception */ public static void cutFile(File file, long length) throws IOException { cutFile(file, length, null); } /** * Cut file. * * @param file the file * @param length the length * @param adapter the adapter * @throws IOException the io exception */ public static void cutFile(File file, long length, FileWriteReadLineAdapter adapter) throws IOException { check(file); if (length >= file.length()) { //return; } if (length < 1024 * 1024 * 10) { // return; } int count = (int) Math.ceil(file.length() / length) + 1; long start = 0; for (int i = 0; i < count; i++) { File saveFile = new File(MessageFormat.format("{0}.{1}", file, i)); rewriteLine(file, saveFile, start, length, adapter); start += length; } // LogUtils.LOGGER.debug(String.format("%s rewriteLine(%s, %s, %s): %.3f s", // Thread.currentThread().getName(), file, length, adapter, // (System.currentTimeMillis() - startTime) / 1000f)); } /** * Check. * * @param file the file */ public static void check(File file) { if (file == null) { throw new IllegalArgumentException("File is null."); } if (!file.exists()) { throw new IllegalArgumentException("File is not exists: " + file); } } /** * Thread read line. * * @param file the file * @param length the length * @param thread the thread * @param adapter the adapter * @throws IOException the io exception * @throws InterruptedException the interrupted exception */ public static void threadReadLine(final File file, final long length, int thread, final FileReadLineAdapter adapter) throws IOException, InterruptedException { check(file); if (length >= file.length()) { // return; } long startTime = System.currentTimeMillis(); ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3, thread >= 3 ? thread : 3, 10, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(3), new ThreadPoolExecutor.CallerRunsPolicy()); // ExecutorService threadPool = Executors.newFixedThreadPool(thread); int count = (int) Math.ceil(file.length() / length) + 1; long start = 0; for (int i = 0; i < count; i++) { final long s = start; threadPool.execute(new Runnable() { @Override public void run() { try { readLine(file, s, length, adapter); } catch (IOException e) { LogUtils.LOGGER.error(e.getMessage(), e); } } }); start += length; } threadPool.shutdown(); try { while (threadPool != null && !threadPool.awaitTermination(1, TimeUnit.SECONDS)) { } } catch (InterruptedException e) { throw e; } finally { threadPool.shutdownNow(); } if (isDebug) { LogUtils.LOGGER.debug(String.format("threadReadLine(%s, %s, %s): %.3f s", file, length, adapter, (System.currentTimeMillis() - startTime) / 1000f)); } } /** * Thread cut file. * * @param file the file * @param length the length * @param thread the thread * @param adapter the adapter * @throws InterruptedException the interrupted exception */ public static void threadCutFile(final File file, final long length, int thread, final FileWriteReadLineAdapter adapter) throws InterruptedException { check(file); if (length >= file.length()) { // return; } long startTime = System.currentTimeMillis(); ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3, thread >= 3 ? thread : 3, 10, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(3), new ThreadPoolExecutor.CallerRunsPolicy()); // ExecutorService threadPool = Executors.newFixedThreadPool(thread); int count = (int) Math.ceil(file.length() / length) + 1; for (int i = 0; i < count; i++) { threadPool.execute(new Runnable() { @Override public void run() { try { cutFile(file, length, adapter); } catch (IOException e) { LogUtils.LOGGER.error(e.getMessage(), e); } } }); } threadPool.shutdown(); try { while (threadPool != null && !threadPool.awaitTermination(1, TimeUnit.SECONDS)) { } } catch (InterruptedException e) { throw e; } finally { threadPool.shutdownNow(); } if (isDebug) { LogUtils.LOGGER.debug(String.format("threadCutFile(%s, %s, %s): %.3f s", file, length, adapter, (System.currentTimeMillis() - startTime) / 1000f)); } } /** * Save file. * * @param src the src * @param dst the dst * @return boolean * @throws IOException the io exception * @Title: saveFile * @Description: */ public static void saveFile(File src, File dst) throws IOException { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src), 1024 * 10); out = new BufferedOutputStream(new FileOutputStream(dst), 1024 * 10); byte[] buffer = new byte[1024 * 10]; int len = 0; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (IOException e) { throw e; } finally { closeQuietly(in); closeQuietly(out); } } /** * Sets file txt. * * @param file the file * @param info the info * @return void * @throws IOException the io exception * @Title: setFileTxt * @Description: */ public static void setFileTxt(File file, String info) throws IOException { setFileTxt(file, info, false); } /** * Sets file txt. * * @param file the file * @param info the info * @param append the append * @return void * @throws IOException the io exception * @Title: setFileTxt * @Description: */ public static void setFileTxt(File file, String info, boolean append) throws IOException { setFileTxt(file, info, Charset.defaultCharset(), append); } /** * Sets file txt. * * @param file the file * @param info the info * @param charset the charset * @param append the append * @throws IOException the io exception */ public static void setFileTxt(File file, String info, Charset charset, boolean append) throws IOException { BufferedWriter bw = null; try { bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(file, append), charset)); bw.write(info); bw.flush(); } catch (IOException e) { throw e; } finally { closeQuietly(bw); } } /** * Gets file txt. * * @param file the file * @return String file txt * @throws IOException the io exception * @Title: getFileTxt * @Description: */ public static String getFileTxt(File file) throws IOException { return getFileTxt(file, -1, -1); } /** * Gets file txt. * * @param file the file * @param startLine the start line * @param countLine the count line * @return String file txt * @throws IOException the io exception * @Title: getFileTxt * @Description: */ public static String getFileTxt(File file, long startLine, long countLine) throws IOException { return getFileTxt(file, Charset.defaultCharset(), startLine, countLine); } /** * Gets file txt. * * @param file the file * @param charset the charset * @param startLine the start line * @param countLine the count line * @return String file txt * @throws IOException the io exception * @Title: getFileTxt * @Description: */ public static String getFileTxt(File file, Charset charset, long startLine, long countLine) throws IOException { // if (file == null || !file.exists()) { // throw new FileNotFoundException(file.getAbsolutePath()); // } String info = ""; BufferedReader br = null; long start = startLine < 0 ? 0 : startLine; long count = countLine < 0 ? -1 : countLine; try { br = new BufferedReader(new InputStreamReader( charset == null ? new FileInputStream(file) : new FileInputStream(file), charset), 1024 * 10); StringBuffer sb = new StringBuffer(); String s = ""; long index = 0; while ((s = br.readLine()) != null) { if (index++ < start) { continue; } sb.append(s); sb.append("\n"); if (count == -1) { continue; } count--; if (count <= 0) { break; } } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } info = sb.toString(); } catch (IOException e) { throw e; } finally { closeQuietly(br); } return info; } /** * Gets file list. * * @param dir the dir * @param arrayList the array list * @return the file list */ public static boolean getFileList(File dir, Set<File> arrayList) { return getFileList(dir, null, arrayList); } /** * Gets file list. * * @param dir the dir * @param filter the filter * @param set the set * @return the file list */ public static boolean getFileList(File dir, FileFilter filter, Set<File> set) { if (dir == null || !dir.exists()) { return false; } if (set == null) { set = new HashSet<File>(); } if (dir.isFile()) { return true; } File[] files = filter == null ? dir.listFiles() : dir.listFiles(filter); for (File f : files) { set.add(f); if (f.isDirectory()) { getFileList(f, filter, set); continue; } } return true; } /** * Close. * * @param in the in * @throws IOException the io exception */ public static void close(InputStream in) throws IOException { if (in == null) { return; } try { in.close(); } catch (IOException e) { throw e; } } /** * Close. * * @param out the out * @throws IOException the io exception */ public static void close(OutputStream out) throws IOException { if (out == null) { return; } try { out.close(); } catch (IOException e) { throw e; } } /** * Close. * * @param in the in * @param out the out * @throws IOException the io exception */ public static void close(InputStream in, OutputStream out) throws IOException { try { close(in); } catch (IOException e) { throw e; } finally { try { close(out); } catch (IOException e) { throw e; } } } /** * Close. * * @param br the br * @throws IOException the io exception */ public static void close(BufferedReader br) throws IOException { if (br == null) { return; } try { br.close(); } catch (IOException e) { throw e; } } /** * Close. * * @param bw the bw * @throws IOException the io exception */ public static void close(BufferedWriter bw) throws IOException { if (bw == null) { return; } try { bw.close(); } catch (IOException e) { throw e; } } /** * Close. * * @param in the in * @param out the out * @throws IOException the io exception */ public static void close(BufferedReader in, BufferedWriter out) throws IOException { try { close(in); } catch (IOException e) { throw e; } finally { try { close(out); } catch (IOException e) { throw e; } } } /** * Gets file info. * * @param file the file * @return the file info */ public static String getFileInfo(File file) { if (file == null) { return "File is null."; } if (!file.exists()) { return MessageFormat.format("Not exist: '{0}'", file); } return MessageFormat.format("{0} {1} {2}", DateTimeUtils.getDateTime(file.lastModified(), false), (file.isFile() ? "F" : "D"), (file.isFile() ? file.length() : "")); } /** * Read txt file string. * * @param file the file * @return the string * @throws IOException the io exception */ public static String readTxtFile(File file) throws IOException { return readTxtFile(file, null); } /** * Read txt file string. * * @param file the file * @param charset the charset * @return the string * @throws IOException the io exception */ public static String readTxtFile(File file, Charset charset) throws IOException { long fileLength = file.length(); if (fileLength >= Integer.MAX_VALUE) { return null; } byte[] b = new byte[(int) fileLength]; FileInputStream in = null; try { in = new FileInputStream(file); in.read(b); } catch (FileNotFoundException e) { throw e; } catch (IOException e) { throw e; } finally { closeQuietly(in); } return charset == null ? new String(b) : new String(b, charset); } /** * Read txt file. * * @param file the file * @param charset the charset * @param adapter the adapter * @param bufferSize the buffer size * @throws IOException the io exception */ public static void readTxtFile(File file, Charset charset, ReadTxtFileAdapter adapter, int bufferSize) throws IOException { long fileLength = file.length(); if (fileLength <= bufferSize) { adapter.todo(readTxtFile(file, charset)); return; } byte[] b = new byte[bufferSize]; FileInputStream in = null; int length = 0; try { in = new FileInputStream(file); while ((length = in.read(b)) != -1) { adapter.todo(charset == null ? new String(b, 0, length) : new String(b, 0, length, charset)); } } catch (FileNotFoundException e) { throw e; } catch (IOException e) { throw e; } finally { closeQuietly(in); } } /** * Read txt file. * * @param file the file * @param charset the charset * @param adapter the adapter * @param bufferSize the buffer size * @param lineBreak the line break * @throws IOException the io exception */ public static void readTxtFile(File file, Charset charset, ReadTxtFileAdapter adapter, int bufferSize, String lineBreak) throws IOException { long fileLength = file.length(); if (fileLength <= bufferSize) { adapter.todo(readTxtFile(file, charset)); return; } byte[] b = new byte[bufferSize]; FileInputStream in = null; int length = 0; try { in = new FileInputStream(file); String newLine = null; while ((length = in.read(b)) != -1) { String txt = charset == null ? new String(b, 0, length) : new String(b, 0, length, charset); if (newLine != null) { txt = String.format("%s%s", newLine, txt); } int offset = MyStringUtils.getLastLineBreakOffset(txt, lineBreak); if (offset == -1) { adapter.todo(txt); newLine = null; // System.out.println(" if (offset == -1)"); continue; } if (offset == 0 && lineBreak.length() == txt.length()) { System.out.println("----"); continue; } if (offset >= 0 && offset < txt.length()) { String txtTmp = txt; txt = txtTmp.substring(0, offset - 1); newLine = txtTmp.substring(offset + lineBreak.length()); adapter.todo(txt); // System.out.println("if (offset < length)"); continue; } // adapter.todo(txt); newLine = null; } } catch (FileNotFoundException e) { throw e; } catch (IOException e) { throw e; } finally { closeQuietly(in); } } /** * Read txt file. * * @param file the file * @param charset the charset * @param adapter the adapter * @throws IOException the io exception */ public static void readTxtFile(File file, Charset charset, ReadTxtFileAdapter adapter) throws IOException { readTxtFile(file, charset, adapter, BUFFER_SIZE); } /** * Read line. * * @param file the file * @param charset the charset * @param adapter the adapter * @throws IOException the io exception */ public static void readLine(File file, Charset charset, ReadLineAdapter adapter) throws IOException { // if (file == null || !file.exists()) { // throw new FileNotFoundException(file.getAbsolutePath()); // } BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader( charset == null ? new FileInputStream(file) : new FileInputStream(file), charset), 1024 * 10); String s = ""; while ((s = br.readLine()) != null) { adapter.todo(s); } } catch (IOException e) { // e.printStackTrace(); throw e; } finally { closeQuietly(br); } } /** * Delete boolean. * * @param dir the dir * @return the boolean */ public static boolean delete(File dir) { boolean ok = true; if (!dir.exists()) { LogUtils.LOGGER.info(MessageFormat.format("Delete... not exits {0}", dir)); return true; } if (dir.isFile()) { ok &= dir.delete(); LogUtils.LOGGER.info(MessageFormat.format("Delete... {1} File {0}", dir, ok)); return ok; } File[] list = dir.listFiles(); for (File file : list) { delete(file); } ok &= dir.delete(); LogUtils.LOGGER.info(MessageFormat.format("Delete... {1} Directory {0}", dir, ok)); return ok; } /** * Close quietly. * * @param closeable the closeable */ public static void closeQuietly(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException e) { LogUtils.LOGGER.debug(MessageFormat.format("closeQuietly() -> {0}", e.getMessage())); } } /** * The interface Read txt file adapter. */ public interface ReadTxtFileAdapter { /** * Todo. * * @param str the str */ public void todo(String str); } /** * The interface Read line adapter. */ public interface ReadLineAdapter { /** * Todo. * * @param str the str */ public void todo(String str); } }
package fr.lteconsulting; public class SaisieProduit { public Produit saisieProduit() { int reference = Saisie.saisieInt( "Référence" ); String designation = Saisie.saisie( "Désignation" ); double prixUnitaire = Saisie.saisieDouble( "Prix unitaire" ); // remplir le produit Produit produit = new Produit(); produit.setReference( reference ); produit.setDesignation( designation ); produit.setPrixUnitaire( prixUnitaire ); return produit; } }
package com.comp486.knightsrush; public class QuestConstants { public static final int QC_TYPE_MONSTER_KILL = 0; public static final int QC_TYPE_KEYS_CHEST = 1; public static final int QC_TYPE_CHEST_NO_MONSTER = 2; }
package AtividadePoo; public class TestaConta { public static void main(String[] args) { Conta c1 = new Conta("1", 250); Conta c2 = new Conta("2", 545); c1 = c2; c1.sacar(35); c1.transferir(c2, 60); System.out.println(c1.saldo); System.out.println(c2.saldo); } }
package chat; import java.util.Date; import java.lang.String; import org.omg.CosNaming.*; public class ChatterImpl extends ChatterPOA { public String getTheDate() { Date day = new Date(); String date = day.toString(); System.out.println(date); return date; } public void receive(String _msg) { System.out.println("Chatter receive: " + _msg); } public void subscribe(String _pseudo, String _chatroom) { try { org.omg.CORBA.Object objRef = this._orb().resolve_initial_references("NameService"); NamingContext ncRef = NamingContextHelper.narrow(objRef); NameComponent[] ns = new NameComponent [3]; ns[0] = new NameComponent("ChatRooms",""); ns[1] = new NameComponent(_chatroom,""); ns[2] = new NameComponent(_pseudo,""); ncRef.rebind(ns, this._this_object()); } catch(org.omg.CosNaming.NamingContextPackage.NotFound e) { e.printStackTrace(); } catch(org.omg.CosNaming.NamingContextPackage.CannotProceed e) { e.printStackTrace(); } catch(org.omg.CosNaming.NamingContextPackage.InvalidName e) { e.printStackTrace(); } catch(org.omg.CORBA.ORBPackage.InvalidName e) { e.printStackTrace(); } } }
package view; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Arc2D; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.Random; import javax.swing.JComponent; import Model.Element; import Model.Model; /** * The Class View. */ public class View extends JComponent implements Observer { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 2118299654730994785L; /** The angle. */ private float angle = 0; /** The model. */ Model model; /** The list arcs. */ private List<Arc2D> listArcs; /** * Instantiates a new view. */ public View() { listArcs = new ArrayList<Arc2D>(); } /** * Gets the model. * * @return the model */ public Model getModel() { return model; } /** * Sets the model. * * @param model the new model */ public void setModel(Model model) { this.model = model; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; Model model = this.getModel(); List<Element> elements = model.getElements(); // Calcul la taille des arcs et les ajoute à la view for (int i = 0; i < elements.size(); i++) { float pourcentage = model.getPourcentage(i) * 3.6f; Arc2D.Double arc = new Arc2D.Double(20, 20, 300, 300, angle, pourcentage, Arc2D.PIE); g2.setColor(new Color(new Random().nextInt())); g2.fill(arc); angle += pourcentage; listArcs.add(arc); } } /** * Gets the arc point clicked. * * @param p the p * @return the arc point clicked */ public int getArcPointClicked(Point2D p) { for (int i = 0; i < listArcs.size(); i++) { if (listArcs.get(i).contains(p.getX(), p.getY())) { return i; } } return -1; } @Override public void update(Observable arg0, Object arg1) { repaint(); } }
package com.quicktortoise.util; import android.app.Activity; import android.content.Context; import android.view.View; import android.view.inputmethod.InputMethodManager; /** * @Description: <p/> * Created by gaoxiaohui on 15-11-9. */ public class InputUtil { /** * open imm * * @param ctx ctx */ public static void openImm(Context ctx) { // get instance of InputMethodManager InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE); if (!imm.isActive()) { imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS); } } /** * close imm * * @param ctx ctx */ public static void closeImm(Context ctx) { InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE); View view = ((Activity) ctx).getWindow().peekDecorView(); if (view != null) { imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } }
package com.ibiscus.myster.repository.survey.data; import com.ibiscus.myster.model.survey.data.Response; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; public interface ResponseRepository extends CrudRepository<Response, Long> { @Query("select r from response r where r.assignmentId = :assignmentId and r.surveyItemId = :surveyItemId") Response findByAssignment(@Param("assignmentId") long assignmentId, @Param("surveyItemId") long surveyItemId); }
package br.com.fiap.jpa.entity; public enum Genero { MASCULINO, FEMININO, INDEFINIDO, OUTROS; }
package pointage.itm.maxime.pointageapp; import android.os.Environment; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; public class Writer { private String textfile; private User user; private PrintWriter writer; public String path; public Writer(User user) { this.textfile = "userPointage.txt"; this.user = user; this.path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/UserPoint"; File dir = new File(path); dir.mkdirs(); } public String getTextfile() { return textfile; } public void writeFile(){ File fichier = new File(path+"/"+this.getTextfile()); String [] userInfos =(user.getID() + ";" + user.getHeure()).split(""); Save(fichier, userInfos); } public static void Save(File file, String[] data) { FileOutputStream fos = null; try { fos = new FileOutputStream(file); } catch (FileNotFoundException e) {e.printStackTrace();} try { try { for (int i = 0; i<data.length; i++) { fos.write(data[i].getBytes()); if (i < data.length-1) { fos.write("\n".getBytes()); } } } catch (IOException e) {e.printStackTrace();} } finally { try { if (fos != null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } } } public static String[] Load(File file) { FileInputStream fis = null; try { fis = new FileInputStream(file); } catch (FileNotFoundException e) {e.printStackTrace();} InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); String test; int anzahl=0; try { while ((test=br.readLine()) != null) { anzahl++; } } catch (IOException e) {e.printStackTrace();} try { fis.getChannel().position(0); } catch (IOException e) {e.printStackTrace();} String[] array = new String[anzahl]; String line; int i = 0; try { while((line=br.readLine())!=null) { array[i] = line; i++; } } catch (IOException e) {e.printStackTrace();} return array; } public void writeInfile(){ //On instancie un nouveau Fichier File fichier = new File(path+"/"+this.getTextfile()); //On écrit dedans try { this.writer = new PrintWriter(new FileWriter(fichier,true)); writer.write(user.getID()+";"+user.getHeure()); writer.println(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public void eraseFile(){ File fichier = new File(this.getTextfile()); //On efface le contenu du fichier try { this.writer = new PrintWriter(new FileWriter(fichier, false)); writer.write(""); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
import java.lang.Thread; class A extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("Thread A "+i); } System.out.println("Exit from Thread A"); } } class B extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("Thread B "+i); } System.out.println("Exit from Thread B"); } } public class ThreadByExtendThreadClass { public static void main(String args[]) { A obA = new A(); B obB = new B(); obA.start(); obB.start(); System.out.println("Exit from Main"); } }
package com.company.item.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.company.item.entity.Unit; @Repository public interface UnitRepository extends JpaRepository<Unit, String> { }
package com.mx.profuturo.bolsa.service.hiring; import com.mx.profuturo.bolsa.model.service.hiringform.dto.*; import com.mx.profuturo.bolsa.util.exception.custom.GenericStatusException; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import com.mx.profuturo.bolsa.model.service.hiringform.vo.DatosFormularioVO; import com.mx.profuturo.bolsa.model.service.hiringform.vo.CandidatoContratacionVO; @Service @Scope("request") @Profile("mock") public class HiringServiceMockImpl extends HiringFormServiceBase { @Override public DatosFormularioVO getPersonalDataHiring(RecuperarFormularioDTO recudto) throws GenericStatusException { // TODO Auto-generated method stub return this.__callDataHiring(recudto); } @Override public CandidatoContratacionVO __callHiValidateCredentials(AccesoFormularioContratacionDTO dto) { CandidatoContratacionVO vo = new CandidatoContratacionVO(); if(dto.getDato1().equals("Ricky Llamas") && dto.getDato2().equals("355")) { //primera vez llenado form vo.setIdCandidato(355); vo.setNombreCandidato("Ricky Llamas"); vo.setIdProceso(124); vo.setEtapaFormulario(1); vo.setStatus(1); } else if(dto.getDato1().equals("Edgar Mendez") && dto.getDato2().equals("100")) { //enviado y cerrado vo.setIdCandidato(100); vo.setNombreCandidato("Edgar Mendez"); vo.setIdProceso(101); vo.setEtapaFormulario(4); vo.setStatus(2); }else if(dto.getDato1().equals("Eduardo Mendez") && dto.getDato2().equals("255")) { //no tiene derecho a completar vo.setIdCandidato(255); vo.setNombreCandidato("Eduardo Mendez"); vo.setIdProceso(111); vo.setEtapaFormulario(0); vo.setStatus(0); }else if(dto.getDato1().equals("Erick Fuentes") && dto.getDato2().equals("255")) { //sin completar form vo.setIdCandidato(255); vo.setNombreCandidato("Erick Fuentes"); vo.setIdProceso(123); vo.setEtapaFormulario(3); vo.setStatus(1); }else if(dto.getDato1().equals("Juani Reyes") && dto.getDato2().equals("455")) { //subir documentos vo.setIdCandidato(255); vo.setNombreCandidato("Juani Reyes"); vo.setIdProceso(123); vo.setEtapaFormulario(5); vo.setStatus(1); } return vo; } @Override public CandidatoContratacionVO validateHiringForm(AccesoFormularioContratacionDTO dto) { return this.__callHiValidateCredentials(dto); } @Override public Boolean __callSaveFormData(GuardarEtapaFormularioDTO dto) throws GenericStatusException { if (dto.getIdProceso()<=0) { throw new GenericStatusException(); } else { return true; } } @Override public DatosFormularioVO __callDataHiring(RecuperarFormularioDTO recudto) throws GenericStatusException { DatosFormularioVO response = new DatosFormularioVO(); FormularioEtapa1DTO etap1 = new FormularioEtapa1DTO(); FormularioEtapa2DTO etap2 = new FormularioEtapa2DTO(); FormularioEtapa3DTO etap3 = new FormularioEtapa3DTO(); FormularioEtapa4DTO etap4 = new FormularioEtapa4DTO(); etap1.setAlcaldia("Alvaro Obregon"); etap1.setApellidoMaterno("Galvan"); etap1.setApellidoPaterno("Llamas"); etap1.setCalle("Gpe"); etap1.setColonia("sn angel inn"); etap1.setCp("01790"); etap1.setCurp("LAGR870128HDFLC08"); etap1.setEmail("ricky@llamas.com"); etap1.setIdEstado(1); etap1.setIdGenero(1); etap1.setNombre("Ricky"); etap1.setNss("123654"); etap1.setNumExt("69"); etap1.setAlcaldia("Alvaro Obregon"); etap1.setApellidoMaterno("Galvan"); etap1.setApellidoPaterno("Llamas"); etap1.setCalle("Gpe"); etap1.setColonia("sn angel inn"); etap1.setCp("01790"); etap1.setCurp("LAGR870128HDFLC08"); etap1.setEmail("ricky@llamas.com"); etap1.setIdEstado(1); etap1.setIdGenero(1); etap1.setNombre("Ricky"); etap1.setNss("123654"); etap1.setNumExt("69"); etap2.setNivelEstudios(1); etap2.setEstatus(1); etap2.setCarrera("SISTEMAS"); etap2.setNombreEmpresa("GGGGG"); etap2.setActividad("SISTEMAS"); etap2.setNombreJefeInmediato("Juan pablo rojas"); etap2.setPuestoJefe("Gerente soluciones"); etap2.setPeriodoLaboradoInicio(2010); etap2.setPeriodoLaboradoFin(2014); etap2.setTelefono("123456780"); etap2.setFunciones("blabla bla bla"); response.setEtapa1(etap1); response.setEtapa2(etap2); response.setEtapa3(etap3); response.setEtapa4(etap4); return response; } @Override public Boolean endHiringForm(TerminarFormularioDTO endFormdto) throws GenericStatusException { return this.__callEndHiringForm(endFormdto); } @Override public Boolean __callEndHiringForm(TerminarFormularioDTO endFormdto) throws GenericStatusException { Boolean sucess= true; if(endFormdto.getIdProceso()<=0){ throw new GenericStatusException(); } return sucess; } }
package com.class01; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class beforeAndAfterMethods { @BeforeMethod public void testMethodsOne() { System.out.println("beforeMethods"); } @Test public void testMethodOne() { System.out.println("testMethod"); } @Test public void testMethodTwo() { System.out.println("testMethodTwo"); } @AfterMethod public void afterMethod() { System.out.println("afterMethods"); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package org.apache.clerezza.implementation.literal; import org.apache.clerezza.BlankNodeOrIRI; import org.apache.clerezza.IRI; import org.apache.clerezza.RDFTerm; import org.apache.clerezza.Triple; import org.apache.clerezza.implementation.TripleImpl; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; /** * @author reto */ @RunWith(JUnitPlatform.class) public class TripleImplTest { @Test public void tripleEquality() { BlankNodeOrIRI subject = new IRI("http://example.org/"); IRI predicate = new IRI("http://example.org/property"); RDFTerm object = new PlainLiteralImpl("property value"); Triple triple1 = new TripleImpl(subject, predicate, object); Triple triple2 = new TripleImpl(subject, predicate, object); Assertions.assertEquals(triple1.hashCode(), triple2.hashCode()); Assertions.assertEquals(triple1, triple2); } }
package com.infytel.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.transaction.annotation.Transactional; import com.infytel.domain.SimDetails; public interface SimCardRepository extends JpaRepository<SimDetails, Long>{ @Transactional @Modifying @Query(value = "update sim_details set sim_status = ? " + " where sim_id = ?", nativeQuery = true) void statusUpdate(String status,int simId); }
package sickbook.ui.notifications; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.widget.AppCompatImageView; import androidx.fragment.app.Fragment; import com.comp.sickbook.AppContext; import com.comp.sickbook.Background.Person; import com.comp.sickbook.R; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.installations.FirebaseInstallations; import java.util.ArrayList; public class NotificationsFragment extends Fragment { static LinearLayout list ; static View root; static Person person; static String userID; /** *loads the saved instance * @param savedInstanceState : saved instance from the last state */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } /** * Runs on the create of the fragment * makes the on click listeners for the refresh button * makes a list of views which hold the notifications * @param inflater : used to inflate the views into layout * @param container : the contain which this viw is held * @param savedInstanceState : saved instance from the last state * @return : root view */ public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { root = inflater.inflate(R.layout.fragment_notifications, container, false); list = root.findViewById(R.id.notification_list); AppCompatImageView refreshButton = root.findViewById(R.id.refreshNotif); refreshButton.setOnClickListener(new View.OnClickListener() { //refreshes the list @Override public void onClick(View v) { list.removeAllViews(); createNotifList(); } }); createNotifList(); return root; } /** * Makes the list of views which are the notifications * Gets the notifications from the firebase in the users reference */ public void createNotifList(){ FirebaseInstallations.getInstance().getId() // attempt to get unique firebase user ID .addOnCompleteListener(new OnCompleteListener<String>() { @Override public void onComplete(@NonNull Task<String> task) { userID = task.getResult(); //gets the unique user Id from firebase FirebaseFirestore db = FirebaseFirestore.getInstance(); DocumentReference personRef = db.collection("people").document(userID); //ref to the person personRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { if (documentSnapshot.exists()) { person = documentSnapshot.toObject(Person.class); ArrayList<String> notifs = person.getNotifications(); for (String notif : notifs){ //for each notification in the list of notifications in firebase int i = notif.indexOf(","); String title = notif.substring(0,i); String message = notif.substring(i+1); addNotif(title,message); } } } }); } }); } /** * Adds a notification to the list in the notification tab * Makes a view for each notification * Each view has a remove button to delete that notification * Also adds the notification to the firebase under the person reference * @param Title : the title to the notification * @param Message : the message of the notification */ public static void addNotif (String Title, String Message){ View view = LayoutInflater.from(AppContext.getAppContext()).inflate(R.layout.notification_temp, null); AppCompatImageView clear = view.findViewById(R.id.makeButton); clear.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { list.removeView(view); String notif = Title+","+Message; person.removeNotification(notif); FirebaseFirestore db = FirebaseFirestore.getInstance(); DocumentReference personRef = db.collection("people").document(userID); personRef.set(person); } }); TextView tmpTitle = view.findViewById(R.id.notify_group_name); tmpTitle.setText(Title); TextView tmpMessage = view.findViewById(R.id.notif_text); tmpMessage.setText(Message); list.addView(view); } }
/* */ package datechooser.beans.editor; /* */ /* */ import datechooser.beans.editor.descriptor.DescriptionManager; /* */ import datechooser.beans.locale.LocaleUtils; /* */ import java.beans.PropertyEditorSupport; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class NavigatePaneEditor /* */ extends PropertyEditorSupport /* */ { /* 22 */ private String[] tagsText = { LocaleUtils.getEditorLocaleString("Fields_navigator"), LocaleUtils.getEditorLocaleString("Button_navigator") }; /* */ /* */ public NavigatePaneEditor() {} /* */ /* */ public String[] getTags() { /* 27 */ return this.tagsText; /* */ } /* */ /* */ public String getAsText() { /* 31 */ return this.tagsText[getValueIndex()]; /* */ } /* */ /* */ public void setAsText(String text) throws IllegalArgumentException { /* 35 */ for (int i = 0; i < this.tagsText.length; i++) { /* 36 */ if (this.tagsText[i].equals(text)) { /* 37 */ setValue(new Integer(i)); /* 38 */ return; /* */ } /* */ } /* 41 */ throw new IllegalArgumentException(); /* */ } /* */ /* */ public String getJavaInitializationString() { /* 45 */ return DescriptionManager.describeJava(getValue(), Integer.class); /* */ } /* */ /* */ private int getValueIndex() { /* 49 */ return ((Integer)getValue()).intValue(); /* */ } /* */ } /* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/datechooser/beans/editor/NavigatePaneEditor.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
package hirondelle.web4j.model; import java.math.BigDecimal; import java.util.*; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.servlet.ServletConfig; import hirondelle.web4j.util.Util; import hirondelle.web4j.BuildImpl; import hirondelle.web4j.readconfig.InitParam; import hirondelle.web4j.request.DateConverter; import hirondelle.web4j.request.Formats; import hirondelle.web4j.security.SafeText; import sun.util.calendar.ZoneInfo; /** Default implementation of {@link ConvertParam}.*/ public class ConvertParamImpl implements ConvertParam { /** Called by the framework upon startup. */ public static void init(ServletConfig aConfig){ fIgnorableParamValue = fIGNORABLE_PARAM_VALUE.fetch(aConfig).getValue(); fAllowString = Util.parseBoolean(fALLOW_STRING.fetch(aConfig).getValue()); fSUPPORTED_CLASSES = new ArrayList<Class<?>>(); fSUPPORTED_CLASSES.add(Integer.class); fSUPPORTED_CLASSES.add(int.class); fSUPPORTED_CLASSES.add(Boolean.class); fSUPPORTED_CLASSES.add(boolean.class); fSUPPORTED_CLASSES.add(BigDecimal.class); fSUPPORTED_CLASSES.add(java.util.Date.class); fSUPPORTED_CLASSES.add(Long.class); fSUPPORTED_CLASSES.add(long.class); fSUPPORTED_CLASSES.add(Id.class); fSUPPORTED_CLASSES.add(SafeText.class); fSUPPORTED_CLASSES.add(Locale.class); fSUPPORTED_CLASSES.add(TimeZone.class); fSUPPORTED_CLASSES.add(ZoneInfo.class); //Cheating - used to id TimeZones fSUPPORTED_CLASSES.add(Decimal.class); fSUPPORTED_CLASSES.add(DateTime.class); if(fAllowString){ fSUPPORTED_CLASSES.add(String.class); } fLogger.fine("Supported Classes : " + Util.logOnePerLine(fSUPPORTED_CLASSES)); } /** Return <tt>true</tt> only if <tt>aTargetClass</tt> is supported by this implementation. <P> The following classes are supported by this implementation as building block classes : <ul> <li><tt>{@link SafeText}</tt> <li><tt>String</tt> (conditionally, see below) <li><tt>Integer</tt> <li><tt>Long</tt> <li><tt>Boolean</tt> <li><tt>BigDecimal</tt> <li><tt>{@link Decimal}</tt> <li><tt>{@link Id}</tt> <li><tt>{@link DateTime}</tt> <li><tt>java.util.Date</tt> <li><tt>Locale</tt> <li><tt>TimeZone</tt> and <tt>sun.util.calendar.ZoneInfo</tt> (which is <i>cheating</i> - see below). </ul> <P><i>You are not obliged to use this class to model Locale and TimeZone. Many will choose to implement them as just another <a href='http://www.web4j.com/UserGuide.jsp#StartupTasksAndCodeTables'>code table</a> instead.</i> In this case, your model object constructors would usually take an {@link Id} parameter for these items, and translate them into a {@link Code}. See the example apps for a demonstration of this technique. <P>The <tt>TimeZone</tt> class is a problem here, since it's abstract. In fact, <b>this demonstrates a defect in the {@link ConvertParam} interface itself</b> - it should take objects themselves, instead of classes. That would allow more flexible checks on <i>type</i> as opposed to concrete <i>class</i>. In this implementation, {@link ZoneInfo} is hard-coded as the representative of all {@link TimeZone} objects. This is poor style, since <tt>ZoneInfo</tt> is public, but "unpublished" by Sun - they may change to some other class in the future. <P><b>String is supported only when explicitly allowed.</b> The <tt>AllowStringAsBuildingBlock</tt> setting in <tt>web.xml</tt> controls whether or not this class allows <tt>String</tt> as a supported class. By default, its value is <tt>FALSE</tt>, since {@link SafeText} is the recommended replacement for <tt>String</tt>. */ public final boolean isSupported(Class<?> aTargetClass){ return fSUPPORTED_CLASSES.contains(aTargetClass); } /** Coerce all parameters with no visible content to <tt>null</tt>. <P>In addition, any raw input value that matches <tt>IgnorableParamValue</tt> in <tt>web.xml</tt> is also coerced to <tt>null</tt>. See <tt>web.xml</tt> for more information. <P>Any non-<tt>null</tt> result is trimmed. This method can be overridden, if desired. */ public String filter(String aRawInputValue){ String result = aRawInputValue; if ( ! Util.textHasContent(aRawInputValue) || aRawInputValue.equals(getIgnorableParamValue()) ){ result = null; } return Util.trimPossiblyNull(result); //some apps may elect to trim elsewhere } /** Apply reasonable parsing policies, suitable for most applications. <P>Roughly, the policies are : <ul> <li><tt>SafeText</tt> uses {@link SafeText#SafeText(String)} <li><tt>String</tt> just return the filtered value as is <li><tt>Integer</tt> uses {@link Integer#Integer(String)} <li><tt>BigDecimal</tt> uses {@link Formats#getDecimalInputFormat()} <li><tt>Decimal</tt> uses {@link Formats#getDecimalInputFormat()} <li><tt>Boolean</tt> uses {@link Util#parseBoolean(String)} <li><tt>DateTime</tt> uses {@link DateConverter#parseEyeFriendlyDateTime(String, Locale)} and {@link DateConverter#parseHandFriendlyDateTime(String, Locale)} <li><tt>Date</tt> uses {@link DateConverter#parseEyeFriendly(String, Locale, TimeZone)} and {@link DateConverter#parseHandFriendly(String, Locale, TimeZone)} <li><tt>Long</tt> uses {@link Long#Long(String)} <li><tt>Id</tt> uses {@link Id#Id(String)} <li><tt>Locale</tt> uses {@link Locale#getAvailableLocales()} and {@link Locale#toString()}, case sensitive. <li><tt>TimeZone</tt> uses {@link TimeZone#getAvailableIDs()}, case sensitive. </ul> */ public final <T> T convert(String aFilteredInputValue, Class<T> aSupportedTargetClass, Locale aLocale, TimeZone aTimeZone) throws ModelCtorException { // Defensive : this check should have already been performed by the calling framework class. if( ! isSupported(aSupportedTargetClass) ) { throw new AssertionError("Unsupported type cannot be translated to an object: " + aSupportedTargetClass + ". If you're trying to use String, consider using SafeText instead. Otherwise, change the AllowStringAsBuildingBlock setting in web.xml."); } Object result = null; if (aSupportedTargetClass == SafeText.class){ //no translation needed; some impl's might trim here, or force CAPS result = parseSafeText(aFilteredInputValue); } else if (aSupportedTargetClass == String.class) { result = aFilteredInputValue; //no translation needed; some impl's might trim here, or force CAPS } else if (aSupportedTargetClass == Integer.class || aSupportedTargetClass == int.class){ result = parseInteger(aFilteredInputValue); } else if (aSupportedTargetClass == Boolean.class || aSupportedTargetClass == boolean.class){ result = Util.parseBoolean(aFilteredInputValue); } else if (aSupportedTargetClass == BigDecimal.class){ result = parseBigDecimal(aFilteredInputValue, aLocale, aTimeZone); } else if (aSupportedTargetClass == Decimal.class){ result = parseDecimal(aFilteredInputValue, aLocale, aTimeZone); } else if (aSupportedTargetClass == java.util.Date.class){ result = parseDate(aFilteredInputValue, aLocale, aTimeZone); } else if (aSupportedTargetClass == DateTime.class){ result = parseDateTime(aFilteredInputValue, aLocale); } else if (aSupportedTargetClass == Long.class || aSupportedTargetClass == long.class){ result = parseLong(aFilteredInputValue); } else if (aSupportedTargetClass == Id.class){ result = new Id(aFilteredInputValue.trim()); } else if (aSupportedTargetClass == Locale.class){ result = parseLocale(aFilteredInputValue); } else if (aSupportedTargetClass == TimeZone.class){ result = parseTimeZone(aFilteredInputValue); } else { throw new AssertionError("Failed to build object for ostensibly supported class: " + aSupportedTargetClass); } fLogger.finer("Converted request param into a " + aSupportedTargetClass.getName()); return (T)result; //this cast is unavoidable, and safe. } /** Return the <tt>IgnorableParamValue</tt> configured in <tt>web.xml</tt>. See <tt>web.xml</tt> for more information. */ public static final String getIgnorableParamValue(){ return fIgnorableParamValue; } // PRIVATE private static List<Class<?>> fSUPPORTED_CLASSES; /** Possible values include <ul> <li> null, denoting that all param values are to be accepted <li> an empty String, corresponding to a blank OPTION <li> '---SELECT---', for example </ul> */ private static String fIgnorableParamValue; private static final InitParam fIGNORABLE_PARAM_VALUE = new InitParam("IgnorableParamValue", ""); private static boolean fAllowString; private static final InitParam fALLOW_STRING = new InitParam("AllowStringAsBuildingBlock", "NO"); private static final ModelCtorException PROBLEM_FOUND = new ModelCtorException(); private static final Logger fLogger = Util.getLogger(ConvertParamImpl.class); private Integer parseInteger(String aUserInputValue) throws ModelCtorException { try { return new Integer(aUserInputValue); } catch (NumberFormatException ex){ throw PROBLEM_FOUND; } } private BigDecimal parseBigDecimal(String aUserInputValue, Locale aLocale, TimeZone aTimeZone) throws ModelCtorException { BigDecimal result = null; Formats formats = new Formats(aLocale, aTimeZone); Pattern pattern = formats.getDecimalInputFormat(); if ( Util.matches(pattern, aUserInputValue)) { //BigDecimal ctor only takes '.' as decimal sign, never ',' result = new BigDecimal(aUserInputValue.replace(',', '.')); } else { throw PROBLEM_FOUND; } return result; } private Decimal parseDecimal(String aUserInputValue, Locale aLocale, TimeZone aTimeZone) throws ModelCtorException { Decimal result = null; BigDecimal amount = null; Formats formats = new Formats(aLocale, aTimeZone); Pattern pattern = formats.getDecimalInputFormat(); if ( Util.matches(pattern, aUserInputValue)) { //BigDecimal ctor only takes '.' as decimal sign, never ',' amount = new BigDecimal(aUserInputValue.replace(',', '.')); try { result = new Decimal(amount); } catch(IllegalArgumentException ex){ throw PROBLEM_FOUND; } } else { throw PROBLEM_FOUND; } return result; } private Date parseDate(String aUserInputValue, Locale aLocale, TimeZone aTimeZone) throws ModelCtorException { Date result = null; DateConverter dateConverter = BuildImpl.forDateConverter(); result = dateConverter.parseHandFriendly(aUserInputValue, aLocale, aTimeZone); if ( result == null ){ result = dateConverter.parseEyeFriendly(aUserInputValue, aLocale, aTimeZone); } if ( result == null ) { throw PROBLEM_FOUND; } return result; } private DateTime parseDateTime(String aUserInputValue, Locale aLocale) throws ModelCtorException { DateTime result = null; DateConverter dateConverter = BuildImpl.forDateConverter(); result = dateConverter.parseHandFriendlyDateTime(aUserInputValue, aLocale); if ( result == null ){ result = dateConverter.parseEyeFriendlyDateTime(aUserInputValue, aLocale); } if ( result == null ) { throw PROBLEM_FOUND; } return result; } private Long parseLong(String aUserInputValue) throws ModelCtorException { Long result = null; if ( Util.textHasContent(aUserInputValue) ){ try { result = new Long(aUserInputValue); } catch (NumberFormatException ex){ throw PROBLEM_FOUND; } } return result; } private SafeText parseSafeText(String aUserInputValue) throws ModelCtorException { SafeText result = null; if( Util.textHasContent(aUserInputValue) ) { try { result = new SafeText(aUserInputValue); } catch(IllegalArgumentException ex){ throw PROBLEM_FOUND; } } return result; } /** Translate user input into a known time zone id. Case sensitive. */ private TimeZone parseTimeZone(String aUserInputValue) throws ModelCtorException { TimeZone result = null; if ( Util.textHasContent(aUserInputValue) ){ List<String> allTimeZoneIds = Arrays.asList(TimeZone.getAvailableIDs()); for(String id : allTimeZoneIds){ if (id.equals(aUserInputValue)){ result = TimeZone.getTimeZone(id); break; } } if(result == null){ //has content, but no match found throw PROBLEM_FOUND; } } return result; } /** Translate user input into a known Locale id. Case sensitive. */ private Locale parseLocale(String aUserInputValue) throws ModelCtorException { Locale result = null; if ( Util.textHasContent(aUserInputValue) ){ List<Locale> allLocales = Arrays.asList(Locale.getAvailableLocales()); for(Locale locale: allLocales){ if (locale.toString().equals(aUserInputValue)){ result = locale; break; } } if(result == null){ //has content, but no match found throw PROBLEM_FOUND; } } return result; } }
package com.vwaber.udacity.popularmovies; import android.content.Context; import android.support.constraint.ConstraintLayout; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.vwaber.udacity.popularmovies.data.Trailer; import java.util.ArrayList; class TrailerAdapter extends RecyclerView.Adapter<TrailerAdapter.TrailerViewHolder> { private final Context mContext; private final ArrayList<Trailer> mTrailerList; private final TrailerClickListener mClickListener; interface TrailerClickListener { void onTrailerClick(Trailer data); } TrailerAdapter(Context context) { mContext = context; mClickListener = (TrailerClickListener) context; mTrailerList = new ArrayList<>(); } void swap(ArrayList<Trailer> data){ if(data == null) return; mTrailerList.clear(); mTrailerList.addAll(data); notifyDataSetChanged(); } @Override public TrailerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { int layoutID = R.layout.trailer_list_item; LayoutInflater inflater = LayoutInflater.from(mContext); ConstraintLayout layout = (ConstraintLayout) inflater.inflate(layoutID, parent, false); return new TrailerViewHolder(layout); } @Override public void onBindViewHolder(TrailerViewHolder holder, int position) { holder.bind(position); } @Override public int getItemCount() { return mTrailerList.size(); } class TrailerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { final TextView nameView; final TextView typeView; TrailerViewHolder(View layout) { super(layout); layout.setOnClickListener(this); nameView = (TextView) layout.findViewById(R.id.tv_trailer_name); typeView = (TextView) layout.findViewById(R.id.tv_trailer_type); } void bind(int position){ Trailer trailer = mTrailerList.get(position); nameView.setText(trailer.name); typeView.setText(trailer.type); } @Override public void onClick(View view) { Trailer trailer = mTrailerList.get(getAdapterPosition()); mClickListener.onTrailerClick(trailer); } } }
package SignaturaDigital; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; public class Signatura { // Signar un missatge amb la clau privada public static byte[] signar(String dades, PrivateKey priv) { byte[] data = dades.getBytes(); byte[] signatura = null; try { Signature signer = Signature.getInstance("SHA1withRSA"); signer.initSign(priv); signer.update(data); signatura = signer.sign(); } catch (Exception ex) { System.err.println("Error signant les dades: " + ex); } return signatura; } //Validar una firma amb la clau pública public static boolean validar(byte[] signatura, String dades, PublicKey pub) { byte[] data = dades.getBytes(); try { Signature signer = Signature.getInstance("SHA1withRSA"); signer.initVerify(pub); signer.update(data); if (signer.verify(signatura)) { return true; } } catch (Exception ex) { System.err.println("Error signant les dades: " + ex); } return false; } }
package fr.demos.Data; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; import fr.demos.formation.today.Climatisation; public class SQLClimatisationDAO implements ClimatisationDAO { private DataSource ds=null; public SQLClimatisationDAO() throws Exception{ // on fait un construcuteur //les deux premieres ligne c'est la recherche dans l'annuaire du pool de connexion (utilisation de la libraire INDI) Context context= new InitialContext(); ds= (DataSource)context.lookup("jdbc/appliclim"); } @Override public void sauve(Climatisation cl) throws Exception { //on demande une connexion au pool Connection cx= ds.getConnection(); //on va pouvoir preparer notre requete SQL PreparedStatement psmt=cx.prepareStatement("insert into climatisation values (?,?,?,?,?)"); psmt.setString(1, cl.getNomSalle()); psmt.setDouble(2, cl.getTemperature()); psmt.setDouble(3,cl.getPression()); psmt.setDouble(4, cl.getTauxHumidite()); psmt.setLong(5,cl.getDatation()); // on lance la commande dans la base psmt.executeUpdate(); // on rend la connexion au pool cx.close(); } @Override public List<Climatisation> recherchetout() throws Exception { Connection cx= ds.getConnection(); PreparedStatement psmt=cx.prepareStatement("select * from climatisation"); ResultSet rs= psmt.executeQuery(); ArrayList<Climatisation>liste=new ArrayList<>(); while (rs.next()){ String nomSalle=rs.getString(1); double temperature=rs.getDouble(2); double pression=rs.getDouble(3); double tauxHumidite=rs.getDouble(4); long datation=rs.getLong(5); Climatisation cl= new Climatisation (nomSalle, pression, tauxHumidite, temperature); liste.add(cl); } return liste; } @Override public List<Climatisation> recherche(String critere) throws Exception { // TODO Auto-generated method stub return null; } @Override public int nombre(String Critere) { int nb=0; try{ List<Climatisation> liste=this.recherchetout(); nb=liste.size(); } catch(Exception e){} return nb; } }
package com.StringAssignment_10_Sep_2021; public class ToCharArray { public static void main(String args[]) { String s1 = "Dheerendra"; char[] character = s1.toCharArray(); for (int i = 0; i < character.length; i++) { System.out.print(character[i]); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.net.imap; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.stream.Stream; import org.apache.commons.net.MalformedServerReplyException; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; public class IMAPReplyTest { private static Stream<String> invalidLiteralCommands() { return Stream.of( "", "{", "}", "{}", "{foobar}", "STORE +FLAGS.SILENT \\DELETED {", "STORE +FLAGS.SILENT \\DELETED }", "STORE +FLAGS.SILENT \\DELETED {-1}", "STORE +FLAGS.SILENT \\DELETED {-10}", "STORE +FLAGS.SILENT \\DELETED {-2147483648}" ); } private static Stream<Arguments> literalCommands() { return Stream.of( Arguments.of(310, "A003 APPEND saved-messages (\\Seen) {310}"), Arguments.of(6, "A284 SEARCH CHARSET UTF-8 TEXT {6}"), Arguments.of(7, "FRED FOOBAR {7}"), Arguments.of(102856, "A044 BLURDYBLOOP {102856}"), Arguments.of(342, "* 12 FETCH (BODY[HEADER] {342}"), Arguments.of(0, "X999 LOGIN {0}"), Arguments.of(Integer.MAX_VALUE, "X999 LOGIN {2147483647}") ); } @Test public void getReplyCodeBadLine() throws IOException { final String badLine = "A044 BAD No such command as \"FOOBAR\""; assertEquals(IMAPReply.BAD, IMAPReply.getReplyCode(badLine)); } @Test public void getReplyCodeContinuationLine() throws IOException { final String continuationLine = "+ Ready for additional command text"; assertEquals(IMAPReply.CONT, IMAPReply.getReplyCode(continuationLine)); } @Test public void getReplyCodeMalformedLine() { final String malformedTaggedLine = "A064 FOO-BAR 0"; final MalformedServerReplyException replyException = assertThrows(MalformedServerReplyException.class, () -> IMAPReply.getReplyCode(malformedTaggedLine)); assertEquals("Received unexpected IMAP protocol response from server: 'A064 FOO-BAR 0'.", replyException.getMessage()); } @Test public void getReplyCodeNoLine() throws IOException { final String noLine = "A223 NO COPY failed: disk is full"; assertEquals(IMAPReply.NO, IMAPReply.getReplyCode(noLine)); } @Test public void getReplyCodeOkLine() throws IOException { final String okLine = "A001 OK LOGIN completed"; assertEquals(IMAPReply.OK, IMAPReply.getReplyCode(okLine)); } @Test public void getUntaggedReplyCodeBadLine() throws IOException { final String badLine = "* BAD Empty command line"; assertEquals(IMAPReply.BAD, IMAPReply.getUntaggedReplyCode(badLine)); } @Test public void getUntaggedReplyCodeContinuationLine() throws IOException { final String continuationLine = "+ Ready for additional command text"; assertEquals(IMAPReply.CONT, IMAPReply.getUntaggedReplyCode(continuationLine)); } @Test public void getUntaggedReplyCodeMalformedLine() { // invalid experimental comm response (missing X prefix) final String malformedUntaggedLine = "* FOO-BAR hello-world"; final MalformedServerReplyException replyException = assertThrows(MalformedServerReplyException.class, () -> IMAPReply.getUntaggedReplyCode(malformedUntaggedLine)); assertEquals("Received unexpected IMAP protocol response from server: '* FOO-BAR hello-world'.", replyException.getMessage()); } @Test public void getUntaggedReplyCodeNoLine() throws IOException { final String noLine = "* NO Disk is 98% full, please delete unnecessary data"; assertEquals(IMAPReply.NO, IMAPReply.getUntaggedReplyCode(noLine)); } @Test public void getUntaggedReplyCodeOkLine() throws IOException { final String okLine = "* OK Salvage successful, no data lost"; assertEquals(IMAPReply.OK, IMAPReply.getUntaggedReplyCode(okLine)); } @Test public void isContinuationReplyCode() { final int replyCode = 3; assertTrue(IMAPReply.isContinuation(replyCode)); } @Test public void isContinuationReplyCodeInvalidCode() { final int invalidContinuationReplyCode = 1; assertFalse(IMAPReply.isContinuation(invalidContinuationReplyCode)); } @Test public void isContinuationReplyLine() { final String replyLine = "+FLAGS completed"; assertTrue(IMAPReply.isContinuation(replyLine)); } @Test public void isContinuationReplyLineInvalidLine() { final String invalidContinuationReplyLine = "* 22 EXPUNGE"; assertFalse(IMAPReply.isContinuation(invalidContinuationReplyLine)); } @Test public void isSuccessReplyCode() { final int successfulReplyCode = 0; assertTrue(IMAPReply.isSuccess(successfulReplyCode)); } @Test public void isSuccessReplyCodeUnsuccessfulCode() { final int unsuccessfulReplyCode = 2; assertFalse(IMAPReply.isSuccess(unsuccessfulReplyCode)); } @Test public void isUntaggedReplyLine() { final String replyLine = "* 18 EXISTS"; assertTrue(IMAPReply.isUntagged(replyLine)); } @Test public void isUntaggedReplyLineInvalidLine() { final String taggedLine = "a001 OK LOGOUT completed"; assertFalse(IMAPReply.isUntagged(taggedLine)); } @ParameterizedTest(name = "reply line `{1}` contains literal {0}") @MethodSource("literalCommands") public void literalCount(final int expectedLiteral, final String replyLine) { assertEquals(expectedLiteral, IMAPReply.literalCount(replyLine)); } @ParameterizedTest(name = "reply line `{0}` does not contain any literal") @MethodSource("invalidLiteralCommands") public void literalCountInvalid(final String replyLine) { assertEquals(-1, IMAPReply.literalCount(replyLine)); } }
package championship.results; public class ImplementsParticipant implements Participant { private String name; private String nation; public ImplementsParticipant(String name, String nation){ this.name = name; this.nation = nation; } public ImplementsParticipant makeParticipant(String name, String nation) { if(name == null || name.length() == 0 || nation == null || nation.length() == 0) { return null; } return new ImplementsParticipant(name, nation); } public String getName(){ return this.name; } public String getNation(){ return this.nation; } }
/* * Copyright (c) 2014 Anthony Benavente * * 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.ambenavente.origins.gameplay.entities; import com.ambenavente.origins.gameplay.entities.interfaces.Renderable; import com.ambenavente.origins.gameplay.world.World; import org.newdawn.slick.*; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.geom.Vector2f; /** * Represents an Entity. An entity is an object in the game that is rendered, * has updatable logic, has a position, and has dimensions. These are * generally exemplified by the Player class, or by any of the other * "character" classes. However, another example of entities would be chests * or arrows that are fired by other entities. This is because they have to be * rendered to the screen in a way that can be easily manipulated through its * coordinates. Do not get this confused with Tiles though; tiles cannot be * manipulated per pixel coordinate. * * @author Anthony Benavente * @version 2/9/14 */ public abstract class Entity implements Renderable { protected static final int DEFAULT_HEIGHT = 21; protected static final int DEFAULT_WIDTH = 30; /** * The image that is used by entities that don't have an animation * or texture set because the user failed to call the entities * setAvatar or setAnimation method */ protected static Image NO_TEX; /** * Attempts to initialize the no-texture image. This is in a static method * because the Image constructor throws a SlickException which I wrapped * in a try catch block. */ static { try { NO_TEX = new Image("no_tex.png"); } catch (SlickException e) { e.printStackTrace(); } } /** * The name to reference this entity by (not as an identifier) */ private String name; /** * The position of the entity in the world */ private Vector2f pos; /** * The width of the entity in pixels */ private int width; /** * The height of the entity in pixels */ private int height; /** * The width of this entity's texture. May be 0 if no texture is present. */ private int textureWidth; /** * The height of this entity's texture. May be 0 if no texture is present. */ private int textureHeight; /** * The direction that the entity is facing */ private Direction direction; /** * The default speed that the entity moves at normally */ private float walkingSpeed; /** * If the entity is in motion (if its position is changing) */ private boolean isMoving; /** * The maximum amount of health an entity can have */ private int maxHealth; /** * The amount of health that the entity has out of its max health */ private int health; /** * If the entity still has health; used for deletion of entities */ private boolean dead; /** * The stats for this entity */ private EntityStats stats; /** * The bounding box used for collision detection with entities */ private Rectangle bounds; /** * Creates an Entity object * * @param x The x coordinate to set the entity at * @param y The y coordinate to set the entity at */ public Entity(float x, float y) { this(new Vector2f(x, y)); } /** * Creates an Entity object * * @param pos The position to set the entity at */ public Entity(Vector2f pos) { this.pos = pos; this.width = 0; this.height = 0; this.direction = Direction.SOUTH; this.walkingSpeed = 1.0f; this.isMoving = false; this.maxHealth = 30; this.health = maxHealth; this.stats = new EntityStats(); this.bounds = new Rectangle(pos.x, pos.y, width, height); } /** * Called when an entity is created */ public abstract void init(); /** * Called on each update in the game loop * * @param container The container that is holding the game * @param delta Delta time */ public abstract void update(GameContainer container, int delta); @Override public abstract void render(Graphics g); /** * Draws the shadow of the entity as a dark ellipse underneath the texture * * @param g The graphics object to draw the ellipse */ protected void drawShadow(Graphics g) { Color col = g.getColor(); g.setColor(new Color(0, 0, 0, 0.25f)); g.fillOval(getX() + 5, getY() + getTextureHeight() - 2, getTextureWidth() - 8, 5); g.setColor(col); } /** * @return The entity's coordinate position in the world */ public Vector2f getPos() { return pos; } /** * Sets the entity's position to the passed in coordinate * * @param pos The position to set the entity at */ protected void setPos(Vector2f pos) { this.pos = pos; updateBounds(); } /** * @return The entity's x coordinate of its position in the world */ public float getX() { return pos.x; } /** * @return The entity's y coordinate of its position in the world */ public float getY() { return pos.y; } /** * @return The entity's width in pixels */ public int getWidth() { return width; } /** * Sets the width of the entity in pixels * * @param width The new width to set the entity to */ protected void setWidth(int width) { this.width = width; updateBounds(); } /** * @return The entity's height in pixels */ public int getHeight() { return height; } /** * Sets the height of the entity in pixels * * @param height The new height to set the entity to */ protected void setHeight(int height) { this.height = height; updateBounds(); } /** * @return The direction that the entity is facing */ public Direction getDirection() { return direction; } /** * Sets the direction that the entity is facing * * @param direction The new direction the entity will be facing */ public void setDirection(Direction direction) { this.direction = direction; } /** * @return How fast the entity moves when it is moving normally * (pixels/frame) */ public float getWalkingSpeed() { return walkingSpeed; } /** * Sets how fast the entity moves when it is moving normally * * @param walkingSpeed The new speed at which the entity will normally move */ protected void setWalkingSpeed(float walkingSpeed) { this.walkingSpeed = walkingSpeed; } /** * @return The percentage of health that the entity has left */ public float getRemainingHealthPercent() { return (float) health / maxHealth; } /** * @return If the entity is moving or not (if its position is changing) */ public boolean isMoving() { return isMoving; } protected void setMoving(boolean isMoving) { this.isMoving = isMoving; } /** * Moves the entity by a Vector2f amount * * @param amount A vector representing how much to add onto the position * vector */ public void move(Vector2f amount) { Vector2f v = new Vector2f(0, 0); float x1 = pos.x + amount.x + (textureWidth - width); float y1 = pos.y + amount.y + (textureWidth - height); float x2 = pos.x + amount.x + width; float y2 = pos.y + amount.y + textureHeight; if (amount.x < 0) { if (!World.getCollision(x1, y2)) { v.x += amount.x; } } else { if (!World.getCollision(x2, y2)) { v.x += amount.x; } } if (amount.y < 0) { if (!World.getCollision(x2, y1) && !World.getCollision(x1, y1)) { v.y += amount.y; } } else { if (!World.getCollision(x2, y2) && !World.getCollision(x1, y2)) { v.y += amount.y; } } setPos(new Vector2f(pos.x + v.x, pos.y + v.y)); } /** * This method inflicts damage on another entity * * @param other The entity to hurt */ protected void hit(Entity other, float amount) { // TODO: Add weapon system for damage adjustment System.out.println(this + " hit " + other + " for " + amount + " damage"); other.health -= amount; if (other.health <= 0) { other.kill(); } } /** * Immediately kills this entity */ protected void kill() { dead = true; } /** * An entity is considered dead if its health is equal to or below 0 * * @return If the entity is dead or not */ public boolean isDead() { return dead; } /** * @return Gets the maximum amount of health an entity can have */ public int getMaxHealth() { return maxHealth; } /** * Sets the maximum amount of health that an entity can have. After this * adjustment, the method then checks to make sure that the current health * for the entity is less than or equal to the max health * * @param maxHealth The new max health for this entity */ protected void setMaxHealth(int maxHealth) { this.maxHealth = maxHealth; health = Math.min(health, maxHealth); } /** * Adds to this entity's health and makes sure that it doesn't exceed the * max health * * @param amount The amount of hp to add */ protected void heal(float amount) { health += amount; health = Math.min(maxHealth, health); } /** * @return The stats for the entity */ protected EntityStats getStats() { return stats; } /** * Sets if the entity is in motion or not * * @param isMoving If the entity is moving, this should be true. */ public void setIsMoving(boolean isMoving) { this.isMoving = isMoving; } /** * @return The width of the entity's main texture */ public int getTextureWidth() { return textureWidth; } /** * Sets the width of the entity's main texture * * @param textureWidth The new width to set for the entity's texture */ protected void setTextureWidth(int textureWidth) { this.textureWidth = textureWidth; updateBounds(); } /** * @return The height of the entity's main texture */ public int getTextureHeight() { return textureHeight; } /** * Sets the height of the entity's main texture * * @param textureHeight The new width to set for the entity's texture */ protected void setTextureHeight(int textureHeight) { this.textureHeight = textureHeight; updateBounds(); } /** * Sets the width and height of this entity that will be used for collision * detection * * @param width The new width to set the entity to * @param height The new height to set the entity to */ protected void setDimensions(int width, int height) { setWidth(width); setHeight(height); } /** * Sets the width and height of this entity's main texture * * @param width The new width to set the entity to * @param height The new height to set the entity to */ protected void setTextureDimensions(int width, int height) { setTextureWidth(width); setTextureHeight(height); } /** * @return The name that this entity goes by */ public String getName() { return name; } /** * Sets the name that this entity will be called * * @param name The new name of the entity */ protected void setName(String name) { this.name = name; } /** * @return The bounding box for this entity */ public Rectangle getBounds() { return bounds; } /** * Call this whenever you change the dimension or position of this entity */ private void updateBounds() { bounds.setBounds(pos.x, pos.y, width, height); } @Override public String toString() { return name; } }
package com.tencent.mm.plugin.aa.ui; import android.view.inputmethod.InputMethodManager; import com.tencent.mm.plugin.aa.ui.BaseAAPresenterActivity.1; class BaseAAPresenterActivity$1$2 implements Runnable { final /* synthetic */ 1 eCL; BaseAAPresenterActivity$1$2(1 1) { this.eCL = 1; } public final void run() { this.eCL.eCK.Wq(); if (this.eCL.eCF) { ((InputMethodManager) this.eCL.eCK.mController.tml.getSystemService("input_method")).showSoftInput(this.eCL.eCH, 0); } } }
package com.thinhlp.cocshopapp.entities; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by thinhlp on 7/7/17. */ public class CartItem { @SerializedName("productId") @Expose private Integer productId; @SerializedName("quantity") @Expose private Integer quantity; @SerializedName("price") @Expose private Integer price; private int id; private int customerId; private String productName; private String imageUrl; private int productInStock; public CartItem() { } public CartItem(Product product, int quantity, int customerId) { this.customerId = customerId; this.productId = product.getProductId(); this.productName = product.getProductName(); this.quantity = quantity; this.productInStock = product.getQuantity(); this.price = product.getPrice(); this.imageUrl = product.getImageUrl(); } public CartItem(int id, int customerId, int productId, String productName, int quantity, int price, String imageUrl, int productInStock) { this.id = id; this.customerId = customerId; this.productId = productId; this.productName = productName; this.quantity = quantity; this.price = price; this.imageUrl = imageUrl; this.productInStock = productInStock; } public int getProductInStock() { return productInStock; } public void setProductInStock(int productInStock) { this.productInStock = productInStock; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCustomerId() { return customerId; } public void setCustomerId(int customerId) { this.customerId = customerId; } public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } }
package com.company; import java.awt.*; public class Rechteck extends Figur { private int breite; private int hoehe; private String name; Rechteck(String name, int xPosition, int yPosition, int hoehe, int breite) { super(xPosition, yPosition); this.hoehe = hoehe; this.breite = breite; this.name = name; } Rechteck(String name, int xPosition, int yPosition, int hoehe, int breite, Color farbe) { super(xPosition, yPosition, farbe); this.hoehe = hoehe; this.breite = breite; this.name = name; } /** * Setzt die Einstellungen zum Zeichnen des Rechtecks und zeichnet es. * @param g */ @Override public void zeichne(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setColor(farbe); g2.drawRect(positionX, positionY, breite, hoehe); } @Override public String toString() { return String.format("%s %s %s %s %s", name, positionX, positionY, hoehe, breite); } }
package array.week_3; import java.util.TreeSet; /** * @Description: LeetCode 类型:数组; 题号:414; 难度:简单 * * 给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。 * 要求算法时间复杂度必须是O(n)。 * * @Author: FanYueXiang * @Date: 2020/1/15 1:16 PM */ public class ThirdMax_414 { /** * 维护一个长度为n的TreeSet集合,与MapReduce,Spark寻找TopN的数据思想一致 * * @param nums * @return */ public int thirdMax(int[] nums) { if (nums == null || nums.length == 0) throw new RuntimeException("error"); TreeSet<Integer> set = new TreeSet<>(); int topN = 3; for (int i = 0; i < nums.length; i++){ set.add(nums[i]); if (set.size() > topN) set.remove(set.first()); } return set.size() < 3?set.last():set.first(); } /** * 使用三个变量one,two,three来存储第一大,第二大和第三大的数字 * @param nums * @return */ public int thirdMax_2(int[] nums) { if (nums == null || nums.length == 0) throw new RuntimeException("nums is null or length of 0"); int n = nums.length; int one = nums[0]; long two = Long.MIN_VALUE; long three = Long.MIN_VALUE; for (int i = 1; i < n; i++){ int current = nums[i]; if (current == one || current == two || current == three) continue; // 如果存在过就跳过不看 if (current > one){ three = two; two = one; one = current; }else if (current > two){ three = two; two = current; }else if (current > three){ three = current; } } if (three == Long.MIN_VALUE) return one; // 没有第三大的元素,就返回最大值 return (int)three; } }
package net.minecraft.client.audio; import net.minecraft.util.ITickable; public interface ITickableSound extends ISound, ITickable { boolean isDonePlaying(); } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\client\audio\ITickableSound.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.github.agmcc.slate.ast.statement; import com.github.agmcc.slate.ast.Node; import com.github.agmcc.slate.ast.Position; import com.github.agmcc.slate.ast.expression.Expression; import com.github.agmcc.slate.bytecode.Scope; import java.util.Optional; import java.util.function.Consumer; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.ToString; import org.objectweb.asm.MethodVisitor; @Getter @Setter @RequiredArgsConstructor @AllArgsConstructor @EqualsAndHashCode @ToString public class Return implements Statement { private final Expression value; private Position position; @Override public void process(Consumer<Node> operation) { operation.accept(this); Optional.ofNullable(value).ifPresent(v -> v.process(operation)); } @Override public void generate(MethodVisitor mv, Scope scope) { if (value != null) { value.push(mv, scope); mv.visitInsn(value.getType(scope).getOpcode(IRETURN)); } else { mv.visitInsn(RETURN); } } }
package com.takshine.wxcrm.model; import com.takshine.wxcrm.base.model.BaseModel; /** * 消息 * @author liulin * */ public class MessagesExtModel extends BaseModel{ private String relaid; private String relatype; private String filename; private String source_filename; private String filetype; public String getRelaid() { return relaid; } public void setRelaid(String relaid) { this.relaid = relaid; } public String getRelatype() { return relatype; } public void setRelatype(String relatype) { this.relatype = relatype; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public String getSource_filename() { return source_filename; } public void setSource_filename(String source_filename) { this.source_filename = source_filename; } public String getFiletype() { return filetype; } public void setFiletype(String filetype) { this.filetype = filetype; } }
package com.stark.netty.section_12.charpter; import io.netty.buffer.ByteBuf; import org.msgpack.annotation.Message; import java.nio.ByteBuffer; /** * Created by Stark on 2018/3/16. * Netty 协议消息体 */ @Message public final class NettyMessage { private Header header;//消息头 private Object body;//消息体 public final Header getHeader() { return header; } public final void setHeader(Header header) { this.header = header; } public final Object getBody() { return body; } public final void setBody(Object body) { this.body = body; } @Override public String toString() { return "Netty Message [header=" + header + "]"; } }
package com.rc.adapter; import java.util.ArrayList; import java.util.List; /** * Created by song on 17-5-30. */ public abstract class BaseAdapter<T extends ViewHolder> { public int getCount() { return 0; } public abstract T onCreateViewHolder(int viewType, int position); public HeaderViewHolder onCreateHeaderViewHolder(int viewType, int position) { return null; } public int getItemViewType(int position) { return 0; } public abstract void onBindViewHolder(T viewHolder, int position); public void onBindHeaderViewHolder(HeaderViewHolder viewHolder, int position) { } }
package com.hb.rssai.event; /** * Created by Administrator on 2017/7/9 0009. */ public class TipsEvent { private int message; private int newsCount; public TipsEvent(int message,int newsCount) { this.message = message; this.newsCount = newsCount; } public TipsEvent(int message) { this.message = message; } public int getMessage() { return message; } public void setMessage(int message) { this.message = message; } public int getNewsCount() { return newsCount; } public void setNewsCount(int newsCount) { this.newsCount = newsCount; } }
package mk.petrovski.weathergurumvp.data.remote.helper.error; /** * Created by Nikola Petrovski on 2/22/2017. */ public class ServerException extends Throwable { public ServerException(Throwable throwable) { super(throwable); } }
package recappservice; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the recappservice package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _GetApplicationsResponse_QNAME = new QName("http://applications/", "getApplicationsResponse"); private final static QName _SetApplications_QNAME = new QName("http://applications/", "setApplications"); private final static QName _RemoveApplication_QNAME = new QName("http://applications/", "removeApplication"); private final static QName _SearchByStatus_QNAME = new QName("http://applications/", "searchByStatus"); private final static QName _Logout_QNAME = new QName("http://applications/", "logout"); private final static QName _SetApplicationsResponse_QNAME = new QName("http://applications/", "setApplicationsResponse"); private final static QName _SearchByRecruiter_QNAME = new QName("http://applications/", "searchByRecruiter"); private final static QName _GetApplications_QNAME = new QName("http://applications/", "getApplications"); private final static QName _SearchByOfferResponse_QNAME = new QName("http://applications/", "searchByOfferResponse"); private final static QName _AddApplicationResponse_QNAME = new QName("http://applications/", "addApplicationResponse"); private final static QName _SearchByRecruiterResponse_QNAME = new QName("http://applications/", "searchByRecruiterResponse"); private final static QName _Login_QNAME = new QName("http://applications/", "login"); private final static QName _SearchByApplicantResponse_QNAME = new QName("http://applications/", "searchByApplicantResponse"); private final static QName _Exception_QNAME = new QName("http://applications/", "Exception"); private final static QName _SearchByStatusResponse_QNAME = new QName("http://applications/", "searchByStatusResponse"); private final static QName _LoginResponse_QNAME = new QName("http://applications/", "loginResponse"); private final static QName _LogoutResponse_QNAME = new QName("http://applications/", "logoutResponse"); private final static QName _SearchByOffer_QNAME = new QName("http://applications/", "searchByOffer"); private final static QName _AddApplication_QNAME = new QName("http://applications/", "addApplication"); private final static QName _SearchByApplicant_QNAME = new QName("http://applications/", "searchByApplicant"); private final static QName _RemoveApplicationResponse_QNAME = new QName("http://applications/", "removeApplicationResponse"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: recappservice * */ public ObjectFactory() { } /** * Create an instance of {@link SearchByStatusResponse } * */ public SearchByStatusResponse createSearchByStatusResponse() { return new SearchByStatusResponse(); } /** * Create an instance of {@link LoginResponse } * */ public LoginResponse createLoginResponse() { return new LoginResponse(); } /** * Create an instance of {@link LogoutResponse } * */ public LogoutResponse createLogoutResponse() { return new LogoutResponse(); } /** * Create an instance of {@link SearchByOffer } * */ public SearchByOffer createSearchByOffer() { return new SearchByOffer(); } /** * Create an instance of {@link AddApplication } * */ public AddApplication createAddApplication() { return new AddApplication(); } /** * Create an instance of {@link RemoveApplicationResponse } * */ public RemoveApplicationResponse createRemoveApplicationResponse() { return new RemoveApplicationResponse(); } /** * Create an instance of {@link SearchByApplicant } * */ public SearchByApplicant createSearchByApplicant() { return new SearchByApplicant(); } /** * Create an instance of {@link AddApplicationResponse } * */ public AddApplicationResponse createAddApplicationResponse() { return new AddApplicationResponse(); } /** * Create an instance of {@link SearchByRecruiterResponse } * */ public SearchByRecruiterResponse createSearchByRecruiterResponse() { return new SearchByRecruiterResponse(); } /** * Create an instance of {@link Login } * */ public Login createLogin() { return new Login(); } /** * Create an instance of {@link Exception } * */ public Exception createException() { return new Exception(); } /** * Create an instance of {@link SearchByApplicantResponse } * */ public SearchByApplicantResponse createSearchByApplicantResponse() { return new SearchByApplicantResponse(); } /** * Create an instance of {@link SearchByStatus } * */ public SearchByStatus createSearchByStatus() { return new SearchByStatus(); } /** * Create an instance of {@link Logout } * */ public Logout createLogout() { return new Logout(); } /** * Create an instance of {@link SetApplicationsResponse } * */ public SetApplicationsResponse createSetApplicationsResponse() { return new SetApplicationsResponse(); } /** * Create an instance of {@link GetApplications } * */ public GetApplications createGetApplications() { return new GetApplications(); } /** * Create an instance of {@link SearchByOfferResponse } * */ public SearchByOfferResponse createSearchByOfferResponse() { return new SearchByOfferResponse(); } /** * Create an instance of {@link SearchByRecruiter } * */ public SearchByRecruiter createSearchByRecruiter() { return new SearchByRecruiter(); } /** * Create an instance of {@link GetApplicationsResponse } * */ public GetApplicationsResponse createGetApplicationsResponse() { return new GetApplicationsResponse(); } /** * Create an instance of {@link RemoveApplication } * */ public RemoveApplication createRemoveApplication() { return new RemoveApplication(); } /** * Create an instance of {@link SetApplications } * */ public SetApplications createSetApplications() { return new SetApplications(); } /** * Create an instance of {@link JobOffer } * */ public JobOffer createJobOffer() { return new JobOffer(); } /** * Create an instance of {@link Applicant } * */ public Applicant createApplicant() { return new Applicant(); } /** * Create an instance of {@link Application } * */ public Application createApplication() { return new Application(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetApplicationsResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "getApplicationsResponse") public JAXBElement<GetApplicationsResponse> createGetApplicationsResponse(GetApplicationsResponse value) { return new JAXBElement<GetApplicationsResponse>(_GetApplicationsResponse_QNAME, GetApplicationsResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SetApplications }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "setApplications") public JAXBElement<SetApplications> createSetApplications(SetApplications value) { return new JAXBElement<SetApplications>(_SetApplications_QNAME, SetApplications.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link RemoveApplication }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "removeApplication") public JAXBElement<RemoveApplication> createRemoveApplication(RemoveApplication value) { return new JAXBElement<RemoveApplication>(_RemoveApplication_QNAME, RemoveApplication.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SearchByStatus }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "searchByStatus") public JAXBElement<SearchByStatus> createSearchByStatus(SearchByStatus value) { return new JAXBElement<SearchByStatus>(_SearchByStatus_QNAME, SearchByStatus.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Logout }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "logout") public JAXBElement<Logout> createLogout(Logout value) { return new JAXBElement<Logout>(_Logout_QNAME, Logout.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SetApplicationsResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "setApplicationsResponse") public JAXBElement<SetApplicationsResponse> createSetApplicationsResponse(SetApplicationsResponse value) { return new JAXBElement<SetApplicationsResponse>(_SetApplicationsResponse_QNAME, SetApplicationsResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SearchByRecruiter }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "searchByRecruiter") public JAXBElement<SearchByRecruiter> createSearchByRecruiter(SearchByRecruiter value) { return new JAXBElement<SearchByRecruiter>(_SearchByRecruiter_QNAME, SearchByRecruiter.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetApplications }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "getApplications") public JAXBElement<GetApplications> createGetApplications(GetApplications value) { return new JAXBElement<GetApplications>(_GetApplications_QNAME, GetApplications.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SearchByOfferResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "searchByOfferResponse") public JAXBElement<SearchByOfferResponse> createSearchByOfferResponse(SearchByOfferResponse value) { return new JAXBElement<SearchByOfferResponse>(_SearchByOfferResponse_QNAME, SearchByOfferResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AddApplicationResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "addApplicationResponse") public JAXBElement<AddApplicationResponse> createAddApplicationResponse(AddApplicationResponse value) { return new JAXBElement<AddApplicationResponse>(_AddApplicationResponse_QNAME, AddApplicationResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SearchByRecruiterResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "searchByRecruiterResponse") public JAXBElement<SearchByRecruiterResponse> createSearchByRecruiterResponse(SearchByRecruiterResponse value) { return new JAXBElement<SearchByRecruiterResponse>(_SearchByRecruiterResponse_QNAME, SearchByRecruiterResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Login }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "login") public JAXBElement<Login> createLogin(Login value) { return new JAXBElement<Login>(_Login_QNAME, Login.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SearchByApplicantResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "searchByApplicantResponse") public JAXBElement<SearchByApplicantResponse> createSearchByApplicantResponse(SearchByApplicantResponse value) { return new JAXBElement<SearchByApplicantResponse>(_SearchByApplicantResponse_QNAME, SearchByApplicantResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Exception }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "Exception") public JAXBElement<Exception> createException(Exception value) { return new JAXBElement<Exception>(_Exception_QNAME, Exception.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SearchByStatusResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "searchByStatusResponse") public JAXBElement<SearchByStatusResponse> createSearchByStatusResponse(SearchByStatusResponse value) { return new JAXBElement<SearchByStatusResponse>(_SearchByStatusResponse_QNAME, SearchByStatusResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link LoginResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "loginResponse") public JAXBElement<LoginResponse> createLoginResponse(LoginResponse value) { return new JAXBElement<LoginResponse>(_LoginResponse_QNAME, LoginResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link LogoutResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "logoutResponse") public JAXBElement<LogoutResponse> createLogoutResponse(LogoutResponse value) { return new JAXBElement<LogoutResponse>(_LogoutResponse_QNAME, LogoutResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SearchByOffer }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "searchByOffer") public JAXBElement<SearchByOffer> createSearchByOffer(SearchByOffer value) { return new JAXBElement<SearchByOffer>(_SearchByOffer_QNAME, SearchByOffer.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AddApplication }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "addApplication") public JAXBElement<AddApplication> createAddApplication(AddApplication value) { return new JAXBElement<AddApplication>(_AddApplication_QNAME, AddApplication.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SearchByApplicant }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "searchByApplicant") public JAXBElement<SearchByApplicant> createSearchByApplicant(SearchByApplicant value) { return new JAXBElement<SearchByApplicant>(_SearchByApplicant_QNAME, SearchByApplicant.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link RemoveApplicationResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://applications/", name = "removeApplicationResponse") public JAXBElement<RemoveApplicationResponse> createRemoveApplicationResponse(RemoveApplicationResponse value) { return new JAXBElement<RemoveApplicationResponse>(_RemoveApplicationResponse_QNAME, RemoveApplicationResponse.class, null, value); } }
/* * Copyright © 2018 tesshu.com (webmaster@tesshu.com) * * 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.tesshu.sonic.player.event.legacy; import com.tesshu.sonic.player.event.ICustomComponent; import javafx.event.Event; import javafx.event.EventDispatchChain; import javafx.event.EventDispatcher; public final class DelegateDispatcher implements EventDispatcher { private final EventDispatcher delegate; private ICustomComponent<?> origin; public DelegateDispatcher(EventDispatcher delegate, ICustomComponent<?> origin) { this.delegate = delegate; this.origin = origin; } @Override public Event dispatchEvent(Event event, EventDispatchChain org) { EventDispatchChain chain = origin.getInstance().buildEventDispatchChain(org); return delegate.dispatchEvent(event, chain); } }
/* * Copyright (C) 2001 - 2015 Marko Salmela, http://fuusio.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fuusio.api.ui.action; import android.content.Context; import java.util.HashMap; import java.util.Stack; public class ActionManager { private static final int MAX_UNDO_STACK_SIZE = 20; private final HashMap<ActionContext, Stack<Action>> mActionStacks; private final HashMap<ActionContext, Action> mRedoableActions; private final Context mApplicationContext; private ActionContext mActiveActionContext; private Stack<Action> mActiveStack; public ActionManager(final Context applicationContext) { mApplicationContext = applicationContext; mActionStacks = new HashMap<>(); mRedoableActions = new HashMap<>(); mActiveStack = null; } public Context getContext() { return mApplicationContext; } public ActionContext getActiveActionContext() { return mActiveActionContext; } public void setActiveActionContext(final ActionContext applicationContext) { mActiveActionContext = applicationContext; if (mActiveActionContext != null) { mActiveStack = mActionStacks.get(mActiveActionContext); if (mActiveStack == null) { mActiveStack = new Stack<>(); mActionStacks.put(applicationContext, mActiveStack); } } } public void clearActions() { mActiveStack.clear(); } public boolean executeAction(final Action action) { boolean wasExecuted = action.execute(mActiveActionContext); if (wasExecuted) { if (mActiveStack.size() >= MAX_UNDO_STACK_SIZE) { mActiveStack.remove(0); } if (action.isUndoable()) { mActiveStack.add(action); } } return wasExecuted; } public boolean redo() { assert (isRedoEnabled()); final Action action = mRedoableActions.get(mApplicationContext); boolean wasExecuted = executeAction(action); mRedoableActions.remove(mApplicationContext); return wasExecuted; } public boolean undo() { assert (isUndoEnabled()); final Action action = mActiveStack.pop(); boolean wasExecuted = action.undo(mActiveActionContext); if (wasExecuted) { mRedoableActions.put(mActiveActionContext, action); } return wasExecuted; } public boolean isRedoEnabled() { return (mRedoableActions.get(mApplicationContext) != null); } public boolean isUndoEnabled() { return !mActiveStack.isEmpty(); } }
package earth.xor.rest; import static org.mockito.Matchers.anyInt; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import spark.Spark; import earth.xor.rest.routes.DeleteBookmarkByIdRoute; import earth.xor.rest.routes.GetBookmarkByIdRoute; import earth.xor.rest.routes.OptionsForIdRoute; import earth.xor.rest.routes.OptionsRoute; import earth.xor.rest.routes.PostBookmarkRoute; @RunWith(PowerMockRunner.class) @PrepareForTest({ Spark.class }) public class TestSparkFacade { @Mock GetBookmarkByIdRoute getBookmarkByIdRoute; @Mock PostBookmarkRoute postBookmarkRoute; @Mock OptionsRoute optionsRoute; @Mock DeleteBookmarkByIdRoute deleteRoute; @Mock OptionsForIdRoute optionsForIdRoute; private SparkFacade facade; @Before public void setUp() { facade = new SparkFacade(); PowerMockito.mockStatic(Spark.class); } @Test public void canSetPort() { facade.setPort(anyInt()); PowerMockito.verifyStatic(); Spark.setPort(anyInt()); } @Test public void canSetGetRoute() { facade.setGetRoute(getBookmarkByIdRoute); PowerMockito.verifyStatic(); Spark.get(getBookmarkByIdRoute); } @Test public void canSetPostRoute() { facade.setGetRoute(postBookmarkRoute); PowerMockito.verifyStatic(); Spark.get(postBookmarkRoute); } @Test public void canSetOptionsRoute() { facade.setOptionsRoute(optionsRoute); PowerMockito.verifyStatic(); Spark.options(optionsRoute); } @Test public void canSetDeleteRoute() { facade.setDeleteRoute(deleteRoute); PowerMockito.verifyStatic(); Spark.delete(deleteRoute); } @Test public void canSetOptionsForIdRoute() { facade.setOptionsForIdRoute(optionsForIdRoute); PowerMockito.verifyStatic(); Spark.options(optionsForIdRoute); } }
package com.tencent.mm.plugin.record.ui; import com.tencent.mm.R; import com.tencent.mm.plugin.record.ui.RecordMsgFileUI.11; import com.tencent.mm.ui.base.l; import com.tencent.mm.ui.base.n.c; class RecordMsgFileUI$11$1 implements c { final /* synthetic */ 11 mtj; RecordMsgFileUI$11$1(11 11) { this.mtj = 11; } public final void a(l lVar) { lVar.e(0, this.mtj.mtg.getString(R.l.favorite_share_with_friend)); } }
package org.terasoluna.gfw.test.utilities.app; import java.io.Serializable; import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.joda.time.LocalTime; import org.springframework.format.annotation.DateTimeFormat; public class RowForm implements Serializable { private static final long serialVersionUID = 1L; private int intItem; private long longItem; private double doubleItem; private char charItem; @DateTimeFormat(pattern = "yyyy/MM/dd HH:mm:ss.SSS") private DateTime dateTimeItem; @DateTimeFormat(pattern = "HH:mm") private LocalTime localTimeItem; @DateTimeFormat(pattern = "yyyy/MM/dd") private DateMidnight dateMidnightItem; public int getIntItem() { return intItem; } public void setIntItem(int intItem) { this.intItem = intItem; } public long getLongItem() { return longItem; } public void setLongItem(long longItem) { this.longItem = longItem; } public double getDoubleItem() { return doubleItem; } public void setDoubleItem(double doubleItem) { this.doubleItem = doubleItem; } public char getCharItem() { return charItem; } public void setCharItem(char charItem) { this.charItem = charItem; } public DateTime getDateTimeItem() { return dateTimeItem; } public void setDateTimeItem(DateTime dateTimeItem) { this.dateTimeItem = dateTimeItem; } public LocalTime getLocalTimeItem() { return localTimeItem; } public void setLocalTimeItem(LocalTime localTimeItem) { this.localTimeItem = localTimeItem; } public DateMidnight getDateMidnightItem() { return dateMidnightItem; } public void setDateMidnightItem(DateMidnight dateMidnightItem) { this.dateMidnightItem = dateMidnightItem; } }
package Objetos; import java.util.Vector; import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.game.Sprite; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * El controlador que administra, dibuja y actualiza a los proyectiles * @author Alberto Ortiz */ public class ControladorProyectil { private Vector contenedor; /** * El metodo constructor que crea un nuevo vector */ public ControladorProyectil() { this.contenedor = new Vector(); } /** * Regresa el tamaño actual del Vector * @return - El tamaño actual del vector */ public int getSize(){ return this.contenedor.size(); } /** * Regresa el proyectil dada una posición * @param index - El lugar del proyectil que se desea obtener * @return - El proyectil en el lugar especificado por el parámetro */ public Proyectil proyectilAt(int index){ return (Proyectil)this.contenedor.elementAt(index); } public void vaciarControlador() { this.contenedor.removeAllElements(); } /** * Agrega un proyectil al Vector * @param proyectil - El proyectil que se ha de agregar */ public void AgregarProyectil(Proyectil proyectil) { this.contenedor.addElement(proyectil); } /** * Borra el proyectil indicado * @param proyectil - EL proyectil que se borrará */ public void BorrarProyectil(Proyectil proyectil) { this.contenedor.removeElement(proyectil); } /** * Dibuja todos los proyectiles que estan dentro del Vector * @param g - Permite dibujar */ public void dibujar(Graphics g) { for(int i = 0; i < this.contenedor.size() - 1; i++) { Proyectil temporal = (Proyectil) this.contenedor.elementAt(i); temporal.dibujar(g); } } /** * Actualiza la posición y estado de todos los proyectiles en el Vector */ public void actualizar() { for(int i = 0; i < this.contenedor.size() - 1; i++) { Proyectil temporal = (Proyectil) this.contenedor.elementAt(i); temporal.actualizar(); if(temporal.impacto || temporal.fueraDeLimites) { this.contenedor.removeElementAt(i); } } } /** * Regresa un String con la información del tamaño, con objetivos de prueba * @return - Un hilo con el tamaño del Vector */ public String toString() { return this.contenedor.size() + ""; } }
/* * This software is licensed under the MIT License * https://github.com/GStefanowich/MC-Server-Protection * * Copyright (c) 2019 Gregory Stefanowich * * 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 net.theelm.sewingmachine.base.objects; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.SimpleInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtList; import net.minecraft.nbt.NbtString; import net.minecraft.registry.Registries; import net.minecraft.screen.GenericContainerScreenHandler; import net.minecraft.screen.ScreenHandler; import net.minecraft.screen.ScreenHandlerType; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import net.minecraft.util.crash.CrashException; import net.minecraft.util.crash.CrashReport; import net.minecraft.util.crash.CrashReportSection; import net.minecraft.util.math.MathHelper; import net.theelm.sewingmachine.base.CoreMod; import net.theelm.sewingmachine.utilities.ModUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; public class PlayerBackpack extends SimpleInventory { private final Set<Identifier> autopickup = new HashSet<>(); private final int rows; private final @NotNull PlayerEntity player; // Create an entirely new backpack public PlayerBackpack(@NotNull PlayerEntity player, int rows) { super(MathHelper.clamp(rows, 1, 6) * 9); this.rows = rows; this.player = player; } public PlayerBackpack(@NotNull PlayerEntity player, @NotNull PlayerBackpack old) { this(player, old.getRows()); // Transfer the contents of the inventory this.readTags(old.getTags()); // Transfer the auto-pickup settings this.readPickupTags(old.getPickupTags()); } // Copy items to the backpack from the previous public PlayerBackpack(@NotNull PlayerBackpack backpack) { this(backpack, backpack.getRows() + 1); } public PlayerBackpack(@NotNull PlayerBackpack backpack, int rows) { this(backpack.getPlayer(), rows); // Transfer the contents of the inventory this.readTags(backpack.getTags()); // Transfer the auto-pickup settings this.readPickupTags(backpack.getPickupTags()); } /* * Insert into the backpack */ public boolean insertStack(@NotNull ItemStack itemStack) { return this.insertStack(-1, itemStack); } public boolean insertStack(int slot, @NotNull ItemStack itemStack) { if (itemStack.isEmpty()) return false; try { // Damaged items must be in their own slot if (itemStack.isDamaged()) { // Search for a slot if (slot == -1) slot = this.getEmptySlot(); // If a slot is not found, fail if (slot < 0) return false; this.setStack(slot, itemStack.copy()); itemStack.decrement(1); return true; } int remainingStack; do { remainingStack = itemStack.getCount(); if (slot == -1) itemStack.setCount(this.insertFrom(itemStack)); else itemStack.setCount(this.insertFrom(slot, itemStack)); } while( !itemStack.isEmpty() && itemStack.getCount() < remainingStack ); return itemStack.getCount() <= remainingStack; } catch (Throwable var6) { CrashReport crashReport = CrashReport.create(var6, "Adding item to inventory"); CrashReportSection crashReportSection = crashReport.addElement("Item being added"); crashReportSection.add("Item ID", Item.getRawId(itemStack.getItem())); crashReportSection.add("Item data", itemStack.getDamage()); crashReportSection.add("Item name", () -> itemStack.getName().getString()); throw new CrashException(crashReport); } } /** * Transfer items from the stack provided into the inventory * @param extStack The stack to take items from * @return The amount of items remaining in the extStack */ private int insertFrom(@NotNull ItemStack extStack) { int i = this.getOccupiedSlotWithRoomForStack(extStack); if (i == -1) i = this.getEmptySlot(); return i == -1 ? extStack.getCount() : this.insertFrom(i, extStack); } /** * Transfer items from the stack provided into a slot in the inventory * @param slot The slot to insert items into * @param extStack The stack to take items from * @return The amount of items remaining in the extStack */ private int insertFrom(int slot, @NotNull ItemStack extStack) { Item item = extStack.getItem(); int j = extStack.getCount(); ItemStack invStack = this.getStack(slot); if (invStack.isEmpty()) { invStack = new ItemStack(item, 0); if (extStack.hasNbt()) { invStack.setNbt(extStack.getOrCreateNbt().copy()); } this.setStack(slot, invStack); } int k = j; if (j > invStack.getMaxCount() - invStack.getCount()) { k = invStack.getMaxCount() - invStack.getCount(); } if (k > this.getMaxCountPerStack() - invStack.getCount()) { k = this.getMaxCountPerStack() - invStack.getCount(); } if (k == 0) { return j; } else { j -= k; invStack.increment(k); return j; } } private boolean canStackAddMore(@NotNull ItemStack mainStack, @NotNull ItemStack otherStack) { return !mainStack.isEmpty() && ItemStack.canCombine(mainStack, otherStack) && mainStack.isStackable() && mainStack.getCount() < mainStack.getMaxCount() && mainStack.getCount() < this.getMaxCountPerStack(); } public int getEmptySlot() { for(int i = 0; i < this.size(); ++i) if (this.getStack(i).isEmpty()) return i; return -1; } public int getOccupiedSlotWithRoomForStack(ItemStack itemStack) { for(int slot = 0; slot < this.size(); ++slot) { if (this.canStackAddMore(this.getStack(slot), itemStack)) { return slot; } } return -1; } /* * Backpack Items as NBT */ public void readTags(@NotNull NbtList listTag) { for(int slot = 0; slot < this.size(); ++slot) { this.setStack(slot, ItemStack.EMPTY); } for(int itemCount = 0; itemCount < listTag.size(); ++itemCount) { NbtCompound compoundTag = listTag.getCompound(itemCount); int slot = compoundTag.getByte("Slot") & 255; if (slot >= 0 && slot < this.size()) { this.setStack(slot, ItemStack.fromNbt(compoundTag)); } } } public @NotNull NbtList getTags() { NbtList listTag = new NbtList(); for(int slot = 0; slot < this.size(); ++slot) { ItemStack itemStack = this.getStack(slot); if (!itemStack.isEmpty()) { NbtCompound compoundTag = new NbtCompound(); compoundTag.putByte("Slot", (byte)slot); itemStack.writeNbt(compoundTag); listTag.add(compoundTag); } } return listTag; } /* * Backpack Auto-Pickup NBT */ public void readPickupTags(@NotNull NbtList listTag) { for (int i = 0; i < listTag.size(); ++i) { this.autopickup.add(new Identifier( listTag.getString(i) )); } } public void readPickupTags(@NotNull Collection<Identifier> listTag) { this.autopickup.addAll(listTag); } public @NotNull NbtList getPickupTags() { NbtList listTag = new NbtList(); for (Identifier identifier : this.autopickup) { listTag.add(NbtString.of( identifier.toString() )); } return listTag; } public @NotNull Collection<Identifier> getPickupIdentifiers() { return this.autopickup; } public @NotNull PlayerEntity getPlayer() { return this.player; } public int getRows() { return this.rows; } public @NotNull Text getName() { return Text.literal(this.player.getDisplayName().getString() + "'s Backpack"); } public @Nullable ScreenHandler createContainer(int syncId, @NotNull PlayerInventory playerInventory) { int slots = this.size(); ScreenHandlerType<?> type; // If the player is using a modded client, we can use special formatting if (ModUtils.hasModule(this.player, "base")) { type = CoreMod.BACKPACK; } else type = PlayerBackpack.getSizeType(slots); return type == null ? null : new GenericContainerScreenHandler(type, syncId, playerInventory, this, slots / 9); } public static @Nullable ScreenHandlerType<?> getSizeType(int slots) { switch (slots) { case 9: return ScreenHandlerType.GENERIC_3X3; case 18: return ScreenHandlerType.GENERIC_9X2; case 27: return ScreenHandlerType.GENERIC_9X3; case 36: return ScreenHandlerType.GENERIC_9X4; case 45: return ScreenHandlerType.GENERIC_9X5; case 54: return ScreenHandlerType.GENERIC_9X6; } return null; } /** * Toggles the Auto-Pickup setting for an Item * @param item * @return TRUE if the item was added, FALSE if it was removed */ public boolean toggleAutoPickup(@NotNull Item item) { Identifier id = Registries.ITEM.getId(item); if (!this.autopickup.remove(id)) { this.autopickup.add(id); return true; } return false; } public boolean shouldAutoPickup(@NotNull ItemStack stack) { return this.shouldAutoPickup(stack.getItem()); } public boolean shouldAutoPickup(@NotNull Item item) { return this.shouldAutoPickup(Registries.ITEM.getId(item)); } public boolean shouldAutoPickup(@NotNull Identifier identifier) { return this.autopickup.contains(identifier); } @Override public void onOpen(@NotNull PlayerEntity player) { // Play sound (Sent by the server) if (player instanceof ServerPlayerEntity) player.playSound(SoundEvents.UI_TOAST_OUT, SoundCategory.BLOCKS, 0.5f, 1.0f); // Parent method super.onOpen(player); } @Override public void onClose(@NotNull PlayerEntity player) { // Play sound (Sent by the server) if (player instanceof ServerPlayerEntity) player.playSound(SoundEvents.UI_TOAST_IN, SoundCategory.BLOCKS, 0.5f, 1.0f); // Parent method super.onClose(player); } public void dropAll() { this.dropAll(false); } public void dropAll(boolean vanish) { List<ItemStack> list = this.clearToList(); for (ItemStack itemStack : list) { if (itemStack.isEmpty() || (vanish && EnchantmentHelper.hasVanishingCurse(itemStack))) continue; this.player.dropItem(itemStack, true, false); } } }