repo_name
stringlengths
7
70
file_path
stringlengths
9
215
context
list
import_statement
stringlengths
47
10.3k
token_num
int64
643
100k
cropped_code
stringlengths
62
180k
all_code
stringlengths
62
224k
next_line
stringlengths
9
1.07k
gold_snippet_index
int64
0
117
created_at
stringlengths
25
25
level
stringclasses
9 values
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/manager/CheckManager.java
[ { "identifier": "Reach", "path": "src/main/java/ac/grim/grimac/checks/impl/combat/Reach.java", "snippet": "public class Reach extends PacketCheck {\n // Concurrent to support weird entity trackers\n private final ConcurrentLinkedQueue<Integer> playerAttackQueue = new ConcurrentLinkedQueue<>();\n\n...
import ac.grim.grimac.checks.impl.combat.Reach; import ac.grim.grimac.checks.impl.groundspoof.NoFallA; import ac.grim.grimac.checks.impl.movement.*; import ac.grim.grimac.checks.impl.prediction.DebugHandler; import ac.grim.grimac.checks.impl.prediction.NoFallB; import ac.grim.grimac.checks.impl.prediction.OffsetHandler; import ac.grim.grimac.checks.impl.scaffolding.AirLiquidPlace; import ac.grim.grimac.checks.impl.velocity.ExplosionHandler; import ac.grim.grimac.checks.impl.velocity.KnockbackHandler; import ac.grim.grimac.checks.type.*; import ac.grim.grimac.events.packets.PacketEntityReplication; import ac.grim.grimac.player.GrimPlayer; import ac.grim.grimac.predictionengine.GhostBlockDetector; import ac.grim.grimac.utils.anticheat.update.*; import ac.grim.grimac.utils.latency.CompensatedCooldown; import com.google.common.collect.ClassToInstanceMap; import com.google.common.collect.ImmutableClassToInstanceMap; import io.github.retrooper.packetevents.event.impl.PacketPlayReceiveEvent; import io.github.retrooper.packetevents.event.impl.PacketPlaySendEvent;
18,419
package ac.grim.grimac.manager; public class CheckManager { ClassToInstanceMap<PacketCheck> packetChecks; ClassToInstanceMap<PositionCheck> positionCheck; ClassToInstanceMap<RotationCheck> rotationCheck; ClassToInstanceMap<VehicleCheck> vehicleCheck; ClassToInstanceMap<BlockPlaceCheck> blockPlaceCheck; ClassToInstanceMap<PostPredictionCheck> postPredictionCheck; public CheckManager(GrimPlayer player) { // Include post checks in the packet check too packetChecks = new ImmutableClassToInstanceMap.Builder<PacketCheck>()
package ac.grim.grimac.manager; public class CheckManager { ClassToInstanceMap<PacketCheck> packetChecks; ClassToInstanceMap<PositionCheck> positionCheck; ClassToInstanceMap<RotationCheck> rotationCheck; ClassToInstanceMap<VehicleCheck> vehicleCheck; ClassToInstanceMap<BlockPlaceCheck> blockPlaceCheck; ClassToInstanceMap<PostPredictionCheck> postPredictionCheck; public CheckManager(GrimPlayer player) { // Include post checks in the packet check too packetChecks = new ImmutableClassToInstanceMap.Builder<PacketCheck>()
.put(Reach.class, new Reach(player))
0
2023-11-11 05:14:12+00:00
24k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/ui/dialog/AlbumDialog.java
[ { "identifier": "BaseAdapter", "path": "library/base/src/main/java/com/hjq/base/BaseAdapter.java", "snippet": "public abstract class BaseAdapter<VH extends BaseAdapter<?>.ViewHolder>\n extends RecyclerView.Adapter<VH> implements ResourcesAction {\n\n /** 上下文对象 */\n private final Context mCo...
import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import com.buaa.food.http.glide.GlideApp; import com.hjq.base.BaseAdapter; import com.hjq.base.BaseDialog; import com.hjq.base.BottomSheetDialog; import com.buaa.food.R; import com.buaa.food.app.AppAdapter; import java.util.List;
15,538
package com.buaa.food.ui.dialog; public final class AlbumDialog { public static final class Builder extends BaseDialog.Builder<Builder>
package com.buaa.food.ui.dialog; public final class AlbumDialog { public static final class Builder extends BaseDialog.Builder<Builder>
implements BaseAdapter.OnItemClickListener {
0
2023-11-14 10:04:26+00:00
24k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/model/block/processed/BlockModel.java
[ { "identifier": "ModelHelper", "path": "src/main/java/useless/dragonfly/helper/ModelHelper.java", "snippet": "public class ModelHelper {\n\tpublic static final Map<NamespaceId, ModelData> modelDataFiles = new HashMap<>();\n\tpublic static final Map<NamespaceId, BlockModel> registeredModels = new HashMap...
import useless.dragonfly.helper.ModelHelper; import useless.dragonfly.model.block.data.ModelData; import useless.dragonfly.model.block.data.PositionData; import useless.dragonfly.registries.TextureRegistry; import useless.dragonfly.utilities.NamespaceId; import javax.annotation.Nonnull; import java.util.HashMap;
16,184
package useless.dragonfly.model.block.processed; public class BlockModel { private static final HashMap<String, PositionData> defaultDisplays = new HashMap<>(); static { PositionData gui = new PositionData(); gui.rotation = new double[]{30, 225, 0}; gui.translation = new double[] {0, 0, 0}; gui.scale = new double[]{0.625, 0.625, 0.625}; PositionData ground = new PositionData(); ground.rotation = new double[]{0, 0, 0}; ground.translation = new double[] {0, 3, 0}; ground.scale = new double[]{0.25, 0.25, 0.25}; PositionData right_3rd = new PositionData(); right_3rd.rotation = new double[]{75, 45, 0}; right_3rd.translation = new double[] {0, 2.5, 0}; right_3rd.scale = new double[]{0.375, 0.375, 0.375}; PositionData right_first = new PositionData(); right_first.rotation = new double[]{0, 45, 0}; right_first.translation = new double[] {0, 0, 0}; right_first.scale = new double[]{0.4, 0.4, 0.4}; defaultDisplays.put("gui", gui); defaultDisplays.put("ground", ground); defaultDisplays.put("thirdperson_righthand", right_3rd); defaultDisplays.put("firstperson_righthand", right_first); } public BlockCube[] blockCubes = new BlockCube[0]; protected ModelData modelData; protected BlockModel parentModel; public HashMap<String, String> textureMap; public HashMap<String, PositionData> display; public final NamespaceId namespaceId; public BlockModel(NamespaceId namespaceId){ this.namespaceId = namespaceId; refreshModel(); } public void refreshModel(){
package useless.dragonfly.model.block.processed; public class BlockModel { private static final HashMap<String, PositionData> defaultDisplays = new HashMap<>(); static { PositionData gui = new PositionData(); gui.rotation = new double[]{30, 225, 0}; gui.translation = new double[] {0, 0, 0}; gui.scale = new double[]{0.625, 0.625, 0.625}; PositionData ground = new PositionData(); ground.rotation = new double[]{0, 0, 0}; ground.translation = new double[] {0, 3, 0}; ground.scale = new double[]{0.25, 0.25, 0.25}; PositionData right_3rd = new PositionData(); right_3rd.rotation = new double[]{75, 45, 0}; right_3rd.translation = new double[] {0, 2.5, 0}; right_3rd.scale = new double[]{0.375, 0.375, 0.375}; PositionData right_first = new PositionData(); right_first.rotation = new double[]{0, 45, 0}; right_first.translation = new double[] {0, 0, 0}; right_first.scale = new double[]{0.4, 0.4, 0.4}; defaultDisplays.put("gui", gui); defaultDisplays.put("ground", ground); defaultDisplays.put("thirdperson_righthand", right_3rd); defaultDisplays.put("firstperson_righthand", right_first); } public BlockCube[] blockCubes = new BlockCube[0]; protected ModelData modelData; protected BlockModel parentModel; public HashMap<String, String> textureMap; public HashMap<String, PositionData> display; public final NamespaceId namespaceId; public BlockModel(NamespaceId namespaceId){ this.namespaceId = namespaceId; refreshModel(); } public void refreshModel(){
this.modelData = ModelHelper.loadBlockModel(namespaceId);
0
2023-11-16 01:10:52+00:00
24k
Shushandr/offroad
src/net/osmand/plus/render/TextRenderer.java
[ { "identifier": "PlatformUtil", "path": "src/net/osmand/PlatformUtil.java", "snippet": "public class PlatformUtil {\n\t\n\tpublic static Log getLog(Class<?> cl){\n\t\treturn LogFactory.getLog(cl);\n\t}\n\t\n\tpublic static XmlPullParser newXMLPullParser() throws XmlPullParserException{\n\t\treturn new o...
import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.geom.Path2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.apache.commons.logging.Log; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.procedure.TIntObjectProcedure; import net.osmand.PlatformUtil; import net.osmand.binary.BinaryMapDataObject; import net.osmand.binary.BinaryMapIndexReader.TagValuePair; import net.osmand.data.QuadRect; import net.osmand.data.QuadTree; import net.osmand.plus.render.OsmandRenderer.RenderingContext; import net.osmand.plus.render.OsmandRenderer.TextInfo; import net.osmand.render.RenderingRuleSearchRequest; import net.osmand.render.RenderingRulesStorage; import net.osmand.util.Algorithms; import net.sf.junidecode.Junidecode; import net.sourceforge.offroad.TextStroke; import net.sourceforge.offroad.ui.ColorUtils;
21,341
float coef = rc.getDensityValue(rc.screenDensityRatio * rc.textScale); BufferedImage ico = RenderingIcons.getIcon(sr, true); if (ico != null) { log.debug("Got shield icon " + sr + ":" + ico.getWidth()+"x" + ico.getHeight()); float left = text.centerX - ico.getWidth() / 2 * coef - 0.5f; float top = text.centerY - ico.getHeight() / 2 * coef - pGraphics2d.getFontMetrics().getDescent() - 0.5f; if(rc.screenDensityRatio != 1f){ Rectangle2D rf = new Rectangle2D.Float(left, top, left + ico.getWidth() * coef, top + ico.getHeight() * coef); Rectangle2D src = new Rectangle2D.Float(0, 0, ico.getWidth(), ico .getHeight()); pGraphics2d.drawImage(ico, (int) rf.getX(), (int) rf.getY(), (int) rf.getMaxX(), (int) rf.getMaxY(), (int) src.getMinX(), (int) src.getMinY(), (int) src.getMaxX(), (int) src.getMaxY(), null); } else { pGraphics2d.drawImage(ico, (int)left, (int)top, null); } } } } private void drawWrappedText(Graphics2D pGraphics2d, TextDrawInfo text, float textSize) { if (text.textWrap == 0) { // set maximum for all text text.textWrap = 40; } if (text.text.length() > text.textWrap) { int start = 0; int end = text.text.length(); int lastSpace = -1; int line = 0; int pos = 0; int limit = 0; while (pos < end) { lastSpace = -1; limit += text.textWrap; while (pos < limit && pos < end) { if (!Character.isLetterOrDigit(text.text.charAt(pos))) { lastSpace = pos; } pos++; } if (lastSpace == -1 || pos == end) { drawTextOnCanvas(pGraphics2d, text.text.substring(start, pos), text.centerX, text.centerY + line * (textSize + 2), text.textShadowColor, text.textShadow); start = pos; } else { drawTextOnCanvas(pGraphics2d, text.text.substring(start, lastSpace), text.centerX, text.centerY + line * (textSize + 2), text.textShadowColor, text.textShadow); start = lastSpace + 1; limit += (start - pos) - 1; } line++; } } else { drawTextOnCanvas(pGraphics2d, text.text, text.centerX, text.centerY, text.textShadowColor, text.textShadow); } } private void createTextDrawInfo(final BinaryMapDataObject o, RenderingRuleSearchRequest render, Graphics2D pGraphics2d, RenderingContext rc, TagValuePair pair, final double xMid, double yMid, Path2D pPath, final Point2D[] points, String name, String tagName) { render.setInitialTagValueZoom(pair.tag, pair.value, rc.zoom, o); render.setIntFilter(render.ALL.R_TEXT_LENGTH, name.length()); render.setStringFilter(render.ALL.R_NAME_TAG, tagName); if(render.search(RenderingRulesStorage.TEXT_RULES)){ if(render.getFloatPropertyValue(render.ALL.R_TEXT_SIZE) > 0){ final TextDrawInfo text = new TextDrawInfo(name); text.fillProperties(rc, render, (float)xMid, (float)yMid); final String tagName2 = render.getStringPropertyValue(render.ALL.R_NAME_TAG2); if (!Algorithms.isEmpty(tagName2)) { o.getObjectNames().forEachEntry(new TIntObjectProcedure<String>() { @Override public boolean execute(int tagid, String nname) { String tagNameN2 = o.getMapIndex().decodeType(tagid).tag; if (tagName2.equals(tagNameN2)) { if (nname != null && nname.trim().length() > 0 && !name.equals(nname)) { text.text += " (" + nname +")"; } return false; } return true; } }); } // paintText.setTextSize(text.textSize); Graphics2D newGraphics = (Graphics2D) pGraphics2d.create(); float textSize = text.textSize * rc.textScale; int fontStyle = 0; if(text.bold && text.italic) { fontStyle = Font.BOLD | Font.ITALIC; } else if(text.bold) { fontStyle = Font.BOLD; } else if(text.italic) { fontStyle = Font.ITALIC; } else { fontStyle = Font.PLAIN; } Font textFont = newGraphics.getFont().deriveFont(fontStyle, textSize); newGraphics.setFont(textFont); FontMetrics metr = newGraphics.getFontMetrics(); int stringWidth = metr.stringWidth(name); int stringHeight = metr.getHeight(); text.bounds = new QuadRect(0, 0, stringWidth, stringHeight); text.bounds.inset(-rc.getDensityValue(3), -rc.getDensityValue(10)); boolean display = true; if(pPath != null) { text.drawOnPath = pPath; display = calculatePathToRotate(rc, text, points, render.getIntPropertyValue(render.ALL.R_TEXT_ON_PATH, 0) != 0); } if(text.drawOnPath == null) { text.bounds.offset(text.centerX, text.centerY); // shift to match alignment text.bounds.offset(-text.bounds.width()/2, - text.bounds.height()/2); } else { text.bounds.offset(text.centerX - text.bounds.width()/2, text.centerY - text.bounds.height()/2); } if(display) {
package net.osmand.plus.render; public class TextRenderer { private static final int MINIMAL_DISTANCE_BETWEEN_SHIELDS_IN_PIXEL = 200; private final static Log log = PlatformUtil.getLog(TextRenderer.class); // private Paint paintText; // private Paint paintIcon; // private Typeface defaultTypeface; // private Typeface boldItalicTypeface; // private Typeface italicTypeface; // private Typeface boldTypeface; static class TextDrawInfo { public TextDrawInfo(String text) { this.text = text; } String text = null; Path2D drawOnPath = null; QuadRect bounds = null; float vOffset = 0; float centerX = 0; float pathRotate = 0; float centerY = 0; float textSize = 0; float minDistance = 0; int textColor = Color.BLACK.getRGB(); int textShadow = 0; int textWrap = 0; boolean bold = false; boolean italic = false; String shieldRes = null; String shieldResIcon = null; int textOrder = 100; int textShadowColor = Color.WHITE.getRGB(); public void fillProperties(RenderingContext rc, RenderingRuleSearchRequest render, float centerX, float centerY) { this.centerX = centerX; // used only for draw on path where centerY doesn't play role this.vOffset = (int) rc.getComplexValue(render, render.ALL.R_TEXT_DY); this.centerY = centerY + this.vOffset; textColor = render.getIntPropertyValue(render.ALL.R_TEXT_COLOR); if (textColor == 0) { textColor = Color.BLACK.getRGB(); } textSize = rc.getComplexValue(render, render.ALL.R_TEXT_SIZE) ; textShadow = (int) rc.getComplexValue(render, render.ALL.R_TEXT_HALO_RADIUS); textShadowColor = render.getIntPropertyValue(render.ALL.R_TEXT_HALO_COLOR); if(textShadowColor == 0) { textShadowColor = Color.WHITE.getRGB(); } textWrap = (int) rc.getComplexValue(render, render.ALL.R_TEXT_WRAP_WIDTH); bold = render.getIntPropertyValue(render.ALL.R_TEXT_BOLD, 0) > 0; italic = render.getIntPropertyValue(render.ALL.R_TEXT_ITALIC, 0) > 0; minDistance = rc.getComplexValue(render, render.ALL.R_TEXT_MIN_DISTANCE); if (render.isSpecified(render.ALL.R_TEXT_SHIELD)) { shieldRes = render.getStringPropertyValue(render.ALL.R_TEXT_SHIELD); } if (render.isSpecified(render.ALL.R_ICON)) { shieldResIcon = render.getStringPropertyValue(render.ALL.R_ICON); } textOrder = render.getIntPropertyValue(render.ALL.R_TEXT_ORDER, 100); } } public TextRenderer() { // paintText = new Paint(); // paintText.setStyle(Style.FILL); // paintText.setStrokeWidth(1); // paintText.setColor(Color.BLACK); // paintText.setTextAlign(Align.CENTER); // defaultTypeface = Typeface.create("Droid Serif", Typeface.NORMAL); // boldItalicTypeface = Typeface.create("Droid Serif", Typeface.BOLD_ITALIC); // italicTypeface = Typeface.create("Droid Serif", Typeface.ITALIC); // boldTypeface = Typeface.create("Droid Serif", Typeface.BOLD); // paintText.setTypeface(defaultTypeface); //$NON-NLS-1$ // paintText.setAntiAlias(true); // // paintIcon = new Paint(); // paintIcon.setStyle(Style.STROKE); } private double sqr(double a) { return a * a; } private double fsqr(double pD) { return pD * pD; } boolean intersects(QuadRect tRect, float tRot, QuadRect sRect, float sRot) { if (Math.abs(tRot) < Math.PI / 15 && Math.abs(sRot) < Math.PI / 15) { return QuadRect.intersects(tRect, sRect); } double dist = Math.sqrt(sqr(tRect.centerX() - sRect.centerX()) + sqr(tRect.centerY() - sRect.centerY())); if (dist < MINIMAL_DISTANCE_BETWEEN_SHIELDS_IN_PIXEL) { return true; } // difference close to 90/270 degrees if (Math.abs(Math.cos(tRot - sRot)) < 0.3) { // rotate one rectangle to 90 degrees tRot += Math.PI / 2; double l = tRect.centerX() - tRect.height() / 2; double t = tRect.centerY() - tRect.width() / 2; tRect = new QuadRect(l, t, l + tRect.height(), t + tRect.width()); } // determine difference close to 180/0 degrees if (Math.abs(Math.sin(tRot - sRot)) < 0.3) { // rotate t box // (calculate offset for t center suppose we rotate around s center) float diff = (float) (-Math.atan2(tRect.centerX() - sRect.centerX(), tRect.centerY() - sRect.centerY()) + Math.PI / 2); diff -= sRot; double left = sRect.centerX() + dist * Math.cos(diff) - tRect.width() / 2; double top = sRect.centerY() - dist * Math.sin(diff) - tRect.height() / 2; QuadRect nRect = new QuadRect(left, top, left + tRect.width(), top + tRect.height()); return QuadRect.intersects(nRect, sRect); } // TODO other cases not covered return QuadRect.intersects(tRect, sRect); } void drawTestBox(Graphics2D pGraphics2d, Rectangle2D r, float rot, String text) { Graphics2D newGraphics = (Graphics2D) pGraphics2d.create(); // cv.save(); newGraphics.translate(r.getCenterX(), r.getCenterY()); newGraphics.rotate((float) (rot * 180 / Math.PI)); Rectangle2D rs = new Rectangle2D.Double(-r.getWidth() / 2, -r.getHeight() / 2, r.getWidth() / 2, r.getHeight() / 2); newGraphics.drawRect((int)rs.getX(), (int)rs.getY(), (int)rs.getWidth(), (int)rs.getHeight()); if (text != null) { // paintText.setTextSize(paintText.getTextSize() - 4); // System.out.println("Text " + text+ "; c=( " + rs.getCenterX() + ", " + rs.getCenterY() + ")"); newGraphics.drawString(text, (int)rs.getCenterX(), (int)rs.getCenterY()); // paintText.setTextSize(paintText.getTextSize() + 4); } // cv.restore(); newGraphics.dispose(); } List<TextDrawInfo> tempSearch = new ArrayList<TextDrawInfo>(); private boolean findTextIntersection(Graphics2D pGraphics2d, RenderingContext rc, QuadTree<TextDrawInfo> boundIntersections, TextDrawInfo text) { // for test purposes // drawTestBox(cv, text.bounds, text.pathRotate, text.text); boundIntersections.queryInBox(text.bounds, tempSearch); for (int i = 0; i < tempSearch.size(); i++) { TextDrawInfo t = tempSearch.get(i); if (intersects(text.bounds, text.pathRotate, t.bounds, t.pathRotate)) { return true; } } if (text.minDistance > 0) { QuadRect boundsSearch = new QuadRect(text.bounds); boundsSearch.inset(-Math.max(rc.getDensityValue(5.0f), text.minDistance), -rc.getDensityValue(15)); boundIntersections.queryInBox(boundsSearch, tempSearch); // drawTestBox(cv, &boundsSearch, text.pathRotate, paintIcon, text.text, NULL/*paintText*/); for (int i = 0; i < tempSearch.size(); i++) { TextDrawInfo t = tempSearch.get(i); if (t.minDistance > 0 && t.text.equals(text.text) && intersects(boundsSearch, text.pathRotate, t.bounds, t.pathRotate)) { return true; } } } boundIntersections.insert(text, text.bounds); return false; } private void drawTextOnCanvas(Graphics2D pGraphics2d, String text, float centerX, float centerY, int shadowColor, float textShadow) { Graphics2D newGraphics = (Graphics2D) pGraphics2d.create(); centerX -= newGraphics.getFontMetrics().stringWidth(text)/2; if (textShadow > 0) { Color c = newGraphics.getColor(); // paintText.setStyle(Style.STROKE); newGraphics.setColor(createColor(shadowColor)); newGraphics.setStroke(new BasicStroke(2 + textShadow)); newGraphics.drawString(text, centerX, centerY); // reset newGraphics.setStroke(new BasicStroke(2f)); // paintText.setStrokeWidth(2); // paintText.setStyle(Style.FILL); // paintText.setColor(c); newGraphics.setColor(c); } newGraphics.drawString(text, centerX, centerY); newGraphics.dispose(); } public void drawTextOverCanvas(RenderingContext rc, Graphics2D pGraphics2d, String preferredLocale) { int size = rc.textToDraw.size(); Graphics2D newGraphics = (Graphics2D) pGraphics2d.create(); // 1. Sort text using text order Collections.sort(rc.textToDraw, new Comparator<TextDrawInfo>() { @Override public int compare(TextDrawInfo object1, TextDrawInfo object2) { return object1.textOrder - object2.textOrder; } }); QuadRect r = new QuadRect(0, 0, rc.width, rc.height); r.inset(-100, -100); QuadTree<TextDrawInfo> nonIntersectedBounds = new QuadTree<TextDrawInfo>(r, 4, 0.6f); for (int i = 0; i < size; i++) { TextDrawInfo text = rc.textToDraw.get(i); if (text.text != null && text.text.length() > 0) { if (preferredLocale.length() > 0) { text.text = Junidecode.unidecode(text.text); } // sest text size before finding intersection (it is used there) float textSize = text.textSize * rc.textScale; int fontStyle = 0; if(text.bold && text.italic) { fontStyle = Font.BOLD | Font.ITALIC; } else if(text.bold) { fontStyle = Font.BOLD; } else if(text.italic) { fontStyle = Font.ITALIC; } else { fontStyle = Font.PLAIN; } Font textFont = newGraphics.getFont().deriveFont(fontStyle, textSize); newGraphics.setFont(textFont); // paintText.setFakeBoldText(text.bold); newGraphics.setColor(createColor(text.textColor)); // align center y FontMetrics metr = newGraphics.getFontMetrics(); text.centerY += - metr.getAscent(); // calculate if there is intersection boolean intersects = findTextIntersection(newGraphics, rc, nonIntersectedBounds, text); if (!intersects) { if (text.drawOnPath != null) { float vOffset = text.vOffset - ( metr.getAscent()/2 + metr.getDescent()); if (text.textShadow > 0) { newGraphics.setColor(createColor(text.textShadowColor)); newGraphics.setStroke(new TextStroke(text.text, textFont, false, false, -vOffset)); newGraphics.draw(text.drawOnPath); } newGraphics.setColor(createColor(text.textColor)); newGraphics.setStroke(new TextStroke(text.text, textFont, false, false, -vOffset)); newGraphics.draw(text.drawOnPath); newGraphics.setStroke(new BasicStroke(0f)); } else { drawShieldIcon(rc, newGraphics, text, text.shieldRes); drawShieldIcon(rc, newGraphics, text, text.shieldResIcon); drawWrappedText(newGraphics, text, textSize); } } } } newGraphics.dispose(); } public Color createColor(int colorInt) { return ColorUtils.create(colorInt); } private void drawShieldIcon(RenderingContext rc, Graphics2D pGraphics2d, TextDrawInfo text, String sr) { if (sr != null) { float coef = rc.getDensityValue(rc.screenDensityRatio * rc.textScale); BufferedImage ico = RenderingIcons.getIcon(sr, true); if (ico != null) { log.debug("Got shield icon " + sr + ":" + ico.getWidth()+"x" + ico.getHeight()); float left = text.centerX - ico.getWidth() / 2 * coef - 0.5f; float top = text.centerY - ico.getHeight() / 2 * coef - pGraphics2d.getFontMetrics().getDescent() - 0.5f; if(rc.screenDensityRatio != 1f){ Rectangle2D rf = new Rectangle2D.Float(left, top, left + ico.getWidth() * coef, top + ico.getHeight() * coef); Rectangle2D src = new Rectangle2D.Float(0, 0, ico.getWidth(), ico .getHeight()); pGraphics2d.drawImage(ico, (int) rf.getX(), (int) rf.getY(), (int) rf.getMaxX(), (int) rf.getMaxY(), (int) src.getMinX(), (int) src.getMinY(), (int) src.getMaxX(), (int) src.getMaxY(), null); } else { pGraphics2d.drawImage(ico, (int)left, (int)top, null); } } } } private void drawWrappedText(Graphics2D pGraphics2d, TextDrawInfo text, float textSize) { if (text.textWrap == 0) { // set maximum for all text text.textWrap = 40; } if (text.text.length() > text.textWrap) { int start = 0; int end = text.text.length(); int lastSpace = -1; int line = 0; int pos = 0; int limit = 0; while (pos < end) { lastSpace = -1; limit += text.textWrap; while (pos < limit && pos < end) { if (!Character.isLetterOrDigit(text.text.charAt(pos))) { lastSpace = pos; } pos++; } if (lastSpace == -1 || pos == end) { drawTextOnCanvas(pGraphics2d, text.text.substring(start, pos), text.centerX, text.centerY + line * (textSize + 2), text.textShadowColor, text.textShadow); start = pos; } else { drawTextOnCanvas(pGraphics2d, text.text.substring(start, lastSpace), text.centerX, text.centerY + line * (textSize + 2), text.textShadowColor, text.textShadow); start = lastSpace + 1; limit += (start - pos) - 1; } line++; } } else { drawTextOnCanvas(pGraphics2d, text.text, text.centerX, text.centerY, text.textShadowColor, text.textShadow); } } private void createTextDrawInfo(final BinaryMapDataObject o, RenderingRuleSearchRequest render, Graphics2D pGraphics2d, RenderingContext rc, TagValuePair pair, final double xMid, double yMid, Path2D pPath, final Point2D[] points, String name, String tagName) { render.setInitialTagValueZoom(pair.tag, pair.value, rc.zoom, o); render.setIntFilter(render.ALL.R_TEXT_LENGTH, name.length()); render.setStringFilter(render.ALL.R_NAME_TAG, tagName); if(render.search(RenderingRulesStorage.TEXT_RULES)){ if(render.getFloatPropertyValue(render.ALL.R_TEXT_SIZE) > 0){ final TextDrawInfo text = new TextDrawInfo(name); text.fillProperties(rc, render, (float)xMid, (float)yMid); final String tagName2 = render.getStringPropertyValue(render.ALL.R_NAME_TAG2); if (!Algorithms.isEmpty(tagName2)) { o.getObjectNames().forEachEntry(new TIntObjectProcedure<String>() { @Override public boolean execute(int tagid, String nname) { String tagNameN2 = o.getMapIndex().decodeType(tagid).tag; if (tagName2.equals(tagNameN2)) { if (nname != null && nname.trim().length() > 0 && !name.equals(nname)) { text.text += " (" + nname +")"; } return false; } return true; } }); } // paintText.setTextSize(text.textSize); Graphics2D newGraphics = (Graphics2D) pGraphics2d.create(); float textSize = text.textSize * rc.textScale; int fontStyle = 0; if(text.bold && text.italic) { fontStyle = Font.BOLD | Font.ITALIC; } else if(text.bold) { fontStyle = Font.BOLD; } else if(text.italic) { fontStyle = Font.ITALIC; } else { fontStyle = Font.PLAIN; } Font textFont = newGraphics.getFont().deriveFont(fontStyle, textSize); newGraphics.setFont(textFont); FontMetrics metr = newGraphics.getFontMetrics(); int stringWidth = metr.stringWidth(name); int stringHeight = metr.getHeight(); text.bounds = new QuadRect(0, 0, stringWidth, stringHeight); text.bounds.inset(-rc.getDensityValue(3), -rc.getDensityValue(10)); boolean display = true; if(pPath != null) { text.drawOnPath = pPath; display = calculatePathToRotate(rc, text, points, render.getIntPropertyValue(render.ALL.R_TEXT_ON_PATH, 0) != 0); } if(text.drawOnPath == null) { text.bounds.offset(text.centerX, text.centerY); // shift to match alignment text.bounds.offset(-text.bounds.width()/2, - text.bounds.height()/2); } else { text.bounds.offset(text.centerX - text.bounds.width()/2, text.centerY - text.bounds.height()/2); } if(display) {
TextInfo info = new TextInfo();
6
2023-11-15 05:04:55+00:00
24k
WuKongOpenSource/Wukong_HRM
common/common-log/src/main/java/com/kakarote/common/log/aspect/OperateLogAspect.java
[ { "identifier": "OperateLogEntity", "path": "common/common-log/src/main/java/com/kakarote/common/log/entity/OperateLogEntity.java", "snippet": "public final class OperateLogEntity {\n private OperateLogEntity() {\n }\n\n public static void registerAllExtensions(\n com.google.protobuf...
import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.extra.servlet.ServletUtil; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.kakarote.common.entity.UserInfo; import com.kakarote.common.log.annotation.OperateLog; import com.kakarote.common.log.entity.OperateLogEntity; import com.kakarote.common.log.entity.OperationLog; import com.kakarote.common.log.entity.OperationResult; import com.kakarote.common.log.enums.BehaviorEnum; import com.kakarote.common.log.enums.OperateTypeEnum; import com.kakarote.common.log.service.OperateLogSaveService; import com.kakarote.common.utils.UserUtil; import com.kakarote.core.common.Result; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.Ordered; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional;
18,915
package com.kakarote.common.log.aspect; /** * user注入切面 */ @Aspect @Component @Slf4j public class OperateLogAspect implements Ordered { @Autowired
package com.kakarote.common.log.aspect; /** * user注入切面 */ @Aspect @Component @Slf4j public class OperateLogAspect implements Ordered { @Autowired
private OperateLogSaveService logSaveService;
5
2023-10-17 05:49:52+00:00
24k
ballerina-platform/module-ballerinax-copybook
commons/src/main/java/io/ballerina/lib/copybook/commons/schema/SchemaBuilder.java
[ { "identifier": "CopybookVisitor", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/generated/CopybookVisitor.java", "snippet": "public interface CopybookVisitor<T> extends ParseTreeVisitor<T> {\n\t/**\n\t * Visit a parse tree produced by {@link CopybookParser#startRule}.\n\t * @param ct...
import io.ballerina.lib.copybook.commons.generated.CopybookVisitor; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.RuleNode; import org.antlr.v4.runtime.tree.TerminalNode; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.BooleanLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.CicsDfhRespLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.CicsDfhValueLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.CobolWordContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.ConditionNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataBlankWhenZeroClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryClausesContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryFormat1Context; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryFormat2Context; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryFormat3Context; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataExternalClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataGlobalClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataJustifiedClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataOccursClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataOccursSortContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataOccursToContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataPictureClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataRedefinesClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataRenamesClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataSignClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataSynchronizedClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataUsageClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueIntervalContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueIntervalFromContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueIntervalToContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.FigurativeConstantContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.IdentifierContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.IndexNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.IntegerLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.LiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.NumericLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.PictureCardinalityContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.PictureCharsContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.PictureStringContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.QualifiedDataNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.StartRuleContext;
19,391
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. 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 io.ballerina.lib.copybook.commons.schema; class SchemaBuilder implements CopybookVisitor<CopybookNode> { private final Schema schema = new Schema(); private GroupItem possibleParent; private final Set<String> redefinedItemNames = new HashSet<>(); private final List<String> errors = new ArrayList<>(); Schema getSchema() { return this.schema; } @Override public CopybookNode visitStartRule(StartRuleContext ctx) { this.possibleParent = null; visitDataDescription(ctx.dataDescription()); for (CopybookNode typedef : this.schema.getTypeDefinitions()) { addRedefinedItems(typedef); } this.schema.addErrors(this.errors); return null; } private void addRedefinedItems(CopybookNode item) { if (this.redefinedItemNames.contains(item.getName())) { this.schema.addRedefinedItem(item); return; } if (item instanceof GroupItem groupItem) { groupItem.getChildren().forEach(this::addRedefinedItems); } } @Override public CopybookNode visitDataDescription(DataDescriptionContext ctx) { for (int i = 0; i < ctx.getChildCount(); i++) { CopybookNode copybookNode = visitDataDescriptionEntry(ctx.dataDescriptionEntry(i)); if (copybookNode instanceof GroupItem groupItem) { this.possibleParent = groupItem; } if (isRootLevelNode(copybookNode)) { this.schema.addTypeDefinition(copybookNode); } } return null; } private boolean isRootLevelNode(CopybookNode copybookNode) { return copybookNode != null && copybookNode.getLevel() == 1; } @Override public CopybookNode visitDataDescriptionEntry(DataDescriptionEntryContext ctx) { if (ctx.dataDescriptionEntryFormat1() != null) { return visitDataDescriptionEntryFormat1(ctx.dataDescriptionEntryFormat1()); } // skipping level 66 and 88 return null; } @Override public CopybookNode visitDataDescriptionEntryFormat1(DataDescriptionEntryFormat1Context ctx) { if (ctx.LEVEL_NUMBER_77() != null) { // skipping level 77 return null; } boolean redefines = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0) != null; String redefinedItemName = null; if (redefines) { redefinedItemName = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0).dataName().getText(); this.redefinedItemNames.add(redefinedItemName); } int level = Integer.parseInt(ctx.INTEGERLITERAL().getText()); String name = ctx.dataName() != null ? ctx.dataName().getText() : ctx.FILLER().getText(); DataPictureClauseContext pictureClause = ctx.dataDescriptionEntryClauses().dataPictureClause(0);
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. 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 io.ballerina.lib.copybook.commons.schema; class SchemaBuilder implements CopybookVisitor<CopybookNode> { private final Schema schema = new Schema(); private GroupItem possibleParent; private final Set<String> redefinedItemNames = new HashSet<>(); private final List<String> errors = new ArrayList<>(); Schema getSchema() { return this.schema; } @Override public CopybookNode visitStartRule(StartRuleContext ctx) { this.possibleParent = null; visitDataDescription(ctx.dataDescription()); for (CopybookNode typedef : this.schema.getTypeDefinitions()) { addRedefinedItems(typedef); } this.schema.addErrors(this.errors); return null; } private void addRedefinedItems(CopybookNode item) { if (this.redefinedItemNames.contains(item.getName())) { this.schema.addRedefinedItem(item); return; } if (item instanceof GroupItem groupItem) { groupItem.getChildren().forEach(this::addRedefinedItems); } } @Override public CopybookNode visitDataDescription(DataDescriptionContext ctx) { for (int i = 0; i < ctx.getChildCount(); i++) { CopybookNode copybookNode = visitDataDescriptionEntry(ctx.dataDescriptionEntry(i)); if (copybookNode instanceof GroupItem groupItem) { this.possibleParent = groupItem; } if (isRootLevelNode(copybookNode)) { this.schema.addTypeDefinition(copybookNode); } } return null; } private boolean isRootLevelNode(CopybookNode copybookNode) { return copybookNode != null && copybookNode.getLevel() == 1; } @Override public CopybookNode visitDataDescriptionEntry(DataDescriptionEntryContext ctx) { if (ctx.dataDescriptionEntryFormat1() != null) { return visitDataDescriptionEntryFormat1(ctx.dataDescriptionEntryFormat1()); } // skipping level 66 and 88 return null; } @Override public CopybookNode visitDataDescriptionEntryFormat1(DataDescriptionEntryFormat1Context ctx) { if (ctx.LEVEL_NUMBER_77() != null) { // skipping level 77 return null; } boolean redefines = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0) != null; String redefinedItemName = null; if (redefines) { redefinedItemName = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0).dataName().getText(); this.redefinedItemNames.add(redefinedItemName); } int level = Integer.parseInt(ctx.INTEGERLITERAL().getText()); String name = ctx.dataName() != null ? ctx.dataName().getText() : ctx.FILLER().getText(); DataPictureClauseContext pictureClause = ctx.dataDescriptionEntryClauses().dataPictureClause(0);
DataOccursClauseContext occursClause = ctx.dataDescriptionEntryClauses().dataOccursClause(0);
17
2023-10-24 04:51:53+00:00
24k
Nxer/Twist-Space-Technology-Mod
src/main/java/com/Nxer/TwistSpaceTechnology/common/block/BlockRegister.java
[ { "identifier": "BasicBlocks", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/BasicBlocks.java", "snippet": "public class BasicBlocks {\n\n public static final Block MetaBlock01 = new BlockBase01(\"MetaBlock01\", \"MetaBlock01\");\n public static final Block PhotonControllerUpgr...
import static com.Nxer.TwistSpaceTechnology.common.block.BasicBlocks.*; import static com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.BlockNuclearReactor.NuclearReactorBlockMeta; import com.Nxer.TwistSpaceTechnology.common.GTCMItemList; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.BlockStar; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.BlockNuclearReactor; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.PhotonControllerUpgradeCasing; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.PhotonControllerUpgradeCasingItemBlock; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationAntiGravityCasing; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationAntiGravityCasingItemBlock; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationStructureCasing; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationStructureCasingItemBlock; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.ItemBlockBase01; import com.Nxer.TwistSpaceTechnology.common.tile.TileStar; import com.Nxer.TwistSpaceTechnology.config.Config; import cpw.mods.fml.common.registry.GameRegistry;
18,723
package com.Nxer.TwistSpaceTechnology.common.block; public class BlockRegister { public static void registryBlocks() {
package com.Nxer.TwistSpaceTechnology.common.block; public class BlockRegister { public static void registryBlocks() {
GameRegistry.registerBlock(MetaBlock01, ItemBlockBase01.class, MetaBlock01.getUnlocalizedName());
11
2023-10-16 09:57:15+00:00
24k
wyjsonGo/GoRouter
GoRouter-Api/src/main/java/com/wyjson/router/GoRouter.java
[ { "identifier": "GoCallback", "path": "GoRouter-Api/src/main/java/com/wyjson/router/callback/GoCallback.java", "snippet": "public interface GoCallback {\n\n /**\n * 当找到目的地的回调\n *\n * @param card\n */\n void onFound(Card card);\n\n /**\n * 迷路后的回调。\n *\n * @param card\...
import android.annotation.SuppressLint; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.widget.Toast; import androidx.activity.result.ActivityResultLauncher; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.core.app.ActivityOptionsCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.Observer; import com.wyjson.router.callback.GoCallback; import com.wyjson.router.callback.InterceptorCallback; import com.wyjson.router.core.ApplicationModuleCenter; import com.wyjson.router.core.EventCenter; import com.wyjson.router.core.InterceptorCenter; import com.wyjson.router.core.InterceptorServiceImpl; import com.wyjson.router.core.RouteCenter; import com.wyjson.router.core.RouteModuleCenter; import com.wyjson.router.core.ServiceCenter; import com.wyjson.router.core.interfaces.IInterceptorService; import com.wyjson.router.exception.NoFoundRouteException; import com.wyjson.router.exception.ParamException; import com.wyjson.router.exception.RouterException; import com.wyjson.router.interfaces.IApplicationModule; import com.wyjson.router.interfaces.IDegradeService; import com.wyjson.router.interfaces.IInterceptor; import com.wyjson.router.interfaces.IPretreatmentService; import com.wyjson.router.interfaces.IService; import com.wyjson.router.logger.DefaultLogger; import com.wyjson.router.logger.ILogger; import com.wyjson.router.model.Card; import com.wyjson.router.module.interfaces.IRouteModuleGroup; import com.wyjson.router.thread.DefaultPoolExecutor; import com.wyjson.router.utils.TextUtils; import java.util.concurrent.ThreadPoolExecutor;
16,606
} @Deprecated public void injectCheck(Fragment fragment, Bundle bundle) throws ParamException { inject(fragment, null, bundle, true); } @Deprecated private <T> void inject(T target, Intent intent, Bundle bundle, boolean isCheck) throws ParamException { RouteCenter.inject(target, intent, bundle, isCheck); } @Nullable public Object go(Context context, Card card, int requestCode, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) { card.setContext(context == null ? mApplication : context); card.setInterceptorException(null); logger.debug(null, "[go] " + card); IPretreatmentService pretreatmentService = getService(IPretreatmentService.class); if (pretreatmentService != null) { if (!pretreatmentService.onPretreatment(card.getContext(), card)) { // 预处理失败,导航取消 logger.debug(null, "[go] IPretreatmentService Failure!"); return null; } } else { logger.warning(null, "[go] This [IPretreatmentService] was not found!"); } try { RouteCenter.assembleRouteCard(card); } catch (NoFoundRouteException e) { logger.warning(null, e.getMessage()); if (isDebug()) { runInMainThread(() -> Toast.makeText(card.getContext(), "There's no route matched!\n" + " Path = [" + card.getPath() + "]\n" + " Group = [" + card.getGroup() + "]", Toast.LENGTH_LONG).show()); } onLost(card.getContext(), card, callback); return null; } runInMainThread(() -> { logger.debug(null, "[go] [onFound] " + card); if (callback != null) { callback.onFound(card); } }); if (isDebug() && card.isDeprecated()) { logger.warning(null, "[go] This page has been marked as deprecated. path[" + card.getPath() + "]"); runInMainThread(() -> Toast.makeText(card.getContext(), "This page has been marked as deprecated!\n" + " Path = [" + card.getPath() + "]\n" + " Group = [" + card.getGroup() + "]", Toast.LENGTH_SHORT).show()); } switch (card.getType()) { case ACTIVITY: IInterceptorService interceptorService = getService(IInterceptorService.class); if (interceptorService != null && !card.isGreenChannel()) { interceptorService.doInterceptions(card, new InterceptorCallback() { @Override public void onContinue(Card card) { goActivity(card.getContext(), card, requestCode, activityResultLauncher, callback); } @Override public void onInterrupt(Card card, @NonNull Throwable exception) { runInMainThread(() -> { if (callback != null) { callback.onInterrupt(card, exception); } }); } }); } else { goActivity(card.getContext(), card, requestCode, activityResultLauncher, callback); } break; case FRAGMENT: return goFragment(card, callback); } return null; } private void onLost(Context context, Card card, GoCallback callback) { runInMainThread(() -> { logger.error(null, "[onLost] There is no route. path[" + card.getPath() + "]"); if (callback != null) { callback.onLost(card); } else { IDegradeService degradeService = getService(IDegradeService.class); if (degradeService != null) { degradeService.onLost(context, card); } else { logger.warning(null, "[onLost] This [IDegradeService] was not found!"); } } }); } @SuppressLint("WrongConstant") private void goActivity(Context context, Card card, int requestCode, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) { Intent intent = new Intent(context, card.getPathClass()); intent.putExtras(card.getExtras()); int flags = card.getFlags(); if (0 != flags) { intent.setFlags(flags); } if (!(context instanceof Activity)) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } String action = card.getAction();
package com.wyjson.router; public final class GoRouter { private final Handler mHandler = new Handler(Looper.getMainLooper()); private volatile static ThreadPoolExecutor executor = DefaultPoolExecutor.getInstance(); public static ILogger logger = new DefaultLogger(); private volatile static boolean isDebug = false; private static Application mApplication; private GoRouter() { InterceptorCenter.clearInterceptors(); ServiceCenter.addService(InterceptorServiceImpl.class); } private static class InstanceHolder { private static final GoRouter mInstance = new GoRouter(); } public static GoRouter getInstance() { return InstanceHolder.mInstance; } /** * 自动加载模块路由 * * @param application */ public static synchronized void autoLoadRouteModule(Application application) { setApplication(application); logger.info(null, "[GoRouter] autoLoadRouteModule!"); RouteModuleCenter.load(application); } /** * 获取路由注册模式 * * @return true [GoRouter-Gradle-Plugin] ,false [scan dex file] */ public boolean isRouteRegisterMode() { return RouteModuleCenter.isRegisterByPlugin(); } public static synchronized void openDebug() { isDebug = true; logger.showLog(isDebug); logger.info(null, "[openDebug]"); } public static void setApplication(Application application) { mApplication = application; } public static boolean isDebug() { return isDebug; } public static synchronized void printStackTrace() { logger.showStackTrace(true); logger.info(null, "[printStackTrace]"); } public static synchronized void setExecutor(ThreadPoolExecutor tpe) { executor = tpe; } public ThreadPoolExecutor getExecutor() { return executor; } public static void setLogger(ILogger userLogger) { if (userLogger != null) { logger = userLogger; } } /** * 获取模块application注册模式 * * @return true [GoRouter-Gradle-Plugin] ,false [scan dex file] */ public boolean isAMRegisterMode() { return ApplicationModuleCenter.isRegisterByPlugin(); } public static void callAMOnCreate(Application application) { setApplication(application); ApplicationModuleCenter.callOnCreate(application); } public static void callAMOnTerminate() { ApplicationModuleCenter.callOnTerminate(); } public static void callAMOnConfigurationChanged(@NonNull Configuration newConfig) { ApplicationModuleCenter.callOnConfigurationChanged(newConfig); } public static void callAMOnLowMemory() { ApplicationModuleCenter.callOnLowMemory(); } public static void callAMOnTrimMemory(int level) { ApplicationModuleCenter.callOnTrimMemory(level); } /** * 动态注册模块application * * @param am */ public static void registerAM(Class<? extends IApplicationModule> am) { ApplicationModuleCenter.register(am); } /** * 实现相同接口的service会被覆盖(更新) * * @param service 实现类.class */ public void addService(Class<? extends IService> service) { ServiceCenter.addService(service); } /** * 实现相同接口的service会被覆盖(更新) * * @param service 实现类.class * @param alias 别名 */ public void addService(Class<? extends IService> service, String alias) { ServiceCenter.addService(service, alias); } /** * 获取service接口的实现 * * @param service 接口.class * @param <T> * @return */ @Nullable public <T> T getService(Class<? extends T> service) { return ServiceCenter.getService(service); } /** * 获取service接口的实现 * * @param service * @param alias 别名 * @param <T> * @return */ @Nullable public <T> T getService(Class<? extends T> service, String alias) { return ServiceCenter.getService(service, alias); } /** * 重复添加相同序号会catch * * @param ordinal * @param interceptor */ public void addInterceptor(int ordinal, Class<? extends IInterceptor> interceptor) { InterceptorCenter.addInterceptor(ordinal, interceptor, false); } /** * 重复添加相同序号会覆盖(更新) * * @param ordinal * @param interceptor */ public void setInterceptor(int ordinal, Class<? extends IInterceptor> interceptor) { InterceptorCenter.setInterceptor(ordinal, interceptor); } /** * 动态添加路由分组,按需加载路由 */ public void addRouterGroup(String group, IRouteModuleGroup routeModuleGroup) { RouteCenter.addRouterGroup(group, routeModuleGroup); } private void runInMainThread(Runnable runnable) { if (Looper.getMainLooper().getThread() != Thread.currentThread()) { mHandler.post(runnable); } else { runnable.run(); } } public Card build(String path) { return build(path, null); } public Card build(String path, Bundle bundle) { return new Card(path, bundle); } public Card build(Uri uri) { return new Card(uri); } /** * 获取原始的URI * * @param activity */ public String getRawURI(Activity activity) { return RouteCenter.getRawURI(activity); } /** * 获取原始的URI * * @param fragment */ public String getRawURI(Fragment fragment) { return RouteCenter.getRawURI(fragment); } /** * 获取当前页面路径 * * @param activity */ public String getCurrentPath(Activity activity) { return RouteCenter.getCurrentPath(activity); } /** * 获取当前页面路径 * * @param fragment */ public String getCurrentPath(Fragment fragment) { return RouteCenter.getCurrentPath(fragment); } @Deprecated public void inject(Activity activity) { inject(activity, null, null, false); } @Deprecated public void inject(Activity activity, Intent intent) { inject(activity, intent, null, false); } @Deprecated public void inject(Activity activity, Bundle bundle) { inject(activity, null, bundle, false); } @Deprecated public void inject(Fragment fragment) { inject(fragment, null, null, false); } @Deprecated public void inject(Fragment fragment, Intent intent) { inject(fragment, intent, null, false); } @Deprecated public void inject(Fragment fragment, Bundle bundle) { inject(fragment, null, bundle, false); } @Deprecated public void injectCheck(Activity activity) throws ParamException { inject(activity, null, null, true); } @Deprecated public void injectCheck(Activity activity, Intent intent) throws ParamException { inject(activity, intent, null, true); } @Deprecated public void injectCheck(Activity activity, Bundle bundle) throws ParamException { inject(activity, null, bundle, true); } @Deprecated public void injectCheck(Fragment fragment) throws ParamException { inject(fragment, null, null, true); } @Deprecated public void injectCheck(Fragment fragment, Intent intent) throws ParamException { inject(fragment, intent, null, true); } @Deprecated public void injectCheck(Fragment fragment, Bundle bundle) throws ParamException { inject(fragment, null, bundle, true); } @Deprecated private <T> void inject(T target, Intent intent, Bundle bundle, boolean isCheck) throws ParamException { RouteCenter.inject(target, intent, bundle, isCheck); } @Nullable public Object go(Context context, Card card, int requestCode, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) { card.setContext(context == null ? mApplication : context); card.setInterceptorException(null); logger.debug(null, "[go] " + card); IPretreatmentService pretreatmentService = getService(IPretreatmentService.class); if (pretreatmentService != null) { if (!pretreatmentService.onPretreatment(card.getContext(), card)) { // 预处理失败,导航取消 logger.debug(null, "[go] IPretreatmentService Failure!"); return null; } } else { logger.warning(null, "[go] This [IPretreatmentService] was not found!"); } try { RouteCenter.assembleRouteCard(card); } catch (NoFoundRouteException e) { logger.warning(null, e.getMessage()); if (isDebug()) { runInMainThread(() -> Toast.makeText(card.getContext(), "There's no route matched!\n" + " Path = [" + card.getPath() + "]\n" + " Group = [" + card.getGroup() + "]", Toast.LENGTH_LONG).show()); } onLost(card.getContext(), card, callback); return null; } runInMainThread(() -> { logger.debug(null, "[go] [onFound] " + card); if (callback != null) { callback.onFound(card); } }); if (isDebug() && card.isDeprecated()) { logger.warning(null, "[go] This page has been marked as deprecated. path[" + card.getPath() + "]"); runInMainThread(() -> Toast.makeText(card.getContext(), "This page has been marked as deprecated!\n" + " Path = [" + card.getPath() + "]\n" + " Group = [" + card.getGroup() + "]", Toast.LENGTH_SHORT).show()); } switch (card.getType()) { case ACTIVITY: IInterceptorService interceptorService = getService(IInterceptorService.class); if (interceptorService != null && !card.isGreenChannel()) { interceptorService.doInterceptions(card, new InterceptorCallback() { @Override public void onContinue(Card card) { goActivity(card.getContext(), card, requestCode, activityResultLauncher, callback); } @Override public void onInterrupt(Card card, @NonNull Throwable exception) { runInMainThread(() -> { if (callback != null) { callback.onInterrupt(card, exception); } }); } }); } else { goActivity(card.getContext(), card, requestCode, activityResultLauncher, callback); } break; case FRAGMENT: return goFragment(card, callback); } return null; } private void onLost(Context context, Card card, GoCallback callback) { runInMainThread(() -> { logger.error(null, "[onLost] There is no route. path[" + card.getPath() + "]"); if (callback != null) { callback.onLost(card); } else { IDegradeService degradeService = getService(IDegradeService.class); if (degradeService != null) { degradeService.onLost(context, card); } else { logger.warning(null, "[onLost] This [IDegradeService] was not found!"); } } }); } @SuppressLint("WrongConstant") private void goActivity(Context context, Card card, int requestCode, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) { Intent intent = new Intent(context, card.getPathClass()); intent.putExtras(card.getExtras()); int flags = card.getFlags(); if (0 != flags) { intent.setFlags(flags); } if (!(context instanceof Activity)) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } String action = card.getAction();
if (!TextUtils.isEmpty(action)) {
23
2023-10-18 13:52:07+00:00
24k
trpc-group/trpc-java
trpc-core/src/main/java/com/tencent/trpc/core/rpc/def/DefProviderInvoker.java
[ { "identifier": "Constants", "path": "trpc-core/src/main/java/com/tencent/trpc/core/common/Constants.java", "snippet": "public class Constants {\n\n public static final int CPUS = Runtime.getRuntime().availableProcessors();\n public static final String UNKNOWN = \"unknown\";\n public static fin...
import com.google.common.collect.Maps; import com.tencent.trpc.core.common.Constants; import com.tencent.trpc.core.common.config.ProtocolConfig; import com.tencent.trpc.core.common.config.ProviderConfig; import com.tencent.trpc.core.exception.ErrorCode; import com.tencent.trpc.core.exception.TRpcException; import com.tencent.trpc.core.logger.Logger; import com.tencent.trpc.core.logger.LoggerFactory; import com.tencent.trpc.core.rpc.InvokeMode; import com.tencent.trpc.core.rpc.ProviderInvoker; import com.tencent.trpc.core.rpc.Request; import com.tencent.trpc.core.rpc.Response; import com.tencent.trpc.core.rpc.RpcContext; import com.tencent.trpc.core.rpc.RpcContextValueKeys; import com.tencent.trpc.core.rpc.RpcInvocation; import com.tencent.trpc.core.utils.PreconditionUtils; import com.tencent.trpc.core.utils.RpcContextUtils; import com.tencent.trpc.core.utils.RpcUtils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import org.apache.commons.lang3.ArrayUtils;
17,595
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.core.rpc.def; /** * Default provider implementation with method granularity. */ public class DefProviderInvoker<T> implements ProviderInvoker<T> { private static final Logger LOG = LoggerFactory.getLogger(DefProviderInvoker.class); private ProtocolConfig config;
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.core.rpc.def; /** * Default provider implementation with method granularity. */ public class DefProviderInvoker<T> implements ProviderInvoker<T> { private static final Logger LOG = LoggerFactory.getLogger(DefProviderInvoker.class); private ProtocolConfig config;
private ProviderConfig<T> providerConfig;
2
2023-10-19 10:54:11+00:00
24k
eclipse-jgit/jgit
org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/GitFilter.java
[ { "identifier": "ErrorServlet", "path": "org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/glue/ErrorServlet.java", "snippet": "public class ErrorServlet extends HttpServlet {\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate final int status;\n\n\t/**\n\t * Sends a specific s...
import java.io.File; import java.text.MessageFormat; import java.util.LinkedList; import java.util.List; import javax.servlet.Filter; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jgit.http.server.glue.ErrorServlet; import org.eclipse.jgit.http.server.glue.MetaFilter; import org.eclipse.jgit.http.server.glue.RegexGroupFilter; import org.eclipse.jgit.http.server.glue.ServletBinder; import org.eclipse.jgit.http.server.resolver.AsIsFileService; import org.eclipse.jgit.http.server.resolver.DefaultReceivePackFactory; import org.eclipse.jgit.http.server.resolver.DefaultUploadPackFactory; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.transport.resolver.FileResolver; import org.eclipse.jgit.transport.resolver.ReceivePackFactory; import org.eclipse.jgit.transport.resolver.RepositoryResolver; import org.eclipse.jgit.transport.resolver.UploadPackFactory; import org.eclipse.jgit.util.StringUtils;
17,194
/* * Copyright (C) 2009-2010, Google Inc. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.http.server; /** * Handles Git repository access over HTTP. * <p> * Applications embedding this filter should map a directory path within the * application to this filter. For a servlet version, see * {@link org.eclipse.jgit.http.server.GitServlet}. * <p> * Applications may wish to add additional repository action URLs to this * servlet by taking advantage of its extension from * {@link org.eclipse.jgit.http.server.glue.MetaFilter}. Callers may register * their own URL suffix translations through {@link #serve(String)}, or their * regex translations through {@link #serveRegex(String)}. Each translation * should contain a complete filter pipeline which ends with the HttpServlet * that should handle the requested action. */ public class GitFilter extends MetaFilter { private volatile boolean initialized; private RepositoryResolver<HttpServletRequest> resolver; private AsIsFileService asIs = new AsIsFileService(); private UploadPackFactory<HttpServletRequest> uploadPackFactory = new DefaultUploadPackFactory(); private UploadPackErrorHandler uploadPackErrorHandler;
/* * Copyright (C) 2009-2010, Google Inc. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.http.server; /** * Handles Git repository access over HTTP. * <p> * Applications embedding this filter should map a directory path within the * application to this filter. For a servlet version, see * {@link org.eclipse.jgit.http.server.GitServlet}. * <p> * Applications may wish to add additional repository action URLs to this * servlet by taking advantage of its extension from * {@link org.eclipse.jgit.http.server.glue.MetaFilter}. Callers may register * their own URL suffix translations through {@link #serve(String)}, or their * regex translations through {@link #serveRegex(String)}. Each translation * should contain a complete filter pipeline which ends with the HttpServlet * that should handle the requested action. */ public class GitFilter extends MetaFilter { private volatile boolean initialized; private RepositoryResolver<HttpServletRequest> resolver; private AsIsFileService asIs = new AsIsFileService(); private UploadPackFactory<HttpServletRequest> uploadPackFactory = new DefaultUploadPackFactory(); private UploadPackErrorHandler uploadPackErrorHandler;
private ReceivePackFactory<HttpServletRequest> receivePackFactory = new DefaultReceivePackFactory();
5
2023-10-20 15:09:17+00:00
24k
wangqi060934/MyAndroidToolsPro
app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/fragment/ActivityRecyclerListFragment.java
[ { "identifier": "IfwUtil", "path": "app/src/main/java/cn/wq/myandroidtoolspro/helper/IfwUtil.java", "snippet": "public class IfwUtil {\n private static final String TAG = \"IfwUtil\";\n private static final String SYSTEM_PROPERTY_EFS_ENABLED = \"persist.security.efs.enabled\";\n\n public static...
import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SwitchCompat; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import cn.wq.myandroidtoolspro.R; import cn.wq.myandroidtoolspro.helper.IfwUtil; import cn.wq.myandroidtoolspro.helper.Utils; import cn.wq.myandroidtoolspro.model.ComponentEntry; import cn.wq.myandroidtoolspro.model.ComponentModel; import cn.wq.myandroidtoolspro.recyclerview.adapter.AbstractComponentAdapter; import cn.wq.myandroidtoolspro.recyclerview.toolbar.MultiSectionWithToolbarRecyclerFragment; import cn.wq.myandroidtoolspro.recyclerview.multi.MultiSelectableViewHolder; import cn.wq.myandroidtoolspro.recyclerview.multi.MultiSelectionUtils;
21,242
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class ActivityRecyclerListFragment extends MultiSectionWithToolbarRecyclerFragment{ private ActivityAdapter mAdapter; private String packageName; private String launchActivityName; private Context mContext; @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } public static ActivityRecyclerListFragment newInstance(Bundle bundle) { ActivityRecyclerListFragment f = new ActivityRecyclerListFragment(); f.setArguments(bundle); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle data = getArguments(); packageName = data.getString("packageName"); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setToolbarLogo(packageName); launchActivityName=getLaunchActivityName(); } private String getLaunchActivityName() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.setPackage(packageName); ResolveInfo rInfo=mContext.getPackageManager().resolveActivity(intent, 0); if (rInfo != null) { return rInfo.activityInfo.name; } return null; } @Override
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class ActivityRecyclerListFragment extends MultiSectionWithToolbarRecyclerFragment{ private ActivityAdapter mAdapter; private String packageName; private String launchActivityName; private Context mContext; @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } public static ActivityRecyclerListFragment newInstance(Bundle bundle) { ActivityRecyclerListFragment f = new ActivityRecyclerListFragment(); f.setArguments(bundle); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle data = getArguments(); packageName = data.getString("packageName"); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setToolbarLogo(packageName); launchActivityName=getLaunchActivityName(); } private String getLaunchActivityName() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.setPackage(packageName); ResolveInfo rInfo=mContext.getPackageManager().resolveActivity(intent, 0); if (rInfo != null) { return rInfo.activityInfo.name; } return null; } @Override
protected AbstractComponentAdapter<ComponentEntry> generateAdapter() {
2
2023-10-18 14:32:49+00:00
24k
A1anSong/jd_unidbg
unidbg-api/src/main/java/com/github/unidbg/arm/AbstractARMDebugger.java
[ { "identifier": "AssemblyCodeDumper", "path": "unidbg-api/src/main/java/com/github/unidbg/AssemblyCodeDumper.java", "snippet": "public class AssemblyCodeDumper implements CodeHook, TraceHook {\n\n private final Emulator<?> emulator;\n\n public AssemblyCodeDumper(Emulator<?> emulator, long begin, l...
import capstone.api.Instruction; import capstone.api.RegsAccess; import com.github.unidbg.AssemblyCodeDumper; import com.github.unidbg.Emulator; import com.github.unidbg.Family; import com.github.unidbg.Module; import com.github.unidbg.Symbol; import com.github.unidbg.TraceMemoryHook; import com.github.unidbg.Utils; import com.github.unidbg.arm.backend.Backend; import com.github.unidbg.arm.backend.BlockHook; import com.github.unidbg.arm.backend.ReadHook; import com.github.unidbg.arm.backend.UnHook; import com.github.unidbg.arm.backend.WriteHook; import com.github.unidbg.debugger.BreakPoint; import com.github.unidbg.debugger.BreakPointCallback; import com.github.unidbg.debugger.DebugListener; import com.github.unidbg.debugger.DebugRunnable; import com.github.unidbg.debugger.Debugger; import com.github.unidbg.debugger.FunctionCallListener; import com.github.unidbg.memory.MemRegion; import com.github.unidbg.memory.Memory; import com.github.unidbg.memory.MemoryMap; import com.github.unidbg.pointer.UnidbgPointer; import com.github.unidbg.thread.Task; import com.github.unidbg.unix.struct.StdString; import com.github.unidbg.unwind.Unwinder; import com.github.unidbg.utils.Inspector; import com.github.zhkl0228.demumble.DemanglerFactory; import com.github.zhkl0228.demumble.GccDemangler; import com.sun.jna.Pointer; import keystone.Keystone; import keystone.KeystoneEncoded; import keystone.exceptions.AssembleFailedKeystoneException; import org.apache.commons.codec.binary.Hex; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import unicorn.Arm64Const; import unicorn.ArmConst; import unicorn.UnicornConst; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern;
17,631
package com.github.unidbg.arm; public abstract class AbstractARMDebugger implements Debugger { private static final Log log = LogFactory.getLog(AbstractARMDebugger.class); private final Map<Long, BreakPoint> breakMap = new LinkedHashMap<>(); protected final Emulator<?> emulator; protected AbstractARMDebugger(Emulator<?> emulator) { this.emulator = emulator; } private final List<UnHook> unHookList = new ArrayList<>(); @Override public void onAttach(UnHook unHook) { unHookList.add(unHook); } @Override public void detach() { for (Iterator<UnHook> iterator = unHookList.iterator(); iterator.hasNext(); ) { iterator.next().unhook(); iterator.remove(); } } @Override public final BreakPoint addBreakPoint(Module module, String symbol) { Symbol sym = module.findSymbolByName(symbol, false); if (sym == null) { throw new IllegalStateException("find symbol failed: " + symbol); } return addBreakPoint(module, sym.getValue()); } @Override
package com.github.unidbg.arm; public abstract class AbstractARMDebugger implements Debugger { private static final Log log = LogFactory.getLog(AbstractARMDebugger.class); private final Map<Long, BreakPoint> breakMap = new LinkedHashMap<>(); protected final Emulator<?> emulator; protected AbstractARMDebugger(Emulator<?> emulator) { this.emulator = emulator; } private final List<UnHook> unHookList = new ArrayList<>(); @Override public void onAttach(UnHook unHook) { unHookList.add(unHook); } @Override public void detach() { for (Iterator<UnHook> iterator = unHookList.iterator(); iterator.hasNext(); ) { iterator.next().unhook(); iterator.remove(); } } @Override public final BreakPoint addBreakPoint(Module module, String symbol) { Symbol sym = module.findSymbolByName(symbol, false); if (sym == null) { throw new IllegalStateException("find symbol failed: " + symbol); } return addBreakPoint(module, sym.getValue()); } @Override
public final BreakPoint addBreakPoint(Module module, String symbol, BreakPointCallback callback) {
13
2023-10-17 06:13:28+00:00
24k
robaho/httpserver
src/test/java/jdk/test/lib/process/ProcessTools.java
[ { "identifier": "JDKToolFinder", "path": "src/test/java/jdk/test/lib/JDKToolFinder.java", "snippet": "public final class JDKToolFinder {\n\n private JDKToolFinder() {\n }\n\n /**\n * Returns the full path to an executable in jdk/bin based on System\n * property {@code test.jdk} or {@cod...
import jdk.test.lib.JDKToolFinder; import jdk.test.lib.Platform; import jdk.test.lib.Utils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.lang.Thread.State; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors;
14,822
} } catch (TimeoutException e) { // continue execution, so wait() give a chance to write } catch (InterruptedException | ExecutionException e) { return -1; } } try { wait(1); } catch (InterruptedException ie) { return -1; } } return this.buf[current++]; } } private static class BufferInputStream extends InputStream { private final BufferOutputStream buffer; public BufferInputStream(Process p) { buffer = new BufferOutputStream(p); } BufferOutputStream getOutputStream() { return buffer; } @Override public int read() throws IOException { return buffer.readNext(); } } /** * <p>Starts a process from its builder.</p> * <span>The default redirects of STDOUT and STDERR are started</span> * <p> * It is possible to wait for the process to get to a warmed-up state * via {@linkplain Predicate} condition on the STDOUT/STDERR and monitor the * in-streams via the provided {@linkplain Consumer} * </p> * * @param name The process name * @param processBuilder The process builder * @param lineConsumer The {@linkplain Consumer} the lines will be forwarded to * @param linePredicate The {@linkplain Predicate} to use on the STDOUT and STDERR. * Used to determine the moment the target app is * properly warmed-up. * It can be null - in that case the warmup is skipped. * @param timeout The timeout for the warmup waiting; -1 = no wait; 0 = wait forever * @param unit The timeout {@linkplain TimeUnit} * @return Returns the initialized {@linkplain Process} * @throws IOException * @throws InterruptedException * @throws TimeoutException */ public static Process startProcess(String name, ProcessBuilder processBuilder, final Consumer<String> lineConsumer, final Predicate<String> linePredicate, long timeout, TimeUnit unit) throws IOException, InterruptedException, TimeoutException { System.out.println("[" + name + "]:" + String.join(" ", processBuilder.command())); Process p = privilegedStart(processBuilder); StreamPumper stdout = new StreamPumper(p.getInputStream()); StreamPumper stderr = new StreamPumper(p.getErrorStream()); stdout.addPump(new LineForwarder(name, System.out)); stderr.addPump(new LineForwarder(name, System.err)); BufferInputStream stdOut = new BufferInputStream(p); BufferInputStream stdErr = new BufferInputStream(p); stdout.addOutputStream(stdOut.getOutputStream()); stderr.addOutputStream(stdErr.getOutputStream()); if (lineConsumer != null) { StreamPumper.LinePump pump = new StreamPumper.LinePump() { @Override protected void processLine(String line) { lineConsumer.accept(line); } }; stdout.addPump(pump); stderr.addPump(pump); } CountDownLatch latch = new CountDownLatch(1); if (linePredicate != null) { StreamPumper.LinePump pump = new StreamPumper.LinePump() { // synchronization between stdout and stderr pumps private final Object sync = new Object(); @Override protected void processLine(String line) { synchronized (sync) { if (latch.getCount() > 0 && linePredicate.test(line)) { latch.countDown(); } } } }; stdout.addPump(pump); stderr.addPump(pump); } else { latch.countDown(); } final Future<Void> stdoutTask = stdout.process(); final Future<Void> stderrTask = stderr.process(); stdOut.getOutputStream().setTask(stdoutTask); stdErr.getOutputStream().setTask(stderrTask); try { if (timeout > -1) {
/* * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.test.lib.process; public final class ProcessTools { private static final class LineForwarder extends StreamPumper.LinePump { private final PrintStream ps; private final String prefix; LineForwarder(String prefix, PrintStream os) { this.ps = os; this.prefix = prefix; } @Override protected void processLine(String line) { ps.println("[" + prefix + "] " + line); } } private ProcessTools() { } /** * <p>Starts a process from its builder.</p> * <span>The default redirects of STDOUT and STDERR are started</span> * <p> * Same as * {@linkplain #startProcess(String, ProcessBuilder, Consumer, Predicate, long, TimeUnit) startProcess} * {@code (name, processBuilder, null, null, -1, TimeUnit.NANOSECONDS)} * </p> * @param name The process name * @param processBuilder The process builder * @return Returns the initialized process * @throws IOException */ public static Process startProcess(String name, ProcessBuilder processBuilder) throws IOException { return startProcess(name, processBuilder, (Consumer<String>) null); } /** * <p>Starts a process from its builder.</p> * <span>The default redirects of STDOUT and STDERR are started</span> * <p> * Same as * {@linkplain #startProcess(String, ProcessBuilder, Consumer, Predicate, long, TimeUnit) startProcess} * {@code (name, processBuilder, consumer, null, -1, TimeUnit.NANOSECONDS)} * </p> * * @param name The process name * @param processBuilder The process builder * @param consumer {@linkplain Consumer} instance to process the in-streams * @return Returns the initialized process * @throws IOException */ @SuppressWarnings("overloads") public static Process startProcess(String name, ProcessBuilder processBuilder, Consumer<String> consumer) throws IOException { try { return startProcess(name, processBuilder, consumer, null, -1, TimeUnit.NANOSECONDS); } catch (InterruptedException | TimeoutException | CancellationException e) { // will never happen throw new RuntimeException(e); } } /** * <p>Starts a process from its builder.</p> * <span>The default redirects of STDOUT and STDERR are started</span> * <p> * Same as * {@linkplain #startProcess(String, ProcessBuilder, Consumer, Predicate, long, TimeUnit) startProcess} * {@code (name, processBuilder, null, linePredicate, timeout, unit)} * </p> * * @param name The process name * @param processBuilder The process builder * @param linePredicate The {@linkplain Predicate} to use on the STDOUT and STDERR. * Used to determine the moment the target app is * properly warmed-up. * It can be null - in that case the warmup is skipped. * @param timeout The timeout for the warmup waiting; -1 = no wait; 0 = wait forever * @param unit The timeout {@linkplain TimeUnit} * @return Returns the initialized {@linkplain Process} * @throws IOException * @throws InterruptedException * @throws TimeoutException */ public static Process startProcess(String name, ProcessBuilder processBuilder, final Predicate<String> linePredicate, long timeout, TimeUnit unit) throws IOException, InterruptedException, TimeoutException { return startProcess(name, processBuilder, null, linePredicate, timeout, unit); } /* BufferOutputStream and BufferInputStream allow to re-use p.getInputStream() amd p.getOutputStream() of processes started with ProcessTools.startProcess(...). Implementation cashes ALL process output and allow to read it through InputStream. The stream uses Future<Void> task from StreamPumper.process() to check if output is complete. */ private static class BufferOutputStream extends ByteArrayOutputStream { private int current = 0; final private Process p; private Future<Void> task; public BufferOutputStream(Process p) { this.p = p; } synchronized void setTask(Future<Void> task) { this.task = task; } synchronized int readNext() { if (current > count) { throw new RuntimeException("Shouldn't ever happen. start: " + current + " count: " + count + " buffer: " + this); } while (current == count) { if (!p.isAlive() && (task != null)) { try { task.get(10, TimeUnit.MILLISECONDS); if (current == count) { return -1; } } catch (TimeoutException e) { // continue execution, so wait() give a chance to write } catch (InterruptedException | ExecutionException e) { return -1; } } try { wait(1); } catch (InterruptedException ie) { return -1; } } return this.buf[current++]; } } private static class BufferInputStream extends InputStream { private final BufferOutputStream buffer; public BufferInputStream(Process p) { buffer = new BufferOutputStream(p); } BufferOutputStream getOutputStream() { return buffer; } @Override public int read() throws IOException { return buffer.readNext(); } } /** * <p>Starts a process from its builder.</p> * <span>The default redirects of STDOUT and STDERR are started</span> * <p> * It is possible to wait for the process to get to a warmed-up state * via {@linkplain Predicate} condition on the STDOUT/STDERR and monitor the * in-streams via the provided {@linkplain Consumer} * </p> * * @param name The process name * @param processBuilder The process builder * @param lineConsumer The {@linkplain Consumer} the lines will be forwarded to * @param linePredicate The {@linkplain Predicate} to use on the STDOUT and STDERR. * Used to determine the moment the target app is * properly warmed-up. * It can be null - in that case the warmup is skipped. * @param timeout The timeout for the warmup waiting; -1 = no wait; 0 = wait forever * @param unit The timeout {@linkplain TimeUnit} * @return Returns the initialized {@linkplain Process} * @throws IOException * @throws InterruptedException * @throws TimeoutException */ public static Process startProcess(String name, ProcessBuilder processBuilder, final Consumer<String> lineConsumer, final Predicate<String> linePredicate, long timeout, TimeUnit unit) throws IOException, InterruptedException, TimeoutException { System.out.println("[" + name + "]:" + String.join(" ", processBuilder.command())); Process p = privilegedStart(processBuilder); StreamPumper stdout = new StreamPumper(p.getInputStream()); StreamPumper stderr = new StreamPumper(p.getErrorStream()); stdout.addPump(new LineForwarder(name, System.out)); stderr.addPump(new LineForwarder(name, System.err)); BufferInputStream stdOut = new BufferInputStream(p); BufferInputStream stdErr = new BufferInputStream(p); stdout.addOutputStream(stdOut.getOutputStream()); stderr.addOutputStream(stdErr.getOutputStream()); if (lineConsumer != null) { StreamPumper.LinePump pump = new StreamPumper.LinePump() { @Override protected void processLine(String line) { lineConsumer.accept(line); } }; stdout.addPump(pump); stderr.addPump(pump); } CountDownLatch latch = new CountDownLatch(1); if (linePredicate != null) { StreamPumper.LinePump pump = new StreamPumper.LinePump() { // synchronization between stdout and stderr pumps private final Object sync = new Object(); @Override protected void processLine(String line) { synchronized (sync) { if (latch.getCount() > 0 && linePredicate.test(line)) { latch.countDown(); } } } }; stdout.addPump(pump); stderr.addPump(pump); } else { latch.countDown(); } final Future<Void> stdoutTask = stdout.process(); final Future<Void> stderrTask = stderr.process(); stdOut.getOutputStream().setTask(stdoutTask); stdErr.getOutputStream().setTask(stderrTask); try { if (timeout > -1) {
long timeoutMs = timeout == 0 ? -1: unit.toMillis(Utils.adjustTimeout(timeout));
2
2023-10-15 15:56:58+00:00
24k
team-moabam/moabam-BE
src/main/java/com/moabam/api/application/room/SearchService.java
[ { "identifier": "GlobalConstant", "path": "src/main/java/com/moabam/global/common/util/GlobalConstant.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class GlobalConstant {\n\n\tpublic static final String BLANK = \"\";\n\tpublic static final String DELIMITER = \"/\";\n\tpubli...
import static com.moabam.global.common.util.GlobalConstant.*; import static com.moabam.global.error.model.ErrorMessage.*; import static org.apache.commons.lang3.StringUtils.*; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Period; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.moabam.api.application.member.MemberService; import com.moabam.api.application.notification.NotificationService; import com.moabam.api.application.room.mapper.CertificationsMapper; import com.moabam.api.application.room.mapper.ParticipantMapper; import com.moabam.api.application.room.mapper.RoomMapper; import com.moabam.api.application.room.mapper.RoutineMapper; import com.moabam.api.domain.item.Inventory; import com.moabam.api.domain.item.repository.InventorySearchRepository; import com.moabam.api.domain.member.Member; import com.moabam.api.domain.room.Certification; import com.moabam.api.domain.room.DailyMemberCertification; import com.moabam.api.domain.room.DailyRoomCertification; import com.moabam.api.domain.room.Participant; import com.moabam.api.domain.room.Room; import com.moabam.api.domain.room.RoomType; import com.moabam.api.domain.room.Routine; import com.moabam.api.domain.room.repository.CertificationsSearchRepository; import com.moabam.api.domain.room.repository.ParticipantSearchRepository; import com.moabam.api.domain.room.repository.RoomRepository; import com.moabam.api.domain.room.repository.RoomSearchRepository; import com.moabam.api.domain.room.repository.RoutineRepository; import com.moabam.api.dto.room.CertificationImageResponse; import com.moabam.api.dto.room.CertificationImagesResponse; import com.moabam.api.dto.room.GetAllRoomResponse; import com.moabam.api.dto.room.GetAllRoomsResponse; import com.moabam.api.dto.room.ManageRoomResponse; import com.moabam.api.dto.room.MyRoomResponse; import com.moabam.api.dto.room.MyRoomsResponse; import com.moabam.api.dto.room.ParticipantResponse; import com.moabam.api.dto.room.RoomDetailsResponse; import com.moabam.api.dto.room.RoomHistoryResponse; import com.moabam.api.dto.room.RoomsHistoryResponse; import com.moabam.api.dto.room.RoutineResponse; import com.moabam.api.dto.room.TodayCertificateRankResponse; import com.moabam.api.dto.room.UnJoinedRoomCertificateRankResponse; import com.moabam.api.dto.room.UnJoinedRoomDetailsResponse; import com.moabam.global.common.util.ClockHolder; import com.moabam.global.error.exception.ForbiddenException; import com.moabam.global.error.exception.NotFoundException; import jakarta.annotation.Nullable; import lombok.RequiredArgsConstructor;
16,026
package com.moabam.api.application.room; @Service @RequiredArgsConstructor @Transactional(readOnly = true) public class SearchService { private final RoomRepository roomRepository; private final RoomSearchRepository roomSearchRepository; private final RoutineRepository routineRepository; private final ParticipantSearchRepository participantSearchRepository; private final CertificationsSearchRepository certificationsSearchRepository; private final InventorySearchRepository inventorySearchRepository; private final CertificationService certificationService; private final MemberService memberService; private final NotificationService notificationService; private final ClockHolder clockHolder; public RoomDetailsResponse getRoomDetails(Long memberId, Long roomId, LocalDate date) { Participant participant = participantSearchRepository.findOne(memberId, roomId) .orElseThrow(() -> new NotFoundException(PARTICIPANT_NOT_FOUND)); Room room = participant.getRoom(); String managerNickname = room.getManagerNickname(); List<DailyMemberCertification> dailyMemberCertifications = certificationsSearchRepository.findSortedDailyMemberCertifications(roomId, date); List<RoutineResponse> routineResponses = getRoutineResponses(roomId); List<TodayCertificateRankResponse> todayCertificateRankResponses = getTodayCertificateRankResponses(memberId, roomId, dailyMemberCertifications, date, room.getRoomType()); List<LocalDate> certifiedDates = getCertifiedDatesBeforeWeek(roomId); double completePercentage = calculateCompletePercentage(dailyMemberCertifications.size(), room, date); return RoomMapper.toRoomDetailsResponse(memberId, room, managerNickname, routineResponses, certifiedDates, todayCertificateRankResponses, completePercentage); } public MyRoomsResponse getMyRooms(Long memberId) { LocalDate today = clockHolder.date(); List<MyRoomResponse> myRoomResponses = new ArrayList<>(); List<Participant> participants = participantSearchRepository.findNotDeletedAllByMemberId(memberId); for (Participant participant : participants) { Room room = participant.getRoom(); boolean isMemberCertified = certificationService.existsMemberCertification(memberId, room.getId(), today); boolean isRoomCertified = certificationService.existsRoomCertification(room.getId(), today); myRoomResponses.add(RoomMapper.toMyRoomResponse(room, isMemberCertified, isRoomCertified)); } return RoomMapper.toMyRoomsResponse(myRoomResponses); } public RoomsHistoryResponse getJoinHistory(Long memberId) { List<Participant> participants = participantSearchRepository.findAllByMemberId(memberId); List<RoomHistoryResponse> roomHistoryResponses = participants.stream() .map(participant -> { if (participant.getRoom() == null) { return RoomMapper.toRoomHistoryResponse(null, participant.getDeletedRoomTitle(), participant); } Room room = participant.getRoom(); return RoomMapper.toRoomHistoryResponse(room.getId(), room.getTitle(), participant); }) .toList(); return RoomMapper.toRoomsHistoryResponse(roomHistoryResponses); } public ManageRoomResponse getRoomForModification(Long memberId, Long roomId) { Participant participant = participantSearchRepository.findOne(memberId, roomId) .orElseThrow(() -> new NotFoundException(PARTICIPANT_NOT_FOUND)); if (!participant.isManager()) { throw new ForbiddenException(ROOM_MODIFY_UNAUTHORIZED_REQUEST); } Room room = participant.getRoom(); List<RoutineResponse> routineResponses = getRoutineResponses(roomId); List<Participant> participants = participantSearchRepository.findAllByRoomId(roomId); List<Long> memberIds = participants.stream() .map(Participant::getMemberId) .toList(); List<Member> members = memberService.getRoomMembers(memberIds); List<ParticipantResponse> participantResponses = new ArrayList<>(); for (Member member : members) { int contributionPoint = calculateContributionPoint(member.getId(), participants, clockHolder.date());
package com.moabam.api.application.room; @Service @RequiredArgsConstructor @Transactional(readOnly = true) public class SearchService { private final RoomRepository roomRepository; private final RoomSearchRepository roomSearchRepository; private final RoutineRepository routineRepository; private final ParticipantSearchRepository participantSearchRepository; private final CertificationsSearchRepository certificationsSearchRepository; private final InventorySearchRepository inventorySearchRepository; private final CertificationService certificationService; private final MemberService memberService; private final NotificationService notificationService; private final ClockHolder clockHolder; public RoomDetailsResponse getRoomDetails(Long memberId, Long roomId, LocalDate date) { Participant participant = participantSearchRepository.findOne(memberId, roomId) .orElseThrow(() -> new NotFoundException(PARTICIPANT_NOT_FOUND)); Room room = participant.getRoom(); String managerNickname = room.getManagerNickname(); List<DailyMemberCertification> dailyMemberCertifications = certificationsSearchRepository.findSortedDailyMemberCertifications(roomId, date); List<RoutineResponse> routineResponses = getRoutineResponses(roomId); List<TodayCertificateRankResponse> todayCertificateRankResponses = getTodayCertificateRankResponses(memberId, roomId, dailyMemberCertifications, date, room.getRoomType()); List<LocalDate> certifiedDates = getCertifiedDatesBeforeWeek(roomId); double completePercentage = calculateCompletePercentage(dailyMemberCertifications.size(), room, date); return RoomMapper.toRoomDetailsResponse(memberId, room, managerNickname, routineResponses, certifiedDates, todayCertificateRankResponses, completePercentage); } public MyRoomsResponse getMyRooms(Long memberId) { LocalDate today = clockHolder.date(); List<MyRoomResponse> myRoomResponses = new ArrayList<>(); List<Participant> participants = participantSearchRepository.findNotDeletedAllByMemberId(memberId); for (Participant participant : participants) { Room room = participant.getRoom(); boolean isMemberCertified = certificationService.existsMemberCertification(memberId, room.getId(), today); boolean isRoomCertified = certificationService.existsRoomCertification(room.getId(), today); myRoomResponses.add(RoomMapper.toMyRoomResponse(room, isMemberCertified, isRoomCertified)); } return RoomMapper.toMyRoomsResponse(myRoomResponses); } public RoomsHistoryResponse getJoinHistory(Long memberId) { List<Participant> participants = participantSearchRepository.findAllByMemberId(memberId); List<RoomHistoryResponse> roomHistoryResponses = participants.stream() .map(participant -> { if (participant.getRoom() == null) { return RoomMapper.toRoomHistoryResponse(null, participant.getDeletedRoomTitle(), participant); } Room room = participant.getRoom(); return RoomMapper.toRoomHistoryResponse(room.getId(), room.getTitle(), participant); }) .toList(); return RoomMapper.toRoomsHistoryResponse(roomHistoryResponses); } public ManageRoomResponse getRoomForModification(Long memberId, Long roomId) { Participant participant = participantSearchRepository.findOne(memberId, roomId) .orElseThrow(() -> new NotFoundException(PARTICIPANT_NOT_FOUND)); if (!participant.isManager()) { throw new ForbiddenException(ROOM_MODIFY_UNAUTHORIZED_REQUEST); } Room room = participant.getRoom(); List<RoutineResponse> routineResponses = getRoutineResponses(roomId); List<Participant> participants = participantSearchRepository.findAllByRoomId(roomId); List<Long> memberIds = participants.stream() .map(Participant::getMemberId) .toList(); List<Member> members = memberService.getRoomMembers(memberIds); List<ParticipantResponse> participantResponses = new ArrayList<>(); for (Member member : members) { int contributionPoint = calculateContributionPoint(member.getId(), participants, clockHolder.date());
participantResponses.add(ParticipantMapper.toParticipantResponse(member, contributionPoint));
5
2023-10-20 06:15:43+00:00
24k
tuxming/xmfx
BaseUI/src/main/java/com/xm2013/jfx/control/date/XmDateSelectorSkin.java
[ { "identifier": "CallBack", "path": "BaseUI/src/main/java/com/xm2013/jfx/common/CallBack.java", "snippet": "public interface CallBack<T> {\n \n /**\n * Call.\n *\n * @param t the t\n */\n public void call(T t);\n}" }, { "identifier": "FxKit", "path": "BaseUI/src/main...
import com.xm2013.jfx.common.CallBack; import com.xm2013.jfx.common.FxKit; import com.xm2013.jfx.control.animate.ClickAnimate; import com.xm2013.jfx.control.animate.ClickRipperAnimate; import com.xm2013.jfx.control.animate.ClickShadowAnimate; import com.xm2013.jfx.control.base.BorderType; import com.xm2013.jfx.control.base.ClickAnimateType; import com.xm2013.jfx.control.base.HueType; import com.xm2013.jfx.control.base.SkinInfo; import com.xm2013.jfx.control.textfield.XmSimpleTextField; import com.xm2013.jfx.control.icon.XmSVGIcon; import javafx.beans.binding.Bindings; import javafx.beans.value.ChangeListener; import javafx.event.EventHandler; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.VPos; import javafx.scene.Node; import javafx.scene.control.SkinBase; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.Font; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Map;
19,724
* 图标的状态变化监听 */ private ChangeListener<Boolean> iconStatusListener = (ob, ov, nv) -> { if(iconPane.isFocused()){ updateSkin(iconPane.isHover()?3:4, 2); }else{ updateSkin(iconPane.isHover()?2: 1, 2); } }; /* --------------------------- override ---------------------------- */ @Override protected double computePrefWidth(double height, double topInset, double rightInset, double bottomInset, double leftInset) { double width = field.prefWidth(-1) + field.prefHeight(-1); Insets padding = control.getPadding(); width += padding.getLeft() + padding.getRight(); return width; } @Override protected void layoutChildren(double contentX, double contentY, double contentWidth, double contentHeight) { double fieldWidth = field.prefWidth(-1), fieldHeight = field.prefHeight(-1); double iconPaneX = contentX + fieldWidth, iconPaneY = (contentHeight - fieldHeight)/2; field.setPrefWidth(contentWidth-fieldHeight); layoutInArea(field, contentX, contentY, contentWidth-fieldHeight, fieldHeight, 0, HPos.CENTER, VPos.CENTER); layoutInArea(iconPane, iconPaneX, iconPaneY, fieldHeight, fieldHeight, 0, HPos.CENTER, VPos.CENTER); } @Override public void dispose() { super.dispose(); iconPane.prefWidthProperty().unbind(); iconPane.prefHeightProperty().unbind(); icon.layoutXProperty().unbind(); icon.layoutYProperty().unbind(); field.focusedProperty().removeListener(fieldStatusListener); field.hoverProperty().removeListener(fieldStatusListener); iconPane.focusedProperty().removeListener(iconStatusListener); iconPane.hoverProperty().removeListener(iconStatusListener); iconPane.removeEventFilter(MouseEvent.MOUSE_CLICKED, iconPaneClickHandler); this.control.getScene().getWindow().focusedProperty().removeListener(windowFocusListener); this.control.getScene().removeEventFilter(MouseEvent.MOUSE_PRESSED, windowClickFilter); this.control.selectedDateProperty().removeListener(selectedDateListener); this.field.removeEventFilter(KeyEvent.KEY_RELEASED, inputKeyReleaseHandler); unregisterChangeListeners(control.hueTypeProperty()); unregisterChangeListeners(control.colorTypeProperty()); unregisterChangeListeners(control.sizeTypeProperty()); unregisterChangeListeners(control.roundTypeProperty()); unregisterChangeListeners(control.fillIconProperty()); } /* ----------------------- method ----------------------------- */ /** * 获取点击动画 * @return */ private ClickAnimate getIconClickAnimate(){ if(iconClickAnimate == null){ ClickAnimateType type = control.getClickAnimateType(); if(ClickAnimateType.SHADOW.equals(type)){ iconClickAnimate = new ClickShadowAnimate(iconPane, control.getColorType()); }else if(ClickAnimateType.RIPPER.equals(type)){ iconClickAnimate = new ClickRipperAnimate(iconPane, control.getColorType(), control.getHueType()); } //设置阴影的动画节点所在的位置 iconClickAnimate.setNodePosition((node, width, height, x, y) -> { Insets margin = control.getMargin(); double left = 0, top = 0; if(margin!=null){ left = margin.getLeft(); top = margin.getTop(); } double w = field.prefWidth(-1); left += w; // System.out.println(String.format("left:%f, top:%f, height:%f, width:%f", left, top, iconPane.minWidth(-1), valuePane.prefHeight(-1) )); layoutInArea(node, left, top, iconPane.prefWidth(-1), iconPane.prefHeight(-1), 0, HPos.CENTER, VPos.CENTER); }); //将动画节点添加控件中 iconClickAnimate.setAddNode(node -> { if(ClickAnimateType.SHADOW.equals(type)){ getChildren().add(0, node); }else if(ClickAnimateType.RIPPER.equals(type)){ //node.setStyle("-fx-background-color: red;"); getChildren().add(node); } }); //动画播放完成后,将动画节点从控件中移除 iconClickAnimate.setRemoveNode(node -> getChildren().remove(node)); } return iconClickAnimate; } /** * 获取弹出框 * @return DateSelectorPopup */ public DateSelectorPopup getPopup(){ if(popup == null){ popup = new DateSelectorPopup(control.colorTypeProperty(), control.dateTypeProperty());
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.xm2013.jfx.control.date; public class XmDateSelectorSkin extends SkinBase { private XmSimpleTextField field; private XmSVGIcon icon; private Pane iconPane; private XmDateSelector control; private ClickAnimate iconClickAnimate; //组件外观信息缓存,用于动态切换组件时缓存改变之前的外观信息 private final Map<Integer, SkinInfo> skins = new HashMap<Integer, SkinInfo>(); private DateSelectorPopup popup; public XmDateSelectorSkin(XmDateSelector control) { super(control); this.control = control; field = new XmSimpleTextField(); field.setEnableSkin(true); field.setPromptText(control.getPromptText()); icon = new XmSVGIcon(FxKit.DATE_PATH); iconPane = new Pane(icon); iconPane.prefWidthProperty().bind(field.heightProperty()); iconPane.prefHeightProperty().bind(field.heightProperty()); icon.layoutXProperty().bind(Bindings.createDoubleBinding(()->(field.getHeight() - icon.prefWidth(-1))/2 , field.heightProperty(), icon.widthProperty())); icon.layoutYProperty().bind(Bindings.createDoubleBinding(()->(field.getHeight() - icon.prefHeight(-1))/2 , field.heightProperty(), icon.heightProperty())); getChildren().addAll(field, iconPane); iconPane.setFocusTraversable(true); updateSkin(1,0); field.focusedProperty().addListener(fieldStatusListener); field.hoverProperty().addListener(fieldStatusListener); field.textProperty().addListener(fieldTextListener); iconPane.focusedProperty().addListener(iconStatusListener); iconPane.hoverProperty().addListener(iconStatusListener); iconPane.addEventFilter(MouseEvent.MOUSE_CLICKED, iconPaneClickHandler); iconPane.addEventFilter(KeyEvent.KEY_RELEASED, iconPaneKeyReleaseHandler); //监听关闭弹窗 this.control.getScene().getWindow().focusedProperty().addListener(windowFocusListener); this.control.getScene().addEventFilter(MouseEvent.MOUSE_PRESSED, windowClickFilter); this.control.selectedDateProperty().addListener(selectedDateListener); this.field.addEventFilter(KeyEvent.KEY_RELEASED, inputKeyReleaseHandler); registerChangeListener(control.hueTypeProperty(), e->{skins.clear(); updateSkin(1, 0);}); registerChangeListener(control.colorTypeProperty(), e->{skins.clear(); updateSkin(1, 0);}); registerChangeListener(control.sizeTypeProperty(), e->{skins.clear(); updateSkin(1, 0);}); registerChangeListener(control.roundTypeProperty(), e->{skins.clear(); updateSkin(1, 0);}); registerChangeListener(control.fillIconProperty(), e->{skins.clear(); updateSkin(1, 0);}); } /* ------------------------ listener ---------------------- */ private ChangeListener<String> fieldTextListener = (ob, ov, nv) -> { if(nv == null || nv.trim().length() == 0){ this.control.setSelectedDate(null); } }; /** * 日期变化监听 */ private ChangeListener<LocalDateTime> selectedDateListener = (ob, ov, nv)->{ if(nv!=null){ String pattern = control.getFormatPattern(); // System.out.println(pattern); DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); String formattedDate = nv.format(formatter); this.field.setText(formattedDate); } }; /** * 输入日期,处理 */ public EventHandler<KeyEvent> inputKeyReleaseHandler = (e) ->{ if(e.getCode() == KeyCode.ENTER){ try{ DateTimeFormatter formatter = DateTimeFormatter.ofPattern(control.getFormatPattern()); LocalDateTime date = LocalDateTime.parse(this.field.getText(), formatter); this.control.setSelectedDate(date); }catch (Exception ex){ ex.printStackTrace(); } } }; /** * 点击主窗体的时候,隐藏下拉框 */ private final EventHandler<MouseEvent> windowClickFilter = e -> { //判断是不是点击iconPane if(isControl((Node) e.getTarget(), 1) == 0){ getPopup().hide(); } }; /** * 窗体失去焦点的时候,隐藏下拉弹框 */ private final ChangeListener<Boolean> windowFocusListener = (ob, ov, nv) -> { if (!nv) { getPopup().hide(); } }; /** * 播放按钮动画,显示下拉框 */ private EventHandler<MouseEvent> iconPaneClickHandler = (e)->{ iconPane.requestFocus(); getIconClickAnimate().setPoint(e.getX(), e.getY()).play(); getPopup().setDate(control.getSelectedDate()).show(this.control); }; /** * 按下enter, space键,出发icon的点击事件 */ private EventHandler<KeyEvent> iconPaneKeyReleaseHandler = e -> { if(iconPane.isFocused() && (e.getCode().equals(KeyCode.ENTER)|| e.getCode().equals(KeyCode.SPACE))){ getIconClickAnimate().setPoint(iconPane.prefWidth(-1)/2, iconPane.prefHeight(-1)/2).play(); getPopup().setDate(control.getSelectedDate()).show(this.control); } }; /** * 设置外观,显示下拉框 */ private ChangeListener<Boolean> fieldStatusListener = (ob, ov, nv) ->{ if(field.isFocused()){ updateSkin(field.isHover()?3:4, 1); // getPopup().setDate(control.getSelectedDate()).show(this.control); }else{ updateSkin(field.isHover()?2: 1, 1); } }; /** * 图标的状态变化监听 */ private ChangeListener<Boolean> iconStatusListener = (ob, ov, nv) -> { if(iconPane.isFocused()){ updateSkin(iconPane.isHover()?3:4, 2); }else{ updateSkin(iconPane.isHover()?2: 1, 2); } }; /* --------------------------- override ---------------------------- */ @Override protected double computePrefWidth(double height, double topInset, double rightInset, double bottomInset, double leftInset) { double width = field.prefWidth(-1) + field.prefHeight(-1); Insets padding = control.getPadding(); width += padding.getLeft() + padding.getRight(); return width; } @Override protected void layoutChildren(double contentX, double contentY, double contentWidth, double contentHeight) { double fieldWidth = field.prefWidth(-1), fieldHeight = field.prefHeight(-1); double iconPaneX = contentX + fieldWidth, iconPaneY = (contentHeight - fieldHeight)/2; field.setPrefWidth(contentWidth-fieldHeight); layoutInArea(field, contentX, contentY, contentWidth-fieldHeight, fieldHeight, 0, HPos.CENTER, VPos.CENTER); layoutInArea(iconPane, iconPaneX, iconPaneY, fieldHeight, fieldHeight, 0, HPos.CENTER, VPos.CENTER); } @Override public void dispose() { super.dispose(); iconPane.prefWidthProperty().unbind(); iconPane.prefHeightProperty().unbind(); icon.layoutXProperty().unbind(); icon.layoutYProperty().unbind(); field.focusedProperty().removeListener(fieldStatusListener); field.hoverProperty().removeListener(fieldStatusListener); iconPane.focusedProperty().removeListener(iconStatusListener); iconPane.hoverProperty().removeListener(iconStatusListener); iconPane.removeEventFilter(MouseEvent.MOUSE_CLICKED, iconPaneClickHandler); this.control.getScene().getWindow().focusedProperty().removeListener(windowFocusListener); this.control.getScene().removeEventFilter(MouseEvent.MOUSE_PRESSED, windowClickFilter); this.control.selectedDateProperty().removeListener(selectedDateListener); this.field.removeEventFilter(KeyEvent.KEY_RELEASED, inputKeyReleaseHandler); unregisterChangeListeners(control.hueTypeProperty()); unregisterChangeListeners(control.colorTypeProperty()); unregisterChangeListeners(control.sizeTypeProperty()); unregisterChangeListeners(control.roundTypeProperty()); unregisterChangeListeners(control.fillIconProperty()); } /* ----------------------- method ----------------------------- */ /** * 获取点击动画 * @return */ private ClickAnimate getIconClickAnimate(){ if(iconClickAnimate == null){ ClickAnimateType type = control.getClickAnimateType(); if(ClickAnimateType.SHADOW.equals(type)){ iconClickAnimate = new ClickShadowAnimate(iconPane, control.getColorType()); }else if(ClickAnimateType.RIPPER.equals(type)){ iconClickAnimate = new ClickRipperAnimate(iconPane, control.getColorType(), control.getHueType()); } //设置阴影的动画节点所在的位置 iconClickAnimate.setNodePosition((node, width, height, x, y) -> { Insets margin = control.getMargin(); double left = 0, top = 0; if(margin!=null){ left = margin.getLeft(); top = margin.getTop(); } double w = field.prefWidth(-1); left += w; // System.out.println(String.format("left:%f, top:%f, height:%f, width:%f", left, top, iconPane.minWidth(-1), valuePane.prefHeight(-1) )); layoutInArea(node, left, top, iconPane.prefWidth(-1), iconPane.prefHeight(-1), 0, HPos.CENTER, VPos.CENTER); }); //将动画节点添加控件中 iconClickAnimate.setAddNode(node -> { if(ClickAnimateType.SHADOW.equals(type)){ getChildren().add(0, node); }else if(ClickAnimateType.RIPPER.equals(type)){ //node.setStyle("-fx-background-color: red;"); getChildren().add(node); } }); //动画播放完成后,将动画节点从控件中移除 iconClickAnimate.setRemoveNode(node -> getChildren().remove(node)); } return iconClickAnimate; } /** * 获取弹出框 * @return DateSelectorPopup */ public DateSelectorPopup getPopup(){ if(popup == null){ popup = new DateSelectorPopup(control.colorTypeProperty(), control.dateTypeProperty());
popup.setSelectedCallback(new CallBack<LocalDateTime>() {
0
2023-10-17 08:57:08+00:00
24k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/discPCFG/ProperNameObjectiveFunction.java
[ { "identifier": "DoubleArrays", "path": "src/berkeley_parser/edu/berkeley/nlp/math/DoubleArrays.java", "snippet": "public class DoubleArrays {\n\tpublic static double[] clone(double[] x) {\n\t\tdouble[] y = new double[x.length];\n\t\tassign(y, x);\n\t\treturn y;\n\t}\n\n\tpublic static void assign(doubl...
import edu.berkeley.nlp.math.DoubleArrays; import edu.berkeley.nlp.math.SloppyMath; import edu.berkeley.nlp.util.Pair;
17,338
package edu.berkeley.nlp.discPCFG; /** * @author petrov * */ /** * This is the MaximumEntropy objective function: the (negative) log conditional * likelihood of the training data, possibly with a penalty for large weights. * Note that this objective get MINIMIZED so it's the negative of the objective * we normally think of. */ public class ProperNameObjectiveFunction<F, L> implements ObjectiveFunction { IndexLinearizer indexLinearizer; Encoding<F, L> encoding; EncodedDatum[] data; double[] x; double sigma; double lastValue; double[] lastDerivative; double[] lastX; boolean isUpToDate; public void shutdown() { } public void updateGoldCountsNextRound() { } public int dimension() { return indexLinearizer.getNumLinearIndexes(); } public double valueAt(double[] x) { ensureCache(x); isUpToDate = false; return lastValue; } public double[] derivativeAt(double[] x) { ensureCache(x); isUpToDate = false; return lastDerivative; } public double[] unregularizedDerivativeAt(double[] x) { return null; } private void ensureCache(double[] x) { if (!isUpToDate) { // requiresUpdate(lastX, x)) { this.x = x; Pair<Double, double[]> currentValueAndDerivative = calculate(); lastValue = currentValueAndDerivative.getFirst(); lastDerivative = currentValueAndDerivative.getSecond(); lastX = x; } } /* * private boolean requiresUpdate(double[] lastX, double[] x) { if (lastX == * null) return true; for (int i = 0; i < x.length; i++) { if (lastX[i] != * x[i]) return true; } return false; } */ public void setX(double[] x) { this.x = x; } public void isUpToDate(boolean b) { isUpToDate = b; } /** * The most important part of the classifier learning process! This method * determines, for the given weight vector x, what the (negative) log * conditional likelihood of the data is, as well as the derivatives of that * likelihood wrt each weight parameter. */ public Pair<Double, double[]> calculate() { double objective = 0.0; System.out.println("In Calculate...");
package edu.berkeley.nlp.discPCFG; /** * @author petrov * */ /** * This is the MaximumEntropy objective function: the (negative) log conditional * likelihood of the training data, possibly with a penalty for large weights. * Note that this objective get MINIMIZED so it's the negative of the objective * we normally think of. */ public class ProperNameObjectiveFunction<F, L> implements ObjectiveFunction { IndexLinearizer indexLinearizer; Encoding<F, L> encoding; EncodedDatum[] data; double[] x; double sigma; double lastValue; double[] lastDerivative; double[] lastX; boolean isUpToDate; public void shutdown() { } public void updateGoldCountsNextRound() { } public int dimension() { return indexLinearizer.getNumLinearIndexes(); } public double valueAt(double[] x) { ensureCache(x); isUpToDate = false; return lastValue; } public double[] derivativeAt(double[] x) { ensureCache(x); isUpToDate = false; return lastDerivative; } public double[] unregularizedDerivativeAt(double[] x) { return null; } private void ensureCache(double[] x) { if (!isUpToDate) { // requiresUpdate(lastX, x)) { this.x = x; Pair<Double, double[]> currentValueAndDerivative = calculate(); lastValue = currentValueAndDerivative.getFirst(); lastDerivative = currentValueAndDerivative.getSecond(); lastX = x; } } /* * private boolean requiresUpdate(double[] lastX, double[] x) { if (lastX == * null) return true; for (int i = 0; i < x.length; i++) { if (lastX[i] != * x[i]) return true; } return false; } */ public void setX(double[] x) { this.x = x; } public void isUpToDate(boolean b) { isUpToDate = b; } /** * The most important part of the classifier learning process! This method * determines, for the given weight vector x, what the (negative) log * conditional likelihood of the data is, as well as the derivatives of that * likelihood wrt each weight parameter. */ public Pair<Double, double[]> calculate() { double objective = 0.0; System.out.println("In Calculate...");
double[] derivatives = DoubleArrays.constantArray(0.0, dimension());
0
2023-10-22 13:13:22+00:00
24k
neftalito/R-Info-Plus
form/Parser.java
[ { "identifier": "Iniciar", "path": "arbol/sentencia/primitiva/Iniciar.java", "snippet": "public class Iniciar extends Primitiva {\n RobotAST r;\n int x;\n int y;\n Identificador Ident;\n DeclaracionRobots robAST;\n DeclaracionVariable varAST;\n\n public Iniciar(final Identificador I...
import arbol.sentencia.primitiva.Iniciar; import arbol.sentencia.primitiva.AsignarArea; import arbol.DeclaracionAreas; import arbol.Programa; import arbol.ParametroFormal; import arbol.Proceso; import arbol.RobotAST; import arbol.DeclaracionProcesos; import arbol.Cuerpo; import arbol.sentencia.IteradorCondicional; import arbol.sentencia.IteradorIncondicional; import arbol.sentencia.Seleccion; import arbol.sentencia.primitiva.Random; import arbol.sentencia.primitiva.RecibirMensaje; import arbol.sentencia.primitiva.EnviarMensaje; import arbol.sentencia.primitiva.DepositarPapel; import arbol.sentencia.primitiva.DepositarFlor; import arbol.sentencia.primitiva.TomarPapel; import arbol.sentencia.primitiva.TomarFlor; import arbol.sentencia.primitiva.Derecha; import arbol.sentencia.primitiva.Izquierda; import arbol.sentencia.primitiva.Mover; import arbol.sentencia.primitiva.Leer; import arbol.sentencia.primitiva.BloquearEsquina; import arbol.sentencia.primitiva.LiberarEsquina; import arbol.sentencia.primitiva.Primitiva; import arbol.llamada.IdentificadorLlamada; import arbol.sentencia.Sentencia; import arbol.sentencia.Asignacion; import arbol.llamada.Pos; import arbol.llamada.Informar; import java.util.ArrayList; import arbol.sentencia.Invocacion; import javax.swing.JOptionPane; import arbol.DeclaracionRobots; import arbol.Tipo; import arbol.Variable; import arbol.Identificador; import arbol.expresion.ExpresionBinaria; import arbol.expresion.ExpresionUnaria; import java.util.Stack; import arbol.DeclaracionVariable; import arbol.expresion.ValorBooleano; import arbol.expresion.ValorNumerico; import arbol.expresion.operador.relacional.MenorIgual; import arbol.expresion.operador.relacional.Menor; import arbol.expresion.operador.relacional.MayorIgual; import arbol.expresion.operador.relacional.Mayor; import arbol.expresion.operador.relacional.Igual; import arbol.expresion.operador.relacional.Distinto; import arbol.expresion.operador.booleano.Not; import arbol.expresion.operador.booleano.Or; import arbol.expresion.operador.booleano.And; import arbol.expresion.operador.aritmetico.Suma; import arbol.expresion.operador.aritmetico.Resta; import arbol.expresion.operador.aritmetico.Multiplicacion; import arbol.expresion.operador.aritmetico.Division; import arbol.expresion.operador.aritmetico.Modulo; import arbol.expresion.operador.Operador; import arbol.expresion.HayObstaculo; import arbol.expresion.HayPapelEnLaEsquina; import arbol.expresion.HayFlorEnLaEsquina; import arbol.expresion.HayPapelEnLaBolsa; import arbol.expresion.HayFlorEnLaBolsa; import arbol.expresion.PosCa; import arbol.expresion.PosAv; import arbol.expresion.CantidadFloresBolsa; import arbol.expresion.CantidadPapelesBolsa; import arbol.expresion.Expresion;
20,803
package form; public class Parser { public Token currentToken; private Scanner scanner; Ciudad city; Parser(final String fuente, final Ciudad city) throws Exception { this.city = city; this.scanner = new Scanner(fuente); try { this.nextToken(); } catch (Exception e) { this.reportParseError("Error in Parser!"); } } public boolean isOperando(final Token token) { return token.kind == 23 || token.kind == 32 || token.kind == 33; } public boolean isVariableEntorno(final Token token) { switch (token.kind) { case 8: case 9: case 10: case 11: case 12: case 13: case 63: case 82: case 83: { return true; } default: { return false; } } } public boolean isOperador(final Token token) { boolean res = false; switch (token.kind) { case 30: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 81: { res = true; break; } default: { res = false; break; } } return res; } public boolean isParentesis(final Token token) { boolean res = false; switch (token.kind) { case 21: case 22: { res = true; break; } default: { res = false; break; } } return res; } public boolean thereIsHighOrEqualPrecedence(final Object o) { boolean res = true; final Token t = (Token) o; if (t.kind == 21 || (this.currentToken.kind == 49 && t.kind == 50) || (this.currentToken.kind == 49 && t.kind == 51) || ((this.currentToken.kind == 48 || this.currentToken.kind == 47 || this.currentToken.kind == 81) && (t.kind == 45 || t.kind == 46))) { res = false; } return res; } public Expresion parseVariableEntorno(final Token t) { Expresion expAST = null; switch (t.kind) { case 8: { expAST = new PosAv(); break; } case 9: {
package form; public class Parser { public Token currentToken; private Scanner scanner; Ciudad city; Parser(final String fuente, final Ciudad city) throws Exception { this.city = city; this.scanner = new Scanner(fuente); try { this.nextToken(); } catch (Exception e) { this.reportParseError("Error in Parser!"); } } public boolean isOperando(final Token token) { return token.kind == 23 || token.kind == 32 || token.kind == 33; } public boolean isVariableEntorno(final Token token) { switch (token.kind) { case 8: case 9: case 10: case 11: case 12: case 13: case 63: case 82: case 83: { return true; } default: { return false; } } } public boolean isOperador(final Token token) { boolean res = false; switch (token.kind) { case 30: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 81: { res = true; break; } default: { res = false; break; } } return res; } public boolean isParentesis(final Token token) { boolean res = false; switch (token.kind) { case 21: case 22: { res = true; break; } default: { res = false; break; } } return res; } public boolean thereIsHighOrEqualPrecedence(final Object o) { boolean res = true; final Token t = (Token) o; if (t.kind == 21 || (this.currentToken.kind == 49 && t.kind == 50) || (this.currentToken.kind == 49 && t.kind == 51) || ((this.currentToken.kind == 48 || this.currentToken.kind == 47 || this.currentToken.kind == 81) && (t.kind == 45 || t.kind == 46))) { res = false; } return res; } public Expresion parseVariableEntorno(final Token t) { Expresion expAST = null; switch (t.kind) { case 8: { expAST = new PosAv(); break; } case 9: {
expAST = new PosCa();
61
2023-10-20 15:45:37+00:00
24k
moonstoneid/aero-cast
apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/eth/EthSubscriberAdapter.java
[ { "identifier": "EthRegistryProperties", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/config/EthRegistryProperties.java", "snippet": "@ConfigurationProperties(prefix = \"eth.registry\")\n@Data\npublic class EthRegistryProperties {\n public String contractAddress;\n}" }, ...
import java.util.List; import com.moonstoneid.aerocast.common.config.EthRegistryProperties; import com.moonstoneid.aerocast.common.eth.BaseEthAdapter; import com.moonstoneid.aerocast.common.eth.EthUtil; import com.moonstoneid.aerocast.common.eth.contracts.FeedRegistry; import com.moonstoneid.aerocast.common.eth.contracts.FeedSubscriber; import com.moonstoneid.aerocast.common.eth.contracts.FeedSubscriber.CreateSubscriptionEventResponse; import com.moonstoneid.aerocast.common.eth.contracts.FeedSubscriber.RemoveSubscriptionEventResponse; import io.reactivex.disposables.Disposable; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.web3j.crypto.Credentials; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.methods.request.EthFilter;
17,642
package com.moonstoneid.aerocast.aggregator.eth; @Component @Slf4j
package com.moonstoneid.aerocast.aggregator.eth; @Component @Slf4j
public class EthSubscriberAdapter extends BaseEthAdapter {
1
2023-10-23 20:33:07+00:00
24k
JonnyOnlineYT/xenza
temp/src/minecraft/net/minecraft/world/gen/FlatLayerInfo.java
[ { "identifier": "Block", "path": "src/minecraft/net/minecraft/block/Block.java", "snippet": "public class Block {\n private static final ResourceLocation AIR_ID = new ResourceLocation(\"air\");\n public static final RegistryNamespacedDefaultedByKey<ResourceLocation, Block> blockRegistry = new Regist...
import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.util.ResourceLocation;
19,086
package net.minecraft.world.gen; public class FlatLayerInfo { private final int field_175902_a;
package net.minecraft.world.gen; public class FlatLayerInfo { private final int field_175902_a;
private IBlockState field_175901_b;
1
2023-10-15 00:21:15+00:00
24k
eclipse-egit/egit
org.eclipse.egit.core/src/org/eclipse/egit/core/op/IgnoreOperation.java
[ { "identifier": "Activator", "path": "org.eclipse.egit.core/src/org/eclipse/egit/core/Activator.java", "snippet": "public class Activator extends Plugin {\n\n\t/** The plug-in ID for Egit core. */\n\tpublic static final String PLUGIN_ID = \"org.eclipse.egit.core\"; //$NON-NLS-1$\n\n\tprivate static Acti...
import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.egit.core.Activator; import org.eclipse.egit.core.IteratorService; import org.eclipse.egit.core.RepositoryCache; import org.eclipse.egit.core.internal.CoreText; import org.eclipse.egit.core.internal.job.RuleUtil; import org.eclipse.egit.core.internal.util.ResourceUtil; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.WorkingTreeIterator; import org.eclipse.jgit.treewalk.filter.PathFilterGroup; import org.eclipse.jgit.util.FileUtils; import org.eclipse.osgi.util.NLS;
18,888
return; } perFolder = pruneFolderMap(perFolder, progress.newChild(1)); if (perFolder == null) { return; } updateGitIgnores(perFolder, progress.newChild(1)); } catch (CoreException e) { throw e; } catch (Exception e) { throw new CoreException(Activator.error( CoreText.IgnoreOperation_error, e)); } } /** * @return true if a gitignore file outside the workspace was changed. In * this case the caller may need to perform manual UI refreshes * because there was no ResourceChanged event. */ public boolean isGitignoreOutsideWSChanged() { return gitignoreOutsideWSChanged; } @Override public ISchedulingRule getSchedulingRule() { return schedulingRule; } private Map<IPath, Collection<String>> getFolderMap( IProgressMonitor monitor) { SubMonitor progress = SubMonitor.convert(monitor, paths.size()); Map<IPath, Collection<String>> result = new HashMap<>(); for (IPath path : paths) { if (progress.isCanceled()) { return null; } IPath parent = path.removeLastSegments(1); Collection<String> values = result.computeIfAbsent(parent, key -> new LinkedHashSet<>()); values.add(path.lastSegment()); progress.worked(1); } return result; } private Map<IPath, Collection<String>> pruneFolderMap( Map<IPath, Collection<String>> perFolder, IProgressMonitor monitor) throws IOException { SubMonitor progress = SubMonitor.convert(monitor, perFolder.size()); for (Map.Entry<IPath, Collection<String>> entry : perFolder .entrySet()) { pruneFolder(entry.getKey(), entry.getValue(), progress.newChild(1)); if (progress.isCanceled()) { return null; } } return perFolder; } private void pruneFolder(IPath folder, Collection<String> files, IProgressMonitor monitor) throws IOException { if (files.isEmpty()) { return; } Repository repository = RepositoryCache.INSTANCE.getRepository(folder); if (repository == null || repository.isBare()) { files.clear(); return; } WorkingTreeIterator treeIterator = IteratorService .createInitialIterator(repository); if (treeIterator == null) { files.clear(); return; } IPath repoRelativePath = folder.makeRelativeTo( new Path(repository.getWorkTree().getAbsolutePath())); if (repoRelativePath.equals(folder)) { files.clear(); return; } Collection<String> repoRelative = new HashSet<>(files.size()); for (String file : files) { repoRelative.add(repoRelativePath.append(file).toPortableString()); } // Remove all entries,then re-add only those found during the tree walk // that are not ignored already files.clear(); try (TreeWalk walk = new TreeWalk(repository)) { walk.addTree(treeIterator); walk.setFilter(PathFilterGroup.createFromStrings(repoRelative)); while (walk.next()) { if (monitor.isCanceled()) { return; } WorkingTreeIterator workingTreeIterator = walk.getTree(0, WorkingTreeIterator.class); if (repoRelative.contains(walk.getPathString())) { if (!workingTreeIterator.isEntryIgnored()) { files.add(walk.getNameString()); } } else if (workingTreeIterator.getEntryFileMode() .equals(FileMode.TREE)) { walk.enterSubtree(); } } } } private void updateGitIgnores(Map<IPath, Collection<String>> perFolder, IProgressMonitor monitor) throws CoreException, IOException { SubMonitor progress = SubMonitor.convert(monitor, perFolder.size() * 2); for (Map.Entry<IPath, Collection<String>> entry : perFolder .entrySet()) { if (progress.isCanceled()) { return; }
/******************************************************************************* * Copyright (C) 2009, Alex Blewitt <alex.blewitt@gmail.com> * Copyright (C) 2010, Jens Baumgart <jens.baumgart@sap.com> * Copyright (C) 2012, 2013 Robin Stocker <robin@nibor.org> * Copyright (C) 2015, Stephan Hackstedt <stephan.hackstedt@googlemail.com> * Copyright (C) 2016, Thomas Wolf <thomas.wolf@paranor.ch> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ package org.eclipse.egit.core.op; /** * IgnoreOperation adds resources to a .gitignore file * */ public class IgnoreOperation implements IEGitOperation { private final Collection<IPath> paths; private boolean gitignoreOutsideWSChanged; private ISchedulingRule schedulingRule; /** * construct an IgnoreOperation * * @param paths * @since 2.2 */ public IgnoreOperation(Collection<IPath> paths) { this.paths = paths; gitignoreOutsideWSChanged = false; schedulingRule = calcSchedulingRule(); } @Override public void execute(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, CoreText.IgnoreOperation_taskName, 3); try { Map<IPath, Collection<String>> perFolder = getFolderMap( progress.newChild(1)); if (perFolder == null) { return; } perFolder = pruneFolderMap(perFolder, progress.newChild(1)); if (perFolder == null) { return; } updateGitIgnores(perFolder, progress.newChild(1)); } catch (CoreException e) { throw e; } catch (Exception e) { throw new CoreException(Activator.error( CoreText.IgnoreOperation_error, e)); } } /** * @return true if a gitignore file outside the workspace was changed. In * this case the caller may need to perform manual UI refreshes * because there was no ResourceChanged event. */ public boolean isGitignoreOutsideWSChanged() { return gitignoreOutsideWSChanged; } @Override public ISchedulingRule getSchedulingRule() { return schedulingRule; } private Map<IPath, Collection<String>> getFolderMap( IProgressMonitor monitor) { SubMonitor progress = SubMonitor.convert(monitor, paths.size()); Map<IPath, Collection<String>> result = new HashMap<>(); for (IPath path : paths) { if (progress.isCanceled()) { return null; } IPath parent = path.removeLastSegments(1); Collection<String> values = result.computeIfAbsent(parent, key -> new LinkedHashSet<>()); values.add(path.lastSegment()); progress.worked(1); } return result; } private Map<IPath, Collection<String>> pruneFolderMap( Map<IPath, Collection<String>> perFolder, IProgressMonitor monitor) throws IOException { SubMonitor progress = SubMonitor.convert(monitor, perFolder.size()); for (Map.Entry<IPath, Collection<String>> entry : perFolder .entrySet()) { pruneFolder(entry.getKey(), entry.getValue(), progress.newChild(1)); if (progress.isCanceled()) { return null; } } return perFolder; } private void pruneFolder(IPath folder, Collection<String> files, IProgressMonitor monitor) throws IOException { if (files.isEmpty()) { return; } Repository repository = RepositoryCache.INSTANCE.getRepository(folder); if (repository == null || repository.isBare()) { files.clear(); return; } WorkingTreeIterator treeIterator = IteratorService .createInitialIterator(repository); if (treeIterator == null) { files.clear(); return; } IPath repoRelativePath = folder.makeRelativeTo( new Path(repository.getWorkTree().getAbsolutePath())); if (repoRelativePath.equals(folder)) { files.clear(); return; } Collection<String> repoRelative = new HashSet<>(files.size()); for (String file : files) { repoRelative.add(repoRelativePath.append(file).toPortableString()); } // Remove all entries,then re-add only those found during the tree walk // that are not ignored already files.clear(); try (TreeWalk walk = new TreeWalk(repository)) { walk.addTree(treeIterator); walk.setFilter(PathFilterGroup.createFromStrings(repoRelative)); while (walk.next()) { if (monitor.isCanceled()) { return; } WorkingTreeIterator workingTreeIterator = walk.getTree(0, WorkingTreeIterator.class); if (repoRelative.contains(walk.getPathString())) { if (!workingTreeIterator.isEntryIgnored()) { files.add(walk.getNameString()); } } else if (workingTreeIterator.getEntryFileMode() .equals(FileMode.TREE)) { walk.enterSubtree(); } } } } private void updateGitIgnores(Map<IPath, Collection<String>> perFolder, IProgressMonitor monitor) throws CoreException, IOException { SubMonitor progress = SubMonitor.convert(monitor, perFolder.size() * 2); for (Map.Entry<IPath, Collection<String>> entry : perFolder .entrySet()) { if (progress.isCanceled()) { return; }
IContainer container = ResourceUtil
5
2023-10-20 15:17:51+00:00
24k
Wind-Gone/Vodka
code/src/main/java/benchmark/olap/query/Q8.java
[ { "identifier": "OLAPTerminal", "path": "code/src/main/java/benchmark/olap/OLAPTerminal.java", "snippet": "public class OLAPTerminal implements Runnable {\n // public static AtomicInteger DeliveryBG=new AtomicInteger(0);\n public static AtomicLong oorderTableSize = new AtomicLong(benchmark.olap.qu...
import benchmark.olap.OLAPTerminal; import benchmark.oltp.OLTPClient; import config.CommonConfig; import org.apache.log4j.Logger; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import static benchmark.oltp.OLTPClient.gloabalSysCurrentTime; import static config.CommonConfig.DB_OCEANBASE;
14,793
package benchmark.olap.query; public class Q8 extends baseQuery { private static Logger log = Logger.getLogger(Q8.class); public double k; public double b; private int dbType; public Q8(int dbType) throws ParseException { super(); this.k = OLTPClient.k1; this.b = OLTPClient.b1; this.filterRate = benchmark.olap.OLAPClient.filterRate[7]; //o_entry_d=0.3115 this.dbType = dbType; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); } public String updateQuery() throws ParseException { // this.orderlineTSize=OLAPTerminal.orderLineTableSize; // this.orderTSize=OLAPTerminal.oorderTableSize; // this.olNotnullSize=OLAPTerminal.orderlineTableNotNullSize; this.k = OLTPClient.k1; this.b = OLTPClient.b1; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); return this.q; } public String getDeltaTimes() throws ParseException { double countNumber = OLAPTerminal.oorderTableSize.get() * filterRate; // log.info("#8:filterRate" + filterRate); // log.info("#1:countNumber"); SimpleDateFormat simFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date start_d = simFormat.parse("1998-08-02 00:00:00");//min date 1992-01-01,1995-01-01 Date start_d_1 = simFormat.parse("1992-01-01 00:00:00"); // log.info("#8: countNumber:" + countNumber + ",size:" + this.orderOriginSize); if (countNumber >= this.orderOriginSize) { // int s = (int) (((countNumber - this.b) / this.k) / 1000); // log.info("Q8-this.b" + this.b + ",this.k" + this.k); // log.info("Q8-1 s: " + s); // return simFormat.format(super.getDateAfter(start_d, s)); int s = (int) ((countNumber / OLAPTerminal.oorderTableSize.get()) * ((2405+OLTPClient.deltaDays) * 24 * 60 * 60)); // log.info("Q8-1 s: " + s); return simFormat.format(super.getDateAfter(start_d_1, s)); } else { // double historyNumber = this.orderOriginSize - countNumber; int s = (int) ((countNumber / this.orderOriginSize) * (2405 * 24 * 60 * 60)); // log.info("Q8-2 s: " + s); return simFormat.format(super.getDateAfter(start_d_1, s)); } } @Override public String getQuery() throws ParseException { // this.dynamicParam = getDeltaTimes(); String query; switch (this.dbType) {
package benchmark.olap.query; public class Q8 extends baseQuery { private static Logger log = Logger.getLogger(Q8.class); public double k; public double b; private int dbType; public Q8(int dbType) throws ParseException { super(); this.k = OLTPClient.k1; this.b = OLTPClient.b1; this.filterRate = benchmark.olap.OLAPClient.filterRate[7]; //o_entry_d=0.3115 this.dbType = dbType; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); } public String updateQuery() throws ParseException { // this.orderlineTSize=OLAPTerminal.orderLineTableSize; // this.orderTSize=OLAPTerminal.oorderTableSize; // this.olNotnullSize=OLAPTerminal.orderlineTableNotNullSize; this.k = OLTPClient.k1; this.b = OLTPClient.b1; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); return this.q; } public String getDeltaTimes() throws ParseException { double countNumber = OLAPTerminal.oorderTableSize.get() * filterRate; // log.info("#8:filterRate" + filterRate); // log.info("#1:countNumber"); SimpleDateFormat simFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date start_d = simFormat.parse("1998-08-02 00:00:00");//min date 1992-01-01,1995-01-01 Date start_d_1 = simFormat.parse("1992-01-01 00:00:00"); // log.info("#8: countNumber:" + countNumber + ",size:" + this.orderOriginSize); if (countNumber >= this.orderOriginSize) { // int s = (int) (((countNumber - this.b) / this.k) / 1000); // log.info("Q8-this.b" + this.b + ",this.k" + this.k); // log.info("Q8-1 s: " + s); // return simFormat.format(super.getDateAfter(start_d, s)); int s = (int) ((countNumber / OLAPTerminal.oorderTableSize.get()) * ((2405+OLTPClient.deltaDays) * 24 * 60 * 60)); // log.info("Q8-1 s: " + s); return simFormat.format(super.getDateAfter(start_d_1, s)); } else { // double historyNumber = this.orderOriginSize - countNumber; int s = (int) ((countNumber / this.orderOriginSize) * (2405 * 24 * 60 * 60)); // log.info("Q8-2 s: " + s); return simFormat.format(super.getDateAfter(start_d_1, s)); } } @Override public String getQuery() throws ParseException { // this.dynamicParam = getDeltaTimes(); String query; switch (this.dbType) {
case CommonConfig.DB_TIDB:
2
2023-10-22 11:22:32+00:00
24k
bowbahdoe/java-audio-stack
tritonus-share/src/main/java/dev/mccue/tritonus/share/sampled/file/TAudioOutputStream.java
[ { "identifier": "convertSign8", "path": "tritonus-share/src/main/java/dev/mccue/tritonus/share/sampled/TConversionTool.java", "snippet": "public static void convertSign8(byte[] buffer, int byteOffset, int sampleCount) {\r\n\tsampleCount+=byteOffset;\r\n\tfor (int i=byteOffset; i<sampleCount; i++) {\r\n\...
import java.io.IOException; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import static dev.mccue.tritonus.share.sampled.TConversionTool.convertSign8; import static dev.mccue.tritonus.share.sampled.TConversionTool.swapOrder16; import static dev.mccue.tritonus.share.sampled.TConversionTool.swapOrder24; import static dev.mccue.tritonus.share.sampled.TConversionTool.swapOrder32; import dev.mccue.tritonus.share.TDebug; import dev.mccue.tritonus.share.sampled.AudioUtils; import dev.mccue.tritonus.share.sampled.TConversionTool;
21,380
/* * TAudioOutputStream.java * * This file is part of Tritonus: http://www.tritonus.org/ */ /* * Copyright (c) 2000 by Matthias Pfisterer * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ /* |<--- this code is formatted to fit into 80 columns --->| */ package dev.mccue.tritonus.share.sampled.file; /** * Base class for classes implementing AudioOutputStream. * * @author Matthias Pfisterer */ public abstract class TAudioOutputStream implements AudioOutputStream { private AudioFormat m_audioFormat; private long m_lLength; // in bytes private long m_lCalculatedLength; private TDataOutputStream m_dataOutputStream; private boolean m_bDoBackPatching; private boolean m_bHeaderWritten; /** if this flag is set, do sign conversion for 8-bit PCM data */ private boolean m_doSignConversion; /** if this flag is set, do endian conversion for 16-bit PCM data */ private boolean m_doEndianConversion; protected TAudioOutputStream(AudioFormat audioFormat, long lLength, TDataOutputStream dataOutputStream, boolean bDoBackPatching) { m_audioFormat = audioFormat; m_lLength = lLength; m_lCalculatedLength = 0; m_dataOutputStream = dataOutputStream; m_bDoBackPatching = bDoBackPatching; m_bHeaderWritten = false; } /** * descendants should call this method if implicit sign conversion for 8-bit * data should be done */ protected void requireSign8bit(boolean signed) { if (m_audioFormat.getSampleSizeInBits() == 8 && AudioUtils.isPCM(m_audioFormat)) { boolean si = m_audioFormat.getEncoding().equals( AudioFormat.Encoding.PCM_SIGNED); m_doSignConversion = signed != si; } } /** * descendants should call this method if implicit endian conversion should * be done. Currently supported for 16, 24, and 32 bits per sample. */ protected void requireEndianness(boolean bigEndian) { int ssib = m_audioFormat.getSampleSizeInBits(); if ((ssib == 16 || ssib == 24 || ssib == 32) && AudioUtils.isPCM(m_audioFormat)) { m_doEndianConversion = bigEndian != m_audioFormat.isBigEndian(); } } public AudioFormat getFormat() { return m_audioFormat; } /** Gives length of the stream. * This value is in bytes. It may be AudioSystem.NOT_SPECIFIED * to express that the length is unknown. */ public long getLength() { return m_lLength; } /** Gives number of bytes already written. */ // IDEA: rename this to BytesWritten or something like that ? public long getCalculatedLength() { return m_lCalculatedLength; } protected TDataOutputStream getDataOutputStream() { return m_dataOutputStream; } /** do sign or endianness conversion */ private void handleImplicitConversions(byte[] abData, int nOffset, int nLength) { if (m_doSignConversion) { TConversionTool.convertSign8(abData, nOffset, nLength); } if (m_doEndianConversion) { switch (m_audioFormat.getSampleSizeInBits()) { case 16: TConversionTool.swapOrder16(abData, nOffset, nLength / 2); break; case 24: TConversionTool.swapOrder24(abData, nOffset, nLength / 3); break; case 32:
/* * TAudioOutputStream.java * * This file is part of Tritonus: http://www.tritonus.org/ */ /* * Copyright (c) 2000 by Matthias Pfisterer * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ /* |<--- this code is formatted to fit into 80 columns --->| */ package dev.mccue.tritonus.share.sampled.file; /** * Base class for classes implementing AudioOutputStream. * * @author Matthias Pfisterer */ public abstract class TAudioOutputStream implements AudioOutputStream { private AudioFormat m_audioFormat; private long m_lLength; // in bytes private long m_lCalculatedLength; private TDataOutputStream m_dataOutputStream; private boolean m_bDoBackPatching; private boolean m_bHeaderWritten; /** if this flag is set, do sign conversion for 8-bit PCM data */ private boolean m_doSignConversion; /** if this flag is set, do endian conversion for 16-bit PCM data */ private boolean m_doEndianConversion; protected TAudioOutputStream(AudioFormat audioFormat, long lLength, TDataOutputStream dataOutputStream, boolean bDoBackPatching) { m_audioFormat = audioFormat; m_lLength = lLength; m_lCalculatedLength = 0; m_dataOutputStream = dataOutputStream; m_bDoBackPatching = bDoBackPatching; m_bHeaderWritten = false; } /** * descendants should call this method if implicit sign conversion for 8-bit * data should be done */ protected void requireSign8bit(boolean signed) { if (m_audioFormat.getSampleSizeInBits() == 8 && AudioUtils.isPCM(m_audioFormat)) { boolean si = m_audioFormat.getEncoding().equals( AudioFormat.Encoding.PCM_SIGNED); m_doSignConversion = signed != si; } } /** * descendants should call this method if implicit endian conversion should * be done. Currently supported for 16, 24, and 32 bits per sample. */ protected void requireEndianness(boolean bigEndian) { int ssib = m_audioFormat.getSampleSizeInBits(); if ((ssib == 16 || ssib == 24 || ssib == 32) && AudioUtils.isPCM(m_audioFormat)) { m_doEndianConversion = bigEndian != m_audioFormat.isBigEndian(); } } public AudioFormat getFormat() { return m_audioFormat; } /** Gives length of the stream. * This value is in bytes. It may be AudioSystem.NOT_SPECIFIED * to express that the length is unknown. */ public long getLength() { return m_lLength; } /** Gives number of bytes already written. */ // IDEA: rename this to BytesWritten or something like that ? public long getCalculatedLength() { return m_lCalculatedLength; } protected TDataOutputStream getDataOutputStream() { return m_dataOutputStream; } /** do sign or endianness conversion */ private void handleImplicitConversions(byte[] abData, int nOffset, int nLength) { if (m_doSignConversion) { TConversionTool.convertSign8(abData, nOffset, nLength); } if (m_doEndianConversion) { switch (m_audioFormat.getSampleSizeInBits()) { case 16: TConversionTool.swapOrder16(abData, nOffset, nLength / 2); break; case 24: TConversionTool.swapOrder24(abData, nOffset, nLength / 3); break; case 32:
TConversionTool.swapOrder32(abData, nOffset, nLength / 4);
3
2023-10-19 14:09:37+00:00
24k
AstroDev2023/2023-studio-1-but-better
source/core/src/main/com/csse3200/game/missions/rewards/ClueReward.java
[ { "identifier": "GameMap", "path": "source/core/src/main/com/csse3200/game/areas/terrain/GameMap.java", "snippet": "public class GameMap {\n\t/**\n\t * The terrainFactory used for creating the game map\n\t */\n\tprivate final TerrainFactory terrainFactory;\n\t/**\n\t * The TiledMap that stores the creat...
import com.badlogic.gdx.math.GridPoint2; import com.badlogic.gdx.math.Vector2; import com.csse3200.game.areas.terrain.GameMap; import com.csse3200.game.areas.terrain.ShipPartTileComponent; import com.csse3200.game.areas.terrain.ShipPartTileFactory; import com.csse3200.game.areas.terrain.TerrainTile; import com.csse3200.game.components.items.ClueComponent; import com.csse3200.game.entities.Entity; import com.csse3200.game.entities.factories.ShipDebrisFactory; import com.csse3200.game.services.ServiceLocator; import com.csse3200.game.services.sound.EffectSoundFile; import com.csse3200.game.services.sound.InvalidSoundFileException; import com.csse3200.game.utils.math.RandomUtils; import java.util.List;
15,817
package com.csse3200.game.missions.rewards; /** * A reward that spawns a ShipPartTile and ShipDebris on collection. */ public class ClueReward extends ItemReward { private final Entity clueItem; public ClueReward(Entity clueItem) { super(List.of(clueItem)); this.clueItem = clueItem; } /** * When called, changes the isCollected variable to true and adds the reward items to the player's inventory. * Also spawns a ShipPartTile and ShipDebris around the base location contained in the Map Item. Also plays the * success sound effect */ @Override public void collect() { ServiceLocator.getEntityService().register(clueItem); ClueComponent clueComponent = clueItem.getComponent(ClueComponent.class); if (clueComponent != null) { Vector2 location = clueComponent.getCurrentBaseLocation(); // Generate tile & debris for the location generateTileAndDebris(location); } super.collect(); try {
package com.csse3200.game.missions.rewards; /** * A reward that spawns a ShipPartTile and ShipDebris on collection. */ public class ClueReward extends ItemReward { private final Entity clueItem; public ClueReward(Entity clueItem) { super(List.of(clueItem)); this.clueItem = clueItem; } /** * When called, changes the isCollected variable to true and adds the reward items to the player's inventory. * Also spawns a ShipPartTile and ShipDebris around the base location contained in the Map Item. Also plays the * success sound effect */ @Override public void collect() { ServiceLocator.getEntityService().register(clueItem); ClueComponent clueComponent = clueItem.getComponent(ClueComponent.class); if (clueComponent != null) { Vector2 location = clueComponent.getCurrentBaseLocation(); // Generate tile & debris for the location generateTileAndDebris(location); } super.collect(); try {
ServiceLocator.getSoundService().getEffectsMusicService().play(EffectSoundFile.SHIP_CLUE_SOLVED);
8
2023-10-17 22:34:04+00:00
24k
Amir-UL-Islam/eTBManager3-Backend
src/main/java/org/msh/etbm/services/cases/tag/ManualCaseTagsService.java
[ { "identifier": "Item", "path": "src/main/java/org/msh/etbm/commons/Item.java", "snippet": "public class Item<E> implements IsItem<E>, Displayable {\n\n private E id;\n private String name;\n\n /**\n * Default constructor\n */\n public Item() {\n super();\n }\n\n /**\n ...
import org.msh.etbm.commons.Item; import org.msh.etbm.commons.commands.CommandLog; import org.msh.etbm.commons.commands.CommandTypes; import org.msh.etbm.db.entities.Tag; import org.msh.etbm.db.entities.TbCase; import org.msh.etbm.db.entities.Workspace; import org.msh.etbm.services.cases.CaseActionEvent; import org.msh.etbm.services.cases.CaseLogHandler; import org.msh.etbm.services.session.usersession.UserRequestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.text.Normalizer; import java.util.ArrayList; import java.util.List; import java.util.UUID;
14,585
package org.msh.etbm.services.cases.tag; /** * Service to update cases tags links of manually assigned tags * Created by Mauricio on 25/07/2016. */ @Service public class ManualCaseTagsService { @PersistenceContext EntityManager entityManager; @Autowired UserRequestService userRequestService; @Autowired ApplicationContext applicationContext; @Transactional @CommandLog(handler = CaseLogHandler.class, type = CommandTypes.CASES_CASE_TAG) public ManualCaseTagsResponse updateTags(CaseTagsFormData data) { TbCase tbcase = entityManager.find(TbCase.class, data.getTbcaseId()); // response to be returned ManualCaseTagsResponse res = new ManualCaseTagsResponse(); // store previous list assignManualTags(tbcase.getTags(), res.getPrevManualTags()); // temporary tag list that will be assigned to the case at the end of this method List<Tag> newTagList = new ArrayList<Tag>(); // store the auto generated tags for (Tag t : tbcase.getTags()) { if (t.getSqlCondition() != null) { newTagList.add(t); } } // load existing tags if ((data.getTagIds() != null && !data.getTagIds().isEmpty())) { for (UUID tagId : data.getTagIds()) { newTagList.add(entityManager.find(Tag.class, tagId)); } } // create new tags and add to list if (data.getNewTags() != null && !data.getNewTags().isEmpty()) { newTagList.addAll(getNewTags(data.getNewTags())); } // set new tag list tbcase.setTags(newTagList); entityManager.persist(tbcase); // update version and synched field of tbcase, so on the next sync this tbcase // and its manual tags_case will be shared on file. entityManager.createNativeQuery("update tbcase " + "set synched = false, version=unix_timestamp()-1000000000 " + "where id = :caseId") .setParameter("caseId", tbcase.getId()) .executeUpdate(); // finish preparing response assignManualTags(tbcase.getTags(), res.getNewManualTags()); res.setCaseId(tbcase.getId()); res.setCaseDisplayString(tbcase.getDisplayString()); applicationContext.publishEvent(new CaseActionEvent(this, res)); return res; } private List<Tag> getNewTags(List<String> newTags) {
package org.msh.etbm.services.cases.tag; /** * Service to update cases tags links of manually assigned tags * Created by Mauricio on 25/07/2016. */ @Service public class ManualCaseTagsService { @PersistenceContext EntityManager entityManager; @Autowired UserRequestService userRequestService; @Autowired ApplicationContext applicationContext; @Transactional @CommandLog(handler = CaseLogHandler.class, type = CommandTypes.CASES_CASE_TAG) public ManualCaseTagsResponse updateTags(CaseTagsFormData data) { TbCase tbcase = entityManager.find(TbCase.class, data.getTbcaseId()); // response to be returned ManualCaseTagsResponse res = new ManualCaseTagsResponse(); // store previous list assignManualTags(tbcase.getTags(), res.getPrevManualTags()); // temporary tag list that will be assigned to the case at the end of this method List<Tag> newTagList = new ArrayList<Tag>(); // store the auto generated tags for (Tag t : tbcase.getTags()) { if (t.getSqlCondition() != null) { newTagList.add(t); } } // load existing tags if ((data.getTagIds() != null && !data.getTagIds().isEmpty())) { for (UUID tagId : data.getTagIds()) { newTagList.add(entityManager.find(Tag.class, tagId)); } } // create new tags and add to list if (data.getNewTags() != null && !data.getNewTags().isEmpty()) { newTagList.addAll(getNewTags(data.getNewTags())); } // set new tag list tbcase.setTags(newTagList); entityManager.persist(tbcase); // update version and synched field of tbcase, so on the next sync this tbcase // and its manual tags_case will be shared on file. entityManager.createNativeQuery("update tbcase " + "set synched = false, version=unix_timestamp()-1000000000 " + "where id = :caseId") .setParameter("caseId", tbcase.getId()) .executeUpdate(); // finish preparing response assignManualTags(tbcase.getTags(), res.getNewManualTags()); res.setCaseId(tbcase.getId()); res.setCaseDisplayString(tbcase.getDisplayString()); applicationContext.publishEvent(new CaseActionEvent(this, res)); return res; } private List<Tag> getNewTags(List<String> newTags) {
Workspace currentWorkspace = entityManager.find(Workspace.class, userRequestService.getUserSession().getWorkspaceId());
4
2023-10-23 13:47:54+00:00
24k
toel--/ocpp-backend-emulator
src/org/java_websocket/server/WebSocketServer.java
[ { "identifier": "AbstractWebSocket", "path": "src/org/java_websocket/AbstractWebSocket.java", "snippet": "public abstract class AbstractWebSocket extends WebSocketAdapter {\n\n /**\n * Logger instance\n *\n * @since 1.4.0\n */\n private final Logger log = LoggerFactory.getLogger(AbstractWebSoc...
import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.java_websocket.AbstractWebSocket; import org.java_websocket.SocketChannelIOHelper; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketFactory; import org.java_websocket.WebSocketImpl; import org.java_websocket.WebSocketServerFactory; import org.java_websocket.WrappedByteChannel; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.WebsocketNotConnectedException; import org.java_websocket.exceptions.WrappedIOException; import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.Handshakedata; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
21,582
* * @return The port number. */ public int getPort() { int port = getAddress().getPort(); if (port == 0 && server != null) { port = server.socket().getLocalPort(); } return port; } /** * Get the list of active drafts * * @return the available drafts for this server */ public List<Draft> getDraft() { return Collections.unmodifiableList(drafts); } /** * Set the requested maximum number of pending connections on the socket. The exact semantics are * implementation specific. The value provided should be greater than 0. If it is less than or * equal to 0, then an implementation specific default will be used. This option will be passed as * "backlog" parameter to {@link ServerSocket#bind(SocketAddress, int)} * * @since 1.5.0 * @param numberOfConnections the new number of allowed pending connections */ public void setMaxPendingConnections(int numberOfConnections) { maxPendingConnections = numberOfConnections; } /** * Returns the currently configured maximum number of pending connections. * * @see #setMaxPendingConnections(int) * @since 1.5.0 * @return the maximum number of pending connections */ public int getMaxPendingConnections() { return maxPendingConnections; } // Runnable IMPLEMENTATION ///////////////////////////////////////////////// public void run() { if (!doEnsureSingleThread()) { return; } if (!doSetupSelectorAndServerThread()) { return; } try { int shutdownCount = 5; int selectTimeout = 0; while (!selectorthread.isInterrupted() && shutdownCount != 0) { SelectionKey key = null; try { if (isclosed.get()) { selectTimeout = 5; } int keyCount = selector.select(selectTimeout); if (keyCount == 0 && isclosed.get()) { shutdownCount--; } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while (i.hasNext()) { key = i.next(); if (!key.isValid()) { continue; } if (key.isAcceptable()) { doAccept(key, i); continue; } if (key.isReadable() && !doRead(key, i)) { continue; } if (key.isWritable()) { doWrite(key); } } doAdditionalRead(); } catch (CancelledKeyException e) { // an other thread may cancel the key } catch (ClosedByInterruptException e) { return; // do the same stuff as when InterruptedException is thrown } catch (WrappedIOException ex) { handleIOException(key, ex.getConnection(), ex.getIOException()); } catch (IOException ex) { handleIOException(key, null, ex); } catch (InterruptedException e) { // FIXME controlled shutdown (e.g. take care of buffermanagement) Thread.currentThread().interrupt(); } } } catch (RuntimeException e) { // should hopefully never occur handleFatal(null, e); } finally { doServerShutdown(); } } /** * Do an additional read * * @throws InterruptedException thrown by taking a buffer * @throws IOException if an error happened during read */ private void doAdditionalRead() throws InterruptedException, IOException { WebSocketImpl conn; while (!iqueue.isEmpty()) { conn = iqueue.remove(0);
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.server; /** * <tt>WebSocketServer</tt> is an abstract class that only takes care of the * HTTP handshake portion of WebSockets. It's up to a subclass to add functionality/purpose to the * server. */ public abstract class WebSocketServer extends AbstractWebSocket implements Runnable { private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); /** * Logger instance * * @since 1.4.0 */ private final Logger log = LoggerFactory.getLogger(WebSocketServer.class); /** * Holds the list of active WebSocket connections. "Active" means WebSocket handshake is complete * and socket can be written to, or read from. */ private final Collection<WebSocket> connections; /** * The port number that this WebSocket server should listen on. Default is * WebSocketImpl.DEFAULT_PORT. */ private final InetSocketAddress address; /** * The socket channel for this WebSocket server. */ private ServerSocketChannel server; /** * The 'Selector' used to get event keys from the underlying socket. */ private Selector selector; /** * The Draft of the WebSocket protocol the Server is adhering to. */ private List<Draft> drafts; private Thread selectorthread; private final AtomicBoolean isclosed = new AtomicBoolean(false); protected List<WebSocketWorker> decoders; private List<WebSocketImpl> iqueue; private BlockingQueue<ByteBuffer> buffers; private int queueinvokes = 0; private final AtomicInteger queuesize = new AtomicInteger(0); private WebSocketServerFactory wsf = new DefaultWebSocketServerFactory(); /** * Attribute which allows you to configure the socket "backlog" parameter which determines how * many client connections can be queued. * * @since 1.5.0 */ private int maxPendingConnections = -1; /** * Creates a WebSocketServer that will attempt to listen on port <var>WebSocketImpl.DEFAULT_PORT</var>. * * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer() { this(new InetSocketAddress(WebSocketImpl.DEFAULT_PORT), AVAILABLE_PROCESSORS, null); } /** * Creates a WebSocketServer that will attempt to bind/listen on the given <var>address</var>. * * @param address The address to listen to * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer(InetSocketAddress address) { this(address, AVAILABLE_PROCESSORS, null); } /** * @param address The address (host:port) this server should listen on. * @param decodercount The number of {@link WebSocketWorker}s that will be used to process the * incoming network data. By default this will be <code>Runtime.getRuntime().availableProcessors()</code> * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer(InetSocketAddress address, int decodercount) { this(address, decodercount, null); } /** * @param address The address (host:port) this server should listen on. * @param drafts The versions of the WebSocket protocol that this server instance should comply * to. Clients that use an other protocol version will be rejected. * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer(InetSocketAddress address, List<Draft> drafts) { this(address, AVAILABLE_PROCESSORS, drafts); } /** * @param address The address (host:port) this server should listen on. * @param decodercount The number of {@link WebSocketWorker}s that will be used to process the * incoming network data. By default this will be <code>Runtime.getRuntime().availableProcessors()</code> * @param drafts The versions of the WebSocket protocol that this server instance should * comply to. Clients that use an other protocol version will be rejected. * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer(InetSocketAddress address, int decodercount, List<Draft> drafts) { this(address, decodercount, drafts, new HashSet<WebSocket>()); } /** * Creates a WebSocketServer that will attempt to bind/listen on the given <var>address</var>, and * comply with <tt>Draft</tt> version <var>draft</var>. * * @param address The address (host:port) this server should listen on. * @param decodercount The number of {@link WebSocketWorker}s that will be used to process * the incoming network data. By default this will be * <code>Runtime.getRuntime().availableProcessors()</code> * @param drafts The versions of the WebSocket protocol that this server instance * should comply to. Clients that use an other protocol version will * be rejected. * @param connectionscontainer Allows to specify a collection that will be used to store the * websockets in. <br> If you plan to often iterate through the * currently connected websockets you may want to use a collection * that does not require synchronization like a {@link * CopyOnWriteArraySet}. In that case make sure that you overload * {@link #removeConnection(WebSocket)} and {@link * #addConnection(WebSocket)}.<br> By default a {@link HashSet} will * be used. * @see #removeConnection(WebSocket) for more control over syncronized operation * @see <a href="https://github.com/TooTallNate/Java-WebSocket/wiki/Drafts" > more about * drafts</a> */ public WebSocketServer(InetSocketAddress address, int decodercount, List<Draft> drafts, Collection<WebSocket> connectionscontainer) { if (address == null || decodercount < 1 || connectionscontainer == null) { throw new IllegalArgumentException( "address and connectionscontainer must not be null and you need at least 1 decoder"); } if (drafts == null) { this.drafts = Collections.emptyList(); } else { this.drafts = drafts; } this.address = address; this.connections = connectionscontainer; setTcpNoDelay(false); setReuseAddr(false); iqueue = new LinkedList<>(); decoders = new ArrayList<>(decodercount); buffers = new LinkedBlockingQueue<>(); for (int i = 0; i < decodercount; i++) { WebSocketWorker ex = new WebSocketWorker(); decoders.add(ex); } } /** * Starts the server selectorthread that binds to the currently set port number and listeners for * WebSocket connection requests. Creates a fixed thread pool with the size {@link * WebSocketServer#AVAILABLE_PROCESSORS}<br> May only be called once. * <p> * Alternatively you can call {@link WebSocketServer#run()} directly. * * @throws IllegalStateException Starting an instance again */ public void start() { if (selectorthread != null) { throw new IllegalStateException(getClass().getName() + " can only be started once."); } new Thread(this).start(); } public void stop(int timeout) throws InterruptedException { stop(timeout, ""); } /** * Closes all connected clients sockets, then closes the underlying ServerSocketChannel, * effectively killing the server socket selectorthread, freeing the port the server was bound to * and stops all internal workerthreads. * <p> * If this method is called before the server is started it will never start. * * @param timeout Specifies how many milliseconds the overall close handshaking may take * altogether before the connections are closed without proper close * handshaking. * @param closeMessage Specifies message for remote client<br> * @throws InterruptedException Interrupt */ public void stop(int timeout, String closeMessage) throws InterruptedException { if (!isclosed.compareAndSet(false, true)) { // this also makes sure that no further connections will be added to this.connections return; } List<WebSocket> socketsToClose; // copy the connections in a list (prevent callback deadlocks) synchronized (connections) { socketsToClose = new ArrayList<>(connections); } for (WebSocket ws : socketsToClose) { ws.close(CloseFrame.GOING_AWAY, closeMessage); } wsf.close(); synchronized (this) { if (selectorthread != null && selector != null) { selector.wakeup(); selectorthread.join(timeout); } } } public void stop() throws InterruptedException { stop(0); } /** * Returns all currently connected clients. This collection does not allow any modification e.g. * removing a client. * * @return A unmodifiable collection of all currently connected clients * @since 1.3.8 */ @Override public Collection<WebSocket> getConnections() { synchronized (connections) { return Collections.unmodifiableCollection(new ArrayList<>(connections)); } } public InetSocketAddress getAddress() { return this.address; } /** * Gets the port number that this server listens on. * * @return The port number. */ public int getPort() { int port = getAddress().getPort(); if (port == 0 && server != null) { port = server.socket().getLocalPort(); } return port; } /** * Get the list of active drafts * * @return the available drafts for this server */ public List<Draft> getDraft() { return Collections.unmodifiableList(drafts); } /** * Set the requested maximum number of pending connections on the socket. The exact semantics are * implementation specific. The value provided should be greater than 0. If it is less than or * equal to 0, then an implementation specific default will be used. This option will be passed as * "backlog" parameter to {@link ServerSocket#bind(SocketAddress, int)} * * @since 1.5.0 * @param numberOfConnections the new number of allowed pending connections */ public void setMaxPendingConnections(int numberOfConnections) { maxPendingConnections = numberOfConnections; } /** * Returns the currently configured maximum number of pending connections. * * @see #setMaxPendingConnections(int) * @since 1.5.0 * @return the maximum number of pending connections */ public int getMaxPendingConnections() { return maxPendingConnections; } // Runnable IMPLEMENTATION ///////////////////////////////////////////////// public void run() { if (!doEnsureSingleThread()) { return; } if (!doSetupSelectorAndServerThread()) { return; } try { int shutdownCount = 5; int selectTimeout = 0; while (!selectorthread.isInterrupted() && shutdownCount != 0) { SelectionKey key = null; try { if (isclosed.get()) { selectTimeout = 5; } int keyCount = selector.select(selectTimeout); if (keyCount == 0 && isclosed.get()) { shutdownCount--; } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while (i.hasNext()) { key = i.next(); if (!key.isValid()) { continue; } if (key.isAcceptable()) { doAccept(key, i); continue; } if (key.isReadable() && !doRead(key, i)) { continue; } if (key.isWritable()) { doWrite(key); } } doAdditionalRead(); } catch (CancelledKeyException e) { // an other thread may cancel the key } catch (ClosedByInterruptException e) { return; // do the same stuff as when InterruptedException is thrown } catch (WrappedIOException ex) { handleIOException(key, ex.getConnection(), ex.getIOException()); } catch (IOException ex) { handleIOException(key, null, ex); } catch (InterruptedException e) { // FIXME controlled shutdown (e.g. take care of buffermanagement) Thread.currentThread().interrupt(); } } } catch (RuntimeException e) { // should hopefully never occur handleFatal(null, e); } finally { doServerShutdown(); } } /** * Do an additional read * * @throws InterruptedException thrown by taking a buffer * @throws IOException if an error happened during read */ private void doAdditionalRead() throws InterruptedException, IOException { WebSocketImpl conn; while (!iqueue.isEmpty()) { conn = iqueue.remove(0);
WrappedByteChannel c = ((WrappedByteChannel) conn.getChannel());
6
2023-10-16 23:10:55+00:00
24k
weibocom/rill-flow
rill-flow-web/src/main/java/com/weibo/rill/flow/configuration/OlympiceneConfiguration.java
[ { "identifier": "FunctionTask", "path": "rill-flow-interfaces/src/main/java/com/weibo/rill/flow/interfaces/model/task/FunctionTask.java", "snippet": "@Getter\n@Setter\n@JsonTypeName(\"function\")\npublic class FunctionTask extends BaseTask {\n String resourceName;\n String resourceProtocol;\n B...
import com.fasterxml.jackson.databind.jsontype.NamedType; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.weibo.rill.flow.interfaces.model.task.FunctionTask; import com.weibo.rill.flow.olympicene.core.event.Callback; import com.weibo.rill.flow.olympicene.core.model.task.*; import com.weibo.rill.flow.olympicene.core.runtime.DAGStorageProcedure; import com.weibo.rill.flow.olympicene.core.switcher.SwitcherManager; import com.weibo.rill.flow.olympicene.ddl.serialize.ObjectMapperFactory; import com.weibo.rill.flow.olympicene.storage.redis.api.RedisClient; import com.weibo.rill.flow.olympicene.storage.redis.lock.impl.RedisDistributedLocker; import com.weibo.rill.flow.olympicene.storage.save.impl.DAGInfoDeserializeService; import com.weibo.rill.flow.olympicene.storage.save.impl.RedisStorageProcedure; import com.weibo.rill.flow.olympicene.traversal.callback.DAGCallbackInfo; import com.weibo.rill.flow.olympicene.traversal.dispatcher.DAGDispatcher; import com.weibo.rill.flow.olympicene.traversal.helper.SameThreadExecutorService; import com.weibo.rill.flow.olympicene.traversal.mappings.JSONPathInputOutputMapping; import com.weibo.rill.flow.service.component.OlympiceneCallback; import com.weibo.rill.flow.service.component.RuntimeExecutorServiceProxy; import com.weibo.rill.flow.service.dconfs.BizDConfs; import com.weibo.rill.flow.service.decorator.ShareMdcFeatureDecoratorAssembler; import com.weibo.rill.flow.service.decorator.TaskDecoratingExecutorServiceDecorator; import com.weibo.rill.flow.service.dispatcher.FunctionTaskDispatcher; import com.weibo.rill.flow.service.invoke.HttpInvokeHelper; import com.weibo.rill.flow.service.manager.DAGClientPool; import com.weibo.rill.flow.service.mapping.JsonValueMapping; import com.weibo.rill.flow.service.statistic.BusinessTimeChecker; import com.weibo.rill.flow.service.statistic.TenantTaskStatistic; import com.weibo.rill.flow.service.storage.LongTermStorage; import com.weibo.rill.flow.service.storage.RuntimeRedisClients; import com.weibo.rill.flow.service.storage.RuntimeStorage; import com.weibo.rill.flow.service.util.IpUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; import java.util.List; import java.util.UUID; import java.util.concurrent.*;
18,954
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.configuration; @Configuration @AutoConfigureOrder(1) public class OlympiceneConfiguration { @Bean public LongTermStorage longTermStorage( @Autowired BizDConfs bizDConfs, @Autowired DAGClientPool dagClientPool) { return new LongTermStorage(bizDConfs, dagClientPool.getLongTermStorageClientIdToRedisClient()); } @Bean public Callback<DAGCallbackInfo> dagCallback( @Autowired HttpInvokeHelper httpInvokeHelper, @Autowired LongTermStorage longTermStorage, @Autowired @Qualifier("inputOutputMapping") JSONPathInputOutputMapping inputOutputMapping, @Autowired @Qualifier("callbackExecutor") ExecutorService callbackExecutor, @Autowired TenantTaskStatistic tenantTaskStatistic, @Autowired SwitcherManager switcherManagerImpl) { return new OlympiceneCallback(httpInvokeHelper, inputOutputMapping, longTermStorage, callbackExecutor, tenantTaskStatistic, switcherManagerImpl); } @Bean
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.configuration; @Configuration @AutoConfigureOrder(1) public class OlympiceneConfiguration { @Bean public LongTermStorage longTermStorage( @Autowired BizDConfs bizDConfs, @Autowired DAGClientPool dagClientPool) { return new LongTermStorage(bizDConfs, dagClientPool.getLongTermStorageClientIdToRedisClient()); } @Bean public Callback<DAGCallbackInfo> dagCallback( @Autowired HttpInvokeHelper httpInvokeHelper, @Autowired LongTermStorage longTermStorage, @Autowired @Qualifier("inputOutputMapping") JSONPathInputOutputMapping inputOutputMapping, @Autowired @Qualifier("callbackExecutor") ExecutorService callbackExecutor, @Autowired TenantTaskStatistic tenantTaskStatistic, @Autowired SwitcherManager switcherManagerImpl) { return new OlympiceneCallback(httpInvokeHelper, inputOutputMapping, longTermStorage, callbackExecutor, tenantTaskStatistic, switcherManagerImpl); } @Bean
public DAGDispatcher dagTaskDispatcher(@Autowired FunctionTaskDispatcher functionTaskDispatcher) {
10
2023-11-03 03:46:01+00:00
24k
estkme-group/InfiLPA
core/src/main/java/com/infineon/esim/lpa/core/LocalProfileAssistantCoreImpl.java
[ { "identifier": "ActivationCode", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/ActivationCode.java", "snippet": "public class ActivationCode implements Parcelable {\n private String activationCode;\n\n private final Boolean isValid;\n private String acFormat;\n private String ...
import com.infineon.esim.lpa.core.dtos.ActivationCode; import com.infineon.esim.lpa.core.dtos.DeviceInformation; import com.infineon.esim.lpa.core.dtos.EuiccInfo; import com.infineon.esim.lpa.core.dtos.ProfileDownloadSession; import com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata; import com.infineon.esim.lpa.core.dtos.result.local.ClearNotificationsResult; import com.infineon.esim.lpa.core.dtos.result.local.DeleteResult; import com.infineon.esim.lpa.core.dtos.result.local.DisableResult; import com.infineon.esim.lpa.core.dtos.result.local.EnableResult; import com.infineon.esim.lpa.core.dtos.result.local.SetNicknameResult; import com.infineon.esim.lpa.core.dtos.result.remote.AuthenticateResult; import com.infineon.esim.lpa.core.dtos.result.remote.CancelSessionResult; import com.infineon.esim.lpa.core.dtos.result.remote.DownloadResult; import com.infineon.esim.lpa.core.dtos.result.remote.HandleNotificationsResult; import com.infineon.esim.lpa.core.dtos.result.remote.RemoteError; import com.infineon.esim.lpa.core.es10.Es10Interface; import com.infineon.esim.lpa.core.es10.EuiccChannel; import com.infineon.esim.lpa.core.es9plus.Es9PlusInterface; import com.infineon.esim.lpa.core.worker.local.ClearAllNotificationsWorker; import com.infineon.esim.lpa.core.worker.local.DeleteProfileWorker; import com.infineon.esim.lpa.core.worker.local.DisableProfileWorker; import com.infineon.esim.lpa.core.worker.local.EnableProfileWorker; import com.infineon.esim.lpa.core.worker.local.GetEidWorker; import com.infineon.esim.lpa.core.worker.local.GetEuiccInfo2Worker; import com.infineon.esim.lpa.core.worker.local.ListProfilesWorker; import com.infineon.esim.lpa.core.worker.local.SetNicknameWorker; import com.infineon.esim.lpa.core.worker.remote.AuthenticateWorker; import com.infineon.esim.lpa.core.worker.remote.CancelSessionWorker; import com.infineon.esim.lpa.core.worker.remote.DownloadProfileWorker; import com.infineon.esim.lpa.core.worker.remote.HandleNotificationsWorker; import com.infineon.esim.util.Log; import java.util.List;
20,837
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core; public class LocalProfileAssistantCoreImpl implements LocalProfileAssistantCore { private static final String TAG = LocalProfileAssistantCoreImpl.class.getName(); private ProfileDownloadSession profileDownloadSession = null; private Es10Interface es10Interface; private Es9PlusInterface es9PlusInterface; public LocalProfileAssistantCoreImpl() { }
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core; public class LocalProfileAssistantCoreImpl implements LocalProfileAssistantCore { private static final String TAG = LocalProfileAssistantCoreImpl.class.getName(); private ProfileDownloadSession profileDownloadSession = null; private Es10Interface es10Interface; private Es9PlusInterface es9PlusInterface; public LocalProfileAssistantCoreImpl() { }
public void setEuiccChannel(EuiccChannel euiccChannel) {
16
2023-11-06 02:41:13+00:00
24k
By1337/BAuction
Core/src/main/java/org/by1337/bauction/db/kernel/MysqlDb.java
[ { "identifier": "Main", "path": "Core/src/main/java/org/by1337/bauction/Main.java", "snippet": "public final class Main extends JavaPlugin {\n private static Message message;\n private static Plugin instance;\n private static Config cfg;\n private static FileDataBase storage;\n private Co...
import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; import org.by1337.api.util.NameKey; import org.by1337.bauction.Main; import org.by1337.bauction.auc.SellItem; import org.by1337.bauction.auc.UnsoldItem; import org.by1337.bauction.db.action.Action; import org.by1337.bauction.db.action.ActionGiveMoney; import org.by1337.bauction.db.action.ActionType; import org.by1337.bauction.db.event.BuyItemCountEvent; import org.by1337.bauction.db.event.BuyItemEvent; import org.by1337.bauction.network.PacketConnection; import org.by1337.bauction.network.PacketIn; import org.by1337.bauction.network.PacketListener; import org.by1337.bauction.network.PacketType; import org.by1337.bauction.network.in.*; import org.by1337.bauction.network.out.*; import org.by1337.bauction.util.Category; import org.by1337.bauction.util.MoneyGiver; import org.by1337.bauction.util.Sorting; import org.by1337.bauction.util.UniqueName; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.sql.*; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue;
14,623
expired BIGINT NOT NULL ) """, """ CREATE TABLE IF NOT EXISTS sell_items ( uuid VARBINARY(36) NOT NULL PRIMARY KEY, seller_uuid VARCHAR(36) NOT NULL, item TEXT NOT NULL, seller_name VARCHAR(50) NOT NULL, price DOUBLE NOT NULL, sale_by_the_piece BOOLEAN NOT NULL, tags TEXT NOT NULL, time_listed_for_sale BIGINT NOT NULL, removal_date BIGINT NOT NULL, material VARCHAR(50) NOT NULL, amount TINYINT NOT NULL, price_for_one DOUBLE NOT NULL, sell_for TEXT NOT NULL, server VARBINARY(36) NOT NULL ) """, """ CREATE TABLE IF NOT EXISTS users ( uuid VARBINARY(36) NOT NULL PRIMARY KEY, name VARCHAR(50) NOT NULL, deal_count INT NOT NULL, deal_sum DOUBLE NOT NULL ) """, """ CREATE TABLE IF NOT EXISTS logs ( time BIGINT NOT NULL, type VARCHAR(20) NOT NULL, owner VARCHAR(36) NOT NULL, server VARCHAR(36) NOT NULL, uuid VARCHAR(36), INDEX idx_time (time) ) """ //</editor-fold> }; for (String sql : createTableStatements) { try (PreparedStatement stat = connection.prepareStatement(sql.replace("\n", ""))) { stat.execute(); } } sqlExecuteTask = //<editor-fold desc="sql execute task" defaultstate="collapsed"> new BukkitRunnable() { @Override public void run() { String sql = null; for (int i = 0; i < 200; i++) { sql = sqlQueue.poll(); if (sql == null) { break; } try (PreparedStatement stat = connection.prepareStatement(sql)) { stat.execute(); } catch (SQLException e) { Main.getMessage().error(e); } } if (sql != null) { Main.getMessage().warning("the number of sql requests is more than 200!"); } } }.runTaskTimerAsynchronously(Main.getInstance(), 10, 1); //</editor-fold> if (isHead) { logClearTask = Bukkit.getScheduler().runTaskTimerAsynchronously( Main.getInstance(), () -> sqlQueue.offer("DELETE FROM logs WHERE time < " + (System.currentTimeMillis() - 3600000L / 2)), 500, 3600000L / 2 ); } else { logClearTask = null; } updateTask = Bukkit.getScheduler().runTaskTimerAsynchronously(Main.getInstance(), () -> update(), 40, 40); } @Override protected void unsoldItemRemover() { if (removeExpiredItems) { unsoldItemRemChecker = () -> { long time = System.currentTimeMillis(); try { long sleep = 50L * 5; int removed = 0; while (getUnsoldItemsSize() > 0) { UnsoldItem unsoldItem = getFirstUnsoldItem(); if (unsoldItem.getDeleteVia() < time) { if (isHead) { removeUnsoldItem(unsoldItem.getUniqueName()); } else { super.removeUnsoldItem(unsoldItem.getUniqueName()); } removed++; if (removed >= 30) break; } else { sleep = Math.min((unsoldItem.getDeleteVia() - time) + 50, 50L * 100); // 100 ticks break; } } if (unsoldItemRemCheckerTask.isCancelled()) return; unsoldItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), unsoldItemRemChecker, sleep / 50); } catch (Exception e) { Main.getMessage().error(e); } }; unsoldItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), unsoldItemRemChecker, 0); } } @Override
package org.by1337.bauction.db.kernel; public class MysqlDb extends FileDataBase implements PacketListener { private final Connection connection; private final PacketConnection packetConnection; private final UUID server = UUID.randomUUID(); private final ConcurrentLinkedQueue<String> sqlQueue = new ConcurrentLinkedQueue<>(); private final BukkitTask sqlExecuteTask; @Nullable private final BukkitTask logClearTask; private final BukkitTask updateTask; private final boolean isHead; private long lastLogCheck; private final MoneyGiver moneyGiver; public MysqlDb(Map<NameKey, Category> categoryMap, Map<NameKey, Sorting> sortingMap, String host, String name, String user, String password, int port) throws SQLException { super(categoryMap, sortingMap); isHead = Main.getDbCfg().getContext().getAsBoolean("mysql-settings.is-head"); packetConnection = new PacketConnection(this); moneyGiver = new MoneyGiver(this); connection = DriverManager.getConnection( "jdbc:mysql://" + host + ":" + port + "/" + name + "?useUnicode=true&characterEncoding=utf8&autoReconnect=true", user, password ); String[] createTableStatements = { //<editor-fold desc="create tables sqls" defaultstate="collapsed"> """ CREATE TABLE IF NOT EXISTS give_money (server VARBINARY(36) NOT NULL, uuid VARCHAR(36) NOT NULL, count DOUBLE NOT NULL) """, """ CREATE TABLE IF NOT EXISTS unsold_items ( uuid VARBINARY(36) NOT NULL PRIMARY KEY, seller_uuid VARCHAR(36) NOT NULL, item TEXT NOT NULL, delete_via BIGINT NOT NULL, expired BIGINT NOT NULL ) """, """ CREATE TABLE IF NOT EXISTS sell_items ( uuid VARBINARY(36) NOT NULL PRIMARY KEY, seller_uuid VARCHAR(36) NOT NULL, item TEXT NOT NULL, seller_name VARCHAR(50) NOT NULL, price DOUBLE NOT NULL, sale_by_the_piece BOOLEAN NOT NULL, tags TEXT NOT NULL, time_listed_for_sale BIGINT NOT NULL, removal_date BIGINT NOT NULL, material VARCHAR(50) NOT NULL, amount TINYINT NOT NULL, price_for_one DOUBLE NOT NULL, sell_for TEXT NOT NULL, server VARBINARY(36) NOT NULL ) """, """ CREATE TABLE IF NOT EXISTS users ( uuid VARBINARY(36) NOT NULL PRIMARY KEY, name VARCHAR(50) NOT NULL, deal_count INT NOT NULL, deal_sum DOUBLE NOT NULL ) """, """ CREATE TABLE IF NOT EXISTS logs ( time BIGINT NOT NULL, type VARCHAR(20) NOT NULL, owner VARCHAR(36) NOT NULL, server VARCHAR(36) NOT NULL, uuid VARCHAR(36), INDEX idx_time (time) ) """ //</editor-fold> }; for (String sql : createTableStatements) { try (PreparedStatement stat = connection.prepareStatement(sql.replace("\n", ""))) { stat.execute(); } } sqlExecuteTask = //<editor-fold desc="sql execute task" defaultstate="collapsed"> new BukkitRunnable() { @Override public void run() { String sql = null; for (int i = 0; i < 200; i++) { sql = sqlQueue.poll(); if (sql == null) { break; } try (PreparedStatement stat = connection.prepareStatement(sql)) { stat.execute(); } catch (SQLException e) { Main.getMessage().error(e); } } if (sql != null) { Main.getMessage().warning("the number of sql requests is more than 200!"); } } }.runTaskTimerAsynchronously(Main.getInstance(), 10, 1); //</editor-fold> if (isHead) { logClearTask = Bukkit.getScheduler().runTaskTimerAsynchronously( Main.getInstance(), () -> sqlQueue.offer("DELETE FROM logs WHERE time < " + (System.currentTimeMillis() - 3600000L / 2)), 500, 3600000L / 2 ); } else { logClearTask = null; } updateTask = Bukkit.getScheduler().runTaskTimerAsynchronously(Main.getInstance(), () -> update(), 40, 40); } @Override protected void unsoldItemRemover() { if (removeExpiredItems) { unsoldItemRemChecker = () -> { long time = System.currentTimeMillis(); try { long sleep = 50L * 5; int removed = 0; while (getUnsoldItemsSize() > 0) { UnsoldItem unsoldItem = getFirstUnsoldItem(); if (unsoldItem.getDeleteVia() < time) { if (isHead) { removeUnsoldItem(unsoldItem.getUniqueName()); } else { super.removeUnsoldItem(unsoldItem.getUniqueName()); } removed++; if (removed >= 30) break; } else { sleep = Math.min((unsoldItem.getDeleteVia() - time) + 50, 50L * 100); // 100 ticks break; } } if (unsoldItemRemCheckerTask.isCancelled()) return; unsoldItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), unsoldItemRemChecker, sleep / 50); } catch (Exception e) { Main.getMessage().error(e); } }; unsoldItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), unsoldItemRemChecker, 0); } } @Override
protected void expiredItem(SellItem item) {
1
2023-11-08 18:25:18+00:00
24k
momentohq/momento-dynamodb-lock-client
src/main/java/com/amazonaws/services/dynamodbv2/MomentoDynamoDBLockClient.java
[ { "identifier": "LockItemUtils", "path": "src/main/java/momento/lock/client/LockItemUtils.java", "snippet": "public class LockItemUtils {\n\n private static final ObjectMapper MAPPER = new ObjectMapper();\n\n public static byte[] serialize(final MomentoLockItem lockItem) {\n try {\n ...
import com.amazonaws.services.dynamodbv2.model.LockCurrentlyUnavailableException; import com.amazonaws.services.dynamodbv2.model.LockNotGrantedException; import com.amazonaws.services.dynamodbv2.util.LockClientUtils; import momento.lock.client.LockItemUtils; import momento.lock.client.LockStorage; import momento.lock.client.MomentoDynamoDBLockClientOptions; import momento.lock.client.MomentoLockClient; import momento.lock.client.MomentoLockClientHeartbeatHandler; import momento.lock.client.MomentoLockItem; import momento.lock.client.NoopDynamoDbClient; import momento.lock.client.model.MomentoClientException; import momento.sdk.CacheClient; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import software.amazon.awssdk.core.exception.SdkClientException; import java.io.Closeable; import java.io.IOException; import java.time.Duration; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Stream;
19,467
/* * This Java source file was generated by the Gradle 'init' task. */ package com.amazonaws.services.dynamodbv2; /** * <p> * Provides a simple library for using DynamoDB's consistent read/write feature to use it for managing distributed locks. * </p> * <p> * In order to use this library, the client must create a cache in Momento, although the library provides a convenience method * for creating that cache (createLockCache.) * </p> * <p> * Here is some example code for how to use the lock client for leader election to work on a resource called "host-2" (it * assumes you already have a Momento cache named lockCache, which can be created with the * {@code createLockCache} helper method): * </p> * <pre> * {@code * AmazonDynamoDBLockClient lockClient = new MomentoDynamoDBLockClient( * MomentoDynamoDBLockClientOptions.builder(dynamoDBClient, "lockTable").build(); * try { * // Attempt to acquire the lock indefinitely, polling Momento every 2 seconds for the lock * LockItem lockItem = lockClient.acquireLock( * AcquireLockOptions.builder("host-2") * .withRefreshPeriod(120L) * .withAdditionalTimeToWaitForLock(Long.MAX_VALUE / 2L) * .withTimeUnit(TimeUnit.MILLISECONDS) * .build()); * if (!lockItem.isExpired()) { * // do business logic, you can call lockItem.isExpired() to periodically check to make sure you still have the lock * // the background thread will keep the lock valid for you by sending heartbeats (default is every 5 seconds) * } * } catch (LockNotGrantedException x) { * // Should only be thrown if the lock could not be acquired for Long.MAX_VALUE / 2L milliseconds. * } * } * </pre> */ public class MomentoDynamoDBLockClient extends AmazonDynamoDBLockClient implements Closeable { private static final Log logger = LogFactory.getLog(MomentoDynamoDBLockClient.class); private final String lockCacheName; private final CacheClient cacheClient; private static final long DEFAULT_BUFFER_MS = 1000; private static final int TTL_GRACE_MILLIS = 200; private final long leaseDurationMillis; private final long heartbeatPeriodInMilliseconds; private final String owner; private final ConcurrentHashMap<String, Thread> sessionMonitors; private final LockStorage lockStorage; private final Function<String, ThreadFactory> namedThreadCreator; private ScheduledExecutorService heartbeatExecutor; private MomentoLockClientHeartbeatHandler heartbeatHandler; private final MomentoLockClient momentoLockClient; private final Boolean holdLockOnServiceUnavailable; private final ScheduledExecutorService executorService; public MomentoDynamoDBLockClient(final MomentoDynamoDBLockClientOptions lockClientOptions) { super(AmazonDynamoDBLockClientOptions.builder(new NoopDynamoDbClient(), lockClientOptions.getCacheName()).build()); Objects.requireNonNull(lockClientOptions.getTableName(), "Table name cannot be null"); Objects.requireNonNull(lockClientOptions.getCacheName(), "Cache name cannot be null"); Objects.requireNonNull(lockClientOptions.getOwnerName(), "Owner name cannot be null"); Objects.requireNonNull(lockClientOptions.getTimeUnit(), "Time unit cannot be null"); Objects.requireNonNull(lockClientOptions.getPartitionKeyName(), "Partition Key Name cannot be null"); Objects.requireNonNull(lockClientOptions.getSortKeyName(), "Sort Key Name cannot be null (use Optional.absent())"); Objects.requireNonNull(lockClientOptions.getNamedThreadCreator(), "Named thread creator cannot be null"); this.lockCacheName = lockClientOptions.getCacheName(); this.sessionMonitors = new ConcurrentHashMap<>(); this.owner = lockClientOptions.getOwnerName(); this.leaseDurationMillis = lockClientOptions.getTimeUnit().toMillis(lockClientOptions.getLeaseDuration()); this.heartbeatPeriodInMilliseconds = lockClientOptions.getTimeUnit().toMillis(lockClientOptions.getHeartbeatPeriod()); this.namedThreadCreator = lockClientOptions.getNamedThreadCreator(); this.holdLockOnServiceUnavailable = lockClientOptions.getHoldLockOnServiceUnavailable(); this.cacheClient = CacheClient.create(lockClientOptions.getCredentialProvider(), lockClientOptions.getConfiguration(), Duration.ofMillis(this.leaseDurationMillis)); this.momentoLockClient = new MomentoLockClient(cacheClient, lockCacheName); this.lockStorage = new LockStorage(); this.heartbeatHandler = new MomentoLockClientHeartbeatHandler(this.lockStorage, this.cacheClient, this.lockCacheName, Duration.ofMillis(leaseDurationMillis), holdLockOnServiceUnavailable, lockClientOptions.getTotalNumBackgroundThreadsForHeartbeating()); if (lockClientOptions.getCreateHeartbeatBackgroundThread()) { if (this.leaseDurationMillis < 2 * this.heartbeatPeriodInMilliseconds) { throw new IllegalArgumentException("Heartbeat period must be no more than half the length of the Lease Duration, " + "or locks might expire due to the heartbeat thread taking too long to update them (recommendation is to make it much greater, for example " + "4+ times greater)"); } this.heartbeatExecutor = new ScheduledThreadPoolExecutor(1); heartbeatExecutor.scheduleAtFixedRate(this.heartbeatHandler, 0, heartbeatPeriodInMilliseconds, TimeUnit.MILLISECONDS); } this.executorService = new ScheduledThreadPoolExecutor(lockClientOptions.getTotalNumThreadsForAcquiringLocks()); } public Stream<LockItem> getAllLocksFromDynamoDB(final boolean deleteOnRelease) { throw new UnsupportedOperationException("This operation is not available on" + " Momento DynamoDB lock client"); } public Stream<LockItem> getLocksByPartitionKey(String key, final boolean deleteOnRelease) { throw new UnsupportedOperationException("This operation is not available on" + " Momento DynamoDB lock client"); } public void createLockCache(final String cacheName) { try { momentoLockClient.createLockCache(cacheName);
/* * This Java source file was generated by the Gradle 'init' task. */ package com.amazonaws.services.dynamodbv2; /** * <p> * Provides a simple library for using DynamoDB's consistent read/write feature to use it for managing distributed locks. * </p> * <p> * In order to use this library, the client must create a cache in Momento, although the library provides a convenience method * for creating that cache (createLockCache.) * </p> * <p> * Here is some example code for how to use the lock client for leader election to work on a resource called "host-2" (it * assumes you already have a Momento cache named lockCache, which can be created with the * {@code createLockCache} helper method): * </p> * <pre> * {@code * AmazonDynamoDBLockClient lockClient = new MomentoDynamoDBLockClient( * MomentoDynamoDBLockClientOptions.builder(dynamoDBClient, "lockTable").build(); * try { * // Attempt to acquire the lock indefinitely, polling Momento every 2 seconds for the lock * LockItem lockItem = lockClient.acquireLock( * AcquireLockOptions.builder("host-2") * .withRefreshPeriod(120L) * .withAdditionalTimeToWaitForLock(Long.MAX_VALUE / 2L) * .withTimeUnit(TimeUnit.MILLISECONDS) * .build()); * if (!lockItem.isExpired()) { * // do business logic, you can call lockItem.isExpired() to periodically check to make sure you still have the lock * // the background thread will keep the lock valid for you by sending heartbeats (default is every 5 seconds) * } * } catch (LockNotGrantedException x) { * // Should only be thrown if the lock could not be acquired for Long.MAX_VALUE / 2L milliseconds. * } * } * </pre> */ public class MomentoDynamoDBLockClient extends AmazonDynamoDBLockClient implements Closeable { private static final Log logger = LogFactory.getLog(MomentoDynamoDBLockClient.class); private final String lockCacheName; private final CacheClient cacheClient; private static final long DEFAULT_BUFFER_MS = 1000; private static final int TTL_GRACE_MILLIS = 200; private final long leaseDurationMillis; private final long heartbeatPeriodInMilliseconds; private final String owner; private final ConcurrentHashMap<String, Thread> sessionMonitors; private final LockStorage lockStorage; private final Function<String, ThreadFactory> namedThreadCreator; private ScheduledExecutorService heartbeatExecutor; private MomentoLockClientHeartbeatHandler heartbeatHandler; private final MomentoLockClient momentoLockClient; private final Boolean holdLockOnServiceUnavailable; private final ScheduledExecutorService executorService; public MomentoDynamoDBLockClient(final MomentoDynamoDBLockClientOptions lockClientOptions) { super(AmazonDynamoDBLockClientOptions.builder(new NoopDynamoDbClient(), lockClientOptions.getCacheName()).build()); Objects.requireNonNull(lockClientOptions.getTableName(), "Table name cannot be null"); Objects.requireNonNull(lockClientOptions.getCacheName(), "Cache name cannot be null"); Objects.requireNonNull(lockClientOptions.getOwnerName(), "Owner name cannot be null"); Objects.requireNonNull(lockClientOptions.getTimeUnit(), "Time unit cannot be null"); Objects.requireNonNull(lockClientOptions.getPartitionKeyName(), "Partition Key Name cannot be null"); Objects.requireNonNull(lockClientOptions.getSortKeyName(), "Sort Key Name cannot be null (use Optional.absent())"); Objects.requireNonNull(lockClientOptions.getNamedThreadCreator(), "Named thread creator cannot be null"); this.lockCacheName = lockClientOptions.getCacheName(); this.sessionMonitors = new ConcurrentHashMap<>(); this.owner = lockClientOptions.getOwnerName(); this.leaseDurationMillis = lockClientOptions.getTimeUnit().toMillis(lockClientOptions.getLeaseDuration()); this.heartbeatPeriodInMilliseconds = lockClientOptions.getTimeUnit().toMillis(lockClientOptions.getHeartbeatPeriod()); this.namedThreadCreator = lockClientOptions.getNamedThreadCreator(); this.holdLockOnServiceUnavailable = lockClientOptions.getHoldLockOnServiceUnavailable(); this.cacheClient = CacheClient.create(lockClientOptions.getCredentialProvider(), lockClientOptions.getConfiguration(), Duration.ofMillis(this.leaseDurationMillis)); this.momentoLockClient = new MomentoLockClient(cacheClient, lockCacheName); this.lockStorage = new LockStorage(); this.heartbeatHandler = new MomentoLockClientHeartbeatHandler(this.lockStorage, this.cacheClient, this.lockCacheName, Duration.ofMillis(leaseDurationMillis), holdLockOnServiceUnavailable, lockClientOptions.getTotalNumBackgroundThreadsForHeartbeating()); if (lockClientOptions.getCreateHeartbeatBackgroundThread()) { if (this.leaseDurationMillis < 2 * this.heartbeatPeriodInMilliseconds) { throw new IllegalArgumentException("Heartbeat period must be no more than half the length of the Lease Duration, " + "or locks might expire due to the heartbeat thread taking too long to update them (recommendation is to make it much greater, for example " + "4+ times greater)"); } this.heartbeatExecutor = new ScheduledThreadPoolExecutor(1); heartbeatExecutor.scheduleAtFixedRate(this.heartbeatHandler, 0, heartbeatPeriodInMilliseconds, TimeUnit.MILLISECONDS); } this.executorService = new ScheduledThreadPoolExecutor(lockClientOptions.getTotalNumThreadsForAcquiringLocks()); } public Stream<LockItem> getAllLocksFromDynamoDB(final boolean deleteOnRelease) { throw new UnsupportedOperationException("This operation is not available on" + " Momento DynamoDB lock client"); } public Stream<LockItem> getLocksByPartitionKey(String key, final boolean deleteOnRelease) { throw new UnsupportedOperationException("This operation is not available on" + " Momento DynamoDB lock client"); } public void createLockCache(final String cacheName) { try { momentoLockClient.createLockCache(cacheName);
} catch (MomentoClientException e) {
7
2023-11-07 03:56:11+00:00
24k
FallenDeity/GameEngine2DJava
src/main/java/engine/scenes/LevelEditorScene.java
[ { "identifier": "Sprite", "path": "src/main/java/engine/components/sprites/Sprite.java", "snippet": "public class Sprite {\n\tprivate Texture texture = null;\n\tprivate float width = 0, height = 0;\n\tprivate Vector2f[] texCoords =\n\t\t\tnew Vector2f[]{\n\t\t\t\t\tnew Vector2f(1, 1), new Vector2f(1, 0)...
import engine.components.*; import engine.components.sprites.Sprite; import engine.components.sprites.SpriteSheet; import engine.editor.JImGui; import engine.physics2d.components.Box2DCollider; import engine.physics2d.components.RigidBody2D; import engine.physics2d.enums.BodyType; import engine.renderer.Sound; import engine.ruby.Window; import engine.util.AssetPool; import engine.util.CONSTANTS; import engine.util.PipeDirection; import engine.util.Prefabs; import imgui.ImGui; import imgui.ImVec2; import org.joml.Vector2f; import java.io.File; import java.util.ArrayList; import java.util.List;
16,086
package engine.scenes; public class LevelEditorScene extends Scene { private final SpriteSheet blocks; private final GameObject editor; public LevelEditorScene() { editor = createGameObject("Editor"); editor.setNotSerializable(); editor.addComponent(new MouseControls()); editor.addComponent(new KeyControls()); editor.addComponent(new GridLines()); editor.addComponent(new EditorCamera(camera)); editor.addComponent(new GizmoSystem(this, editor)); blocks = AssetPool.getSpriteSheet(CONSTANTS.BLOCK_SHEET_PATH.getValue(), 16, 16, 0, 81); addGameObjectToScene(editor); AssetPool.getSound(CONSTANTS.SOUNDS_PATH.getValue() + "main-theme-overworld.ogg").stop(); } public boolean gizmoActive() { GizmoSystem gizmoSystem = editor.getComponent(GizmoSystem.class); return gizmoSystem.gizmoActive(); } private List<Sound> loadSounds() { String sound_dir = CONSTANTS.SOUNDS_PATH.getValue(); File[] files = new File(sound_dir).listFiles(); if (files != null) { for (File file : files) { if (file.isFile() && file.getName().endsWith(".ogg")) { String path = file.getAbsolutePath(); AssetPool.getSound(path, false); } } } return new ArrayList<>(AssetPool.getSounds()); } private void addBlock(SpriteSheet sheet, int i, ImVec2 windowSize, ImVec2 itemSpacing, float windowX, boolean decoration) { Sprite sprite = sheet.getSprite(i); float spriteWidth = sprite.getWidth() * 3, spriteHeight = sprite.getHeight() * 3; Vector2f[] texCoords = sprite.getTexCoords(); int id = sprite.getTextureID(); ImGui.pushID(i); if (ImGui.imageButton( id, spriteWidth, spriteHeight, texCoords[2].x, texCoords[0].y, texCoords[0].x, texCoords[2].y)) {
package engine.scenes; public class LevelEditorScene extends Scene { private final SpriteSheet blocks; private final GameObject editor; public LevelEditorScene() { editor = createGameObject("Editor"); editor.setNotSerializable(); editor.addComponent(new MouseControls()); editor.addComponent(new KeyControls()); editor.addComponent(new GridLines()); editor.addComponent(new EditorCamera(camera)); editor.addComponent(new GizmoSystem(this, editor)); blocks = AssetPool.getSpriteSheet(CONSTANTS.BLOCK_SHEET_PATH.getValue(), 16, 16, 0, 81); addGameObjectToScene(editor); AssetPool.getSound(CONSTANTS.SOUNDS_PATH.getValue() + "main-theme-overworld.ogg").stop(); } public boolean gizmoActive() { GizmoSystem gizmoSystem = editor.getComponent(GizmoSystem.class); return gizmoSystem.gizmoActive(); } private List<Sound> loadSounds() { String sound_dir = CONSTANTS.SOUNDS_PATH.getValue(); File[] files = new File(sound_dir).listFiles(); if (files != null) { for (File file : files) { if (file.isFile() && file.getName().endsWith(".ogg")) { String path = file.getAbsolutePath(); AssetPool.getSound(path, false); } } } return new ArrayList<>(AssetPool.getSounds()); } private void addBlock(SpriteSheet sheet, int i, ImVec2 windowSize, ImVec2 itemSpacing, float windowX, boolean decoration) { Sprite sprite = sheet.getSprite(i); float spriteWidth = sprite.getWidth() * 3, spriteHeight = sprite.getHeight() * 3; Vector2f[] texCoords = sprite.getTexCoords(); int id = sprite.getTextureID(); ImGui.pushID(i); if (ImGui.imageButton( id, spriteWidth, spriteHeight, texCoords[2].x, texCoords[0].y, texCoords[0].x, texCoords[2].y)) {
GameObject ob = Prefabs.generateSpriteObject(sprite, CONSTANTS.GRID_WIDTH.getIntValue(), CONSTANTS.GRID_HEIGHT.getIntValue());
11
2023-11-04 13:19:21+00:00
24k
RezaGooner/University-food-ordering
Frames/Admin/Managment/ColorChangeMenu.java
[ { "identifier": "LoginFrame", "path": "Frames/LoginFrame.java", "snippet": "public class LoginFrame extends JFrame {\r\n\r\n public static boolean isNumeric(String str) {\r\n if (str == null || str.length() == 0) {\r\n return false;\r\n }\r\n try {\r\n Long....
import static Classes.Pathes.ClassesPath.*; import static Frames.Admin.Managment.ChangeThemeColor.changeColor; import static Frames.Admin.Managment.ColorChooser.setColor; import static Frames.Profile.ChangePasswordFrame.colorBackground; import static Frames.Profile.ChangePasswordFrame.colorButton; import Frames.LoginFrame; import Frames.Order.UniversitySelfRestaurant; import Frames.Profile.ForgotPassword; import Frames.Profile.NewUserFrame; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
21,009
package Frames.Admin.Managment; /* این کد جاوا یک کلاس است که متد setColor() را دارد. این متد یک پنجره رنگ انتخاب کننده باز می کند و رنگ انتخاب شده توسط کاربر را برمی گرداند. در ابتدا، یک آرایه رشته ای و سه آرایه از integer تعریف می شود. پس از باز شدن پنجره رنگ انتخاب کننده، مقادیر رنگ قرمز، سبز و آبی را از رنگ انتخاب شده به دست می آورد و آنها را در آرایه های integer مربوطه ذخیره می کند. سپس پیامی به کاربر نمایش داده می شود که تغییرات با موفقیت اعمال شده است و رشته ای که شامل مقادیر رنگ است برمی گردانده می شود. در صورتی که کاربر هیچ رنگی را انتخاب نکرده باشد، مقدار null برگردانده می شود. ````````````````````````````````````````````````````` It extends the `JFrame` class and provides a graphical user interface for changing the colors of different frames in a Java Swing application. Here is a breakdown of the code: 1. The code imports various classes from different packages, including `javax.swing` for GUI components and `java.awt` for basic AWT components. 2. The `ColorChangeMenu` class is defined, which extends the `JFrame` class. 3. The constructor of the `ColorChangeMenu` class is defined. It sets up the main frame by setting the title, making it non-resizable, and positioning it at the center of the screen. 4. A `JPanel` named `panel` is created with a grid layout of 5 rows and 1 column. This panel will contain other panels representing different menus. 5. Five panels (`panel1` to `panel5`) are created, each representing a different menu. Each panel has a titled border. 6. Within each panel, there are two buttons and two labels representing the background color and button color of the corresponding frame. The buttons are initially set to the current colors of the frames. When clicked, these buttons open a color chooser dialog (`JColorChooser`) that allows the user to select a new color. 7. The `ColorChangeListener` class is defined as an inner class within `ColorChangeMenu`. This class implements the `ActionListener` interface and is responsible for handling color change events when the buttons are clicked. 8. The `actionPerformed` method of `ColorChangeListener` is implemented to handle the button click events. It opens a color chooser dialog and retrieves the selected color. Then it updates the background color or button color of the corresponding frame, based on which button was clicked. 9. The `main` method is defined, which creates an instance of `ColorChangeMenu` and sets it visible. Overall, this code creates a GUI with multiple panels, each allowing the user to change the colors of different frames in a Java Swing application. */ public class ColorChangeMenu extends JFrame { public ColorChangeMenu() { setTitle("تغییر رنگ منو ها"); setResizable(false); setLocationRelativeTo(null); JPanel panel = new JPanel(new GridLayout(5, 1)); JPanel panel1 = new JPanel (); panel1.setBorder(new TitledBorder(null, "منوی ورود", TitledBorder.LEFT, TitledBorder.TOP)); JButton button12 = new JButton("");
package Frames.Admin.Managment; /* این کد جاوا یک کلاس است که متد setColor() را دارد. این متد یک پنجره رنگ انتخاب کننده باز می کند و رنگ انتخاب شده توسط کاربر را برمی گرداند. در ابتدا، یک آرایه رشته ای و سه آرایه از integer تعریف می شود. پس از باز شدن پنجره رنگ انتخاب کننده، مقادیر رنگ قرمز، سبز و آبی را از رنگ انتخاب شده به دست می آورد و آنها را در آرایه های integer مربوطه ذخیره می کند. سپس پیامی به کاربر نمایش داده می شود که تغییرات با موفقیت اعمال شده است و رشته ای که شامل مقادیر رنگ است برمی گردانده می شود. در صورتی که کاربر هیچ رنگی را انتخاب نکرده باشد، مقدار null برگردانده می شود. ````````````````````````````````````````````````````` It extends the `JFrame` class and provides a graphical user interface for changing the colors of different frames in a Java Swing application. Here is a breakdown of the code: 1. The code imports various classes from different packages, including `javax.swing` for GUI components and `java.awt` for basic AWT components. 2. The `ColorChangeMenu` class is defined, which extends the `JFrame` class. 3. The constructor of the `ColorChangeMenu` class is defined. It sets up the main frame by setting the title, making it non-resizable, and positioning it at the center of the screen. 4. A `JPanel` named `panel` is created with a grid layout of 5 rows and 1 column. This panel will contain other panels representing different menus. 5. Five panels (`panel1` to `panel5`) are created, each representing a different menu. Each panel has a titled border. 6. Within each panel, there are two buttons and two labels representing the background color and button color of the corresponding frame. The buttons are initially set to the current colors of the frames. When clicked, these buttons open a color chooser dialog (`JColorChooser`) that allows the user to select a new color. 7. The `ColorChangeListener` class is defined as an inner class within `ColorChangeMenu`. This class implements the `ActionListener` interface and is responsible for handling color change events when the buttons are clicked. 8. The `actionPerformed` method of `ColorChangeListener` is implemented to handle the button click events. It opens a color chooser dialog and retrieves the selected color. Then it updates the background color or button color of the corresponding frame, based on which button was clicked. 9. The `main` method is defined, which creates an instance of `ColorChangeMenu` and sets it visible. Overall, this code creates a GUI with multiple panels, each allowing the user to change the colors of different frames in a Java Swing application. */ public class ColorChangeMenu extends JFrame { public ColorChangeMenu() { setTitle("تغییر رنگ منو ها"); setResizable(false); setLocationRelativeTo(null); JPanel panel = new JPanel(new GridLayout(5, 1)); JPanel panel1 = new JPanel (); panel1.setBorder(new TitledBorder(null, "منوی ورود", TitledBorder.LEFT, TitledBorder.TOP)); JButton button12 = new JButton("");
button12.setBackground(LoginFrame.colorBackground);
0
2023-11-03 08:35:22+00:00
24k
schadfield/shogi-explorer
src/main/java/com/chadfield/shogiexplorer/objects/GameAnalyser.java
[ { "identifier": "AnalysisManager", "path": "src/main/java/com/chadfield/shogiexplorer/main/AnalysisManager.java", "snippet": "public class AnalysisManager {\n\n private AnalysisManager() {\n throw new IllegalStateException(\"Utility class\");\n }\n\n public static void save(Analysis anal...
import com.chadfield.shogiexplorer.main.AnalysisManager; import com.chadfield.shogiexplorer.main.EngineManager; import com.chadfield.shogiexplorer.main.SFENParser; import com.chadfield.shogiexplorer.objects.Board.Turn; import com.chadfield.shogiexplorer.utils.NotationUtils; import com.chadfield.shogiexplorer.utils.ParserUtils; import static com.chadfield.shogiexplorer.utils.StringUtils.getFileExtension; import com.ibm.icu.text.Transliterator; import java.awt.Rectangle; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JList; import javax.swing.JMenuItem; import javax.swing.JRadioButtonMenuItem; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.DefaultIntervalXYDataset;
15,085
this.resumeAnalysisMenuItem = analysisParam.getResumeAnalysisMenuItem(); this.resumeAnalysisToolbarButton = analysisParam.getResumeAnalysisToolbarButton(); this.x1Start = analysisParam.getX1Start(); this.x1 = analysisParam.getX1(); this.x1End = analysisParam.getX1End(); this.y1Start = analysisParam.getY1Start(); this.y1 = analysisParam.getY1(); this.y1End = analysisParam.getY1End(); this.x2Start = analysisParam.getX2Start(); this.x2 = analysisParam.getX2(); this.x2End = analysisParam.getX2End(); this.y2Start = analysisParam.getY2Start(); this.y2 = analysisParam.getY2(); this.y2End = analysisParam.getY2End(); initializeEngine(engine); initiateUSIProtocol(); setOptions(engine); getReady(); String engineMove = null; String japaneseMove = null; String sfen = null; String lastSFEN = null; int count = 1; int resumeCount = 1; if (resume) { resumeCount = analysisTable.getRowCount(); } Coordinate lastDestination = null; Coordinate previousMoveDestination = null; if (!resume) { game.setAnalysisPositionList(new ArrayList<>()); } scoreList = new ArrayList<>(); game.isHandicap(); if (game.isHandicap()) { turn = Turn.GOTE; } else { turn = Turn.SENTE; } interrupted = false; for (Position position : game.getPositionList()) { if (engineMove != null) { if (!resume || count > resumeCount) { updateMoveList(moveList, count); analysePosition(game, lastSFEN, engineMove, japaneseMove, analysisTable, plotDataset, count, turn, previousMoveDestination); } if (interrupted) { break; } previousMoveDestination = lastDestination; count++; turn = ParserUtils.switchTurn(turn); } lastSFEN = sfen; sfen = position.getGameSFEN(); engineMove = position.getNotation().getEngineMove(); if (turn == Turn.SENTE) { japaneseMove = trans.transliterate(" ☗" + position.getNotation().getJapanese()); } else { japaneseMove = trans.transliterate(" ☖" + position.getNotation().getJapanese()); } lastDestination = position.getDestination(); } if (!interrupted) { updateMoveList(moveList, count); analysePosition(game, lastSFEN, engineMove, japaneseMove, analysisTable, plotDataset, count, turn, previousMoveDestination); count++; } if (analysisTable.getRowCount() > 0) { analysisTable.setRowSelectionInterval(count - 2, count - 2); analysisTable.scrollRectToVisible(new Rectangle(analysisTable.getCellRect(count - 2, 0, true))); } quitEngine(); stopAnalysisMenuItem.setEnabled(false); stopAnalysisToolbarButton.setEnabled(false); analyseGameMenuItem.setEnabled(true); analyseGameToolbarButton.setEnabled(true); analysePositionMenuItem.setEnabled(true); analysePositionToolbarButton.setEnabled(true); resumeAnalysisMenuItem.setEnabled(count < game.getPositionList().size() - 1); resumeAnalysisToolbarButton.setEnabled(resumeAnalysisMenuItem.isEnabled()); analysisParam.setX1Start(x1Start); analysisParam.setX1(x1); analysisParam.setX1End(x1End); analysisParam.setY1Start(y1Start); analysisParam.setY1(y1); analysisParam.setY1End(y1End); analysisParam.setX2Start(x2Start); analysisParam.setX2(x2); analysisParam.setX2End(x2End); analysisParam.setY2Start(y2Start); analysisParam.setY2(y2); analysisParam.setY2End(y2End); if (saveAnalysis) { Analysis analysis = new Analysis(); analysis.setAnalysisPositionList(game.getAnalysisPositionList()); List<Object[]> tableRows = new ArrayList<>(); DefaultTableModel analysisTableModel = (DefaultTableModel) analysisTable.getModel(); for (int i = 0; i < analysisTableModel.getRowCount(); i++) { tableRows.add(new Object[]{ analysisTableModel.getValueAt(i, 0), analysisTableModel.getValueAt(i, 1), analysisTableModel.getValueAt(i, 2), analysisTableModel.getValueAt(i, 3), analysisTableModel.getValueAt(i, 4) }); } analysis.setTableRows(tableRows); analysis.setScoreList(scoreList);
/* Copyright © 2021, 2022 Stephen R Chadfield. This file is part of Shogi Explorer. Shogi Explorer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Shogi Explorer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Shogi Explorer. If not, see <https://www.gnu.org/licenses/>. */ package com.chadfield.shogiexplorer.objects; public class GameAnalyser { private Process process; private OutputStream stdin; private BufferedReader bufferedReader; private String lastScore = ""; private String opinion = ""; private int analysisTimePerMove; private static final int ANALYSIS_MISTAKE_THRESHOLD = 250; private static final int ANALYSIS_BLUNDER_THRESHOLD = 500; private static final int ANALYSIS_IGNORE_THRESHOLD = 2000; double[] x1Start; double[] x1; double[] x1End; double[] y1Start; double[] y1; double[] y1End; double[][] data1; double[] x2Start; double[] x2; double[] x2End; double[] y2Start; double[] y2; double[] y2End; double[][] data2; XYPlot plot; int range; String scoreStr; List<Integer> scoreList; JRadioButtonMenuItem graphView1; JRadioButtonMenuItem graphView2; JRadioButtonMenuItem graphView3; JButton stopAnalysisToolbarButton; JMenuItem stopAnalysisMenuItem; JMenuItem analyseGameMenuItem; JButton analyseGameToolbarButton; JMenuItem analysePositionMenuItem; JButton analysePositionToolbarButton; JMenuItem resumeAnalysisMenuItem; JButton resumeAnalysisToolbarButton; Transliterator trans = Transliterator.getInstance("Halfwidth-Fullwidth"); Turn turn; int multiPV; int rowNum; boolean bestMove; boolean interrupted; private List<List<Position>> positionAnalysisList; private static final String OS = System.getProperty("os.name").toLowerCase(); public static final boolean IS_WINDOWS = (OS.contains("win")); public static final boolean IS_MAC = (OS.contains("mac")); public static final boolean IS_LINUX = (OS.contains("nux")); public void analyse(Game game, Engine engine, JList<String> moveList, JTable analysisTable, AnalysisParameter analysisParam, AtomicBoolean analysing, XYPlot plot, boolean saveAnalysis, boolean resume) throws IOException { analysing.set(true); this.plot = plot; DefaultIntervalXYDataset plotDataset = (DefaultIntervalXYDataset) plot.getDataset(); this.analysisTimePerMove = analysisParam.getAnalysisTimePerMove(); this.graphView1 = analysisParam.getGraphView1(); this.graphView2 = analysisParam.getGraphView2(); this.graphView3 = analysisParam.getGraphView3(); this.stopAnalysisToolbarButton = analysisParam.getHaltAnalysisButton(); this.stopAnalysisMenuItem = analysisParam.getStopAnalysisMenuItem(); this.analyseGameMenuItem = analysisParam.getAnalyseGameMenuItem(); this.analyseGameToolbarButton = analysisParam.getAnalyseGameToolbarButton(); this.analysePositionMenuItem = analysisParam.getAnalysePositionMenuItem(); this.analysePositionToolbarButton = analysisParam.getAnalysePositionToolbarButton(); this.resumeAnalysisMenuItem = analysisParam.getResumeAnalysisMenuItem(); this.resumeAnalysisToolbarButton = analysisParam.getResumeAnalysisToolbarButton(); this.x1Start = analysisParam.getX1Start(); this.x1 = analysisParam.getX1(); this.x1End = analysisParam.getX1End(); this.y1Start = analysisParam.getY1Start(); this.y1 = analysisParam.getY1(); this.y1End = analysisParam.getY1End(); this.x2Start = analysisParam.getX2Start(); this.x2 = analysisParam.getX2(); this.x2End = analysisParam.getX2End(); this.y2Start = analysisParam.getY2Start(); this.y2 = analysisParam.getY2(); this.y2End = analysisParam.getY2End(); initializeEngine(engine); initiateUSIProtocol(); setOptions(engine); getReady(); String engineMove = null; String japaneseMove = null; String sfen = null; String lastSFEN = null; int count = 1; int resumeCount = 1; if (resume) { resumeCount = analysisTable.getRowCount(); } Coordinate lastDestination = null; Coordinate previousMoveDestination = null; if (!resume) { game.setAnalysisPositionList(new ArrayList<>()); } scoreList = new ArrayList<>(); game.isHandicap(); if (game.isHandicap()) { turn = Turn.GOTE; } else { turn = Turn.SENTE; } interrupted = false; for (Position position : game.getPositionList()) { if (engineMove != null) { if (!resume || count > resumeCount) { updateMoveList(moveList, count); analysePosition(game, lastSFEN, engineMove, japaneseMove, analysisTable, plotDataset, count, turn, previousMoveDestination); } if (interrupted) { break; } previousMoveDestination = lastDestination; count++; turn = ParserUtils.switchTurn(turn); } lastSFEN = sfen; sfen = position.getGameSFEN(); engineMove = position.getNotation().getEngineMove(); if (turn == Turn.SENTE) { japaneseMove = trans.transliterate(" ☗" + position.getNotation().getJapanese()); } else { japaneseMove = trans.transliterate(" ☖" + position.getNotation().getJapanese()); } lastDestination = position.getDestination(); } if (!interrupted) { updateMoveList(moveList, count); analysePosition(game, lastSFEN, engineMove, japaneseMove, analysisTable, plotDataset, count, turn, previousMoveDestination); count++; } if (analysisTable.getRowCount() > 0) { analysisTable.setRowSelectionInterval(count - 2, count - 2); analysisTable.scrollRectToVisible(new Rectangle(analysisTable.getCellRect(count - 2, 0, true))); } quitEngine(); stopAnalysisMenuItem.setEnabled(false); stopAnalysisToolbarButton.setEnabled(false); analyseGameMenuItem.setEnabled(true); analyseGameToolbarButton.setEnabled(true); analysePositionMenuItem.setEnabled(true); analysePositionToolbarButton.setEnabled(true); resumeAnalysisMenuItem.setEnabled(count < game.getPositionList().size() - 1); resumeAnalysisToolbarButton.setEnabled(resumeAnalysisMenuItem.isEnabled()); analysisParam.setX1Start(x1Start); analysisParam.setX1(x1); analysisParam.setX1End(x1End); analysisParam.setY1Start(y1Start); analysisParam.setY1(y1); analysisParam.setY1End(y1End); analysisParam.setX2Start(x2Start); analysisParam.setX2(x2); analysisParam.setX2End(x2End); analysisParam.setY2Start(y2Start); analysisParam.setY2(y2); analysisParam.setY2End(y2End); if (saveAnalysis) { Analysis analysis = new Analysis(); analysis.setAnalysisPositionList(game.getAnalysisPositionList()); List<Object[]> tableRows = new ArrayList<>(); DefaultTableModel analysisTableModel = (DefaultTableModel) analysisTable.getModel(); for (int i = 0; i < analysisTableModel.getRowCount(); i++) { tableRows.add(new Object[]{ analysisTableModel.getValueAt(i, 0), analysisTableModel.getValueAt(i, 1), analysisTableModel.getValueAt(i, 2), analysisTableModel.getValueAt(i, 3), analysisTableModel.getValueAt(i, 4) }); } analysis.setTableRows(tableRows); analysis.setScoreList(scoreList);
AnalysisManager.save(analysis, analysisParam.getKifFile());
0
2023-11-08 09:24:57+00:00
24k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/service/impl/SysUserApplyServiceImpl.java
[ { "identifier": "FriendAdapt", "path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/adapt/FriendAdapt.java", "snippet": "public class FriendAdapt {\n\n /**\n * 构建保存好友信息\n *\n * @param applyFriendDTO 申请好友 dto\n * @return {@link SysUserApply }\n * @author q...
import cn.dev33.satoken.stp.StpUtil; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.qingmeng.config.adapt.FriendAdapt; import com.qingmeng.config.adapt.UserSettingAdapt; import com.qingmeng.config.cache.UserCache; import com.qingmeng.dao.SysUserApplyDao; import com.qingmeng.dao.SysUserFriendSettingDao; import com.qingmeng.dto.common.PageDTO; import com.qingmeng.dto.user.AgreeApplyFriendDTO; import com.qingmeng.dto.user.ApplyFriendDTO; import com.qingmeng.entity.SysUser; import com.qingmeng.entity.SysUserApply; import com.qingmeng.entity.SysUserFriend; import com.qingmeng.entity.SysUserFriendSetting; import com.qingmeng.enums.user.ApplyFriendChannelEnum; import com.qingmeng.enums.user.ApplyStatusEnum; import com.qingmeng.service.ChatFriendRoomService; import com.qingmeng.service.SysUserApplyService; import com.qingmeng.service.SysUserFriendService; import com.qingmeng.config.strategy.applyFriend.ApplyFriendFactory; import com.qingmeng.config.strategy.applyFriend.ApplyFriendStrategy; import com.qingmeng.utils.AssertUtils; import com.qingmeng.utils.CommonUtils; import com.qingmeng.vo.common.CommonPageVO; import com.qingmeng.vo.user.FriendApplyRecordVO; import org.jetbrains.annotations.NotNull; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;
15,757
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月10日 11:18:00 */ @Service public class SysUserApplyServiceImpl implements SysUserApplyService { @Resource private ApplyFriendFactory applyFriendFactory; @Resource private SysUserApplyDao sysUserApplyDao; @Resource private SysUserFriendSettingDao sysUserFriendSettingDao; @Resource private SysUserFriendService sysUserFriendService; @Resource private ChatFriendRoomService chatFriendRoomService; @Resource private UserCache userCache; /** * 申请好友 * * @param applyFriendDTO 申请好友 dto * @author qingmeng * @createTime: 2023/11/27 15:56:45 */ @Override public void applyFriend(ApplyFriendDTO applyFriendDTO) { // 根据getApplyChannel获取对应渠道的枚举进而获取对应处理的策略实现类 ApplyFriendChannelEnum channelEnum = ApplyFriendChannelEnum.get(applyFriendDTO.getApplyChannel());
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月10日 11:18:00 */ @Service public class SysUserApplyServiceImpl implements SysUserApplyService { @Resource private ApplyFriendFactory applyFriendFactory; @Resource private SysUserApplyDao sysUserApplyDao; @Resource private SysUserFriendSettingDao sysUserFriendSettingDao; @Resource private SysUserFriendService sysUserFriendService; @Resource private ChatFriendRoomService chatFriendRoomService; @Resource private UserCache userCache; /** * 申请好友 * * @param applyFriendDTO 申请好友 dto * @author qingmeng * @createTime: 2023/11/27 15:56:45 */ @Override public void applyFriend(ApplyFriendDTO applyFriendDTO) { // 根据getApplyChannel获取对应渠道的枚举进而获取对应处理的策略实现类 ApplyFriendChannelEnum channelEnum = ApplyFriendChannelEnum.get(applyFriendDTO.getApplyChannel());
ApplyFriendStrategy strategyWithType = applyFriendFactory.getStrategyWithType(channelEnum.getValue());
18
2023-11-07 16:04:55+00:00
24k
dingodb/dingo-expr
test/src/test/java/io/dingodb/expr/test/cases/EvalConstProvider.java
[ { "identifier": "Types", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/Types.java", "snippet": "public final class Types {\n public static final NullType NULL = new NullType();\n public static final IntType INT = new IntType();\n public static final LongType LONG = new LongType();...
import com.google.common.collect.ImmutableMap; import io.dingodb.expr.runtime.type.Types; import io.dingodb.expr.runtime.utils.DateTimeUtils; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import static io.dingodb.expr.runtime.expr.Exprs.ABS; import static io.dingodb.expr.runtime.expr.Exprs.ABS_C; import static io.dingodb.expr.runtime.expr.Exprs.ACOS; import static io.dingodb.expr.runtime.expr.Exprs.ADD; import static io.dingodb.expr.runtime.expr.Exprs.AND; import static io.dingodb.expr.runtime.expr.Exprs.AND_FUN; import static io.dingodb.expr.runtime.expr.Exprs.ARRAY; import static io.dingodb.expr.runtime.expr.Exprs.ASIN; import static io.dingodb.expr.runtime.expr.Exprs.ATAN; import static io.dingodb.expr.runtime.expr.Exprs.CASE; import static io.dingodb.expr.runtime.expr.Exprs.CEIL; import static io.dingodb.expr.runtime.expr.Exprs.CHAR_LENGTH; import static io.dingodb.expr.runtime.expr.Exprs.CONCAT; import static io.dingodb.expr.runtime.expr.Exprs.COS; import static io.dingodb.expr.runtime.expr.Exprs.COSH; import static io.dingodb.expr.runtime.expr.Exprs.DATEDIFF; import static io.dingodb.expr.runtime.expr.Exprs.DATE_FORMAT1; import static io.dingodb.expr.runtime.expr.Exprs.DATE_FORMAT2; import static io.dingodb.expr.runtime.expr.Exprs.DIV; import static io.dingodb.expr.runtime.expr.Exprs.EQ; import static io.dingodb.expr.runtime.expr.Exprs.EXP; import static io.dingodb.expr.runtime.expr.Exprs.FLOOR; import static io.dingodb.expr.runtime.expr.Exprs.FORMAT; import static io.dingodb.expr.runtime.expr.Exprs.FROM_UNIXTIME; import static io.dingodb.expr.runtime.expr.Exprs.GE; import static io.dingodb.expr.runtime.expr.Exprs.GT; import static io.dingodb.expr.runtime.expr.Exprs.HEX; import static io.dingodb.expr.runtime.expr.Exprs.INDEX; import static io.dingodb.expr.runtime.expr.Exprs.IS_FALSE; import static io.dingodb.expr.runtime.expr.Exprs.IS_NULL; import static io.dingodb.expr.runtime.expr.Exprs.IS_TRUE; import static io.dingodb.expr.runtime.expr.Exprs.LE; import static io.dingodb.expr.runtime.expr.Exprs.LEFT; import static io.dingodb.expr.runtime.expr.Exprs.LIST; import static io.dingodb.expr.runtime.expr.Exprs.LOCATE2; import static io.dingodb.expr.runtime.expr.Exprs.LOCATE3; import static io.dingodb.expr.runtime.expr.Exprs.LOG; import static io.dingodb.expr.runtime.expr.Exprs.LOWER; import static io.dingodb.expr.runtime.expr.Exprs.LT; import static io.dingodb.expr.runtime.expr.Exprs.LTRIM1; import static io.dingodb.expr.runtime.expr.Exprs.LTRIM2; import static io.dingodb.expr.runtime.expr.Exprs.MAP; import static io.dingodb.expr.runtime.expr.Exprs.MATCHES; import static io.dingodb.expr.runtime.expr.Exprs.MATCHES_NC; import static io.dingodb.expr.runtime.expr.Exprs.MAX; import static io.dingodb.expr.runtime.expr.Exprs.MID2; import static io.dingodb.expr.runtime.expr.Exprs.MID3; import static io.dingodb.expr.runtime.expr.Exprs.MIN; import static io.dingodb.expr.runtime.expr.Exprs.MOD; import static io.dingodb.expr.runtime.expr.Exprs.MUL; import static io.dingodb.expr.runtime.expr.Exprs.NE; import static io.dingodb.expr.runtime.expr.Exprs.NEG; import static io.dingodb.expr.runtime.expr.Exprs.NOT; import static io.dingodb.expr.runtime.expr.Exprs.OR; import static io.dingodb.expr.runtime.expr.Exprs.OR_FUN; import static io.dingodb.expr.runtime.expr.Exprs.POS; import static io.dingodb.expr.runtime.expr.Exprs.POW; import static io.dingodb.expr.runtime.expr.Exprs.REPEAT; import static io.dingodb.expr.runtime.expr.Exprs.REPLACE; import static io.dingodb.expr.runtime.expr.Exprs.REVERSE; import static io.dingodb.expr.runtime.expr.Exprs.RIGHT; import static io.dingodb.expr.runtime.expr.Exprs.ROUND1; import static io.dingodb.expr.runtime.expr.Exprs.ROUND2; import static io.dingodb.expr.runtime.expr.Exprs.RTRIM1; import static io.dingodb.expr.runtime.expr.Exprs.RTRIM2; import static io.dingodb.expr.runtime.expr.Exprs.SIN; import static io.dingodb.expr.runtime.expr.Exprs.SINH; import static io.dingodb.expr.runtime.expr.Exprs.SLICE; import static io.dingodb.expr.runtime.expr.Exprs.SUB; import static io.dingodb.expr.runtime.expr.Exprs.SUBSTR2; import static io.dingodb.expr.runtime.expr.Exprs.SUBSTR3; import static io.dingodb.expr.runtime.expr.Exprs.TAN; import static io.dingodb.expr.runtime.expr.Exprs.TANH; import static io.dingodb.expr.runtime.expr.Exprs.TIMESTAMP_FORMAT1; import static io.dingodb.expr.runtime.expr.Exprs.TIMESTAMP_FORMAT2; import static io.dingodb.expr.runtime.expr.Exprs.TIME_FORMAT1; import static io.dingodb.expr.runtime.expr.Exprs.TIME_FORMAT2; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_BOOL; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_BYTES; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_DATE; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_DECIMAL; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_DOUBLE; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_FLOAT; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_INT; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_INT_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_LONG; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_LONG_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_STRING; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_TIME; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_TIMESTAMP; import static io.dingodb.expr.runtime.expr.Exprs.TO_BOOL; import static io.dingodb.expr.runtime.expr.Exprs.TO_BYTES; import static io.dingodb.expr.runtime.expr.Exprs.TO_DATE; import static io.dingodb.expr.runtime.expr.Exprs.TO_DECIMAL; import static io.dingodb.expr.runtime.expr.Exprs.TO_DOUBLE; import static io.dingodb.expr.runtime.expr.Exprs.TO_FLOAT; import static io.dingodb.expr.runtime.expr.Exprs.TO_INT; import static io.dingodb.expr.runtime.expr.Exprs.TO_INT_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_BOOL; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_BYTES; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_DATE; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_DECIMAL; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_DOUBLE; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_FLOAT; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_INT; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_INT_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_LONG; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_LONG_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_STRING; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_TIME; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_TIMESTAMP; import static io.dingodb.expr.runtime.expr.Exprs.TO_LONG; import static io.dingodb.expr.runtime.expr.Exprs.TO_LONG_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_STRING; import static io.dingodb.expr.runtime.expr.Exprs.TO_TIME; import static io.dingodb.expr.runtime.expr.Exprs.TO_TIMESTAMP; import static io.dingodb.expr.runtime.expr.Exprs.TRIM1; import static io.dingodb.expr.runtime.expr.Exprs.TRIM2; import static io.dingodb.expr.runtime.expr.Exprs.UNIX_TIMESTAMP1; import static io.dingodb.expr.runtime.expr.Exprs.UPPER; import static io.dingodb.expr.runtime.expr.Exprs._CP1; import static io.dingodb.expr.runtime.expr.Exprs._CP2; import static io.dingodb.expr.runtime.expr.Exprs._CTF; import static io.dingodb.expr.runtime.expr.Exprs.op; import static io.dingodb.expr.runtime.expr.Exprs.val; import static io.dingodb.expr.runtime.expr.Val.NULL; import static io.dingodb.expr.runtime.expr.Val.NULL_BOOL; import static io.dingodb.expr.runtime.expr.Val.NULL_BYTES; import static io.dingodb.expr.runtime.expr.Val.NULL_DATE; import static io.dingodb.expr.runtime.expr.Val.NULL_DECIMAL; import static io.dingodb.expr.runtime.expr.Val.NULL_DOUBLE; import static io.dingodb.expr.runtime.expr.Val.NULL_FLOAT; import static io.dingodb.expr.runtime.expr.Val.NULL_INT; import static io.dingodb.expr.runtime.expr.Val.NULL_LONG; import static io.dingodb.expr.runtime.expr.Val.NULL_STRING; import static io.dingodb.expr.runtime.expr.Val.NULL_TIME; import static io.dingodb.expr.runtime.expr.Val.NULL_TIMESTAMP; import static io.dingodb.expr.test.ExprsHelper.bytes; import static io.dingodb.expr.test.ExprsHelper.date; import static io.dingodb.expr.test.ExprsHelper.dec; import static io.dingodb.expr.test.ExprsHelper.sec; import static io.dingodb.expr.test.ExprsHelper.time; import static io.dingodb.expr.test.ExprsHelper.ts; import static org.junit.jupiter.params.provider.Arguments.arguments;
19,845
arguments(op(SUBSTR3, "HeLLo", 1, 3), "eL"), arguments(op(MID2, "Alice", 2), "lice"), arguments(op(MID2, "Alice", 0), ""), arguments(op(MID2, "Alice", NULL_INT), null), arguments(op(MID2, "Alice", -2), "ce"), arguments(op(MID3, NULL_STRING, 0, 0), null), arguments(op(MID3, "Alice", NULL_INT, 0), null), arguments(op(MID3, "Alice", 1, NULL_INT), null), arguments(op(MID3, "Alice", 0, 0), ""), arguments(op(MID3, "Alice", 1, 0), ""), arguments(op(MID3, "Alice", 1, 3), "Ali"), arguments(op(MID3, "Alice", -1, 1), "e"), arguments(op(MID3, "Alice", -3, 2), "ic"), arguments(op(MID3, "Alice", -3, 1.5), "ic"), arguments(op(REPEAT, NULL_STRING, 3), null), arguments(op(REPEAT, "Abc", -1), ""), arguments(op(REPEAT, "Abc", 3), "AbcAbcAbc"), arguments(op(REPEAT, "Abc", 1.7), "AbcAbc"), arguments(op(REVERSE, NULL_STRING), null), arguments(op(REVERSE, "AbCdE"), "EdCbA"), arguments(op(REPLACE, "HeLLo", "eL", "El"), "HElLo"), arguments(op(REPLACE, NULL, "a", "b"), null), arguments(op(LOCATE2, NULL_STRING, "a"), null), arguments(op(LOCATE2, "at", "Water"), 2), arguments(op(LOCATE2, "am", "Water"), 0), arguments(op(LOCATE2, NULL_STRING, "Water"), null), arguments(op(LOCATE2, "", "Water"), 1), arguments(op(LOCATE3, "", "Water", 3), 3), arguments(op(LOCATE3, "a", "Banana", 3), 4), arguments(op(LOCATE3, "a", "Banana", 7), 0), arguments(op(LOCATE3, "a", "Banana", 3.5), 4), arguments(op(HEX, "414243"), "ABC".getBytes(StandardCharsets.UTF_8)), arguments(op(FORMAT, 100.21, 1), "100.2"), arguments(op(FORMAT, 99.00000, 2), "99.00"), arguments(op(FORMAT, 1220.532, 0), "1221"), arguments(op(FORMAT, 18, 2), "18.00"), arguments(op(FORMAT, 15354.6651, 1.6), "15354.67"), arguments(op(MATCHES, "abc123", ".*c\\d{2}."), true), arguments(op(MATCHES, "abc123", "c\\d{2}"), false), arguments(op(MATCHES, "abc123", "Abc\\d{3}"), false), arguments(op(MATCHES_NC, "abc123", "Abc\\d{3}"), true), arguments(op(_CTF, "%Y"), "uuuu"), arguments(op(_CTF, "%Y-%m-%d"), "uuuu'-'MM'-'dd"), arguments(op(_CTF, "%A%B%C"), "'ABC'"), arguments(op(_CTF, "Year: %Y, Month: %m"), "'Year: 'uuuu', Month: 'MM"), arguments(op(_CP1, "%"), ".*"), arguments(op(_CP1, "_"), "."), arguments(op(_CP1, "a_b%c"), "a.b.*c"), arguments(op(_CP1, "a\\_b\\%c"), "a_b%c"), arguments(op(_CP1, "a\\nb\\%c"), "a\\nb%c"), arguments(op(_CP2, "a\\_b\\%c", "|"), "a\\.b\\.*c"), arguments(op(_CP2, "a|_b|%c", "|"), "a_b%c"), // Date & times arguments(op(DATE_FORMAT1, 0), "1970-01-01"), arguments(op(DATE_FORMAT2, 0, "uuuu:MM:dd"), "1970:01:01"), arguments(op(DATE_FORMAT2, 0, op(_CTF, "%Y:%m:%d")), "1970:01:01"), arguments(op(TIME_FORMAT1, 0), "00:00:00"), arguments(op(TIME_FORMAT2, 0, "HH-mm-ss"), "00-00-00"), arguments(op(TIME_FORMAT2, 0, op(_CTF, "%H-%i-%s")), "00-00-00"), arguments( op(TIMESTAMP_FORMAT1, 0), DateTimeUtils.timestampFormat(new Timestamp(0), DateTimeUtils.DEFAULT_OUTPUT_TIMESTAMP_FORMATTER) ), arguments( op(TIMESTAMP_FORMAT2, 0, "uuuuMMddHHmmss"), DateTimeUtils.timestampFormat(new Timestamp(0), "uuuuMMddHHmmss") ), arguments( op(TIMESTAMP_FORMAT2, 0, op(_CTF, "%Y%m%d%H%i%s")), DateTimeUtils.timestampFormat(new Timestamp(0), "uuuuMMddHHmmss") ), arguments(op(FROM_UNIXTIME, 1), new Timestamp(sec(1L))), arguments(op(FROM_UNIXTIME, 1L), new Timestamp(sec(1L))), arguments(op(FROM_UNIXTIME, dec(1.23)), new Timestamp(sec(BigDecimal.valueOf(1.23)))), arguments(op(UNIX_TIMESTAMP1, ts(1L)), 1L), arguments(op(UNIX_TIMESTAMP1, 2L), 2L), arguments(op(UNIX_TIMESTAMP1, 3.5), 4L), arguments(op(DATEDIFF, 24L * 60L * 60L, 0L), 1L), // Collections arguments(op(ARRAY, 1, 2, 3), new int[]{1, 2, 3}), arguments(op(ARRAY, 1L, 2, 3), new long[]{1L, 2L, 3L}), arguments(op(ARRAY, 1L, 2.0, 3), new double[]{1.0, 2.0, 3.0}), arguments(op(LIST, 1, 2, 3), Arrays.asList(1, 2, 3)), arguments(op(LIST, 1L, 2, 3), Arrays.asList(1L, 2L, 3L)), arguments(op(LIST, 1L, 2.0, 3), Arrays.asList(1.0, 2.0, 3.0)), arguments(op(MAP, 'a', 1, 'b', 2), ImmutableMap.of('a', 1, 'b', 2)), arguments(op(MAP, 1, 1, 2, 2), ImmutableMap.of(1, 1, 2, 2)), arguments(op(MAP, '1', 1, 2, '2'), ImmutableMap.of('1', 1, 2, '2')), arguments(op(TO_ARRAY_INT, op(ARRAY, 1.1, 2.2, 3.3, 4.4, 5.5)), new int[]{1, 2, 3, 4, 6}), arguments(op(TO_ARRAY_INT_C, op(ARRAY, 1.1, 2.2, 3.3, 4.4, 5.5)), new int[]{1, 2, 3, 4, 6}), arguments(op(TO_ARRAY_LONG, op(ARRAY, "1", "2", "3")), new long[]{1L, 2L, 3L}), arguments(op(TO_ARRAY_LONG_C, op(ARRAY, "1", "2", "3")), new long[]{1L, 2L, 3L}), arguments(op(TO_ARRAY_FLOAT, op(ARRAY, 1, 2, 3)), new float[]{1.0f, 2.0f, 3.0f}), arguments(op(TO_ARRAY_DOUBLE, op(ARRAY, 1, 2, 3)), new double[]{1.0, 2.0, 3.0}), arguments(op(TO_ARRAY_BOOL, op(ARRAY, 1, 0, 1)), new boolean[]{true, false, true}), arguments(op(TO_ARRAY_DECIMAL, op(ARRAY, 1, 0)), new BigDecimal[]{BigDecimal.ONE, BigDecimal.ZERO}), arguments(op(TO_ARRAY_STRING, op(ARRAY, 1, 2, 3)), new String[]{"1", "2", "3"}), arguments(op(TO_ARRAY_BYTES, op(ARRAY, "a", "b")), new byte[][]{"a".getBytes(), "b".getBytes()}), arguments(op(TO_ARRAY_DATE, op(ARRAY, 1, 2)), new Date[]{new Date(sec(1L)), new Date(sec(2L))}), arguments(op(TO_ARRAY_TIME, op(ARRAY, 1, 2)), new Time[]{new Time(sec(1L)), new Time(sec(2L))}), arguments(op(TO_ARRAY_TIMESTAMP, op(ARRAY, 1, 2)), new Timestamp[]{new Timestamp(sec(1L)), new Timestamp(sec(2L))}), arguments(op(TO_ARRAY_INT, op(LIST, 1.1, 2.2, 3.3, 4.4, 5.5)), new int[]{1, 2, 3, 4, 6}), arguments(op(TO_ARRAY_INT_C, op(LIST, 1.1, 2.2, 3.3, 4.4, 5.5)), new int[]{1, 2, 3, 4, 6}), arguments(op(TO_ARRAY_LONG, op(LIST, "1", "2", "3")), new long[]{1, 2, 3}), arguments(op(TO_ARRAY_LONG_C, op(LIST, "1", "2", "3")), new long[]{1, 2, 3}), arguments(op(TO_ARRAY_FLOAT, op(LIST, 1, 2, 3)), new float[]{1.0f, 2.0f, 3.0f}), arguments(op(TO_ARRAY_DOUBLE, op(LIST, 1, 2, 3)), new double[]{1.0, 2.0, 3.0}), arguments(op(TO_ARRAY_BOOL, op(LIST, 1, 0, 1)), new boolean[]{true, false, true}), arguments(op(TO_ARRAY_DECIMAL, op(LIST, 1, 0)), new BigDecimal[]{BigDecimal.ONE, BigDecimal.ZERO}), arguments(op(TO_ARRAY_STRING, op(LIST, 1, 2, 3)), new String[]{"1", "2", "3"}), arguments(op(TO_ARRAY_BYTES, op(LIST, "a", "b")), new byte[][]{"a".getBytes(), "b".getBytes()}), arguments(op(TO_ARRAY_DATE, op(LIST, 1, 2)), new Date[]{new Date(sec(1L)), new Date(sec(2L))}), arguments(op(TO_ARRAY_TIME, op(LIST, 1, 2)), new Time[]{new Time(sec(1L)), new Time(sec(2L))}), arguments(op(TO_ARRAY_TIMESTAMP, op(LIST, 1, 2)), new Timestamp[]{new Timestamp(sec(1L)), new Timestamp(sec(2L))}), arguments(op(TO_LIST_INT, op(ARRAY, 1.1, 2.2, 3.3, 4.4, 5.5)), Arrays.asList(1, 2, 3, 4, 6)), arguments(op(TO_LIST_INT_C, op(ARRAY, 1.1, 2.2, 3.3, 4.4, 5.5)), Arrays.asList(1, 2, 3, 4, 6)),
/* * Copyright 2021 DataCanvas * * 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 io.dingodb.expr.test.cases; public class EvalConstProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { return Stream.of( // Values arguments(val(1), 1), arguments(val(2L), 2L), arguments(val(3.3f), 3.3f), arguments(val(4.4), 4.4), arguments(val(true), true), arguments(val(false), false), arguments(dec(5.5), BigDecimal.valueOf(5.5)), arguments(val("abc"), "abc"), arguments(bytes("123"), "123".getBytes(StandardCharsets.UTF_8)), arguments(date(1L), new Date(sec(1L))), arguments(time(2L), new Time(sec(2L))), arguments(ts(3L), new Timestamp(sec(3L))), arguments(val(null), null), // Castings arguments(op(TO_INT, 1), 1), arguments(op(TO_INT, 1L), 1), arguments(op(TO_INT_C, 1L), 1), arguments(op(TO_INT, 1.4f), 1), arguments(op(TO_INT_C, 1.4f), 1), arguments(op(TO_INT, 1.5f), 2), arguments(op(TO_INT_C, 1.5f), 2), arguments(op(TO_INT, 1.4), 1), arguments(op(TO_INT, 1.5), 2), arguments(op(TO_INT, true), 1), arguments(op(TO_INT, false), 0), arguments(op(TO_INT, dec(1.4)), 1), arguments(op(TO_INT_C, dec(1.4)), 1), arguments(op(TO_INT, dec(1.5)), 2), arguments(op(TO_INT_C, dec(1.5)), 2), arguments(op(TO_INT, "10"), 10), arguments(op(TO_LONG, 1), 1L), arguments(op(TO_LONG, 1L), 1L), arguments(op(TO_LONG, 1.4f), 1L), arguments(op(TO_LONG_C, 1.4f), 1L), arguments(op(TO_LONG, 1.5f), 2L), arguments(op(TO_LONG_C, 1.4f), 1L), arguments(op(TO_LONG, 1.4), 1L), arguments(op(TO_LONG, 1.5), 2L), arguments(op(TO_LONG, true), 1L), arguments(op(TO_LONG, false), 0L), arguments(op(TO_LONG, dec(1.4)), 1L), arguments(op(TO_LONG, dec(1.5)), 2L), arguments(op(TO_LONG, "10"), 10L), arguments(op(TO_FLOAT, 1), 1.0f), arguments(op(TO_FLOAT, 1L), 1.0f), arguments(op(TO_FLOAT, 1.4f), 1.4f), arguments(op(TO_FLOAT, 1.4), 1.4f), arguments(op(TO_FLOAT, true), 1.0f), arguments(op(TO_FLOAT, false), 0.0f), arguments(op(TO_FLOAT, dec(1.4)), 1.4f), arguments(op(TO_FLOAT, "12.3"), 12.3f), arguments(op(TO_DOUBLE, 1), 1.0), arguments(op(TO_DOUBLE, 1L), 1.0), arguments(op(TO_DOUBLE, 1.4f), 1.4), arguments(op(TO_DOUBLE, 1.4), 1.4), arguments(op(TO_DOUBLE, true), 1.0), arguments(op(TO_DOUBLE, false), 0.0), arguments(op(TO_DOUBLE, dec(1.4)), 1.4), arguments(op(TO_DOUBLE, "12.3"), 12.3), arguments(op(TO_BOOL, 1), true), arguments(op(TO_BOOL, 0), false), arguments(op(TO_BOOL, 1L), true), arguments(op(TO_BOOL, 0L), false), arguments(op(TO_BOOL, 1.4f), true), arguments(op(TO_BOOL, 0.0f), false), arguments(op(TO_BOOL, 1.4), true), arguments(op(TO_BOOL, 0.0), false), arguments(op(TO_BOOL, true), true), arguments(op(TO_BOOL, false), false), arguments(op(TO_BOOL, val(BigDecimal.ONE)), true), arguments(op(TO_BOOL, val(BigDecimal.ZERO)), false), arguments(op(TO_DECIMAL, 1), BigDecimal.ONE), arguments(op(TO_DECIMAL, 1L), BigDecimal.ONE), arguments(op(TO_DECIMAL, 1.4f), BigDecimal.valueOf(1.4f)), arguments(op(TO_DECIMAL, 1.4), BigDecimal.valueOf(1.4)), arguments(op(TO_DECIMAL, true), BigDecimal.ONE), arguments(op(TO_DECIMAL, false), BigDecimal.ZERO), arguments(op(TO_DECIMAL, dec(1.4)), BigDecimal.valueOf(1.4)), arguments(op(TO_DECIMAL, "12.3"), BigDecimal.valueOf(12.3)), arguments(op(TO_STRING, 1), "1"), arguments(op(TO_STRING, 1L), "1"), arguments(op(TO_STRING, 1.4f), "1.4"), arguments(op(TO_STRING, 1.4), "1.4"), arguments(op(TO_STRING, true), "true"), arguments(op(TO_STRING, false), "false"), arguments(op(TO_STRING, dec(12.3)), "12.3"), arguments(op(TO_STRING, "abc"), "abc"), arguments(op(TO_BYTES, bytes("abc")), "abc".getBytes(StandardCharsets.UTF_8)), arguments(op(TO_BYTES, "abc"), "abc".getBytes(StandardCharsets.UTF_8)), arguments(op(TO_DATE, 1), new Date(sec(1L))), arguments(op(TO_DATE, 1L), new Date(sec(1L))), arguments(op(TO_DATE, "1970-01-01"), new Date(sec(0L))), arguments(op(TO_DATE, date(1L)), new Date(sec(1L))), arguments(op(TO_TIME, 1), new Time(sec(1L))), arguments(op(TO_TIME, 1L), new Time(sec(1L))), arguments(op(TO_TIME, "00:00:00"), new Time(sec(0L))), arguments(op(TO_TIME, time(1L)), new Time(sec(1L))), arguments(op(TO_TIMESTAMP, 1), new Timestamp(sec(1L))), arguments(op(TO_TIMESTAMP, 1L), new Timestamp(sec(1L))), arguments( op(TO_TIMESTAMP, "1970-01-01 00:00:00"), DateTimeUtils.parseTimestamp("1970-01-01 00:00:00") ), arguments(op(TO_TIMESTAMP, ts(1L)), new Timestamp(sec(1L))), // Arithmetics arguments(op(POS, 1), 1), arguments(op(POS, 1L), 1L), arguments(op(POS, 1.1f), 1.1f), arguments(op(POS, 1.1), 1.1), arguments(op(POS, dec(1.1)), BigDecimal.valueOf(1.1)), arguments(op(NEG, 1), -1), arguments(op(NEG, 1L), -1L), arguments(op(NEG, 1.1f), -1.1f), arguments(op(NEG, 1.1), -1.1), arguments(op(NEG, dec(1.1)), BigDecimal.valueOf(-1.1)), arguments(op(ADD, 1, 2), 3), arguments(op(ADD, 1L, 2L), 3L), arguments(op(ADD, 1.1f, 2.2f), 3.3f), arguments(op(ADD, 1.1, 2.2), 3.3), arguments(op(ADD, dec(1.1), dec(2.2)), BigDecimal.valueOf(3.3)), arguments(op(ADD, 1, 2L), 3L), arguments(op(ADD, 1L, 2.2f), 3.2f), arguments(op(ADD, 1.1f, 2.2), 3.3), arguments(op(ADD, 1.1, dec(2.2)), BigDecimal.valueOf(3.3)), arguments(op(ADD, "a", "bc"), "abc"), arguments(op(SUB, 1, 2), -1), arguments(op(SUB, 1L, 2L), -1L), arguments(op(SUB, 1.1f, 2.2f), -1.1f), arguments(op(SUB, 1.1, 2.2), -1.1), arguments(op(SUB, dec(1.1), dec(2.2)), BigDecimal.valueOf(-1.1)), arguments(op(SUB, 1, 2L), -1L), arguments(op(SUB, 1L, 2.2f), -1.2f), arguments(op(SUB, 1.1f, 2.2), -1.1), arguments(op(SUB, 1.1, dec(2.2)), BigDecimal.valueOf(-1.1)), arguments(op(MUL, 1, 2), 2), arguments(op(MUL, 1L, 2L), 2L), arguments(op(MUL, 1.1f, 2.2f), 2.42f), arguments(op(MUL, 1.1, 2.2), 2.42), arguments(op(MUL, dec(1.1), dec(2.2)), BigDecimal.valueOf(2.42)), arguments(op(MUL, 1, 2L), 2L), arguments(op(MUL, 1L, 2.2f), 2.2f), arguments(op(MUL, 1.1f, 2.2), 2.42), arguments(op(MUL, 1.1, dec(2.2)), BigDecimal.valueOf(2.42)), arguments(op(DIV, 1, 2), 0), arguments(op(DIV, 1L, 2L), 0L), arguments(op(DIV, 1.1f, 2.2f), 0.5f), arguments(op(DIV, 1.1, 2.2), 0.5), arguments(op(DIV, dec(1.1), dec(2.2)), BigDecimal.valueOf(0.5)), arguments(op(DIV, 1, 2L), 0L), arguments(op(DIV, 1L, 2.0f), 0.5f), arguments(op(DIV, 1.1f, 2.2), 0.5), arguments(op(DIV, 1.1, dec(2.2)), BigDecimal.valueOf(0.5)), arguments(op(DIV, 1, 0), null), arguments(op(DIV, 1.1f, 0.0f), null), arguments(op(DIV, 1.2, 0.0), null), arguments(op(DIV, dec(1.3), dec(0)), null), // Relations arguments(op(EQ, 1, 1), true), arguments(op(EQ, 1L, 2L), false), arguments(op(EQ, 1.1f, 1.1f), true), arguments(op(EQ, 1.1, 2.2), false), arguments(op(EQ, true, true), true), arguments(op(EQ, dec(1.1), dec(2.2)), false), arguments(op(EQ, "abc", "abc"), true), arguments(op(EQ, date(1L), date(2L)), false), arguments(op(EQ, time(1L), time(1L)), true), arguments(op(EQ, ts(2L), ts(1L)), false), arguments(op(NE, 1, 1), false), arguments(op(NE, 1L, 2L), true), arguments(op(NE, 1.1f, 1.1f), false), arguments(op(NE, 1.1, 2.2), true), arguments(op(NE, true, true), false), arguments(op(NE, dec(1.1), dec(2.2)), true), arguments(op(NE, "abc", "abc"), false), arguments(op(NE, date(1L), date(2L)), true), arguments(op(NE, time(1L), time(1L)), false), arguments(op(NE, ts(2L), ts(1L)), true), arguments(op(GT, 1, 1), false), arguments(op(GT, 1L, 2L), false), arguments(op(GT, 1.1f, 1.1f), false), arguments(op(GT, 1.1, 2.2), false), arguments(op(GT, true, true), false), arguments(op(GT, dec(1.1), dec(2.2)), false), arguments(op(GT, "abc", "abc"), false), arguments(op(GT, date(1L), date(2L)), false), arguments(op(GT, time(1L), time(1L)), false), arguments(op(GT, ts(2L), ts(1L)), true), arguments(op(GE, 1, 1), true), arguments(op(GE, 1L, 2L), false), arguments(op(GE, 1.1f, 1.1f), true), arguments(op(GE, 1.1, 2.2), false), arguments(op(GE, true, true), true), arguments(op(GE, dec(1.1), dec(2.2)), false), arguments(op(GE, "abc", "abc"), true), arguments(op(GE, date(1L), date(2L)), false), arguments(op(GE, time(1L), time(1L)), true), arguments(op(GE, ts(2L), ts(1L)), true), arguments(op(LT, 1, 1), false), arguments(op(LT, 1L, 2L), true), arguments(op(LT, 1.1f, 1.1f), false), arguments(op(LT, 1.1, 2.2), true), arguments(op(LT, true, true), false), arguments(op(LT, dec(1.1), dec(2.2)), true), arguments(op(LT, "abc", "abc"), false), arguments(op(LT, date(1L), date(2L)), true), arguments(op(LT, time(1L), time(1L)), false), arguments(op(LT, ts(2L), ts(1L)), false), arguments(op(LE, 1, 1), true), arguments(op(LE, 1L, 2L), true), arguments(op(LE, 1.1f, 1.1f), true), arguments(op(LE, 1.1, 2.2), true), arguments(op(LE, true, true), true), arguments(op(LE, dec(1.1), dec(2.2)), true), arguments(op(LE, "abc", "abc"), true), arguments(op(LE, date(1L), date(2L)), true), arguments(op(LE, time(1L), time(1L)), true), arguments(op(LE, ts(2L), ts(1L)), false), // Logics arguments(op(AND, false, false), false), arguments(op(AND, false, true), false), arguments(op(AND, false, NULL_BOOL), false), arguments(op(AND, true, false), false), arguments(op(AND, true, true), true), arguments(op(AND, true, NULL_BOOL), null), arguments(op(AND, NULL_BOOL, false), false), arguments(op(AND, NULL_BOOL, true), null), arguments(op(AND, NULL_BOOL, NULL_BOOL), null), arguments(op(OR, false, false), false), arguments(op(OR, false, true), true), arguments(op(OR, false, NULL_BOOL), null), arguments(op(OR, true, false), true), arguments(op(OR, true, true), true), arguments(op(OR, true, NULL_BOOL), true), arguments(op(OR, NULL_BOOL, false), null), arguments(op(OR, NULL_BOOL, true), true), arguments(op(OR, NULL_BOOL, NULL_BOOL), null), arguments(op(NOT, false), true), arguments(op(NOT, true), false), arguments(op(NOT, NULL_BOOL), null), arguments(op(AND_FUN, true, false, true), false), arguments(op(AND_FUN, true, NULL_BOOL, true), null), arguments(op(AND_FUN, true, true, true), true), arguments(op(OR_FUN, true, false, true), true), arguments(op(OR_FUN, false, NULL_BOOL, false), null), arguments(op(OR_FUN, false, false, false), false), // Specials arguments(op(IS_NULL, 1), false), arguments(op(IS_NULL, NULL_INT), true), arguments(op(IS_NULL, 1L), false), arguments(op(IS_NULL, NULL_LONG), true), arguments(op(IS_NULL, 1.1f), false), arguments(op(IS_NULL, NULL_FLOAT), true), arguments(op(IS_NULL, 1.1), false), arguments(op(IS_NULL, NULL_DOUBLE), true), arguments(op(IS_NULL, false), false), arguments(op(IS_NULL, NULL_BOOL), true), arguments(op(IS_NULL, dec(1)), false), arguments(op(IS_NULL, NULL_DECIMAL), true), arguments(op(IS_NULL, ""), false), arguments(op(IS_NULL, NULL_STRING), true), arguments(op(IS_NULL, bytes("")), false), arguments(op(IS_NULL, NULL_BYTES), true), arguments(op(IS_NULL, date(0)), false), arguments(op(IS_NULL, NULL_DATE), true), arguments(op(IS_NULL, time(0)), false), arguments(op(IS_NULL, NULL_TIME), true), arguments(op(IS_NULL, ts(0)), false), arguments(op(IS_NULL, NULL_TIMESTAMP), true), arguments(op(IS_TRUE, 1), true), arguments(op(IS_TRUE, 0), false), arguments(op(IS_TRUE, NULL_INT), false), arguments(op(IS_TRUE, 1L), true), arguments(op(IS_TRUE, 0L), false), arguments(op(IS_TRUE, NULL_LONG), false), arguments(op(IS_TRUE, 1.1f), true), arguments(op(IS_TRUE, 0.0f), false), arguments(op(IS_TRUE, NULL_FLOAT), false), arguments(op(IS_TRUE, 1.1), true), arguments(op(IS_TRUE, 0.0), false), arguments(op(IS_TRUE, NULL_DOUBLE), false), arguments(op(IS_TRUE, true), true), arguments(op(IS_TRUE, false), false), arguments(op(IS_TRUE, NULL_BOOL), false), arguments(op(IS_TRUE, dec(1)), true), arguments(op(IS_TRUE, dec(0)), false), arguments(op(IS_TRUE, NULL_DECIMAL), false), arguments(op(IS_TRUE, "abc"), false), arguments(op(IS_TRUE, ""), false), arguments(op(IS_TRUE, NULL_STRING), false), arguments(op(IS_TRUE, bytes("abc")), false), arguments(op(IS_TRUE, bytes("")), false), arguments(op(IS_TRUE, NULL_BYTES), false), arguments(op(IS_TRUE, date(0)), true), arguments(op(IS_TRUE, NULL_DATE), false), arguments(op(IS_TRUE, time(0)), true), arguments(op(IS_TRUE, NULL_TIME), false), arguments(op(IS_TRUE, ts(0)), true), arguments(op(IS_TRUE, NULL_TIMESTAMP), false), arguments(op(IS_FALSE, 1), false), arguments(op(IS_FALSE, 0), true), arguments(op(IS_FALSE, NULL_INT), false), arguments(op(IS_FALSE, 1L), false), arguments(op(IS_FALSE, 0L), true), arguments(op(IS_FALSE, NULL_LONG), false), arguments(op(IS_FALSE, 1.1f), false), arguments(op(IS_FALSE, 0.0f), true), arguments(op(IS_FALSE, NULL_FLOAT), false), arguments(op(IS_FALSE, 1.1), false), arguments(op(IS_FALSE, 0.0), true), arguments(op(IS_FALSE, NULL_DOUBLE), false), arguments(op(IS_FALSE, true), false), arguments(op(IS_FALSE, false), true), arguments(op(IS_FALSE, NULL_BOOL), false), arguments(op(IS_FALSE, dec(1)), false), arguments(op(IS_FALSE, dec(0)), true), arguments(op(IS_FALSE, NULL_DECIMAL), false), arguments(op(IS_FALSE, "abc"), true), arguments(op(IS_FALSE, ""), true), arguments(op(IS_FALSE, NULL_STRING), false), arguments(op(IS_FALSE, bytes("abc")), true), arguments(op(IS_FALSE, bytes("")), true), arguments(op(IS_FALSE, NULL_BYTES), false), arguments(op(IS_FALSE, date(0)), false), arguments(op(IS_FALSE, NULL_DATE), false), arguments(op(IS_FALSE, time(0)), false), arguments(op(IS_FALSE, NULL_TIME), false), arguments(op(IS_FALSE, ts(0)), false), arguments(op(IS_FALSE, NULL_TIMESTAMP), false), arguments(op(CASE, 100), 100), arguments(op(CASE, true, 1, 100), 1), arguments(op(CASE, false, 1, true, 2, 100), 2), // Mathematics arguments(op(ABS, -1), 1), arguments(op(ABS, 1), 1), arguments(op(ABS, -1L), 1L), arguments(op(ABS, 1L), 1L), arguments(op(ABS, -0.5f), 0.5f), arguments(op(ABS, 0.5f), 0.5f), arguments(op(ABS, -0.5), 0.5), arguments(op(ABS, 0.5), 0.5), arguments(op(ABS, dec(-0.5)), BigDecimal.valueOf(0.5)), arguments(op(ABS, dec(0.5)), BigDecimal.valueOf(0.5)), arguments(op(ABS_C, -1), 1), arguments(op(ABS_C, 1), 1), arguments(op(ABS_C, -1L), 1L), arguments(op(ABS_C, 1L), 1L), arguments(op(ABS_C, -0.5f), 0.5f), arguments(op(ABS_C, 0.5f), 0.5f), arguments(op(ABS_C, -0.5), 0.5), arguments(op(ABS_C, 0.5), 0.5), arguments(op(ABS_C, dec(-0.5)), BigDecimal.valueOf(0.5)), arguments(op(ABS_C, dec(0.5)), BigDecimal.valueOf(0.5)), arguments(op(MIN, 1, 2), 1), arguments(op(MIN, 1L, 2L), 1L), arguments(op(MIN, 1.1f, 2.2f), 1.1f), arguments(op(MIN, 1.1, 2.2), 1.1), arguments(op(MIN, dec(1.1), dec(2.2)), BigDecimal.valueOf(1.1)), arguments(op(MIN, "abc", "def"), "abc"), arguments(op(MIN, date(1L), date(2L)), new Date(sec(1L))), arguments(op(MIN, time(1L), time(2L)), new Time(sec(1L))), arguments(op(MIN, ts(1L), ts(2L)), new Timestamp(sec(1L))), arguments(op(MAX, 1, 2), 2), arguments(op(MAX, 1L, 2L), 2L), arguments(op(MAX, 1.1f, 2.2f), 2.2f), arguments(op(MAX, 1.1, 2.2), 2.2), arguments(op(MAX, dec(1.1), dec(2.2)), BigDecimal.valueOf(2.2)), arguments(op(MAX, "abc", "def"), "def"), arguments(op(MAX, date(1L), date(2L)), new Date(sec(2L))), arguments(op(MAX, time(1L), time(2L)), new Time(sec(2L))), arguments(op(MAX, ts(1L), ts(2L)), new Timestamp(sec(2L))), arguments(op(MOD, 4, 3), 1), arguments(op(MOD, -4, 3), -1), arguments(op(MOD, 1, 0), null), arguments(op(MOD, 4L, -3L), 1L), arguments(op(MOD, -4L, -3L), -1L), arguments(op(MOD, 1L, 0L), null), arguments(op(MOD, dec(5.0), dec(2.5)), BigDecimal.valueOf(0.0)), arguments(op(MOD, dec(5.1), dec(2.5)), BigDecimal.valueOf(0.1)), arguments(op(MOD, dec(5.1), dec(0)), null), arguments(op(SIN, 0), 0.0), arguments(op(SIN, Math.PI / 6), 0.5), arguments(op(SIN, Math.PI / 2), 1.0), arguments(op(SIN, 5 * Math.PI / 6), 0.5), arguments(op(SIN, Math.PI), 0.0), arguments(op(SIN, 7 * Math.PI / 6), -0.5), arguments(op(SIN, 3 * Math.PI / 2), -1.0), arguments(op(SIN, 11 * Math.PI / 6), -0.5), arguments(op(SIN, 2 * Math.PI), 0.0), arguments(op(COS, 0), 1.0), arguments(op(COS, Math.PI / 3), 0.5), arguments(op(COS, Math.PI / 2), 0.0), arguments(op(COS, 2 * Math.PI / 3), -0.5), arguments(op(COS, Math.PI), -1.0), arguments(op(COS, 4 * Math.PI / 3), -0.5), arguments(op(COS, 3 * Math.PI / 2), 0.0), arguments(op(COS, 5 * Math.PI / 3), 0.5), arguments(op(COS, 2 * Math.PI), 1.0), arguments(op(TAN, 0), 0.0), arguments(op(TAN, Math.PI / 4), 1.0), arguments(op(TAN, 3 * Math.PI / 4), -1.0), arguments(op(TAN, Math.PI), 0.0), arguments(op(TAN, 5 * Math.PI / 4), 1.0), arguments(op(TAN, 7 * Math.PI / 4), -1.0), arguments(op(TAN, 2 * Math.PI), 0.0), arguments(op(ASIN, -1), -Math.PI / 2), arguments(op(ASIN, -0.5), -Math.PI / 6), arguments(op(ASIN, 0), 0.0), arguments(op(ASIN, 0.5), Math.PI / 6), arguments(op(ASIN, 1), Math.PI / 2), arguments(op(ACOS, -1), Math.PI), arguments(op(ACOS, -0.5), 2 * Math.PI / 3), arguments(op(ACOS, 0), Math.PI / 2), arguments(op(ACOS, 0.5), Math.PI / 3), arguments(op(ACOS, 1), 0.0), arguments(op(ATAN, -1), -Math.PI / 4), arguments(op(ATAN, 0), 0.0), arguments(op(ATAN, 1), Math.PI / 4), arguments(op(SINH, 0), 0.0), arguments(op(COSH, 0), 1.0), arguments(op(TANH, 0), 0.0), arguments(op(EXP, 0), 1.0), arguments(op(EXP, 1), Math.exp(1.0)), arguments(op(LOG, Math.E), 1.0), arguments(op(LOG, 1.0 / Math.E), -1.0), arguments(op(CEIL, 1), 1), arguments(op(CEIL, 1L), 1L), arguments(op(CEIL, 2.3f), 3.0), arguments(op(CEIL, 3.4), 4.0), arguments(op(CEIL, dec(1.23)), BigDecimal.valueOf(2)), arguments(op(FLOOR, 1), 1), arguments(op(FLOOR, 1L), 1L), arguments(op(FLOOR, 2.5f), 2.0), arguments(op(FLOOR, 3.6), 3.0), arguments(op(FLOOR, dec(1.23)), BigDecimal.valueOf(1)), arguments(op(POW, 2, 3), 8.0), arguments(op(POW, 3, 3), 27.0), arguments(op(POW, -3.1, 3), -29.791), arguments(op(POW, "10", -2), 0.01), arguments(op(ROUND2, 123, -2), 100), arguments(op(ROUND2, 12.677, 2), 12.68), arguments(op(ROUND2, 195334.12, -4), 200000.0), arguments(op(ROUND2, -155.586, -2), -200.0), arguments(op(ROUND2, 101, -2), 100), arguments(op(ROUND2, 101.0, -2), 100.0), arguments(op(ROUND2, 105, -2), 100), arguments(op(ROUND2, dec(105), -1), BigDecimal.valueOf(110)), arguments(op(ROUND2, 105, "-2"), 100), arguments(op(ROUND1, 10), 10), arguments(op(ROUND2, 3.6, 0), 4.0), arguments(op(ROUND1, 3.4), 3.0), // Strings arguments(op(CHAR_LENGTH, NULL_STRING), null), arguments(op(CHAR_LENGTH, ""), 0), arguments(op(CHAR_LENGTH, "Alice"), 5), arguments(op(CONCAT, NULL_STRING, "Betty"), null), arguments(op(CONCAT, "Alice", NULL_STRING), null), arguments(op(CONCAT, "Alice", "Betty"), "AliceBetty"), arguments(op(LOWER, "HeLLo"), "hello"), arguments(op(UPPER, "HeLLo"), "HELLO"), arguments(op(LEFT, NULL_STRING, 1), null), arguments(op(LEFT, "Alice", NULL_INT), null), arguments(op(LEFT, "Alice", 0), ""), arguments(op(LEFT, "Alice", -1), ""), arguments(op(LEFT, "Alice", 10), "Alice"), arguments(op(LEFT, "Alice", 3), "Ali"), arguments(op(LEFT, "Alice", 3.5), "Alic"), arguments(op(RIGHT, NULL_STRING, 1), null), arguments(op(RIGHT, "Alice", NULL_INT), null), arguments(op(RIGHT, "Alice", 0), ""), arguments(op(RIGHT, "Alice", -1), ""), arguments(op(RIGHT, "Alice", 10), "Alice"), arguments(op(RIGHT, "Alice", 3), "ice"), arguments(op(RIGHT, "Alice", 3.5), "lice"), arguments(op(TRIM1, " HeLLo "), "HeLLo"), arguments(op(TRIM2, "aBcHeLLoaBcaBc", "aBc"), "HeLLo"), arguments(op(LTRIM1, NULL_STRING), null), arguments(op(LTRIM1, " HeLLo "), "HeLLo "), arguments(op(LTRIM2, "aBcaBcHeLLoaBc", "aBc"), "HeLLoaBc"), arguments(op(RTRIM1, NULL_STRING), null), arguments(op(RTRIM1, " HeLLo "), " HeLLo"), arguments(op(RTRIM2, "aBcHeLLoaBc", "aBc"), "aBcHeLLo"), arguments(op(SUBSTR2, "HeLLo", 2), "LLo"), arguments(op(SUBSTR2, "HeLLo", 2.5), "Lo"), arguments(op(SUBSTR3, "HeLLo", 1, 3), "eL"), arguments(op(MID2, "Alice", 2), "lice"), arguments(op(MID2, "Alice", 0), ""), arguments(op(MID2, "Alice", NULL_INT), null), arguments(op(MID2, "Alice", -2), "ce"), arguments(op(MID3, NULL_STRING, 0, 0), null), arguments(op(MID3, "Alice", NULL_INT, 0), null), arguments(op(MID3, "Alice", 1, NULL_INT), null), arguments(op(MID3, "Alice", 0, 0), ""), arguments(op(MID3, "Alice", 1, 0), ""), arguments(op(MID3, "Alice", 1, 3), "Ali"), arguments(op(MID3, "Alice", -1, 1), "e"), arguments(op(MID3, "Alice", -3, 2), "ic"), arguments(op(MID3, "Alice", -3, 1.5), "ic"), arguments(op(REPEAT, NULL_STRING, 3), null), arguments(op(REPEAT, "Abc", -1), ""), arguments(op(REPEAT, "Abc", 3), "AbcAbcAbc"), arguments(op(REPEAT, "Abc", 1.7), "AbcAbc"), arguments(op(REVERSE, NULL_STRING), null), arguments(op(REVERSE, "AbCdE"), "EdCbA"), arguments(op(REPLACE, "HeLLo", "eL", "El"), "HElLo"), arguments(op(REPLACE, NULL, "a", "b"), null), arguments(op(LOCATE2, NULL_STRING, "a"), null), arguments(op(LOCATE2, "at", "Water"), 2), arguments(op(LOCATE2, "am", "Water"), 0), arguments(op(LOCATE2, NULL_STRING, "Water"), null), arguments(op(LOCATE2, "", "Water"), 1), arguments(op(LOCATE3, "", "Water", 3), 3), arguments(op(LOCATE3, "a", "Banana", 3), 4), arguments(op(LOCATE3, "a", "Banana", 7), 0), arguments(op(LOCATE3, "a", "Banana", 3.5), 4), arguments(op(HEX, "414243"), "ABC".getBytes(StandardCharsets.UTF_8)), arguments(op(FORMAT, 100.21, 1), "100.2"), arguments(op(FORMAT, 99.00000, 2), "99.00"), arguments(op(FORMAT, 1220.532, 0), "1221"), arguments(op(FORMAT, 18, 2), "18.00"), arguments(op(FORMAT, 15354.6651, 1.6), "15354.67"), arguments(op(MATCHES, "abc123", ".*c\\d{2}."), true), arguments(op(MATCHES, "abc123", "c\\d{2}"), false), arguments(op(MATCHES, "abc123", "Abc\\d{3}"), false), arguments(op(MATCHES_NC, "abc123", "Abc\\d{3}"), true), arguments(op(_CTF, "%Y"), "uuuu"), arguments(op(_CTF, "%Y-%m-%d"), "uuuu'-'MM'-'dd"), arguments(op(_CTF, "%A%B%C"), "'ABC'"), arguments(op(_CTF, "Year: %Y, Month: %m"), "'Year: 'uuuu', Month: 'MM"), arguments(op(_CP1, "%"), ".*"), arguments(op(_CP1, "_"), "."), arguments(op(_CP1, "a_b%c"), "a.b.*c"), arguments(op(_CP1, "a\\_b\\%c"), "a_b%c"), arguments(op(_CP1, "a\\nb\\%c"), "a\\nb%c"), arguments(op(_CP2, "a\\_b\\%c", "|"), "a\\.b\\.*c"), arguments(op(_CP2, "a|_b|%c", "|"), "a_b%c"), // Date & times arguments(op(DATE_FORMAT1, 0), "1970-01-01"), arguments(op(DATE_FORMAT2, 0, "uuuu:MM:dd"), "1970:01:01"), arguments(op(DATE_FORMAT2, 0, op(_CTF, "%Y:%m:%d")), "1970:01:01"), arguments(op(TIME_FORMAT1, 0), "00:00:00"), arguments(op(TIME_FORMAT2, 0, "HH-mm-ss"), "00-00-00"), arguments(op(TIME_FORMAT2, 0, op(_CTF, "%H-%i-%s")), "00-00-00"), arguments( op(TIMESTAMP_FORMAT1, 0), DateTimeUtils.timestampFormat(new Timestamp(0), DateTimeUtils.DEFAULT_OUTPUT_TIMESTAMP_FORMATTER) ), arguments( op(TIMESTAMP_FORMAT2, 0, "uuuuMMddHHmmss"), DateTimeUtils.timestampFormat(new Timestamp(0), "uuuuMMddHHmmss") ), arguments( op(TIMESTAMP_FORMAT2, 0, op(_CTF, "%Y%m%d%H%i%s")), DateTimeUtils.timestampFormat(new Timestamp(0), "uuuuMMddHHmmss") ), arguments(op(FROM_UNIXTIME, 1), new Timestamp(sec(1L))), arguments(op(FROM_UNIXTIME, 1L), new Timestamp(sec(1L))), arguments(op(FROM_UNIXTIME, dec(1.23)), new Timestamp(sec(BigDecimal.valueOf(1.23)))), arguments(op(UNIX_TIMESTAMP1, ts(1L)), 1L), arguments(op(UNIX_TIMESTAMP1, 2L), 2L), arguments(op(UNIX_TIMESTAMP1, 3.5), 4L), arguments(op(DATEDIFF, 24L * 60L * 60L, 0L), 1L), // Collections arguments(op(ARRAY, 1, 2, 3), new int[]{1, 2, 3}), arguments(op(ARRAY, 1L, 2, 3), new long[]{1L, 2L, 3L}), arguments(op(ARRAY, 1L, 2.0, 3), new double[]{1.0, 2.0, 3.0}), arguments(op(LIST, 1, 2, 3), Arrays.asList(1, 2, 3)), arguments(op(LIST, 1L, 2, 3), Arrays.asList(1L, 2L, 3L)), arguments(op(LIST, 1L, 2.0, 3), Arrays.asList(1.0, 2.0, 3.0)), arguments(op(MAP, 'a', 1, 'b', 2), ImmutableMap.of('a', 1, 'b', 2)), arguments(op(MAP, 1, 1, 2, 2), ImmutableMap.of(1, 1, 2, 2)), arguments(op(MAP, '1', 1, 2, '2'), ImmutableMap.of('1', 1, 2, '2')), arguments(op(TO_ARRAY_INT, op(ARRAY, 1.1, 2.2, 3.3, 4.4, 5.5)), new int[]{1, 2, 3, 4, 6}), arguments(op(TO_ARRAY_INT_C, op(ARRAY, 1.1, 2.2, 3.3, 4.4, 5.5)), new int[]{1, 2, 3, 4, 6}), arguments(op(TO_ARRAY_LONG, op(ARRAY, "1", "2", "3")), new long[]{1L, 2L, 3L}), arguments(op(TO_ARRAY_LONG_C, op(ARRAY, "1", "2", "3")), new long[]{1L, 2L, 3L}), arguments(op(TO_ARRAY_FLOAT, op(ARRAY, 1, 2, 3)), new float[]{1.0f, 2.0f, 3.0f}), arguments(op(TO_ARRAY_DOUBLE, op(ARRAY, 1, 2, 3)), new double[]{1.0, 2.0, 3.0}), arguments(op(TO_ARRAY_BOOL, op(ARRAY, 1, 0, 1)), new boolean[]{true, false, true}), arguments(op(TO_ARRAY_DECIMAL, op(ARRAY, 1, 0)), new BigDecimal[]{BigDecimal.ONE, BigDecimal.ZERO}), arguments(op(TO_ARRAY_STRING, op(ARRAY, 1, 2, 3)), new String[]{"1", "2", "3"}), arguments(op(TO_ARRAY_BYTES, op(ARRAY, "a", "b")), new byte[][]{"a".getBytes(), "b".getBytes()}), arguments(op(TO_ARRAY_DATE, op(ARRAY, 1, 2)), new Date[]{new Date(sec(1L)), new Date(sec(2L))}), arguments(op(TO_ARRAY_TIME, op(ARRAY, 1, 2)), new Time[]{new Time(sec(1L)), new Time(sec(2L))}), arguments(op(TO_ARRAY_TIMESTAMP, op(ARRAY, 1, 2)), new Timestamp[]{new Timestamp(sec(1L)), new Timestamp(sec(2L))}), arguments(op(TO_ARRAY_INT, op(LIST, 1.1, 2.2, 3.3, 4.4, 5.5)), new int[]{1, 2, 3, 4, 6}), arguments(op(TO_ARRAY_INT_C, op(LIST, 1.1, 2.2, 3.3, 4.4, 5.5)), new int[]{1, 2, 3, 4, 6}), arguments(op(TO_ARRAY_LONG, op(LIST, "1", "2", "3")), new long[]{1, 2, 3}), arguments(op(TO_ARRAY_LONG_C, op(LIST, "1", "2", "3")), new long[]{1, 2, 3}), arguments(op(TO_ARRAY_FLOAT, op(LIST, 1, 2, 3)), new float[]{1.0f, 2.0f, 3.0f}), arguments(op(TO_ARRAY_DOUBLE, op(LIST, 1, 2, 3)), new double[]{1.0, 2.0, 3.0}), arguments(op(TO_ARRAY_BOOL, op(LIST, 1, 0, 1)), new boolean[]{true, false, true}), arguments(op(TO_ARRAY_DECIMAL, op(LIST, 1, 0)), new BigDecimal[]{BigDecimal.ONE, BigDecimal.ZERO}), arguments(op(TO_ARRAY_STRING, op(LIST, 1, 2, 3)), new String[]{"1", "2", "3"}), arguments(op(TO_ARRAY_BYTES, op(LIST, "a", "b")), new byte[][]{"a".getBytes(), "b".getBytes()}), arguments(op(TO_ARRAY_DATE, op(LIST, 1, 2)), new Date[]{new Date(sec(1L)), new Date(sec(2L))}), arguments(op(TO_ARRAY_TIME, op(LIST, 1, 2)), new Time[]{new Time(sec(1L)), new Time(sec(2L))}), arguments(op(TO_ARRAY_TIMESTAMP, op(LIST, 1, 2)), new Timestamp[]{new Timestamp(sec(1L)), new Timestamp(sec(2L))}), arguments(op(TO_LIST_INT, op(ARRAY, 1.1, 2.2, 3.3, 4.4, 5.5)), Arrays.asList(1, 2, 3, 4, 6)), arguments(op(TO_LIST_INT_C, op(ARRAY, 1.1, 2.2, 3.3, 4.4, 5.5)), Arrays.asList(1, 2, 3, 4, 6)),
arguments(op(TO_LIST_LONG, op(ARRAY, "1", "2", "3")), Arrays.asList(1L, 2L, 3L)),
108
2023-11-04 08:43:49+00:00
24k
conductor-oss/conductor
java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/AnnotatedWorker.java
[ { "identifier": "Worker", "path": "client/src/main/java/com/netflix/conductor/client/worker/Worker.java", "snippet": "public interface Worker {\n\n /**\n * Retrieve the name of the task definition the worker is currently working on.\n *\n * @return the name of the task definition.\n *...
import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.util.*; import com.netflix.conductor.client.worker.Worker; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.TaskResult; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.sdk.workflow.def.tasks.DynamicFork; import com.netflix.conductor.sdk.workflow.def.tasks.DynamicForkInput; import com.netflix.conductor.sdk.workflow.task.InputParam; import com.netflix.conductor.sdk.workflow.task.OutputParam; import com.netflix.conductor.sdk.workflow.utils.ObjectMapperProvider; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper;
18,089
return result; } private Object[] getInvocationParameters(Task task) { Class<?>[] parameterTypes = workerMethod.getParameterTypes(); Parameter[] parameters = workerMethod.getParameters(); if (parameterTypes.length == 1 && parameterTypes[0].equals(Task.class)) { return new Object[] {task}; } else if (parameterTypes.length == 1 && parameterTypes[0].equals(Map.class)) { return new Object[] {task.getInputData()}; } return getParameters(task, parameterTypes, parameters); } private Object[] getParameters(Task task, Class<?>[] parameterTypes, Parameter[] parameters) { Annotation[][] parameterAnnotations = workerMethod.getParameterAnnotations(); Object[] values = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { Annotation[] paramAnnotation = parameterAnnotations[i]; if (paramAnnotation != null && paramAnnotation.length > 0) { Type type = parameters[i].getParameterizedType(); Class<?> parameterType = parameterTypes[i]; values[i] = getInputValue(task, parameterType, type, paramAnnotation); } else { values[i] = om.convertValue(task.getInputData(), parameterTypes[i]); } } return values; } private Object getInputValue( Task task, Class<?> parameterType, Type type, Annotation[] paramAnnotation) { InputParam ip = findInputParamAnnotation(paramAnnotation); if (ip == null) { return om.convertValue(task.getInputData(), parameterType); } final String name = ip.value(); final Object value = task.getInputData().get(name); if (value == null) { return null; } if (List.class.isAssignableFrom(parameterType)) { List<?> list = om.convertValue(value, List.class); if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Class<?> typeOfParameter = (Class<?>) parameterizedType.getActualTypeArguments()[0]; List<Object> parameterizedList = new ArrayList<>(); for (Object item : list) { parameterizedList.add(om.convertValue(item, typeOfParameter)); } return parameterizedList; } else { return list; } } else { return om.convertValue(value, parameterType); } } private static InputParam findInputParamAnnotation(Annotation[] paramAnnotation) { return (InputParam) Arrays.stream(paramAnnotation) .filter(ann -> ann.annotationType().equals(InputParam.class)) .findFirst() .orElse(null); } private TaskResult setValue(Object invocationResult, TaskResult result) { if (invocationResult == null) { result.setStatus(TaskResult.Status.COMPLETED); return result; } OutputParam opAnnotation = workerMethod.getAnnotatedReturnType().getAnnotation(OutputParam.class); if (opAnnotation != null) { String name = opAnnotation.value(); result.getOutputData().put(name, invocationResult); result.setStatus(TaskResult.Status.COMPLETED); return result; } else if (invocationResult instanceof TaskResult) { return (TaskResult) invocationResult; } else if (invocationResult instanceof Map) { Map resultAsMap = (Map) invocationResult; result.getOutputData().putAll(resultAsMap); result.setStatus(TaskResult.Status.COMPLETED); return result; } else if (invocationResult instanceof String || invocationResult instanceof Number || invocationResult instanceof Boolean) { result.getOutputData().put("result", invocationResult); result.setStatus(TaskResult.Status.COMPLETED); return result; } else if (invocationResult instanceof List) { List resultAsList = om.convertValue(invocationResult, List.class); result.getOutputData().put("result", resultAsList); result.setStatus(TaskResult.Status.COMPLETED); return result; } else if (invocationResult instanceof DynamicForkInput) { DynamicForkInput forkInput = (DynamicForkInput) invocationResult; List<com.netflix.conductor.sdk.workflow.def.tasks.Task<?>> tasks = forkInput.getTasks(); List<WorkflowTask> workflowTasks = new ArrayList<>(); for (com.netflix.conductor.sdk.workflow.def.tasks.Task<?> sdkTask : tasks) { workflowTasks.addAll(sdkTask.getWorkflowDefTasks()); }
/* * Copyright 2021 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.sdk.workflow.executor.task; public class AnnotatedWorker implements Worker { private String name; private Method workerMethod; private Object obj; private ObjectMapper om = new ObjectMapperProvider().getObjectMapper(); private int pollingInterval = 100; private Set<TaskResult.Status> failedStatuses = Set.of(TaskResult.Status.FAILED, TaskResult.Status.FAILED_WITH_TERMINAL_ERROR); public AnnotatedWorker(String name, Method workerMethod, Object obj) { this.name = name; this.workerMethod = workerMethod; this.obj = obj; om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } @Override public String getTaskDefName() { return name; } @Override public TaskResult execute(Task task) { TaskResult result = null; try { TaskContext context = TaskContext.set(task); Object[] parameters = getInvocationParameters(task); Object invocationResult = workerMethod.invoke(obj, parameters); result = setValue(invocationResult, context.getTaskResult()); if (!failedStatuses.contains(result.getStatus()) && result.getCallbackAfterSeconds() > 0) { result.setStatus(TaskResult.Status.IN_PROGRESS); } } catch (InvocationTargetException invocationTargetException) { if (result == null) { result = new TaskResult(task); } Throwable e = invocationTargetException.getCause(); e.printStackTrace(); if (e instanceof NonRetryableException) { result.setStatus(TaskResult.Status.FAILED_WITH_TERMINAL_ERROR); } else { result.setStatus(TaskResult.Status.FAILED); } result.setReasonForIncompletion(e.getMessage()); StringBuilder stackTrace = new StringBuilder(); for (StackTraceElement stackTraceElement : e.getStackTrace()) { String className = stackTraceElement.getClassName(); if (className.startsWith("jdk.") || className.startsWith(AnnotatedWorker.class.getName())) { break; } stackTrace.append(stackTraceElement); stackTrace.append("\n"); } result.log(stackTrace.toString()); } catch (Exception e) { throw new RuntimeException(e); } return result; } private Object[] getInvocationParameters(Task task) { Class<?>[] parameterTypes = workerMethod.getParameterTypes(); Parameter[] parameters = workerMethod.getParameters(); if (parameterTypes.length == 1 && parameterTypes[0].equals(Task.class)) { return new Object[] {task}; } else if (parameterTypes.length == 1 && parameterTypes[0].equals(Map.class)) { return new Object[] {task.getInputData()}; } return getParameters(task, parameterTypes, parameters); } private Object[] getParameters(Task task, Class<?>[] parameterTypes, Parameter[] parameters) { Annotation[][] parameterAnnotations = workerMethod.getParameterAnnotations(); Object[] values = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { Annotation[] paramAnnotation = parameterAnnotations[i]; if (paramAnnotation != null && paramAnnotation.length > 0) { Type type = parameters[i].getParameterizedType(); Class<?> parameterType = parameterTypes[i]; values[i] = getInputValue(task, parameterType, type, paramAnnotation); } else { values[i] = om.convertValue(task.getInputData(), parameterTypes[i]); } } return values; } private Object getInputValue( Task task, Class<?> parameterType, Type type, Annotation[] paramAnnotation) { InputParam ip = findInputParamAnnotation(paramAnnotation); if (ip == null) { return om.convertValue(task.getInputData(), parameterType); } final String name = ip.value(); final Object value = task.getInputData().get(name); if (value == null) { return null; } if (List.class.isAssignableFrom(parameterType)) { List<?> list = om.convertValue(value, List.class); if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Class<?> typeOfParameter = (Class<?>) parameterizedType.getActualTypeArguments()[0]; List<Object> parameterizedList = new ArrayList<>(); for (Object item : list) { parameterizedList.add(om.convertValue(item, typeOfParameter)); } return parameterizedList; } else { return list; } } else { return om.convertValue(value, parameterType); } } private static InputParam findInputParamAnnotation(Annotation[] paramAnnotation) { return (InputParam) Arrays.stream(paramAnnotation) .filter(ann -> ann.annotationType().equals(InputParam.class)) .findFirst() .orElse(null); } private TaskResult setValue(Object invocationResult, TaskResult result) { if (invocationResult == null) { result.setStatus(TaskResult.Status.COMPLETED); return result; } OutputParam opAnnotation = workerMethod.getAnnotatedReturnType().getAnnotation(OutputParam.class); if (opAnnotation != null) { String name = opAnnotation.value(); result.getOutputData().put(name, invocationResult); result.setStatus(TaskResult.Status.COMPLETED); return result; } else if (invocationResult instanceof TaskResult) { return (TaskResult) invocationResult; } else if (invocationResult instanceof Map) { Map resultAsMap = (Map) invocationResult; result.getOutputData().putAll(resultAsMap); result.setStatus(TaskResult.Status.COMPLETED); return result; } else if (invocationResult instanceof String || invocationResult instanceof Number || invocationResult instanceof Boolean) { result.getOutputData().put("result", invocationResult); result.setStatus(TaskResult.Status.COMPLETED); return result; } else if (invocationResult instanceof List) { List resultAsList = om.convertValue(invocationResult, List.class); result.getOutputData().put("result", resultAsList); result.setStatus(TaskResult.Status.COMPLETED); return result; } else if (invocationResult instanceof DynamicForkInput) { DynamicForkInput forkInput = (DynamicForkInput) invocationResult; List<com.netflix.conductor.sdk.workflow.def.tasks.Task<?>> tasks = forkInput.getTasks(); List<WorkflowTask> workflowTasks = new ArrayList<>(); for (com.netflix.conductor.sdk.workflow.def.tasks.Task<?> sdkTask : tasks) { workflowTasks.addAll(sdkTask.getWorkflowDefTasks()); }
result.getOutputData().put(DynamicFork.FORK_TASK_PARAM, workflowTasks);
4
2023-12-08 06:06:09+00:00
24k
10cks/fofaEX
src/main/java/Main.java
[ { "identifier": "CommonExecute", "path": "src/main/java/plugins/CommonExecute.java", "snippet": "public class CommonExecute {\n\n public static JTable table = new JTable(); // 表格\n\n public static void exportTableToExcel(JTable table) {\n XSSFWorkbook workbook = new XSSFWorkbook();\n\n ...
import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.util.*; import javax.swing.BorderFactory; import javax.swing.event.*; import java.awt.Color; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import plugins.CommonExecute; import plugins.CommonTemplate; import plugins.FofaHack; import tableInit.HighlightRenderer; import tableInit.RightClickFunctions; import javax.swing.table.*; import javax.swing.text.Document; import javax.swing.undo.UndoManager; import static java.awt.BorderLayout.*; import static java.lang.Thread.sleep; import static plugins.CommonTemplate.saveTableData; import static plugins.CommonTemplate.switchTab; import static tableInit.GetjTableHeader.adjustColumnWidths; import static tableInit.GetjTableHeader.getjTableHeader; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors;
16,564
public class Main { // 创建输入框 private static JTextField fofaUrl = createTextField("https://fofa.info"); private static JTextField fofaEmail = createTextField("当前版本不需要输入邮箱"); private static JTextField fofaKey = createTextField("请输入API key"); private static String rulesPath = "rules.txt"; private static String accountsPath = "accounts.json"; // 设置 field 规则 private static boolean hostMark = true; private static boolean ipMark = true; private static boolean portMark = true; private static boolean protocolMark = true; private static boolean titleMark = true; private static boolean domainMark = true; private static boolean linkMark = true; private static boolean icpMark = false; private static boolean cityMark = false; private static boolean countryMark = false; /* 下面未完成 */ private static boolean country_nameMark = false; private static boolean regionMark = false; private static boolean longitudeMark = false; private static boolean latitudeMark = false; private static boolean asNumberMark = false; private static boolean asOrganizationMark = false; private static boolean osMark = false; private static boolean serverMark = false; private static boolean jarmMark = false; private static boolean headerMark = false; private static boolean bannerMark = false; private static boolean baseProtocolMark = false; private static boolean certsIssuerOrgMark = false; private static boolean certsIssuerCnMark = false; private static boolean certsSubjectOrgMark = false; private static boolean certsSubjectCnMark = false; private static boolean tlsJa3sMark = false; private static boolean tlsVersionMark = false; private static boolean productMark = false; private static boolean productCategoryMark = false; private static boolean versionMark = false; private static boolean lastupdatetimeMark = false; private static boolean cnameMark = false; private static boolean iconHashMark = false; private static boolean certsValidMark = false; private static boolean cnameDomainMark = false; private static boolean bodyMark = false; private static boolean iconMark = false; private static boolean fidMark = false; private static boolean structinfoMark = false; private static boolean scrollPaneMark = true; // 标记 private static boolean exportButtonAdded = false; private static boolean timeAdded = false; private static JLabel timeLabel; private static int queryTotalNumber; private static int numberOfItems; private static int currentPage = 1; private static boolean setFull = true; private static int sizeSetting = 10000; private static boolean openFileMark = false; // 创建全局数据表 private static JTable table; // 在类的成员变量中创建弹出菜单 private static JPopupMenu popupMenu = new JPopupMenu(); private static JMenuItem itemSelectColumn = new JMenuItem("选择当前整列"); private static JMenuItem itemDeselectColumn = new JMenuItem("取消选择整列"); private static JMenuItem itemOpenLink = new JMenuItem("打开链接"); static JMenuItem itemCopy = new JMenuItem("复制"); private static JMenuItem itemSearch = new JMenuItem("表格搜索"); private static File lastOpenedPath; // 添加一个成员变量来保存上次打开的文件路径 static TableCellRenderer highlightRenderer = new HighlightRenderer(); private static TableCellRenderer defaultRenderer; private static JTabbedPane tabbedPane0; public static void main(String[] args) throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException, FileNotFoundException { JFrame jFrame = new JFrame("fofaEX"); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); try { URL resource = Main.class.getResource("icon.png"); jFrame.setIconImage((new ImageIcon(resource).getImage())); //给Frame设置图标 } catch (Exception e) { System.out.println(e); } // 设置外观风格 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // 创建 CardLayout 布局管理器 CardLayout cardLayout = new CardLayout(); jFrame.setLayout(cardLayout); // 创建 tab 面板 tabbedPane0 = new JTabbedPane(); // 创建菜单栏 JMenuBar menuBar = new JMenuBar(); // 在JFrame中添加菜单栏 jFrame.setJMenuBar(menuBar); // 创建"账户设置"菜单项 JMenu settingsMenu = new JMenu("账户设置"); JMenuItem changePasswordMenuItem = new JMenuItem("FOFA API"); settingsMenu.add(changePasswordMenuItem); menuBar.add(settingsMenu); // 创建"搜索设置"菜单项 JMenu configureMenu = new JMenu("查询设置"); JMenuItem configureMenuItem = new JMenuItem("默认查询数量"); JMenuItem configureFullItem = new JMenuItem("默认查询区间"); JCheckBox defaultCheckFullBox = new JCheckBox("是否默认仅查询近一年数据?", false); defaultCheckFullBox.setFocusPainted(false); configureMenu.add(configureMenuItem); configureMenu.add(configureFullItem); menuBar.add(configureMenu); // 创建 “实验功能” 菜单项 JMenu labMenu = new JMenu("实验功能"); JMenuItem openFileMenuItem = new JMenuItem("打开文件"); JMenuItem iconHashLabMenuItem = new JMenuItem("iconHash 计算"); JMenu pluginMenu = new JMenu("插件模式"); JMenu fofaHackMenu = new JMenu("Fofa-Hack"); JMenuItem fofaHackMenuItemRun = new JMenuItem("运行"); JMenuItem fofaHackMenuItemSetting = new JMenuItem("设置"); JMenuItem fofaHackMenuItemAbout = new JMenuItem("关于"); CommonTemplate.addMenuItemsFromFile(pluginMenu, tabbedPane0); JMenu testMenu = new JMenu("测试模式"); JMenuItem focusTestItem = new JMenuItem("焦点测试"); JMenuItem switchToHttpxItem = new JMenuItem("跳转测试"); labMenu.add(openFileMenuItem); labMenu.add(iconHashLabMenuItem); labMenu.add(pluginMenu); // 发布需要注释 pluginMenu.add(fofaHackMenu); fofaHackMenu.add(fofaHackMenuItemRun); fofaHackMenu.add(fofaHackMenuItemSetting); fofaHackMenu.add(fofaHackMenuItemAbout); //labMenu.add(testMenu); // 发布需要注释 testMenu.add(focusTestItem); testMenu.add(switchToHttpxItem); menuBar.add(labMenu); // 创建"关于"菜单项 JMenu aboutMenu = new JMenu("关于"); JMenuItem aboutMenuItem = new JMenuItem("关于项目"); aboutMenu.add(aboutMenuItem); menuBar.add(aboutMenu); // 刷新jf容器及其内部组件的外观 SwingUtilities.updateComponentTreeUI(jFrame); jFrame.setSize(1000, 800); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 确保按下关闭按钮时结束程序 // 创建 fofa 输入框 JTextField textField0 = createTextFieldFofa("fofaEX: FOFA Extension"); // 创建数据表 if (table == null) { table = new JTable(); } // 初始化 table 右键 RightClickFunctions.table = table; RightClickFunctions.initializeTable(); textField0.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { // 当输入框内的文字是提示文字时,先清空输入框再允许输入 if (textField0.getText().equals("fofaEX: FOFA Extension")) { textField0.setText(""); } } }); // 设置背景色为 (4, 12, 31) textField0.setBackground(new Color(48, 49, 52)); // 设置光标 textField0.setCaret(new CustomCaret(Color.WHITE)); // 设置字体 Font font = new Font("Mono", Font.BOLD, 14); textField0.setFont(font); // fofaEX: FOFA Extension 事件 textField0.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { // 当输入框得到焦点时,如果当前是提示文字,则清空输入框并将文字颜色设置为白色 if (textField0.getText().equals("fofaEX: FOFA Extension")) { textField0.setText(""); textField0.setForeground(Color.WHITE); } } @Override public void focusLost(FocusEvent e) { // 当输入框失去焦点时,如果输入框为空,则显示提示文字,并将文字颜色设置为灰色 if (textField0.getText().isEmpty()) { textField0.setText("fofaEX: FOFA Extension"); textField0.setForeground(Color.GRAY); } } }); textField0.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (textField0.getText().equals("fofaEX: FOFA Extension")) { textField0.setText(""); textField0.setForeground(Color.WHITE); } } }); textField0.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { textField0.setForeground(Color.WHITE); } @Override public void removeUpdate(DocumentEvent e) { if (textField0.getText().isEmpty()) { textField0.setForeground(Color.GRAY); } else { textField0.setForeground(Color.WHITE); } } @Override public void changedUpdate(DocumentEvent e) { // 平滑字体,无需处理 } }); // 将光标放在末尾 // textField0.setCaretPosition(textField0.getText().length()); // 编辑撤销 // 创建UndoManager和添加UndoableEditListener。 final UndoManager undoManager = new UndoManager(); Document doc = textField0.getDocument(); doc.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { undoManager.addEdit(e.getEdit()); } }); // 添加KeyListener到textField。 textField0.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if ((e.getKeyCode() == KeyEvent.VK_Z) && ((e.getModifiersEx() & KeyEvent.CTRL_DOWN_MASK) != 0)) { if (undoManager.canUndo()) { undoManager.undo(); } } else { if ((e.getKeyCode() == KeyEvent.VK_Z)) { e.getModifiersEx(); } } } }); // String asciiIcon = // " __ __ _____ __ __\n" + // " / _| ___ / _| __ _ | ____| \\ \\/ /\n" + // " | |_ / _ \\ | |_ / _` | | _| \\ / \n" + // " | _| | (_) | | _| | (_| | | |___ / \\ \n" + // " |_| \\___/ |_| \\__,_| |_____| /_/\\_\\"; // // JLabel labelIcon = new JLabel("<html><pre>" + asciiIcon + "</pre></html>"); JLabel labelIcon = new JLabel(" FOFA EX"); labelIcon.setForeground(new Color(48, 49, 52)); Font iconFont = new Font("Times New Roman", Font.BOLD, 60); labelIcon.setFont(iconFont); // 创建按钮面板,不改变布局(保持BoxLayout) final JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS)); // 创建主面板并使用BoxLayout布局 JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); // 创建一个子面板,用来在搜索框边上新增按钮 JPanel subPanel1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10)); // 创建面板并使用FlowLayout布局 JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 4)); // hgap: 组件间的水平间距 vgap: 件间的垂直间距 JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0)); JPanel panel3 = new JPanel(new GridLayout(0, 10, 0, 0)); JPanel panel4 = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10)); // 创建面板并使用GridLayout布局 JPanel panel5 = new JPanel(new GridLayout(0, 5, 10, 10)); // 0表示行数不限,5表示每行最多5个组件,10, 10是组件之间的间距 JPanel panel6 = new JPanel(new BorderLayout()); panel6.setBorder(BorderFactory.createEmptyBorder(20, 5, 10, 5)); JPanel panel7 = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0)); // panel8 用来放导出表格的按键 JPanel panel8 = new JPanel(); JPanel panel9 = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0)); // 创建"更新规则"按钮 创建"新增"按钮 JButton updateButton = new JButton("➕"); updateButton.setFocusPainted(false); updateButton.setFocusable(false); // 新增一个LinkedHashMap,用于存储按钮的键名和键值 Map<String, JButton> buttonsMap = new LinkedHashMap<>(); BufferedReader rulesReader = null; File accountsFile = null; try { // 创建 rules.txt 文件如果它不存在 File rulesFile = new File(rulesPath); if (!rulesFile.exists()) { rulesFile.createNewFile(); System.out.println("[+] The current path does not contain " + rulesPath + ". Create "+ rulesPath +"."); } rulesReader = new BufferedReader(new FileReader(rulesFile)); // 创建 accounts.txt 文件如果它不存在 accountsFile = new File(accountsPath); if (!accountsFile.exists()) { accountsFile.createNewFile(); System.out.println("[+] The current path does not contain " + accountsPath + ". Create " + accountsPath + "."); } } catch (IOException e) { // IO 异常处理 e.printStackTrace(); } settingInit(rulesReader, accountsFile, panel5, textField0, fofaEmail, fofaKey, buttonsMap); updateButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 创建一个JPanel来包含两个输入框 JPanel inputPanel = new JPanel(new GridLayout(4, 4)); inputPanel.add(new JLabel("键名:")); JTextField nameField = new JTextField(10); inputPanel.add(nameField); inputPanel.add(new JLabel("键值:")); JTextField valueField = new JTextField(10); inputPanel.add(valueField); // 弹出自定义对话框 int result = JOptionPane.showConfirmDialog(null, inputPanel, "新增按键", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); // 当用户点击OK时处理输入 if (result == JOptionPane.OK_OPTION) { String keyName = nameField.getText().trim(); String keyValue = valueField.getText().trim(); // 验证输入是否非空 if (!keyName.isEmpty() && !keyValue.isEmpty()) { // 将键名和键值以"键名":{键值}的形式保存在rule.txt的最后一行 try (BufferedWriter writer = new BufferedWriter(new FileWriter(rulesPath, true))) { System.out.println(keyValue); writer.write("\"" + keyName + "\":{" + keyValue + "},"); writer.newLine(); // Ensure the new entry is on a new line } catch (IOException addError) { addError.printStackTrace(); JOptionPane.showMessageDialog(null, "无法写入文件", "错误", JOptionPane.ERROR_MESSAGE); } // 添加右键菜单功能 try { BufferedReader reader = new BufferedReader(new FileReader(rulesPath)); Map<String, String> newMap = new LinkedHashMap<>(); String line; while ((line = reader.readLine()) != null) { line = line.trim(); // 跳过井号注释 if (line.startsWith("#")) { continue; } if (line.startsWith("\"") && line.contains("{") && line.contains("}")) { String[] parts = line.split(":", 2); String key = parts[0].substring(1, parts[0].length() - 1).trim(); String value = parts[1].substring(1, parts[1].length() - 2).trim(); newMap.put(key, value); } } reader.close(); // 配置文件更新并新增按钮 for (Map.Entry<String, String> entry : newMap.entrySet()) { JButton existingButton = buttonsMap.get(entry.getKey()); if (existingButton == null) { // 新按钮 JButton newButton = new JButton(entry.getKey()); newButton.setActionCommand(entry.getValue()); newButton.setToolTipText(entry.getValue()); // 设置按钮的 ToolTip 为键值,悬浮显示 newButton.setFocusPainted(false); // 添加这一行来取消焦点边框的绘制 newButton.setFocusable(false); // 禁止了按钮获取焦点,因此按钮不会在被点击后显示为"激活"或"选中"的状态 newButton.addActionListener(actionEvent -> { if (newButton.getForeground() != Color.RED) { // 如果文本为提示文字,则清空文本 if (textField0.getText().contains("fofaEX: FOFA Extension")) { textField0.setText(""); } textField0.setText(textField0.getText() + " " + newButton.getActionCommand()); newButton.setForeground(Color.RED); newButton.setFont(newButton.getFont().deriveFont(Font.BOLD)); // 设置字体为粗体 } else { textField0.setText(textField0.getText().replace(" " + newButton.getActionCommand(), "")); newButton.setForeground(null); newButton.setFont(null); // 如果为空则设置 prompt if (textField0.getText().isEmpty()) { textField0.setText("fofaEX: FOFA Extension"); textField0.setForeground(Color.GRAY); // 将光标放在开头 textField0.setCaretPosition(0); } } }); // 添加右键单击事件的处理 newButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { // 在这里处理右键单击事件 JPopupMenu popupMenu = new JPopupMenu(); JMenuItem deleteItem = new JMenuItem("删除"); JMenuItem editItem = new JMenuItem("修改"); deleteItem.addActionListener(actionEvent -> { // 删除:在这里处理删除操作 int dialogResult = JOptionPane.showConfirmDialog(panel5, "是否删除?", "删除确认", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (dialogResult == JOptionPane.YES_OPTION) { // 确认删除操作 panel5.remove(newButton); panel5.revalidate(); panel5.repaint(); // 从文件中删除 removeButtonAndLineFromFile(entry.getKey(), rulesPath); } }); editItem.addActionListener(actionEvent -> { // 获取当前按钮的名称和对应的JButton对象 String oldName = entry.getKey(); JButton buttonToUpdate = newButton; // 确保newButton是当前要修改的按钮的引用 // 创建一个JPanel来包含两个输入框 JPanel panel = new JPanel(new GridLayout(4, 4)); panel.add(new JLabel("键名:")); JTextField nameField = new JTextField(newButton.getText()); panel.add(nameField); panel.add(new JLabel("键值:")); JTextField valueField = new JTextField(buttonToUpdate.getActionCommand()); panel.add(valueField); // 弹出自定义对话框 int result = JOptionPane.showConfirmDialog(panel5, panel, "修改配置", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); // 当用户点击OK时处理输入 if (result == JOptionPane.OK_OPTION) { String newName = nameField.getText().trim(); String newValue = valueField.getText().trim(); // 验证输入是否已变更且非空 if (!newName.isEmpty() && !newValue.isEmpty()) { // 修改按钮名称和键值 updateButtonNameAndValue(oldName, newName, newValue, buttonToUpdate, buttonsMap, rulesPath); // 更新界面 panel5.revalidate(); panel5.repaint(); } } }); popupMenu.add(editItem); popupMenu.add(deleteItem); popupMenu.show(e.getComponent(), e.getX(), e.getY()); popupMenu.add(deleteItem); popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }); panel5.add(newButton); buttonsMap.put(entry.getKey(), newButton); } else { // This is an existing button existingButton.setActionCommand(entry.getValue()); existingButton.setText(entry.getKey()); // Update button text } } panel5.revalidate(); panel5.repaint(); } catch (IOException ioException) { ioException.printStackTrace(); } // 更新界面 panel5.revalidate(); panel5.repaint(); } } // 读取文件内容,并创建新的按钮 } }); // 搜索按钮 // 将textField0添加到新的SubPanel subPanel1.add(textField0); searchButton("搜索", true, subPanel1, textField0, fofaEmail, fofaKey, fofaUrl, panel6, panel8, labelIcon, panel2, panel3, panel7, panel9, "null"); panel1.add(labelIcon); panel2.add(subPanel1); // 搜索框 + 搜索按钮 JLabel jLabel7 = new JLabel("total lines "); panel7.add(jLabel7); searchButton("◁", false, panel7, textField0, fofaEmail, fofaKey, fofaUrl, panel6, panel8, labelIcon, panel2, panel3, panel7, panel9, "left"); searchButton("▷", false, panel7, textField0, fofaEmail, fofaKey, fofaUrl, panel6, panel8, labelIcon, panel2, panel3, panel7, panel9, "right"); // 添加逻辑运算组件 createLogicAddButton("=", "=", panel4, textField0); createLogicAddButton("==", "==", panel4, textField0); createLogicAddButton("&&", "&&", panel4, textField0); createLogicAddButton("||", "||", panel4, textField0); createLogicAddButton("!=", "!=", panel4, textField0); createLogicAddButton("*=", "*=", panel4, textField0); // 新增折叠按钮到panel3 JButton foldButton = new JButton("▼"); foldButton.setFocusPainted(false); //添加这一行来取消焦点边框的绘制 foldButton.setFocusable(false); // 添加点击事件 foldButton.addActionListener(new ActionListener() { boolean isFolded = false; @Override public void actionPerformed(ActionEvent actionEvent) { if (!isFolded) { // 折叠 panel5 panel5.setVisible(false); foldButton.setText("◀"); scrollPaneMark = false; } else { // 展开 panel5 panel5.setVisible(true); foldButton.setText("▼"); scrollPaneMark = true; } isFolded = !isFolded; // 重新验证和重绘包含 panel5 和 panel6 的主面板 mainPanel.revalidate(); mainPanel.repaint(); } }); panel4.add(updateButton); // 更新规则 panel4.add(foldButton); // 创建复选框 addRuleBox(panel3, "host", newValue -> hostMark = newValue, hostMark, true); addRuleBox(panel3, "ip", newValue -> ipMark = newValue, ipMark, true); addRuleBox(panel3, "port", newValue -> portMark = newValue, portMark, true); addRuleBox(panel3, "protocol", newValue -> protocolMark = newValue, protocolMark); addRuleBox(panel3, "title", newValue -> titleMark = newValue, titleMark); addRuleBox(panel3, "domain", newValue -> domainMark = newValue, domainMark); addRuleBox(panel3, "link", newValue -> linkMark = newValue, linkMark); addRuleBox(panel3, "icp", newValue -> icpMark = newValue, icpMark); addRuleBox(panel3, "city", newValue -> cityMark = newValue, cityMark); /* 下面代码未完成 */ addRuleBox(panel3, "country", newValue -> countryMark = newValue, countryMark); /* 测试一下 */ addRuleBox(panel3, "country_name", newValue -> country_nameMark = newValue, country_nameMark); addRuleBox(panel3, "region", newValue -> regionMark = newValue, regionMark); addRuleBox(panel3, "longitude", newValue -> longitudeMark = newValue, longitudeMark); addRuleBox(panel3, "latitude", newValue -> latitudeMark = newValue, latitudeMark); addRuleBox(panel3, "asNumber", newValue -> asNumberMark = newValue, asNumberMark); addRuleBox(panel3, "asOrganization", newValue -> asOrganizationMark = newValue, asOrganizationMark); addRuleBox(panel3, "os", newValue -> osMark = newValue, osMark); addRuleBox(panel3, "server", newValue -> serverMark = newValue, serverMark); addRuleBox(panel3, "jarm", newValue -> jarmMark = newValue, jarmMark); addRuleBox(panel3, "header", newValue -> headerMark = newValue, headerMark); addRuleBox(panel3, "banner", newValue -> bannerMark = newValue, bannerMark); addRuleBox(panel3, "baseProtocol", newValue -> baseProtocolMark = newValue, baseProtocolMark); addRuleBox(panel3, "certsIssuerOrg", newValue -> certsIssuerOrgMark = newValue, certsIssuerOrgMark); addRuleBox(panel3, "certsIssuerCn", newValue -> certsIssuerCnMark = newValue, certsIssuerCnMark); addRuleBox(panel3, "certsSubjectOrg", newValue -> certsSubjectOrgMark = newValue, certsSubjectOrgMark); addRuleBox(panel3, "certsSubjectCn", newValue -> certsSubjectCnMark = newValue, certsSubjectCnMark); addRuleBox(panel3, "tlsJa3s", newValue -> tlsJa3sMark = newValue, tlsJa3sMark); addRuleBox(panel3, "tlsVersion", newValue -> tlsVersionMark = newValue, tlsVersionMark); addRuleBox(panel3, "product", newValue -> productMark = newValue, productMark); addRuleBox(panel3, "productCategory", newValue -> productCategoryMark = newValue, productCategoryMark); addRuleBox(panel3, "version", newValue -> versionMark = newValue, versionMark); addRuleBox(panel3, "lastupdatetime", newValue -> lastupdatetimeMark = newValue, lastupdatetimeMark); addRuleBox(panel3, "cname", newValue -> cnameMark = newValue, cnameMark); addRuleBox(panel3, "iconHash", newValue -> iconHashMark = newValue, iconHashMark); addRuleBox(panel3, "certsValid", newValue -> certsValidMark = newValue, certsValidMark); addRuleBox(panel3, "cnameDomain", newValue -> cnameDomainMark = newValue, cnameDomainMark); addRuleBox(panel3, "body", newValue -> bodyMark = newValue, bodyMark); addRuleBox(panel3, "icon", newValue -> iconMark = newValue, iconMark); addRuleBox(panel3, "fid", newValue -> fidMark = newValue, fidMark); addRuleBox(panel3, "structinfo", newValue -> structinfoMark = newValue, structinfoMark); // 设置全局边框:创建一个带有指定的空白边框的新面板,其中指定了上、左、下、右的边距 mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 添加面板到主面板 mainPanel.add(panel1); mainPanel.add(panel2); mainPanel.add(panel3); mainPanel.add(panel4); mainPanel.add(panel5); mainPanel.add(panel6); mainPanel.add(panel7); mainPanel.add(panel8); mainPanel.add(panel9); tabbedPane0.addTab("FofaEX", mainPanel); tabbedPane0.setTabPlacement(JTabbedPane.BOTTOM); // 将标签放置在底部 // fofa 插件初始化 FofaHack.panel = panel6; FofaHack.table = table; FofaHack.exportPanel = panel8; FofaHack.exportButtonAdded = false; FofaHack.rowCountLabel = jLabel7; // 设置窗口居中并显示 jFrame.setLocationRelativeTo(null); jFrame.add(tabbedPane0); ; jFrame.setVisible(true); // 在程序运行时,使 textField0 获得焦点 SwingUtilities.invokeLater(new Runnable() { public void run() { textField0.requestFocusInWindow(); } }); // 更改"账户设置"菜单项的事件监听 changePasswordMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 创建新的JFrame JFrame settingsFrame = new JFrame("Settings"); // 创建新的面板并添加组件 JPanel settingsPanel = new JPanel(new GridLayout(4, 2, 5, 5)); // 使用4行2列的GridLayout settingsPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 设置边距 JButton checkButton = new JButton("检查账户"); checkButton.setFocusPainted(false); // 添加这一行来取消焦点边框的绘制 checkButton.setFocusable(false); checkButton.addActionListener(e1 -> { // 点击按钮时显示输入的数据 String email = fofaEmail.getText(); String key = fofaKey.getText(); String fofaUrl_str = fofaUrl.getText(); // https://fofa.info/api/v1/info/my?email= String authUrl = fofaUrl_str + "/api/v1/info/my?email=" + email + "&key=" + key; HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(authUrl); try { HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); // 解析JSON数据 JSONObject json = new JSONObject(responseBody); if (!json.getBoolean("error")) { // 账户验证有效 StringBuilder output = new StringBuilder(); output.append("账户验证有效\n"); output.append("邮箱地址: ").append(json.getString("email")).append("\n"); output.append("用户名: ").append(json.getString("username")).append("\n"); if (json.getBoolean("isvip")) { output.append("身份权限:FOFA会员\n"); } else { output.append("身份权限:普通用户\n"); } ; output.append("F点数量: ").append(json.getInt("fofa_point")).append("\n"); output.append("API月度剩余查询次数: ").append(json.getInt("remain_api_query")).append("\n"); output.append("API月度剩余返回数量: ").append(json.getInt("remain_api_data")).append("\n"); JOptionPane.showMessageDialog(null, output.toString()); } else { // 账户验证无效 JOptionPane.showMessageDialog(null, "账户验证无效!", "提示", JOptionPane.WARNING_MESSAGE); } } catch (IOException | JSONException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "发生错误,请重试!", "错误", JOptionPane.ERROR_MESSAGE); } }); // 创建"保存设置"按钮 JButton saveSettingsButton = new JButton("保存设置"); saveSettingsButton.setFocusPainted(false); // 取消焦点边框的绘制 saveSettingsButton.setFocusable(false); saveSettingsButton.addActionListener(SaveError -> { // 准备一个 JsonObject JsonObject jsonObject = new JsonObject(); File jsonFile = new File(accountsPath); // 如果文件存在且其内容不为空,从中读取 JsonObject if (jsonFile.exists() && jsonFile.length() != 0) { try (FileReader reader = new FileReader(jsonFile)) { Gson gson = new Gson(); jsonObject = gson.fromJson(reader, JsonObject.class); } catch (Exception ex) { // parse error handling ex.printStackTrace(); } } // 更新邮件和密钥设置 jsonObject.addProperty("fofaEmail", fofaEmail.getText()); jsonObject.addProperty("fofaKey", fofaKey.getText()); // 将已更新的 jsonObject 写回到 "accounts.json" 文件 try (FileWriter writer = new FileWriter(accountsPath)) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(jsonObject, writer); JOptionPane.showMessageDialog(null, "设置已保存。"); } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "保存设置时发生错误!", "错误", JOptionPane.ERROR_MESSAGE); } }); // 添加组件到设置面板 settingsPanel.add(new JLabel("FOFA URL:")); settingsPanel.add(fofaUrl); settingsPanel.add(new JLabel("Email:")); settingsPanel.add(fofaEmail); settingsPanel.add(new JLabel("API Key:")); settingsPanel.add(fofaKey); settingsPanel.add(checkButton); settingsPanel.add(saveSettingsButton); // 添加设置面板到设置窗口,并显示设置窗口 settingsFrame.add(settingsPanel); settingsFrame.pack(); settingsFrame.setLocationRelativeTo(null); // 使窗口居中显示 settingsFrame.setResizable(false); settingsFrame.setVisible(true); } }); configureMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JTextField inputField = new JTextField(String.valueOf(sizeSetting)); JButton okButton = new JButton("保存"); JButton cancelButton = new JButton("取消"); JOptionPane optionPane = new JOptionPane(inputField, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION); optionPane.setOptions(new Object[] { okButton, cancelButton }); JDialog dialog = optionPane.createDialog("请输入默认查询数量"); okButton.addActionListener(ev -> { try { sizeSetting = Integer.parseInt(inputField.getText()); // 读取JSON文件 JsonObject jsonObject; File jsonFile = new File(accountsPath); if (jsonFile.exists() && jsonFile.length() != 0) { try (FileReader reader = new FileReader(jsonFile)) { Gson gson = new Gson(); jsonObject = gson.fromJson(reader, JsonObject.class); } catch (Exception ex) { ex.printStackTrace(); return; } } else { jsonObject = new JsonObject(); } // 更新queryNumber并重新写入文件 jsonObject.addProperty("queryNumber", sizeSetting); try (FileWriter writer = new FileWriter(accountsPath)) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(jsonObject, writer); } // 显示保存成功提醒 JOptionPane.showMessageDialog(null, "保存成功!"); // 关闭原始对话框 dialog.dispose(); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(null, "请输入一个有效的整数值。"); } catch (IOException ex) { // 处理文件读写异常 JOptionPane.showMessageDialog(null, "发生错误,账户配置文件不存在。"); } }); cancelButton.addActionListener(ev -> dialog.dispose()); dialog.setVisible(true); } }); configureFullItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JsonObject jsonObject; File jsonFile = new File("accounts.json"); // 如果文件存在且其内容不为空,从中读取 JsonObject if (jsonFile.exists() && jsonFile.length() != 0) { try (FileReader reader = new FileReader(jsonFile)) { Gson gson = new Gson(); jsonObject = gson.fromJson(reader, JsonObject.class); } catch (Exception ex) { // 解析错误处理 ex.printStackTrace(); return; } } else { jsonObject = new JsonObject(); } // 读取 queryFull 的值,并设置复选框的选择状态 if (jsonObject.has("queryFull")) { defaultCheckFullBox.setSelected(!jsonObject.get("queryFull").getAsBoolean()); } JButton okButton = new JButton("保存"); JButton cancelButton = new JButton("取消"); JOptionPane optionPane = new JOptionPane(defaultCheckFullBox, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION); optionPane.setOptions(new Object[]{okButton, cancelButton}); JDialog dialog = optionPane.createDialog("是否默认查询区间"); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); okButton.addActionListener(ev -> { // 如果复选框选中,则设置 queryFull 为 false,否则为 true boolean queryFull = !defaultCheckFullBox.isSelected(); jsonObject.addProperty("queryFull", queryFull); // 更新 setFull 的值 setFull = queryFull; // 将 jsonObject 保存到 "accounts.json" 文件中 try (FileWriter writer = new FileWriter(jsonFile)) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(jsonObject, writer); JOptionPane.showMessageDialog(null, "保存成功!"); dialog.dispose(); } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "发生错误,保存设置失败。"); } }); cancelButton.addActionListener(ev -> dialog.dispose()); dialog.setVisible(true); } }); // 图标哈希计算事件 iconHashLabMenuItem.addActionListener((ActionEvent event) -> { EventQueue.invokeLater(() -> { IconHashCalculator calculator = new IconHashCalculator(); calculator.setVisible(true); }); }); fofaHackMenuItemRun.addActionListener((ActionEvent event) -> { EventQueue.invokeLater(() -> { FofaHack.main(); }); }); openFileMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); // 如果存在上次打开的路径,则设置文件选择器的当前目录 if (lastOpenedPath != null) { fileChooser.setCurrentDirectory(lastOpenedPath); } if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); // 更新 lastOpenedPath 为当前选择的文件或文件夹 lastOpenedPath = fileChooser.getCurrentDirectory(); // 调用方法来处理文件 FofaHack.loadFileIntoTable(file); } } }); // 焦点测试 点击事件:显示当前标签 focusTestItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { CommonTemplate.localCurrentTab(tabbedPane0); // CommonTemplate.switchTab(tabbedPane0,tabName); } }); switchToHttpxItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { switchTab(tabbedPane0, "httpx"); } }); // 为"关于项目"菜单项添加动作监听器 aboutMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JEditorPane editorPane = new JEditorPane("text/html", ""); editorPane.setText( "<html><body>" + "<b>fofa EX:</b><br>" + "Project: <a href='https://github.com/10cks/fofaEX'>https://github.com/10cks/fofaEX</a><br>" + "Author: bwner@OverSpace<br>" + "Version: 2.2<br>" + "JDK Version: 11.0.5<br>" + "Update: 2023.12.11<br>" + "</body></html>" ); editorPane.setEditable(false); editorPane.setOpaque(false); editorPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent evt) { if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { try { Desktop.getDesktop().browse(evt.getURL().toURI()); } catch (IOException | URISyntaxException ex) { JOptionPane.showMessageDialog(null, "无法打开链接,错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } } }); // 弹出一个包含JEditorPane的消息对话框 JOptionPane.showMessageDialog(null, new JScrollPane(editorPane), "关于项目", JOptionPane.PLAIN_MESSAGE); } }); // 为 "fofahack 设置" 添加动作监听器 fofaHackMenuItemSetting.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 检查文件是否存在 File fofaHackSettingsFile = new File(".\\plugins\\fofahack\\FofaHackSetting.txt"); if (fofaHackSettingsFile.exists()) { // 如果文件存在,使用系统默认编辑器打开它 try { Desktop.getDesktop().edit(fofaHackSettingsFile); } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "无法打开配置文件!", "错误", JOptionPane.ERROR_MESSAGE); } } else { // 如果文件不存在,显示弹窗 JOptionPane.showMessageDialog(null, "未获取到配置文件!", "错误", JOptionPane.ERROR_MESSAGE); } } }); // 为" fofahack 关于项目"菜单项添加动作监听器 fofaHackMenuItemAbout.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JEditorPane editorPane = new JEditorPane("text/html", ""); editorPane.setText( "<html><body>" + "<b>fofa-hack:</b><br>" + "Project: <a href='https://github.com/Cl0udG0d/Fofa-hack'>https://github.com/Cl0udG0d/Fofa-hack</a><br>" + "Author: Cl0udG0d<br>" + "version: 当前使用为修改版<br>" + "</body></html>" ); editorPane.setEditable(false); editorPane.setOpaque(false); editorPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent evt) { if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { try { Desktop.getDesktop().browse(evt.getURL().toURI()); } catch (IOException | URISyntaxException ex) { JOptionPane.showMessageDialog(null, "无法打开链接,错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } } }); // 弹出一个包含JEditorPane的消息对话框 JOptionPane.showMessageDialog(null, new JScrollPane(editorPane), "关于项目", JOptionPane.PLAIN_MESSAGE); } }); } private static JTextField createTextField(String text) { JTextField textField = new JTextField(text, 20); textField.setPreferredSize(new Dimension(200, 20)); // 创建只有底边的边框 Border blueBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.RED); Border defaultBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY); // 设置默认边框 textField.setBorder(defaultBorder); // 添加鼠标监听器 textField.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { // 鼠标进入时,设置边框颜色为蓝色 textField.setBorder(blueBorder); } @Override public void mouseExited(MouseEvent e) { // 鼠标离开时,将边框颜色设回默认颜色 textField.setBorder(defaultBorder); } }); return textField; } private static JTextField createTextFieldFofa(String text) { RoundJTextField textField = new RoundJTextField(0); textField.setText(text); textField.setPreferredSize(new Dimension(800, 50)); // 设置文本与边框的间距 textField.setMargin(new Insets(0, 10, 0, 5)); // 创建只有底边的边框 Border blueBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.RED); Border defaultBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY); // 设置默认边框 // textField.setBorder(defaultBorder); return textField; } private static void createLogicAddButton(String buttonText, String appendText, JPanel panel, JTextField textField) { // 创建按钮 JButton button = new JButton(buttonText); button.setFocusPainted(false); // 不显示按钮焦点外边框 button.setFocusable(false); // 禁止按钮获取焦点 // 添加点击事件 button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (textField.getText().contains("fofaEX: FOFA Extension")) { textField.setText(""); } // 追加指定文本到文本框中 textField.setText(textField.getText() + " " + appendText); } }); // 将按钮添加到指定面板中 panel.add(button); } private static void searchButton(String buttonText, boolean shouldSetSize, JPanel panel, JTextField textField, JTextField emailField, JTextField keyField, JTextField urlField, JPanel resultPanel, JPanel exportPanel, JLabel changeIcon, JPanel disablePanel2, JPanel disablePanel3, JPanel disablePanel7, JPanel totalPanel8, String pageButton) { JButton button = new JButton(buttonText); button.setFocusPainted(false); button.setFocusable(false); if (shouldSetSize) { button.setPreferredSize(new Dimension(60, 50)); } button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { String domain = urlField.getText().trim(); String email = emailField.getText().trim(); String key = keyField.getText().trim(); String grammar = textField.getText().trim(); String orginIconStr = changeIcon.getText(); // String searchAsciiIcon = " ____ _ _ \n" + // " / ___| ___ __ _ _ __ ___ | |__ (_) _ __ __ _ \n" + // " \\___ \\ / _ \\ / _` | | '__| / __| | '_ \\ | | | '_ \\ / _` | \n" + // " ___) | | __/ | (_| | | | | (__ | | | | | | | | | | | (_| | \n" + // " |____/ \\___| \\__,_| |_| \\___| |_| |_| |_| |_| |_| \\__, | \n" ; // // // changeIcon.setText("<html><pre>" + searchAsciiIcon + "</pre></html>"); changeIcon.setText(" FOFA EX"); changeIcon.setForeground(new Color(89, 154, 248)); // 设置文本颜色为红色 Font font = new Font("Times New Roman", Font.BOLD, 60); changeIcon.setFont(font); setComponentsEnabled(disablePanel2, false); setComponentsEnabled(disablePanel3, false); setComponentsEnabled(disablePanel7, false); // 创建 SwingWorker 来处理搜索任务 SwingWorker<SearchResults, Void> worker = new SwingWorker<SearchResults, Void>() { private void fontSet(JLabel changeIcon, String originIconStr) { changeIcon.setText(originIconStr); changeIcon.setForeground(new Color(48, 49, 52)); } @Override protected SearchResults doInBackground() throws Exception { SearchResults results = new SearchResults(); QueryResponse queryResponse = new QueryResponse(); String errorMessage = null; // 用于存储错误消息 errorMessage = queryResponse.errmsg; // 存储错误消息以便后面使用 String fieldsTotal = ""; long startTime = System.nanoTime(); try { String query = grammar; if (query.equals("fofaEX: FOFA Extension")) { query = ""; // 将字符串设置为空 } if (protocolMark) { fieldsTotal += ",protocol"; } if (titleMark) { fieldsTotal += ",title"; } if (domainMark) { fieldsTotal += ",domain"; } if (linkMark) { fieldsTotal += ",link"; } if (icpMark) { fieldsTotal += ",icp"; } if (cityMark) { fieldsTotal += ",city"; } if (countryMark) { fieldsTotal += ",country"; } if (country_nameMark) { fieldsTotal += ",country_name"; } if (regionMark) { fieldsTotal += ",region"; } if (longitudeMark) { fieldsTotal += ",longitude"; } if (latitudeMark) { fieldsTotal += ",latitude"; } if (asNumberMark) { fieldsTotal += ",as_number"; } if (asOrganizationMark) { fieldsTotal += ",as_organization"; } if (osMark) { fieldsTotal += ",os"; } if (serverMark) { fieldsTotal += ",server"; } if (jarmMark) { fieldsTotal += ",jarm"; } if (headerMark) { fieldsTotal += ",header"; } if (bannerMark) { fieldsTotal += ",banner"; } if (baseProtocolMark) { fieldsTotal += ",base_protocol"; } if (certsIssuerOrgMark) { fieldsTotal += ",certs_issuer_org"; } if (certsIssuerCnMark) { fieldsTotal += ",certs_issuer_cn"; } if (certsSubjectOrgMark) { fieldsTotal += ",certs_subject_org"; } if (certsSubjectCnMark) { fieldsTotal += ",certs_subject_cn"; } if (tlsJa3sMark) { fieldsTotal += ",tls_ja3s"; } if (tlsVersionMark) { fieldsTotal += ",tls_version"; } if (productMark) { fieldsTotal += ",product"; } if (productCategoryMark) { fieldsTotal += ",product_category"; } if (versionMark) { fieldsTotal += ",version"; } if (lastupdatetimeMark) { fieldsTotal += ",lastupdatetime"; } if (cnameMark) { fieldsTotal += ",cname"; } if (iconHashMark) { fieldsTotal += ",icon_hash"; } if (certsValidMark) { fieldsTotal += ",certs_valid"; } if (cnameDomainMark) { fieldsTotal += ",cname_domain"; } if (bodyMark) { fieldsTotal += ",body"; } if (iconMark) { fieldsTotal += ",icon"; } if (fidMark) { fieldsTotal += ",fid"; } if (structinfoMark) { fieldsTotal += ",structinfo"; } // 创建字典 Map<String, Boolean> marks = new LinkedHashMap<>(); marks.put("host", ipMark); marks.put("ip", ipMark); marks.put("port", portMark); marks.put("protocol", protocolMark); marks.put("title", titleMark); marks.put("domain", domainMark); marks.put("link", linkMark); marks.put("icp", icpMark); marks.put("city", cityMark); marks.put("country", countryMark); marks.put("country_name", country_nameMark); marks.put("region", regionMark); marks.put("longitude", longitudeMark); marks.put("latitude", latitudeMark); marks.put("asNumber", asNumberMark); marks.put("asOrganization", asOrganizationMark); marks.put("os", osMark); marks.put("server", serverMark); marks.put("jarm", jarmMark); marks.put("header", headerMark); marks.put("banner", bannerMark); marks.put("baseProtocol", baseProtocolMark); marks.put("certsIssuerOrg", certsIssuerOrgMark); marks.put("certsIssuerCn", certsIssuerCnMark); marks.put("certsSubjectOrg", certsSubjectOrgMark); marks.put("certsSubjectCn", certsSubjectCnMark); marks.put("tlsJa3s", tlsJa3sMark); marks.put("tlsVersion", tlsVersionMark); marks.put("product", productMark); marks.put("productCategory", productCategoryMark); marks.put("version", versionMark); marks.put("lastupdatetime", lastupdatetimeMark); marks.put("cname", cnameMark); marks.put("iconHash", iconHashMark); marks.put("certsValid", certsValidMark); marks.put("cnameDomain", cnameDomainMark); marks.put("body", bodyMark); marks.put("icon", iconMark); marks.put("fid", fidMark); marks.put("structinfo", structinfoMark); // 标记为真的放在一起 List<String> trueMarks = extractTrueMarks(marks); System.out.println(trueMarks); if (pageButton.equals("left")) { if (currentPage != 0) { currentPage = currentPage - 1; } else { } currentPage = 1; } else if (pageButton.equals("right")) { currentPage = currentPage + 1; } // 开始查询 JSONObject jsonResponse = FofaAPI.getAllJsonResult(domain, email, key, query, fieldsTotal, sizeSetting, currentPage, setFull); // 检查错误信息 queryResponse.error = (boolean) FofaAPI.getValueFromJson(jsonResponse, "error"); queryResponse.errmsg = (String) FofaAPI.getValueFromJson(jsonResponse, "errmsg"); // 取出整体 results queryResponse.results = (List<List<String>>) FofaAPI.getValueFromJson(jsonResponse, "results"); if (queryResponse.error) { throw new Exception(queryResponse.errmsg); } List<List<String>> allShow = queryResponse.results; // 需要放在异常后面 // currentPage = (int) FofaAPI.getValueFromJson(jsonResponse, "page"); queryTotalNumber = (int) FofaAPI.getValueFromJson(jsonResponse, "size"); List<String> hostShow = FofaAPI.getColumn(allShow, 0); numberOfItems = hostShow.size(); int i = 0; for (String mark : trueMarks) { switch (mark) { case "host": results.host = FofaAPI.getColumn(allShow, i); break; case "ip": results.ip = FofaAPI.getColumn(allShow, i); break; case "protocol": results.protocol = FofaAPI.getColumn(allShow, i); break; case "port": results.port = FofaAPI.getColumn(allShow, i); break; case "title": results.title = decodeHtmlEntities(FofaAPI.getColumn(allShow, i)); break; case "domain": results.domain = FofaAPI.getColumn(allShow, i); break; case "link": results.link = FofaAPI.getColumn(allShow, i); break; case "icp": results.icp = FofaAPI.getColumn(allShow, i); break; case "city": results.city = FofaAPI.getColumn(allShow, i); break; case "country": results.country = FofaAPI.getColumn(allShow, i); break; case "country_name": results.country_name = FofaAPI.getColumn(allShow, i); break; case "region": results.region = FofaAPI.getColumn(allShow, i); break; case "longitude": results.longitude = FofaAPI.getColumn(allShow, i); break; case "latitude": results.latitude = FofaAPI.getColumn(allShow, i); break; case "asNumber": results.asNumber = FofaAPI.getColumn(allShow, i); break; case "asOrganization": results.asOrganization = FofaAPI.getColumn(allShow, i); break; case "os": results.os = FofaAPI.getColumn(allShow, i); break; case "server": results.server = FofaAPI.getColumn(allShow, i); break; case "jarm": results.jarm = FofaAPI.getColumn(allShow, i); break; case "header": results.header = FofaAPI.getColumn(allShow, i); break; case "banner": results.banner = FofaAPI.getColumn(allShow, i); break; case "baseProtocol": results.baseProtocol = FofaAPI.getColumn(allShow, i); break; case "certsIssuerOrg": results.certsIssuerOrg = FofaAPI.getColumn(allShow, i); break; case "certsIssuerCn": results.certsIssuerCn = FofaAPI.getColumn(allShow, i); break; case "certsSubjectOrg": results.certsSubjectOrg = FofaAPI.getColumn(allShow, i); break; case "certsSubjectCn": results.certsSubjectCn = FofaAPI.getColumn(allShow, i); break; case "tlsJa3s": results.tlsJa3s = FofaAPI.getColumn(allShow, i); break; case "tlsVersion": results.tlsVersion = FofaAPI.getColumn(allShow, i); break; case "product": results.product = FofaAPI.getColumn(allShow, i); break; case "productCategory": results.productCategory = FofaAPI.getColumn(allShow, i); break; case "version": results.version = FofaAPI.getColumn(allShow, i); break; case "lastupdatetime": results.lastupdatetime = FofaAPI.getColumn(allShow, i); break; case "cname": results.cname = FofaAPI.getColumn(allShow, i); break; case "iconHash": results.iconHash = FofaAPI.getColumn(allShow, i); break; case "certsValid": results.certsValid = FofaAPI.getColumn(allShow, i); break; case "cnameDomain": results.cnameDomain = FofaAPI.getColumn(allShow, i); break; case "body": results.body = FofaAPI.getColumn(allShow, i); break; case "icon": results.icon = FofaAPI.getColumn(allShow, i); break; case "fid": results.fid = FofaAPI.getColumn(allShow, i); break; case "structinfo": results.structinfo = FofaAPI.getColumn(allShow, i); break; } i = i + 1; } // 导出表格 JButton exportButton = new JButton("Export to Excel"); exportButton.setFocusPainted(false); // 添加这一行来取消焦点边框的绘制 exportButton.setFocusable(false); // 禁止了按钮获取焦点,因此按钮不会在被点击后显示为"激活"或"选中"的状态 if (!exportButtonAdded) { exportPanel.add(exportButton); exportButtonAdded = true; } exportButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 在这里检查 table 是否被初始化 if (table == null) { JOptionPane.showMessageDialog(null, "表格没有被初始化"); fontSet(changeIcon, orginIconStr); setComponentsEnabled(disablePanel2, true); setComponentsEnabled(disablePanel3, true); setComponentsEnabled(disablePanel7, true); return; } // 检查 table 是否有模型和数据 if (table.getModel() == null || table.getModel().getRowCount() <= 0) { JOptionPane.showMessageDialog(null, "当前无数据"); fontSet(changeIcon, orginIconStr); setComponentsEnabled(disablePanel2, true); setComponentsEnabled(disablePanel3, true); setComponentsEnabled(disablePanel7, true); return; } CommonExecute.exportTableToExcel(table); } }); } catch (JSONException ex) { currentPage = 1; ex.printStackTrace(); JOptionPane.showMessageDialog(null, "发生错误,请重试!", "错误", JOptionPane.ERROR_MESSAGE); fontSet(changeIcon, orginIconStr); setComponentsEnabled(disablePanel2, true); setComponentsEnabled(disablePanel3, true); setComponentsEnabled(disablePanel7, true); } catch (Exception e) { JOptionPane.showMessageDialog(null, errorMessage != null ? errorMessage : e.getMessage(), "执行失败", JOptionPane.ERROR_MESSAGE); currentPage = 1; fontSet(changeIcon, orginIconStr); setComponentsEnabled(disablePanel2, true); setComponentsEnabled(disablePanel3, true); setComponentsEnabled(disablePanel7, true); throw new RuntimeException(e); } finally { long endTime = System.nanoTime(); // Stop the timer long duration = endTime - startTime; double seconds = (double) duration / 1_000_000_000.0; // Convert nanoseconds to seconds SwingUtilities.invokeLater(() -> { String totalLabelShow = "<html>" + "Page: " + currentPage + "<br>" + "Items/Totals: " + numberOfItems * currentPage + "/" + queryTotalNumber + "<br>Time: " + seconds + " seconds</html>"; if (!timeAdded) { // 只有当timeLabel为null时才创建新的实例 if (timeLabel == null) { timeLabel = new JLabel(); } timeLabel.setText(totalLabelShow); totalPanel8.add(timeLabel); timeAdded = true; } else { if (timeLabel != null) { // 确保timeLabel不为null timeLabel.setText(totalLabelShow); } } totalPanel8.revalidate(); totalPanel8.repaint(); }); } fontSet(changeIcon, orginIconStr); setComponentsEnabled(disablePanel2, true); setComponentsEnabled(disablePanel3, true); setComponentsEnabled(disablePanel7, true); return results; } @Override protected void done() { try { SearchResults searchResults = get(); assert searchResults != null; showResultsInTable( searchResults.host, searchResults.ip, searchResults.port, searchResults.protocol, searchResults.title, searchResults.domain, searchResults.link, searchResults.icp, searchResults.city, searchResults.country, searchResults.country_name, searchResults.region, searchResults.longitude, searchResults.latitude, searchResults.asNumber, searchResults.asOrganization, searchResults.os, searchResults.server, searchResults.jarm, searchResults.header, searchResults.banner, searchResults.baseProtocol, searchResults.certsIssuerOrg, searchResults.certsIssuerCn, searchResults.certsSubjectOrg, searchResults.certsSubjectCn, searchResults.tlsJa3s, searchResults.tlsVersion, searchResults.product, searchResults.productCategory, searchResults.version, searchResults.lastupdatetime, searchResults.cname, searchResults.iconHash, searchResults.certsValid, searchResults.cnameDomain, searchResults.body, searchResults.icon, searchResults.fid, searchResults.structinfo, resultPanel ); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } }; // 启动 SwingWorker worker.execute(); } }); panel.add(button); } private static void showResultsInTable(List<String> host, List<String> tableIpShow, List<String> tablePortShow, List<String> protocolShow, List<String> titleShow, List<String> domainShow, List<String> linkShow, List<String> icpShow, List<String> cityShow, List<String> countryShow, List<String> country_nameShow, List<String> regionShow, List<String> longitudeShow, List<String> latitudeShow, List<String> asNumberShow, List<String> asOrganizationShow, List<String> osShow, List<String> serverShow, List<String> jarmShow, List<String> headerShow, List<String> bannerShow, List<String> baseProtocolShow, List<String> certsIssuerOrgShow, List<String> certsIssuerCnShow, List<String> certsSubjectOrgShow, List<String> certsSubjectCnShow, List<String> tlsJa3sShow, List<String> tlsVersionShow, List<String> productShow, List<String> productCategoryShow, List<String> versionShow, List<String> lastupdatetimeShow, List<String> cnameShow, List<String> iconHashShow, List<String> certsValidShow, List<String> cnameDomainShow, List<String> bodyShow, List<String> iconShow, List<String> fidShow, List<String> structinfoShow, JPanel panel) { List<String> columnNamesList = new ArrayList<String>(List.of("host")); if (structinfoMark) { columnNamesList.add(1, "structinfo"); } if (fidMark) { columnNamesList.add(1, "fid"); } if (iconMark) { columnNamesList.add(1, "icon"); } if (bodyMark) { columnNamesList.add(1, "body"); } if (cnameDomainMark) { columnNamesList.add(1, "cnameDomain"); } if (certsValidMark) { columnNamesList.add(1, "certsValid"); } if (iconHashMark) { columnNamesList.add(1, "iconHash"); } if (cnameMark) { columnNamesList.add(1, "cname"); } if (lastupdatetimeMark) { columnNamesList.add(1, "lastupdatetime"); } if (versionMark) { columnNamesList.add(1, "version"); } if (productCategoryMark) { columnNamesList.add(1, "productCategory"); } if (productMark) { columnNamesList.add(1, "product"); } if (tlsVersionMark) { columnNamesList.add(1, "tlsVersion"); } if (tlsJa3sMark) { columnNamesList.add(1, "tlsJa3s"); } if (certsSubjectCnMark) { columnNamesList.add(1, "certsSubjectCn"); } if (certsSubjectOrgMark) { columnNamesList.add(1, "certsSubjectOrg"); } if (certsIssuerCnMark) { columnNamesList.add(1, "certsIssuerCn"); } if (certsIssuerOrgMark) { columnNamesList.add(1, "certsIssuerOrg"); } if (baseProtocolMark) { columnNamesList.add(1, "baseProtocol"); } if (bannerMark) { columnNamesList.add(1, "banner"); } if (headerMark) { columnNamesList.add(1, "header"); } if (jarmMark) { columnNamesList.add(1, "jarm"); } if (serverMark) { columnNamesList.add(1, "server"); } if (osMark) { columnNamesList.add(1, "os"); } if (asOrganizationMark) { columnNamesList.add(1, "asOrganization"); } if (asNumberMark) { columnNamesList.add(1, "asNumber"); } if (latitudeMark) { columnNamesList.add(1, "latitude"); } if (longitudeMark) { columnNamesList.add(1, "longitude"); } if (regionMark) { columnNamesList.add(1, "region"); } if (country_nameMark) { columnNamesList.add(1, "country_name"); } if (countryMark) { columnNamesList.add(1, "country"); } if (cityMark) { columnNamesList.add(1, "city"); } if (icpMark) { columnNamesList.add(1, "icp"); } if (linkMark) { columnNamesList.add(1, "link"); } if (domainMark) { columnNamesList.add(1, "domain"); } if (titleMark) { columnNamesList.add(1, "title"); } if (protocolMark) { columnNamesList.add(1, "protocol"); } if (portMark) { columnNamesList.add(1, "port"); } if (ipMark) { columnNamesList.add(1, "ip"); } String[] columnNames = columnNamesList.toArray(new String[0]); Object[][] data = new Object[host.size()][columnNames.length]; for (int i = 0; i < host.size(); i++) { data[i][0] = host.get(i); int columnIndex = 1; if (ipMark && tableIpShow.size() > i) { data[i][columnIndex++] = tableIpShow.get(i); } if (portMark && tablePortShow.size() > i) { data[i][columnIndex++] = tablePortShow.get(i); } if (protocolMark && protocolShow.size() > i) { data[i][columnIndex++] = protocolShow.get(i); } if (titleMark && titleShow.size() > i) { data[i][columnIndex++] = titleShow.get(i); } if (domainMark && domainShow.size() > i) { data[i][columnIndex++] = domainShow.get(i); } if (linkMark && linkShow.size() > i) { data[i][columnIndex++] = linkShow.get(i); } if (icpMark && icpShow.size() > i) { data[i][columnIndex++] = icpShow.get(i); } if (cityMark && cityShow.size() > i) { data[i][columnIndex++] = cityShow.get(i); } if (countryMark && countryShow.size() > i) { data[i][columnIndex++] = countryShow.get(i); } if (country_nameMark && country_nameShow.size() > i) { data[i][columnIndex++] = country_nameShow.get(i); } if (regionMark && regionShow.size() > i) { data[i][columnIndex++] = regionShow.get(i); } if (longitudeMark && longitudeShow.size() > i) { data[i][columnIndex++] = longitudeShow.get(i); } if (latitudeMark && latitudeShow.size() > i) { data[i][columnIndex++] = latitudeShow.get(i); } if (asNumberMark && asNumberShow.size() > i) { data[i][columnIndex++] = asNumberShow.get(i); } if (asOrganizationMark && asOrganizationShow.size() > i) { data[i][columnIndex++] = asOrganizationShow.get(i); } if (osMark && osShow.size() > i) { data[i][columnIndex++] = osShow.get(i); } if (serverMark && serverShow.size() > i) { data[i][columnIndex++] = serverShow.get(i); } if (jarmMark && jarmShow.size() > i) { data[i][columnIndex++] = jarmShow.get(i); } if (headerMark && headerShow.size() > i) { data[i][columnIndex++] = headerShow.get(i); } if (bannerMark && bannerShow.size() > i) { data[i][columnIndex++] = bannerShow.get(i); } if (baseProtocolMark && baseProtocolShow.size() > i) { data[i][columnIndex++] = baseProtocolShow.get(i); } if (certsIssuerOrgMark && certsIssuerOrgShow.size() > i) { data[i][columnIndex++] = certsIssuerOrgShow.get(i); } if (certsIssuerCnMark && certsIssuerCnShow.size() > i) { data[i][columnIndex++] = certsIssuerCnShow.get(i); } if (certsSubjectOrgMark && certsSubjectOrgShow.size() > i) { data[i][columnIndex++] = certsSubjectOrgShow.get(i); } if (certsSubjectCnMark && certsSubjectCnShow.size() > i) { data[i][columnIndex++] = certsSubjectCnShow.get(i); } if (tlsJa3sMark && tlsJa3sShow.size() > i) { data[i][columnIndex++] = tlsJa3sShow.get(i); } if (tlsVersionMark && tlsVersionShow.size() > i) { data[i][columnIndex++] = tlsVersionShow.get(i); } if (productMark && productShow.size() > i) { data[i][columnIndex++] = productShow.get(i); } if (productCategoryMark && productCategoryShow.size() > i) { data[i][columnIndex++] = productCategoryShow.get(i); } if (versionMark && versionShow.size() > i) { data[i][columnIndex++] = versionShow.get(i); } if (lastupdatetimeMark && lastupdatetimeShow.size() > i) { data[i][columnIndex++] = lastupdatetimeShow.get(i); } if (cnameMark && cnameShow.size() > i) { data[i][columnIndex++] = cnameShow.get(i); } if (iconHashMark && iconHashShow.size() > i) { data[i][columnIndex++] = iconHashShow.get(i); } if (certsValidMark && certsValidShow.size() > i) { data[i][columnIndex++] = certsValidShow.get(i); } if (cnameDomainMark && cnameDomainShow.size() > i) { data[i][columnIndex++] = cnameDomainShow.get(i); } if (bodyMark && bodyShow.size() > i) { data[i][columnIndex++] = bodyShow.get(i); } if (iconMark && iconShow.size() > i) { data[i][columnIndex++] = iconShow.get(i); } if (fidMark && fidShow.size() > i) { data[i][columnIndex++] = fidShow.get(i); } if (structinfoMark && structinfoShow.size() > i) { data[i][columnIndex++] = structinfoShow.get(i); } } DefaultTableModel model = new DefaultTableModel(data, columnNames); table.setModel(model); // 重新设置表格头,以便新的渲染器生效 JTableHeader header = getjTableHeader(table); table.setTableHeader(header);
public class Main { // 创建输入框 private static JTextField fofaUrl = createTextField("https://fofa.info"); private static JTextField fofaEmail = createTextField("当前版本不需要输入邮箱"); private static JTextField fofaKey = createTextField("请输入API key"); private static String rulesPath = "rules.txt"; private static String accountsPath = "accounts.json"; // 设置 field 规则 private static boolean hostMark = true; private static boolean ipMark = true; private static boolean portMark = true; private static boolean protocolMark = true; private static boolean titleMark = true; private static boolean domainMark = true; private static boolean linkMark = true; private static boolean icpMark = false; private static boolean cityMark = false; private static boolean countryMark = false; /* 下面未完成 */ private static boolean country_nameMark = false; private static boolean regionMark = false; private static boolean longitudeMark = false; private static boolean latitudeMark = false; private static boolean asNumberMark = false; private static boolean asOrganizationMark = false; private static boolean osMark = false; private static boolean serverMark = false; private static boolean jarmMark = false; private static boolean headerMark = false; private static boolean bannerMark = false; private static boolean baseProtocolMark = false; private static boolean certsIssuerOrgMark = false; private static boolean certsIssuerCnMark = false; private static boolean certsSubjectOrgMark = false; private static boolean certsSubjectCnMark = false; private static boolean tlsJa3sMark = false; private static boolean tlsVersionMark = false; private static boolean productMark = false; private static boolean productCategoryMark = false; private static boolean versionMark = false; private static boolean lastupdatetimeMark = false; private static boolean cnameMark = false; private static boolean iconHashMark = false; private static boolean certsValidMark = false; private static boolean cnameDomainMark = false; private static boolean bodyMark = false; private static boolean iconMark = false; private static boolean fidMark = false; private static boolean structinfoMark = false; private static boolean scrollPaneMark = true; // 标记 private static boolean exportButtonAdded = false; private static boolean timeAdded = false; private static JLabel timeLabel; private static int queryTotalNumber; private static int numberOfItems; private static int currentPage = 1; private static boolean setFull = true; private static int sizeSetting = 10000; private static boolean openFileMark = false; // 创建全局数据表 private static JTable table; // 在类的成员变量中创建弹出菜单 private static JPopupMenu popupMenu = new JPopupMenu(); private static JMenuItem itemSelectColumn = new JMenuItem("选择当前整列"); private static JMenuItem itemDeselectColumn = new JMenuItem("取消选择整列"); private static JMenuItem itemOpenLink = new JMenuItem("打开链接"); static JMenuItem itemCopy = new JMenuItem("复制"); private static JMenuItem itemSearch = new JMenuItem("表格搜索"); private static File lastOpenedPath; // 添加一个成员变量来保存上次打开的文件路径 static TableCellRenderer highlightRenderer = new HighlightRenderer(); private static TableCellRenderer defaultRenderer; private static JTabbedPane tabbedPane0; public static void main(String[] args) throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException, FileNotFoundException { JFrame jFrame = new JFrame("fofaEX"); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); try { URL resource = Main.class.getResource("icon.png"); jFrame.setIconImage((new ImageIcon(resource).getImage())); //给Frame设置图标 } catch (Exception e) { System.out.println(e); } // 设置外观风格 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // 创建 CardLayout 布局管理器 CardLayout cardLayout = new CardLayout(); jFrame.setLayout(cardLayout); // 创建 tab 面板 tabbedPane0 = new JTabbedPane(); // 创建菜单栏 JMenuBar menuBar = new JMenuBar(); // 在JFrame中添加菜单栏 jFrame.setJMenuBar(menuBar); // 创建"账户设置"菜单项 JMenu settingsMenu = new JMenu("账户设置"); JMenuItem changePasswordMenuItem = new JMenuItem("FOFA API"); settingsMenu.add(changePasswordMenuItem); menuBar.add(settingsMenu); // 创建"搜索设置"菜单项 JMenu configureMenu = new JMenu("查询设置"); JMenuItem configureMenuItem = new JMenuItem("默认查询数量"); JMenuItem configureFullItem = new JMenuItem("默认查询区间"); JCheckBox defaultCheckFullBox = new JCheckBox("是否默认仅查询近一年数据?", false); defaultCheckFullBox.setFocusPainted(false); configureMenu.add(configureMenuItem); configureMenu.add(configureFullItem); menuBar.add(configureMenu); // 创建 “实验功能” 菜单项 JMenu labMenu = new JMenu("实验功能"); JMenuItem openFileMenuItem = new JMenuItem("打开文件"); JMenuItem iconHashLabMenuItem = new JMenuItem("iconHash 计算"); JMenu pluginMenu = new JMenu("插件模式"); JMenu fofaHackMenu = new JMenu("Fofa-Hack"); JMenuItem fofaHackMenuItemRun = new JMenuItem("运行"); JMenuItem fofaHackMenuItemSetting = new JMenuItem("设置"); JMenuItem fofaHackMenuItemAbout = new JMenuItem("关于"); CommonTemplate.addMenuItemsFromFile(pluginMenu, tabbedPane0); JMenu testMenu = new JMenu("测试模式"); JMenuItem focusTestItem = new JMenuItem("焦点测试"); JMenuItem switchToHttpxItem = new JMenuItem("跳转测试"); labMenu.add(openFileMenuItem); labMenu.add(iconHashLabMenuItem); labMenu.add(pluginMenu); // 发布需要注释 pluginMenu.add(fofaHackMenu); fofaHackMenu.add(fofaHackMenuItemRun); fofaHackMenu.add(fofaHackMenuItemSetting); fofaHackMenu.add(fofaHackMenuItemAbout); //labMenu.add(testMenu); // 发布需要注释 testMenu.add(focusTestItem); testMenu.add(switchToHttpxItem); menuBar.add(labMenu); // 创建"关于"菜单项 JMenu aboutMenu = new JMenu("关于"); JMenuItem aboutMenuItem = new JMenuItem("关于项目"); aboutMenu.add(aboutMenuItem); menuBar.add(aboutMenu); // 刷新jf容器及其内部组件的外观 SwingUtilities.updateComponentTreeUI(jFrame); jFrame.setSize(1000, 800); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 确保按下关闭按钮时结束程序 // 创建 fofa 输入框 JTextField textField0 = createTextFieldFofa("fofaEX: FOFA Extension"); // 创建数据表 if (table == null) { table = new JTable(); } // 初始化 table 右键 RightClickFunctions.table = table; RightClickFunctions.initializeTable(); textField0.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { // 当输入框内的文字是提示文字时,先清空输入框再允许输入 if (textField0.getText().equals("fofaEX: FOFA Extension")) { textField0.setText(""); } } }); // 设置背景色为 (4, 12, 31) textField0.setBackground(new Color(48, 49, 52)); // 设置光标 textField0.setCaret(new CustomCaret(Color.WHITE)); // 设置字体 Font font = new Font("Mono", Font.BOLD, 14); textField0.setFont(font); // fofaEX: FOFA Extension 事件 textField0.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { // 当输入框得到焦点时,如果当前是提示文字,则清空输入框并将文字颜色设置为白色 if (textField0.getText().equals("fofaEX: FOFA Extension")) { textField0.setText(""); textField0.setForeground(Color.WHITE); } } @Override public void focusLost(FocusEvent e) { // 当输入框失去焦点时,如果输入框为空,则显示提示文字,并将文字颜色设置为灰色 if (textField0.getText().isEmpty()) { textField0.setText("fofaEX: FOFA Extension"); textField0.setForeground(Color.GRAY); } } }); textField0.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (textField0.getText().equals("fofaEX: FOFA Extension")) { textField0.setText(""); textField0.setForeground(Color.WHITE); } } }); textField0.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { textField0.setForeground(Color.WHITE); } @Override public void removeUpdate(DocumentEvent e) { if (textField0.getText().isEmpty()) { textField0.setForeground(Color.GRAY); } else { textField0.setForeground(Color.WHITE); } } @Override public void changedUpdate(DocumentEvent e) { // 平滑字体,无需处理 } }); // 将光标放在末尾 // textField0.setCaretPosition(textField0.getText().length()); // 编辑撤销 // 创建UndoManager和添加UndoableEditListener。 final UndoManager undoManager = new UndoManager(); Document doc = textField0.getDocument(); doc.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { undoManager.addEdit(e.getEdit()); } }); // 添加KeyListener到textField。 textField0.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if ((e.getKeyCode() == KeyEvent.VK_Z) && ((e.getModifiersEx() & KeyEvent.CTRL_DOWN_MASK) != 0)) { if (undoManager.canUndo()) { undoManager.undo(); } } else { if ((e.getKeyCode() == KeyEvent.VK_Z)) { e.getModifiersEx(); } } } }); // String asciiIcon = // " __ __ _____ __ __\n" + // " / _| ___ / _| __ _ | ____| \\ \\/ /\n" + // " | |_ / _ \\ | |_ / _` | | _| \\ / \n" + // " | _| | (_) | | _| | (_| | | |___ / \\ \n" + // " |_| \\___/ |_| \\__,_| |_____| /_/\\_\\"; // // JLabel labelIcon = new JLabel("<html><pre>" + asciiIcon + "</pre></html>"); JLabel labelIcon = new JLabel(" FOFA EX"); labelIcon.setForeground(new Color(48, 49, 52)); Font iconFont = new Font("Times New Roman", Font.BOLD, 60); labelIcon.setFont(iconFont); // 创建按钮面板,不改变布局(保持BoxLayout) final JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS)); // 创建主面板并使用BoxLayout布局 JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); // 创建一个子面板,用来在搜索框边上新增按钮 JPanel subPanel1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10)); // 创建面板并使用FlowLayout布局 JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 4)); // hgap: 组件间的水平间距 vgap: 件间的垂直间距 JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0)); JPanel panel3 = new JPanel(new GridLayout(0, 10, 0, 0)); JPanel panel4 = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10)); // 创建面板并使用GridLayout布局 JPanel panel5 = new JPanel(new GridLayout(0, 5, 10, 10)); // 0表示行数不限,5表示每行最多5个组件,10, 10是组件之间的间距 JPanel panel6 = new JPanel(new BorderLayout()); panel6.setBorder(BorderFactory.createEmptyBorder(20, 5, 10, 5)); JPanel panel7 = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0)); // panel8 用来放导出表格的按键 JPanel panel8 = new JPanel(); JPanel panel9 = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0)); // 创建"更新规则"按钮 创建"新增"按钮 JButton updateButton = new JButton("➕"); updateButton.setFocusPainted(false); updateButton.setFocusable(false); // 新增一个LinkedHashMap,用于存储按钮的键名和键值 Map<String, JButton> buttonsMap = new LinkedHashMap<>(); BufferedReader rulesReader = null; File accountsFile = null; try { // 创建 rules.txt 文件如果它不存在 File rulesFile = new File(rulesPath); if (!rulesFile.exists()) { rulesFile.createNewFile(); System.out.println("[+] The current path does not contain " + rulesPath + ". Create "+ rulesPath +"."); } rulesReader = new BufferedReader(new FileReader(rulesFile)); // 创建 accounts.txt 文件如果它不存在 accountsFile = new File(accountsPath); if (!accountsFile.exists()) { accountsFile.createNewFile(); System.out.println("[+] The current path does not contain " + accountsPath + ". Create " + accountsPath + "."); } } catch (IOException e) { // IO 异常处理 e.printStackTrace(); } settingInit(rulesReader, accountsFile, panel5, textField0, fofaEmail, fofaKey, buttonsMap); updateButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 创建一个JPanel来包含两个输入框 JPanel inputPanel = new JPanel(new GridLayout(4, 4)); inputPanel.add(new JLabel("键名:")); JTextField nameField = new JTextField(10); inputPanel.add(nameField); inputPanel.add(new JLabel("键值:")); JTextField valueField = new JTextField(10); inputPanel.add(valueField); // 弹出自定义对话框 int result = JOptionPane.showConfirmDialog(null, inputPanel, "新增按键", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); // 当用户点击OK时处理输入 if (result == JOptionPane.OK_OPTION) { String keyName = nameField.getText().trim(); String keyValue = valueField.getText().trim(); // 验证输入是否非空 if (!keyName.isEmpty() && !keyValue.isEmpty()) { // 将键名和键值以"键名":{键值}的形式保存在rule.txt的最后一行 try (BufferedWriter writer = new BufferedWriter(new FileWriter(rulesPath, true))) { System.out.println(keyValue); writer.write("\"" + keyName + "\":{" + keyValue + "},"); writer.newLine(); // Ensure the new entry is on a new line } catch (IOException addError) { addError.printStackTrace(); JOptionPane.showMessageDialog(null, "无法写入文件", "错误", JOptionPane.ERROR_MESSAGE); } // 添加右键菜单功能 try { BufferedReader reader = new BufferedReader(new FileReader(rulesPath)); Map<String, String> newMap = new LinkedHashMap<>(); String line; while ((line = reader.readLine()) != null) { line = line.trim(); // 跳过井号注释 if (line.startsWith("#")) { continue; } if (line.startsWith("\"") && line.contains("{") && line.contains("}")) { String[] parts = line.split(":", 2); String key = parts[0].substring(1, parts[0].length() - 1).trim(); String value = parts[1].substring(1, parts[1].length() - 2).trim(); newMap.put(key, value); } } reader.close(); // 配置文件更新并新增按钮 for (Map.Entry<String, String> entry : newMap.entrySet()) { JButton existingButton = buttonsMap.get(entry.getKey()); if (existingButton == null) { // 新按钮 JButton newButton = new JButton(entry.getKey()); newButton.setActionCommand(entry.getValue()); newButton.setToolTipText(entry.getValue()); // 设置按钮的 ToolTip 为键值,悬浮显示 newButton.setFocusPainted(false); // 添加这一行来取消焦点边框的绘制 newButton.setFocusable(false); // 禁止了按钮获取焦点,因此按钮不会在被点击后显示为"激活"或"选中"的状态 newButton.addActionListener(actionEvent -> { if (newButton.getForeground() != Color.RED) { // 如果文本为提示文字,则清空文本 if (textField0.getText().contains("fofaEX: FOFA Extension")) { textField0.setText(""); } textField0.setText(textField0.getText() + " " + newButton.getActionCommand()); newButton.setForeground(Color.RED); newButton.setFont(newButton.getFont().deriveFont(Font.BOLD)); // 设置字体为粗体 } else { textField0.setText(textField0.getText().replace(" " + newButton.getActionCommand(), "")); newButton.setForeground(null); newButton.setFont(null); // 如果为空则设置 prompt if (textField0.getText().isEmpty()) { textField0.setText("fofaEX: FOFA Extension"); textField0.setForeground(Color.GRAY); // 将光标放在开头 textField0.setCaretPosition(0); } } }); // 添加右键单击事件的处理 newButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { // 在这里处理右键单击事件 JPopupMenu popupMenu = new JPopupMenu(); JMenuItem deleteItem = new JMenuItem("删除"); JMenuItem editItem = new JMenuItem("修改"); deleteItem.addActionListener(actionEvent -> { // 删除:在这里处理删除操作 int dialogResult = JOptionPane.showConfirmDialog(panel5, "是否删除?", "删除确认", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (dialogResult == JOptionPane.YES_OPTION) { // 确认删除操作 panel5.remove(newButton); panel5.revalidate(); panel5.repaint(); // 从文件中删除 removeButtonAndLineFromFile(entry.getKey(), rulesPath); } }); editItem.addActionListener(actionEvent -> { // 获取当前按钮的名称和对应的JButton对象 String oldName = entry.getKey(); JButton buttonToUpdate = newButton; // 确保newButton是当前要修改的按钮的引用 // 创建一个JPanel来包含两个输入框 JPanel panel = new JPanel(new GridLayout(4, 4)); panel.add(new JLabel("键名:")); JTextField nameField = new JTextField(newButton.getText()); panel.add(nameField); panel.add(new JLabel("键值:")); JTextField valueField = new JTextField(buttonToUpdate.getActionCommand()); panel.add(valueField); // 弹出自定义对话框 int result = JOptionPane.showConfirmDialog(panel5, panel, "修改配置", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); // 当用户点击OK时处理输入 if (result == JOptionPane.OK_OPTION) { String newName = nameField.getText().trim(); String newValue = valueField.getText().trim(); // 验证输入是否已变更且非空 if (!newName.isEmpty() && !newValue.isEmpty()) { // 修改按钮名称和键值 updateButtonNameAndValue(oldName, newName, newValue, buttonToUpdate, buttonsMap, rulesPath); // 更新界面 panel5.revalidate(); panel5.repaint(); } } }); popupMenu.add(editItem); popupMenu.add(deleteItem); popupMenu.show(e.getComponent(), e.getX(), e.getY()); popupMenu.add(deleteItem); popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }); panel5.add(newButton); buttonsMap.put(entry.getKey(), newButton); } else { // This is an existing button existingButton.setActionCommand(entry.getValue()); existingButton.setText(entry.getKey()); // Update button text } } panel5.revalidate(); panel5.repaint(); } catch (IOException ioException) { ioException.printStackTrace(); } // 更新界面 panel5.revalidate(); panel5.repaint(); } } // 读取文件内容,并创建新的按钮 } }); // 搜索按钮 // 将textField0添加到新的SubPanel subPanel1.add(textField0); searchButton("搜索", true, subPanel1, textField0, fofaEmail, fofaKey, fofaUrl, panel6, panel8, labelIcon, panel2, panel3, panel7, panel9, "null"); panel1.add(labelIcon); panel2.add(subPanel1); // 搜索框 + 搜索按钮 JLabel jLabel7 = new JLabel("total lines "); panel7.add(jLabel7); searchButton("◁", false, panel7, textField0, fofaEmail, fofaKey, fofaUrl, panel6, panel8, labelIcon, panel2, panel3, panel7, panel9, "left"); searchButton("▷", false, panel7, textField0, fofaEmail, fofaKey, fofaUrl, panel6, panel8, labelIcon, panel2, panel3, panel7, panel9, "right"); // 添加逻辑运算组件 createLogicAddButton("=", "=", panel4, textField0); createLogicAddButton("==", "==", panel4, textField0); createLogicAddButton("&&", "&&", panel4, textField0); createLogicAddButton("||", "||", panel4, textField0); createLogicAddButton("!=", "!=", panel4, textField0); createLogicAddButton("*=", "*=", panel4, textField0); // 新增折叠按钮到panel3 JButton foldButton = new JButton("▼"); foldButton.setFocusPainted(false); //添加这一行来取消焦点边框的绘制 foldButton.setFocusable(false); // 添加点击事件 foldButton.addActionListener(new ActionListener() { boolean isFolded = false; @Override public void actionPerformed(ActionEvent actionEvent) { if (!isFolded) { // 折叠 panel5 panel5.setVisible(false); foldButton.setText("◀"); scrollPaneMark = false; } else { // 展开 panel5 panel5.setVisible(true); foldButton.setText("▼"); scrollPaneMark = true; } isFolded = !isFolded; // 重新验证和重绘包含 panel5 和 panel6 的主面板 mainPanel.revalidate(); mainPanel.repaint(); } }); panel4.add(updateButton); // 更新规则 panel4.add(foldButton); // 创建复选框 addRuleBox(panel3, "host", newValue -> hostMark = newValue, hostMark, true); addRuleBox(panel3, "ip", newValue -> ipMark = newValue, ipMark, true); addRuleBox(panel3, "port", newValue -> portMark = newValue, portMark, true); addRuleBox(panel3, "protocol", newValue -> protocolMark = newValue, protocolMark); addRuleBox(panel3, "title", newValue -> titleMark = newValue, titleMark); addRuleBox(panel3, "domain", newValue -> domainMark = newValue, domainMark); addRuleBox(panel3, "link", newValue -> linkMark = newValue, linkMark); addRuleBox(panel3, "icp", newValue -> icpMark = newValue, icpMark); addRuleBox(panel3, "city", newValue -> cityMark = newValue, cityMark); /* 下面代码未完成 */ addRuleBox(panel3, "country", newValue -> countryMark = newValue, countryMark); /* 测试一下 */ addRuleBox(panel3, "country_name", newValue -> country_nameMark = newValue, country_nameMark); addRuleBox(panel3, "region", newValue -> regionMark = newValue, regionMark); addRuleBox(panel3, "longitude", newValue -> longitudeMark = newValue, longitudeMark); addRuleBox(panel3, "latitude", newValue -> latitudeMark = newValue, latitudeMark); addRuleBox(panel3, "asNumber", newValue -> asNumberMark = newValue, asNumberMark); addRuleBox(panel3, "asOrganization", newValue -> asOrganizationMark = newValue, asOrganizationMark); addRuleBox(panel3, "os", newValue -> osMark = newValue, osMark); addRuleBox(panel3, "server", newValue -> serverMark = newValue, serverMark); addRuleBox(panel3, "jarm", newValue -> jarmMark = newValue, jarmMark); addRuleBox(panel3, "header", newValue -> headerMark = newValue, headerMark); addRuleBox(panel3, "banner", newValue -> bannerMark = newValue, bannerMark); addRuleBox(panel3, "baseProtocol", newValue -> baseProtocolMark = newValue, baseProtocolMark); addRuleBox(panel3, "certsIssuerOrg", newValue -> certsIssuerOrgMark = newValue, certsIssuerOrgMark); addRuleBox(panel3, "certsIssuerCn", newValue -> certsIssuerCnMark = newValue, certsIssuerCnMark); addRuleBox(panel3, "certsSubjectOrg", newValue -> certsSubjectOrgMark = newValue, certsSubjectOrgMark); addRuleBox(panel3, "certsSubjectCn", newValue -> certsSubjectCnMark = newValue, certsSubjectCnMark); addRuleBox(panel3, "tlsJa3s", newValue -> tlsJa3sMark = newValue, tlsJa3sMark); addRuleBox(panel3, "tlsVersion", newValue -> tlsVersionMark = newValue, tlsVersionMark); addRuleBox(panel3, "product", newValue -> productMark = newValue, productMark); addRuleBox(panel3, "productCategory", newValue -> productCategoryMark = newValue, productCategoryMark); addRuleBox(panel3, "version", newValue -> versionMark = newValue, versionMark); addRuleBox(panel3, "lastupdatetime", newValue -> lastupdatetimeMark = newValue, lastupdatetimeMark); addRuleBox(panel3, "cname", newValue -> cnameMark = newValue, cnameMark); addRuleBox(panel3, "iconHash", newValue -> iconHashMark = newValue, iconHashMark); addRuleBox(panel3, "certsValid", newValue -> certsValidMark = newValue, certsValidMark); addRuleBox(panel3, "cnameDomain", newValue -> cnameDomainMark = newValue, cnameDomainMark); addRuleBox(panel3, "body", newValue -> bodyMark = newValue, bodyMark); addRuleBox(panel3, "icon", newValue -> iconMark = newValue, iconMark); addRuleBox(panel3, "fid", newValue -> fidMark = newValue, fidMark); addRuleBox(panel3, "structinfo", newValue -> structinfoMark = newValue, structinfoMark); // 设置全局边框:创建一个带有指定的空白边框的新面板,其中指定了上、左、下、右的边距 mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 添加面板到主面板 mainPanel.add(panel1); mainPanel.add(panel2); mainPanel.add(panel3); mainPanel.add(panel4); mainPanel.add(panel5); mainPanel.add(panel6); mainPanel.add(panel7); mainPanel.add(panel8); mainPanel.add(panel9); tabbedPane0.addTab("FofaEX", mainPanel); tabbedPane0.setTabPlacement(JTabbedPane.BOTTOM); // 将标签放置在底部 // fofa 插件初始化 FofaHack.panel = panel6; FofaHack.table = table; FofaHack.exportPanel = panel8; FofaHack.exportButtonAdded = false; FofaHack.rowCountLabel = jLabel7; // 设置窗口居中并显示 jFrame.setLocationRelativeTo(null); jFrame.add(tabbedPane0); ; jFrame.setVisible(true); // 在程序运行时,使 textField0 获得焦点 SwingUtilities.invokeLater(new Runnable() { public void run() { textField0.requestFocusInWindow(); } }); // 更改"账户设置"菜单项的事件监听 changePasswordMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 创建新的JFrame JFrame settingsFrame = new JFrame("Settings"); // 创建新的面板并添加组件 JPanel settingsPanel = new JPanel(new GridLayout(4, 2, 5, 5)); // 使用4行2列的GridLayout settingsPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 设置边距 JButton checkButton = new JButton("检查账户"); checkButton.setFocusPainted(false); // 添加这一行来取消焦点边框的绘制 checkButton.setFocusable(false); checkButton.addActionListener(e1 -> { // 点击按钮时显示输入的数据 String email = fofaEmail.getText(); String key = fofaKey.getText(); String fofaUrl_str = fofaUrl.getText(); // https://fofa.info/api/v1/info/my?email= String authUrl = fofaUrl_str + "/api/v1/info/my?email=" + email + "&key=" + key; HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(authUrl); try { HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); // 解析JSON数据 JSONObject json = new JSONObject(responseBody); if (!json.getBoolean("error")) { // 账户验证有效 StringBuilder output = new StringBuilder(); output.append("账户验证有效\n"); output.append("邮箱地址: ").append(json.getString("email")).append("\n"); output.append("用户名: ").append(json.getString("username")).append("\n"); if (json.getBoolean("isvip")) { output.append("身份权限:FOFA会员\n"); } else { output.append("身份权限:普通用户\n"); } ; output.append("F点数量: ").append(json.getInt("fofa_point")).append("\n"); output.append("API月度剩余查询次数: ").append(json.getInt("remain_api_query")).append("\n"); output.append("API月度剩余返回数量: ").append(json.getInt("remain_api_data")).append("\n"); JOptionPane.showMessageDialog(null, output.toString()); } else { // 账户验证无效 JOptionPane.showMessageDialog(null, "账户验证无效!", "提示", JOptionPane.WARNING_MESSAGE); } } catch (IOException | JSONException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "发生错误,请重试!", "错误", JOptionPane.ERROR_MESSAGE); } }); // 创建"保存设置"按钮 JButton saveSettingsButton = new JButton("保存设置"); saveSettingsButton.setFocusPainted(false); // 取消焦点边框的绘制 saveSettingsButton.setFocusable(false); saveSettingsButton.addActionListener(SaveError -> { // 准备一个 JsonObject JsonObject jsonObject = new JsonObject(); File jsonFile = new File(accountsPath); // 如果文件存在且其内容不为空,从中读取 JsonObject if (jsonFile.exists() && jsonFile.length() != 0) { try (FileReader reader = new FileReader(jsonFile)) { Gson gson = new Gson(); jsonObject = gson.fromJson(reader, JsonObject.class); } catch (Exception ex) { // parse error handling ex.printStackTrace(); } } // 更新邮件和密钥设置 jsonObject.addProperty("fofaEmail", fofaEmail.getText()); jsonObject.addProperty("fofaKey", fofaKey.getText()); // 将已更新的 jsonObject 写回到 "accounts.json" 文件 try (FileWriter writer = new FileWriter(accountsPath)) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(jsonObject, writer); JOptionPane.showMessageDialog(null, "设置已保存。"); } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "保存设置时发生错误!", "错误", JOptionPane.ERROR_MESSAGE); } }); // 添加组件到设置面板 settingsPanel.add(new JLabel("FOFA URL:")); settingsPanel.add(fofaUrl); settingsPanel.add(new JLabel("Email:")); settingsPanel.add(fofaEmail); settingsPanel.add(new JLabel("API Key:")); settingsPanel.add(fofaKey); settingsPanel.add(checkButton); settingsPanel.add(saveSettingsButton); // 添加设置面板到设置窗口,并显示设置窗口 settingsFrame.add(settingsPanel); settingsFrame.pack(); settingsFrame.setLocationRelativeTo(null); // 使窗口居中显示 settingsFrame.setResizable(false); settingsFrame.setVisible(true); } }); configureMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JTextField inputField = new JTextField(String.valueOf(sizeSetting)); JButton okButton = new JButton("保存"); JButton cancelButton = new JButton("取消"); JOptionPane optionPane = new JOptionPane(inputField, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION); optionPane.setOptions(new Object[] { okButton, cancelButton }); JDialog dialog = optionPane.createDialog("请输入默认查询数量"); okButton.addActionListener(ev -> { try { sizeSetting = Integer.parseInt(inputField.getText()); // 读取JSON文件 JsonObject jsonObject; File jsonFile = new File(accountsPath); if (jsonFile.exists() && jsonFile.length() != 0) { try (FileReader reader = new FileReader(jsonFile)) { Gson gson = new Gson(); jsonObject = gson.fromJson(reader, JsonObject.class); } catch (Exception ex) { ex.printStackTrace(); return; } } else { jsonObject = new JsonObject(); } // 更新queryNumber并重新写入文件 jsonObject.addProperty("queryNumber", sizeSetting); try (FileWriter writer = new FileWriter(accountsPath)) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(jsonObject, writer); } // 显示保存成功提醒 JOptionPane.showMessageDialog(null, "保存成功!"); // 关闭原始对话框 dialog.dispose(); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(null, "请输入一个有效的整数值。"); } catch (IOException ex) { // 处理文件读写异常 JOptionPane.showMessageDialog(null, "发生错误,账户配置文件不存在。"); } }); cancelButton.addActionListener(ev -> dialog.dispose()); dialog.setVisible(true); } }); configureFullItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JsonObject jsonObject; File jsonFile = new File("accounts.json"); // 如果文件存在且其内容不为空,从中读取 JsonObject if (jsonFile.exists() && jsonFile.length() != 0) { try (FileReader reader = new FileReader(jsonFile)) { Gson gson = new Gson(); jsonObject = gson.fromJson(reader, JsonObject.class); } catch (Exception ex) { // 解析错误处理 ex.printStackTrace(); return; } } else { jsonObject = new JsonObject(); } // 读取 queryFull 的值,并设置复选框的选择状态 if (jsonObject.has("queryFull")) { defaultCheckFullBox.setSelected(!jsonObject.get("queryFull").getAsBoolean()); } JButton okButton = new JButton("保存"); JButton cancelButton = new JButton("取消"); JOptionPane optionPane = new JOptionPane(defaultCheckFullBox, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION); optionPane.setOptions(new Object[]{okButton, cancelButton}); JDialog dialog = optionPane.createDialog("是否默认查询区间"); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); okButton.addActionListener(ev -> { // 如果复选框选中,则设置 queryFull 为 false,否则为 true boolean queryFull = !defaultCheckFullBox.isSelected(); jsonObject.addProperty("queryFull", queryFull); // 更新 setFull 的值 setFull = queryFull; // 将 jsonObject 保存到 "accounts.json" 文件中 try (FileWriter writer = new FileWriter(jsonFile)) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(jsonObject, writer); JOptionPane.showMessageDialog(null, "保存成功!"); dialog.dispose(); } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "发生错误,保存设置失败。"); } }); cancelButton.addActionListener(ev -> dialog.dispose()); dialog.setVisible(true); } }); // 图标哈希计算事件 iconHashLabMenuItem.addActionListener((ActionEvent event) -> { EventQueue.invokeLater(() -> { IconHashCalculator calculator = new IconHashCalculator(); calculator.setVisible(true); }); }); fofaHackMenuItemRun.addActionListener((ActionEvent event) -> { EventQueue.invokeLater(() -> { FofaHack.main(); }); }); openFileMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); // 如果存在上次打开的路径,则设置文件选择器的当前目录 if (lastOpenedPath != null) { fileChooser.setCurrentDirectory(lastOpenedPath); } if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); // 更新 lastOpenedPath 为当前选择的文件或文件夹 lastOpenedPath = fileChooser.getCurrentDirectory(); // 调用方法来处理文件 FofaHack.loadFileIntoTable(file); } } }); // 焦点测试 点击事件:显示当前标签 focusTestItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { CommonTemplate.localCurrentTab(tabbedPane0); // CommonTemplate.switchTab(tabbedPane0,tabName); } }); switchToHttpxItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { switchTab(tabbedPane0, "httpx"); } }); // 为"关于项目"菜单项添加动作监听器 aboutMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JEditorPane editorPane = new JEditorPane("text/html", ""); editorPane.setText( "<html><body>" + "<b>fofa EX:</b><br>" + "Project: <a href='https://github.com/10cks/fofaEX'>https://github.com/10cks/fofaEX</a><br>" + "Author: bwner@OverSpace<br>" + "Version: 2.2<br>" + "JDK Version: 11.0.5<br>" + "Update: 2023.12.11<br>" + "</body></html>" ); editorPane.setEditable(false); editorPane.setOpaque(false); editorPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent evt) { if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { try { Desktop.getDesktop().browse(evt.getURL().toURI()); } catch (IOException | URISyntaxException ex) { JOptionPane.showMessageDialog(null, "无法打开链接,错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } } }); // 弹出一个包含JEditorPane的消息对话框 JOptionPane.showMessageDialog(null, new JScrollPane(editorPane), "关于项目", JOptionPane.PLAIN_MESSAGE); } }); // 为 "fofahack 设置" 添加动作监听器 fofaHackMenuItemSetting.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 检查文件是否存在 File fofaHackSettingsFile = new File(".\\plugins\\fofahack\\FofaHackSetting.txt"); if (fofaHackSettingsFile.exists()) { // 如果文件存在,使用系统默认编辑器打开它 try { Desktop.getDesktop().edit(fofaHackSettingsFile); } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "无法打开配置文件!", "错误", JOptionPane.ERROR_MESSAGE); } } else { // 如果文件不存在,显示弹窗 JOptionPane.showMessageDialog(null, "未获取到配置文件!", "错误", JOptionPane.ERROR_MESSAGE); } } }); // 为" fofahack 关于项目"菜单项添加动作监听器 fofaHackMenuItemAbout.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JEditorPane editorPane = new JEditorPane("text/html", ""); editorPane.setText( "<html><body>" + "<b>fofa-hack:</b><br>" + "Project: <a href='https://github.com/Cl0udG0d/Fofa-hack'>https://github.com/Cl0udG0d/Fofa-hack</a><br>" + "Author: Cl0udG0d<br>" + "version: 当前使用为修改版<br>" + "</body></html>" ); editorPane.setEditable(false); editorPane.setOpaque(false); editorPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent evt) { if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { try { Desktop.getDesktop().browse(evt.getURL().toURI()); } catch (IOException | URISyntaxException ex) { JOptionPane.showMessageDialog(null, "无法打开链接,错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } } }); // 弹出一个包含JEditorPane的消息对话框 JOptionPane.showMessageDialog(null, new JScrollPane(editorPane), "关于项目", JOptionPane.PLAIN_MESSAGE); } }); } private static JTextField createTextField(String text) { JTextField textField = new JTextField(text, 20); textField.setPreferredSize(new Dimension(200, 20)); // 创建只有底边的边框 Border blueBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.RED); Border defaultBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY); // 设置默认边框 textField.setBorder(defaultBorder); // 添加鼠标监听器 textField.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { // 鼠标进入时,设置边框颜色为蓝色 textField.setBorder(blueBorder); } @Override public void mouseExited(MouseEvent e) { // 鼠标离开时,将边框颜色设回默认颜色 textField.setBorder(defaultBorder); } }); return textField; } private static JTextField createTextFieldFofa(String text) { RoundJTextField textField = new RoundJTextField(0); textField.setText(text); textField.setPreferredSize(new Dimension(800, 50)); // 设置文本与边框的间距 textField.setMargin(new Insets(0, 10, 0, 5)); // 创建只有底边的边框 Border blueBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.RED); Border defaultBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY); // 设置默认边框 // textField.setBorder(defaultBorder); return textField; } private static void createLogicAddButton(String buttonText, String appendText, JPanel panel, JTextField textField) { // 创建按钮 JButton button = new JButton(buttonText); button.setFocusPainted(false); // 不显示按钮焦点外边框 button.setFocusable(false); // 禁止按钮获取焦点 // 添加点击事件 button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (textField.getText().contains("fofaEX: FOFA Extension")) { textField.setText(""); } // 追加指定文本到文本框中 textField.setText(textField.getText() + " " + appendText); } }); // 将按钮添加到指定面板中 panel.add(button); } private static void searchButton(String buttonText, boolean shouldSetSize, JPanel panel, JTextField textField, JTextField emailField, JTextField keyField, JTextField urlField, JPanel resultPanel, JPanel exportPanel, JLabel changeIcon, JPanel disablePanel2, JPanel disablePanel3, JPanel disablePanel7, JPanel totalPanel8, String pageButton) { JButton button = new JButton(buttonText); button.setFocusPainted(false); button.setFocusable(false); if (shouldSetSize) { button.setPreferredSize(new Dimension(60, 50)); } button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { String domain = urlField.getText().trim(); String email = emailField.getText().trim(); String key = keyField.getText().trim(); String grammar = textField.getText().trim(); String orginIconStr = changeIcon.getText(); // String searchAsciiIcon = " ____ _ _ \n" + // " / ___| ___ __ _ _ __ ___ | |__ (_) _ __ __ _ \n" + // " \\___ \\ / _ \\ / _` | | '__| / __| | '_ \\ | | | '_ \\ / _` | \n" + // " ___) | | __/ | (_| | | | | (__ | | | | | | | | | | | (_| | \n" + // " |____/ \\___| \\__,_| |_| \\___| |_| |_| |_| |_| |_| \\__, | \n" ; // // // changeIcon.setText("<html><pre>" + searchAsciiIcon + "</pre></html>"); changeIcon.setText(" FOFA EX"); changeIcon.setForeground(new Color(89, 154, 248)); // 设置文本颜色为红色 Font font = new Font("Times New Roman", Font.BOLD, 60); changeIcon.setFont(font); setComponentsEnabled(disablePanel2, false); setComponentsEnabled(disablePanel3, false); setComponentsEnabled(disablePanel7, false); // 创建 SwingWorker 来处理搜索任务 SwingWorker<SearchResults, Void> worker = new SwingWorker<SearchResults, Void>() { private void fontSet(JLabel changeIcon, String originIconStr) { changeIcon.setText(originIconStr); changeIcon.setForeground(new Color(48, 49, 52)); } @Override protected SearchResults doInBackground() throws Exception { SearchResults results = new SearchResults(); QueryResponse queryResponse = new QueryResponse(); String errorMessage = null; // 用于存储错误消息 errorMessage = queryResponse.errmsg; // 存储错误消息以便后面使用 String fieldsTotal = ""; long startTime = System.nanoTime(); try { String query = grammar; if (query.equals("fofaEX: FOFA Extension")) { query = ""; // 将字符串设置为空 } if (protocolMark) { fieldsTotal += ",protocol"; } if (titleMark) { fieldsTotal += ",title"; } if (domainMark) { fieldsTotal += ",domain"; } if (linkMark) { fieldsTotal += ",link"; } if (icpMark) { fieldsTotal += ",icp"; } if (cityMark) { fieldsTotal += ",city"; } if (countryMark) { fieldsTotal += ",country"; } if (country_nameMark) { fieldsTotal += ",country_name"; } if (regionMark) { fieldsTotal += ",region"; } if (longitudeMark) { fieldsTotal += ",longitude"; } if (latitudeMark) { fieldsTotal += ",latitude"; } if (asNumberMark) { fieldsTotal += ",as_number"; } if (asOrganizationMark) { fieldsTotal += ",as_organization"; } if (osMark) { fieldsTotal += ",os"; } if (serverMark) { fieldsTotal += ",server"; } if (jarmMark) { fieldsTotal += ",jarm"; } if (headerMark) { fieldsTotal += ",header"; } if (bannerMark) { fieldsTotal += ",banner"; } if (baseProtocolMark) { fieldsTotal += ",base_protocol"; } if (certsIssuerOrgMark) { fieldsTotal += ",certs_issuer_org"; } if (certsIssuerCnMark) { fieldsTotal += ",certs_issuer_cn"; } if (certsSubjectOrgMark) { fieldsTotal += ",certs_subject_org"; } if (certsSubjectCnMark) { fieldsTotal += ",certs_subject_cn"; } if (tlsJa3sMark) { fieldsTotal += ",tls_ja3s"; } if (tlsVersionMark) { fieldsTotal += ",tls_version"; } if (productMark) { fieldsTotal += ",product"; } if (productCategoryMark) { fieldsTotal += ",product_category"; } if (versionMark) { fieldsTotal += ",version"; } if (lastupdatetimeMark) { fieldsTotal += ",lastupdatetime"; } if (cnameMark) { fieldsTotal += ",cname"; } if (iconHashMark) { fieldsTotal += ",icon_hash"; } if (certsValidMark) { fieldsTotal += ",certs_valid"; } if (cnameDomainMark) { fieldsTotal += ",cname_domain"; } if (bodyMark) { fieldsTotal += ",body"; } if (iconMark) { fieldsTotal += ",icon"; } if (fidMark) { fieldsTotal += ",fid"; } if (structinfoMark) { fieldsTotal += ",structinfo"; } // 创建字典 Map<String, Boolean> marks = new LinkedHashMap<>(); marks.put("host", ipMark); marks.put("ip", ipMark); marks.put("port", portMark); marks.put("protocol", protocolMark); marks.put("title", titleMark); marks.put("domain", domainMark); marks.put("link", linkMark); marks.put("icp", icpMark); marks.put("city", cityMark); marks.put("country", countryMark); marks.put("country_name", country_nameMark); marks.put("region", regionMark); marks.put("longitude", longitudeMark); marks.put("latitude", latitudeMark); marks.put("asNumber", asNumberMark); marks.put("asOrganization", asOrganizationMark); marks.put("os", osMark); marks.put("server", serverMark); marks.put("jarm", jarmMark); marks.put("header", headerMark); marks.put("banner", bannerMark); marks.put("baseProtocol", baseProtocolMark); marks.put("certsIssuerOrg", certsIssuerOrgMark); marks.put("certsIssuerCn", certsIssuerCnMark); marks.put("certsSubjectOrg", certsSubjectOrgMark); marks.put("certsSubjectCn", certsSubjectCnMark); marks.put("tlsJa3s", tlsJa3sMark); marks.put("tlsVersion", tlsVersionMark); marks.put("product", productMark); marks.put("productCategory", productCategoryMark); marks.put("version", versionMark); marks.put("lastupdatetime", lastupdatetimeMark); marks.put("cname", cnameMark); marks.put("iconHash", iconHashMark); marks.put("certsValid", certsValidMark); marks.put("cnameDomain", cnameDomainMark); marks.put("body", bodyMark); marks.put("icon", iconMark); marks.put("fid", fidMark); marks.put("structinfo", structinfoMark); // 标记为真的放在一起 List<String> trueMarks = extractTrueMarks(marks); System.out.println(trueMarks); if (pageButton.equals("left")) { if (currentPage != 0) { currentPage = currentPage - 1; } else { } currentPage = 1; } else if (pageButton.equals("right")) { currentPage = currentPage + 1; } // 开始查询 JSONObject jsonResponse = FofaAPI.getAllJsonResult(domain, email, key, query, fieldsTotal, sizeSetting, currentPage, setFull); // 检查错误信息 queryResponse.error = (boolean) FofaAPI.getValueFromJson(jsonResponse, "error"); queryResponse.errmsg = (String) FofaAPI.getValueFromJson(jsonResponse, "errmsg"); // 取出整体 results queryResponse.results = (List<List<String>>) FofaAPI.getValueFromJson(jsonResponse, "results"); if (queryResponse.error) { throw new Exception(queryResponse.errmsg); } List<List<String>> allShow = queryResponse.results; // 需要放在异常后面 // currentPage = (int) FofaAPI.getValueFromJson(jsonResponse, "page"); queryTotalNumber = (int) FofaAPI.getValueFromJson(jsonResponse, "size"); List<String> hostShow = FofaAPI.getColumn(allShow, 0); numberOfItems = hostShow.size(); int i = 0; for (String mark : trueMarks) { switch (mark) { case "host": results.host = FofaAPI.getColumn(allShow, i); break; case "ip": results.ip = FofaAPI.getColumn(allShow, i); break; case "protocol": results.protocol = FofaAPI.getColumn(allShow, i); break; case "port": results.port = FofaAPI.getColumn(allShow, i); break; case "title": results.title = decodeHtmlEntities(FofaAPI.getColumn(allShow, i)); break; case "domain": results.domain = FofaAPI.getColumn(allShow, i); break; case "link": results.link = FofaAPI.getColumn(allShow, i); break; case "icp": results.icp = FofaAPI.getColumn(allShow, i); break; case "city": results.city = FofaAPI.getColumn(allShow, i); break; case "country": results.country = FofaAPI.getColumn(allShow, i); break; case "country_name": results.country_name = FofaAPI.getColumn(allShow, i); break; case "region": results.region = FofaAPI.getColumn(allShow, i); break; case "longitude": results.longitude = FofaAPI.getColumn(allShow, i); break; case "latitude": results.latitude = FofaAPI.getColumn(allShow, i); break; case "asNumber": results.asNumber = FofaAPI.getColumn(allShow, i); break; case "asOrganization": results.asOrganization = FofaAPI.getColumn(allShow, i); break; case "os": results.os = FofaAPI.getColumn(allShow, i); break; case "server": results.server = FofaAPI.getColumn(allShow, i); break; case "jarm": results.jarm = FofaAPI.getColumn(allShow, i); break; case "header": results.header = FofaAPI.getColumn(allShow, i); break; case "banner": results.banner = FofaAPI.getColumn(allShow, i); break; case "baseProtocol": results.baseProtocol = FofaAPI.getColumn(allShow, i); break; case "certsIssuerOrg": results.certsIssuerOrg = FofaAPI.getColumn(allShow, i); break; case "certsIssuerCn": results.certsIssuerCn = FofaAPI.getColumn(allShow, i); break; case "certsSubjectOrg": results.certsSubjectOrg = FofaAPI.getColumn(allShow, i); break; case "certsSubjectCn": results.certsSubjectCn = FofaAPI.getColumn(allShow, i); break; case "tlsJa3s": results.tlsJa3s = FofaAPI.getColumn(allShow, i); break; case "tlsVersion": results.tlsVersion = FofaAPI.getColumn(allShow, i); break; case "product": results.product = FofaAPI.getColumn(allShow, i); break; case "productCategory": results.productCategory = FofaAPI.getColumn(allShow, i); break; case "version": results.version = FofaAPI.getColumn(allShow, i); break; case "lastupdatetime": results.lastupdatetime = FofaAPI.getColumn(allShow, i); break; case "cname": results.cname = FofaAPI.getColumn(allShow, i); break; case "iconHash": results.iconHash = FofaAPI.getColumn(allShow, i); break; case "certsValid": results.certsValid = FofaAPI.getColumn(allShow, i); break; case "cnameDomain": results.cnameDomain = FofaAPI.getColumn(allShow, i); break; case "body": results.body = FofaAPI.getColumn(allShow, i); break; case "icon": results.icon = FofaAPI.getColumn(allShow, i); break; case "fid": results.fid = FofaAPI.getColumn(allShow, i); break; case "structinfo": results.structinfo = FofaAPI.getColumn(allShow, i); break; } i = i + 1; } // 导出表格 JButton exportButton = new JButton("Export to Excel"); exportButton.setFocusPainted(false); // 添加这一行来取消焦点边框的绘制 exportButton.setFocusable(false); // 禁止了按钮获取焦点,因此按钮不会在被点击后显示为"激活"或"选中"的状态 if (!exportButtonAdded) { exportPanel.add(exportButton); exportButtonAdded = true; } exportButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 在这里检查 table 是否被初始化 if (table == null) { JOptionPane.showMessageDialog(null, "表格没有被初始化"); fontSet(changeIcon, orginIconStr); setComponentsEnabled(disablePanel2, true); setComponentsEnabled(disablePanel3, true); setComponentsEnabled(disablePanel7, true); return; } // 检查 table 是否有模型和数据 if (table.getModel() == null || table.getModel().getRowCount() <= 0) { JOptionPane.showMessageDialog(null, "当前无数据"); fontSet(changeIcon, orginIconStr); setComponentsEnabled(disablePanel2, true); setComponentsEnabled(disablePanel3, true); setComponentsEnabled(disablePanel7, true); return; } CommonExecute.exportTableToExcel(table); } }); } catch (JSONException ex) { currentPage = 1; ex.printStackTrace(); JOptionPane.showMessageDialog(null, "发生错误,请重试!", "错误", JOptionPane.ERROR_MESSAGE); fontSet(changeIcon, orginIconStr); setComponentsEnabled(disablePanel2, true); setComponentsEnabled(disablePanel3, true); setComponentsEnabled(disablePanel7, true); } catch (Exception e) { JOptionPane.showMessageDialog(null, errorMessage != null ? errorMessage : e.getMessage(), "执行失败", JOptionPane.ERROR_MESSAGE); currentPage = 1; fontSet(changeIcon, orginIconStr); setComponentsEnabled(disablePanel2, true); setComponentsEnabled(disablePanel3, true); setComponentsEnabled(disablePanel7, true); throw new RuntimeException(e); } finally { long endTime = System.nanoTime(); // Stop the timer long duration = endTime - startTime; double seconds = (double) duration / 1_000_000_000.0; // Convert nanoseconds to seconds SwingUtilities.invokeLater(() -> { String totalLabelShow = "<html>" + "Page: " + currentPage + "<br>" + "Items/Totals: " + numberOfItems * currentPage + "/" + queryTotalNumber + "<br>Time: " + seconds + " seconds</html>"; if (!timeAdded) { // 只有当timeLabel为null时才创建新的实例 if (timeLabel == null) { timeLabel = new JLabel(); } timeLabel.setText(totalLabelShow); totalPanel8.add(timeLabel); timeAdded = true; } else { if (timeLabel != null) { // 确保timeLabel不为null timeLabel.setText(totalLabelShow); } } totalPanel8.revalidate(); totalPanel8.repaint(); }); } fontSet(changeIcon, orginIconStr); setComponentsEnabled(disablePanel2, true); setComponentsEnabled(disablePanel3, true); setComponentsEnabled(disablePanel7, true); return results; } @Override protected void done() { try { SearchResults searchResults = get(); assert searchResults != null; showResultsInTable( searchResults.host, searchResults.ip, searchResults.port, searchResults.protocol, searchResults.title, searchResults.domain, searchResults.link, searchResults.icp, searchResults.city, searchResults.country, searchResults.country_name, searchResults.region, searchResults.longitude, searchResults.latitude, searchResults.asNumber, searchResults.asOrganization, searchResults.os, searchResults.server, searchResults.jarm, searchResults.header, searchResults.banner, searchResults.baseProtocol, searchResults.certsIssuerOrg, searchResults.certsIssuerCn, searchResults.certsSubjectOrg, searchResults.certsSubjectCn, searchResults.tlsJa3s, searchResults.tlsVersion, searchResults.product, searchResults.productCategory, searchResults.version, searchResults.lastupdatetime, searchResults.cname, searchResults.iconHash, searchResults.certsValid, searchResults.cnameDomain, searchResults.body, searchResults.icon, searchResults.fid, searchResults.structinfo, resultPanel ); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } }; // 启动 SwingWorker worker.execute(); } }); panel.add(button); } private static void showResultsInTable(List<String> host, List<String> tableIpShow, List<String> tablePortShow, List<String> protocolShow, List<String> titleShow, List<String> domainShow, List<String> linkShow, List<String> icpShow, List<String> cityShow, List<String> countryShow, List<String> country_nameShow, List<String> regionShow, List<String> longitudeShow, List<String> latitudeShow, List<String> asNumberShow, List<String> asOrganizationShow, List<String> osShow, List<String> serverShow, List<String> jarmShow, List<String> headerShow, List<String> bannerShow, List<String> baseProtocolShow, List<String> certsIssuerOrgShow, List<String> certsIssuerCnShow, List<String> certsSubjectOrgShow, List<String> certsSubjectCnShow, List<String> tlsJa3sShow, List<String> tlsVersionShow, List<String> productShow, List<String> productCategoryShow, List<String> versionShow, List<String> lastupdatetimeShow, List<String> cnameShow, List<String> iconHashShow, List<String> certsValidShow, List<String> cnameDomainShow, List<String> bodyShow, List<String> iconShow, List<String> fidShow, List<String> structinfoShow, JPanel panel) { List<String> columnNamesList = new ArrayList<String>(List.of("host")); if (structinfoMark) { columnNamesList.add(1, "structinfo"); } if (fidMark) { columnNamesList.add(1, "fid"); } if (iconMark) { columnNamesList.add(1, "icon"); } if (bodyMark) { columnNamesList.add(1, "body"); } if (cnameDomainMark) { columnNamesList.add(1, "cnameDomain"); } if (certsValidMark) { columnNamesList.add(1, "certsValid"); } if (iconHashMark) { columnNamesList.add(1, "iconHash"); } if (cnameMark) { columnNamesList.add(1, "cname"); } if (lastupdatetimeMark) { columnNamesList.add(1, "lastupdatetime"); } if (versionMark) { columnNamesList.add(1, "version"); } if (productCategoryMark) { columnNamesList.add(1, "productCategory"); } if (productMark) { columnNamesList.add(1, "product"); } if (tlsVersionMark) { columnNamesList.add(1, "tlsVersion"); } if (tlsJa3sMark) { columnNamesList.add(1, "tlsJa3s"); } if (certsSubjectCnMark) { columnNamesList.add(1, "certsSubjectCn"); } if (certsSubjectOrgMark) { columnNamesList.add(1, "certsSubjectOrg"); } if (certsIssuerCnMark) { columnNamesList.add(1, "certsIssuerCn"); } if (certsIssuerOrgMark) { columnNamesList.add(1, "certsIssuerOrg"); } if (baseProtocolMark) { columnNamesList.add(1, "baseProtocol"); } if (bannerMark) { columnNamesList.add(1, "banner"); } if (headerMark) { columnNamesList.add(1, "header"); } if (jarmMark) { columnNamesList.add(1, "jarm"); } if (serverMark) { columnNamesList.add(1, "server"); } if (osMark) { columnNamesList.add(1, "os"); } if (asOrganizationMark) { columnNamesList.add(1, "asOrganization"); } if (asNumberMark) { columnNamesList.add(1, "asNumber"); } if (latitudeMark) { columnNamesList.add(1, "latitude"); } if (longitudeMark) { columnNamesList.add(1, "longitude"); } if (regionMark) { columnNamesList.add(1, "region"); } if (country_nameMark) { columnNamesList.add(1, "country_name"); } if (countryMark) { columnNamesList.add(1, "country"); } if (cityMark) { columnNamesList.add(1, "city"); } if (icpMark) { columnNamesList.add(1, "icp"); } if (linkMark) { columnNamesList.add(1, "link"); } if (domainMark) { columnNamesList.add(1, "domain"); } if (titleMark) { columnNamesList.add(1, "title"); } if (protocolMark) { columnNamesList.add(1, "protocol"); } if (portMark) { columnNamesList.add(1, "port"); } if (ipMark) { columnNamesList.add(1, "ip"); } String[] columnNames = columnNamesList.toArray(new String[0]); Object[][] data = new Object[host.size()][columnNames.length]; for (int i = 0; i < host.size(); i++) { data[i][0] = host.get(i); int columnIndex = 1; if (ipMark && tableIpShow.size() > i) { data[i][columnIndex++] = tableIpShow.get(i); } if (portMark && tablePortShow.size() > i) { data[i][columnIndex++] = tablePortShow.get(i); } if (protocolMark && protocolShow.size() > i) { data[i][columnIndex++] = protocolShow.get(i); } if (titleMark && titleShow.size() > i) { data[i][columnIndex++] = titleShow.get(i); } if (domainMark && domainShow.size() > i) { data[i][columnIndex++] = domainShow.get(i); } if (linkMark && linkShow.size() > i) { data[i][columnIndex++] = linkShow.get(i); } if (icpMark && icpShow.size() > i) { data[i][columnIndex++] = icpShow.get(i); } if (cityMark && cityShow.size() > i) { data[i][columnIndex++] = cityShow.get(i); } if (countryMark && countryShow.size() > i) { data[i][columnIndex++] = countryShow.get(i); } if (country_nameMark && country_nameShow.size() > i) { data[i][columnIndex++] = country_nameShow.get(i); } if (regionMark && regionShow.size() > i) { data[i][columnIndex++] = regionShow.get(i); } if (longitudeMark && longitudeShow.size() > i) { data[i][columnIndex++] = longitudeShow.get(i); } if (latitudeMark && latitudeShow.size() > i) { data[i][columnIndex++] = latitudeShow.get(i); } if (asNumberMark && asNumberShow.size() > i) { data[i][columnIndex++] = asNumberShow.get(i); } if (asOrganizationMark && asOrganizationShow.size() > i) { data[i][columnIndex++] = asOrganizationShow.get(i); } if (osMark && osShow.size() > i) { data[i][columnIndex++] = osShow.get(i); } if (serverMark && serverShow.size() > i) { data[i][columnIndex++] = serverShow.get(i); } if (jarmMark && jarmShow.size() > i) { data[i][columnIndex++] = jarmShow.get(i); } if (headerMark && headerShow.size() > i) { data[i][columnIndex++] = headerShow.get(i); } if (bannerMark && bannerShow.size() > i) { data[i][columnIndex++] = bannerShow.get(i); } if (baseProtocolMark && baseProtocolShow.size() > i) { data[i][columnIndex++] = baseProtocolShow.get(i); } if (certsIssuerOrgMark && certsIssuerOrgShow.size() > i) { data[i][columnIndex++] = certsIssuerOrgShow.get(i); } if (certsIssuerCnMark && certsIssuerCnShow.size() > i) { data[i][columnIndex++] = certsIssuerCnShow.get(i); } if (certsSubjectOrgMark && certsSubjectOrgShow.size() > i) { data[i][columnIndex++] = certsSubjectOrgShow.get(i); } if (certsSubjectCnMark && certsSubjectCnShow.size() > i) { data[i][columnIndex++] = certsSubjectCnShow.get(i); } if (tlsJa3sMark && tlsJa3sShow.size() > i) { data[i][columnIndex++] = tlsJa3sShow.get(i); } if (tlsVersionMark && tlsVersionShow.size() > i) { data[i][columnIndex++] = tlsVersionShow.get(i); } if (productMark && productShow.size() > i) { data[i][columnIndex++] = productShow.get(i); } if (productCategoryMark && productCategoryShow.size() > i) { data[i][columnIndex++] = productCategoryShow.get(i); } if (versionMark && versionShow.size() > i) { data[i][columnIndex++] = versionShow.get(i); } if (lastupdatetimeMark && lastupdatetimeShow.size() > i) { data[i][columnIndex++] = lastupdatetimeShow.get(i); } if (cnameMark && cnameShow.size() > i) { data[i][columnIndex++] = cnameShow.get(i); } if (iconHashMark && iconHashShow.size() > i) { data[i][columnIndex++] = iconHashShow.get(i); } if (certsValidMark && certsValidShow.size() > i) { data[i][columnIndex++] = certsValidShow.get(i); } if (cnameDomainMark && cnameDomainShow.size() > i) { data[i][columnIndex++] = cnameDomainShow.get(i); } if (bodyMark && bodyShow.size() > i) { data[i][columnIndex++] = bodyShow.get(i); } if (iconMark && iconShow.size() > i) { data[i][columnIndex++] = iconShow.get(i); } if (fidMark && fidShow.size() > i) { data[i][columnIndex++] = fidShow.get(i); } if (structinfoMark && structinfoShow.size() > i) { data[i][columnIndex++] = structinfoShow.get(i); } } DefaultTableModel model = new DefaultTableModel(data, columnNames); table.setModel(model); // 重新设置表格头,以便新的渲染器生效 JTableHeader header = getjTableHeader(table); table.setTableHeader(header);
adjustColumnWidths(table); // 自动调整列宽
7
2023-12-07 13:46:27+00:00
24k
Mahmud0808/ColorBlendr
app/src/main/java/com/drdisagree/colorblendr/ui/fragments/ColorsFragment.java
[ { "identifier": "MANUAL_OVERRIDE_COLORS", "path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java", "snippet": "public static final String MANUAL_OVERRIDE_COLORS = \"manualOverrideColors\";" }, { "identifier": "MONET_ACCENT_SATURATION", "path": "app/src/main/java/com/drdisagr...
import static com.drdisagree.colorblendr.common.Const.MANUAL_OVERRIDE_COLORS; import static com.drdisagree.colorblendr.common.Const.MONET_ACCENT_SATURATION; import static com.drdisagree.colorblendr.common.Const.MONET_ACCURATE_SHADES; import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_LIGHTNESS; import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_SATURATION; import static com.drdisagree.colorblendr.common.Const.MONET_LAST_UPDATED; import static com.drdisagree.colorblendr.common.Const.MONET_PITCH_BLACK_THEME; import static com.drdisagree.colorblendr.common.Const.MONET_SEED_COLOR; import static com.drdisagree.colorblendr.common.Const.MONET_SEED_COLOR_ENABLED; import static com.drdisagree.colorblendr.common.Const.MONET_STYLE; import static com.drdisagree.colorblendr.common.Const.WALLPAPER_COLOR_LIST; import android.content.BroadcastReceiver; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; 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.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.drdisagree.colorblendr.R; import com.drdisagree.colorblendr.common.Const; import com.drdisagree.colorblendr.config.RPrefs; import com.drdisagree.colorblendr.databinding.FragmentColorsBinding; import com.drdisagree.colorblendr.ui.viewmodels.SharedViewModel; import com.drdisagree.colorblendr.ui.views.WallColorPreview; import com.drdisagree.colorblendr.utils.ColorSchemeUtil; import com.drdisagree.colorblendr.utils.ColorUtil; import com.drdisagree.colorblendr.utils.MiscUtil; import com.drdisagree.colorblendr.utils.OverlayManager; import com.drdisagree.colorblendr.utils.WallpaperUtil; import com.google.android.material.snackbar.Snackbar; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import me.jfenn.colorpickerdialog.dialogs.ColorPickerDialog; import me.jfenn.colorpickerdialog.views.picker.ImagePickerView;
18,756
package com.drdisagree.colorblendr.ui.fragments; @SuppressWarnings("deprecation") public class ColorsFragment extends Fragment { private static final String TAG = ColorsFragment.class.getSimpleName(); private FragmentColorsBinding binding; private int[] monetSeedColor; private LinearLayout[] colorTableRows; private SharedViewModel sharedViewModel; private final String[][] colorNames = ColorUtil.getColorNames(); private static final int[] colorCodes = { 0, 10, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 }; private final BroadcastReceiver wallpaperChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, android.content.Intent intent) { if (binding.colorsToggleGroup.getCheckedButtonId() == R.id.wallpaper_colors_button) { addWallpaperColorItems(); } } }; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentColorsBinding.inflate(inflater, container, false); MiscUtil.setToolbarTitle(requireContext(), R.string.app_name, false, binding.header.toolbar); monetSeedColor = new int[]{RPrefs.getInt(
package com.drdisagree.colorblendr.ui.fragments; @SuppressWarnings("deprecation") public class ColorsFragment extends Fragment { private static final String TAG = ColorsFragment.class.getSimpleName(); private FragmentColorsBinding binding; private int[] monetSeedColor; private LinearLayout[] colorTableRows; private SharedViewModel sharedViewModel; private final String[][] colorNames = ColorUtil.getColorNames(); private static final int[] colorCodes = { 0, 10, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 }; private final BroadcastReceiver wallpaperChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, android.content.Intent intent) { if (binding.colorsToggleGroup.getCheckedButtonId() == R.id.wallpaper_colors_button) { addWallpaperColorItems(); } } }; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentColorsBinding.inflate(inflater, container, false); MiscUtil.setToolbarTitle(requireContext(), R.string.app_name, false, binding.header.toolbar); monetSeedColor = new int[]{RPrefs.getInt(
MONET_SEED_COLOR,
7
2023-12-06 13:20:16+00:00
24k
lxs2601055687/contextAdminRuoYi
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java
[ { "identifier": "CacheNames", "path": "ruoyi-common/src/main/java/com/ruoyi/common/constant/CacheNames.java", "snippet": "public interface CacheNames {\n\n /**\n * 演示案例\n */\n String DEMO_CACHE = \"demo:cache#60s#10m#20\";\n\n /**\n * 系统配置\n */\n String SYS_CONFIG = \"sys_con...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ruoyi.common.constant.CacheNames; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.PageQuery; import com.ruoyi.common.core.domain.entity.SysDept; import com.ruoyi.common.core.domain.entity.SysRole; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.core.service.UserService; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.helper.DataBaseHelper; import com.ruoyi.common.helper.LoginHelper; import com.ruoyi.common.utils.StreamUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.SysPost; import com.ruoyi.system.domain.SysUserPost; import com.ruoyi.system.domain.SysUserRole; import com.ruoyi.system.mapper.*; import com.ruoyi.system.service.ISysUserService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Arrays; import java.util.List; import java.util.Map;
15,928
* @return 结果 */ @Override public boolean updateUserAvatar(String userName, String avatar) { return baseMapper.update(null, new LambdaUpdateWrapper<SysUser>() .set(SysUser::getAvatar, avatar) .eq(SysUser::getUserName, userName)) > 0; } /** * 重置用户密码 * * @param user 用户信息 * @return 结果 */ @Override public int resetPwd(SysUser user) { return baseMapper.updateById(user); } /** * 重置用户密码 * * @param userName 用户名 * @param password 密码 * @return 结果 */ @Override public int resetUserPwd(String userName, String password) { return baseMapper.update(null, new LambdaUpdateWrapper<SysUser>() .set(SysUser::getPassword, password) .eq(SysUser::getUserName, userName)); } /** * 新增用户角色信息 * * @param user 用户对象 */ public void insertUserRole(SysUser user) { this.insertUserRole(user.getUserId(), user.getRoleIds()); } /** * 新增用户岗位信息 * * @param user 用户对象 */ public void insertUserPost(SysUser user) { Long[] posts = user.getPostIds(); if (ArrayUtil.isNotEmpty(posts)) { // 新增用户与岗位管理 List<SysUserPost> list = StreamUtils.toList(Arrays.asList(posts), postId -> { SysUserPost up = new SysUserPost(); up.setUserId(user.getUserId()); up.setPostId(postId); return up; }); userPostMapper.insertBatch(list); } } /** * 新增用户角色信息 * * @param userId 用户ID * @param roleIds 角色组 */ public void insertUserRole(Long userId, Long[] roleIds) { if (ArrayUtil.isNotEmpty(roleIds)) { // 新增用户与角色管理 List<SysUserRole> list = StreamUtils.toList(Arrays.asList(roleIds), roleId -> { SysUserRole ur = new SysUserRole(); ur.setUserId(userId); ur.setRoleId(roleId); return ur; }); userRoleMapper.insertBatch(list); } } /** * 通过用户ID删除用户 * * @param userId 用户ID * @return 结果 */ @Override @Transactional(rollbackFor = Exception.class) public int deleteUserById(Long userId) { // 删除用户与角色关联 userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId)); // 删除用户与岗位表 userPostMapper.delete(new LambdaQueryWrapper<SysUserPost>().eq(SysUserPost::getUserId, userId)); return baseMapper.deleteById(userId); } /** * 批量删除用户信息 * * @param userIds 需要删除的用户ID * @return 结果 */ @Override @Transactional(rollbackFor = Exception.class) public int deleteUserByIds(Long[] userIds) { for (Long userId : userIds) { checkUserAllowed(new SysUser(userId)); checkUserDataScope(userId); } List<Long> ids = Arrays.asList(userIds); // 删除用户与角色关联 userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, ids)); // 删除用户与岗位表 userPostMapper.delete(new LambdaQueryWrapper<SysUserPost>().in(SysUserPost::getUserId, ids)); return baseMapper.deleteBatchIds(ids); }
package com.ruoyi.system.service.impl; /** * 用户 业务层处理 * * @author Lion Li */ @Slf4j @RequiredArgsConstructor @Service public class SysUserServiceImpl implements ISysUserService, UserService { private final SysUserMapper baseMapper; private final SysDeptMapper deptMapper; private final SysRoleMapper roleMapper; private final SysPostMapper postMapper; private final SysUserRoleMapper userRoleMapper; private final SysUserPostMapper userPostMapper; @Override public TableDataInfo<SysUser> selectPageUserList(SysUser user, PageQuery pageQuery) { Page<SysUser> page = baseMapper.selectPageUserList(pageQuery.build(), this.buildQueryWrapper(user)); return TableDataInfo.build(page); } /** * 根据条件分页查询用户列表 * * @param user 用户信息 * @return 用户信息集合信息 */ @Override public List<SysUser> selectUserList(SysUser user) { return baseMapper.selectUserList(this.buildQueryWrapper(user)); } private Wrapper<SysUser> buildQueryWrapper(SysUser user) { Map<String, Object> params = user.getParams(); QueryWrapper<SysUser> wrapper = Wrappers.query(); wrapper.eq("u.del_flag", UserConstants.USER_NORMAL) .eq(ObjectUtil.isNotNull(user.getUserId()), "u.user_id", user.getUserId()) .like(StringUtils.isNotBlank(user.getUserName()), "u.user_name", user.getUserName()) .eq(StringUtils.isNotBlank(user.getStatus()), "u.status", user.getStatus()) .like(StringUtils.isNotBlank(user.getPhonenumber()), "u.phonenumber", user.getPhonenumber()) .between(params.get("beginTime") != null && params.get("endTime") != null, "u.create_time", params.get("beginTime"), params.get("endTime")) .and(ObjectUtil.isNotNull(user.getDeptId()), w -> { List<SysDept> deptList = deptMapper.selectList(new LambdaQueryWrapper<SysDept>() .select(SysDept::getDeptId) .apply(DataBaseHelper.findInSet(user.getDeptId(), "ancestors"))); List<Long> ids = StreamUtils.toList(deptList, SysDept::getDeptId); ids.add(user.getDeptId()); w.in("u.dept_id", ids); }); return wrapper; } /** * 根据条件分页查询已分配用户角色列表 * * @param user 用户信息 * @return 用户信息集合信息 */ @Override public TableDataInfo<SysUser> selectAllocatedList(SysUser user, PageQuery pageQuery) { QueryWrapper<SysUser> wrapper = Wrappers.query(); wrapper.eq("u.del_flag", UserConstants.USER_NORMAL) .eq(ObjectUtil.isNotNull(user.getRoleId()), "r.role_id", user.getRoleId()) .like(StringUtils.isNotBlank(user.getUserName()), "u.user_name", user.getUserName()) .eq(StringUtils.isNotBlank(user.getStatus()), "u.status", user.getStatus()) .like(StringUtils.isNotBlank(user.getPhonenumber()), "u.phonenumber", user.getPhonenumber()); Page<SysUser> page = baseMapper.selectAllocatedList(pageQuery.build(), wrapper); return TableDataInfo.build(page); } /** * 根据条件分页查询未分配用户角色列表 * * @param user 用户信息 * @return 用户信息集合信息 */ @Override public TableDataInfo<SysUser> selectUnallocatedList(SysUser user, PageQuery pageQuery) { List<Long> userIds = userRoleMapper.selectUserIdsByRoleId(user.getRoleId()); QueryWrapper<SysUser> wrapper = Wrappers.query(); wrapper.eq("u.del_flag", UserConstants.USER_NORMAL) .and(w -> w.ne("r.role_id", user.getRoleId()).or().isNull("r.role_id")) .notIn(CollUtil.isNotEmpty(userIds), "u.user_id", userIds) .like(StringUtils.isNotBlank(user.getUserName()), "u.user_name", user.getUserName()) .like(StringUtils.isNotBlank(user.getPhonenumber()), "u.phonenumber", user.getPhonenumber()); Page<SysUser> page = baseMapper.selectUnallocatedList(pageQuery.build(), wrapper); return TableDataInfo.build(page); } /** * 通过用户名查询用户 * * @param userName 用户名 * @return 用户对象信息 */ @Override public SysUser selectUserByUserName(String userName) { return baseMapper.selectUserByUserName(userName); } /** * 通过手机号查询用户 * * @param phonenumber 手机号 * @return 用户对象信息 */ @Override public SysUser selectUserByPhonenumber(String phonenumber) { return baseMapper.selectUserByPhonenumber(phonenumber); } /** * 通过用户ID查询用户 * * @param userId 用户ID * @return 用户对象信息 */ @Override public SysUser selectUserById(Long userId) { return baseMapper.selectUserById(userId); } /** * 查询用户所属角色组 * * @param userName 用户名 * @return 结果 */ @Override public String selectUserRoleGroup(String userName) { List<SysRole> list = roleMapper.selectRolesByUserName(userName); if (CollUtil.isEmpty(list)) { return StringUtils.EMPTY; } return StreamUtils.join(list, SysRole::getRoleName); } /** * 查询用户所属岗位组 * * @param userName 用户名 * @return 结果 */ @Override public String selectUserPostGroup(String userName) { List<SysPost> list = postMapper.selectPostsByUserName(userName); if (CollUtil.isEmpty(list)) { return StringUtils.EMPTY; } return StreamUtils.join(list, SysPost::getPostName); } /** * 校验用户名称是否唯一 * * @param user 用户信息 * @return 结果 */ @Override public boolean checkUserNameUnique(SysUser user) { boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysUser>() .eq(SysUser::getUserName, user.getUserName()) .ne(ObjectUtil.isNotNull(user.getUserId()), SysUser::getUserId, user.getUserId())); return !exist; } /** * 校验手机号码是否唯一 * * @param user 用户信息 */ @Override public boolean checkPhoneUnique(SysUser user) { boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysUser>() .eq(SysUser::getPhonenumber, user.getPhonenumber()) .ne(ObjectUtil.isNotNull(user.getUserId()), SysUser::getUserId, user.getUserId())); return !exist; } /** * 校验email是否唯一 * * @param user 用户信息 */ @Override public boolean checkEmailUnique(SysUser user) { boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysUser>() .eq(SysUser::getEmail, user.getEmail()) .ne(ObjectUtil.isNotNull(user.getUserId()), SysUser::getUserId, user.getUserId())); return !exist; } /** * 校验用户是否允许操作 * * @param user 用户信息 */ @Override public void checkUserAllowed(SysUser user) { if (ObjectUtil.isNotNull(user.getUserId()) && user.isAdmin()) { throw new ServiceException("不允许操作超级管理员用户"); } } /** * 校验用户是否有数据权限 * * @param userId 用户id */ @Override public void checkUserDataScope(Long userId) { if (!LoginHelper.isAdmin()) { SysUser user = new SysUser(); user.setUserId(userId); List<SysUser> users = this.selectUserList(user); if (CollUtil.isEmpty(users)) { throw new ServiceException("没有权限访问用户数据!"); } } } /** * 新增保存用户信息 * * @param user 用户信息 * @return 结果 */ @Override @Transactional(rollbackFor = Exception.class) public int insertUser(SysUser user) { // 新增用户信息 int rows = baseMapper.insert(user); // 新增用户岗位关联 insertUserPost(user); // 新增用户与角色管理 insertUserRole(user); return rows; } /** * 注册用户信息 * * @param user 用户信息 * @return 结果 */ @Override public boolean registerUser(SysUser user) { user.setCreateBy(user.getUserName()); user.setUpdateBy(user.getUserName()); return baseMapper.insert(user) > 0; } /** * 修改保存用户信息 * * @param user 用户信息 * @return 结果 */ @Override @Transactional(rollbackFor = Exception.class) public int updateUser(SysUser user) { Long userId = user.getUserId(); // 删除用户与角色关联 userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId)); // 新增用户与角色管理 insertUserRole(user); // 删除用户与岗位关联 userPostMapper.delete(new LambdaQueryWrapper<SysUserPost>().eq(SysUserPost::getUserId, userId)); // 新增用户与岗位管理 insertUserPost(user); return baseMapper.updateById(user); } /** * 用户授权角色 * * @param userId 用户ID * @param roleIds 角色组 */ @Override @Transactional(rollbackFor = Exception.class) public void insertUserAuth(Long userId, Long[] roleIds) { userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>() .eq(SysUserRole::getUserId, userId)); insertUserRole(userId, roleIds); } /** * 修改用户状态 * * @param user 用户信息 * @return 结果 */ @Override public int updateUserStatus(SysUser user) { return baseMapper.updateById(user); } /** * 修改用户基本信息 * * @param user 用户信息 * @return 结果 */ @Override public int updateUserProfile(SysUser user) { return baseMapper.updateById(user); } /** * 修改用户头像 * * @param userName 用户名 * @param avatar 头像地址 * @return 结果 */ @Override public boolean updateUserAvatar(String userName, String avatar) { return baseMapper.update(null, new LambdaUpdateWrapper<SysUser>() .set(SysUser::getAvatar, avatar) .eq(SysUser::getUserName, userName)) > 0; } /** * 重置用户密码 * * @param user 用户信息 * @return 结果 */ @Override public int resetPwd(SysUser user) { return baseMapper.updateById(user); } /** * 重置用户密码 * * @param userName 用户名 * @param password 密码 * @return 结果 */ @Override public int resetUserPwd(String userName, String password) { return baseMapper.update(null, new LambdaUpdateWrapper<SysUser>() .set(SysUser::getPassword, password) .eq(SysUser::getUserName, userName)); } /** * 新增用户角色信息 * * @param user 用户对象 */ public void insertUserRole(SysUser user) { this.insertUserRole(user.getUserId(), user.getRoleIds()); } /** * 新增用户岗位信息 * * @param user 用户对象 */ public void insertUserPost(SysUser user) { Long[] posts = user.getPostIds(); if (ArrayUtil.isNotEmpty(posts)) { // 新增用户与岗位管理 List<SysUserPost> list = StreamUtils.toList(Arrays.asList(posts), postId -> { SysUserPost up = new SysUserPost(); up.setUserId(user.getUserId()); up.setPostId(postId); return up; }); userPostMapper.insertBatch(list); } } /** * 新增用户角色信息 * * @param userId 用户ID * @param roleIds 角色组 */ public void insertUserRole(Long userId, Long[] roleIds) { if (ArrayUtil.isNotEmpty(roleIds)) { // 新增用户与角色管理 List<SysUserRole> list = StreamUtils.toList(Arrays.asList(roleIds), roleId -> { SysUserRole ur = new SysUserRole(); ur.setUserId(userId); ur.setRoleId(roleId); return ur; }); userRoleMapper.insertBatch(list); } } /** * 通过用户ID删除用户 * * @param userId 用户ID * @return 结果 */ @Override @Transactional(rollbackFor = Exception.class) public int deleteUserById(Long userId) { // 删除用户与角色关联 userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId)); // 删除用户与岗位表 userPostMapper.delete(new LambdaQueryWrapper<SysUserPost>().eq(SysUserPost::getUserId, userId)); return baseMapper.deleteById(userId); } /** * 批量删除用户信息 * * @param userIds 需要删除的用户ID * @return 结果 */ @Override @Transactional(rollbackFor = Exception.class) public int deleteUserByIds(Long[] userIds) { for (Long userId : userIds) { checkUserAllowed(new SysUser(userId)); checkUserDataScope(userId); } List<Long> ids = Arrays.asList(userIds); // 删除用户与角色关联 userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, ids)); // 删除用户与岗位表 userPostMapper.delete(new LambdaQueryWrapper<SysUserPost>().in(SysUserPost::getUserId, ids)); return baseMapper.deleteBatchIds(ids); }
@Cacheable(cacheNames = CacheNames.SYS_USER_NAME, key = "#userId")
0
2023-12-07 12:06:21+00:00
24k
DantSu/studio
web-ui/src/main/java/studio/webui/service/StoryTellerService.java
[ { "identifier": "PackFormat", "path": "core/src/main/java/studio/core/v1/utils/PackFormat.java", "snippet": "public enum PackFormat {\n\n ARCHIVE(new ArchiveStoryPackReader(), new ArchiveStoryPackWriter()),\n\n RAW(new BinaryStoryPackReader(), new BinaryStoryPackWriter()),\n\n FS(new FsStoryPac...
import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.usb4java.Device; import io.vertx.core.eventbus.EventBus; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import studio.core.v1.utils.PackFormat; import studio.core.v1.utils.SecurityUtils; import studio.core.v1.utils.exception.StoryTellerException; import studio.driver.StoryTellerAsyncDriver; import studio.driver.fs.FsStoryTellerAsyncDriver; import studio.driver.model.StoryPackInfos; import studio.driver.model.fs.FsDeviceInfos; import studio.driver.model.fs.FsStoryPackInfos; import studio.driver.model.raw.RawDeviceInfos; import studio.driver.model.raw.RawStoryPackInfos; import studio.driver.raw.LibUsbMassStorageHelper; import studio.driver.raw.RawStoryTellerAsyncDriver; import studio.metadata.DatabaseMetadataService;
19,936
// React when a device with firmware 2.x is plugged or unplugged fsDriver.registerDeviceListener( device -> { if (device == null) { LOGGER.error("Device 2.x plugged but got null device"); // Send 'failure' event on bus sendFailure(); } else { LOGGER.info("Device 2.x plugged"); StoryTellerService.this.fsDevice = device; CompletableFuture.runAsync(() -> fsDriver.getDeviceInfos().handle((infos, e) -> { if (e != null) { LOGGER.error("Failed to plug device 2.x", e); // Send 'failure' event on bus sendFailure(); } else { // Send 'plugged' event on bus sendDevicePlugged(toJson(infos)); } return null; })); } }, device -> { LOGGER.info("Device 2.x unplugged"); StoryTellerService.this.fsDevice = null; sendDeviceUnplugged(); }); } public CompletionStage<JsonObject> deviceInfos() { if (rawDevice != null) { return rawDriver.getDeviceInfos().thenApply(this::toJson); } if (fsDevice != null) { return fsDriver.getDeviceInfos().thenApply(this::toJson); } return CompletableFuture.completedFuture(new JsonObject().put("plugged", false)); } public CompletionStage<JsonArray> packs() { if (rawDevice != null) { return rawDriver.getPacksList().thenApply( packs -> new JsonArray(packs.stream().map(this::getRawPackMetadata).collect(Collectors.toList()))); } if (fsDevice != null) { return fsDriver.getPacksList().thenApply( packs -> new JsonArray(packs.stream().map(this::getFsPackMetadata).collect(Collectors.toList()))); } return CompletableFuture.completedFuture(new JsonArray()); } public CompletionStage<Optional<String>> addPack(String uuid, Path packFile) { if (rawDevice != null) { return rawDriver.getPacksList().thenApply(packs -> upload(packs, rawDriver, uuid, packFile)); } if (fsDevice != null) { return fsDriver.getPacksList().thenApply(packs -> upload(packs, fsDriver, uuid, packFile)); } return CompletableFuture.completedFuture(Optional.empty()); } public CompletionStage<Boolean> deletePack(String uuid) { if (rawDevice != null) { return rawDriver.deletePack(uuid); } if (fsDevice != null) { return fsDriver.deletePack(uuid); } return CompletableFuture.completedFuture(false); } public CompletionStage<Boolean> reorderPacks(List<String> uuids) { if (rawDevice != null) { return rawDriver.reorderPacks(uuids); } if (fsDevice != null) { return fsDriver.reorderPacks(uuids); } return CompletableFuture.completedFuture(false); } public CompletionStage<Optional<String>> extractPack(String uuid, Path packFile) { if (rawDevice != null) { return CompletableFuture.completedFuture(download(rawDriver, uuid, packFile)); } if (fsDevice != null) { return CompletableFuture.completedFuture(download(fsDriver, uuid, packFile)); } return CompletableFuture.completedFuture(Optional.empty()); } public CompletionStage<Void> dump(Path outputPath) { if (rawDevice != null) { return rawDriver.dump(outputPath); } // unavailable for fsDevice return CompletableFuture.completedFuture(null); } private void sendDevicePlugged(JsonObject infos) { eventBus.send("storyteller.plugged", infos); } private void sendDeviceUnplugged() { eventBus.send("storyteller.unplugged", null); } private void sendFailure() { eventBus.send("storyteller.failure", null); } private void sendProgress(String id, double p) { eventBus.send("storyteller.transfer." + id + ".progress", new JsonObject().put("progress", p)); } private void sendDone(String id, boolean success) { eventBus.send("storyteller.transfer." + id + ".done", new JsonObject().put("success", success)); }
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package studio.webui.service; public class StoryTellerService implements IStoryTellerService { private static final Logger LOGGER = LogManager.getLogger(StoryTellerService.class); private final EventBus eventBus; private final DatabaseMetadataService databaseMetadataService; private RawStoryTellerAsyncDriver rawDriver; private FsStoryTellerAsyncDriver fsDriver; private Device rawDevice; private Device fsDevice; public StoryTellerService(EventBus eventBus, DatabaseMetadataService databaseMetadataService) { this.eventBus = eventBus; this.databaseMetadataService = databaseMetadataService; LOGGER.info("Setting up story teller driver"); rawDriver = new RawStoryTellerAsyncDriver(); fsDriver = new FsStoryTellerAsyncDriver(); // React when a device with firmware 1.x is plugged or unplugged rawDriver.registerDeviceListener( device -> { if (device == null) { LOGGER.error("Device 1.x plugged but got null device"); // Send 'failure' event on bus sendFailure(); } else { LOGGER.info("Device 1.x plugged"); StoryTellerService.this.rawDevice = device; CompletableFuture.runAsync(() -> rawDriver.getDeviceInfos().handle((infos, e) -> { if (e != null) { LOGGER.error("Failed to plug device 1.x", e); // Send 'failure' event on bus sendFailure(); } else { // Send 'plugged' event on bus sendDevicePlugged(toJson(infos)); } return null; })); } }, device -> { LOGGER.info("Device 1.x unplugged"); StoryTellerService.this.rawDevice = null; sendDeviceUnplugged(); }); // React when a device with firmware 2.x is plugged or unplugged fsDriver.registerDeviceListener( device -> { if (device == null) { LOGGER.error("Device 2.x plugged but got null device"); // Send 'failure' event on bus sendFailure(); } else { LOGGER.info("Device 2.x plugged"); StoryTellerService.this.fsDevice = device; CompletableFuture.runAsync(() -> fsDriver.getDeviceInfos().handle((infos, e) -> { if (e != null) { LOGGER.error("Failed to plug device 2.x", e); // Send 'failure' event on bus sendFailure(); } else { // Send 'plugged' event on bus sendDevicePlugged(toJson(infos)); } return null; })); } }, device -> { LOGGER.info("Device 2.x unplugged"); StoryTellerService.this.fsDevice = null; sendDeviceUnplugged(); }); } public CompletionStage<JsonObject> deviceInfos() { if (rawDevice != null) { return rawDriver.getDeviceInfos().thenApply(this::toJson); } if (fsDevice != null) { return fsDriver.getDeviceInfos().thenApply(this::toJson); } return CompletableFuture.completedFuture(new JsonObject().put("plugged", false)); } public CompletionStage<JsonArray> packs() { if (rawDevice != null) { return rawDriver.getPacksList().thenApply( packs -> new JsonArray(packs.stream().map(this::getRawPackMetadata).collect(Collectors.toList()))); } if (fsDevice != null) { return fsDriver.getPacksList().thenApply( packs -> new JsonArray(packs.stream().map(this::getFsPackMetadata).collect(Collectors.toList()))); } return CompletableFuture.completedFuture(new JsonArray()); } public CompletionStage<Optional<String>> addPack(String uuid, Path packFile) { if (rawDevice != null) { return rawDriver.getPacksList().thenApply(packs -> upload(packs, rawDriver, uuid, packFile)); } if (fsDevice != null) { return fsDriver.getPacksList().thenApply(packs -> upload(packs, fsDriver, uuid, packFile)); } return CompletableFuture.completedFuture(Optional.empty()); } public CompletionStage<Boolean> deletePack(String uuid) { if (rawDevice != null) { return rawDriver.deletePack(uuid); } if (fsDevice != null) { return fsDriver.deletePack(uuid); } return CompletableFuture.completedFuture(false); } public CompletionStage<Boolean> reorderPacks(List<String> uuids) { if (rawDevice != null) { return rawDriver.reorderPacks(uuids); } if (fsDevice != null) { return fsDriver.reorderPacks(uuids); } return CompletableFuture.completedFuture(false); } public CompletionStage<Optional<String>> extractPack(String uuid, Path packFile) { if (rawDevice != null) { return CompletableFuture.completedFuture(download(rawDriver, uuid, packFile)); } if (fsDevice != null) { return CompletableFuture.completedFuture(download(fsDriver, uuid, packFile)); } return CompletableFuture.completedFuture(Optional.empty()); } public CompletionStage<Void> dump(Path outputPath) { if (rawDevice != null) { return rawDriver.dump(outputPath); } // unavailable for fsDevice return CompletableFuture.completedFuture(null); } private void sendDevicePlugged(JsonObject infos) { eventBus.send("storyteller.plugged", infos); } private void sendDeviceUnplugged() { eventBus.send("storyteller.unplugged", null); } private void sendFailure() { eventBus.send("storyteller.failure", null); } private void sendProgress(String id, double p) { eventBus.send("storyteller.transfer." + id + ".progress", new JsonObject().put("progress", p)); } private void sendDone(String id, boolean success) { eventBus.send("storyteller.transfer." + id + ".done", new JsonObject().put("success", success)); }
private <T,U,V extends StoryPackInfos> Optional<String> upload(List<V> packs, StoryTellerAsyncDriver<T, U> driver, String uuid, Path packFile) {
5
2023-12-14 15:08:35+00:00
24k
conductor-oss/conductor-community
persistence/postgres-persistence/src/main/java/com/netflix/conductor/postgres/config/PostgresConfiguration.java
[ { "identifier": "PostgresExecutionDAO", "path": "persistence/postgres-persistence/src/main/java/com/netflix/conductor/postgres/dao/PostgresExecutionDAO.java", "snippet": "public class PostgresExecutionDAO extends PostgresBaseDAO\n implements ExecutionDAO, RateLimitingDAO, PollDataDAO, ConcurrentE...
import java.sql.SQLException; import java.util.Optional; import javax.annotation.PostConstruct; import javax.sql.DataSource; import org.flywaydb.core.Flyway; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.*; import org.springframework.retry.RetryContext; import org.springframework.retry.backoff.NoBackOffPolicy; import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.RetryTemplate; import com.netflix.conductor.postgres.dao.PostgresExecutionDAO; import com.netflix.conductor.postgres.dao.PostgresIndexDAO; import com.netflix.conductor.postgres.dao.PostgresMetadataDAO; import com.netflix.conductor.postgres.dao.PostgresQueueDAO; import com.fasterxml.jackson.databind.ObjectMapper;
19,862
/* * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.postgres.config; @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(PostgresProperties.class) @ConditionalOnProperty(name = "conductor.db.type", havingValue = "postgres") // Import the DataSourceAutoConfiguration when postgres database is selected. // By default, the datasource configuration is excluded in the main module. @Import(DataSourceAutoConfiguration.class) public class PostgresConfiguration { DataSource dataSource; private final PostgresProperties properties; public PostgresConfiguration(DataSource dataSource, PostgresProperties properties) { this.dataSource = dataSource; this.properties = properties; } @Bean(initMethod = "migrate") @PostConstruct public Flyway flywayForPrimaryDb() { return Flyway.configure() .locations("classpath:db/migration_postgres") .schemas(properties.getSchema()) .dataSource(dataSource) .baselineOnMigrate(true) .load(); } @Bean @DependsOn({"flywayForPrimaryDb"}) public PostgresMetadataDAO postgresMetadataDAO( @Qualifier("postgresRetryTemplate") RetryTemplate retryTemplate, ObjectMapper objectMapper, PostgresProperties properties) { return new PostgresMetadataDAO(retryTemplate, objectMapper, dataSource, properties); } @Bean @DependsOn({"flywayForPrimaryDb"}) public PostgresExecutionDAO postgresExecutionDAO( @Qualifier("postgresRetryTemplate") RetryTemplate retryTemplate, ObjectMapper objectMapper) { return new PostgresExecutionDAO(retryTemplate, objectMapper, dataSource); } @Bean @DependsOn({"flywayForPrimaryDb"})
/* * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.postgres.config; @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(PostgresProperties.class) @ConditionalOnProperty(name = "conductor.db.type", havingValue = "postgres") // Import the DataSourceAutoConfiguration when postgres database is selected. // By default, the datasource configuration is excluded in the main module. @Import(DataSourceAutoConfiguration.class) public class PostgresConfiguration { DataSource dataSource; private final PostgresProperties properties; public PostgresConfiguration(DataSource dataSource, PostgresProperties properties) { this.dataSource = dataSource; this.properties = properties; } @Bean(initMethod = "migrate") @PostConstruct public Flyway flywayForPrimaryDb() { return Flyway.configure() .locations("classpath:db/migration_postgres") .schemas(properties.getSchema()) .dataSource(dataSource) .baselineOnMigrate(true) .load(); } @Bean @DependsOn({"flywayForPrimaryDb"}) public PostgresMetadataDAO postgresMetadataDAO( @Qualifier("postgresRetryTemplate") RetryTemplate retryTemplate, ObjectMapper objectMapper, PostgresProperties properties) { return new PostgresMetadataDAO(retryTemplate, objectMapper, dataSource, properties); } @Bean @DependsOn({"flywayForPrimaryDb"}) public PostgresExecutionDAO postgresExecutionDAO( @Qualifier("postgresRetryTemplate") RetryTemplate retryTemplate, ObjectMapper objectMapper) { return new PostgresExecutionDAO(retryTemplate, objectMapper, dataSource); } @Bean @DependsOn({"flywayForPrimaryDb"})
public PostgresQueueDAO postgresQueueDAO(
3
2023-12-08 06:06:20+00:00
24k
Ispirer/COBOL-to-Java-Conversion-Samples
Java/programs/Drptab.java
[ { "identifier": "TransactionManager", "path": "IspirerFramework/com/ispirer/sw/db/TransactionManager.java", "snippet": "public class TransactionManager extends SqlCA {\r\n\tprivate static TransactionManager instance;\r\n\r\n\tprivate boolean useSqlca = false;\r\n\tprivate boolean useOraca = false;\r\n\r...
import java.sql.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ispirer.sw.db.TransactionManager; import com.ispirer.sw.exception.ExitProgram; import com.ispirer.sw.strings.AlphanumericFormat; import com.ispirer.sw.types.PictureType;
14,476
package programs; public class Drptab { private static final Logger LOGGER = LoggerFactory.getLogger(Drptab.class); private static Drptab instance; public boolean isCalled = false;
package programs; public class Drptab { private static final Logger LOGGER = LoggerFactory.getLogger(Drptab.class); private static Drptab instance; public boolean isCalled = false;
public PictureType<String> TableNm = new PictureType<>(PictureType.Type.String, new AlphanumericFormat("X(100)"));
3
2023-12-13 14:56:32+00:00
24k
lyswhut/react-native-local-media-metadata
android/src/main/java/com/localmediametadata/Metadata.java
[ { "identifier": "AudioFile", "path": "android/src/main/java/org/jaudiotagger/audio/AudioFile.java", "snippet": "public class AudioFile\n{\n //Logger\n public static Logger logger = Logger.getLogger(\"org.jaudiotagger.audio\");\n\n /**\n *\n * The physical file that this instance represe...
import android.os.Bundle; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.WritableMap; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.audio.AudioHeader; import org.jaudiotagger.tag.FieldKey; import org.jaudiotagger.tag.Tag; import org.jaudiotagger.tag.TagField; import org.jaudiotagger.tag.flac.FlacTag; import org.jaudiotagger.tag.id3.valuepair.ImageFormats; import org.jaudiotagger.tag.images.Artwork; import org.jaudiotagger.tag.images.ArtworkFactory; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream;
19,431
package com.localmediametadata; public class Metadata { private static WritableMap buildMetadata(MediaFile file, AudioHeader audioHeader, Tag tag) { WritableMap params = Arguments.createMap(); String name = tag.getFirst(FieldKey.TITLE); if ("".equals(name)) name = Utils.getName(file.getName()); params.putString("name", name); params.putString("singer", tag.getFirst(FieldKey.ARTIST).replaceAll("\\u0000", "、")); params.putString("albumName", tag.getFirst(FieldKey.ALBUM)); params.putDouble("interval", audioHeader.getTrackLength()); params.putString("bitrate", audioHeader.getBitRate()); params.putString("type", audioHeader.getEncodingType()); params.putString("ext", Utils.getFileExtension(file.getName())); params.putDouble("size", file.size()); return params; } static public WritableMap readMetadata(ReactApplicationContext context, String filePath) throws Exception { MediaFile mediaFile = new MediaFile(context, filePath); try { File file = mediaFile.getFile(false);
package com.localmediametadata; public class Metadata { private static WritableMap buildMetadata(MediaFile file, AudioHeader audioHeader, Tag tag) { WritableMap params = Arguments.createMap(); String name = tag.getFirst(FieldKey.TITLE); if ("".equals(name)) name = Utils.getName(file.getName()); params.putString("name", name); params.putString("singer", tag.getFirst(FieldKey.ARTIST).replaceAll("\\u0000", "、")); params.putString("albumName", tag.getFirst(FieldKey.ALBUM)); params.putDouble("interval", audioHeader.getTrackLength()); params.putString("bitrate", audioHeader.getBitRate()); params.putString("type", audioHeader.getEncodingType()); params.putString("ext", Utils.getFileExtension(file.getName())); params.putDouble("size", file.size()); return params; } static public WritableMap readMetadata(ReactApplicationContext context, String filePath) throws Exception { MediaFile mediaFile = new MediaFile(context, filePath); try { File file = mediaFile.getFile(false);
AudioFile audioFile = AudioFileIO.read(file);
1
2023-12-11 05:58:19+00:00
24k
xhtcode/xht-cloud-parent
xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/user/service/impl/SysUserServiceImpl.java
[ { "identifier": "PageResponse", "path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/api/response/PageResponse.java", "snippet": "@Data\n@Schema(description = \"分页信息响应实体\")\npublic class PageResponse<T> extends Response {\n\n /**\n * 当前页\n */\n @...
import cn.hutool.captcha.generator.RandomGenerator; import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.RandomUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.xht.cloud.framework.core.api.response.PageResponse; import com.xht.cloud.framework.core.constant.CommonConstants; import com.xht.cloud.framework.core.support.StringUtils; import com.xht.cloud.framework.exception.Assert; import com.xht.cloud.framework.exception.business.UserNameNotFountException; import com.xht.cloud.framework.mybatis.core.DataScopeFieldBuilder; import com.xht.cloud.framework.mybatis.core.enums.DataScopeTypeEnums; import com.xht.cloud.framework.mybatis.handler.DataScopeFactory; import com.xht.cloud.framework.mybatis.tool.PageTool; import com.xht.cloud.framework.redis.key.RedisKeyTool; import com.xht.cloud.framework.redis.service.RedisService; import com.xht.cloud.framework.security.constant.UserTypeEnums; import com.xht.cloud.framework.security.support.SecurityContextUtil; import com.xht.cloud.system.enums.MenuTypeEnums; import com.xht.cloud.system.manager.MinioManager; import com.xht.cloud.system.module.dept.controller.response.SysDeptResponse; import com.xht.cloud.system.module.dept.convert.SysDeptConvert; import com.xht.cloud.system.module.dept.dao.dataobject.SysDeptDO; import com.xht.cloud.system.module.dept.dao.mapper.SysDeptMapper; import com.xht.cloud.system.module.permissions.dao.dataobject.SysMenuDO; import com.xht.cloud.system.module.permissions.dao.dataobject.SysRoleDO; import com.xht.cloud.system.module.permissions.dao.mapper.SysMenuMapper; import com.xht.cloud.system.module.permissions.dao.mapper.SysRoleMapper; import com.xht.cloud.system.module.user.controller.request.SysUserBaseAddUpdate; import com.xht.cloud.system.module.user.controller.request.SysUserProfileRequest; import com.xht.cloud.system.module.user.controller.request.SysUserQueryRequest; import com.xht.cloud.system.module.user.controller.request.UpdatePassWordRequest; import com.xht.cloud.system.module.user.controller.response.SysUserProfileResponse; import com.xht.cloud.system.module.user.controller.response.SysUserResponse; import com.xht.cloud.system.module.user.controller.response.SysUserVo; import com.xht.cloud.system.module.user.convert.SysUserConvert; import com.xht.cloud.system.module.user.convert.SysUserProfileConvert; import com.xht.cloud.system.module.user.dao.dataobject.SysUserDO; import com.xht.cloud.system.module.user.dao.dataobject.SysUserProfileDO; import com.xht.cloud.system.module.user.dao.mapper.SysUserMapper; import com.xht.cloud.system.module.user.dao.mapper.SysUserProfileMapper; import com.xht.cloud.system.module.user.dao.wrapper.SysUserWrapper; import com.xht.cloud.system.module.user.service.ISysUserService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.NotNull; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.io.InputStream; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
18,271
package com.xht.cloud.system.module.user.service.impl; /** * 描述 :用户 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class SysUserServiceImpl implements ISysUserService { private final SysUserMapper sysUserMapper; private final SysUserProfileMapper sysUserProfileMapper; private final SysUserConvert sysUserConvert; private final SysUserProfileConvert sysUserProfileConvert; private final SysRoleMapper sysRoleMapper; private final SysMenuMapper sysMenuMapper; private final DataScopeFactory dataScopeFactory; private final PasswordEncoder passwordEncoder; private final RedisService redisService; private final SysDeptConvert sysDeptConvert; private final SysDeptMapper sysDeptMapper; private final MinioManager minioManager; /** * 创建 * * @param request {@link SysUserBaseAddUpdate} * @return {@link String} 主键 */ @Override @Transactional(rollbackFor = Exception.class) public String create(SysUserBaseAddUpdate request) { SysUserDO entity = sysUserConvert.toDO(request.getSysUser()); entity.setUserName("CS" + RandomUtil.randomNumbers(5)); String randomGenerator = new RandomGenerator(6).generate(); entity.setPassWord(passwordEncoder.encode(String.format("123456%s", randomGenerator))); entity.setPassWordSalt(randomGenerator); entity.setIsActive("1"); entity.setIsLock("1"); entity.setIsAdmin("0"); entity.setUserType("1"); entity.setRegisteredTime(LocalDateTime.now()); SysUserProfileRequest profile = request.getProfile(); if (Objects.isNull(profile)) { profile = new SysUserProfileRequest(); } SysUserProfileDO sysUserProfileDO = sysUserProfileConvert.toDO(profile); sysUserMapper.insert(entity); sysUserProfileDO.setUserId(entity.getId()); sysUserProfileMapper.insert(sysUserProfileDO); return entity.getUserName(); } /** * 根据id修改 * * @param request {@link SysUserBaseAddUpdate} */ @Override @Transactional(rollbackFor = Exception.class) public String update(SysUserBaseAddUpdate request) { String userId = request.getSysUser().getId(); SysUserDO sysUserDO = sysUserMapper.selectOne(SysUserDO::getId, userId).orElse(null); if (Objects.isNull(sysUserDO)) { Assert.fail("修改的对象不存在"); } SysUserProfileDO sysUserProfileDO = sysUserProfileConvert.toDO(request.getProfile()); sysUserProfileDO.setUserId(userId); SysUserProfileDO dbSysUserProfileDO = sysUserProfileMapper.selectOne(SysUserProfileDO::getUserId, userId).orElse(null); if (Objects.nonNull(dbSysUserProfileDO)) { sysUserProfileDO.setId(dbSysUserProfileDO.getId()); sysUserProfileMapper.updateById(sysUserProfileDO); } else { sysUserProfileMapper.insert(sysUserProfileDO); }
package com.xht.cloud.system.module.user.service.impl; /** * 描述 :用户 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class SysUserServiceImpl implements ISysUserService { private final SysUserMapper sysUserMapper; private final SysUserProfileMapper sysUserProfileMapper; private final SysUserConvert sysUserConvert; private final SysUserProfileConvert sysUserProfileConvert; private final SysRoleMapper sysRoleMapper; private final SysMenuMapper sysMenuMapper; private final DataScopeFactory dataScopeFactory; private final PasswordEncoder passwordEncoder; private final RedisService redisService; private final SysDeptConvert sysDeptConvert; private final SysDeptMapper sysDeptMapper; private final MinioManager minioManager; /** * 创建 * * @param request {@link SysUserBaseAddUpdate} * @return {@link String} 主键 */ @Override @Transactional(rollbackFor = Exception.class) public String create(SysUserBaseAddUpdate request) { SysUserDO entity = sysUserConvert.toDO(request.getSysUser()); entity.setUserName("CS" + RandomUtil.randomNumbers(5)); String randomGenerator = new RandomGenerator(6).generate(); entity.setPassWord(passwordEncoder.encode(String.format("123456%s", randomGenerator))); entity.setPassWordSalt(randomGenerator); entity.setIsActive("1"); entity.setIsLock("1"); entity.setIsAdmin("0"); entity.setUserType("1"); entity.setRegisteredTime(LocalDateTime.now()); SysUserProfileRequest profile = request.getProfile(); if (Objects.isNull(profile)) { profile = new SysUserProfileRequest(); } SysUserProfileDO sysUserProfileDO = sysUserProfileConvert.toDO(profile); sysUserMapper.insert(entity); sysUserProfileDO.setUserId(entity.getId()); sysUserProfileMapper.insert(sysUserProfileDO); return entity.getUserName(); } /** * 根据id修改 * * @param request {@link SysUserBaseAddUpdate} */ @Override @Transactional(rollbackFor = Exception.class) public String update(SysUserBaseAddUpdate request) { String userId = request.getSysUser().getId(); SysUserDO sysUserDO = sysUserMapper.selectOne(SysUserDO::getId, userId).orElse(null); if (Objects.isNull(sysUserDO)) { Assert.fail("修改的对象不存在"); } SysUserProfileDO sysUserProfileDO = sysUserProfileConvert.toDO(request.getProfile()); sysUserProfileDO.setUserId(userId); SysUserProfileDO dbSysUserProfileDO = sysUserProfileMapper.selectOne(SysUserProfileDO::getUserId, userId).orElse(null); if (Objects.nonNull(dbSysUserProfileDO)) { sysUserProfileDO.setId(dbSysUserProfileDO.getId()); sysUserProfileMapper.updateById(sysUserProfileDO); } else { sysUserProfileMapper.insert(sysUserProfileDO); }
redisService.delete(RedisKeyTool.createNameTemplate("user:profile:info:{}", sysUserDO.getUserName()));
9
2023-12-12 08:16:30+00:00
24k
serendipitk/LunarCore
src/main/java/emu/lunarcore/server/packet/recv/HandlerLeaveChallengeCsReq.java
[ { "identifier": "GameConstants", "path": "src/main/java/emu/lunarcore/GameConstants.java", "snippet": "public class GameConstants {\n public static String VERSION = \"1.6.0\";\n \n public static final ZoneOffset CURRENT_ZONEOFFSET = ZoneOffset.systemDefault().getRules().getOffset(Instant.now())...
import emu.lunarcore.GameConstants; import emu.lunarcore.game.enums.PlaneType; import emu.lunarcore.server.game.GameSession; import emu.lunarcore.server.packet.CmdId; import emu.lunarcore.server.packet.Opcodes; import emu.lunarcore.server.packet.PacketHandler;
20,835
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.LeaveChallengeCsReq) public class HandlerLeaveChallengeCsReq extends PacketHandler { @Override
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.LeaveChallengeCsReq) public class HandlerLeaveChallengeCsReq extends PacketHandler { @Override
public void handle(GameSession session, byte[] data) throws Exception {
2
2023-12-08 14:13:04+00:00
24k
mklemmingen/senet-boom
core/src/com/senetboom/game/frontend/stages/GameStage.java
[ { "identifier": "SenetBoom", "path": "core/src/com/senetboom/game/SenetBoom.java", "snippet": "public class SenetBoom extends ApplicationAdapter {\n\n\t// for the stage the bot moves a piece on\n\tpublic static Group botMovingStage;\n\n\t// for the empty tile texture\n\tpublic static Texture emptyTextur...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.senetboom.game.SenetBoom; import com.senetboom.game.backend.Board; import com.senetboom.game.backend.Coordinate; import com.senetboom.game.backend.Piece; import com.senetboom.game.backend.Tile; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Stack; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.utils.DragListener; import static com.senetboom.game.SenetBoom.*; import static com.senetboom.game.backend.Board.getBoard; import static com.senetboom.game.backend.Board.setAllowedTile;
18,635
package com.senetboom.game.frontend.stages; public class GameStage { public static Stage drawMap() { Stage stage = new Stage(); // create a root table for the tiles Table root = new Table(); root.setFillParent(true); // iterate through the board, at each tile
package com.senetboom.game.frontend.stages; public class GameStage { public static Stage drawMap() { Stage stage = new Stage(); // create a root table for the tiles Table root = new Table(); root.setFillParent(true); // iterate through the board, at each tile
final Tile[] board = getBoard();
4
2023-12-05 22:19:00+00:00
24k
sinbad-navigator/erp-crm
system/src/main/java/com/ec/sys/service/impl/SysUserServiceImpl.java
[ { "identifier": "BeanValidators", "path": "common/src/main/java/com/ec/common/utils/bean/BeanValidators.java", "snippet": "public class BeanValidators {\n public static void validateWithException(Validator validator, Object object, Class<?>... groups)\n throws ConstraintViolationException ...
import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import javax.validation.Validator; import com.ec.common.utils.bean.BeanValidators; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import com.ec.common.annotation.DataScope; import com.ec.common.constant.UserConstants; import com.ec.common.core.domain.entity.SysRole; import com.ec.common.core.domain.entity.SysUser; import com.ec.common.exception.ServiceException; import com.ec.common.utils.SecurityUtils; import com.ec.common.utils.StringUtils; import com.ec.common.utils.spring.SpringUtils; import com.ec.sys.domain.SysPost; import com.ec.sys.domain.SysUserPost; import com.ec.sys.domain.SysUserRole; import com.ec.sys.mapper.SysPostMapper; import com.ec.sys.mapper.SysRoleMapper; import com.ec.sys.mapper.SysUserMapper; import com.ec.sys.mapper.SysUserPostMapper; import com.ec.sys.mapper.SysUserRoleMapper; import com.ec.sys.service.ISysConfigService; import com.ec.sys.service.ISysUserService;
16,053
package com.ec.sys.service.impl; /** * 用户 业务层处理 * * @author ec */ @Service public class SysUserServiceImpl implements ISysUserService { private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class); @Autowired protected Validator validator; @Autowired private SysUserMapper userMapper; @Autowired private SysRoleMapper roleMapper; @Autowired private SysPostMapper postMapper; @Autowired private SysUserRoleMapper userRoleMapper; @Autowired private SysUserPostMapper userPostMapper; @Autowired
package com.ec.sys.service.impl; /** * 用户 业务层处理 * * @author ec */ @Service public class SysUserServiceImpl implements ISysUserService { private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class); @Autowired protected Validator validator; @Autowired private SysUserMapper userMapper; @Autowired private SysRoleMapper roleMapper; @Autowired private SysPostMapper postMapper; @Autowired private SysUserRoleMapper userRoleMapper; @Autowired private SysUserPostMapper userPostMapper; @Autowired
private ISysConfigService configService;
16
2023-12-07 14:23:12+00:00
24k
Crydsch/the-one
src/movement/ExternalPathMovement.java
[ { "identifier": "ExternalPathMovementReader", "path": "src/input/ExternalPathMovementReader.java", "snippet": "public class ExternalPathMovementReader {\n\t // Singletons are evil, but I'm lazy\n\tprivate static Map<String, ExternalPathMovementReader> singletons =\n\t\tnew HashMap<String, ExternalPathMo...
import input.ExternalPathMovementReader; import java.util.List; import core.Coord; import core.DTNHost; import core.Settings; import core.SimClock;
17,001
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package movement; /** * External movement trace reader for traces that are in path format. * See <code>ExternalPathMovementReader</code> for details. * * @author teemuk * */ public class ExternalPathMovement extends MovementModel { /** external locations file's path -setting id ({@value})*/ public static final String MOVEMENT_FILE_S = "traceFile"; /** activity file's path -setting id ({@value})*/ public static final String ACTIVITY_FILE_S = "activeFile"; // Settings private String traceFile; private String activeFile; // Node's paths private List<List<ExternalPathMovementReader.Entry>> paths; private int curPath=0; private List<ExternalPathMovementReader.ActiveTime> active; public ExternalPathMovement(Settings settings) { this.traceFile = settings.getSetting(MOVEMENT_FILE_S); this.activeFile = settings.getSetting(ACTIVITY_FILE_S); } /** * Copy-constructor. * * @param mm */ public ExternalPathMovement(ExternalPathMovement mm) { this.traceFile = mm.traceFile; this.activeFile = mm.activeFile; } /** * Initializes the movement model. Uses a reader to get the paths for this * host. */ private void init() { // Get paths for this node ExternalPathMovementReader reader = ExternalPathMovementReader.getInstance(this.traceFile, this.activeFile); this.paths = reader.getPaths(getHost().getID()); this.active = reader.getActive(getHost().getID()); } @Override public void setHost(DTNHost host) { super.setHost(host); this.init(); // Can only initialize after the host has been set } @Override public boolean isActive() { double t = SimClock.getTime(); // Check whether the current time falls in one of the active periods for (ExternalPathMovementReader.ActiveTime a : this.active) { if (t >= a.start && t <= a.end) return true; } return false; } @Override public Path getPath() { // Make sure to not give out paths when the node is not active if (!this.isActive()) { return null; } // Check whether we're moving or waiting for the next path to start double t = SimClock.getTime(); if (t < this.paths.get(this.curPath).get(0).time) { return null; } // Get the path List<ExternalPathMovementReader.Entry> path = this.paths.get(this.curPath); this.curPath++; // Drop the node to the the beginning of the new path in case the // previous path ended somewhere else.
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package movement; /** * External movement trace reader for traces that are in path format. * See <code>ExternalPathMovementReader</code> for details. * * @author teemuk * */ public class ExternalPathMovement extends MovementModel { /** external locations file's path -setting id ({@value})*/ public static final String MOVEMENT_FILE_S = "traceFile"; /** activity file's path -setting id ({@value})*/ public static final String ACTIVITY_FILE_S = "activeFile"; // Settings private String traceFile; private String activeFile; // Node's paths private List<List<ExternalPathMovementReader.Entry>> paths; private int curPath=0; private List<ExternalPathMovementReader.ActiveTime> active; public ExternalPathMovement(Settings settings) { this.traceFile = settings.getSetting(MOVEMENT_FILE_S); this.activeFile = settings.getSetting(ACTIVITY_FILE_S); } /** * Copy-constructor. * * @param mm */ public ExternalPathMovement(ExternalPathMovement mm) { this.traceFile = mm.traceFile; this.activeFile = mm.activeFile; } /** * Initializes the movement model. Uses a reader to get the paths for this * host. */ private void init() { // Get paths for this node ExternalPathMovementReader reader = ExternalPathMovementReader.getInstance(this.traceFile, this.activeFile); this.paths = reader.getPaths(getHost().getID()); this.active = reader.getActive(getHost().getID()); } @Override public void setHost(DTNHost host) { super.setHost(host); this.init(); // Can only initialize after the host has been set } @Override public boolean isActive() { double t = SimClock.getTime(); // Check whether the current time falls in one of the active periods for (ExternalPathMovementReader.ActiveTime a : this.active) { if (t >= a.start && t <= a.end) return true; } return false; } @Override public Path getPath() { // Make sure to not give out paths when the node is not active if (!this.isActive()) { return null; } // Check whether we're moving or waiting for the next path to start double t = SimClock.getTime(); if (t < this.paths.get(this.curPath).get(0).time) { return null; } // Get the path List<ExternalPathMovementReader.Entry> path = this.paths.get(this.curPath); this.curPath++; // Drop the node to the the beginning of the new path in case the // previous path ended somewhere else.
Coord curPos = super.getHost().getLocation();
1
2023-12-10 15:51:41+00:00
24k
seleuco/MAME4droid-2024
android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/input/TouchController.java
[ { "identifier": "Emulator", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/Emulator.java", "snippet": "public class Emulator {\n\n\t//gets\n\tfinal static public int IN_MENU = 1;\n\tfinal static public int IN_GAME = 2;\n\tfinal static public int NUMBTNS = 3;\n\tfinal static public ...
import android.content.Context; import android.content.res.Configuration; import android.graphics.Rect; import android.os.Vibrator; import android.view.MotionEvent; import com.seleuco.mame4droid.Emulator; import com.seleuco.mame4droid.MAME4droid; import com.seleuco.mame4droid.helpers.DialogHelper; import com.seleuco.mame4droid.helpers.PrefsHelper; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer;
18,456
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid.input; public class TouchController implements IController { static final int MAX_FINGERS = 20; final byte vibrate_time = 1;//16; protected static int[] newtouches = new int[MAX_FINGERS]; protected static int[] oldtouches = new int[MAX_FINGERS]; protected static boolean[] touchstates = new boolean[MAX_FINGERS]; final public static int TYPE_MAIN_RECT = 1; final public static int TYPE_STICK_RECT = 2; final public static int TYPE_BUTTON_RECT = 3; final public static int TYPE_STICK_IMG = 4; final public static int TYPE_BUTTON_IMG = 5; final public static int TYPE_SWITCH = 6; final public static int TYPE_OPACITY = 7; final public static int TYPE_ANALOG_RECT = 8; final public static int STATE_SHOWING_CONTROLLER = 1; final public static int STATE_SHOWING_NONE = 3; protected int state = STATE_SHOWING_CONTROLLER; public int getState() { return state; } protected int stick_state; public int getStick_state() { return stick_state; } protected int old_stick_state; protected int[] btnStates = new int[NUM_BUTTONS]; public int[] getBtnStates() { return btnStates; } protected int[] old_btnStates = new int[NUM_BUTTONS]; protected int ax = 0; protected int ay = 0; protected float dx = 1; protected float dy = 1; protected ArrayList<InputValue> values = new ArrayList<>();
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid.input; public class TouchController implements IController { static final int MAX_FINGERS = 20; final byte vibrate_time = 1;//16; protected static int[] newtouches = new int[MAX_FINGERS]; protected static int[] oldtouches = new int[MAX_FINGERS]; protected static boolean[] touchstates = new boolean[MAX_FINGERS]; final public static int TYPE_MAIN_RECT = 1; final public static int TYPE_STICK_RECT = 2; final public static int TYPE_BUTTON_RECT = 3; final public static int TYPE_STICK_IMG = 4; final public static int TYPE_BUTTON_IMG = 5; final public static int TYPE_SWITCH = 6; final public static int TYPE_OPACITY = 7; final public static int TYPE_ANALOG_RECT = 8; final public static int STATE_SHOWING_CONTROLLER = 1; final public static int STATE_SHOWING_NONE = 3; protected int state = STATE_SHOWING_CONTROLLER; public int getState() { return state; } protected int stick_state; public int getStick_state() { return stick_state; } protected int old_stick_state; protected int[] btnStates = new int[NUM_BUTTONS]; public int[] getBtnStates() { return btnStates; } protected int[] old_btnStates = new int[NUM_BUTTONS]; protected int ax = 0; protected int ay = 0; protected float dx = 1; protected float dy = 1; protected ArrayList<InputValue> values = new ArrayList<>();
MAME4droid mm = null;
1
2023-12-18 11:16:18+00:00
24k
Swofty-Developments/HypixelSkyBlock
generic/src/main/java/net/swofty/types/generic/gui/inventory/inventories/coop/GUICoopInviteTarget.java
[ { "identifier": "DataHandler", "path": "generic/src/main/java/net/swofty/types/generic/data/DataHandler.java", "snippet": "public class DataHandler {\n public static Map<UUID, DataHandler> userCache = new HashMap<>();\n @Getter\n private UUID uuid;\n private final Map<String, Datapoint> data...
import net.minestom.server.MinecraftServer; import net.minestom.server.entity.PlayerSkin; import net.minestom.server.event.inventory.InventoryCloseEvent; import net.minestom.server.event.inventory.InventoryPreClickEvent; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryType; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import net.minestom.server.timer.TaskSchedule; import net.swofty.types.generic.SkyBlockGenericLoader; import net.swofty.types.generic.data.DataHandler; import net.swofty.types.generic.data.datapoints.DatapointBoolean; import net.swofty.types.generic.data.datapoints.DatapointString; import net.swofty.types.generic.data.datapoints.DatapointUUID; import net.swofty.types.generic.data.mongodb.CoopDatabase; import net.swofty.types.generic.data.mongodb.ProfilesDatabase; import net.swofty.types.generic.data.mongodb.UserDatabase; import net.swofty.types.generic.gui.inventory.ItemStackCreator; import net.swofty.types.generic.gui.inventory.SkyBlockInventoryGUI; import net.swofty.types.generic.gui.inventory.item.GUIClickableItem; import net.swofty.types.generic.gui.inventory.item.GUIItem; import net.swofty.types.generic.user.SkyBlockPlayer; import net.swofty.types.generic.user.UserProfiles; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID;
15,514
package net.swofty.types.generic.gui.inventory.inventories.coop; public class GUICoopInviteTarget extends SkyBlockInventoryGUI { private static final Map<Integer, List<Integer>> SLOTS_MAP = new HashMap<>( Map.of( 1, List.of(13), 2, List.of(12, 14), 3, List.of(11, 13, 15), 4, List.of(10, 12, 14, 16), 5, List.of(11, 12, 13, 14, 15) ) ); public GUICoopInviteTarget(CoopDatabase.Coop coop) { super("Co-op Invitation", InventoryType.CHEST_5_ROW); fill(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE)); int amountInProfile = coop.memberInvites().size() + coop.members().size(); int[] slots = SLOTS_MAP.get(amountInProfile).stream().mapToInt(Integer::intValue).toArray(); // Put everyone who is a member as TRUE and ones only invited as FALSE Map<UUID, Boolean> invites = new HashMap<>(); coop.members().forEach(uuid -> invites.put(uuid, true)); coop.memberInvites().forEach(uuid -> invites.put(uuid, false)); // Remove originator invites.remove(coop.originator()); set(new GUIItem(slots[0]) { @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return ItemStackCreator.getStackHead( SkyBlockPlayer.getDisplayName(coop.originator()), PlayerSkin.fromUuid(String.valueOf(coop.originator())), 1, " ", "§bCreated the invite!" ); } }); for (int i = 0; i < invites.size(); i++) { UUID target = (UUID) invites.keySet().toArray()[i]; boolean accepted = invites.get(target); String displayName = SkyBlockPlayer.getDisplayName(target); int finalI = i; set(new GUIItem(slots[finalI + 1]) { @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return ItemStackCreator.getStackHead( displayName, PlayerSkin.fromUuid(String.valueOf(target)), 1, " ", "§7Accepted: " + (accepted ? "§aYes" : "§cNot yet") ); } }); } set(new GUIClickableItem(33) { @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { coop.removeInvite(player.getUuid()); coop.save(); player.sendMessage("§b[Co-op] §eYou have denied the co-op invite!"); player.closeInventory(); SkyBlockPlayer target = SkyBlockGenericLoader.getLoadedPlayers().stream().filter(player1 -> player1.getUuid().equals(coop.originator())).findFirst().orElse(null); if (target != null && (coop.memberInvites().contains(target.getUuid()) || coop.members().contains(target.getUuid()))) target.sendMessage("§b[Co-op] §e" + player.getUsername() + " §chas denied your co-op invite!"); } @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return ItemStackCreator.getStack("§cDeny Invite", Material.BARRIER, (short) 0, 1); } }); set(new GUIClickableItem(29) { @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { coop.memberInvites().remove(player.getUuid()); coop.members().add(player.getUuid()); coop.save(); UUID profileId = UUID.randomUUID(); DataHandler handler = DataHandler.initUserWithDefaultData(player.getUuid()); handler.get(DataHandler.Data.IS_COOP, DatapointBoolean.class).setValue(true); if (coop.memberProfiles().isEmpty()) {
package net.swofty.types.generic.gui.inventory.inventories.coop; public class GUICoopInviteTarget extends SkyBlockInventoryGUI { private static final Map<Integer, List<Integer>> SLOTS_MAP = new HashMap<>( Map.of( 1, List.of(13), 2, List.of(12, 14), 3, List.of(11, 13, 15), 4, List.of(10, 12, 14, 16), 5, List.of(11, 12, 13, 14, 15) ) ); public GUICoopInviteTarget(CoopDatabase.Coop coop) { super("Co-op Invitation", InventoryType.CHEST_5_ROW); fill(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE)); int amountInProfile = coop.memberInvites().size() + coop.members().size(); int[] slots = SLOTS_MAP.get(amountInProfile).stream().mapToInt(Integer::intValue).toArray(); // Put everyone who is a member as TRUE and ones only invited as FALSE Map<UUID, Boolean> invites = new HashMap<>(); coop.members().forEach(uuid -> invites.put(uuid, true)); coop.memberInvites().forEach(uuid -> invites.put(uuid, false)); // Remove originator invites.remove(coop.originator()); set(new GUIItem(slots[0]) { @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return ItemStackCreator.getStackHead( SkyBlockPlayer.getDisplayName(coop.originator()), PlayerSkin.fromUuid(String.valueOf(coop.originator())), 1, " ", "§bCreated the invite!" ); } }); for (int i = 0; i < invites.size(); i++) { UUID target = (UUID) invites.keySet().toArray()[i]; boolean accepted = invites.get(target); String displayName = SkyBlockPlayer.getDisplayName(target); int finalI = i; set(new GUIItem(slots[finalI + 1]) { @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return ItemStackCreator.getStackHead( displayName, PlayerSkin.fromUuid(String.valueOf(target)), 1, " ", "§7Accepted: " + (accepted ? "§aYes" : "§cNot yet") ); } }); } set(new GUIClickableItem(33) { @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { coop.removeInvite(player.getUuid()); coop.save(); player.sendMessage("§b[Co-op] §eYou have denied the co-op invite!"); player.closeInventory(); SkyBlockPlayer target = SkyBlockGenericLoader.getLoadedPlayers().stream().filter(player1 -> player1.getUuid().equals(coop.originator())).findFirst().orElse(null); if (target != null && (coop.memberInvites().contains(target.getUuid()) || coop.members().contains(target.getUuid()))) target.sendMessage("§b[Co-op] §e" + player.getUsername() + " §chas denied your co-op invite!"); } @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return ItemStackCreator.getStack("§cDeny Invite", Material.BARRIER, (short) 0, 1); } }); set(new GUIClickableItem(29) { @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { coop.memberInvites().remove(player.getUuid()); coop.members().add(player.getUuid()); coop.save(); UUID profileId = UUID.randomUUID(); DataHandler handler = DataHandler.initUserWithDefaultData(player.getUuid()); handler.get(DataHandler.Data.IS_COOP, DatapointBoolean.class).setValue(true); if (coop.memberProfiles().isEmpty()) {
handler.get(DataHandler.Data.ISLAND_UUID, DatapointUUID.class).setValue(UUID.randomUUID());
3
2023-12-14 09:51:15+00:00
24k
Tianscar/uxgl
base/src/main/java/unrefined/io/BinaryInputStream.java
[ { "identifier": "FastMath", "path": "base/src/main/java/unrefined/math/FastMath.java", "snippet": "public final class FastMath {\n\n private FastMath() {\n throw new NotInstantiableError(FastMath.class);\n }\n\n public static final double E = Math.E;\n public static final double PI = ...
import unrefined.math.FastMath; import unrefined.util.function.BiSlot; import unrefined.util.function.FunctionTargetException; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger;
16,725
package unrefined.io; public class BinaryInputStream extends DataInputStream implements BinaryInput { public BinaryInputStream(InputStream in) { super(in); } @Override public void readPortable(Portable obj) throws IOException { obj.readPortable(this); } @Override public <T> void readObject(T obj, BiSlot<T, BinaryInput> readProc) throws IOException { try { readProc.accept(obj, this); }
package unrefined.io; public class BinaryInputStream extends DataInputStream implements BinaryInput { public BinaryInputStream(InputStream in) { super(in); } @Override public void readPortable(Portable obj) throws IOException { obj.readPortable(this); } @Override public <T> void readObject(T obj, BiSlot<T, BinaryInput> readProc) throws IOException { try { readProc.accept(obj, this); }
catch (FunctionTargetException e) {
2
2023-12-15 19:03:31+00:00
24k
litongjava/next-jfinal
src/main/java/com/litongjava/tio/boot/context/TioApplicationContext.java
[ { "identifier": "Aop", "path": "src/main/java/com/jfinal/aop/Aop.java", "snippet": "public class Aop {\n\n static AopFactory aopFactory = new AopFactory();\n\n public static <T> T get(Class<T> targetClass) {\n return aopFactory.get(targetClass);\n }\n\n /**\n * 如果需要被注入的成员是一个接口类,从mapping中查找实现类,找...
import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.concurrent.ThreadPoolExecutor; import com.jfinal.aop.Aop; import com.jfinal.aop.AopManager; import com.jfinal.aop.annotation.Import; import com.litongjava.tio.boot.constatns.ConfigKeys; import com.litongjava.tio.boot.http.handler.DefaultHttpRequestHandler; import com.litongjava.tio.boot.http.handler.JFinalAopControllerFactory; import com.litongjava.tio.boot.http.handler.TioBootHttpRoutes; import com.litongjava.tio.boot.http.interceptor.DefaultHttpServerInterceptor; import com.litongjava.tio.boot.server.TioBootServer; import com.litongjava.tio.boot.server.TioBootServerHandler; import com.litongjava.tio.boot.server.TioBootServerHandlerListener; import com.litongjava.tio.boot.server.TioBootServerListener; import com.litongjava.tio.boot.tcp.ServerHanlderListener; import com.litongjava.tio.boot.tcp.ServerTcpHandler; import com.litongjava.tio.boot.websocket.handler.DefaultWebSocketHandler; import com.litongjava.tio.http.common.HttpConfig; import com.litongjava.tio.http.common.TioConfigKey; import com.litongjava.tio.http.common.handler.HttpRequestHandler; import com.litongjava.tio.http.common.session.id.impl.UUIDSessionIdGenerator; import com.litongjava.tio.http.server.mvc.intf.ControllerFactory; import com.litongjava.tio.server.ServerTioConfig; import com.litongjava.tio.server.TioServer; import com.litongjava.tio.server.intf.ServerAioListener; import com.litongjava.tio.utils.Threads; import com.litongjava.tio.utils.cache.caffeine.CaffeineCache; import com.litongjava.tio.utils.enviorment.EnviormentUtils; import com.litongjava.tio.utils.enviorment.PropUtils; import com.litongjava.tio.utils.thread.pool.SynThreadPoolExecutor; import com.litongjava.tio.websocket.common.WsTioUuid; import com.litongjava.tio.websocket.server.WsServerConfig; import cn.hutool.core.io.resource.ResourceUtil; import lombok.extern.slf4j.Slf4j;
19,703
package com.litongjava.tio.boot.context; @Slf4j public class TioApplicationContext implements Context { private TioBootServer tioBootServer; private StartupCallback beforeStart; private StartedCallBack afterStarted; private ShutdownCallback beforeStop; private ShutCallback afterStoped; /** * 1.服务启动前配置 * 2.启动服务器 * 3.初始配置类 * 4.初始化组件类 * 5.添加路由 */ @Override public Context run(Class<?>[] primarySources, String[] args) { long scanClassStartTime = System.currentTimeMillis(); long serverStartTime = System.currentTimeMillis(); EnviormentUtils.buildCmdArgsMap(args); String env = EnviormentUtils.get("app.env"); if (ResourceUtil.getResource(ConfigKeys.defaultConfigFileName) != null) { PropUtils.use(ConfigKeys.defaultConfigFileName, env); } else { if (env != null) { PropUtils.use("app-" + env + ".properties"); } } List<Class<?>> scannedClasses = null; // 执行组件扫描 try { scannedClasses = Aop.scan(primarySources); } catch (Exception e1) { e1.printStackTrace(); } // 添加@Improt的类 for (Class<?> primarySource : primarySources) { Import importAnnotaion = primarySource.getAnnotation(Import.class); if (importAnnotaion != null) { Class<?>[] value = importAnnotaion.value(); for (Class<?> clazzz : value) { scannedClasses.add(clazzz); } } } scannedClasses = this.processBeforeStartConfiguration(scannedClasses); long scanClassEndTime = System.currentTimeMillis(); TioBootServerListener serverListener = AopManager.me().getAopFactory().getOnly(TioBootServerListener.class); if (serverListener != null) { serverListener.boforeStart(primarySources, args); } // 启动端口 int port = EnviormentUtils.getInt(ConfigKeys.serverPort, 80); String contextPath = EnviormentUtils.get(ConfigKeys.serverContextPath); HttpConfig httpConfig = configHttp(port, contextPath); httpConfig.setBindIp(EnviormentUtils.get(ConfigKeys.serverAddress)); // 第二个参数也可以是数组,自动考试扫描handler的路径 HttpRequestHandler requestHandler = null; DefaultHttpRequestHandler defaultHttpRequestHandler = null;
package com.litongjava.tio.boot.context; @Slf4j public class TioApplicationContext implements Context { private TioBootServer tioBootServer; private StartupCallback beforeStart; private StartedCallBack afterStarted; private ShutdownCallback beforeStop; private ShutCallback afterStoped; /** * 1.服务启动前配置 * 2.启动服务器 * 3.初始配置类 * 4.初始化组件类 * 5.添加路由 */ @Override public Context run(Class<?>[] primarySources, String[] args) { long scanClassStartTime = System.currentTimeMillis(); long serverStartTime = System.currentTimeMillis(); EnviormentUtils.buildCmdArgsMap(args); String env = EnviormentUtils.get("app.env"); if (ResourceUtil.getResource(ConfigKeys.defaultConfigFileName) != null) { PropUtils.use(ConfigKeys.defaultConfigFileName, env); } else { if (env != null) { PropUtils.use("app-" + env + ".properties"); } } List<Class<?>> scannedClasses = null; // 执行组件扫描 try { scannedClasses = Aop.scan(primarySources); } catch (Exception e1) { e1.printStackTrace(); } // 添加@Improt的类 for (Class<?> primarySource : primarySources) { Import importAnnotaion = primarySource.getAnnotation(Import.class); if (importAnnotaion != null) { Class<?>[] value = importAnnotaion.value(); for (Class<?> clazzz : value) { scannedClasses.add(clazzz); } } } scannedClasses = this.processBeforeStartConfiguration(scannedClasses); long scanClassEndTime = System.currentTimeMillis(); TioBootServerListener serverListener = AopManager.me().getAopFactory().getOnly(TioBootServerListener.class); if (serverListener != null) { serverListener.boforeStart(primarySources, args); } // 启动端口 int port = EnviormentUtils.getInt(ConfigKeys.serverPort, 80); String contextPath = EnviormentUtils.get(ConfigKeys.serverContextPath); HttpConfig httpConfig = configHttp(port, contextPath); httpConfig.setBindIp(EnviormentUtils.get(ConfigKeys.serverAddress)); // 第二个参数也可以是数组,自动考试扫描handler的路径 HttpRequestHandler requestHandler = null; DefaultHttpRequestHandler defaultHttpRequestHandler = null;
TioBootHttpRoutes routes = null;
5
2023-12-19 10:58:33+00:00
24k
HypixelSkyblockmod/ChromaHud
src/java/xyz/apfelmus/cheeto/client/clickgui/ConfigLabel.java
[ { "identifier": "ConfigGUI", "path": "src/java/xyz/apfelmus/cheeto/client/clickgui/ConfigGUI.java", "snippet": "@Metadata(mv={1, 6, 0}, k=1, xi=48, d1={\"\\u0000X\\n\\u0002\\u0018\\u0002\\n\\u0002\\u0018\\u0002\\n\\u0002\\b\\u0002\\n\\u0002\\u0018\\u0002\\n\\u0002\\b\\b\\n\\u0002\\u0018\\u0002\\n\\u0002...
import gg.essential.elementa.UIComponent; import gg.essential.elementa.UIConstraints; import gg.essential.elementa.components.UIContainer; import gg.essential.elementa.components.UIText; import gg.essential.elementa.constraints.CenterConstraint; import gg.essential.elementa.constraints.ChildBasedMaxSizeConstraint; import gg.essential.elementa.constraints.ColorConstraint; import gg.essential.elementa.constraints.HeightConstraint; import gg.essential.elementa.constraints.SiblingConstraint; import gg.essential.elementa.constraints.WidthConstraint; import gg.essential.elementa.constraints.XConstraint; import gg.essential.elementa.constraints.YConstraint; import gg.essential.elementa.constraints.animation.AnimatingConstraints; import gg.essential.elementa.constraints.animation.AnimationStrategy; import gg.essential.elementa.constraints.animation.Animations; import gg.essential.elementa.dsl.ComponentsKt; import gg.essential.elementa.dsl.UtilitiesKt; import gg.essential.elementa.events.UIClickEvent; import gg.essential.elementa.font.DefaultFonts; import gg.essential.universal.USound; import java.awt.Color; import kotlin.Metadata; import kotlin.Unit; import kotlin.jvm.functions.Function1; import kotlin.jvm.functions.Function2; import kotlin.jvm.internal.Intrinsics; import kotlin.jvm.internal.PropertyReference1; import kotlin.jvm.internal.PropertyReference1Impl; import kotlin.jvm.internal.Reflection; import kotlin.properties.ReadWriteProperty; import kotlin.reflect.KProperty; import org.jetbrains.annotations.NotNull; import xyz.apfelmus.cheeto.client.clickgui.ConfigGUI; import xyz.apfelmus.cheeto.client.utils.client.ColorUtils;
16,198
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * gg.essential.elementa.UIComponent * gg.essential.elementa.UIConstraints * gg.essential.elementa.components.UIContainer * gg.essential.elementa.components.UIText * gg.essential.elementa.constraints.CenterConstraint * gg.essential.elementa.constraints.ChildBasedMaxSizeConstraint * gg.essential.elementa.constraints.ColorConstraint * gg.essential.elementa.constraints.HeightConstraint * gg.essential.elementa.constraints.SiblingConstraint * gg.essential.elementa.constraints.WidthConstraint * gg.essential.elementa.constraints.XConstraint * gg.essential.elementa.constraints.YConstraint * gg.essential.elementa.constraints.animation.AnimatingConstraints * gg.essential.elementa.constraints.animation.AnimationStrategy * gg.essential.elementa.constraints.animation.Animations * gg.essential.elementa.dsl.ComponentsKt * gg.essential.elementa.dsl.UtilitiesKt * gg.essential.elementa.events.UIClickEvent * gg.essential.elementa.font.DefaultFonts * gg.essential.universal.USound * kotlin.Metadata * kotlin.Unit * kotlin.jvm.functions.Function1 * kotlin.jvm.functions.Function2 * kotlin.jvm.internal.Intrinsics * kotlin.jvm.internal.PropertyReference1 * kotlin.jvm.internal.PropertyReference1Impl * kotlin.jvm.internal.Reflection * kotlin.properties.ReadWriteProperty * kotlin.reflect.KProperty * org.jetbrains.annotations.NotNull */ package xyz.apfelmus.cheeto.client.clickgui; @Metadata(mv={1, 6, 0}, k=1, xi=48, d1={"\u00000\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u000e\n\u0002\b\u0002\n\u0002\u0010\u000b\n\u0002\b\u0004\n\u0002\u0018\u0002\n\u0002\b\u0005\n\u0002\u0010\u0002\n\u0002\b\u0002\u0018\u00002\u00020\u0001B\u0015\u0012\u0006\u0010\u0002\u001a\u00020\u0003\u0012\u0006\u0010\u0004\u001a\u00020\u0005\u00a2\u0006\u0002\u0010\u0006J\u0006\u0010\u0012\u001a\u00020\u0013J\u0006\u0010\u0014\u001a\u00020\u0013R\u000e\u0010\u0004\u001a\u00020\u0005X\u0082\u0004\u00a2\u0006\u0002\n\u0000R\u000e\u0010\u0002\u001a\u00020\u0003X\u0082\u0004\u00a2\u0006\u0002\n\u0000R\u001a\u0010\u0007\u001a\u00020\bX\u0086\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b\u0007\u0010\t\"\u0004\b\n\u0010\u000bR\u001b\u0010\f\u001a\u00020\r8BX\u0082\u0084\u0002\u00a2\u0006\f\n\u0004\b\u0010\u0010\u0011\u001a\u0004\b\u000e\u0010\u000f\u00a8\u0006\u0015"}, d2={"Lxyz/apfelmus/cheeto/client/clickgui/ConfigLabel;", "Lgg/essential/elementa/components/UIContainer;", "gui", "Lxyz/apfelmus/cheeto/client/clickgui/ConfigGUI;", "config", "", "(Lxyz/apfelmus/cheeto/client/clickgui/ConfigGUI;Ljava/lang/String;)V", "isSelected", "", "()Z", "setSelected", "(Z)V", "text", "Lgg/essential/elementa/components/UIText;", "getText", "()Lgg/essential/elementa/components/UIText;", "text$delegate", "Lkotlin/properties/ReadWriteProperty;", "deselect", "", "select", "Cheeto"}) public final class ConfigLabel extends UIContainer { static final /* synthetic */ KProperty<Object>[] $$delegatedProperties; @NotNull private final ConfigGUI gui; @NotNull private final String config; @NotNull private final ReadWriteProperty text$delegate; private boolean isSelected; /* * WARNING - void declaration */ public ConfigLabel(@NotNull ConfigGUI gui, @NotNull String config) { void $this$text_delegate_u24lambda_u2d0; UIComponent uIComponent; Intrinsics.checkNotNullParameter((Object)((Object)gui), (String)"gui"); Intrinsics.checkNotNullParameter((Object)config, (String)"config"); this.gui = gui; this.config = config; UIComponent $this$constrain$iv = (UIComponent)new UIText(this.config, false, null, 6, null); boolean $i$f$constrain = false; UIComponent $this$constrain_u24lambda_u2d0$iv = uIComponent = $this$constrain$iv; boolean bl = false; UIConstraints uIConstraints = $this$constrain_u24lambda_u2d0$iv.getConstraints(); ConfigLabel configLabel = this; boolean bl2 = false; $this$text_delegate_u24lambda_u2d0.setX((XConstraint)new CenterConstraint()); $this$text_delegate_u24lambda_u2d0.setY((YConstraint)new CenterConstraint()); $this$text_delegate_u24lambda_u2d0.setTextScale((HeightConstraint)UtilitiesKt.pixels$default((Number)1, (boolean)false, (boolean)false, (int)3, null));
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * gg.essential.elementa.UIComponent * gg.essential.elementa.UIConstraints * gg.essential.elementa.components.UIContainer * gg.essential.elementa.components.UIText * gg.essential.elementa.constraints.CenterConstraint * gg.essential.elementa.constraints.ChildBasedMaxSizeConstraint * gg.essential.elementa.constraints.ColorConstraint * gg.essential.elementa.constraints.HeightConstraint * gg.essential.elementa.constraints.SiblingConstraint * gg.essential.elementa.constraints.WidthConstraint * gg.essential.elementa.constraints.XConstraint * gg.essential.elementa.constraints.YConstraint * gg.essential.elementa.constraints.animation.AnimatingConstraints * gg.essential.elementa.constraints.animation.AnimationStrategy * gg.essential.elementa.constraints.animation.Animations * gg.essential.elementa.dsl.ComponentsKt * gg.essential.elementa.dsl.UtilitiesKt * gg.essential.elementa.events.UIClickEvent * gg.essential.elementa.font.DefaultFonts * gg.essential.universal.USound * kotlin.Metadata * kotlin.Unit * kotlin.jvm.functions.Function1 * kotlin.jvm.functions.Function2 * kotlin.jvm.internal.Intrinsics * kotlin.jvm.internal.PropertyReference1 * kotlin.jvm.internal.PropertyReference1Impl * kotlin.jvm.internal.Reflection * kotlin.properties.ReadWriteProperty * kotlin.reflect.KProperty * org.jetbrains.annotations.NotNull */ package xyz.apfelmus.cheeto.client.clickgui; @Metadata(mv={1, 6, 0}, k=1, xi=48, d1={"\u00000\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u000e\n\u0002\b\u0002\n\u0002\u0010\u000b\n\u0002\b\u0004\n\u0002\u0018\u0002\n\u0002\b\u0005\n\u0002\u0010\u0002\n\u0002\b\u0002\u0018\u00002\u00020\u0001B\u0015\u0012\u0006\u0010\u0002\u001a\u00020\u0003\u0012\u0006\u0010\u0004\u001a\u00020\u0005\u00a2\u0006\u0002\u0010\u0006J\u0006\u0010\u0012\u001a\u00020\u0013J\u0006\u0010\u0014\u001a\u00020\u0013R\u000e\u0010\u0004\u001a\u00020\u0005X\u0082\u0004\u00a2\u0006\u0002\n\u0000R\u000e\u0010\u0002\u001a\u00020\u0003X\u0082\u0004\u00a2\u0006\u0002\n\u0000R\u001a\u0010\u0007\u001a\u00020\bX\u0086\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b\u0007\u0010\t\"\u0004\b\n\u0010\u000bR\u001b\u0010\f\u001a\u00020\r8BX\u0082\u0084\u0002\u00a2\u0006\f\n\u0004\b\u0010\u0010\u0011\u001a\u0004\b\u000e\u0010\u000f\u00a8\u0006\u0015"}, d2={"Lxyz/apfelmus/cheeto/client/clickgui/ConfigLabel;", "Lgg/essential/elementa/components/UIContainer;", "gui", "Lxyz/apfelmus/cheeto/client/clickgui/ConfigGUI;", "config", "", "(Lxyz/apfelmus/cheeto/client/clickgui/ConfigGUI;Ljava/lang/String;)V", "isSelected", "", "()Z", "setSelected", "(Z)V", "text", "Lgg/essential/elementa/components/UIText;", "getText", "()Lgg/essential/elementa/components/UIText;", "text$delegate", "Lkotlin/properties/ReadWriteProperty;", "deselect", "", "select", "Cheeto"}) public final class ConfigLabel extends UIContainer { static final /* synthetic */ KProperty<Object>[] $$delegatedProperties; @NotNull private final ConfigGUI gui; @NotNull private final String config; @NotNull private final ReadWriteProperty text$delegate; private boolean isSelected; /* * WARNING - void declaration */ public ConfigLabel(@NotNull ConfigGUI gui, @NotNull String config) { void $this$text_delegate_u24lambda_u2d0; UIComponent uIComponent; Intrinsics.checkNotNullParameter((Object)((Object)gui), (String)"gui"); Intrinsics.checkNotNullParameter((Object)config, (String)"config"); this.gui = gui; this.config = config; UIComponent $this$constrain$iv = (UIComponent)new UIText(this.config, false, null, 6, null); boolean $i$f$constrain = false; UIComponent $this$constrain_u24lambda_u2d0$iv = uIComponent = $this$constrain$iv; boolean bl = false; UIConstraints uIConstraints = $this$constrain_u24lambda_u2d0$iv.getConstraints(); ConfigLabel configLabel = this; boolean bl2 = false; $this$text_delegate_u24lambda_u2d0.setX((XConstraint)new CenterConstraint()); $this$text_delegate_u24lambda_u2d0.setY((YConstraint)new CenterConstraint()); $this$text_delegate_u24lambda_u2d0.setTextScale((HeightConstraint)UtilitiesKt.pixels$default((Number)1, (boolean)false, (boolean)false, (int)3, null));
Color color = ColorUtils.LABEL;
1
2023-12-21 16:22:25+00:00
24k
emtee40/ApkSignatureKill-pc
apksigner/src/main/java/android/sun/security/x509/InhibitAnyPolicyExtension.java
[ { "identifier": "Debug", "path": "apksigner/src/main/java/android/sun/security/util/Debug.java", "snippet": "public class Debug {\n\n private String prefix;\n\n private static String args;\n\n static {\n args = java.security.AccessController.doPrivileged\n (new GetProperty...
import android.sun.security.util.DerOutputStream; import android.sun.security.util.DerValue; import android.sun.security.util.ObjectIdentifier; import java.io.IOException; import java.io.OutputStream; import java.util.Enumeration; import android.sun.security.util.Debug;
20,903
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package android.sun.security.x509; /** * This class represents the Inhibit Any-Policy Extension. * * <p>The inhibit any-policy extension can be used in certificates issued * to CAs. The inhibit any-policy indicates that the special any-policy * OID, with the value {2 5 29 32 0}, is not considered an explicit * match for other certificate policies. The value indicates the number * of additional certificates that may appear in the path before any- * policy is no longer permitted. For example, a value of one indicates * that any-policy may be processed in certificates issued by the sub- * ject of this certificate, but not in additional certificates in the * path. * <p> * This extension MUST be critical. * <p> * The ASN.1 syntax for this extension is: * <code><pre> * id-ce-inhibitAnyPolicy OBJECT IDENTIFIER ::= { id-ce 54 } * * InhibitAnyPolicy ::= SkipCerts * * SkipCerts ::= INTEGER (0..MAX) * </pre></code> * @author Anne Anderson * @see android.sun.security.x509.CertAttrSet * @see android.sun.security.x509.Extension */ public class InhibitAnyPolicyExtension extends Extension implements CertAttrSet<String> { private static final Debug debug = Debug.getInstance("certpath"); /** * Identifier for this attribute, to be used with the * get, set, delete methods of Certificate, x509 type. */ public static final String IDENT = "x509.info.extensions.InhibitAnyPolicy"; /** * Object identifier for "any-policy" */
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package android.sun.security.x509; /** * This class represents the Inhibit Any-Policy Extension. * * <p>The inhibit any-policy extension can be used in certificates issued * to CAs. The inhibit any-policy indicates that the special any-policy * OID, with the value {2 5 29 32 0}, is not considered an explicit * match for other certificate policies. The value indicates the number * of additional certificates that may appear in the path before any- * policy is no longer permitted. For example, a value of one indicates * that any-policy may be processed in certificates issued by the sub- * ject of this certificate, but not in additional certificates in the * path. * <p> * This extension MUST be critical. * <p> * The ASN.1 syntax for this extension is: * <code><pre> * id-ce-inhibitAnyPolicy OBJECT IDENTIFIER ::= { id-ce 54 } * * InhibitAnyPolicy ::= SkipCerts * * SkipCerts ::= INTEGER (0..MAX) * </pre></code> * @author Anne Anderson * @see android.sun.security.x509.CertAttrSet * @see android.sun.security.x509.Extension */ public class InhibitAnyPolicyExtension extends Extension implements CertAttrSet<String> { private static final Debug debug = Debug.getInstance("certpath"); /** * Identifier for this attribute, to be used with the * get, set, delete methods of Certificate, x509 type. */ public static final String IDENT = "x509.info.extensions.InhibitAnyPolicy"; /** * Object identifier for "any-policy" */
public static ObjectIdentifier AnyPolicy_Id;
3
2023-12-16 11:11:16+00:00
24k
PeytonPlayz595/0.30-WebGL-Server
src/com/mojang/minecraft/level/tile/i.java
[ { "identifier": "Level", "path": "src/com/mojang/minecraft/level/Level.java", "snippet": "public class Level implements Serializable {\r\n\r\n public static final long serialVersionUID = 0L;\r\n public int width;\r\n public int height;\r\n public int depth;\r\n public byte[] blocks;\r\n publ...
import com.mojang.minecraft.level.Level; import com.mojang.minecraft.level.liquid.LiquidType; import com.mojang.minecraft.level.tile.a; import com.mojang.minecraft.level.tile.r; import java.util.Random;
17,968
package com.mojang.minecraft.level.tile; public final class i extends r { protected i(int var1, LiquidType var2) { super(var1, var2); this.af = var1 - 1; this.ae = var1; this.a(false); }
package com.mojang.minecraft.level.tile; public final class i extends r { protected i(int var1, LiquidType var2) { super(var1, var2); this.af = var1 - 1; this.ae = var1; this.a(false); }
public final void a(Level var1, int var2, int var3, int var4, Random var5) {}
0
2023-12-18 15:38:59+00:00
24k
Frig00/Progetto-Ing-Software
src/main/java/it/unipv/po/aioobe/trenissimo/controller/AcquistoController.java
[ { "identifier": "Utils", "path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/Utils.java", "snippet": "public class Utils {\n\n /**\n * Metodo che converte una stringa contente un tempo, in secondi.\n *\n * @param time in formato \"ore:minuti:secondi\"\n * @return Integer, i sec...
import it.unipv.po.aioobe.trenissimo.model.Utils; import it.unipv.po.aioobe.trenissimo.model.acquisto.Acquisto; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.TitoloViaggioEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.service.TitoloViaggioService; import it.unipv.po.aioobe.trenissimo.model.persistence.service.VoucherService; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.CorsaSingola; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.enumeration.TipoTitoloViaggio; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.utils.TicketBuilder; import it.unipv.po.aioobe.trenissimo.model.user.Account; import it.unipv.po.aioobe.trenissimo.model.viaggio.Viaggio; import it.unipv.po.aioobe.trenissimo.view.HomePage; import it.unipv.po.aioobe.trenissimo.view.ViaggioControl; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.net.URL; import java.util.*;
17,265
} /** * Imposta i dati dell'acquisto e la lista dei viaggi * * @param viaggi * @see Viaggio */ public void set_viaggi(@NotNull List<Viaggio> viaggi) { for (Viaggio v : viaggi) { subtotale = subtotale + v.getPrezzoTot(); iva = iva + v.getPrezzoIva(); } lblSubtotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); lblIVA.setText("€ " + String.format(Locale.US, "%.2f", iva)); lblTotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); _viaggi.setAll(viaggi); } /** * Gestisce il pagamento e il download del biglietto PDF * * @throws Exception * @see #onScaricaBigliettoPDF(Acquisto) * @see HomePage * @see Acquisto * @see Viaggio * @see CorsaSingola * @see TipoTitoloViaggio * @see Account */ @FXML protected void onPaga() throws Exception { onAlert("Acquisto avvenuto con successo!"); List<Acquisto> biglietti = new ArrayList<>(); for (Viaggio v : _viaggi) { biglietti.add(new CorsaSingola(TipoTitoloViaggio.BIGLIETTOCORSASINGOLA, v)); } biglietti.forEach(x -> x.pagare()); if (Account.getLoggedIn()) { biglietti.forEach(x -> x.puntiFedelta(biglietti)); //metodi per aggiornare i punti fedeltà dal db all'istanza di Account String username = Account.getInstance().getUsername(); Account.getInstance().setAccount(username); } for (Acquisto a : biglietti) { onScaricaBigliettoPDF(a); } biglietto.delete(); HomePage.openScene(root.getScene().getWindow()); } /** * Apre il file chooser e permette di scaricare il biglietto in formato PDF * * @param a * @throws Exception * @see #fillPDF(Acquisto) * @see File * @see FileChooser * @see TicketBuilder */ @FXML protected void onScaricaBigliettoPDF(Acquisto a) throws Exception { fillPDF(a); this.biglietto = new File(TicketBuilder.DEST); //biglietto in folder temporanea FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Scegli dove salvare il titolo di viaggio"); fileChooser.setInitialFileName(a.getId()); File destin = new File(fileChooser.showSaveDialog(new Stage()).getAbsolutePath().concat(".pdf")); TicketBuilder.copy(biglietto, destin); } /** * Compila i campi del biglietto PDF * * @param a acquisto da cui prendere informazioni * @throws Exception * @see TitoloViaggioService * @see TitoloViaggioEntity * @see Acquisto * @see TicketBuilder */ private void fillPDF(@NotNull Acquisto a) throws Exception { TitoloViaggioService titoloViaggioService = new TitoloViaggioService(); TitoloViaggioEntity titoloViaggioEntity; titoloViaggioEntity = titoloViaggioService.findById(a.getId()); if (a.getId().startsWith("CS")) titoloViaggio = new TicketBuilder(titoloViaggioEntity.getStazionePartenza(), titoloViaggioEntity.getStazioneArrivo(), titoloViaggioEntity.getDataPartenza().toString(), titoloViaggioEntity.getDataArrivo().toString(), titoloViaggioEntity.getOraPartenza().toString(), titoloViaggioEntity.getOraArrivo().toString(), txtNome.getText(), txtCognome.getText(), dtpDataNascita.getValue().toString(), a.getId(), String.valueOf(a.getPrezzo()), String.valueOf(_viaggi.get(0).getNumAdulti()), String.valueOf(_viaggi.get(0).getNumRagazzi()), String.valueOf(_viaggi.get(0).getNumBambini()), String.valueOf(_viaggi.get(0).getNumAnimali())); titoloViaggio.createPdf(a.getId()); } /** * Gestisce il riscatto del voucher * * @throws Exception * @see VoucherService * @see Utils * @see Task * @see Thread */ @FXML protected void onRiscatta() throws Exception { VoucherService voucherService = new VoucherService();
package it.unipv.po.aioobe.trenissimo.controller; /** * Controller class per acquistoView.fxml * * @author ArrayIndexOutOfBoundsException * @see it.unipv.po.aioobe.trenissimo.view.acquistoView * @see javafx.fxml.Initializable */ public class AcquistoController implements Initializable { @FXML private BorderPane root; @FXML private VBox boxViaggi; @FXML private Button btnAcquisto; @FXML private TextField txtNumCarta; @FXML private TextField txtDataScadenza; @FXML private TextField txtCVV; @FXML private Label lblRiscattoOK; @FXML private Label lblErroreRiscatto; @FXML private Button btnRiscatta; @FXML private TextField txtVoucher; @FXML private Label lblSubtotale; @FXML private Label lblIVA; @FXML private Label lblSconto; @FXML private Label lblTotale; @FXML private TextField txtNome; @FXML private TextField txtCognome; @FXML private DatePicker dtpDataNascita; @FXML private TextField txtEmail; @FXML private TextField txtVia; @FXML private TextField txtCivico; @FXML private TextField txtCitta; @FXML private TextField txtCAP; @FXML private Button btnAggiungiPagamento; @FXML private Label lblErroreNumCarta; @FXML private Label lblErroreData; @FXML private Label lblErroreCVV; @FXML private Label lblErroreCAP; @FXML private Label lblErroreEmail; @FXML private Label lblErroreDataNascita; @FXML private Label lblErroreNome; @FXML private Label lblErroreCognome; @FXML private Label lblErroreVia; @FXML private Label lblErroreCivico; @FXML private Label lblErroreCitta; @FXML private Label lblCartaOK; @FXML private Button btnConferma; @FXML private Label lblDatiOK; private ObservableList<Viaggio> _viaggi; private TicketBuilder titoloViaggio; private boolean isIdVoucherOK; private Double subtotale; private Double iva; private boolean acquistoSoloVoucher; private boolean isRiscattoUsed; private File biglietto; /** * Metodo d'Inizializzazione * * @param location * @param resources * @see #checkIdRealTime() * @see #checkPagamentoRealTime() * @see #checkDatiRealTime() * @see Account * @see ViaggioControl */ @Override public void initialize(URL location, ResourceBundle resources) { _viaggi = FXCollections.observableArrayList(); _viaggi.addListener((ListChangeListener<Viaggio>) c -> { boxViaggi.getChildren().setAll(_viaggi.stream().map(x -> new ViaggioControl(x, null)).toList()); }); this.subtotale = 0.0; this.iva = 0.0; this.isRiscattoUsed = false; checkIdRealTime(); checkPagamentoRealTime(); checkDatiRealTime(); if (Account.getLoggedIn()) { txtNome.setText(Account.getInstance().getDatiPersonali().getNome()); txtCognome.setText(Account.getInstance().getDatiPersonali().getCognome()); dtpDataNascita.setValue(Account.getInstance().getDatiPersonali().getDataNascita().toLocalDate()); txtEmail.setText(Account.getInstance().getDatiPersonali().getMail()); txtVia.setText(Account.getInstance().getDatiPersonali().getVia()); txtCivico.setText(Account.getInstance().getDatiPersonali().getCivico()); txtCitta.setText(Account.getInstance().getDatiPersonali().getCitta()); txtCAP.setText(Account.getInstance().getDatiPersonali().getCap().toString()); } } /** * Verifica per abilitazione del tasto acquista dopo la conferma dei dati personali e dei dati di pagamento/riscatto voucher */ private void check() { if ((lblDatiOK.isVisible() && lblCartaOK.isVisible())) btnAcquisto.setDisable(false); else if ((lblDatiOK.isVisible() && acquistoSoloVoucher)) btnAcquisto.setDisable(false); } /** * Imposta i dati dell'acquisto e la lista dei viaggi * * @param viaggi * @see Viaggio */ public void set_viaggi(@NotNull List<Viaggio> viaggi) { for (Viaggio v : viaggi) { subtotale = subtotale + v.getPrezzoTot(); iva = iva + v.getPrezzoIva(); } lblSubtotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); lblIVA.setText("€ " + String.format(Locale.US, "%.2f", iva)); lblTotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); _viaggi.setAll(viaggi); } /** * Gestisce il pagamento e il download del biglietto PDF * * @throws Exception * @see #onScaricaBigliettoPDF(Acquisto) * @see HomePage * @see Acquisto * @see Viaggio * @see CorsaSingola * @see TipoTitoloViaggio * @see Account */ @FXML protected void onPaga() throws Exception { onAlert("Acquisto avvenuto con successo!"); List<Acquisto> biglietti = new ArrayList<>(); for (Viaggio v : _viaggi) { biglietti.add(new CorsaSingola(TipoTitoloViaggio.BIGLIETTOCORSASINGOLA, v)); } biglietti.forEach(x -> x.pagare()); if (Account.getLoggedIn()) { biglietti.forEach(x -> x.puntiFedelta(biglietti)); //metodi per aggiornare i punti fedeltà dal db all'istanza di Account String username = Account.getInstance().getUsername(); Account.getInstance().setAccount(username); } for (Acquisto a : biglietti) { onScaricaBigliettoPDF(a); } biglietto.delete(); HomePage.openScene(root.getScene().getWindow()); } /** * Apre il file chooser e permette di scaricare il biglietto in formato PDF * * @param a * @throws Exception * @see #fillPDF(Acquisto) * @see File * @see FileChooser * @see TicketBuilder */ @FXML protected void onScaricaBigliettoPDF(Acquisto a) throws Exception { fillPDF(a); this.biglietto = new File(TicketBuilder.DEST); //biglietto in folder temporanea FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Scegli dove salvare il titolo di viaggio"); fileChooser.setInitialFileName(a.getId()); File destin = new File(fileChooser.showSaveDialog(new Stage()).getAbsolutePath().concat(".pdf")); TicketBuilder.copy(biglietto, destin); } /** * Compila i campi del biglietto PDF * * @param a acquisto da cui prendere informazioni * @throws Exception * @see TitoloViaggioService * @see TitoloViaggioEntity * @see Acquisto * @see TicketBuilder */ private void fillPDF(@NotNull Acquisto a) throws Exception { TitoloViaggioService titoloViaggioService = new TitoloViaggioService(); TitoloViaggioEntity titoloViaggioEntity; titoloViaggioEntity = titoloViaggioService.findById(a.getId()); if (a.getId().startsWith("CS")) titoloViaggio = new TicketBuilder(titoloViaggioEntity.getStazionePartenza(), titoloViaggioEntity.getStazioneArrivo(), titoloViaggioEntity.getDataPartenza().toString(), titoloViaggioEntity.getDataArrivo().toString(), titoloViaggioEntity.getOraPartenza().toString(), titoloViaggioEntity.getOraArrivo().toString(), txtNome.getText(), txtCognome.getText(), dtpDataNascita.getValue().toString(), a.getId(), String.valueOf(a.getPrezzo()), String.valueOf(_viaggi.get(0).getNumAdulti()), String.valueOf(_viaggi.get(0).getNumRagazzi()), String.valueOf(_viaggi.get(0).getNumBambini()), String.valueOf(_viaggi.get(0).getNumAnimali())); titoloViaggio.createPdf(a.getId()); } /** * Gestisce il riscatto del voucher * * @throws Exception * @see VoucherService * @see Utils * @see Task * @see Thread */ @FXML protected void onRiscatta() throws Exception { VoucherService voucherService = new VoucherService();
if (!(Utils.checkIdVoucher(txtVoucher.getText()))) {
0
2023-12-21 10:41:11+00:00
24k
green-code-initiative/ecoCode-java
src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java
[ { "identifier": "ArrayCopyCheck", "path": "src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java", "snippet": "@Rule(key = \"EC27\")\n@DeprecatedRuleKey(repositoryKey = \"greencodeinitiative-java\", ruleKey = \"GRPS0027\")\npublic class ArrayCopyCheck extends IssuableSubscriptionVisitor {...
import java.util.Collections; import java.util.List; import fr.greencodeinitiative.java.checks.ArrayCopyCheck; import fr.greencodeinitiative.java.checks.AvoidConcatenateStringsInLoop; import fr.greencodeinitiative.java.checks.AvoidFullSQLRequest; import fr.greencodeinitiative.java.checks.AvoidGettingSizeCollectionInLoop; import fr.greencodeinitiative.java.checks.AvoidMultipleIfElseStatement; import fr.greencodeinitiative.java.checks.AvoidRegexPatternNotStatic; import fr.greencodeinitiative.java.checks.AvoidSQLRequestInLoop; import fr.greencodeinitiative.java.checks.AvoidSetConstantInBatchUpdate; import fr.greencodeinitiative.java.checks.AvoidSpringRepositoryCallInLoopOrStreamCheck; import fr.greencodeinitiative.java.checks.AvoidStatementForDMLQueries; import fr.greencodeinitiative.java.checks.AvoidUsageOfStaticCollections; import fr.greencodeinitiative.java.checks.AvoidUsingGlobalVariablesCheck; import fr.greencodeinitiative.java.checks.FreeResourcesOfAutoCloseableInterface; import fr.greencodeinitiative.java.checks.IncrementCheck; import fr.greencodeinitiative.java.checks.InitializeBufferWithAppropriateSize; import fr.greencodeinitiative.java.checks.NoFunctionCallWhenDeclaringForLoop; import fr.greencodeinitiative.java.checks.OptimizeReadFileExceptions; import fr.greencodeinitiative.java.checks.UnnecessarilyAssignValuesToVariables; import fr.greencodeinitiative.java.checks.UseCorrectForLoop; import org.sonar.plugins.java.api.CheckRegistrar; import org.sonar.plugins.java.api.JavaCheck; import org.sonarsource.api.sonarlint.SonarLintSide;
14,710
/* * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package fr.greencodeinitiative.java; /** * Provide the "checks" (implementations of rules) classes that are going be executed during * source code analysis. * <p> * This class is a batch extension by implementing the {@link org.sonar.plugins.java.api.CheckRegistrar} interface. */ @SonarLintSide public class JavaCheckRegistrar implements CheckRegistrar { private static final List<Class<? extends JavaCheck>> ANNOTATED_RULE_CLASSES = List.of( ArrayCopyCheck.class, IncrementCheck.class, AvoidConcatenateStringsInLoop.class,
/* * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package fr.greencodeinitiative.java; /** * Provide the "checks" (implementations of rules) classes that are going be executed during * source code analysis. * <p> * This class is a batch extension by implementing the {@link org.sonar.plugins.java.api.CheckRegistrar} interface. */ @SonarLintSide public class JavaCheckRegistrar implements CheckRegistrar { private static final List<Class<? extends JavaCheck>> ANNOTATED_RULE_CLASSES = List.of( ArrayCopyCheck.class, IncrementCheck.class, AvoidConcatenateStringsInLoop.class,
AvoidUsageOfStaticCollections.class,
10
2023-12-19 20:38:40+00:00
24k
f1den/MrCrayfishGunMod
src/main/java/com/mrcrayfish/guns/client/screen/WorkbenchScreen.java
[ { "identifier": "WorkbenchBlockEntity", "path": "src/main/java/com/mrcrayfish/guns/blockentity/WorkbenchBlockEntity.java", "snippet": "public class WorkbenchBlockEntity extends SyncedBlockEntity implements IStorageBlock\n{\n private NonNullList<ItemStack> inventory = NonNullList.withSize(1, ItemStack...
import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Vector3f; import com.mrcrayfish.guns.blockentity.WorkbenchBlockEntity; import com.mrcrayfish.guns.client.util.RenderUtil; import com.mrcrayfish.guns.common.NetworkGunManager; import com.mrcrayfish.guns.common.container.WorkbenchContainer; import com.mrcrayfish.guns.crafting.WorkbenchIngredient; import com.mrcrayfish.guns.crafting.WorkbenchRecipe; import com.mrcrayfish.guns.crafting.WorkbenchRecipes; import com.mrcrayfish.guns.init.ModItems; import com.mrcrayfish.guns.item.GunItem; import com.mrcrayfish.guns.item.IAmmo; import com.mrcrayfish.guns.item.IColored; import com.mrcrayfish.guns.item.attachment.IAttachment; import com.mrcrayfish.guns.network.PacketHandler; import com.mrcrayfish.guns.network.message.C2SMessageCraft; import com.mrcrayfish.guns.util.InventoryUtil; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.block.model.ItemTransforms; import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.client.resources.sounds.SimpleSoundInstance; import net.minecraft.core.NonNullList; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvents; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.DyeItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraftforge.registries.ForgeRegistries; import org.lwjgl.opengl.GL11; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream;
15,633
for(GunItem gunItem : NetworkGunManager.getClientRegisteredGuns()) { if(id.equals(gunItem.getModifiedGun(stack).getProjectile().getItem())) { return true; } } return false; } @Override public void init() { super.init(); if(!this.tabs.isEmpty()) { this.topPos += 28; } this.addRenderableWidget(new Button(this.leftPos + 9, this.topPos + 18, 15, 20, Component.literal("<"), button -> { int index = this.currentTab.getCurrentIndex(); if(index - 1 < 0) { this.loadItem(this.currentTab.getRecipes().size() - 1); } else { this.loadItem(index - 1); } })); this.addRenderableWidget(new Button(this.leftPos + 153, this.topPos + 18, 15, 20, Component.literal(">"), button -> { int index = this.currentTab.getCurrentIndex(); if(index + 1 >= this.currentTab.getRecipes().size()) { this.loadItem(0); } else { this.loadItem(index + 1); } })); this.btnCraft = this.addRenderableWidget(new Button(this.leftPos + 195, this.topPos + 16, 74, 20, Component.translatable("gui.cgm.workbench.assemble"), button -> { int index = this.currentTab.getCurrentIndex(); WorkbenchRecipe recipe = this.currentTab.getRecipes().get(index); ResourceLocation registryName = recipe.getId(); PacketHandler.getPlayChannel().sendToServer(new C2SMessageCraft(registryName, this.workbench.getBlockPos())); })); this.btnCraft.active = false; this.checkBoxMaterials = this.addRenderableWidget(new CheckBox(this.leftPos + 172, this.topPos + 51, Component.translatable("gui.cgm.workbench.show_remaining"))); this.checkBoxMaterials.setToggled(WorkbenchScreen.showRemaining); this.loadItem(this.currentTab.getCurrentIndex()); } @Override public void containerTick() { super.containerTick(); for(MaterialItem material : this.materials) { material.tick(); } boolean canCraft = true; for(MaterialItem material : this.materials) { if(!material.isEnabled()) { canCraft = false; break; } } this.btnCraft.active = canCraft; this.updateColor(); } private void updateColor() { if(this.currentTab != null) { ItemStack item = this.displayStack; if(IColored.isDyeable(item)) { IColored colored = (IColored) item.getItem(); if(!this.workbench.getItem(0).isEmpty()) { ItemStack dyeStack = this.workbench.getItem(0); if(dyeStack.getItem() instanceof DyeItem) { DyeColor color = ((DyeItem) dyeStack.getItem()).getDyeColor(); float[] components = color.getTextureDiffuseColors(); int red = (int) (components[0] * 255F); int green = (int) (components[1] * 255F); int blue = (int) (components[2] * 255F); colored.setColor(item, ((red & 0xFF) << 16) | ((green & 0xFF) << 8) | ((blue & 0xFF))); } else { colored.removeColor(item); } } else { colored.removeColor(item); } } } } @Override public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) { boolean result = super.mouseClicked(mouseX, mouseY, mouseButton); WorkbenchScreen.showRemaining = this.checkBoxMaterials.isToggled(); for(int i = 0; i < this.tabs.size(); i++) {
package com.mrcrayfish.guns.client.screen; /** * Author: MrCrayfish */ public class WorkbenchScreen extends AbstractContainerScreen<WorkbenchContainer> { private static final ResourceLocation GUI_BASE = new ResourceLocation("cgm:textures/gui/workbench.png"); private static boolean showRemaining = false; private Tab currentTab; private List<Tab> tabs = new ArrayList<>(); private List<MaterialItem> materials; private List<MaterialItem> filteredMaterials; private Inventory playerInventory; private WorkbenchBlockEntity workbench; private Button btnCraft; private CheckBox checkBoxMaterials; private ItemStack displayStack; public WorkbenchScreen(WorkbenchContainer container, Inventory playerInventory, Component title) { super(container, playerInventory, title); this.playerInventory = playerInventory; this.workbench = container.getWorkbench(); this.imageWidth = 275; this.imageHeight = 184; this.materials = new ArrayList<>(); this.createTabs(WorkbenchRecipes.getAll(playerInventory.player.level)); if(!this.tabs.isEmpty()) { this.imageHeight += 28; } } private void createTabs(NonNullList<WorkbenchRecipe> recipes) { List<WorkbenchRecipe> weapons = new ArrayList<>(); List<WorkbenchRecipe> attachments = new ArrayList<>(); List<WorkbenchRecipe> ammo = new ArrayList<>(); List<WorkbenchRecipe> misc = new ArrayList<>(); for(WorkbenchRecipe recipe : recipes) { ItemStack output = recipe.getItem(); if(output.getItem() instanceof GunItem) { weapons.add(recipe); } else if(output.getItem() instanceof IAttachment) { attachments.add(recipe); } else if(this.isAmmo(output)) { ammo.add(recipe); } else { misc.add(recipe); } } if(!weapons.isEmpty()) { ItemStack icon = new ItemStack(ModItems.ASSAULT_RIFLE.get()); icon.getOrCreateTag().putInt("AmmoCount", ModItems.ASSAULT_RIFLE.get().getGun().getGeneral().getMaxAmmo()); this.tabs.add(new Tab(icon, "weapons", weapons)); } if(!attachments.isEmpty()) { this.tabs.add(new Tab(new ItemStack(ModItems.LONG_SCOPE.get()), "attachments", attachments)); } if(!ammo.isEmpty()) { this.tabs.add(new Tab(new ItemStack(ModItems.SHELL.get()), "ammo", ammo)); } if(!misc.isEmpty()) { this.tabs.add(new Tab(new ItemStack(Items.BARRIER), "misc", misc)); } if(!this.tabs.isEmpty()) { this.currentTab = this.tabs.get(0); } } private boolean isAmmo(ItemStack stack) { if(stack.getItem() instanceof IAmmo) { return true; } ResourceLocation id = ForgeRegistries.ITEMS.getKey(stack.getItem()); Objects.requireNonNull(id); for(GunItem gunItem : NetworkGunManager.getClientRegisteredGuns()) { if(id.equals(gunItem.getModifiedGun(stack).getProjectile().getItem())) { return true; } } return false; } @Override public void init() { super.init(); if(!this.tabs.isEmpty()) { this.topPos += 28; } this.addRenderableWidget(new Button(this.leftPos + 9, this.topPos + 18, 15, 20, Component.literal("<"), button -> { int index = this.currentTab.getCurrentIndex(); if(index - 1 < 0) { this.loadItem(this.currentTab.getRecipes().size() - 1); } else { this.loadItem(index - 1); } })); this.addRenderableWidget(new Button(this.leftPos + 153, this.topPos + 18, 15, 20, Component.literal(">"), button -> { int index = this.currentTab.getCurrentIndex(); if(index + 1 >= this.currentTab.getRecipes().size()) { this.loadItem(0); } else { this.loadItem(index + 1); } })); this.btnCraft = this.addRenderableWidget(new Button(this.leftPos + 195, this.topPos + 16, 74, 20, Component.translatable("gui.cgm.workbench.assemble"), button -> { int index = this.currentTab.getCurrentIndex(); WorkbenchRecipe recipe = this.currentTab.getRecipes().get(index); ResourceLocation registryName = recipe.getId(); PacketHandler.getPlayChannel().sendToServer(new C2SMessageCraft(registryName, this.workbench.getBlockPos())); })); this.btnCraft.active = false; this.checkBoxMaterials = this.addRenderableWidget(new CheckBox(this.leftPos + 172, this.topPos + 51, Component.translatable("gui.cgm.workbench.show_remaining"))); this.checkBoxMaterials.setToggled(WorkbenchScreen.showRemaining); this.loadItem(this.currentTab.getCurrentIndex()); } @Override public void containerTick() { super.containerTick(); for(MaterialItem material : this.materials) { material.tick(); } boolean canCraft = true; for(MaterialItem material : this.materials) { if(!material.isEnabled()) { canCraft = false; break; } } this.btnCraft.active = canCraft; this.updateColor(); } private void updateColor() { if(this.currentTab != null) { ItemStack item = this.displayStack; if(IColored.isDyeable(item)) { IColored colored = (IColored) item.getItem(); if(!this.workbench.getItem(0).isEmpty()) { ItemStack dyeStack = this.workbench.getItem(0); if(dyeStack.getItem() instanceof DyeItem) { DyeColor color = ((DyeItem) dyeStack.getItem()).getDyeColor(); float[] components = color.getTextureDiffuseColors(); int red = (int) (components[0] * 255F); int green = (int) (components[1] * 255F); int blue = (int) (components[2] * 255F); colored.setColor(item, ((red & 0xFF) << 16) | ((green & 0xFF) << 8) | ((blue & 0xFF))); } else { colored.removeColor(item); } } else { colored.removeColor(item); } } } } @Override public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) { boolean result = super.mouseClicked(mouseX, mouseY, mouseButton); WorkbenchScreen.showRemaining = this.checkBoxMaterials.isToggled(); for(int i = 0; i < this.tabs.size(); i++) {
if(RenderUtil.isMouseWithin((int) mouseX, (int) mouseY, this.leftPos + 28 * i, this.topPos - 28, 28, 28))
1
2023-12-18 15:04:35+00:00
24k
ReChronoRain/HyperCeiler
app/src/main/java/com/sevtinge/hyperceiler/ui/MainActivity.java
[ { "identifier": "NavigationActivity", "path": "app/src/main/java/com/sevtinge/hyperceiler/ui/base/NavigationActivity.java", "snippet": "public abstract class NavigationActivity extends BaseActivity implements PreferenceFragmentCompat.OnPreferenceStartFragmentCallback {\n\n String lastFilter;\n Vie...
import android.content.Intent; import android.os.Bundle; import androidx.annotation.Nullable; import com.sevtinge.hyperceiler.R; import com.sevtinge.hyperceiler.ui.base.NavigationActivity; import com.sevtinge.hyperceiler.utils.BackupUtils; import com.sevtinge.hyperceiler.utils.Helpers; import com.sevtinge.hyperceiler.utils.PrefsUtils; import com.sevtinge.hyperceiler.utils.PropUtils; import com.sevtinge.hyperceiler.utils.SearchHelper; import com.sevtinge.hyperceiler.utils.ShellUtils; import com.sevtinge.hyperceiler.utils.api.ProjectApi; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.regex.Matcher; import java.util.regex.Pattern; import moralnorm.appcompat.app.AlertDialog;
16,105
package com.sevtinge.hyperceiler.ui; public class MainActivity extends NavigationActivity { @Override public void onCreate(Bundle savedInstanceState) { int def = Integer.parseInt(PrefsUtils.mSharedPreferences.getString("prefs_key_log_level", "2")); super.onCreate(savedInstanceState); new Thread(() -> SearchHelper.getAllMods(MainActivity.this, savedInstanceState != null)).start(); Helpers.checkXposedActivateState(this);
package com.sevtinge.hyperceiler.ui; public class MainActivity extends NavigationActivity { @Override public void onCreate(Bundle savedInstanceState) { int def = Integer.parseInt(PrefsUtils.mSharedPreferences.getString("prefs_key_log_level", "2")); super.onCreate(savedInstanceState); new Thread(() -> SearchHelper.getAllMods(MainActivity.this, savedInstanceState != null)).start(); Helpers.checkXposedActivateState(this);
if (!PropUtils.setProp("persist.hyperceiler.log.level",
4
2023-10-27 17:17:42+00:00
24k
sgware/sabre
src/edu/uky/cs/nil/sabre/prog/RelaxedPlanHeuristic.java
[ { "identifier": "Action", "path": "src/edu/uky/cs/nil/sabre/Action.java", "snippet": "public class Action implements Event {\n\t\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\t\n\t/** Identifies the action's name and arguments */\n\tpublic final Sign...
import java.util.HashSet; import java.util.Set; import edu.uky.cs.nil.sabre.Action; import edu.uky.cs.nil.sabre.comp.CompiledProblem; import edu.uky.cs.nil.sabre.hg.ArithmeticNode; import edu.uky.cs.nil.sabre.hg.ClauseNode; import edu.uky.cs.nil.sabre.hg.DisjunctionNode; import edu.uky.cs.nil.sabre.hg.EffectNode; import edu.uky.cs.nil.sabre.hg.EventNode; import edu.uky.cs.nil.sabre.hg.FluentNode; import edu.uky.cs.nil.sabre.hg.FormulaNode; import edu.uky.cs.nil.sabre.hg.GoalNode; import edu.uky.cs.nil.sabre.hg.Node; import edu.uky.cs.nil.sabre.hg.PreconditionNode; import edu.uky.cs.nil.sabre.hg.UtilityNode; import edu.uky.cs.nil.sabre.logic.Comparison; import edu.uky.cs.nil.sabre.logic.Value; import edu.uky.cs.nil.sabre.util.Worker.Status;
19,114
package edu.uky.cs.nil.sabre.prog; /** * A {@link GraphHeuristic graph cost function}, meant to be used as the {@link * ProgressionSearch#heuristic heuristic} in a {@link ProgressionSearch * heuristic progression search}, which solves a relaxed version of the planning * problem and uses the cost of the solution to that relaxed problem as an * approximation of the cost of solving the real problem. This heuristic is * inspired by Jörg Hoffmann's Fast Forward heuristic. * <p> * The relaxed plan heuristic works initializing a {@link * edu.uky.cs.nil.sabre.hg.MaxGraph max heuristic graph} to the state it is * evaluating and then extending the graph until it is possible for the {@link * ProgressionNode#getCharacter() node's character's} utility to be higher. It * then selects a sequence of actions from the heuristic graph that approximate * a solution to the problem. Ideally, these actions will be similar to an * actual solution to the problem. * <p> * The relaxed problem implicitly being solved by this method is as follows: * suppose that once a proposition becomes true, it stays true forever. Few * real problems have this property, but if we make this assumption about a * real problem (even when it doesn't actually hold), we can solve a relaxed * version of the problem that is computationally easier. Then we can use the * solution to the relaxed problem as an approximation of the solution to the * real problem. * * @author Stephen G. Ware */ public class RelaxedPlanHeuristic extends GraphHeuristic.MaxGraphHeuristic { /** * A {@link ProgressionCostFactory factory} for creating {@link * RelaxedPlanHeuristic relaxed plan heuristic costs}. */ public static final ProgressionCostFactory FACTORY = new ProgressionCostFactory() { /** Serial version ID */ private static final long serialVersionUID = 1L; @Override public String toString() { return STRING; } @Override public RelaxedPlanHeuristic getCost(CompiledProblem problem, Status status) { return new RelaxedPlanHeuristic(problem, status); } }; /** The name of this heuristic */ private static final String STRING = "relaxed plan"; /** Records which nodes from the graph are part of the relaxed solution */ protected final Set<Node> subgraph = new HashSet<>(); /** Counts the number of actions in the subgraph */ private int cost = 0; /** * Constructs a new relaxed plan heuristic. * * @param problem that problem for which this heuristic will approximate * costs * @param status a status to update while building the sum graph */ public RelaxedPlanHeuristic(CompiledProblem problem, Status status) { super(problem, status); } @Override public String toString() { return STRING; } @Override public <N> double evaluate(ProgressionNode<N> node) { if(node.isExplained(node.getCharacter())) return 0; Value start = node.getUtility(node.getCharacter()); UtilityNode utility = graph.getUtility(node.getCharacter()); graph.initialize(node); while(utility.getCost(Comparison.GREATER_THAN, start) == Double.POSITIVE_INFINITY && graph.extend()); if(utility.getCost(Comparison.GREATER_THAN, start) == Double.POSITIVE_INFINITY) return Double.POSITIVE_INFINITY; else { subgraph.clear(); cost = 0; extract(utility, Comparison.GREATER_THAN, start); return cost; } } /** * Adds nodes from the {@link #graph heuristic graph} to the {@link * #subgraph solution subgraph} which are needed to make a {@link * FormulaNode formula node} compare to a value. * * @param formula the formula node * @param operator the relationship between the formula and the value * @param value the value */ protected void extract(FormulaNode formula, Comparison.Operator operator, Value value) { if(formula instanceof FluentNode) extract((FluentNode) formula, operator, value);
package edu.uky.cs.nil.sabre.prog; /** * A {@link GraphHeuristic graph cost function}, meant to be used as the {@link * ProgressionSearch#heuristic heuristic} in a {@link ProgressionSearch * heuristic progression search}, which solves a relaxed version of the planning * problem and uses the cost of the solution to that relaxed problem as an * approximation of the cost of solving the real problem. This heuristic is * inspired by Jörg Hoffmann's Fast Forward heuristic. * <p> * The relaxed plan heuristic works initializing a {@link * edu.uky.cs.nil.sabre.hg.MaxGraph max heuristic graph} to the state it is * evaluating and then extending the graph until it is possible for the {@link * ProgressionNode#getCharacter() node's character's} utility to be higher. It * then selects a sequence of actions from the heuristic graph that approximate * a solution to the problem. Ideally, these actions will be similar to an * actual solution to the problem. * <p> * The relaxed problem implicitly being solved by this method is as follows: * suppose that once a proposition becomes true, it stays true forever. Few * real problems have this property, but if we make this assumption about a * real problem (even when it doesn't actually hold), we can solve a relaxed * version of the problem that is computationally easier. Then we can use the * solution to the relaxed problem as an approximation of the solution to the * real problem. * * @author Stephen G. Ware */ public class RelaxedPlanHeuristic extends GraphHeuristic.MaxGraphHeuristic { /** * A {@link ProgressionCostFactory factory} for creating {@link * RelaxedPlanHeuristic relaxed plan heuristic costs}. */ public static final ProgressionCostFactory FACTORY = new ProgressionCostFactory() { /** Serial version ID */ private static final long serialVersionUID = 1L; @Override public String toString() { return STRING; } @Override public RelaxedPlanHeuristic getCost(CompiledProblem problem, Status status) { return new RelaxedPlanHeuristic(problem, status); } }; /** The name of this heuristic */ private static final String STRING = "relaxed plan"; /** Records which nodes from the graph are part of the relaxed solution */ protected final Set<Node> subgraph = new HashSet<>(); /** Counts the number of actions in the subgraph */ private int cost = 0; /** * Constructs a new relaxed plan heuristic. * * @param problem that problem for which this heuristic will approximate * costs * @param status a status to update while building the sum graph */ public RelaxedPlanHeuristic(CompiledProblem problem, Status status) { super(problem, status); } @Override public String toString() { return STRING; } @Override public <N> double evaluate(ProgressionNode<N> node) { if(node.isExplained(node.getCharacter())) return 0; Value start = node.getUtility(node.getCharacter()); UtilityNode utility = graph.getUtility(node.getCharacter()); graph.initialize(node); while(utility.getCost(Comparison.GREATER_THAN, start) == Double.POSITIVE_INFINITY && graph.extend()); if(utility.getCost(Comparison.GREATER_THAN, start) == Double.POSITIVE_INFINITY) return Double.POSITIVE_INFINITY; else { subgraph.clear(); cost = 0; extract(utility, Comparison.GREATER_THAN, start); return cost; } } /** * Adds nodes from the {@link #graph heuristic graph} to the {@link * #subgraph solution subgraph} which are needed to make a {@link * FormulaNode formula node} compare to a value. * * @param formula the formula node * @param operator the relationship between the formula and the value * @param value the value */ protected void extract(FormulaNode formula, Comparison.Operator operator, Value value) { if(formula instanceof FluentNode) extract((FluentNode) formula, operator, value);
else if(formula instanceof ArithmeticNode)
2
2023-10-26 18:14:19+00:00
24k
granny/Pl3xMap
core/src/main/java/net/pl3x/map/core/renderer/task/UpdateSettingsData.java
[ { "identifier": "Pl3xMap", "path": "core/src/main/java/net/pl3x/map/core/Pl3xMap.java", "snippet": "public abstract class Pl3xMap {\n public static @NotNull Pl3xMap api() {\n return Provider.api();\n }\n\n private final boolean isBukkit;\n\n private final Attributes manifestAttributes...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import net.pl3x.map.core.Pl3xMap; import net.pl3x.map.core.configuration.Config; import net.pl3x.map.core.configuration.Lang; import net.pl3x.map.core.configuration.PlayersLayerConfig; import net.pl3x.map.core.configuration.WorldConfig; import net.pl3x.map.core.image.io.IO; import net.pl3x.map.core.markers.Point; import net.pl3x.map.core.scheduler.Task; import net.pl3x.map.core.util.FileUtil; import net.pl3x.map.core.world.World; import org.jetbrains.annotations.NotNull;
16,816
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * 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.pl3x.map.core.renderer.task; public class UpdateSettingsData extends Task { private final Gson gson = new GsonBuilder() //.setPrettyPrinting() .disableHtmlEscaping() .serializeNulls() .setLenient() .create(); public UpdateSettingsData() { super(1, true); } @Override public void run() { try { parseSettings(); } catch (Throwable t) { t.printStackTrace(); } } private @NotNull List<@NotNull Object> parsePlayers() { if (!PlayersLayerConfig.ENABLED) { return Collections.emptyList(); } List<Object> players = new ArrayList<>(); Pl3xMap.api().getPlayerRegistry().forEach(player -> { // do not expose hidden players in the json if (player.isHidden() || player.isNPC()) { return; } if (PlayersLayerConfig.HIDE_SPECTATORS && player.isSpectator()) { return; } if (PlayersLayerConfig.HIDE_INVISIBLE && player.isInvisible()) { return; } Map<String, Object> playerEntry = new LinkedHashMap<>(); playerEntry.put("name", player.getDecoratedName()); playerEntry.put("uuid", player.getUUID().toString()); playerEntry.put("displayName", player.getDecoratedName()); playerEntry.put("world", player.getWorld().getName()); playerEntry.put("position", player.getPosition()); players.add(playerEntry); }); return players; } private @NotNull List<@NotNull Map<@NotNull String, @NotNull Object>> parseWorlds() { List<Map<String, Object>> worldSettings = new ArrayList<>(); Pl3xMap.api().getWorldRegistry().entrySet().forEach(entry -> {
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * 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.pl3x.map.core.renderer.task; public class UpdateSettingsData extends Task { private final Gson gson = new GsonBuilder() //.setPrettyPrinting() .disableHtmlEscaping() .serializeNulls() .setLenient() .create(); public UpdateSettingsData() { super(1, true); } @Override public void run() { try { parseSettings(); } catch (Throwable t) { t.printStackTrace(); } } private @NotNull List<@NotNull Object> parsePlayers() { if (!PlayersLayerConfig.ENABLED) { return Collections.emptyList(); } List<Object> players = new ArrayList<>(); Pl3xMap.api().getPlayerRegistry().forEach(player -> { // do not expose hidden players in the json if (player.isHidden() || player.isNPC()) { return; } if (PlayersLayerConfig.HIDE_SPECTATORS && player.isSpectator()) { return; } if (PlayersLayerConfig.HIDE_INVISIBLE && player.isInvisible()) { return; } Map<String, Object> playerEntry = new LinkedHashMap<>(); playerEntry.put("name", player.getDecoratedName()); playerEntry.put("uuid", player.getUUID().toString()); playerEntry.put("displayName", player.getDecoratedName()); playerEntry.put("world", player.getWorld().getName()); playerEntry.put("position", player.getPosition()); players.add(playerEntry); }); return players; } private @NotNull List<@NotNull Map<@NotNull String, @NotNull Object>> parseWorlds() { List<Map<String, Object>> worldSettings = new ArrayList<>(); Pl3xMap.api().getWorldRegistry().entrySet().forEach(entry -> {
World world = entry.getValue();
8
2023-10-26 01:14:31+00:00
24k
kandybaby/S3mediaArchival
backend/src/test/java/com/example/mediaarchival/MediaArchivalApplicationTests.java
[ { "identifier": "MediaObjectTransferListenerTest", "path": "backend/src/test/java/com/example/mediaarchival/consumers/MediaObjectTransferListenerTest.java", "snippet": "public class MediaObjectTransferListenerTest {\n\n @Mock private MediaRepository mediaRepository;\n\n @Mock private MediaController m...
import com.example.mediaarchival.consumers.MediaObjectTransferListenerTest; import com.example.mediaarchival.controllers.LibraryControllerTest; import com.example.mediaarchival.controllers.MediaControllerTest; import com.example.mediaarchival.controllers.UserControllerTest; import com.example.mediaarchival.converters.StringToArchivedStatusConverterTest; import com.example.mediaarchival.converters.StringToMediaTypeConverterTest; import com.example.mediaarchival.deserializers.ArchivedStatusDeserializerTest; import com.example.mediaarchival.deserializers.MediaCategoryDeserializerTest; import com.example.mediaarchival.filters.JwtValidationFilterTest; import com.example.mediaarchival.tasks.S3CleanupTaskTest; import com.example.mediaarchival.tasks.StartupResetTasksTest; import com.example.mediaarchival.utils.TarUtilsTest; import com.example.mediaarchival.utils.TokenUtilsTest; import com.example.mediaarchival.tasks.RestoreCheckerTest; import com.example.mediaarchival.utils.DirectoryUtilsTest; import com.example.mediaarchival.consumers.LibraryUpdateConsumerTest; import com.example.mediaarchival.consumers.RestoreConsumerTest; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance;
17,014
package com.example.mediaarchival; @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaArchivalApplicationTests { @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaControllerTests extends MediaControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class LibraryControllerTests extends LibraryControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class JwtValidationFilterTests extends JwtValidationFilterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class StringToMediaTypeConverterTests extends StringToMediaTypeConverterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaCategoryDeserializerTests extends MediaCategoryDeserializerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class StringToArchivedStatusConverterTests extends StringToArchivedStatusConverterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ArchivedStatusDeserializerTests extends ArchivedStatusDeserializerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class UserControllerTests extends UserControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class TokenUtilsTests extends TokenUtilsTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class TarUtilsTests extends TarUtilsTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS)
package com.example.mediaarchival; @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaArchivalApplicationTests { @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaControllerTests extends MediaControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class LibraryControllerTests extends LibraryControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class JwtValidationFilterTests extends JwtValidationFilterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class StringToMediaTypeConverterTests extends StringToMediaTypeConverterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaCategoryDeserializerTests extends MediaCategoryDeserializerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class StringToArchivedStatusConverterTests extends StringToArchivedStatusConverterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ArchivedStatusDeserializerTests extends ArchivedStatusDeserializerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class UserControllerTests extends UserControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class TokenUtilsTests extends TokenUtilsTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class TarUtilsTests extends TarUtilsTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MediaObjectTransferListenerTests extends MediaObjectTransferListenerTest {}
0
2023-10-27 01:54:57+00:00
24k
siam1026/siam-cloud
siam-goods/goods-provider/src/main/java/com/siam/package_goods/service/GoodsService.java
[ { "identifier": "GoodsMenuDto", "path": "siam-goods/goods-api/src/main/java/com/siam/package_goods/model/dto/GoodsMenuDto.java", "snippet": "public class GoodsMenuDto extends Goods {\n\n @ApiModelProperty(notes = \"菜单id\")\n private Integer menuId;\n\n @ApiModelProperty(notes = \"菜单名称\")\n p...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.package_goods.model.dto.GoodsMenuDto; import com.siam.package_goods.entity.Goods; import com.siam.package_goods.model.example.GoodsExample; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.InputStream; import java.util.Date; import java.util.List; import java.util.Map;
15,558
package com.siam.package_goods.service; public interface GoodsService { int countByExample(GoodsExample example); void deleteByPrimaryKey(Integer id); void insertSelective(Goods record); List<Goods> selectByExample(GoodsExample example); Goods selectByPrimaryKey(Integer id); void updateByPrimaryKeySelective(Goods record); Page<Goods> getListByPage(int pageNo, int pageSize, Goods goods);
package com.siam.package_goods.service; public interface GoodsService { int countByExample(GoodsExample example); void deleteByPrimaryKey(Integer id); void insertSelective(Goods record); List<Goods> selectByExample(GoodsExample example); Goods selectByPrimaryKey(Integer id); void updateByPrimaryKeySelective(Goods record); Page<Goods> getListByPage(int pageNo, int pageSize, Goods goods);
Page<Map<String, Object>> getListByPageJoinMenu(int pageNo, int pageSize, GoodsMenuDto goodsMenuDto);
0
2023-10-26 10:45:10+00:00
24k
elizagamedev/android-libre-japanese-input
app/src/main/java/sh/eliza/japaneseinput/CandidateWordView.java
[ { "identifier": "BackgroundDrawableFactory", "path": "app/src/main/java/sh/eliza/japaneseinput/keyboard/BackgroundDrawableFactory.java", "snippet": "public class BackgroundDrawableFactory {\n /** Drawable to create. */\n public enum DrawableType {\n // Key background for twelvekeys layout.\n TWE...
import android.content.Context; import android.graphics.Canvas; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.accessibility.AccessibilityManager; import android.widget.EdgeEffect; import androidx.core.view.ViewCompat; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import javax.annotation.Nullable; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCandidates.CandidateList; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCandidates.CandidateWord; import sh.eliza.japaneseinput.accessibility.CandidateWindowAccessibilityDelegate; import sh.eliza.japaneseinput.keyboard.BackgroundDrawableFactory; import sh.eliza.japaneseinput.keyboard.BackgroundDrawableFactory.DrawableType; import sh.eliza.japaneseinput.ui.CandidateLayout; import sh.eliza.japaneseinput.ui.CandidateLayout.Row; import sh.eliza.japaneseinput.ui.CandidateLayout.Span; import sh.eliza.japaneseinput.ui.CandidateLayoutRenderer; import sh.eliza.japaneseinput.ui.CandidateLayouter; import sh.eliza.japaneseinput.ui.SnapScroller; import sh.eliza.japaneseinput.view.Skin;
14,952
return true; } return false; } } /** Polymorphic behavior based on scroll orientation. */ // TODO(hidehiko): rename OrientationTrait to OrientationTraits. interface OrientationTrait { /** * @return scroll position of which direction corresponds to the orientation. */ int getScrollPosition(View view); /** * @return the projected value. */ float projectVector(float x, float y); /** Scrolls to {@code position}. {@code position} is applied to corresponding axis. */ void scrollTo(View view, int position); /** * @return left or top position based on the orientation. */ float getCandidatePosition(Row row, Span span); /** * @return width or height based on the orientation. */ float getCandidateLength(Row row, Span span); /** * @return view's width or height based on the orientation. */ int getViewLength(View view); /** * @return the page size of the layout for the scroll orientation. */ int getPageSize(CandidateLayouter layouter); /** * @return the content size for the scroll orientation of the layout. 0 for absent. */ float getContentSize(Optional<CandidateLayout> layout); } enum Orientation implements OrientationTrait { VERTICAL { @Override public int getScrollPosition(View view) { return view.getScrollY(); } @Override public void scrollTo(View view, int position) { view.scrollTo(0, position); } @Override public float getCandidatePosition(Row row, Span span) { return row.getTop(); } @Override public float getCandidateLength(Row row, Span span) { return row.getHeight(); } @Override public int getViewLength(View view) { return view.getHeight(); } @Override public float projectVector(float x, float y) { return y; } @Override public int getPageSize(CandidateLayouter layouter) { return Preconditions.checkNotNull(layouter).getPageHeight(); } @Override public float getContentSize(Optional<CandidateLayout> layout) { return layout.isPresent() ? layout.get().getContentHeight() : 0; } } } private CandidateSelectListener candidateSelectListener; // Finally, we only need vertical scrolling. // TODO(hidehiko): Remove horizontal scrolling related codes. private final EdgeEffect topEdgeEffect = new EdgeEffect(getContext()); private final EdgeEffect bottomEdgeEffect = new EdgeEffect(getContext()); // The Scroller which manages the status of scrolling the view. // Default behavior of ScrollView does not suffice our UX design // so we introduced this Scroller. // TODO(matsuzakit): The parameter is TBD (needs UX study?). protected final SnapScroller scroller = new SnapScroller(); // The CandidateLayouter which calculates the layout of candidate words. // This fields is not final but must be set in initialization in the subclasses. protected CandidateLayouter layouter; // The calculated layout, created by this.layouter. protected CandidateLayout calculatedLayout; // The CandidateList which is currently shown on the view. protected CandidateList currentCandidateList; protected final CandidateLayoutRenderer candidateLayoutRenderer = new CandidateLayoutRenderer(); final CandidateWordGestureDetector candidateWordGestureDetector = new CandidateWordGestureDetector(getContext()); // Scroll orientation. private final OrientationTrait orientationTrait;
// Copyright 2010-2018, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package sh.eliza.japaneseinput; /** A view for candidate words. */ // TODO(matsuzakit): Optional is introduced partially. Complete introduction. abstract class CandidateWordView extends View implements MemoryManageable { /** Handles gestures to scroll candidate list and choose a candidate. */ class CandidateWordGestureDetector { class CandidateWordViewGestureListener extends SimpleOnGestureListener { @Override public boolean onFling( MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) { float velocity = orientationTrait.projectVector(velocityX, velocityY); // As fling is started, current action is not tapping. // Reset pressing state so that candidate selection is not triggered at touch up event. reset(); // Fling makes scrolling. scroller.fling(-(int) velocity); invalidate(); return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { float distance = orientationTrait.projectVector(distanceX, distanceY); int oldScrollPosition = scroller.getScrollPosition(); int oldMaxScrollPosition = scroller.getMaxScrollPosition(); scroller.scrollBy((int) distance); orientationTrait.scrollTo(CandidateWordView.this, scroller.getScrollPosition()); // As scroll is started, current action is not tapping. // Reset pressing state so that candidate selection is not triggered at touch up event. reset(); // Edge effect. Now, in production, we only support vertical scroll. if (oldScrollPosition + distance < 0) { topEdgeEffect.onPull(distance / getHeight()); if (!bottomEdgeEffect.isFinished()) { bottomEdgeEffect.onRelease(); } } else if (oldScrollPosition + distance > oldMaxScrollPosition) { bottomEdgeEffect.onPull(distance / getHeight()); if (!topEdgeEffect.isFinished()) { topEdgeEffect.onRelease(); } } invalidate(); return true; } } // GestureDetector cannot handle all complex gestures which we need. // But we use GestureDetector for some gesture recognition // because implementing whole gesture detection logic by ourselves is a bit tedious. private final GestureDetector gestureDetector; /** * Points to an instance of currently pressed candidate word. Or {@code null} if any candidates * aren't pressed. */ @Nullable private CandidateWord pressedCandidate; private final RectF candidateRect = new RectF(); private Optional<Integer> pressedRowIndex = Optional.absent(); public CandidateWordGestureDetector(Context context) { gestureDetector = new GestureDetector(context, new CandidateWordViewGestureListener()); } private void pressCandidate(int rowIndex, Span span) { Row row = calculatedLayout.getRowList().get(rowIndex); pressedRowIndex = Optional.of(rowIndex); pressedCandidate = span.getCandidateWord().orNull(); // TODO(yamaguchi):maybe better to make this rect larger by several pixels to avoid that // users fail to select a candidate by unconscious small movement of tap point. // (i.e. give hysterisis for noise reduction) // Needs UX study. candidateRect.set( span.getLeft(), row.getTop(), span.getRight(), row.getTop() + row.getHeight()); } void reset() { pressedCandidate = null; pressedRowIndex = Optional.absent(); // NOTE: candidateRect doesn't need reset. } CandidateWord getPressedCandidate() { return pressedCandidate; } /** * Checks if a down event is fired inside a candidate rectangle. If so, begin pressing it. * * <p>It is assumed that rows are stored in up-to-down order, and spans are in left-to-right * order. * * @param scrolledX X coordinate of down event point including scroll offset * @param scrolledY Y coordinate of down event point including scroll offset * @return true if the down event is fired inside a candidate rectangle. */ private boolean findCandidateAndPress(float scrolledX, float scrolledY) { if (calculatedLayout == null) { return false; } for (int rowIndex = 0; rowIndex < calculatedLayout.getRowList().size(); ++rowIndex) { Row row = calculatedLayout.getRowList().get(rowIndex); if (scrolledY < row.getTop()) { break; } if (scrolledY >= row.getTop() + row.getHeight()) { continue; } for (Span span : row.getSpanList()) { if (scrolledX < span.getLeft()) { break; } if (scrolledX >= span.getRight()) { continue; } pressCandidate(rowIndex, span); invalidate(); return true; } return false; } return false; } boolean onTouchEvent(MotionEvent event) { // Before delegation to gesture detector, handle ACTION_UP event // in order to release edge effect. if (event.getAction() == MotionEvent.ACTION_UP) { topEdgeEffect.onRelease(); bottomEdgeEffect.onRelease(); invalidate(); } if (gestureDetector.onTouchEvent(event)) { return true; } float scrolledX = event.getX() + getScrollX(); float scrolledY = event.getY() + getScrollY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: findCandidateAndPress(scrolledX, scrolledY); scroller.stopScrolling(); if (!topEdgeEffect.isFinished()) { topEdgeEffect.onRelease(); invalidate(); } if (!bottomEdgeEffect.isFinished()) { bottomEdgeEffect.onRelease(); invalidate(); } return true; case MotionEvent.ACTION_MOVE: if (pressedCandidate != null) { // Turn off highlighting if contact point gets out of the candidate. if (!candidateRect.contains(scrolledX, scrolledY)) { reset(); invalidate(); } } return true; case MotionEvent.ACTION_CANCEL: if (pressedCandidate != null) { reset(); invalidate(); } return true; case MotionEvent.ACTION_UP: if (pressedCandidate != null) { if (candidateRect.contains(scrolledX, scrolledY) && candidateSelectListener != null) { candidateSelectListener.onCandidateSelected( CandidateWordView.this, pressedCandidate, pressedRowIndex); } reset(); invalidate(); } return true; } return false; } } /** Polymorphic behavior based on scroll orientation. */ // TODO(hidehiko): rename OrientationTrait to OrientationTraits. interface OrientationTrait { /** * @return scroll position of which direction corresponds to the orientation. */ int getScrollPosition(View view); /** * @return the projected value. */ float projectVector(float x, float y); /** Scrolls to {@code position}. {@code position} is applied to corresponding axis. */ void scrollTo(View view, int position); /** * @return left or top position based on the orientation. */ float getCandidatePosition(Row row, Span span); /** * @return width or height based on the orientation. */ float getCandidateLength(Row row, Span span); /** * @return view's width or height based on the orientation. */ int getViewLength(View view); /** * @return the page size of the layout for the scroll orientation. */ int getPageSize(CandidateLayouter layouter); /** * @return the content size for the scroll orientation of the layout. 0 for absent. */ float getContentSize(Optional<CandidateLayout> layout); } enum Orientation implements OrientationTrait { VERTICAL { @Override public int getScrollPosition(View view) { return view.getScrollY(); } @Override public void scrollTo(View view, int position) { view.scrollTo(0, position); } @Override public float getCandidatePosition(Row row, Span span) { return row.getTop(); } @Override public float getCandidateLength(Row row, Span span) { return row.getHeight(); } @Override public int getViewLength(View view) { return view.getHeight(); } @Override public float projectVector(float x, float y) { return y; } @Override public int getPageSize(CandidateLayouter layouter) { return Preconditions.checkNotNull(layouter).getPageHeight(); } @Override public float getContentSize(Optional<CandidateLayout> layout) { return layout.isPresent() ? layout.get().getContentHeight() : 0; } } } private CandidateSelectListener candidateSelectListener; // Finally, we only need vertical scrolling. // TODO(hidehiko): Remove horizontal scrolling related codes. private final EdgeEffect topEdgeEffect = new EdgeEffect(getContext()); private final EdgeEffect bottomEdgeEffect = new EdgeEffect(getContext()); // The Scroller which manages the status of scrolling the view. // Default behavior of ScrollView does not suffice our UX design // so we introduced this Scroller. // TODO(matsuzakit): The parameter is TBD (needs UX study?). protected final SnapScroller scroller = new SnapScroller(); // The CandidateLayouter which calculates the layout of candidate words. // This fields is not final but must be set in initialization in the subclasses. protected CandidateLayouter layouter; // The calculated layout, created by this.layouter. protected CandidateLayout calculatedLayout; // The CandidateList which is currently shown on the view. protected CandidateList currentCandidateList; protected final CandidateLayoutRenderer candidateLayoutRenderer = new CandidateLayoutRenderer(); final CandidateWordGestureDetector candidateWordGestureDetector = new CandidateWordGestureDetector(getContext()); // Scroll orientation. private final OrientationTrait orientationTrait;
protected final BackgroundDrawableFactory backgroundDrawableFactory =
0
2023-10-25 07:33:25+00:00
24k
oghenevovwerho/yaa
src/main/java/yaa/semantic/passes/fs2/F2.java
[ { "identifier": "YaaInfo", "path": "src/main/java/yaa/pojos/YaaInfo.java", "snippet": "public class YaaInfo implements Serializable {\r\n public String codeName;\r\n public int privacy = 0;\r\n public YaaClz typeParam;\r\n public int column;\r\n public int startLine;\r\n public String name;\r\n p...
import yaa.ast.*; import yaa.pojos.YaaInfo; import yaa.pojos.FileState; import yaa.pojos.GlobalData; import yaa.pojos.YaaClz; import yaa.pojos.YaaError; import java.util.List; import static yaa.pojos.GlobalData.*; import static yaa.pojos.GlobalData.nothing; import static yaa.pojos.NameUtils.top$elements$clz$name;
20,462
package yaa.semantic.passes.fs2; public class F2 extends FileState { public F2(List<Stmt> stmts, String filePath) { super(stmts, filePath); } @Override public YaaInfo $programOut(ProgramOut programOut) { fs = null; fs2 = null; return nothing; } @Override public YaaInfo $programIn(ProgramIn in) { this.tables = GlobalData.tables4File.get(in.path); this.table = tables.get(in); fs2 = this; fs = this; YaaError.filePath = in.path; topClzCodeName.put(in.path, top$elements$clz$name()); return nothing; } public void pushTable(Stmt stmt) { this.table = tables.get(stmt); } public void popTable() { this.table = table.parent; } @Override public YaaInfo $imports(Imports imp) { F2Imp.f2ImportsStmt(imp); return nothing; } @Override public YaaInfo $function(NewFun newFun) { F2NFun.f2NewFunction(newFun); return nothing; } @Override public YaaInfo $init(Init init) { F2Init.f2Init(init); return nothing; } @Override public YaaInfo $newClass(NewClass newClass) { F2NClass.newType(newClass); return nothing; } @Override public YaaInfo $fInterface(NewFunctionalInterface ctx) { F2FInterface.fInterface(ctx); return nothing; } @Override public YaaInfo $newRecord(NewRecord newRecord) { F2NRecord.newRecord(newRecord); return nothing; } @Override public YaaInfo $innerBlock(InnerBlock iBlock) { pushTable(iBlock); for (var stmt : iBlock.stmts) { stmt.visit(this); } popTable(); return nothing; } @Override public YaaInfo $objectType(ObjectType objectType) {
package yaa.semantic.passes.fs2; public class F2 extends FileState { public F2(List<Stmt> stmts, String filePath) { super(stmts, filePath); } @Override public YaaInfo $programOut(ProgramOut programOut) { fs = null; fs2 = null; return nothing; } @Override public YaaInfo $programIn(ProgramIn in) { this.tables = GlobalData.tables4File.get(in.path); this.table = tables.get(in); fs2 = this; fs = this; YaaError.filePath = in.path; topClzCodeName.put(in.path, top$elements$clz$name()); return nothing; } public void pushTable(Stmt stmt) { this.table = tables.get(stmt); } public void popTable() { this.table = table.parent; } @Override public YaaInfo $imports(Imports imp) { F2Imp.f2ImportsStmt(imp); return nothing; } @Override public YaaInfo $function(NewFun newFun) { F2NFun.f2NewFunction(newFun); return nothing; } @Override public YaaInfo $init(Init init) { F2Init.f2Init(init); return nothing; } @Override public YaaInfo $newClass(NewClass newClass) { F2NClass.newType(newClass); return nothing; } @Override public YaaInfo $fInterface(NewFunctionalInterface ctx) { F2FInterface.fInterface(ctx); return nothing; } @Override public YaaInfo $newRecord(NewRecord newRecord) { F2NRecord.newRecord(newRecord); return nothing; } @Override public YaaInfo $innerBlock(InnerBlock iBlock) { pushTable(iBlock); for (var stmt : iBlock.stmts) { stmt.visit(this); } popTable(); return nothing; } @Override public YaaInfo $objectType(ObjectType objectType) {
return YaaClz.f2Clz(objectType);
3
2023-10-26 17:41:13+00:00
24k
unloggedio/intellij-java-plugin
src/main/java/com/insidious/plugin/ui/highlighter/UnloggedGutterNavigationHandler.java
[ { "identifier": "JavaMethodAdapter", "path": "src/main/java/com/insidious/plugin/adapter/java/JavaMethodAdapter.java", "snippet": "public class JavaMethodAdapter implements MethodAdapter {\n private final PsiMethod psiMethod;\n\n public JavaMethodAdapter(PsiMethod methodItem) {\n assert met...
import com.insidious.plugin.adapter.java.JavaMethodAdapter; import com.insidious.plugin.factory.GutterState; import com.insidious.plugin.factory.InsidiousService; import com.insidious.plugin.factory.UsageInsightTracker; import com.insidious.plugin.util.LoggerUtil; import com.intellij.codeInsight.daemon.GutterIconNavigationHandler; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiIdentifier; import com.intellij.psi.PsiMethod; import com.intellij.psi.util.PsiTreeUtil; import java.awt.event.MouseEvent;
18,601
package com.insidious.plugin.ui.highlighter; public class UnloggedGutterNavigationHandler implements GutterIconNavigationHandler<PsiIdentifier> { private static final Logger logger = LoggerUtil.getInstance(UnloggedGutterNavigationHandler.class);
package com.insidious.plugin.ui.highlighter; public class UnloggedGutterNavigationHandler implements GutterIconNavigationHandler<PsiIdentifier> { private static final Logger logger = LoggerUtil.getInstance(UnloggedGutterNavigationHandler.class);
private final GutterState state;
1
2023-10-31 09:07:46+00:00
24k
quentin452/DangerRPG-Continuation
src/main/java/mixac1/dangerrpg/item/weapon/ItemRPGStaff.java
[ { "identifier": "DangerRPG", "path": "src/main/java/mixac1/dangerrpg/DangerRPG.java", "snippet": "@Mod(\n modid = DangerRPG.MODID,\n name = DangerRPG.MODNAME,\n version = DangerRPG.VERSION,\n acceptedMinecraftVersions = DangerRPG.ACCEPTED_VERSION,\n dependencies = \"required-after:Forge\"...
import mixac1.dangerrpg.DangerRPG; import mixac1.dangerrpg.api.item.IRPGItem.IRPGItemStaff; import mixac1.dangerrpg.capability.ItemAttributes; import mixac1.dangerrpg.capability.RPGItemHelper; import mixac1.dangerrpg.capability.data.RPGItemRegister.RPGItemData; import mixac1.dangerrpg.entity.projectile.EntityMagicOrb; import mixac1.dangerrpg.init.RPGItems; import mixac1.dangerrpg.init.RPGOther.RPGCreativeTabs; import mixac1.dangerrpg.item.IHasBooksInfo; import mixac1.dangerrpg.item.RPGItemComponent.RPGStaffComponent; import mixac1.dangerrpg.item.RPGToolMaterial; import mixac1.dangerrpg.util.RPGHelper; import mixac1.dangerrpg.util.Utils; import mixac1.dangerrpg.world.RPGEntityFXManager; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumAction; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.util.Vec3; import net.minecraft.world.World;
18,080
package mixac1.dangerrpg.item.weapon; public class ItemRPGStaff extends ItemSword implements IRPGItemStaff, IHasBooksInfo { public RPGToolMaterial toolMaterial; public RPGStaffComponent staffComponent; public ItemRPGStaff(RPGToolMaterial toolMaterial, RPGStaffComponent staffComponent) { super(toolMaterial.material); this.toolMaterial = toolMaterial; this.staffComponent = staffComponent; setUnlocalizedName(RPGItems.getRPGName(getItemComponent(this), getToolMaterial(this))); setTextureName(Utils.toString(DangerRPG.MODID, ":weapons/range/", unlocalizedName)); setCreativeTab(RPGCreativeTabs.tabRPGAmmunitions); setMaxStackSize(1); } @Override public void registerAttributes(Item item, RPGItemData map) { RPGItemHelper.registerParamsItemStaff(item, map); } @Override public RPGToolMaterial getToolMaterial(Item item) { return toolMaterial; } @Override public RPGStaffComponent getItemComponent(Item item) { return staffComponent; } @Override public String getInformationToInfoBook(ItemStack item, EntityPlayer player) { return null; } @Override public float func_150893_a(ItemStack stack, Block block) { Material material = block.getMaterial(); return material != Material.plants && material != Material.vine && material != Material.coral && material != Material.leaves && material != Material.gourd ? 1.0F : 1.5F; } @Override public boolean func_150897_b(Block block) { return false; } @Override public EnumAction getItemUseAction(ItemStack p_77661_1_) { return EnumAction.bow; } @Override public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
package mixac1.dangerrpg.item.weapon; public class ItemRPGStaff extends ItemSword implements IRPGItemStaff, IHasBooksInfo { public RPGToolMaterial toolMaterial; public RPGStaffComponent staffComponent; public ItemRPGStaff(RPGToolMaterial toolMaterial, RPGStaffComponent staffComponent) { super(toolMaterial.material); this.toolMaterial = toolMaterial; this.staffComponent = staffComponent; setUnlocalizedName(RPGItems.getRPGName(getItemComponent(this), getToolMaterial(this))); setTextureName(Utils.toString(DangerRPG.MODID, ":weapons/range/", unlocalizedName)); setCreativeTab(RPGCreativeTabs.tabRPGAmmunitions); setMaxStackSize(1); } @Override public void registerAttributes(Item item, RPGItemData map) { RPGItemHelper.registerParamsItemStaff(item, map); } @Override public RPGToolMaterial getToolMaterial(Item item) { return toolMaterial; } @Override public RPGStaffComponent getItemComponent(Item item) { return staffComponent; } @Override public String getInformationToInfoBook(ItemStack item, EntityPlayer player) { return null; } @Override public float func_150893_a(ItemStack stack, Block block) { Material material = block.getMaterial(); return material != Material.plants && material != Material.vine && material != Material.coral && material != Material.leaves && material != Material.gourd ? 1.0F : 1.5F; } @Override public boolean func_150897_b(Block block) { return false; } @Override public EnumAction getItemUseAction(ItemStack p_77661_1_) { return EnumAction.bow; } @Override public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
if (RPGHelper.spendMana(player, ItemAttributes.MANA_COST.getSafe(stack, player, 0))) {
2
2023-10-31 21:00:14+00:00
24k
llllllxy/tiny-jdbc-boot-starter
src/main/java/org/tinycloud/jdbc/support/AbstractSqlSupport.java
[ { "identifier": "Criteria", "path": "src/main/java/org/tinycloud/jdbc/criteria/Criteria.java", "snippet": "public class Criteria extends AbstractCriteria {\n\n public <R> Criteria lt(String field, R value) {\n String condition = \" AND \" + field + \" < \" + \"?\";\n conditions.add(cond...
import org.springframework.jdbc.core.*; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.tinycloud.jdbc.criteria.Criteria; import org.tinycloud.jdbc.criteria.LambdaCriteria; import org.tinycloud.jdbc.exception.JdbcException; import org.tinycloud.jdbc.page.IPageHandle; import org.tinycloud.jdbc.page.Page; import org.tinycloud.jdbc.sql.SqlGenerator; import org.tinycloud.jdbc.sql.SqlProvider; import java.lang.reflect.ParameterizedType; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.*;
14,738
package org.tinycloud.jdbc.support; /** * jdbc抽象类,给出默认的支持 * * @author liuxingyu01 * @since 2022-03-11-16:49 **/ public abstract class AbstractSqlSupport<T, ID> implements ISqlSupport<T, ID>, IObjectSupport<T, ID> { protected abstract JdbcTemplate getJdbcTemplate(); protected abstract IPageHandle getPageHandle(); /** * 泛型 */ private final Class<T> entityClass; /** * bean转换器 */ private final RowMapper<T> rowMapper; @SuppressWarnings("unchecked") public AbstractSqlSupport() { ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass(); entityClass = (Class<T>) type.getActualTypeArguments()[0]; rowMapper = BeanPropertyRowMapper.newInstance(entityClass); } /** * 执行查询sql,有查询条件 * * @param sql 要执行的SQL * @param params 要绑定到查询的参数 ,可以不传 * @return 查询结果 */ @Override public List<T> select(String sql, Object... params) { List<T> resultList; if (params != null && params.length > 0) { resultList = getJdbcTemplate().query(sql, params, rowMapper); } else { // BeanPropertyRowMapper是自动映射实体类的 resultList = getJdbcTemplate().query(sql, rowMapper); } return resultList; } /** * 执行查询sql,有查询条件 * * @param sql 要执行的SQL * @param clazz 实体类 * @param params 要绑定到查询的参数 ,可以不传 * @param <F> 泛型 * @return 查询结果 */ @Override public <F> List<F> select(String sql, Class<F> clazz, Object... params) { List<F> resultList; if (params != null && params.length > 0) { resultList = getJdbcTemplate().query(sql, params, new BeanPropertyRowMapper<>(clazz)); } else { // BeanPropertyRowMapper是自动映射实体类的 resultList = getJdbcTemplate().query(sql, new BeanPropertyRowMapper<>(clazz)); } return resultList; } /** * 执行查询sql,有查询条件,(固定返回List<Map<String, Object>>) * * @param sql 要执行的sql * @param params 要绑定到查询的参数 * @return Map<String, Object> */ @Override public List<Map<String, Object>> selectMap(String sql, Object... params) { return getJdbcTemplate().queryForList(sql, params); } /** * 执行查询sql,有查询条件,结果返回第一条(固定返回Map<String, Object>) * * @param sql 要执行的sql * @param params 要绑定到查询的参数 * @return Map<String, Object> */ @Override public Map<String, Object> selectOneMap(String sql, final Object... params) { List<Map<String, Object>> resultList = getJdbcTemplate().queryForList(sql, params); if (!CollectionUtils.isEmpty(resultList)) { return resultList.get(0); } return null; } /** * 查询一个值(经常用于查count) * * @param sql 要执行的SQL查询 * @param clazz 实体类 * @param params 要绑定到查询的参数 * @param <F> 泛型 * @return T */ @Override public <F> F selectOneColumn(String sql, Class<F> clazz, Object... params) { F result; if (params == null || params.length == 0) { result = getJdbcTemplate().queryForObject(sql, clazz); } else { result = getJdbcTemplate().queryForObject(sql, params, clazz); } return result; } /** * 分页查询 * * @param sql 要执行的SQL查询 * @param page 分页参数 * @return T */ @Override
package org.tinycloud.jdbc.support; /** * jdbc抽象类,给出默认的支持 * * @author liuxingyu01 * @since 2022-03-11-16:49 **/ public abstract class AbstractSqlSupport<T, ID> implements ISqlSupport<T, ID>, IObjectSupport<T, ID> { protected abstract JdbcTemplate getJdbcTemplate(); protected abstract IPageHandle getPageHandle(); /** * 泛型 */ private final Class<T> entityClass; /** * bean转换器 */ private final RowMapper<T> rowMapper; @SuppressWarnings("unchecked") public AbstractSqlSupport() { ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass(); entityClass = (Class<T>) type.getActualTypeArguments()[0]; rowMapper = BeanPropertyRowMapper.newInstance(entityClass); } /** * 执行查询sql,有查询条件 * * @param sql 要执行的SQL * @param params 要绑定到查询的参数 ,可以不传 * @return 查询结果 */ @Override public List<T> select(String sql, Object... params) { List<T> resultList; if (params != null && params.length > 0) { resultList = getJdbcTemplate().query(sql, params, rowMapper); } else { // BeanPropertyRowMapper是自动映射实体类的 resultList = getJdbcTemplate().query(sql, rowMapper); } return resultList; } /** * 执行查询sql,有查询条件 * * @param sql 要执行的SQL * @param clazz 实体类 * @param params 要绑定到查询的参数 ,可以不传 * @param <F> 泛型 * @return 查询结果 */ @Override public <F> List<F> select(String sql, Class<F> clazz, Object... params) { List<F> resultList; if (params != null && params.length > 0) { resultList = getJdbcTemplate().query(sql, params, new BeanPropertyRowMapper<>(clazz)); } else { // BeanPropertyRowMapper是自动映射实体类的 resultList = getJdbcTemplate().query(sql, new BeanPropertyRowMapper<>(clazz)); } return resultList; } /** * 执行查询sql,有查询条件,(固定返回List<Map<String, Object>>) * * @param sql 要执行的sql * @param params 要绑定到查询的参数 * @return Map<String, Object> */ @Override public List<Map<String, Object>> selectMap(String sql, Object... params) { return getJdbcTemplate().queryForList(sql, params); } /** * 执行查询sql,有查询条件,结果返回第一条(固定返回Map<String, Object>) * * @param sql 要执行的sql * @param params 要绑定到查询的参数 * @return Map<String, Object> */ @Override public Map<String, Object> selectOneMap(String sql, final Object... params) { List<Map<String, Object>> resultList = getJdbcTemplate().queryForList(sql, params); if (!CollectionUtils.isEmpty(resultList)) { return resultList.get(0); } return null; } /** * 查询一个值(经常用于查count) * * @param sql 要执行的SQL查询 * @param clazz 实体类 * @param params 要绑定到查询的参数 * @param <F> 泛型 * @return T */ @Override public <F> F selectOneColumn(String sql, Class<F> clazz, Object... params) { F result; if (params == null || params.length == 0) { result = getJdbcTemplate().queryForObject(sql, clazz); } else { result = getJdbcTemplate().queryForObject(sql, params, clazz); } return result; } /** * 分页查询 * * @param sql 要执行的SQL查询 * @param page 分页参数 * @return T */ @Override
public Page<T> paginate(String sql, Page<T> page) {
4
2023-10-25 14:44:59+00:00
24k
ansforge/SAMU-Hub-Modeles
src/main/java/com/hubsante/model/health/CreateCaseHealth.java
[ { "identifier": "AdditionalInformation", "path": "src/main/java/com/hubsante/model/health/AdditionalInformation.java", "snippet": "@JsonPropertyOrder({AdditionalInformation.JSON_PROPERTY_CUSTOM_MAP})\n@JsonTypeName(\"additionalInformation\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n\npublic class A...
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.dataformat.xml.annotation.*; import com.hubsante.model.health.AdditionalInformation; import com.hubsante.model.health.Alert; import com.hubsante.model.health.Location; import com.hubsante.model.health.MedicalAnalysis; import com.hubsante.model.health.Operator; import com.hubsante.model.health.Patient; import com.hubsante.model.health.Qualification; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Arrays; import java.util.List; import java.util.Objects;
15,387
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * 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. */ /* * * * * * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ package com.hubsante.model.health; /** * CreateCaseHealth */ @JsonPropertyOrder({CreateCaseHealth.JSON_PROPERTY_CASE_ID, CreateCaseHealth.JSON_PROPERTY_SENDER_CASE_ID, CreateCaseHealth.JSON_PROPERTY_CREATION, CreateCaseHealth.JSON_PROPERTY_REFERENCE_VERSION, CreateCaseHealth.JSON_PROPERTY_QUALIFICATION, CreateCaseHealth.JSON_PROPERTY_LOCATION, CreateCaseHealth.JSON_PROPERTY_INITIAL_ALERT, CreateCaseHealth.JSON_PROPERTY_OWNER, CreateCaseHealth.JSON_PROPERTY_OPERATOR, CreateCaseHealth.JSON_PROPERTY_PATIENT, CreateCaseHealth.JSON_PROPERTY_MEDICAL_ANALYSIS, CreateCaseHealth.JSON_PROPERTY_NEW_ALERT, CreateCaseHealth.JSON_PROPERTY_ADDITIONAL_INFORMATION, CreateCaseHealth.JSON_PROPERTY_FREETEXT}) @JsonTypeName("createCaseHealth") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class CreateCaseHealth { public static final String JSON_PROPERTY_CASE_ID = "caseId"; private String caseId; public static final String JSON_PROPERTY_SENDER_CASE_ID = "senderCaseId"; private String senderCaseId; public static final String JSON_PROPERTY_CREATION = "creation"; private OffsetDateTime creation; public static final String JSON_PROPERTY_REFERENCE_VERSION = "referenceVersion"; private String referenceVersion; public static final String JSON_PROPERTY_QUALIFICATION = "qualification"; private Qualification qualification; public static final String JSON_PROPERTY_LOCATION = "location"; private Location location; public static final String JSON_PROPERTY_INITIAL_ALERT = "initialAlert"; private Alert initialAlert; public static final String JSON_PROPERTY_OWNER = "owner"; private String owner; public static final String JSON_PROPERTY_OPERATOR = "operator"; private List<Operator> operator; public static final String JSON_PROPERTY_PATIENT = "patient"; private List<Patient> patient; public static final String JSON_PROPERTY_MEDICAL_ANALYSIS = "medicalAnalysis"; private List<MedicalAnalysis> medicalAnalysis; public static final String JSON_PROPERTY_NEW_ALERT = "newAlert"; private List<Alert> newAlert; public static final String JSON_PROPERTY_ADDITIONAL_INFORMATION = "additionalInformation";
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * 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. */ /* * * * * * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ package com.hubsante.model.health; /** * CreateCaseHealth */ @JsonPropertyOrder({CreateCaseHealth.JSON_PROPERTY_CASE_ID, CreateCaseHealth.JSON_PROPERTY_SENDER_CASE_ID, CreateCaseHealth.JSON_PROPERTY_CREATION, CreateCaseHealth.JSON_PROPERTY_REFERENCE_VERSION, CreateCaseHealth.JSON_PROPERTY_QUALIFICATION, CreateCaseHealth.JSON_PROPERTY_LOCATION, CreateCaseHealth.JSON_PROPERTY_INITIAL_ALERT, CreateCaseHealth.JSON_PROPERTY_OWNER, CreateCaseHealth.JSON_PROPERTY_OPERATOR, CreateCaseHealth.JSON_PROPERTY_PATIENT, CreateCaseHealth.JSON_PROPERTY_MEDICAL_ANALYSIS, CreateCaseHealth.JSON_PROPERTY_NEW_ALERT, CreateCaseHealth.JSON_PROPERTY_ADDITIONAL_INFORMATION, CreateCaseHealth.JSON_PROPERTY_FREETEXT}) @JsonTypeName("createCaseHealth") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class CreateCaseHealth { public static final String JSON_PROPERTY_CASE_ID = "caseId"; private String caseId; public static final String JSON_PROPERTY_SENDER_CASE_ID = "senderCaseId"; private String senderCaseId; public static final String JSON_PROPERTY_CREATION = "creation"; private OffsetDateTime creation; public static final String JSON_PROPERTY_REFERENCE_VERSION = "referenceVersion"; private String referenceVersion; public static final String JSON_PROPERTY_QUALIFICATION = "qualification"; private Qualification qualification; public static final String JSON_PROPERTY_LOCATION = "location"; private Location location; public static final String JSON_PROPERTY_INITIAL_ALERT = "initialAlert"; private Alert initialAlert; public static final String JSON_PROPERTY_OWNER = "owner"; private String owner; public static final String JSON_PROPERTY_OPERATOR = "operator"; private List<Operator> operator; public static final String JSON_PROPERTY_PATIENT = "patient"; private List<Patient> patient; public static final String JSON_PROPERTY_MEDICAL_ANALYSIS = "medicalAnalysis"; private List<MedicalAnalysis> medicalAnalysis; public static final String JSON_PROPERTY_NEW_ALERT = "newAlert"; private List<Alert> newAlert; public static final String JSON_PROPERTY_ADDITIONAL_INFORMATION = "additionalInformation";
private AdditionalInformation additionalInformation;
0
2023-10-25 14:24:31+00:00
24k
yaroslav318/shop-telegram-bot
telegram-bot/src/main/java/ua/ivanzaitsev/bot/Application.java
[ { "identifier": "ConfigReader", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/core/ConfigReader.java", "snippet": "public class ConfigReader {\n\n private static final ConfigReader INSTANCE = new ConfigReader();\n\n private final Properties properties;\n\n private ConfigReader() {\n ...
import java.util.ArrayList; import java.util.List; import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.updatesreceivers.DefaultBotSession; import ua.ivanzaitsev.bot.core.ConfigReader; import ua.ivanzaitsev.bot.core.TelegramBot; import ua.ivanzaitsev.bot.handlers.ActionHandler; import ua.ivanzaitsev.bot.handlers.CommandHandler; import ua.ivanzaitsev.bot.handlers.UpdateHandler; import ua.ivanzaitsev.bot.handlers.commands.CartCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.CatalogCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderConfirmCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterAddressCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterCityCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterNameCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterPhoneNumberCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderStepCancelCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderStepPreviousCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.StartCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.registries.CommandHandlerRegistry; import ua.ivanzaitsev.bot.handlers.commands.registries.CommandHandlerRegistryDefault; import ua.ivanzaitsev.bot.repositories.CartRepository; import ua.ivanzaitsev.bot.repositories.CategoryRepository; import ua.ivanzaitsev.bot.repositories.ClientActionRepository; import ua.ivanzaitsev.bot.repositories.ClientCommandStateRepository; import ua.ivanzaitsev.bot.repositories.ClientOrderStateRepository; import ua.ivanzaitsev.bot.repositories.ClientRepository; import ua.ivanzaitsev.bot.repositories.OrderRepository; import ua.ivanzaitsev.bot.repositories.ProductRepository; import ua.ivanzaitsev.bot.repositories.database.CategoryRepositoryDefault; import ua.ivanzaitsev.bot.repositories.database.ClientRepositoryDefault; import ua.ivanzaitsev.bot.repositories.database.OrderRepositoryDefault; import ua.ivanzaitsev.bot.repositories.database.ProductRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.CartRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.ClientActionRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.ClientCommandStateRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.ClientOrderStateRepositoryDefault; import ua.ivanzaitsev.bot.services.MessageService; import ua.ivanzaitsev.bot.services.NotificationService; import ua.ivanzaitsev.bot.services.impl.MessageServiceDefault; import ua.ivanzaitsev.bot.services.impl.NotificationServiceDefault;
18,795
package ua.ivanzaitsev.bot; public class Application { private ConfigReader configReader = ConfigReader.getInstance(); private ClientActionRepository clientActionRepository; private ClientCommandStateRepository clientCommandStateRepository; private ClientOrderStateRepository clientOrderStateRepository;
package ua.ivanzaitsev.bot; public class Application { private ConfigReader configReader = ConfigReader.getInstance(); private ClientActionRepository clientActionRepository; private ClientCommandStateRepository clientCommandStateRepository; private ClientOrderStateRepository clientOrderStateRepository;
private CartRepository cartRepository;
17
2023-10-29 15:49:41+00:00
24k
Java-Game-Engine-Merger/Libgdx-Processing
framework/src/main/java/pama1234/gdx/util/app/UtilScreen.java
[ { "identifier": "TextField", "path": "framework/src/main/java/pama1234/gdx/game/ui/element/TextField.java", "snippet": "public class TextField extends Widget implements Disableable{\n protected static final char BACKSPACE=8;\n protected static final char CARRIAGE_RETURN='\\r';\n protected static fina...
import pama1234.gdx.game.ui.element.TextField; import pama1234.gdx.util.SharedResources; import pama1234.gdx.util.cam.CameraController; import pama1234.gdx.util.info.MouseInfo; import pama1234.gdx.util.info.TouchInfo; import pama1234.gdx.util.input.UtilInputProcesser; import pama1234.gdx.util.listener.EntityListener; import pama1234.gdx.util.listener.EntityNeoListener; import pama1234.gdx.util.wrapper.AutoEntityManager; import pama1234.gdx.util.wrapper.EntityCenter; import pama1234.gdx.util.wrapper.EntityNeoCenter; import pama1234.gdx.util.wrapper.ScreenContentContainer; import pama1234.util.wrapper.Center; import pama1234.util.wrapper.ServerEntityCenter; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.scenes.scene2d.Group; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.IntArray; import com.badlogic.gdx.utils.Scaling; import com.badlogic.gdx.utils.viewport.ScalingViewport; import hhs.gdx.hslib.tools.LoopThread;
18,648
package pama1234.gdx.util.app; /** * 此中间类主要放渲染相关的东东 * * @see UtilScreen2D * @see UtilScreen3D */ public abstract class UtilScreen extends UtilScreenRender{ public void createRenderUtil() { fontBatch=SharedResources.instance.fontBatch; font=SharedResources.instance.font; font.fontBatch=fontBatch; font.styleFast=fontStyle; textColor=new Color(0,0,0,1); font.color(textColor); fillColor=new Color(1,1,1,1); strokeColor=new Color(0,0,0,1); rFill=SharedResources.instance.rFill; rStroke=SharedResources.instance.rStroke; rFill.setColor(fillColor); rStroke.setColor(strokeColor); pFill=SharedResources.instance.pFill; pFill.setColor(fillColor); } public void createInputUtil() { vectorCache=new Vector3(); mouse=new MouseInfo(this); for(int i=0;i<touches.length;i++) touches[i]=new TouchInfo(this); keyPressedArray=new IntArray(false,12); backgroundColor=new Color(1,1,1,0); } //--------------------------------------------------------------------------- public void preInit() { screenCam=new OrthographicCamera(); imageBatch=SharedResources.instance.imageBatch; tvgDrawer=SharedResources.instance.tvgDrawer; Gdx.input.setInputProcessor(inputProcessor=new UtilInputProcesser(this)); // TODO serverCenter=new ServerEntityCenter<>(null); centerSys=new Center<>(); center=new EntityCenter<>(this); center.list.add(cam=createCamera()); centerSys.list.add(cam); // TOOD update顺序,centerScreen应当先于centerCam center.list.add(centerScreen=new EntityCenter<>(this)); center.list.add(centerCam=new EntityCenter<>(this)); center.list.add(centerNeo=new EntityNeoCenter<>(this)); screenStage=new Stage(screenViewport=new ScalingViewport(Scaling.fit,width,height,screenCam),imageBatch); camStage=new Stage(camViewport=new ScalingViewport(Scaling.fit,width,height,cam.camera),imageBatch); inputProcessor.sub.add.add(screenStage); inputProcessor.sub.add.add(camStage); center.list.add(new EntityListener() { @Override public void update() { screenStage.act(); camStage.act(); } @Override public void mousePressed(MouseInfo info) { screenStage.setKeyboardFocus(null); camStage.setKeyboardFocus(null); } @Override public void frameResized(int w,int h) { bu=pus*24; screenViewport.setWorldSize(width,height); screenViewport.update(width,height); camViewport.setWorldSize(width,height); camViewport.update(width,height); } }); centerScreen.list.add(new EntityListener() { @Override public void display() { screenStage.draw(); } }); centerCam.list.add(new EntityListener() { @Override public void display() { camStage.draw(); } });
package pama1234.gdx.util.app; /** * 此中间类主要放渲染相关的东东 * * @see UtilScreen2D * @see UtilScreen3D */ public abstract class UtilScreen extends UtilScreenRender{ public void createRenderUtil() { fontBatch=SharedResources.instance.fontBatch; font=SharedResources.instance.font; font.fontBatch=fontBatch; font.styleFast=fontStyle; textColor=new Color(0,0,0,1); font.color(textColor); fillColor=new Color(1,1,1,1); strokeColor=new Color(0,0,0,1); rFill=SharedResources.instance.rFill; rStroke=SharedResources.instance.rStroke; rFill.setColor(fillColor); rStroke.setColor(strokeColor); pFill=SharedResources.instance.pFill; pFill.setColor(fillColor); } public void createInputUtil() { vectorCache=new Vector3(); mouse=new MouseInfo(this); for(int i=0;i<touches.length;i++) touches[i]=new TouchInfo(this); keyPressedArray=new IntArray(false,12); backgroundColor=new Color(1,1,1,0); } //--------------------------------------------------------------------------- public void preInit() { screenCam=new OrthographicCamera(); imageBatch=SharedResources.instance.imageBatch; tvgDrawer=SharedResources.instance.tvgDrawer; Gdx.input.setInputProcessor(inputProcessor=new UtilInputProcesser(this)); // TODO serverCenter=new ServerEntityCenter<>(null); centerSys=new Center<>(); center=new EntityCenter<>(this); center.list.add(cam=createCamera()); centerSys.list.add(cam); // TOOD update顺序,centerScreen应当先于centerCam center.list.add(centerScreen=new EntityCenter<>(this)); center.list.add(centerCam=new EntityCenter<>(this)); center.list.add(centerNeo=new EntityNeoCenter<>(this)); screenStage=new Stage(screenViewport=new ScalingViewport(Scaling.fit,width,height,screenCam),imageBatch); camStage=new Stage(camViewport=new ScalingViewport(Scaling.fit,width,height,cam.camera),imageBatch); inputProcessor.sub.add.add(screenStage); inputProcessor.sub.add.add(camStage); center.list.add(new EntityListener() { @Override public void update() { screenStage.act(); camStage.act(); } @Override public void mousePressed(MouseInfo info) { screenStage.setKeyboardFocus(null); camStage.setKeyboardFocus(null); } @Override public void frameResized(int w,int h) { bu=pus*24; screenViewport.setWorldSize(width,height); screenViewport.update(width,height); camViewport.setWorldSize(width,height); camViewport.update(width,height); } }); centerScreen.list.add(new EntityListener() { @Override public void display() { screenStage.draw(); } }); centerCam.list.add(new EntityListener() { @Override public void display() { camStage.draw(); } });
auto=new AutoEntityManager<UtilScreen>(this);
8
2023-10-27 05:47:39+00:00
24k
danielbatres/orthodontic-dentistry-clinical-management
src/com/view/readPct/ModifyConsulta.java
[ { "identifier": "ApplicationContext", "path": "src/com/context/ApplicationContext.java", "snippet": "public class ApplicationContext {\r\n public static SesionUsuario sesionUsuario;\r\n public static LoadingApp loading = new LoadingApp();\r\n public static LoadingApplication loadingApplication ...
import com.context.ApplicationContext; import com.context.ChoosedPalette; import com.helper.ConsultasHelper; import com.model.ConsultaModel; import com.utils.Styles; import com.utils.Tools; import com.view.createPacient.NewContext; import static com.view.createPacient.NewContext.dateTimeFormatter; import static com.view.readPct.AgendaContext.validateCombo; import static com.view.readPct.AgendaContext.validateComplete; import static com.view.readPct.AgendaContext.validateHour; import java.time.LocalDateTime;
17,472
.addComponent(title5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(advertenciaHora, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(container5, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(9, Short.MAX_VALUE))) ); jPanel10.add(jPanel16); jPanel18.setOpaque(false); tratamientoCombo.setBackground(new java.awt.Color(255, 255, 255)); tratamientoCombo.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N tratamientoCombo.setBorder(null); tratamientoCombo.setFocusable(false); tratamientoCombo.setOpaque(false); tratamientoCombo.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { tratamientoComboItemStateChanged(evt); } }); tratamientoCombo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tratamientoComboActionPerformed(evt); } }); title6.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N title6.setForeground(new java.awt.Color(0, 0, 0)); title6.setText("Tratamientos"); advertenciaCombo.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 10)); // NOI18N advertenciaCombo.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); javax.swing.GroupLayout jPanel18Layout = new javax.swing.GroupLayout(jPanel18); jPanel18.setLayout(jPanel18Layout); jPanel18Layout.setHorizontalGroup( jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel18Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tratamientoCombo, 0, 263, Short.MAX_VALUE) .addGroup(jPanel18Layout.createSequentialGroup() .addComponent(title6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(advertenciaCombo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); jPanel18Layout.setVerticalGroup( jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel18Layout.createSequentialGroup() .addGap(12, 12, 12) .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(title6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(advertenciaCombo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tratamientoCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel10.add(jPanel18); javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9); jPanel9.setLayout(jPanel9Layout); jPanel9Layout.setHorizontalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel9Layout.setVerticalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 57, Short.MAX_VALUE)) ); jPanel7.add(jPanel9, java.awt.BorderLayout.CENTER); jPanel1.add(jPanel7); jPanel6.setOpaque(false); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 199, Short.MAX_VALUE) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 397, Short.MAX_VALUE) ); jPanel1.add(jPanel6); jPanel4.add(jPanel1, java.awt.BorderLayout.CENTER); add(jPanel4, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void textField1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textField1KeyTyped }//GEN-LAST:event_textField1KeyTyped private void textField2KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textField2KeyTyped // TODO add your handling code here: }//GEN-LAST:event_textField2KeyTyped private void textField3KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textField3KeyTyped // TODO add your handling code here: }//GEN-LAST:event_textField3KeyTyped private void saveButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveButtonMouseClicked validateComplete(container1, textField1, advertenciaDia, 31); validateComplete(container2, textField2, advertenciaMes, 12); validateComplete(container3, textField3, advertenciaAnnio, 10000); validateHour(container5, textField4, advertenciaHora); validateCombo(tratamientoCombo, advertenciaCombo); if (AgendaContext.countedErrors == 0) { ConsultasHelper.updateConsulta(devolverDatos());
package com.view.readPct; /** * * @author Daniel Batres * @version 1.0.0 * @since 2/10/22 */ public class ModifyConsulta extends Styles { private int idConsulta; /** * Creates new form ModificarConsulta */ public ModifyConsulta() { initComponents(); styleMyComponentBaby(); } private ConsultaModel devolverDatos() { ConsultaModel consultaModel = new ConsultaModel(); try { consultaModel.setId(idConsulta); consultaModel.setDiaDeConsulta(Integer.parseInt(textField1.getText())); consultaModel.setMesDeConsulta(Integer.parseInt(textField2.getText())); consultaModel.setAnnioDeConsulta(Integer.parseInt(textField3.getText())); consultaModel.setHoraDeConsulta(textField4.getText()); consultaModel.setConsultaRealizada(false); consultaModel.setTratamientoDeConsulta(tratamientoCombo.getSelectedItem().toString()); consultaModel.setDiaModificacion(LocalDateTime.now().getDayOfMonth()); consultaModel.setMesModificacion(LocalDateTime.now().getMonthValue()); consultaModel.setAnnioModificacion(LocalDateTime.now().getYear()); consultaModel.setHoraModificacion(String.valueOf(LocalDateTime.now().getHour()) + ":" + String.valueOf(LocalDateTime.now().getMinute()) + " " + NewContext.localTime.format(dateTimeFormatter)); } catch (NumberFormatException e) { System.out.println(e); return null; } return consultaModel; } public void setData(ConsultaModel consulta) { idConsulta = consulta.getId(); textField1.setText(String.valueOf(consulta.getDiaDeConsulta())); textField2.setText(String.valueOf(consulta.getMesDeConsulta())); textField3.setText(String.valueOf(consulta.getAnnioDeConsulta())); textField4.setText(consulta.getHoraDeConsulta()); switch (consulta.getTratamientoDeConsulta()) { case "Odontolog\u00eda": tratamientoCombo.setSelectedIndex(1); break; case "Ortodoncia": tratamientoCombo.setSelectedIndex(2); break; } } private void addItems() { tratamientoCombo.addItem("Elegir tratamiento"); tratamientoCombo.addItem("Odontolog\u00eda"); tratamientoCombo.addItem("Ortodoncia"); } @Override public void addTitlesAndSubtitles() { TITLES_AND_SUBTITLES.add(title1); TITLES_AND_SUBTITLES.add(title2); TITLES_AND_SUBTITLES.add(title3); TITLES_AND_SUBTITLES.add(title4); TITLES_AND_SUBTITLES.add(title5); TITLES_AND_SUBTITLES.add(title6); } @Override public void addPlainText() { PLAIN_TEXT.add(text1); } @Override public void addContainers() { CONTAINERS.add(container); CONTAINERS.add(container1); CONTAINERS.add(container2); CONTAINERS.add(container3); CONTAINERS.add(container5); } @Override public void addTextFields() { TEXTFIELDS.add(textField1); TEXTFIELDS.add(textField2); TEXTFIELDS.add(textField3); TEXTFIELDS.add(textField4); } @Override public void colorBasics() { paintAll(); paintOneContainer(saveButton, ChoosedPalette.getMidColor()); paintOneContainer(cancelButton, ChoosedPalette.getMidColor()); cancel.setForeground(ChoosedPalette.getMidColor()); } @Override public void initStyles(){ addItems(); informationIcon.setSize(50, 50); Tools.addMouseListenerIngresa(TEXTFIELDS); Tools.setImageLabel(informationIcon, "src/com/assets/documento.png", 25, 25, ChoosedPalette.getWhite()); } @Override public void dark() { paintAll(); paintOneContainer(container, ChoosedPalette.getSecondaryBackground()); } @Override public void addComboBox() { COMBOBOX.add(tratamientoCombo); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel13 = new javax.swing.JPanel(); jPanel14 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); container = new com.k33ptoo.components.KGradientPanel(); jPanel30 = new javax.swing.JPanel(); jPanel31 = new javax.swing.JPanel(); jPanel32 = new javax.swing.JPanel(); jPanel33 = new javax.swing.JPanel(); jPanel17 = new javax.swing.JPanel(); saveButton = new com.k33ptoo.components.KGradientPanel(); jLabel3 = new javax.swing.JLabel(); cancelButton = new com.k33ptoo.components.KGradientPanel(); cancel = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jPanel8 = new javax.swing.JPanel(); text1 = new javax.swing.JLabel(); title1 = new javax.swing.JLabel(); kGradientPanel3 = new com.k33ptoo.components.KGradientPanel(); informationIcon = new javax.swing.JLabel(); jPanel9 = new javax.swing.JPanel(); jPanel10 = new javax.swing.JPanel(); jPanel11 = new javax.swing.JPanel(); container1 = new com.k33ptoo.components.KGradientPanel(); jPanel44 = new javax.swing.JPanel(); jPanel45 = new javax.swing.JPanel(); textField1 = new javax.swing.JTextField(); title2 = new javax.swing.JLabel(); advertenciaDia = new javax.swing.JLabel(); jPanel12 = new javax.swing.JPanel(); container2 = new com.k33ptoo.components.KGradientPanel(); jPanel46 = new javax.swing.JPanel(); jPanel47 = new javax.swing.JPanel(); textField2 = new javax.swing.JTextField(); title3 = new javax.swing.JLabel(); advertenciaMes = new javax.swing.JLabel(); jPanel15 = new javax.swing.JPanel(); container3 = new com.k33ptoo.components.KGradientPanel(); jPanel48 = new javax.swing.JPanel(); jPanel49 = new javax.swing.JPanel(); textField3 = new javax.swing.JTextField(); title4 = new javax.swing.JLabel(); advertenciaAnnio = new javax.swing.JLabel(); jPanel16 = new javax.swing.JPanel(); advertenciaGenero = new javax.swing.JLabel(); container5 = new com.k33ptoo.components.KGradientPanel(); jPanel51 = new javax.swing.JPanel(); jPanel52 = new javax.swing.JPanel(); textField4 = new javax.swing.JTextField(); title5 = new javax.swing.JLabel(); advertenciaHora = new javax.swing.JLabel(); jPanel18 = new javax.swing.JPanel(); tratamientoCombo = new javax.swing.JComboBox<>(); title6 = new javax.swing.JLabel(); advertenciaCombo = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); setMinimumSize(new java.awt.Dimension(976, 522)); setOpaque(false); setLayout(new java.awt.BorderLayout()); jPanel13.setBackground(new java.awt.Color(255, 255, 255)); jPanel13.setMinimumSize(new java.awt.Dimension(14, 0)); jPanel13.setOpaque(false); jPanel13.setPreferredSize(new java.awt.Dimension(14, 35)); javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13); jPanel13.setLayout(jPanel13Layout); jPanel13Layout.setHorizontalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); jPanel13Layout.setVerticalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 477, Short.MAX_VALUE) ); add(jPanel13, java.awt.BorderLayout.LINE_END); jPanel14.setBackground(new java.awt.Color(255, 255, 255)); jPanel14.setMinimumSize(new java.awt.Dimension(14, 0)); jPanel14.setOpaque(false); jPanel14.setPreferredSize(new java.awt.Dimension(14, 35)); javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14); jPanel14.setLayout(jPanel14Layout); jPanel14Layout.setHorizontalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); jPanel14Layout.setVerticalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 477, Short.MAX_VALUE) ); add(jPanel14, java.awt.BorderLayout.LINE_START); jPanel2.setBackground(new java.awt.Color(255, 255, 255)); jPanel2.setMinimumSize(new java.awt.Dimension(100, 20)); jPanel2.setOpaque(false); jPanel2.setPreferredSize(new java.awt.Dimension(976, 20)); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 977, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 20, Short.MAX_VALUE) ); add(jPanel2, java.awt.BorderLayout.PAGE_END); jPanel3.setBackground(new java.awt.Color(255, 255, 255)); jPanel3.setMinimumSize(new java.awt.Dimension(100, 25)); jPanel3.setOpaque(false); jPanel3.setPreferredSize(new java.awt.Dimension(976, 25)); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 977, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 25, Short.MAX_VALUE) ); add(jPanel3, java.awt.BorderLayout.PAGE_START); jPanel4.setOpaque(false); jPanel4.setLayout(new java.awt.BorderLayout()); container.setkEndColor(new java.awt.Color(204, 204, 204)); container.setkFillBackground(false); container.setkStartColor(new java.awt.Color(204, 204, 204)); container.setMinimumSize(new java.awt.Dimension(28, 80)); container.setOpaque(false); container.setPreferredSize(new java.awt.Dimension(949, 80)); container.setLayout(new java.awt.BorderLayout()); jPanel30.setBackground(new java.awt.Color(255, 255, 255)); jPanel30.setMinimumSize(new java.awt.Dimension(14, 100)); jPanel30.setOpaque(false); jPanel30.setPreferredSize(new java.awt.Dimension(14, 150)); javax.swing.GroupLayout jPanel30Layout = new javax.swing.GroupLayout(jPanel30); jPanel30.setLayout(jPanel30Layout); jPanel30Layout.setHorizontalGroup( jPanel30Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); jPanel30Layout.setVerticalGroup( jPanel30Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); container.add(jPanel30, java.awt.BorderLayout.LINE_END); jPanel31.setBackground(new java.awt.Color(255, 255, 255)); jPanel31.setMinimumSize(new java.awt.Dimension(14, 100)); jPanel31.setOpaque(false); jPanel31.setPreferredSize(new java.awt.Dimension(14, 150)); javax.swing.GroupLayout jPanel31Layout = new javax.swing.GroupLayout(jPanel31); jPanel31.setLayout(jPanel31Layout); jPanel31Layout.setHorizontalGroup( jPanel31Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); jPanel31Layout.setVerticalGroup( jPanel31Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); container.add(jPanel31, java.awt.BorderLayout.LINE_START); jPanel32.setBackground(new java.awt.Color(255, 255, 255)); jPanel32.setMinimumSize(new java.awt.Dimension(14, 14)); jPanel32.setOpaque(false); javax.swing.GroupLayout jPanel32Layout = new javax.swing.GroupLayout(jPanel32); jPanel32.setLayout(jPanel32Layout); jPanel32Layout.setHorizontalGroup( jPanel32Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 949, Short.MAX_VALUE) ); jPanel32Layout.setVerticalGroup( jPanel32Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); container.add(jPanel32, java.awt.BorderLayout.PAGE_END); jPanel33.setBackground(new java.awt.Color(255, 255, 255)); jPanel33.setMinimumSize(new java.awt.Dimension(14, 14)); jPanel33.setOpaque(false); javax.swing.GroupLayout jPanel33Layout = new javax.swing.GroupLayout(jPanel33); jPanel33.setLayout(jPanel33Layout); jPanel33Layout.setHorizontalGroup( jPanel33Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 949, Short.MAX_VALUE) ); jPanel33Layout.setVerticalGroup( jPanel33Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); container.add(jPanel33, java.awt.BorderLayout.PAGE_START); jPanel17.setOpaque(false); saveButton.setkEndColor(new java.awt.Color(0, 0, 0)); saveButton.setkStartColor(new java.awt.Color(0, 0, 0)); saveButton.setOpaque(false); saveButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { saveButtonMouseClicked(evt); } }); jLabel3.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("Guardar"); jLabel3.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); javax.swing.GroupLayout saveButtonLayout = new javax.swing.GroupLayout(saveButton); saveButton.setLayout(saveButtonLayout); saveButtonLayout.setHorizontalGroup( saveButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(saveButtonLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE) .addContainerGap()) ); saveButtonLayout.setVerticalGroup( saveButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(saveButtonLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) .addContainerGap()) ); cancelButton.setkEndColor(new java.awt.Color(0, 0, 0)); cancelButton.setkFillBackground(false); cancelButton.setkStartColor(new java.awt.Color(0, 0, 0)); cancelButton.setOpaque(false); cancelButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { cancelButtonMouseClicked(evt); } }); cancel.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N cancel.setForeground(new java.awt.Color(255, 255, 255)); cancel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); cancel.setText("Cancelar"); cancel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); javax.swing.GroupLayout cancelButtonLayout = new javax.swing.GroupLayout(cancelButton); cancelButton.setLayout(cancelButtonLayout); cancelButtonLayout.setHorizontalGroup( cancelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(cancelButtonLayout.createSequentialGroup() .addContainerGap() .addComponent(cancel, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE) .addContainerGap()) ); cancelButtonLayout.setVerticalGroup( cancelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(cancelButtonLayout.createSequentialGroup() .addContainerGap() .addComponent(cancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout jPanel17Layout = new javax.swing.GroupLayout(jPanel17); jPanel17.setLayout(jPanel17Layout); jPanel17Layout.setHorizontalGroup( jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel17Layout.createSequentialGroup() .addContainerGap(537, Short.MAX_VALUE) .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel17Layout.setVerticalGroup( jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(saveButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(cancelButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); container.add(jPanel17, java.awt.BorderLayout.CENTER); jPanel4.add(container, java.awt.BorderLayout.PAGE_END); jPanel1.setOpaque(false); jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.LINE_AXIS)); jPanel5.setOpaque(false); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 199, Short.MAX_VALUE) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 397, Short.MAX_VALUE) ); jPanel1.add(jPanel5); jPanel7.setMaximumSize(new java.awt.Dimension(550, 2147483647)); jPanel7.setMinimumSize(new java.awt.Dimension(550, 100)); jPanel7.setOpaque(false); jPanel7.setPreferredSize(new java.awt.Dimension(550, 382)); jPanel7.setLayout(new java.awt.BorderLayout()); jPanel8.setMinimumSize(new java.awt.Dimension(80, 80)); jPanel8.setOpaque(false); jPanel8.setPreferredSize(new java.awt.Dimension(616, 80)); text1.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N text1.setForeground(new java.awt.Color(153, 153, 153)); text1.setText("Edita la información de esta consulta"); title1.setBackground(new java.awt.Color(0, 0, 0)); title1.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 18)); // NOI18N title1.setForeground(new java.awt.Color(0, 0, 0)); title1.setText("Modificar consulta"); kGradientPanel3.setkBorderRadius(100); kGradientPanel3.setkEndColor(new java.awt.Color(69, 98, 255)); kGradientPanel3.setkStartColor(new java.awt.Color(69, 98, 255)); kGradientPanel3.setMaximumSize(new java.awt.Dimension(50, 50)); kGradientPanel3.setMinimumSize(new java.awt.Dimension(50, 50)); kGradientPanel3.setOpaque(false); kGradientPanel3.setLayout(new java.awt.BorderLayout()); informationIcon.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); kGradientPanel3.add(informationIcon, java.awt.BorderLayout.CENTER); javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8); jPanel8.setLayout(jPanel8Layout); jPanel8Layout.setHorizontalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel8Layout.createSequentialGroup() .addContainerGap() .addComponent(kGradientPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel8Layout.createSequentialGroup() .addComponent(title1, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 217, Short.MAX_VALUE)) .addComponent(text1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel8Layout.setVerticalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel8Layout.createSequentialGroup() .addGap(9, 9, 9) .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(kGradientPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel8Layout.createSequentialGroup() .addComponent(title1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(text1))) .addContainerGap(21, Short.MAX_VALUE)) ); jPanel7.add(jPanel8, java.awt.BorderLayout.PAGE_START); jPanel9.setOpaque(false); jPanel10.setOpaque(false); jPanel10.setLayout(new java.awt.GridLayout(3, 2)); jPanel11.setOpaque(false); container1.setkEndColor(new java.awt.Color(204, 204, 204)); container1.setkFillBackground(false); container1.setkStartColor(new java.awt.Color(204, 204, 204)); container1.setMaximumSize(new java.awt.Dimension(32767, 45)); container1.setMinimumSize(new java.awt.Dimension(100, 45)); container1.setOpaque(false); container1.setLayout(new java.awt.BorderLayout()); jPanel44.setMaximumSize(new java.awt.Dimension(5, 32767)); jPanel44.setMinimumSize(new java.awt.Dimension(5, 100)); jPanel44.setOpaque(false); jPanel44.setPreferredSize(new java.awt.Dimension(5, 45)); javax.swing.GroupLayout jPanel44Layout = new javax.swing.GroupLayout(jPanel44); jPanel44.setLayout(jPanel44Layout); jPanel44Layout.setHorizontalGroup( jPanel44Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 5, Short.MAX_VALUE) ); jPanel44Layout.setVerticalGroup( jPanel44Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); container1.add(jPanel44, java.awt.BorderLayout.LINE_END); jPanel45.setMaximumSize(new java.awt.Dimension(10, 32767)); jPanel45.setMinimumSize(new java.awt.Dimension(10, 100)); jPanel45.setOpaque(false); jPanel45.setPreferredSize(new java.awt.Dimension(10, 45)); javax.swing.GroupLayout jPanel45Layout = new javax.swing.GroupLayout(jPanel45); jPanel45.setLayout(jPanel45Layout); jPanel45Layout.setHorizontalGroup( jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); jPanel45Layout.setVerticalGroup( jPanel45Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); container1.add(jPanel45, java.awt.BorderLayout.LINE_START); textField1.setBackground(new java.awt.Color(255, 255, 255)); textField1.setText("Ingresar dia de la consulta"); textField1.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(204, 204, 204))); textField1.setOpaque(false); textField1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { textField1KeyTyped(evt); } }); container1.add(textField1, java.awt.BorderLayout.CENTER); title2.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N title2.setForeground(new java.awt.Color(0, 0, 0)); title2.setText("Dia"); advertenciaDia.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 10)); // NOI18N advertenciaDia.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11); jPanel11.setLayout(jPanel11Layout); jPanel11Layout.setHorizontalGroup( jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel11Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(container1, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE) .addGroup(jPanel11Layout.createSequentialGroup() .addComponent(title2) .addGap(18, 18, 18) .addComponent(advertenciaDia, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); jPanel11Layout.setVerticalGroup( jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel11Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(title2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(advertenciaDia, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(container1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel10.add(jPanel11); jPanel12.setOpaque(false); container2.setkEndColor(new java.awt.Color(204, 204, 204)); container2.setkFillBackground(false); container2.setkStartColor(new java.awt.Color(204, 204, 204)); container2.setMaximumSize(new java.awt.Dimension(32767, 45)); container2.setMinimumSize(new java.awt.Dimension(100, 45)); container2.setOpaque(false); container2.setLayout(new java.awt.BorderLayout()); jPanel46.setMaximumSize(new java.awt.Dimension(5, 32767)); jPanel46.setMinimumSize(new java.awt.Dimension(5, 100)); jPanel46.setOpaque(false); jPanel46.setPreferredSize(new java.awt.Dimension(5, 45)); javax.swing.GroupLayout jPanel46Layout = new javax.swing.GroupLayout(jPanel46); jPanel46.setLayout(jPanel46Layout); jPanel46Layout.setHorizontalGroup( jPanel46Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 5, Short.MAX_VALUE) ); jPanel46Layout.setVerticalGroup( jPanel46Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); container2.add(jPanel46, java.awt.BorderLayout.LINE_END); jPanel47.setMaximumSize(new java.awt.Dimension(10, 32767)); jPanel47.setMinimumSize(new java.awt.Dimension(10, 100)); jPanel47.setOpaque(false); jPanel47.setPreferredSize(new java.awt.Dimension(10, 45)); javax.swing.GroupLayout jPanel47Layout = new javax.swing.GroupLayout(jPanel47); jPanel47.setLayout(jPanel47Layout); jPanel47Layout.setHorizontalGroup( jPanel47Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); jPanel47Layout.setVerticalGroup( jPanel47Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); container2.add(jPanel47, java.awt.BorderLayout.LINE_START); textField2.setBackground(new java.awt.Color(255, 255, 255)); textField2.setText("Ingresar mes de la consulta"); textField2.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(204, 204, 204))); textField2.setOpaque(false); textField2.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { textField2KeyTyped(evt); } }); container2.add(textField2, java.awt.BorderLayout.CENTER); title3.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N title3.setForeground(new java.awt.Color(0, 0, 0)); title3.setText("Mes"); advertenciaMes.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 10)); // NOI18N advertenciaMes.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12); jPanel12.setLayout(jPanel12Layout); jPanel12Layout.setHorizontalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel12Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(container2, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE) .addGroup(jPanel12Layout.createSequentialGroup() .addComponent(title3) .addGap(18, 18, 18) .addComponent(advertenciaMes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); jPanel12Layout.setVerticalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel12Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(title3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(advertenciaMes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(container2, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel10.add(jPanel12); jPanel15.setOpaque(false); container3.setkEndColor(new java.awt.Color(204, 204, 204)); container3.setkFillBackground(false); container3.setkStartColor(new java.awt.Color(204, 204, 204)); container3.setMaximumSize(new java.awt.Dimension(32767, 45)); container3.setMinimumSize(new java.awt.Dimension(100, 45)); container3.setOpaque(false); container3.setLayout(new java.awt.BorderLayout()); jPanel48.setMaximumSize(new java.awt.Dimension(5, 32767)); jPanel48.setMinimumSize(new java.awt.Dimension(5, 100)); jPanel48.setOpaque(false); jPanel48.setPreferredSize(new java.awt.Dimension(5, 45)); javax.swing.GroupLayout jPanel48Layout = new javax.swing.GroupLayout(jPanel48); jPanel48.setLayout(jPanel48Layout); jPanel48Layout.setHorizontalGroup( jPanel48Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 5, Short.MAX_VALUE) ); jPanel48Layout.setVerticalGroup( jPanel48Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); container3.add(jPanel48, java.awt.BorderLayout.LINE_END); jPanel49.setMaximumSize(new java.awt.Dimension(10, 32767)); jPanel49.setMinimumSize(new java.awt.Dimension(10, 100)); jPanel49.setOpaque(false); jPanel49.setPreferredSize(new java.awt.Dimension(10, 45)); javax.swing.GroupLayout jPanel49Layout = new javax.swing.GroupLayout(jPanel49); jPanel49.setLayout(jPanel49Layout); jPanel49Layout.setHorizontalGroup( jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); jPanel49Layout.setVerticalGroup( jPanel49Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); container3.add(jPanel49, java.awt.BorderLayout.LINE_START); textField3.setBackground(new java.awt.Color(255, 255, 255)); textField3.setText("Ingresar año de la consulta"); textField3.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(204, 204, 204))); textField3.setOpaque(false); textField3.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { textField3KeyTyped(evt); } }); container3.add(textField3, java.awt.BorderLayout.CENTER); title4.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N title4.setForeground(new java.awt.Color(0, 0, 0)); title4.setText("Año"); advertenciaAnnio.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 10)); // NOI18N advertenciaAnnio.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15); jPanel15.setLayout(jPanel15Layout); jPanel15Layout.setHorizontalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel15Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(container3, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE) .addGroup(jPanel15Layout.createSequentialGroup() .addComponent(title4) .addGap(18, 18, 18) .addComponent(advertenciaAnnio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); jPanel15Layout.setVerticalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel15Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(title4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(advertenciaAnnio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(container3, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel10.add(jPanel15); jPanel16.setOpaque(false); advertenciaGenero.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 10)); // NOI18N advertenciaGenero.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); container5.setkEndColor(new java.awt.Color(204, 204, 204)); container5.setkFillBackground(false); container5.setkStartColor(new java.awt.Color(204, 204, 204)); container5.setMaximumSize(new java.awt.Dimension(32767, 45)); container5.setMinimumSize(new java.awt.Dimension(100, 45)); container5.setOpaque(false); container5.setLayout(new java.awt.BorderLayout()); jPanel51.setMaximumSize(new java.awt.Dimension(5, 32767)); jPanel51.setMinimumSize(new java.awt.Dimension(5, 100)); jPanel51.setOpaque(false); jPanel51.setPreferredSize(new java.awt.Dimension(5, 45)); javax.swing.GroupLayout jPanel51Layout = new javax.swing.GroupLayout(jPanel51); jPanel51.setLayout(jPanel51Layout); jPanel51Layout.setHorizontalGroup( jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 5, Short.MAX_VALUE) ); jPanel51Layout.setVerticalGroup( jPanel51Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); container5.add(jPanel51, java.awt.BorderLayout.LINE_END); jPanel52.setMaximumSize(new java.awt.Dimension(10, 32767)); jPanel52.setMinimumSize(new java.awt.Dimension(10, 100)); jPanel52.setOpaque(false); jPanel52.setPreferredSize(new java.awt.Dimension(10, 45)); javax.swing.GroupLayout jPanel52Layout = new javax.swing.GroupLayout(jPanel52); jPanel52.setLayout(jPanel52Layout); jPanel52Layout.setHorizontalGroup( jPanel52Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); jPanel52Layout.setVerticalGroup( jPanel52Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); container5.add(jPanel52, java.awt.BorderLayout.LINE_START); textField4.setBackground(new java.awt.Color(255, 255, 255)); textField4.setText("Ingresar hora de la consulta"); textField4.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(204, 204, 204))); textField4.setOpaque(false); textField4.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { textField4KeyTyped(evt); } }); container5.add(textField4, java.awt.BorderLayout.CENTER); title5.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N title5.setForeground(new java.awt.Color(0, 0, 0)); title5.setText("Hora"); advertenciaHora.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 10)); // NOI18N advertenciaHora.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); javax.swing.GroupLayout jPanel16Layout = new javax.swing.GroupLayout(jPanel16); jPanel16.setLayout(jPanel16Layout); jPanel16Layout.setHorizontalGroup( jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel16Layout.createSequentialGroup() .addGap(68, 68, 68) .addComponent(advertenciaGenero, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE) .addContainerGap()) .addGroup(jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel16Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(container5, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE) .addGroup(jPanel16Layout.createSequentialGroup() .addComponent(title5) .addGap(18, 18, 18) .addComponent(advertenciaHora, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap())) ); jPanel16Layout.setVerticalGroup( jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel16Layout.createSequentialGroup() .addContainerGap() .addComponent(advertenciaGenero, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(63, Short.MAX_VALUE)) .addGroup(jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel16Layout.createSequentialGroup() .addGap(9, 9, 9) .addGroup(jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(title5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(advertenciaHora, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(container5, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(9, Short.MAX_VALUE))) ); jPanel10.add(jPanel16); jPanel18.setOpaque(false); tratamientoCombo.setBackground(new java.awt.Color(255, 255, 255)); tratamientoCombo.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N tratamientoCombo.setBorder(null); tratamientoCombo.setFocusable(false); tratamientoCombo.setOpaque(false); tratamientoCombo.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { tratamientoComboItemStateChanged(evt); } }); tratamientoCombo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tratamientoComboActionPerformed(evt); } }); title6.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N title6.setForeground(new java.awt.Color(0, 0, 0)); title6.setText("Tratamientos"); advertenciaCombo.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 10)); // NOI18N advertenciaCombo.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); javax.swing.GroupLayout jPanel18Layout = new javax.swing.GroupLayout(jPanel18); jPanel18.setLayout(jPanel18Layout); jPanel18Layout.setHorizontalGroup( jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel18Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tratamientoCombo, 0, 263, Short.MAX_VALUE) .addGroup(jPanel18Layout.createSequentialGroup() .addComponent(title6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(advertenciaCombo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); jPanel18Layout.setVerticalGroup( jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel18Layout.createSequentialGroup() .addGap(12, 12, 12) .addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(title6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(advertenciaCombo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tratamientoCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel10.add(jPanel18); javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9); jPanel9.setLayout(jPanel9Layout); jPanel9Layout.setHorizontalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel9Layout.setVerticalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 57, Short.MAX_VALUE)) ); jPanel7.add(jPanel9, java.awt.BorderLayout.CENTER); jPanel1.add(jPanel7); jPanel6.setOpaque(false); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 199, Short.MAX_VALUE) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 397, Short.MAX_VALUE) ); jPanel1.add(jPanel6); jPanel4.add(jPanel1, java.awt.BorderLayout.CENTER); add(jPanel4, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void textField1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textField1KeyTyped }//GEN-LAST:event_textField1KeyTyped private void textField2KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textField2KeyTyped // TODO add your handling code here: }//GEN-LAST:event_textField2KeyTyped private void textField3KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textField3KeyTyped // TODO add your handling code here: }//GEN-LAST:event_textField3KeyTyped private void saveButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveButtonMouseClicked validateComplete(container1, textField1, advertenciaDia, 31); validateComplete(container2, textField2, advertenciaMes, 12); validateComplete(container3, textField3, advertenciaAnnio, 10000); validateHour(container5, textField4, advertenciaHora); validateCombo(tratamientoCombo, advertenciaCombo); if (AgendaContext.countedErrors == 0) { ConsultasHelper.updateConsulta(devolverDatos());
ApplicationContext.agendaPaciente.addTargets(ApplicationContext.selectedPacient.getId());
0
2023-10-26 19:35:40+00:00
24k
inceptive-tech/ENTSOEDataRetrieval
src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/ENTSOEHistoricalDataRetrieval.java
[ { "identifier": "CSVGenerator", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/csv/CSVGenerator.java", "snippet": "public class CSVGenerator {\n\n private static final Logger LOGGER = LogManager.getLogger(CSVGenerator.class);\n \n private static record ColumnBlock(List<ColumnD...
import java.io.File; import java.io.IOException; import java.time.Duration; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import tech.inceptive.ai4czc.entsoedataretrieval.csv.CSVGenerator; import tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.CSVTransformer; import tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.GLDocumentCSVTransformer; import tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.PublicationDocCSVTransformer; import tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.UnavailabilityDocCSVTransformer; import tech.inceptive.ai4czc.entsoedataretrieval.exceptions.DataRetrievalError; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.ENTSOEDataFetcher; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.Area; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.ColumnType; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.GLMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.PublicationMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.UnavailabilityMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.tools.DateTimeDivider;
20,364
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license */ package tech.inceptive.ai4czc.entsoedataretrieval; /** * The class to fetch an dataset from entsoe. * * @author andres */ public class ENTSOEHistoricalDataRetrieval { private final Set<ColumnType> columnType; private ENTSOEDataFetcher fetcher; // not final for testing purpose private CSVGenerator csvGen; // not final for testing purpose private final String csvEscapeChar; private final String csvSeparator; // TODO : make the time granularity configurable? public ENTSOEHistoricalDataRetrieval(String authToken, Set<ColumnType> columnType, String csvEscapeChar, String csvSeparator, boolean useRequestCache) { this.columnType = columnType; this.fetcher = new ENTSOEDataFetcher(authToken, useRequestCache); this.csvEscapeChar = csvEscapeChar; this.csvSeparator = csvSeparator; this.csvGen = new CSVGenerator(csvSeparator, csvEscapeChar); } /** * Retrieves to a temporal file the dataset, on CSV format. * * @param startDate * @param endDate * @return */
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license */ package tech.inceptive.ai4czc.entsoedataretrieval; /** * The class to fetch an dataset from entsoe. * * @author andres */ public class ENTSOEHistoricalDataRetrieval { private final Set<ColumnType> columnType; private ENTSOEDataFetcher fetcher; // not final for testing purpose private CSVGenerator csvGen; // not final for testing purpose private final String csvEscapeChar; private final String csvSeparator; // TODO : make the time granularity configurable? public ENTSOEHistoricalDataRetrieval(String authToken, Set<ColumnType> columnType, String csvEscapeChar, String csvSeparator, boolean useRequestCache) { this.columnType = columnType; this.fetcher = new ENTSOEDataFetcher(authToken, useRequestCache); this.csvEscapeChar = csvEscapeChar; this.csvSeparator = csvSeparator; this.csvGen = new CSVGenerator(csvSeparator, csvEscapeChar); } /** * Retrieves to a temporal file the dataset, on CSV format. * * @param startDate * @param endDate * @return */
public File fetchDataset(LocalDateTime startDate, LocalDateTime endDate, Duration timeStep, Set<Area> targetAreas,
7
2023-10-30 09:09:53+00:00
24k
EricFan2002/SC2002
src/app/ui/camp/listview/CampListViewStaff.java
[ { "identifier": "UserController", "path": "src/app/controller/user/UserController.java", "snippet": "public class UserController {\n /**\n * Private constructor to prevent instantiation.\n */\n private UserController() {\n }\n\n private static User currentUser;\n\n /**\n * Aut...
import app.controller.user.UserController; import app.entity.RepositoryCollection; import app.entity.camp.Camp; import app.entity.camp.CampList; import app.entity.user.Staff; import app.ui.camp.modificationview.OverlayCampStaffEditView; import app.ui.camp.enquiriesview.OverlayCampInfoDisplayEnquiriesStaff; import app.ui.camp.infomationview.OverlayCampInfoDisplayWithParticipantsViewStudentView; import app.ui.camp.suggestionview.OverlayCampSuggestionCommitteeView; import app.ui.camp.suggestionview.OverlayCampSuggestionStaffView; import app.ui.overlayactions.OverlayCampListViewStaffCampActions; import app.ui.overlayactions.OverlayChooseBox; import app.ui.overlayactions.OverlayNotification; import app.ui.widgets.WidgetButton; import app.ui.widgets.WidgetToggle; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.Date; import static java.lang.System.currentTimeMillis;
18,997
package app.ui.camp.listview; /** * Represents a view specifically designed for staff members to manage camps. * Extends the CampListView class, providing additional functionalities for staff users. */ public class CampListViewStaff extends CampListView { protected WidgetToggle toggleCreated = new WidgetToggle(1, 7, getLenX() / 4 - 1, "Created Camps"); protected WidgetToggle toggleMySchool = new WidgetToggle(1 + getLenX() / 4, 7, getLenX() / 4 - 1, "My Faculty Camps"); protected WidgetButton sortByButton = new WidgetButton(1 + getLenX() / 4 + getLenX() / 8, 8, getLenX() / 8, "Sort By"); protected WidgetButton generateReportButton = new WidgetButton(getLenX() / 4 + 1, 8, getLenX() / 8, "Generate Report"); protected WidgetButton createNewCampButton = new WidgetButton(1, 8, getLenX() / 4 - 1, "Create New Camp"); protected Camp selectedCamp; protected OverlayCampInfoDisplayEnquiriesStaff overlayCampInfoDisplayEnquiriesStaff; protected OverlayCampSuggestionCommitteeView overlayCampSuggestionCommitteeView; protected OverlayCampSuggestionStaffView overlayCampSuggestionStaffView; private int staffMainViewIndex; private String sortMethod = "By"; /** * Constructs a CampListViewStaff with specific staff view index. * @param staffMainViewIndex The index for the main staff view. */ public CampListViewStaff(int staffMainViewIndex) { super(); this.staffMainViewIndex = staffMainViewIndex; addWidgetAfter(toggleCreated, filter4Index); addWidgetAfter(toggleMySchool, filter4Index + 1); addWidgetAfter(createNewCampButton, filter4Index + 2); addWidgetAfter(generateReportButton, filter4Index + 3); addWidgetAfter(sortByButton, filter4Index + 4); } private WidgetButton buttonPosition; /** * Customizes the filter for camps based on staff-specific criteria. * Overrides the method in the parent class. * @param list The original list of camps to be filtered. * @return The filtered list of camps based on staff-specific criteria. */
package app.ui.camp.listview; /** * Represents a view specifically designed for staff members to manage camps. * Extends the CampListView class, providing additional functionalities for staff users. */ public class CampListViewStaff extends CampListView { protected WidgetToggle toggleCreated = new WidgetToggle(1, 7, getLenX() / 4 - 1, "Created Camps"); protected WidgetToggle toggleMySchool = new WidgetToggle(1 + getLenX() / 4, 7, getLenX() / 4 - 1, "My Faculty Camps"); protected WidgetButton sortByButton = new WidgetButton(1 + getLenX() / 4 + getLenX() / 8, 8, getLenX() / 8, "Sort By"); protected WidgetButton generateReportButton = new WidgetButton(getLenX() / 4 + 1, 8, getLenX() / 8, "Generate Report"); protected WidgetButton createNewCampButton = new WidgetButton(1, 8, getLenX() / 4 - 1, "Create New Camp"); protected Camp selectedCamp; protected OverlayCampInfoDisplayEnquiriesStaff overlayCampInfoDisplayEnquiriesStaff; protected OverlayCampSuggestionCommitteeView overlayCampSuggestionCommitteeView; protected OverlayCampSuggestionStaffView overlayCampSuggestionStaffView; private int staffMainViewIndex; private String sortMethod = "By"; /** * Constructs a CampListViewStaff with specific staff view index. * @param staffMainViewIndex The index for the main staff view. */ public CampListViewStaff(int staffMainViewIndex) { super(); this.staffMainViewIndex = staffMainViewIndex; addWidgetAfter(toggleCreated, filter4Index); addWidgetAfter(toggleMySchool, filter4Index + 1); addWidgetAfter(createNewCampButton, filter4Index + 2); addWidgetAfter(generateReportButton, filter4Index + 3); addWidgetAfter(sortByButton, filter4Index + 4); } private WidgetButton buttonPosition; /** * Customizes the filter for camps based on staff-specific criteria. * Overrides the method in the parent class. * @param list The original list of camps to be filtered. * @return The filtered list of camps based on staff-specific criteria. */
protected CampList CustomFilter(CampList list) {
3
2023-11-01 05:18:29+00:00
24k
sinch/sinch-sdk-java
client/src/main/com/sinch/sdk/domains/sms/adapters/GroupsService.java
[ { "identifier": "ApiException", "path": "core/src/main/com/sinch/sdk/core/exceptions/ApiException.java", "snippet": "public class ApiException extends RuntimeException {\n\n private static final long serialVersionUID = -1L;\n private int code = 0;\n\n public ApiException() {}\n\n public ApiException...
import com.sinch.sdk.core.exceptions.ApiException; import com.sinch.sdk.core.http.AuthManager; import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.core.http.HttpMapper; import com.sinch.sdk.core.models.pagination.Page; import com.sinch.sdk.domains.sms.adapters.api.v1.GroupsApi; import com.sinch.sdk.domains.sms.adapters.converters.GroupsDtoConverter; import com.sinch.sdk.domains.sms.models.Group; import com.sinch.sdk.domains.sms.models.SMSCursorPageNavigator; import com.sinch.sdk.domains.sms.models.dto.v1.ApiGroupListDto; import com.sinch.sdk.domains.sms.models.dto.v1.CreateGroupResponseDto; import com.sinch.sdk.domains.sms.models.requests.GroupCreateRequestParameters; import com.sinch.sdk.domains.sms.models.requests.GroupReplaceRequestParameters; import com.sinch.sdk.domains.sms.models.requests.GroupUpdateRequestParameters; import com.sinch.sdk.domains.sms.models.requests.GroupsListRequestParameters; import com.sinch.sdk.domains.sms.models.responses.GroupsListResponse; import com.sinch.sdk.models.Configuration; import java.util.Collection; import java.util.Map;
19,663
package com.sinch.sdk.domains.sms.adapters; public class GroupsService implements com.sinch.sdk.domains.sms.GroupsService { private Configuration configuration; private GroupsApi api; public GroupsService() {} private GroupsApi getApi() { return this.api; } public GroupsService( Configuration configuration, HttpClient httpClient, Map<String, AuthManager> authManagers) { this.configuration = configuration; this.api = new GroupsApi(httpClient, configuration.getSmsServer(), authManagers, new HttpMapper()); } public Group get(String groupId) throws ApiException { CreateGroupResponseDto response = getApi().retrieveGroup(configuration.getProjectId(), groupId);
package com.sinch.sdk.domains.sms.adapters; public class GroupsService implements com.sinch.sdk.domains.sms.GroupsService { private Configuration configuration; private GroupsApi api; public GroupsService() {} private GroupsApi getApi() { return this.api; } public GroupsService( Configuration configuration, HttpClient httpClient, Map<String, AuthManager> authManagers) { this.configuration = configuration; this.api = new GroupsApi(httpClient, configuration.getSmsServer(), authManagers, new HttpMapper()); } public Group get(String groupId) throws ApiException { CreateGroupResponseDto response = getApi().retrieveGroup(configuration.getProjectId(), groupId);
return GroupsDtoConverter.convert(response);
6
2023-10-31 08:32:59+00:00
24k
Melledy/LunarCore
src/main/java/emu/lunarcore/server/packet/recv/HandlerPlayerLogoutCsReq.java
[ { "identifier": "GameSession", "path": "src/main/java/emu/lunarcore/server/game/GameSession.java", "snippet": "@Getter\npublic class GameSession {\n private final GameServer server;\n private final Int2LongMap packetCooldown;\n private InetSocketAddress address;\n\n private Account account;\...
import emu.lunarcore.server.game.GameSession; import emu.lunarcore.server.packet.CmdId; import emu.lunarcore.server.packet.Opcodes; import emu.lunarcore.server.packet.PacketHandler;
19,891
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.PlayerLogoutCsReq) public class HandlerPlayerLogoutCsReq extends PacketHandler { @Override
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.PlayerLogoutCsReq) public class HandlerPlayerLogoutCsReq extends PacketHandler { @Override
public void handle(GameSession session, byte[] data) throws Exception {
0
2023-10-10 12:57:35+00:00
24k
jar-analyzer/jar-analyzer
src/main/java/me/n1ar4/jar/analyzer/gui/action/CleanAction.java
[ { "identifier": "ConfigEngine", "path": "src/main/java/me/n1ar4/jar/analyzer/config/ConfigEngine.java", "snippet": "public class ConfigEngine {\n private static final Logger logger = LogManager.getLogger();\n public static final String CONFIG_FILE_PATH = \".jar-analyzer\";\n\n public static boo...
import me.n1ar4.jar.analyzer.config.ConfigEngine; import me.n1ar4.jar.analyzer.gui.MainForm; import me.n1ar4.jar.analyzer.gui.util.LogUtil; import me.n1ar4.jar.analyzer.starter.Const; import me.n1ar4.jar.analyzer.utils.DirUtil; import javax.swing.*; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths;
20,377
package me.n1ar4.jar.analyzer.gui.action; public class CleanAction { public static void run() { MainForm.getInstance().getCleanButton().addActionListener(e -> { LogUtil.log("clean jar-analyzer"); int res = JOptionPane.showConfirmDialog(MainForm.getInstance().getMasterPanel(), "<html>" + "do you want to clean jar-analyzer?<br>" + "delete jar-analyzer.db <br>" + "delete jar-analyzer-temp <br>" + "delete .jar-analyzer file <br>" + "</html>"); if (res == JOptionPane.OK_OPTION) { try {
package me.n1ar4.jar.analyzer.gui.action; public class CleanAction { public static void run() { MainForm.getInstance().getCleanButton().addActionListener(e -> { LogUtil.log("clean jar-analyzer"); int res = JOptionPane.showConfirmDialog(MainForm.getInstance().getMasterPanel(), "<html>" + "do you want to clean jar-analyzer?<br>" + "delete jar-analyzer.db <br>" + "delete jar-analyzer-temp <br>" + "delete .jar-analyzer file <br>" + "</html>"); if (res == JOptionPane.OK_OPTION) { try {
Files.delete(Paths.get(Const.dbFile));
3
2023-10-07 15:42:35+00:00
24k
lunasaw/gb28181-proxy
gb28181-client/src/test/java/io/github/lunasw/gbproxy/client/test/cmd/ApplicationTest.java
[ { "identifier": "Gb28181Client", "path": "gb28181-client/src/main/java/io/github/lunasaw/gbproxy/client/Gb28181Client.java", "snippet": "@SpringBootApplication\npublic class Gb28181Client {\n\n public static void main(String[] args) {\n SpringApplication.run(Gb28181Client.class, args);\n }\...
import javax.sip.message.Request; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import io.github.lunasaw.gbproxy.client.Gb28181Client; import io.github.lunasaw.gbproxy.client.transmit.request.message.ClientMessageRequestProcessor; import io.github.lunasaw.gbproxy.client.transmit.response.register.RegisterResponseProcessor; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.layer.SipLayer; import io.github.lunasaw.sip.common.transmit.SipProcessorObserver; import io.github.lunasaw.sip.common.transmit.SipSender; import io.github.lunasaw.sip.common.transmit.event.Event; import io.github.lunasaw.sip.common.transmit.event.EventResult; import io.github.lunasaw.sip.common.transmit.request.SipRequestProvider; import io.github.lunasaw.sip.common.utils.SipRequestUtils; import lombok.SneakyThrows;
16,438
package io.github.lunasw.gbproxy.client.test.cmd; /** * @author luna * @date 2023/10/13 */ @SpringBootTest(classes = Gb28181Client.class) public class ApplicationTest { static String localIp = "172.19.128.100"; FromDevice fromDevice; ToDevice toDevice; @Autowired SipLayer sipLayer; @BeforeEach public void before() { sipLayer.addListeningPoint(localIp, 8117); fromDevice = FromDevice.getInstance("33010602011187000001", localIp, 8117); toDevice = ToDevice.getInstance("41010500002000000001", localIp, 8118); toDevice.setPassword("luna"); toDevice.setRealm("4101050000"); } @SneakyThrows @Test public void atest() {
package io.github.lunasw.gbproxy.client.test.cmd; /** * @author luna * @date 2023/10/13 */ @SpringBootTest(classes = Gb28181Client.class) public class ApplicationTest { static String localIp = "172.19.128.100"; FromDevice fromDevice; ToDevice toDevice; @Autowired SipLayer sipLayer; @BeforeEach public void before() { sipLayer.addListeningPoint(localIp, 8117); fromDevice = FromDevice.getInstance("33010602011187000001", localIp, 8117); toDevice = ToDevice.getInstance("41010500002000000001", localIp, 8118); toDevice.setPassword("luna"); toDevice.setRealm("4101050000"); } @SneakyThrows @Test public void atest() {
String callId = SipRequestUtils.getNewCallId();
11
2023-10-11 06:56:28+00:00
24k
Swofty-Developments/Continued-Slime-World-Manager
swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/SWMPlugin.java
[ { "identifier": "SlimePlugin", "path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/SlimePlugin.java", "snippet": "public interface SlimePlugin {\n\n /**\n * Returns the {@link ConfigManager} of the plugin.\n * This can be used to retrieve the {@link net.swofty.swm.api.world.data....
import com.flowpowered.nbt.CompoundMap; import com.flowpowered.nbt.CompoundTag; import net.swofty.swm.api.SlimePlugin; import net.swofty.swm.api.events.PostGenerateWorldEvent; import net.swofty.swm.api.events.PreGenerateWorldEvent; import net.swofty.swm.api.exceptions.*; import net.swofty.swm.api.loaders.SlimeLoader; import net.swofty.swm.api.world.SlimeWorld; import net.swofty.swm.api.world.data.WorldData; import net.swofty.swm.api.world.data.WorldsConfig; import net.swofty.swm.api.world.properties.SlimePropertyMap; import net.swofty.swm.nms.craft.CraftSlimeWorld; import net.swofty.swm.nms.SlimeNMS; import net.swofty.swm.plugin.commands.CommandLoader; import net.swofty.swm.plugin.commands.SWMCommand; import net.swofty.swm.plugin.loader.LoaderUtils; import net.swofty.swm.plugin.log.Logging; import net.swofty.swm.plugin.world.WorldUnlocker; import net.swofty.swm.plugin.world.importer.WorldImporter; import lombok.Getter; import net.swofty.swm.plugin.config.ConfigManager; import ninja.leaping.configurate.objectmapping.ObjectMappingException; import org.bukkit.*; import org.bukkit.command.CommandMap; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.plugin.java.JavaPlugin; import org.reflections.Reflections; import java.io.*; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors;
17,701
package net.swofty.swm.plugin; @Getter public class SWMPlugin extends JavaPlugin implements SlimePlugin { @Getter private static SWMPlugin instance; private SlimeNMS nms; private CommandLoader cl; public CommandMap commandMap; private final List<SlimeWorld> toGenerate = Collections.synchronizedList(new ArrayList<>()); private final ExecutorService worldGeneratorService = Executors.newFixedThreadPool(1); @Override public void onLoad() { /* Static abuse?!?! Nah I'm meming, we all know this is the easiest way to do it Credit: @swofty */ instance = this; /* Initialize config files */ try { ConfigManager.initialize(); } catch (NullPointerException | IOException | ObjectMappingException ex) {
package net.swofty.swm.plugin; @Getter public class SWMPlugin extends JavaPlugin implements SlimePlugin { @Getter private static SWMPlugin instance; private SlimeNMS nms; private CommandLoader cl; public CommandMap commandMap; private final List<SlimeWorld> toGenerate = Collections.synchronizedList(new ArrayList<>()); private final ExecutorService worldGeneratorService = Executors.newFixedThreadPool(1); @Override public void onLoad() { /* Static abuse?!?! Nah I'm meming, we all know this is the easiest way to do it Credit: @swofty */ instance = this; /* Initialize config files */ try { ConfigManager.initialize(); } catch (NullPointerException | IOException | ObjectMappingException ex) {
Logging.error("Failed to load config files:");
13
2023-10-08 10:54:28+00:00
24k
ZJU-ACES-ISE/chatunitest-core
src/main/java/zju/cst/aces/util/Counter.java
[ { "identifier": "Config", "path": "src/main/java/zju/cst/aces/api/config/Config.java", "snippet": "@Getter\n@Setter\npublic class Config {\n public String date;\n public Gson GSON;\n public Project project;\n public JavaParser parser;\n public JavaParserFacade parserFacade;\n public Li...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import zju.cst.aces.api.config.Config; import zju.cst.aces.dto.ClassInfo; import zju.cst.aces.dto.MethodInfo; import zju.cst.aces.parser.ClassParser; import zju.cst.aces.parser.ProjectParser; import zju.cst.aces.runner.MethodRunner; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
15,220
package zju.cst.aces.util; public class Counter { public static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); public static void main(String[] args) throws IOException { countClassMethod(Paths.get("/private/tmp/chatunitest-info/chatgpt-spring-boot-starter/class-info")); } public static Map<String, List<String>> countClassMethod(Path parseOutputPath) throws IOException { Map<String, List<String>> testMap = new HashMap<>(); // get all json files names "class.json" List<String> classJsonFiles = Files.walk(parseOutputPath) .filter(Files::isRegularFile) .map(Path::toString) .filter(f -> f.endsWith("class.json")) .collect(Collectors.toList()); for (String classJsonFile : classJsonFiles) { File classInfoFile = new File(classJsonFile); ClassInfo classInfo = GSON.fromJson(Files.readString(classInfoFile.toPath(), StandardCharsets.UTF_8), ClassInfo.class); if (!filter(classInfo)) { continue; } List<String> methodList = new ArrayList<>(); for (String mSig : classInfo.methodSigs.keySet()) {
package zju.cst.aces.util; public class Counter { public static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); public static void main(String[] args) throws IOException { countClassMethod(Paths.get("/private/tmp/chatunitest-info/chatgpt-spring-boot-starter/class-info")); } public static Map<String, List<String>> countClassMethod(Path parseOutputPath) throws IOException { Map<String, List<String>> testMap = new HashMap<>(); // get all json files names "class.json" List<String> classJsonFiles = Files.walk(parseOutputPath) .filter(Files::isRegularFile) .map(Path::toString) .filter(f -> f.endsWith("class.json")) .collect(Collectors.toList()); for (String classJsonFile : classJsonFiles) { File classInfoFile = new File(classJsonFile); ClassInfo classInfo = GSON.fromJson(Files.readString(classInfoFile.toPath(), StandardCharsets.UTF_8), ClassInfo.class); if (!filter(classInfo)) { continue; } List<String> methodList = new ArrayList<>(); for (String mSig : classInfo.methodSigs.keySet()) {
MethodInfo methodInfo = getMethodInfo(parseOutputPath, classInfo, mSig);
2
2023-10-14 07:15:10+00:00
24k
wise-old-man/wiseoldman-runelite-plugin
src/main/java/net/wiseoldman/web/WomClient.java
[ { "identifier": "WomUtilsPlugin", "path": "src/main/java/net/wiseoldman/WomUtilsPlugin.java", "snippet": "@Slf4j\n@PluginDependency(XpUpdaterPlugin.class)\n@PluginDescriptor(\n\tname = \"Wise Old Man\",\n\ttags = {\"wom\", \"utils\", \"group\", \"xp\"},\n\tdescription = \"Helps you manage your wiseoldma...
import com.google.gson.Gson; import net.wiseoldman.WomUtilsPlugin; import net.wiseoldman.beans.GroupInfoWithMemberships; import net.wiseoldman.beans.NameChangeEntry; import net.wiseoldman.beans.ParticipantWithStanding; import net.wiseoldman.beans.WomStatus; import net.wiseoldman.beans.ParticipantWithCompetition; import net.wiseoldman.beans.GroupMemberAddition; import net.wiseoldman.beans.Member; import net.wiseoldman.beans.GroupMemberRemoval; import net.wiseoldman.beans.PlayerInfo; import net.wiseoldman.beans.WomPlayerUpdate; import net.wiseoldman.events.WomOngoingPlayerCompetitionsFetched; import net.wiseoldman.events.WomUpcomingPlayerCompetitionsFetched; import net.wiseoldman.ui.WomIconHandler; import net.wiseoldman.WomUtilsConfig; import net.wiseoldman.events.WomGroupMemberAdded; import net.wiseoldman.events.WomGroupMemberRemoved; import net.wiseoldman.events.WomGroupSynced; import java.awt.Color; import java.io.IOException; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.MessageNode; import net.runelite.api.events.ChatMessage; import net.runelite.client.callback.ClientThread; 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.eventbus.EventBus; import okhttp3.Callback; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response;
16,370
} private void syncClanMembersCallBack(Response response) { final String message; if (response.isSuccessful()) { GroupInfoWithMemberships data = parseResponse(response, GroupInfoWithMemberships.class); postEvent(new WomGroupSynced(data)); } else { WomStatus data = parseResponse(response, WomStatus.class); message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void removeMemberCallback(Response response, String username) { final String message; final WomStatus data = parseResponse(response, WomStatus.class); if (response.isSuccessful()) { postEvent(new WomGroupMemberRemoved(username)); } else { message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void addMemberCallback(Response response, String username) { final String message; if (response.isSuccessful()) { postEvent(new WomGroupMemberAdded(username)); } else { WomStatus data = parseResponse(response, WomStatus.class); message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void playerOngoingCompetitionsCallback(String username, Response response) { if (response.isSuccessful()) { ParticipantWithStanding[] comps = parseResponse(response, ParticipantWithStanding[].class); postEvent(new WomOngoingPlayerCompetitionsFetched(username, comps)); } else { WomStatus data = parseResponse(response, WomStatus.class); String message = "Error: " + data.getMessage(); sendResponseToChat(message, ERROR); } } private void playerUpcomingCompetitionsCallback(String username, Response response) { if (response.isSuccessful()) { ParticipantWithCompetition[] comps = parseResponse(response, ParticipantWithCompetition[].class); postEvent(new WomUpcomingPlayerCompetitionsFetched(username, comps)); } else { WomStatus data = parseResponse(response, WomStatus.class); String message = "Error: " + data.getMessage(); sendResponseToChat(message, ERROR); } } private <T> T parseResponse(Response r, Class<T> clazz) { return parseResponse(r, clazz, false); } private <T> T parseResponse(Response r, Class<T> clazz, boolean nullIferror) { if (nullIferror && !r.isSuccessful()) { return null; } String body; try { body = r.body().string(); } catch (IOException e) { log.error("Could not read response {}", e.getMessage()); return null; } return gson.fromJson(body, clazz); } private void sendResponseToChat(String message, Color color) { ChatMessageBuilder cmb = new ChatMessageBuilder(); cmb.append("[WOM] "); cmb.append(color, message); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(cmb.build()) .build()); }
package net.wiseoldman.web; @Slf4j public class WomClient { @Inject private OkHttpClient okHttpClient; private Gson gson; @Inject private WomIconHandler iconHandler; @Inject private Client client; @Inject private WomUtilsConfig config; @Inject private ChatMessageManager chatMessageManager; @Inject private ClientThread clientThread; @Inject private EventBus eventBus; private static final Color SUCCESS = new Color(170, 255, 40); private static final Color ERROR = new Color(204, 66, 66); private static final DecimalFormat NUMBER_FORMAT = new DecimalFormat("#.##"); private final WomUtilsPlugin plugin; private final String leagueError = " You are currently in a League world. Your group configurations might be for the main game."; @Inject public WomClient(Gson gson, WomUtilsPlugin plugin) { this.gson = gson.newBuilder() .setDateFormat(DateFormat.FULL, DateFormat.FULL) .create(); this.plugin = plugin; } public void submitNameChanges(NameChangeEntry[] changes) { Request request = createRequest(changes, HttpMethod.POST, "names", "bulk"); sendRequest(request); log.info("Submitted {} name changes to WOM", changes.length); } void sendRequest(Request request) { sendRequest(request, r -> {}); } void sendRequest(Request request, Consumer<Response> consumer) { sendRequest(request, new WomCallback(consumer)); } void sendRequest(Request request, Consumer<Response> consumer, Consumer<Exception> exceptionConsumer) { sendRequest(request, new WomCallback(consumer, exceptionConsumer)); } void sendRequest(Request request, Callback callback) { okHttpClient.newCall(request).enqueue(callback); } private Request createRequest(Object payload, String... pathSegments) { return createRequest(payload, HttpMethod.POST, pathSegments); } private Request createRequest(Object payload, HttpMethod httpMethod, String... pathSegments) { HttpUrl url = buildUrl(pathSegments); RequestBody body = RequestBody.create( MediaType.parse("application/json; charset=utf-8"), gson.toJson(payload) ); Request.Builder requestBuilder = new Request.Builder() .header("User-Agent", "WiseOldMan RuneLite Plugin") .url(url); if (httpMethod == HttpMethod.PUT) { return requestBuilder.put(body).build(); } else if (httpMethod == HttpMethod.DELETE) { return requestBuilder.delete(body).build(); } return requestBuilder.post(body).build(); } private Request createRequest(String... pathSegments) { HttpUrl url = buildUrl(pathSegments); return new Request.Builder() .header("User-Agent", "WiseOldMan RuneLite Plugin") .url(url) .build(); } private HttpUrl buildUrl(String[] pathSegments) { HttpUrl.Builder urlBuilder = new HttpUrl.Builder() .scheme("https") .host("api.wiseoldman.net") .addPathSegment(this.plugin.isSeasonal ? "league" : "v2"); for (String pathSegment : pathSegments) { if (pathSegment.startsWith("?")) { // A query param String[] kv = pathSegment.substring(1).split("="); urlBuilder.addQueryParameter(kv[0], kv[1]); } else { urlBuilder.addPathSegment(pathSegment); } } return urlBuilder.build(); } public void importGroupMembers() { if (config.groupId() > 0) { Request request = createRequest("groups", "" + config.groupId()); sendRequest(request, this::importMembersCallback); } } private void importMembersCallback(Response response) { if (!response.isSuccessful()) { return; } GroupInfoWithMemberships groupInfo = parseResponse(response, GroupInfoWithMemberships.class); postEvent(new WomGroupSynced(groupInfo, true)); } private void syncClanMembersCallBack(Response response) { final String message; if (response.isSuccessful()) { GroupInfoWithMemberships data = parseResponse(response, GroupInfoWithMemberships.class); postEvent(new WomGroupSynced(data)); } else { WomStatus data = parseResponse(response, WomStatus.class); message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void removeMemberCallback(Response response, String username) { final String message; final WomStatus data = parseResponse(response, WomStatus.class); if (response.isSuccessful()) { postEvent(new WomGroupMemberRemoved(username)); } else { message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void addMemberCallback(Response response, String username) { final String message; if (response.isSuccessful()) { postEvent(new WomGroupMemberAdded(username)); } else { WomStatus data = parseResponse(response, WomStatus.class); message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void playerOngoingCompetitionsCallback(String username, Response response) { if (response.isSuccessful()) { ParticipantWithStanding[] comps = parseResponse(response, ParticipantWithStanding[].class); postEvent(new WomOngoingPlayerCompetitionsFetched(username, comps)); } else { WomStatus data = parseResponse(response, WomStatus.class); String message = "Error: " + data.getMessage(); sendResponseToChat(message, ERROR); } } private void playerUpcomingCompetitionsCallback(String username, Response response) { if (response.isSuccessful()) { ParticipantWithCompetition[] comps = parseResponse(response, ParticipantWithCompetition[].class); postEvent(new WomUpcomingPlayerCompetitionsFetched(username, comps)); } else { WomStatus data = parseResponse(response, WomStatus.class); String message = "Error: " + data.getMessage(); sendResponseToChat(message, ERROR); } } private <T> T parseResponse(Response r, Class<T> clazz) { return parseResponse(r, clazz, false); } private <T> T parseResponse(Response r, Class<T> clazz, boolean nullIferror) { if (nullIferror && !r.isSuccessful()) { return null; } String body; try { body = r.body().string(); } catch (IOException e) { log.error("Could not read response {}", e.getMessage()); return null; } return gson.fromJson(body, clazz); } private void sendResponseToChat(String message, Color color) { ChatMessageBuilder cmb = new ChatMessageBuilder(); cmb.append("[WOM] "); cmb.append(color, message); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(cmb.build()) .build()); }
public void syncClanMembers(ArrayList<Member> clanMembers)
7
2023-10-09 14:23:06+00:00
24k
PeytonPlayz595/c0.0.23a_01
src/main/java/com/mojang/minecraft/gui/Gui.java
[ { "identifier": "Tesselator", "path": "src/main/java/com/mojang/minecraft/renderer/Tesselator.java", "snippet": "public class Tesselator {\n\n\t/** The byte buffer used for GL allocation. */\n\tprivate Int32Array intBuffer;\n\tprivate Float32Array floatBuffer;\n\n\t/**\n\t * The number of vertices to be...
import com.mojang.minecraft.renderer.Tesselator; import org.lwjgl.opengl.GL11;
15,461
package com.mojang.minecraft.gui; public class Gui { protected float zLevel = 0.0F; protected static void fill(int var0, int var1, int var2, int var3, int var4) { float var5 = (float)(var4 >>> 24) / 255.0F; float var6 = (float)(var4 >> 16 & 255) / 255.0F; float var7 = (float)(var4 >> 8 & 255) / 255.0F; float var9 = (float)(var4 & 255) / 255.0F; Tesselator var8 = Tesselator.instance;
package com.mojang.minecraft.gui; public class Gui { protected float zLevel = 0.0F; protected static void fill(int var0, int var1, int var2, int var3, int var4) { float var5 = (float)(var4 >>> 24) / 255.0F; float var6 = (float)(var4 >> 16 & 255) / 255.0F; float var7 = (float)(var4 >> 8 & 255) / 255.0F; float var9 = (float)(var4 & 255) / 255.0F; Tesselator var8 = Tesselator.instance;
GL11.glEnable(GL11.GL_BLEND);
1
2023-10-10 17:10:45+00:00
24k
5152Alotobots/2024_Crescendo_Preseason
src/main/java/frc/robot/chargedup/commands/auto/singleelement/cube/Auto_rightbluecharge_1cube_Cmd.java
[ { "identifier": "Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj", "path": "src/main/java/frc/robot/library/drivetrains/commands/Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj.java", "snippet": "public class Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj extends CommandBase {\n /** Creates a new Cmd_SubSys_Dr...
import edu.wpi.first.wpilibj.DriverStation.Alliance; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.ParallelCommandGroup; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.WaitCommand; import frc.robot.library.drivetrains.commands.Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj; import frc.robot.chargedup.subsystems.arm.SubSys_Arm; import frc.robot.chargedup.subsystems.arm.commands.Cmd_SubSys_Arm_RotateAndExtend; import frc.robot.chargedup.subsystems.bling.SubSys_Bling; import frc.robot.chargedup.subsystems.bling.SubSys_Bling_Constants; import frc.robot.chargedup.subsystems.bling.commands.Cmd_SubSys_Bling_SetColorValue; import frc.robot.chargedup.subsystems.chargestation.commands.Cmd_SubSys_ChargeStation_Balance; import frc.robot.chargedup.subsystems.hand.SubSys_Hand; import frc.robot.library.drivetrains.SubSys_DriveTrain; import frc.robot.library.gyroscopes.pigeon2.SubSys_PigeonGyro;
16,799
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. /* __ __ _ _ _ _ \ \ / / | | /\ | | | | | | \ \ /\ / /_ _ _ _ | |_ ___ __ _ ___ / \ _ _| |_ ___ | |_ ___ __ _ _ __ ___ | | \ \/ \/ / _` | | | | | __/ _ \ / _` |/ _ \ / /\ \| | | | __/ _ \ | __/ _ \/ _` | '_ ` _ \| | \ /\ / (_| | |_| | | || (_) | | (_| | (_) | / ____ \ |_| | || (_) | | || __/ (_| | | | | | |_| \/ \/ \__,_|\__, | \__\___/ \__, |\___/ /_/ \_\__,_|\__\___/ \__\___|\__,_|_| |_| |_(_) __/ | __/ | |___/ |___/ */ // WORKS - TESTED ON FIELD package frc.robot.chargedup.commands.auto.singleelement.cube; /** * *Link For PathPlaner * * https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e65ac68f1d_0_48 */ public class Auto_rightbluecharge_1cube_Cmd extends SequentialCommandGroup { private final SubSys_DriveTrain m_DriveTrain; private final SubSys_PigeonGyro m_pigeonGyro; private final SubSys_Arm subsysArm; private final SubSys_Hand subsysHand; private final SubSys_Bling blingSubSys; /** Creates a new Auto_Challenge1_Cmd. */ public Auto_rightbluecharge_1cube_Cmd( SubSys_DriveTrain driveSubSys, SubSys_PigeonGyro pigeonGyro, SubSys_Arm arm, SubSys_Hand hand, SubSys_Bling bling) { m_DriveTrain = driveSubSys; m_pigeonGyro = pigeonGyro; subsysArm = arm; subsysHand = hand; blingSubSys = bling; /* Construct parallel command groups */ ParallelCommandGroup driveAndRetractArm = new ParallelCommandGroup(
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. /* __ __ _ _ _ _ \ \ / / | | /\ | | | | | | \ \ /\ / /_ _ _ _ | |_ ___ __ _ ___ / \ _ _| |_ ___ | |_ ___ __ _ _ __ ___ | | \ \/ \/ / _` | | | | | __/ _ \ / _` |/ _ \ / /\ \| | | | __/ _ \ | __/ _ \/ _` | '_ ` _ \| | \ /\ / (_| | |_| | | || (_) | | (_| | (_) | / ____ \ |_| | || (_) | | || __/ (_| | | | | | |_| \/ \/ \__,_|\__, | \__\___/ \__, |\___/ /_/ \_\__,_|\__\___/ \__\___|\__,_|_| |_| |_(_) __/ | __/ | |___/ |___/ */ // WORKS - TESTED ON FIELD package frc.robot.chargedup.commands.auto.singleelement.cube; /** * *Link For PathPlaner * * https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e65ac68f1d_0_48 */ public class Auto_rightbluecharge_1cube_Cmd extends SequentialCommandGroup { private final SubSys_DriveTrain m_DriveTrain; private final SubSys_PigeonGyro m_pigeonGyro; private final SubSys_Arm subsysArm; private final SubSys_Hand subsysHand; private final SubSys_Bling blingSubSys; /** Creates a new Auto_Challenge1_Cmd. */ public Auto_rightbluecharge_1cube_Cmd( SubSys_DriveTrain driveSubSys, SubSys_PigeonGyro pigeonGyro, SubSys_Arm arm, SubSys_Hand hand, SubSys_Bling bling) { m_DriveTrain = driveSubSys; m_pigeonGyro = pigeonGyro; subsysArm = arm; subsysHand = hand; blingSubSys = bling; /* Construct parallel command groups */ ParallelCommandGroup driveAndRetractArm = new ParallelCommandGroup(
new Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj(
0
2023-10-09 00:27:11+00:00
24k
nexus3a/monitor-remote-agent
src/main/java/com/monitor/agent/server/Server.java
[ { "identifier": "RootHandler", "path": "src/main/java/com/monitor/agent/server/handler/RootHandler.java", "snippet": "public class RootHandler extends DefaultResponder {\r\n\r\n @Override\r\n public NanoHTTPD.Response get(\r\n RouterNanoHTTPD.UriResource uriResource, \r\n Map...
import com.monitor.agent.server.handler.RootHandler; import com.monitor.agent.server.handler.LogRecordsHandler; import com.monitor.agent.server.handler.NotFoundHandler; import com.monitor.agent.server.handler.AckHandler; import com.fasterxml.jackson.databind.JsonMappingException; import com.monitor.agent.server.handler.ConfigHandler; import com.monitor.agent.server.handler.WatchMapHandler; import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.router.RouterNanoHTTPD; import static org.apache.log4j.Level.*; import java.io.IOException; import com.monitor.agent.server.config.ConfigurationManager; import com.monitor.agent.server.config.FilesConfig; import com.monitor.agent.server.config.OneCServerConfig; import com.monitor.agent.server.handler.AccessibilityHandler; import com.monitor.agent.server.handler.ContinueServerHandler; import com.monitor.agent.server.handler.DefaultResponder; import com.monitor.agent.server.handler.ExecQueryHandler; import com.monitor.agent.server.handler.TJLogConfigHandler; import com.monitor.agent.server.handler.OneCSessionsInfoHandler; import com.monitor.agent.server.handler.PauseServerHandler; import com.monitor.agent.server.handler.PingHandler; import com.monitor.agent.server.handler.StopServerHandler; import com.monitor.agent.server.handler.VersionHandler; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.concurrent.Semaphore; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.log4j.Appender; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Layout; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.RollingFileAppender; import org.apache.log4j.spi.RootLogger;
18,244
package com.monitor.agent.server; /* * Copyright 2015 Didier Fetter * Copyright 2021 Aleksei Andreev * * 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. * * Changes by Aleksei Andreev: * - almost all code except option processing was rewriten * */ public class Server { private static final Logger logger = Logger.getLogger(Server.class); private static final String AGENT_VERSION = "2.6.3"; private static final String SINCEDB = ".monitor-remote-agent"; private static final String SINCEDB_CAT = "sincedb"; private static Level logLevel = INFO; private RouterNanoHTTPD httpd; private int starterPort = 0; private int port = 8085; private int spoolSize = 1024; private String config; private ConfigurationManager configManager; private int signatureLength = 4096; private boolean tailSelected = false; private String sincedbFile = SINCEDB; private boolean debugWatcherSelected = false; private String stopRoute = "/shutdown"; private boolean stopServer = false; private String logfile = null; private String logfileSize = "10MB"; private int logfileNumber = 5; private final Semaphore pauseLock = new Semaphore(1); private final HashMap<Section, FileWatcher> watchers = new HashMap<>(); public static boolean isCaseInsensitiveFileSystem() { return System.getProperty("os.name").toLowerCase().startsWith("win"); } public static String version() { return AGENT_VERSION; } @SuppressWarnings({"UseSpecificCatch", "CallToPrintStackTrace"}) public static void main(String[] args) { try { Server server = new Server(); server.parseOptions(args); if (server.stopServer) { server.sendStop(); return; } server.setupLogging(); server.initializeFileWatchers(); server.startServer(); } catch (Exception e) { e.printStackTrace(); System.exit(3); } } public Server() { } private void startServer() throws IOException { new File(SINCEDB_CAT).mkdir(); httpd = new RouterNanoHTTPD(port); httpd.addRoute("/", RootHandler.class); httpd.addRoute("/ping", PingHandler.class); httpd.addRoute("/version", VersionHandler.class); httpd.addRoute("/pause", PauseServerHandler.class, this); httpd.addRoute("/continue", ContinueServerHandler.class, this); httpd.addRoute("/config", ConfigHandler.class, this); httpd.addRoute("/accessibility", AccessibilityHandler.class, this);
package com.monitor.agent.server; /* * Copyright 2015 Didier Fetter * Copyright 2021 Aleksei Andreev * * 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. * * Changes by Aleksei Andreev: * - almost all code except option processing was rewriten * */ public class Server { private static final Logger logger = Logger.getLogger(Server.class); private static final String AGENT_VERSION = "2.6.3"; private static final String SINCEDB = ".monitor-remote-agent"; private static final String SINCEDB_CAT = "sincedb"; private static Level logLevel = INFO; private RouterNanoHTTPD httpd; private int starterPort = 0; private int port = 8085; private int spoolSize = 1024; private String config; private ConfigurationManager configManager; private int signatureLength = 4096; private boolean tailSelected = false; private String sincedbFile = SINCEDB; private boolean debugWatcherSelected = false; private String stopRoute = "/shutdown"; private boolean stopServer = false; private String logfile = null; private String logfileSize = "10MB"; private int logfileNumber = 5; private final Semaphore pauseLock = new Semaphore(1); private final HashMap<Section, FileWatcher> watchers = new HashMap<>(); public static boolean isCaseInsensitiveFileSystem() { return System.getProperty("os.name").toLowerCase().startsWith("win"); } public static String version() { return AGENT_VERSION; } @SuppressWarnings({"UseSpecificCatch", "CallToPrintStackTrace"}) public static void main(String[] args) { try { Server server = new Server(); server.parseOptions(args); if (server.stopServer) { server.sendStop(); return; } server.setupLogging(); server.initializeFileWatchers(); server.startServer(); } catch (Exception e) { e.printStackTrace(); System.exit(3); } } public Server() { } private void startServer() throws IOException { new File(SINCEDB_CAT).mkdir(); httpd = new RouterNanoHTTPD(port); httpd.addRoute("/", RootHandler.class); httpd.addRoute("/ping", PingHandler.class); httpd.addRoute("/version", VersionHandler.class); httpd.addRoute("/pause", PauseServerHandler.class, this); httpd.addRoute("/continue", ContinueServerHandler.class, this); httpd.addRoute("/config", ConfigHandler.class, this); httpd.addRoute("/accessibility", AccessibilityHandler.class, this);
httpd.addRoute("/watchmap", WatchMapHandler.class, this);
5
2023-10-11 20:25:12+00:00
24k
giteecode/bookmanage2-public
nhXJH-admin/src/main/java/com/nhXJH/web/controller/appllication/BookStockBrowHistoryController.java
[ { "identifier": "LoginUser", "path": "nhXJH-common/src/main/java/com/nhXJH/common/core/domain/model/LoginUser.java", "snippet": "public class LoginUser implements UserDetails {\n private static final long serialVersionUID = 1L;\n\n /**\n * 用户ID\n */\n private Long userId;\n\n /**\n ...
import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nhXJH.common.core.domain.model.LoginUser; import com.nhXJH.common.utils.StringUtils; import com.nhXJH.enums.DelEnums; import com.nhXJH.enums.HasBrowedEnums; import com.nhXJH.enums.StatusEnums; import com.nhXJH.framework.web.service.TokenService; import com.nhXJH.system.mapper.SysRoleMapper; import com.nhXJH.web.domain.BookStockBrowHistory; import com.nhXJH.web.domain.vo.BookBrowHistoryVO; import com.nhXJH.web.service.IBookStockBrowHistoryService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.nhXJH.common.annotation.Log; import com.nhXJH.common.core.controller.BaseController; import com.nhXJH.common.core.domain.AjaxResult; import com.nhXJH.common.enums.BusinessType; import com.nhXJH.common.utils.poi.ExcelUtil; import com.nhXJH.common.core.page.TableDataInfo;
21,584
package com.nhXJH.web.controller.appllication; /** * 借书信息Controller * * @author xjh * @date 2022-03-14 */ @RestController @RequestMapping("/userApplication/history") @Api(tags = {"借书信息"}) public class BookStockBrowHistoryController extends BaseController { @Autowired private IBookStockBrowHistoryService bookStockBrowHistoryService; @Autowired private TokenService tokenService; @Autowired private SysRoleMapper sysRoleMapper; /** * 查询借书信息列表 */ @PreAuthorize("@ss.hasPermi('userApplication:history:list')") @GetMapping("/list") @ApiOperation(value ="查询借书信息列表",notes = "查询借书信息列表") public TableDataInfo list(BookStockBrowHistory bookStockBrowHistory) { startPage(); List<BookStockBrowHistory> list = bookStockBrowHistoryService.selectBookStockBrowHistoryList(bookStockBrowHistory); return getDataTable(list); } /** * 查询借书信息列表 */ @PreAuthorize("@ss.hasPermi('userApplication:history:list')") @GetMapping("/mine/history") @ApiOperation(value ="查询借书信息列表",notes = "查询借书信息列表") public TableDataInfo getMyHistory(BookStockBrowHistory bookStockBrowHistory, HttpServletRequest request) { LoginUser loginUser = tokenService.getLoginUser(request); Long userId = loginUser.getUserId(); List<Long> longs = sysRoleMapper.selectRoleListByUserId(userId); bookStockBrowHistory.setUserId(userId); longs.stream().forEach(mapper ->{ if(1 == mapper || 4 == mapper) { bookStockBrowHistory.setUserId(null); } }); startPage();
package com.nhXJH.web.controller.appllication; /** * 借书信息Controller * * @author xjh * @date 2022-03-14 */ @RestController @RequestMapping("/userApplication/history") @Api(tags = {"借书信息"}) public class BookStockBrowHistoryController extends BaseController { @Autowired private IBookStockBrowHistoryService bookStockBrowHistoryService; @Autowired private TokenService tokenService; @Autowired private SysRoleMapper sysRoleMapper; /** * 查询借书信息列表 */ @PreAuthorize("@ss.hasPermi('userApplication:history:list')") @GetMapping("/list") @ApiOperation(value ="查询借书信息列表",notes = "查询借书信息列表") public TableDataInfo list(BookStockBrowHistory bookStockBrowHistory) { startPage(); List<BookStockBrowHistory> list = bookStockBrowHistoryService.selectBookStockBrowHistoryList(bookStockBrowHistory); return getDataTable(list); } /** * 查询借书信息列表 */ @PreAuthorize("@ss.hasPermi('userApplication:history:list')") @GetMapping("/mine/history") @ApiOperation(value ="查询借书信息列表",notes = "查询借书信息列表") public TableDataInfo getMyHistory(BookStockBrowHistory bookStockBrowHistory, HttpServletRequest request) { LoginUser loginUser = tokenService.getLoginUser(request); Long userId = loginUser.getUserId(); List<Long> longs = sysRoleMapper.selectRoleListByUserId(userId); bookStockBrowHistory.setUserId(userId); longs.stream().forEach(mapper ->{ if(1 == mapper || 4 == mapper) { bookStockBrowHistory.setUserId(null); } }); startPage();
List<BookBrowHistoryVO> list = bookStockBrowHistoryService.getMyHistory(bookStockBrowHistory);
8
2023-10-13 07:19:20+00:00
24k
M-D-Team/ait-fabric-1.20.1
src/main/java/mdteam/ait/tardis/handler/FuelHandler.java
[ { "identifier": "AITMod", "path": "src/main/java/mdteam/ait/AITMod.java", "snippet": "public class AITMod implements ModInitializer {\n public static final String MOD_ID = \"ait\";\n public static final Logger LOGGER = LoggerFactory.getLogger(\"ait\");\n public static final Boolean DEBUG = true...
import mdteam.ait.AITMod; import mdteam.ait.api.tardis.TardisEvents; import mdteam.ait.core.interfaces.RiftChunk; import mdteam.ait.core.managers.DeltaTimeManager; import mdteam.ait.datagen.datagen_providers.AITLanguageProvider; import mdteam.ait.tardis.Exclude; import mdteam.ait.tardis.TardisTravel; import mdteam.ait.tardis.handler.properties.PropertiesHandler; import net.minecraft.server.MinecraftServer; import java.util.UUID;
14,808
package mdteam.ait.tardis.handler; public class FuelHandler extends TardisLink { @Exclude public static final double TARDIS_MAX_FUEL = 25000; public static final String FUEL_COUNT = "fuel_count"; public static final String REFUELING = "refueling"; public FuelHandler(UUID tardisId) { super(tardisId); } public double getFuel() {
package mdteam.ait.tardis.handler; public class FuelHandler extends TardisLink { @Exclude public static final double TARDIS_MAX_FUEL = 25000; public static final String FUEL_COUNT = "fuel_count"; public static final String REFUELING = "refueling"; public FuelHandler(UUID tardisId) { super(tardisId); } public double getFuel() {
if (PropertiesHandler.get(tardis().getHandlers().getProperties(), FUEL_COUNT) == null) {
6
2023-10-08 00:38:53+00:00
24k
jianjian3219/044_bookmanage2-public
nhXJH-generator/src/main/java/com/nhXJH/generator/service/GenTableServiceImpl.java
[ { "identifier": "Constants", "path": "nhXJH-common/src/main/java/com/nhXJH/common/constant/Constants.java", "snippet": "public class Constants {\n /**\n * UTF-8 字符集\n */\n public static final String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n public static final String GBK =...
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.nhXJH.common.constant.Constants; import com.nhXJH.common.constant.GenConstants; import com.nhXJH.common.core.text.CharsetKit; import com.nhXJH.common.exception.ServiceException; import com.nhXJH.common.utils.SecurityUtils; import com.nhXJH.common.utils.StringUtils; import com.nhXJH.generator.domain.GenTable; import com.nhXJH.generator.domain.GenTableColumn; import com.nhXJH.generator.mapper.GenTableColumnMapper; import com.nhXJH.generator.mapper.GenTableMapper; import com.nhXJH.generator.util.GenUtils; import com.nhXJH.generator.util.VelocityInitializer; import com.nhXJH.generator.util.VelocityUtils;
18,889
package com.nhXJH.generator.service; /** * 业务 服务层实现 * * @author nhXJH */ @Service public class GenTableServiceImpl implements IGenTableService { private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class); @Autowired private GenTableMapper genTableMapper; @Autowired private GenTableColumnMapper genTableColumnMapper; /** * 查询业务信息 * * @param id 业务ID * @return 业务信息 */ @Override public GenTable selectGenTableById(Long id) { GenTable genTable = genTableMapper.selectGenTableById(id); setTableFromOptions(genTable); return genTable; } /** * 查询业务列表 * * @param genTable 业务信息 * @return 业务集合 */ @Override public List<GenTable> selectGenTableList(GenTable genTable) { return genTableMapper.selectGenTableList(genTable); } /** * 查询据库列表 * * @param genTable 业务信息 * @return 数据库表集合 */ @Override public List<GenTable> selectDbTableList(GenTable genTable) { return genTableMapper.selectDbTableList(genTable); } /** * 查询据库列表 * * @param tableNames 表名称组 * @return 数据库表集合 */ @Override public List<GenTable> selectDbTableListByNames(String[] tableNames) { return genTableMapper.selectDbTableListByNames(tableNames); } /** * 查询所有表信息 * * @return 表信息集合 */ @Override public List<GenTable> selectGenTableAll() { return genTableMapper.selectGenTableAll(); } /** * 修改业务 * * @param genTable 业务信息 * @return 结果 */ @Override @Transactional public void updateGenTable(GenTable genTable) { String options = JSON.toJSONString(genTable.getParams()); genTable.setOptions(options); int row = genTableMapper.updateGenTable(genTable); if (row > 0) { for (GenTableColumn cenTableColumn : genTable.getColumns()) { genTableColumnMapper.updateGenTableColumn(cenTableColumn); } } } /** * 删除业务对象 * * @param tableIds 需要删除的数据ID * @return 结果 */ @Override @Transactional public void deleteGenTableByIds(Long[] tableIds) { genTableMapper.deleteGenTableByIds(tableIds); genTableColumnMapper.deleteGenTableColumnByIds(tableIds); } /** * 导入表结构 * * @param tableList 导入表列表 */ @Override @Transactional public void importGenTable(List<GenTable> tableList) { String operName = SecurityUtils.getUsername(); try { for (GenTable table : tableList) { String tableName = table.getTableName();
package com.nhXJH.generator.service; /** * 业务 服务层实现 * * @author nhXJH */ @Service public class GenTableServiceImpl implements IGenTableService { private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class); @Autowired private GenTableMapper genTableMapper; @Autowired private GenTableColumnMapper genTableColumnMapper; /** * 查询业务信息 * * @param id 业务ID * @return 业务信息 */ @Override public GenTable selectGenTableById(Long id) { GenTable genTable = genTableMapper.selectGenTableById(id); setTableFromOptions(genTable); return genTable; } /** * 查询业务列表 * * @param genTable 业务信息 * @return 业务集合 */ @Override public List<GenTable> selectGenTableList(GenTable genTable) { return genTableMapper.selectGenTableList(genTable); } /** * 查询据库列表 * * @param genTable 业务信息 * @return 数据库表集合 */ @Override public List<GenTable> selectDbTableList(GenTable genTable) { return genTableMapper.selectDbTableList(genTable); } /** * 查询据库列表 * * @param tableNames 表名称组 * @return 数据库表集合 */ @Override public List<GenTable> selectDbTableListByNames(String[] tableNames) { return genTableMapper.selectDbTableListByNames(tableNames); } /** * 查询所有表信息 * * @return 表信息集合 */ @Override public List<GenTable> selectGenTableAll() { return genTableMapper.selectGenTableAll(); } /** * 修改业务 * * @param genTable 业务信息 * @return 结果 */ @Override @Transactional public void updateGenTable(GenTable genTable) { String options = JSON.toJSONString(genTable.getParams()); genTable.setOptions(options); int row = genTableMapper.updateGenTable(genTable); if (row > 0) { for (GenTableColumn cenTableColumn : genTable.getColumns()) { genTableColumnMapper.updateGenTableColumn(cenTableColumn); } } } /** * 删除业务对象 * * @param tableIds 需要删除的数据ID * @return 结果 */ @Override @Transactional public void deleteGenTableByIds(Long[] tableIds) { genTableMapper.deleteGenTableByIds(tableIds); genTableColumnMapper.deleteGenTableColumnByIds(tableIds); } /** * 导入表结构 * * @param tableList 导入表列表 */ @Override @Transactional public void importGenTable(List<GenTable> tableList) { String operName = SecurityUtils.getUsername(); try { for (GenTable table : tableList) { String tableName = table.getTableName();
GenUtils.initTable(table, operName);
10
2023-10-14 04:57:42+00:00
24k
codegrits/CodeGRITS
src/main/java/actions/StartStopTrackingAction.java
[ { "identifier": "ConfigDialog", "path": "src/main/java/components/ConfigDialog.java", "snippet": "public class ConfigDialog extends DialogWrapper {\n\n private List<JCheckBox> checkBoxes;\n\n private final JPanel panel = new JPanel();\n private static List<JTextField> labelAreas = new ArrayList...
import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import components.ConfigDialog; import entity.Config; import org.jetbrains.annotations.NotNull; import trackers.EyeTracker; import trackers.IDETracker; import trackers.ScreenRecorder; import utils.AvailabilityChecker; import javax.swing.*; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.IOException; import java.util.Objects;
17,627
package actions; /** * This class is the action for starting/stopping tracking. */ public class StartStopTrackingAction extends AnAction { /** * This variable indicates whether the tracking is started. */ private static boolean isTracking = false; /** * This variable is the IDE tracker. */ private static IDETracker iDETracker; /** * This variable is the eye tracker. */ private static EyeTracker eyeTracker; /** * This variable is the screen recorder. */ private final ScreenRecorder screenRecorder = ScreenRecorder.getInstance(); /** * This variable is the configuration. */
package actions; /** * This class is the action for starting/stopping tracking. */ public class StartStopTrackingAction extends AnAction { /** * This variable indicates whether the tracking is started. */ private static boolean isTracking = false; /** * This variable is the IDE tracker. */ private static IDETracker iDETracker; /** * This variable is the eye tracker. */ private static EyeTracker eyeTracker; /** * This variable is the screen recorder. */ private final ScreenRecorder screenRecorder = ScreenRecorder.getInstance(); /** * This variable is the configuration. */
Config config = new Config();
1
2023-10-12 15:40:39+00:00
24k
giteecode/supermarket2Public
src/main/java/com/ruoyi/project/system/dict/controller/DictTypeController.java
[ { "identifier": "UserConstants", "path": "src/main/java/com/ruoyi/common/constant/UserConstants.java", "snippet": "public class UserConstants\n{\n /** 正常状态 */\n public static final String NORMAL = \"0\";\n\n /** 异常状态 */\n public static final String EXCEPTION = \"1\";\n\n /** 用户封禁状态 */\n ...
import java.util.List; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.framework.aspectj.lang.annotation.Log; import com.ruoyi.framework.aspectj.lang.enums.BusinessType; import com.ruoyi.framework.web.controller.BaseController; import com.ruoyi.framework.web.domain.AjaxResult; import com.ruoyi.framework.web.domain.Ztree; import com.ruoyi.framework.web.page.TableDataInfo; import com.ruoyi.project.system.dict.domain.DictType; import com.ruoyi.project.system.dict.service.IDictTypeService;
17,183
package com.ruoyi.project.system.dict.controller; /** * 数据字典信息 * * @author ruoyi */ @Controller @RequestMapping("/system/dict") public class DictTypeController extends BaseController { private String prefix = "system/dict/type"; @Autowired private IDictTypeService dictTypeService; @RequiresPermissions("system:dict:view") @GetMapping() public String dictType() { return prefix + "/type"; } @PostMapping("/list") @RequiresPermissions("system:dict:list") @ResponseBody public TableDataInfo list(DictType dictType) { startPage(); List<DictType> list = dictTypeService.selectDictTypeList(dictType); return getDataTable(list); } @Log(title = "字典类型", businessType = BusinessType.EXPORT) @RequiresPermissions("system:dict:export") @PostMapping("/export") @ResponseBody public AjaxResult export(DictType dictType) { List<DictType> list = dictTypeService.selectDictTypeList(dictType);
package com.ruoyi.project.system.dict.controller; /** * 数据字典信息 * * @author ruoyi */ @Controller @RequestMapping("/system/dict") public class DictTypeController extends BaseController { private String prefix = "system/dict/type"; @Autowired private IDictTypeService dictTypeService; @RequiresPermissions("system:dict:view") @GetMapping() public String dictType() { return prefix + "/type"; } @PostMapping("/list") @RequiresPermissions("system:dict:list") @ResponseBody public TableDataInfo list(DictType dictType) { startPage(); List<DictType> list = dictTypeService.selectDictTypeList(dictType); return getDataTable(list); } @Log(title = "字典类型", businessType = BusinessType.EXPORT) @RequiresPermissions("system:dict:export") @PostMapping("/export") @ResponseBody public AjaxResult export(DictType dictType) { List<DictType> list = dictTypeService.selectDictTypeList(dictType);
ExcelUtil<DictType> util = new ExcelUtil<DictType>(DictType.class);
1
2023-10-14 02:27:47+00:00
24k
lukas-mb/ABAP-SQL-Beautifier
ABAP SQL Beautifier/src/com/abap/sql/beautifier/StatementProcessor.java
[ { "identifier": "PreferenceConstants", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/preferences/PreferenceConstants.java", "snippet": "public class PreferenceConstants {\n\n\tpublic static final String ALLIGN_OPERS = \"ALLIGN_OPERS\";\n\n\tpublic static final String COMBINE_CHAR_LIMIT = \"CO...
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.contentassist.CompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext; import org.eclipse.jface.text.quickassist.IQuickAssistProcessor; import org.eclipse.jface.text.source.Annotation; import org.eclipse.ui.PlatformUI; import com.abap.sql.beautifier.preferences.PreferenceConstants; import com.abap.sql.beautifier.settings.AbstractSqlSetting; import com.abap.sql.beautifier.settings.CommentsAdder; import com.abap.sql.beautifier.settings.ConditionAligner; import com.abap.sql.beautifier.settings.JoinCombiner; import com.abap.sql.beautifier.settings.OperatorUnifier; import com.abap.sql.beautifier.settings.Restructor; import com.abap.sql.beautifier.settings.SelectCombiner; import com.abap.sql.beautifier.settings.SpaceAdder; import com.abap.sql.beautifier.statement.AbapSql; import com.abap.sql.beautifier.utility.BeautifierIcon; import com.abap.sql.beautifier.utility.Utility; import com.sap.adt.tools.abapsource.ui.AbapSourceUi; import com.sap.adt.tools.abapsource.ui.IAbapSourceUi; import com.sap.adt.tools.abapsource.ui.sources.IAbapSourceScannerServices; import com.sap.adt.tools.abapsource.ui.sources.IAbapSourceScannerServices.Token; import com.sap.adt.tools.abapsource.ui.sources.editors.AbapSourcePage;
14,516
diff = startReplacement - lineOffset; } catch (BadLocationException e) { e.printStackTrace(); } break; } } if (firstToken != null) { if (firstToken.equalsIgnoreCase(Abap.SELECT)) { sql = code.substring(startReplacement, end); String sqlHelper = sql.replaceAll(",", ""); sqlHelper = Utility.cleanString(sqlHelper); List<String> customTokens = Arrays.asList(sqlHelper.split(" ")); if (customTokens.size() > 2) { // check if old or new syntax String secToken = customTokens.get(1).toString().toUpperCase(); String thirdToken = customTokens.get(2).toString().toUpperCase(); if (secToken.equals(Abap.FROM) || (secToken.equals(Abap.SINGLE) && thirdToken.equals(Abap.FROM))) { this.oldSyntax = false; } } // TODO // check if second SELECT or WHEN in statement --> not working currently in this // plugin // check if it contains multiple 'select' or 'when' // when? if (sql.toUpperCase().contains(" WHEN ")) { return false; } // mult. select? int count = Utility.countKeyword(sql, Abap.SELECT); if (count <= 1) { return true; } } } } return false; } @Override public boolean canFix(Annotation annotation) { return true; } @Override public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext invocationContext) { List<ICompletionProposal> proposals = new ArrayList<>(); if (canAssist(invocationContext)) { int replaceLength = end - startReplacement + 1; String beautifulSql = ""; String convertedSql = ""; try { beautifulSql = beautifyStatement(sql); if (this.oldSyntax) { // convertedSql = convertToNewSyntax(beautifulSql); } } catch (Exception e) { // to avoid 'disturbing' other plugins with other proposals if there is a bug e.printStackTrace(); return null; } String descBeautify = "Beautify this SQL statement depending on the settings in your preferences."; BeautifyProposal beautifyProp = new BeautifyProposal(beautifulSql, startReplacement, replaceLength, 0, BeautifierIcon.get(), "Beautify SQL-Statement", null, descBeautify); proposals.add(beautifyProp); // if (this.oldSyntax) { // CompletionProposal conversionProp = new CompletionProposal(convertedSql, startReplacement, // replaceLength, 0, BeautifierIcon.get(), "Convert SQL-Statement", null, // "Convert this SQL statement to the new syntax depending on the settings in your preferences."); // // proposals.add(conversionProp); // } return proposals.toArray(new ICompletionProposal[proposals.size()]); } return null; } @Override public String getErrorMessage() { return null; } private List<AbstractSqlSetting> generateSettings() { List<AbstractSqlSetting> settings = new ArrayList<>(); settings.add(new Restructor()); settings.add(new OperatorUnifier()); if (this.oldSyntax) { // settings.add(new CommasAdder()); settings.add(new JoinCombiner()); settings.add(new SelectCombiner()); // settings.add(new EscapingAdder()); }
package com.abap.sql.beautifier; public class StatementProcessor implements IQuickAssistProcessor { public IDocument document = null; public IAbapSourceScannerServices scannerServices = null; public AbapSourcePage sourcePage; public IAbapSourceUi sourceUi = null; private String sql = ""; private String code; private int diff; private int end; private int offsetCursor; private int startReplacement; private boolean oldSyntax = true; private String beautifyStatement(String inputCode) { // otherwise the whole beautifier would not work inputCode = inputCode.toUpperCase(); AbapSql abapSql = new AbapSql(inputCode, diff); System.out.println("=================================="); System.out.println("Input"); System.out.println(inputCode); List<AbstractSqlSetting> settings = generateSettings(); // apply settings for (AbstractSqlSetting setting : settings) { System.out.println("=================================="); System.out.println(setting.getClass().getSimpleName()); setting.setAbapSql(abapSql); setting.apply(); abapSql = setting.getAbapSql(); System.out.println(abapSql.toString()); } abapSql.setPoint(); String outputCode = abapSql.toString(); // delete last empty row if (outputCode.endsWith("\r\n")) { outputCode = outputCode.substring(0, outputCode.length() - "\r\n".length()); } System.out.println("=================================="); System.out.println("Output"); System.out.println(outputCode); return outputCode; } @Override public boolean canAssist(IQuickAssistInvocationContext invocationContext) { // get part of code and check if the current code part is a sql statement document = invocationContext.getSourceViewer().getDocument(); sourceUi = AbapSourceUi.getInstance(); scannerServices = sourceUi.getSourceScannerServices(); sourcePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor() .getAdapter(AbapSourcePage.class); code = document.get(); // offset of current cursor offsetCursor = invocationContext.getOffset(); // get offset of last and next dot int start = scannerServices.goBackToDot(document, offsetCursor) + 1; end = scannerServices.goForwardToDot(document, offsetCursor); // all words in selected code List<Token> statementTokens = scannerServices.getStatementTokens(document, start); // check first word if (statementTokens.size() > 0) { String firstToken = null; // get first non comment token for (int i = 0; i < statementTokens.size(); i++) { Token t = statementTokens.get(i); if (!scannerServices.isComment(document, t.offset)) { firstToken = t.toString(); // offset of last dot and startReplacement could be different startReplacement = t.offset; try { int line = document.getLineOfOffset(startReplacement); int lineOffset = document.getLineOffset(line); diff = startReplacement - lineOffset; } catch (BadLocationException e) { e.printStackTrace(); } break; } } if (firstToken != null) { if (firstToken.equalsIgnoreCase(Abap.SELECT)) { sql = code.substring(startReplacement, end); String sqlHelper = sql.replaceAll(",", ""); sqlHelper = Utility.cleanString(sqlHelper); List<String> customTokens = Arrays.asList(sqlHelper.split(" ")); if (customTokens.size() > 2) { // check if old or new syntax String secToken = customTokens.get(1).toString().toUpperCase(); String thirdToken = customTokens.get(2).toString().toUpperCase(); if (secToken.equals(Abap.FROM) || (secToken.equals(Abap.SINGLE) && thirdToken.equals(Abap.FROM))) { this.oldSyntax = false; } } // TODO // check if second SELECT or WHEN in statement --> not working currently in this // plugin // check if it contains multiple 'select' or 'when' // when? if (sql.toUpperCase().contains(" WHEN ")) { return false; } // mult. select? int count = Utility.countKeyword(sql, Abap.SELECT); if (count <= 1) { return true; } } } } return false; } @Override public boolean canFix(Annotation annotation) { return true; } @Override public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext invocationContext) { List<ICompletionProposal> proposals = new ArrayList<>(); if (canAssist(invocationContext)) { int replaceLength = end - startReplacement + 1; String beautifulSql = ""; String convertedSql = ""; try { beautifulSql = beautifyStatement(sql); if (this.oldSyntax) { // convertedSql = convertToNewSyntax(beautifulSql); } } catch (Exception e) { // to avoid 'disturbing' other plugins with other proposals if there is a bug e.printStackTrace(); return null; } String descBeautify = "Beautify this SQL statement depending on the settings in your preferences."; BeautifyProposal beautifyProp = new BeautifyProposal(beautifulSql, startReplacement, replaceLength, 0, BeautifierIcon.get(), "Beautify SQL-Statement", null, descBeautify); proposals.add(beautifyProp); // if (this.oldSyntax) { // CompletionProposal conversionProp = new CompletionProposal(convertedSql, startReplacement, // replaceLength, 0, BeautifierIcon.get(), "Convert SQL-Statement", null, // "Convert this SQL statement to the new syntax depending on the settings in your preferences."); // // proposals.add(conversionProp); // } return proposals.toArray(new ICompletionProposal[proposals.size()]); } return null; } @Override public String getErrorMessage() { return null; } private List<AbstractSqlSetting> generateSettings() { List<AbstractSqlSetting> settings = new ArrayList<>(); settings.add(new Restructor()); settings.add(new OperatorUnifier()); if (this.oldSyntax) { // settings.add(new CommasAdder()); settings.add(new JoinCombiner()); settings.add(new SelectCombiner()); // settings.add(new EscapingAdder()); }
settings.add(new SpaceAdder());
8
2023-10-10 18:56:27+00:00
24k
Spider-Admin/Frost
src/main/java/frost/storage/perst/PerstFrostDownloadItem.java
[ { "identifier": "FreenetPriority", "path": "src/main/java/frost/fileTransfer/FreenetPriority.java", "snippet": "public enum FreenetPriority {\n\tMAXIMUM(0),\n\tVERY_HIGH(1),\n\tHIGH(2),\n\tMEDIUM(3),\n\tLOW(4),\n\tVERY_LOW(5),\n\tPAUSE(6);\n\t\n\tfinal int priority;\n\t\n\tFreenetPriority(final int prio...
import org.garret.perst.Persistent; import org.slf4j.Logger; import frost.fileTransfer.FreenetPriority; import frost.fileTransfer.FrostFileListFileObject; import frost.fileTransfer.download.FrostDownloadItem; import frost.storage.perst.filelist.FileListStorage;
14,636
/* PerstFrostDownloadItem.java / Frost Copyright (C) 2007 Frost Project <jtcfrost.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.storage.perst; /** * Class to make FrostDownloadItem persistent. * FrostDownloadItem itself extends ModelItem and cannot extend Persistent. */ public class PerstFrostDownloadItem extends Persistent { public String fileName; public String prefix; public String downloadDir; public long fileSize; public String key; public boolean enabled; public int state; public long downloadAddedTime; public long downloadStartedTime; public long downloadFinishedTime; public int retries; public long lastDownloadStopTime; public String gqIdentifier; public String fileListFileSha; public boolean isLoggedToFile; public boolean isTracked; public boolean isCompletionProgRun; public int runtimeSecondsWithoutProgress; public int oldDoneBlocks; private FreenetPriority priority; public String associatedBoardName; public String associatedMessageId; public PerstFrostDownloadItem() {} public PerstFrostDownloadItem(final FrostDownloadItem dlItem) { fileName = dlItem.getUnprefixedFilename(); prefix = dlItem.getFilenamePrefix(); downloadDir = dlItem.getDownloadDir(); fileSize = dlItem.getFileSize(); key = dlItem.getKey(); enabled = (dlItem.isEnabled()==null?true:dlItem.isEnabled().booleanValue()); state = dlItem.getState(); downloadAddedTime = dlItem.getDownloadAddedMillis(); downloadStartedTime = dlItem.getDownloadStartedMillis(); downloadFinishedTime = dlItem.getDownloadFinishedMillis(); retries = dlItem.getRetries(); lastDownloadStopTime = dlItem.getLastDownloadStopTime(); gqIdentifier = dlItem.getGqIdentifier(); fileListFileSha = (dlItem.getFileListFileObject()==null?null:dlItem.getFileListFileObject().getSha()); isLoggedToFile = dlItem.isLoggedToFile(); isTracked = dlItem.isTracked(); isCompletionProgRun = dlItem.isCompletionProgRun(); runtimeSecondsWithoutProgress = dlItem.getRuntimeSecondsWithoutProgress(); oldDoneBlocks = dlItem.getOldDoneBlocks(); associatedBoardName = dlItem.getAssociatedBoardName(); associatedMessageId = dlItem.getAssociatedMessageId(); priority = dlItem.getPriority(); } public FrostDownloadItem toFrostDownloadItem(final Logger logger) { FrostFileListFileObject sharedFileObject = null; if( fileListFileSha != null && fileListFileSha.length() > 0 ) {
/* PerstFrostDownloadItem.java / Frost Copyright (C) 2007 Frost Project <jtcfrost.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.storage.perst; /** * Class to make FrostDownloadItem persistent. * FrostDownloadItem itself extends ModelItem and cannot extend Persistent. */ public class PerstFrostDownloadItem extends Persistent { public String fileName; public String prefix; public String downloadDir; public long fileSize; public String key; public boolean enabled; public int state; public long downloadAddedTime; public long downloadStartedTime; public long downloadFinishedTime; public int retries; public long lastDownloadStopTime; public String gqIdentifier; public String fileListFileSha; public boolean isLoggedToFile; public boolean isTracked; public boolean isCompletionProgRun; public int runtimeSecondsWithoutProgress; public int oldDoneBlocks; private FreenetPriority priority; public String associatedBoardName; public String associatedMessageId; public PerstFrostDownloadItem() {} public PerstFrostDownloadItem(final FrostDownloadItem dlItem) { fileName = dlItem.getUnprefixedFilename(); prefix = dlItem.getFilenamePrefix(); downloadDir = dlItem.getDownloadDir(); fileSize = dlItem.getFileSize(); key = dlItem.getKey(); enabled = (dlItem.isEnabled()==null?true:dlItem.isEnabled().booleanValue()); state = dlItem.getState(); downloadAddedTime = dlItem.getDownloadAddedMillis(); downloadStartedTime = dlItem.getDownloadStartedMillis(); downloadFinishedTime = dlItem.getDownloadFinishedMillis(); retries = dlItem.getRetries(); lastDownloadStopTime = dlItem.getLastDownloadStopTime(); gqIdentifier = dlItem.getGqIdentifier(); fileListFileSha = (dlItem.getFileListFileObject()==null?null:dlItem.getFileListFileObject().getSha()); isLoggedToFile = dlItem.isLoggedToFile(); isTracked = dlItem.isTracked(); isCompletionProgRun = dlItem.isCompletionProgRun(); runtimeSecondsWithoutProgress = dlItem.getRuntimeSecondsWithoutProgress(); oldDoneBlocks = dlItem.getOldDoneBlocks(); associatedBoardName = dlItem.getAssociatedBoardName(); associatedMessageId = dlItem.getAssociatedMessageId(); priority = dlItem.getPriority(); } public FrostDownloadItem toFrostDownloadItem(final Logger logger) { FrostFileListFileObject sharedFileObject = null; if( fileListFileSha != null && fileListFileSha.length() > 0 ) {
sharedFileObject = FileListStorage.inst().getFileBySha(fileListFileSha);
3
2023-10-07 22:25:20+00:00
24k
seraxis/lr2oraja-endlessdream
core/src/bms/player/beatoraja/skin/json/JsonSkinObjectLoader.java
[ { "identifier": "SkinGauge", "path": "core/src/bms/player/beatoraja/play/SkinGauge.java", "snippet": "public class SkinGauge extends SkinObject {\n\n\t/**\n\t * イメージ\n\t */\n\tprivate SkinSourceSet image;\n\t/**\n\t * アニメーションの種類\n\t */\n\tprivate int animationType = ANIMATION_RANDOM;\n\t/**\n\t * アニメーショ...
import bms.player.beatoraja.play.SkinGauge; import bms.player.beatoraja.result.SkinGaugeGraphObject; import bms.player.beatoraja.select.MusicSelectSkin; import bms.player.beatoraja.select.SkinDistributionGraph; import bms.player.beatoraja.skin.*; import bms.player.beatoraja.skin.SkinObject.SkinOffset; import bms.player.beatoraja.skin.json.JSONSkinLoader.SourceData; import bms.player.beatoraja.skin.property.StringProperty; import bms.player.beatoraja.skin.property.StringPropertyFactory; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import java.io.File; import java.nio.file.Path;
15,445
SkinBPMGraph st = new SkinBPMGraph(ggraph.delay, ggraph.lineWidth, ggraph.mainBPMColor, ggraph.minBPMColor, ggraph.maxBPMColor, ggraph.otherBPMColor, ggraph.stopLineColor, ggraph.transitionLineColor); return st; } } for (JsonSkin.HitErrorVisualizer hev : sk.hiterrorvisualizer) { if (dst.id.equals(hev.id)) { SkinHitErrorVisualizer st = new SkinHitErrorVisualizer(hev.width, hev.judgeWidthMillis, hev.lineWidth, hev.colorMode, hev.hiterrorMode, hev.emaMode, hev.lineColor, hev.centerColor, hev.PGColor, hev.GRColor, hev.GDColor, hev.BDColor, hev.PRColor, hev.emaColor, hev.alpha, hev.windowLength, hev.transparent, hev.drawDecay); return st; } } for (JsonSkin.TimingVisualizer tv : sk.timingvisualizer) { if (dst.id.equals(tv.id)) { SkinTimingVisualizer st = new SkinTimingVisualizer(tv.width, tv.judgeWidthMillis, tv.lineWidth, tv.lineColor, tv.centerColor, tv.PGColor, tv.GRColor, tv.GDColor, tv.BDColor, tv.PRColor, tv.transparent, tv.drawDecay); return st; } } for (JsonSkin.TimingDistributionGraph td : sk.timingdistributiongraph) { if (dst.id.equals(td.id)) { SkinTimingDistributionGraph st = new SkinTimingDistributionGraph(td.width, td.lineWidth, td.graphColor, td.averageColor, td.devColor, td.PGColor, td.GRColor, td.GDColor, td.BDColor, td.PRColor, td.drawAverage, td.drawDev); return st; } } // gauge (playskin or resultskin only) if (sk.gauge != null && dst.id.equals(sk.gauge.id)) { int[][] indexmap = null; switch(sk.gauge.nodes.length) { case 4: indexmap = new int[][]{{0,4,6,10,12,16,18,22,24,28,30,34},{1,5,7,11,13,17,19,23,25,29,31,35},{2,8,14,20,26,32},{3,9,15,21,27,33}}; break; case 8: indexmap = new int[][]{{12,16,18,22},{13,17,19,23},{14,20},{15,21}, {0,4,6,10,24,28,30,34},{1,5,7,11,25,29,31,35},{2,8,26,32},{3,9,27,33}}; break; case 12: indexmap = new int[][]{{12,18},{13,19},{14,20},{15,21}, {0,6,24,30},{1,7,25,31},{2,8,26,32},{3,9,27,33}, {16,22}, {17,23}, {4, 10, 28, 34}, {5,11,29,35}}; break; case 36: break; } TextureRegion[][] pgaugetex = new TextureRegion[36][]; int gaugelength = 0; for (int i = 0; i < sk.gauge.nodes.length; i++) { for (JsonSkin.Image img : sk.image) { if (sk.gauge.nodes[i].equals(img.id)) { Texture tex = getTexture(img.src, p); if(tex != null) { if(indexmap != null) { for(int index : indexmap[i]) { pgaugetex[index] = getSourceImage(tex, img.x, img.y, img.w, img.h, img.divx, img.divy); gaugelength = pgaugetex[index].length; } } else { pgaugetex[i] = getSourceImage(tex, img.x, img.y, img.w, img.h, img.divx, img.divy); gaugelength = pgaugetex[i].length; } } break; } } } TextureRegion[][] gaugetex = new TextureRegion[gaugelength][36]; for (int i = 0; i < 36; i++) { for (int j = 0; j < gaugetex.length; j++) { gaugetex[j][i] = pgaugetex[i][j]; } } obj = new SkinGauge(gaugetex, 0, 0, sk.gauge.parts, sk.gauge.type, sk.gauge.range, sk.gauge.cycle); ((SkinGauge)obj).setStarttime(sk.gauge.starttime); ((SkinGauge)obj).setEndtime(sk.gauge.endtime); return obj; } //POMYU chara for (JsonSkin.PMchara chara : sk.pmchara) { if (dst.id.equals(chara.id)) { //type 0:プレイ 1:キャラ背景 2:名前画像 3:ハリアイ画像(上半身のみ) 4:ハリアイ画像(全体) 5:キャラアイコン 6:NEUTRAL 7:FEVER 8:GREAT 9:GOOD 10:BAD 11:FEVERWIN 12:WIN 13:LOSE 14:OJAMA 15:DANCE File imagefile = getSrcIdPath(chara.src, p); if(dst.dst.length > 0 && imagefile != null) { int color = chara.color == 2 ? 2 : 1; int side = chara.side == 2 ? 2 : 1; int[] option = new int[3]; for(int i = 0; i < option.length; i++) { if(i < dst.op.length) option[i] = dst.op[i]; else option[i] = 0; } if(chara.type == 0) { new PomyuCharaLoader(skin).load(loader.usecim, imagefile, chara.type, color, dst.dst[0].x, dst.dst[0].y, dst.dst[0].w, dst.dst[0].h, side, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, dst.offset); } else if(chara.type >= 1 && chara.type <= 5) { SkinImage si = new PomyuCharaLoader(skin).load(loader.usecim, imagefile, chara.type, color, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); obj = si; } else if(chara.type >= 6 && chara.type <= 15) { new PomyuCharaLoader(skin).load(loader.usecim, imagefile, chara.type, color, dst.dst[0].x, dst.dst[0].y, dst.dst[0].w, dst.dst[0].h, Integer.MIN_VALUE, dst.timer, option[0], option[1], option[2], dst.offset); } } return obj; } } return obj; } protected Texture getTexture(String srcid, Path p) { if(srcid == null) { return null; }
package bms.player.beatoraja.skin.json; /** * JSONスキンオブジェクトローダー * * @author exch * * @param <S> */ public abstract class JsonSkinObjectLoader<S extends Skin> { protected final JSONSkinLoader loader; public JsonSkinObjectLoader(JSONSkinLoader loader) { this.loader = loader; } public abstract S getSkin(SkinHeader header); public SkinObject loadSkinObject(S skin, JsonSkin.Skin sk, JsonSkin.Destination dst, Path p) { SkinObject obj = null; for (JsonSkin.Image img : sk.image) { if (dst.id.equals(img.id)) { Object data = loader.getSource(img.src, p); if(data instanceof SkinSourceMovie) { obj = new SkinImage((SkinSourceMovie)data); } else if(data instanceof Texture) { Texture tex = (Texture) data; if (img.len > 1) { TextureRegion[] srcimg = getSourceImage(tex, img.x, img.y, img.w, img.h, img.divx, img.divy); TextureRegion[][] tr = new TextureRegion[img.len][]; for (int i = 0; i < tr.length; i++) { tr[i] = new TextureRegion[srcimg.length / img.len]; for (int j = 0; j < tr[i].length; j++) { tr[i][j] = srcimg[i * tr[i].length + j]; } } SkinImage si = new SkinImage(tr, img.timer, img.cycle); si.setReferenceID(img.ref); obj = si; } else { obj = new SkinImage(getSourceImage(tex, img.x, img.y, img.w, img.h, img.divx, img.divy), img.timer, img.cycle); } } if (obj != null && img.act != null) { obj.setClickevent(img.act); obj.setClickeventType(img.click); } return obj; } } for (JsonSkin.ImageSet imgs : sk.imageset) { if (dst.id.equals(imgs.id)) { SkinSourceImage[] sources = new SkinSourceImage[imgs.images.length]; for (int index = 0; index < imgs.images.length; index++) { for (JsonSkin.Image img : sk.image) { if (img.id.equals(imgs.images[index])) { Object data = loader.getSource(img.src, p); if(data instanceof Texture) { Texture tex = (Texture) data; sources[index] = new SkinSourceImage(getSourceImage(tex, img.x, img.y, img.w, img.h, img.divx, img.divy), img.timer, img.cycle); } break; } } } SkinImage si = new SkinImage(sources); if (imgs.value != null) { si.setReference(imgs.value); } else { si.setReferenceID(imgs.ref); } obj = si; if (imgs.act != null) { obj.setClickevent(imgs.act); obj.setClickeventType(imgs.click); } return obj; } } for (JsonSkin.Value value : sk.value) { if (dst.id.equals(value.id)) { Texture tex = getTexture(value.src, p); TextureRegion[] images = getSourceImage(tex, value.x, value.y, value.w, value.h, value.divx, value.divy); if (images.length % 24 == 0) { TextureRegion[][] pn = new TextureRegion[images.length / 24][]; TextureRegion[][] mn = new TextureRegion[images.length / 24][]; for (int j = 0; j < pn.length; j++) { pn[j] = new TextureRegion[12]; mn[j] = new TextureRegion[12]; for (int i = 0; i < 12; i++) { pn[j][i] = images[j * 24 + i]; mn[j][i] = images[j * 24 + i + 12]; } } SkinNumber num = null; if(value.value != null) { num = new SkinNumber(pn, mn, value.timer, value.cycle, value.digit, value.zeropadding, value.space, value.value); } else { num = new SkinNumber(pn, mn, value.timer, value.cycle, value.digit, value.zeropadding, value.space, value.ref); } num.setAlign(value.align); if(value.offset != null) { SkinOffset[] offsets = new SkinOffset[value.offset.length]; for(int i = 0;i < offsets.length;i++) { offsets[i] = new SkinOffset(); offsets[i].x = value.offset[i].x; offsets[i].y = value.offset[i].y; offsets[i].w = value.offset[i].w; offsets[i].h = value.offset[i].h; } num.setOffsets(offsets); } obj = num; } else { int d = images.length % 10 == 0 ? 10 : 11; TextureRegion[][] nimages = new TextureRegion[value.divx * value.divy / d][d]; for (int i = 0; i < d; i++) { for (int j = 0; j < value.divx * value.divy / d; j++) { nimages[j][i] = images[j * d + i]; } } SkinNumber num = null; if(value.value != null) { num = new SkinNumber(nimages, value.timer, value.cycle, value.digit, d > 10 ? 2 : value.padding, value.space, value.value); } else { num = new SkinNumber(nimages, value.timer, value.cycle, value.digit, d > 10 ? 2 : value.padding, value.space, value.ref); } num.setAlign(value.align); if(value.offset != null) { SkinOffset[] offsets = new SkinOffset[value.offset.length]; for(int i = 0;i < offsets.length;i++) { offsets[i] = new SkinOffset(); offsets[i].x = value.offset[i].x; offsets[i].y = value.offset[i].y; offsets[i].w = value.offset[i].w; offsets[i].h = value.offset[i].h; } num.setOffsets(offsets); } obj = num; } return obj; } } // text for (JsonSkin.Text text : sk.text) { if (dst.id.equals(text.id)) { if (text.ref == SkinProperty.STRING_SEARCHWORD) { JsonSkin.Animation a = dst.dst[0]; Rectangle r = new Rectangle(a.x * ((float)loader.dstr.width / sk.w), a.y * ((float)loader.dstr.height / sk.h), a.w * ((float)loader.dstr.width / sk.w), a.h * ((float)loader.dstr.height / sk.h)); ((MusicSelectSkin) skin).setSearchTextRegion(r); } else { obj = createText(text, p); } return obj; } } // slider for (JsonSkin.Slider img : sk.slider) { if (dst.id.equals(img.id)) { Texture tex = getTexture(img.src, p); if(tex != null) { if(img.value != null) { obj = new SkinSlider(getSourceImage(tex, img.x, img.y, img.w, img.h, img.divx, img.divy), img.timer, img.cycle, img.angle, (int) ((img.angle == 1 || img.angle == 3 ? ((float)loader.dstr.width / sk.w) : ((float)loader.dstr.height / sk.h)) * img.range), img.value, img.event); } else if(img.isRefNum) { obj = new SkinSlider(getSourceImage(tex, img.x, img.y, img.w, img.h, img.divx, img.divy), img.timer, img.cycle, img.angle, (int) ((img.angle == 1 || img.angle == 3 ? ((float)loader.dstr.width / sk.w) : ((float)loader.dstr.height / sk.h)) * img.range), img.type, img.min, img.max); } else { obj = new SkinSlider(getSourceImage(tex, img.x, img.y, img.w, img.h, img.divx, img.divy), img.timer, img.cycle, img.angle, (int) ((img.angle == 1 || img.angle == 3 ? ((float)loader.dstr.width / sk.w) : ((float)loader.dstr.height / sk.h)) * img.range), img.type); } ((SkinSlider)obj).setChangeable(img.changeable); } return obj; } } // graph for (JsonSkin.Graph img : sk.graph) { if (dst.id.equals(img.id)) { if (img.type < 0) { Texture tex = getTexture(img.src, p); if(tex != null) { TextureRegion[] images = getSourceImage(tex, img.x, img.y, img.w, img.h, img.divx, img.divy); final int len = img.type == -1 ? 11 : 28; TextureRegion[][] imgs = new TextureRegion[len][images.length / len]; for(int j = 0 ;j < len;j++) { for(int i = 0 ;i < imgs[j].length;i++) { imgs[j][i] = images[i * len + j]; } } final int graphtype = img.type == -1 ? 0 : 1; obj = new SkinDistributionGraph(graphtype, imgs, img.timer, img.cycle); } } else { Texture tex = getTexture(img.src, p); if(tex != null) { if(img.value != null) { obj = new SkinGraph(getSourceImage(tex, img.x, img.y, img.w, img.h, img.divx, img.divy), img.timer, img.cycle, img.value); } else if(img.isRefNum) { obj = new SkinGraph(getSourceImage(tex, img.x, img.y, img.w, img.h, img.divx, img.divy), img.timer, img.cycle, img.type, img.min, img.max); } else { obj = new SkinGraph(getSourceImage(tex, img.x, img.y, img.w, img.h, img.divx, img.divy), img.timer, img.cycle, img.type); } ((SkinGraph) obj).setDirection(img.angle); } } return obj; } } for (JsonSkin.GaugeGraph ggraph : sk.gaugegraph) { if (dst.id.equals(ggraph.id)) { SkinGaugeGraphObject st = null; if(ggraph.color != null) { Color[][] colors = new Color[6][4]; for(int i = 0;i < 24 && i < ggraph.color.length;i++) { colors[i / 4][i % 4] = Color.valueOf(ggraph.color[i]); } st = new SkinGaugeGraphObject(colors); } else { st = new SkinGaugeGraphObject(ggraph.assistClearBGColor, ggraph.assistAndEasyFailBGColor, ggraph.grooveFailBGColor, ggraph.grooveClearAndHardBGColor, ggraph.exHardBGColor, ggraph.hazardBGColor, ggraph.assistClearLineColor, ggraph.assistAndEasyFailLineColor, ggraph.grooveFailLineColor, ggraph.grooveClearAndHardLineColor, ggraph.exHardLineColor, ggraph.hazardLineColor, ggraph.borderlineColor, ggraph.borderColor); } obj = st; return obj; } } for (JsonSkin.JudgeGraph ggraph : sk.judgegraph) { if (dst.id.equals(ggraph.id)) { SkinNoteDistributionGraph st = new SkinNoteDistributionGraph(ggraph.type, ggraph.delay, ggraph.backTexOff, ggraph.orderReverse, ggraph.noGap); obj = st; break; } } for (JsonSkin.BPMGraph ggraph : sk.bpmgraph) { if (dst.id.equals(ggraph.id)) { SkinBPMGraph st = new SkinBPMGraph(ggraph.delay, ggraph.lineWidth, ggraph.mainBPMColor, ggraph.minBPMColor, ggraph.maxBPMColor, ggraph.otherBPMColor, ggraph.stopLineColor, ggraph.transitionLineColor); return st; } } for (JsonSkin.HitErrorVisualizer hev : sk.hiterrorvisualizer) { if (dst.id.equals(hev.id)) { SkinHitErrorVisualizer st = new SkinHitErrorVisualizer(hev.width, hev.judgeWidthMillis, hev.lineWidth, hev.colorMode, hev.hiterrorMode, hev.emaMode, hev.lineColor, hev.centerColor, hev.PGColor, hev.GRColor, hev.GDColor, hev.BDColor, hev.PRColor, hev.emaColor, hev.alpha, hev.windowLength, hev.transparent, hev.drawDecay); return st; } } for (JsonSkin.TimingVisualizer tv : sk.timingvisualizer) { if (dst.id.equals(tv.id)) { SkinTimingVisualizer st = new SkinTimingVisualizer(tv.width, tv.judgeWidthMillis, tv.lineWidth, tv.lineColor, tv.centerColor, tv.PGColor, tv.GRColor, tv.GDColor, tv.BDColor, tv.PRColor, tv.transparent, tv.drawDecay); return st; } } for (JsonSkin.TimingDistributionGraph td : sk.timingdistributiongraph) { if (dst.id.equals(td.id)) { SkinTimingDistributionGraph st = new SkinTimingDistributionGraph(td.width, td.lineWidth, td.graphColor, td.averageColor, td.devColor, td.PGColor, td.GRColor, td.GDColor, td.BDColor, td.PRColor, td.drawAverage, td.drawDev); return st; } } // gauge (playskin or resultskin only) if (sk.gauge != null && dst.id.equals(sk.gauge.id)) { int[][] indexmap = null; switch(sk.gauge.nodes.length) { case 4: indexmap = new int[][]{{0,4,6,10,12,16,18,22,24,28,30,34},{1,5,7,11,13,17,19,23,25,29,31,35},{2,8,14,20,26,32},{3,9,15,21,27,33}}; break; case 8: indexmap = new int[][]{{12,16,18,22},{13,17,19,23},{14,20},{15,21}, {0,4,6,10,24,28,30,34},{1,5,7,11,25,29,31,35},{2,8,26,32},{3,9,27,33}}; break; case 12: indexmap = new int[][]{{12,18},{13,19},{14,20},{15,21}, {0,6,24,30},{1,7,25,31},{2,8,26,32},{3,9,27,33}, {16,22}, {17,23}, {4, 10, 28, 34}, {5,11,29,35}}; break; case 36: break; } TextureRegion[][] pgaugetex = new TextureRegion[36][]; int gaugelength = 0; for (int i = 0; i < sk.gauge.nodes.length; i++) { for (JsonSkin.Image img : sk.image) { if (sk.gauge.nodes[i].equals(img.id)) { Texture tex = getTexture(img.src, p); if(tex != null) { if(indexmap != null) { for(int index : indexmap[i]) { pgaugetex[index] = getSourceImage(tex, img.x, img.y, img.w, img.h, img.divx, img.divy); gaugelength = pgaugetex[index].length; } } else { pgaugetex[i] = getSourceImage(tex, img.x, img.y, img.w, img.h, img.divx, img.divy); gaugelength = pgaugetex[i].length; } } break; } } } TextureRegion[][] gaugetex = new TextureRegion[gaugelength][36]; for (int i = 0; i < 36; i++) { for (int j = 0; j < gaugetex.length; j++) { gaugetex[j][i] = pgaugetex[i][j]; } } obj = new SkinGauge(gaugetex, 0, 0, sk.gauge.parts, sk.gauge.type, sk.gauge.range, sk.gauge.cycle); ((SkinGauge)obj).setStarttime(sk.gauge.starttime); ((SkinGauge)obj).setEndtime(sk.gauge.endtime); return obj; } //POMYU chara for (JsonSkin.PMchara chara : sk.pmchara) { if (dst.id.equals(chara.id)) { //type 0:プレイ 1:キャラ背景 2:名前画像 3:ハリアイ画像(上半身のみ) 4:ハリアイ画像(全体) 5:キャラアイコン 6:NEUTRAL 7:FEVER 8:GREAT 9:GOOD 10:BAD 11:FEVERWIN 12:WIN 13:LOSE 14:OJAMA 15:DANCE File imagefile = getSrcIdPath(chara.src, p); if(dst.dst.length > 0 && imagefile != null) { int color = chara.color == 2 ? 2 : 1; int side = chara.side == 2 ? 2 : 1; int[] option = new int[3]; for(int i = 0; i < option.length; i++) { if(i < dst.op.length) option[i] = dst.op[i]; else option[i] = 0; } if(chara.type == 0) { new PomyuCharaLoader(skin).load(loader.usecim, imagefile, chara.type, color, dst.dst[0].x, dst.dst[0].y, dst.dst[0].w, dst.dst[0].h, side, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, dst.offset); } else if(chara.type >= 1 && chara.type <= 5) { SkinImage si = new PomyuCharaLoader(skin).load(loader.usecim, imagefile, chara.type, color, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); obj = si; } else if(chara.type >= 6 && chara.type <= 15) { new PomyuCharaLoader(skin).load(loader.usecim, imagefile, chara.type, color, dst.dst[0].x, dst.dst[0].y, dst.dst[0].w, dst.dst[0].h, Integer.MIN_VALUE, dst.timer, option[0], option[1], option[2], dst.offset); } } return obj; } } return obj; } protected Texture getTexture(String srcid, Path p) { if(srcid == null) { return null; }
final SourceData data = loader.sourceMap.get(srcid);
5
2023-12-02 23:41:17+00:00
24k
parttimenerd/hello-ebpf
bcc/src/main/java/me/bechberger/ebpf/samples/chapter2/ex/HelloBufferEvenOdd.java
[ { "identifier": "BPF", "path": "bcc/src/main/java/me/bechberger/ebpf/bcc/BPF.java", "snippet": "public class BPF implements AutoCloseable {\n\n static {\n try {\n System.loadLibrary(\"bcc\");\n } catch (UnsatisfiedLinkError e) {\n try {\n System.load...
import static me.bechberger.ebpf.samples.chapter2.HelloBuffer.DATA_TYPE; import me.bechberger.ebpf.bcc.BPF; import me.bechberger.ebpf.bcc.BPFTable; import me.bechberger.ebpf.samples.chapter2.HelloBuffer;
20,952
/** * HelloBuffer that outputs different trace messages for even and odd process ids */ package me.bechberger.ebpf.samples.chapter2.ex; /** * Also shows how to reuse data types from {@link HelloBuffer} */ public class HelloBufferEvenOdd { public static void main(String[] args) throws InterruptedException { try (var b = BPF.builder(""" BPF_PERF_OUTPUT(output); struct data_t { int pid; int uid; char command[16]; char message[12]; }; int hello(void *ctx) { struct data_t data = {}; char even_message[12] = "Even pid"; char odd_message[12] = "Odd pid"; data.pid = bpf_get_current_pid_tgid() >> 32; data.uid = bpf_get_current_uid_gid() & 0xFFFFFFFF; bpf_get_current_comm(&data.command, sizeof(data.command)); if (data.pid % 2 == 0) { bpf_probe_read_kernel(&data.message, sizeof(data.message), even_message); } else { bpf_probe_read_kernel(&data.message, sizeof(data.message), odd_message); } output.perf_submit(ctx, &data, sizeof(data)); return 0; } """).build()) { var syscall = b.get_syscall_fnname("execve"); b.attach_kprobe(syscall, "hello");
/** * HelloBuffer that outputs different trace messages for even and odd process ids */ package me.bechberger.ebpf.samples.chapter2.ex; /** * Also shows how to reuse data types from {@link HelloBuffer} */ public class HelloBufferEvenOdd { public static void main(String[] args) throws InterruptedException { try (var b = BPF.builder(""" BPF_PERF_OUTPUT(output); struct data_t { int pid; int uid; char command[16]; char message[12]; }; int hello(void *ctx) { struct data_t data = {}; char even_message[12] = "Even pid"; char odd_message[12] = "Odd pid"; data.pid = bpf_get_current_pid_tgid() >> 32; data.uid = bpf_get_current_uid_gid() & 0xFFFFFFFF; bpf_get_current_comm(&data.command, sizeof(data.command)); if (data.pid % 2 == 0) { bpf_probe_read_kernel(&data.message, sizeof(data.message), even_message); } else { bpf_probe_read_kernel(&data.message, sizeof(data.message), odd_message); } output.perf_submit(ctx, &data, sizeof(data)); return 0; } """).build()) { var syscall = b.get_syscall_fnname("execve"); b.attach_kprobe(syscall, "hello");
BPFTable.PerfEventArray.EventCallback<HelloBuffer.Data> print_event = (array, cpu, data, size) -> {
2
2023-12-01 20:24:28+00:00
24k
WiIIiam278/HuskClaims
common/src/main/java/net/william278/huskclaims/command/ExtendClaimCommand.java
[ { "identifier": "HuskClaims", "path": "common/src/main/java/net/william278/huskclaims/HuskClaims.java", "snippet": "public interface HuskClaims extends Task.Supplier, ConfigProvider, DatabaseProvider, GsonProvider, UserManager,\n ClaimManager, GroupManager, TrustTagManager, ListenerProvider, User...
import java.util.Optional; import lombok.AllArgsConstructor; import net.william278.huskclaims.HuskClaims; import net.william278.huskclaims.claim.Claim; import net.william278.huskclaims.claim.ClaimWorld; import net.william278.huskclaims.claim.ClaimingMode; import net.william278.huskclaims.claim.Region; import net.william278.huskclaims.config.Settings; import net.william278.huskclaims.user.OnlineUser; import org.jetbrains.annotations.NotNull; import java.util.List;
15,453
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <will27528@gmail.com> * Copyright (c) contributors * * 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 net.william278.huskclaims.command; public class ExtendClaimCommand extends InClaimCommand { protected ExtendClaimCommand(@NotNull HuskClaims plugin) { super( List.of("extendclaim"), "<blocks>", plugin ); } @Override
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <will27528@gmail.com> * Copyright (c) contributors * * 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 net.william278.huskclaims.command; public class ExtendClaimCommand extends InClaimCommand { protected ExtendClaimCommand(@NotNull HuskClaims plugin) { super( List.of("extendclaim"), "<blocks>", plugin ); } @Override
public void execute(@NotNull OnlineUser executor, @NotNull ClaimWorld world,
6
2023-11-28 01:09:43+00:00
24k
Manzzx/multi-channel-message-reach
metax-modules/metax-system/src/main/java/com/metax/system/controller/SysConfigController.java
[ { "identifier": "ExcelUtil", "path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/utils/poi/ExcelUtil.java", "snippet": "public class ExcelUtil<T>\n{\n private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);\n\n public static final String FORMULA_REGEX_ST...
import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.metax.common.core.utils.poi.ExcelUtil; import com.metax.common.core.web.controller.BaseController; import com.metax.common.core.web.domain.AjaxResult; import com.metax.common.core.web.page.TableDataInfo; import com.metax.common.log.annotation.Log; import com.metax.common.log.enums.BusinessType; import com.metax.common.security.annotation.RequiresPermissions; import com.metax.common.security.utils.SecurityUtils; import com.metax.system.domain.SysConfig; import com.metax.system.service.ISysConfigService;
16,241
package com.metax.system.controller; /** * 参数配置 信息操作处理 * * @author ruoyi */ @RestController @RequestMapping("/config") public class SysConfigController extends BaseController { @Autowired private ISysConfigService configService; /** * 获取参数配置列表 */ @RequiresPermissions("system:config:list") @GetMapping("/list")
package com.metax.system.controller; /** * 参数配置 信息操作处理 * * @author ruoyi */ @RestController @RequestMapping("/config") public class SysConfigController extends BaseController { @Autowired private ISysConfigService configService; /** * 获取参数配置列表 */ @RequiresPermissions("system:config:list") @GetMapping("/list")
public TableDataInfo list(SysConfig config)
3
2023-12-04 05:10:13+00:00
24k
ydb-platform/yoj-project
repository-inmemory/src/main/java/tech/ydb/yoj/repository/test/inmemory/InMemoryTable.java
[ { "identifier": "FilterExpression", "path": "databind/src/main/java/tech/ydb/yoj/databind/expression/FilterExpression.java", "snippet": "public interface FilterExpression<T> {\n <V> V visit(@NonNull Visitor<T, V> visitor);\n\n Schema<T> getSchema();\n\n Type getType();\n\n <U> FilterExpressi...
import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import tech.ydb.yoj.databind.expression.FilterExpression; import tech.ydb.yoj.databind.expression.OrderExpression; import tech.ydb.yoj.databind.schema.ObjectSchema; import tech.ydb.yoj.databind.schema.Schema; import tech.ydb.yoj.repository.db.Entity; import tech.ydb.yoj.repository.db.EntityExpressions; import tech.ydb.yoj.repository.db.EntityIdSchema; import tech.ydb.yoj.repository.db.EntitySchema; import tech.ydb.yoj.repository.db.Range; import tech.ydb.yoj.repository.db.Table; import tech.ydb.yoj.repository.db.ViewSchema; import tech.ydb.yoj.repository.db.cache.FirstLevelCache; import tech.ydb.yoj.repository.db.exception.IllegalTransactionIsolationLevelException; import tech.ydb.yoj.repository.db.list.InMemoryQueries; import tech.ydb.yoj.repository.db.readtable.ReadTableParams; import tech.ydb.yoj.repository.db.statement.Changeset; import javax.annotation.Nullable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toUnmodifiableMap; import static java.util.stream.Collectors.toUnmodifiableSet;
20,855
} private <ID extends Entity.Id<T>> void markKeyRead(ID id) { EntityIdSchema<Entity.Id<T>> idSchema = schema.getIdSchema(); if (idSchema.flattenFieldNames().size() != idSchema.flatten(id).size()) { // Partial key, will throw error when not searching by PK prefix transaction.getWatcher().markRangeRead(type, Range.create(id, id)); } else { transaction.getWatcher().markRowRead(type, id); } } @Override @SuppressWarnings("unchecked") public <ID extends Entity.Id<T>> List<ID> findIds(Set<ID> ids) { return find(ids).stream() .map(e -> (ID) e.getId()) .sorted(schema.getIdSchema()) .toList(); } @Override public T insert(T tt) { T t = tt.preSave(); transaction.getWatcher().markRowRead(type, t.getId()); transaction.doInWriteTransaction("insert(" + t + ")", type, shard -> shard.insert(t)); transaction.getTransactionLocal().firstLevelCache().put(t); transaction.getTransactionLocal().projectionCache().save(t); return t; } @Override public T save(T tt) { T t = tt.preSave(); transaction.doInWriteTransaction("save(" + t + ")", type, shard -> shard.save(t)); transaction.getTransactionLocal().firstLevelCache().put(t); transaction.getTransactionLocal().projectionCache().save(t); return t; } @Override public void delete(Entity.Id<T> id) { transaction.doInWriteTransaction("delete(" + id + ")", type, shard -> shard.delete(id)); transaction.getTransactionLocal().firstLevelCache().putEmpty(id); transaction.getTransactionLocal().projectionCache().delete(id); } @Override public void deleteAll() { transaction.doInWriteTransaction("deleteAll(" + type.getName() + ")", type, WriteTxDataShard::deleteAll); } private List<T> getAllEntries() { return transaction.doInTransaction("findAll(" + type.getName() + ")", type, ReadOnlyTxDataShard::findAll); } private List<T> findAll0() { List<T> all = getAllEntries(); return postLoad(all); } @Override public Stream<T> streamAll(int batchSize) { return streamPartial(null, batchSize); } @Override public <ID extends Entity.Id<T>> Stream<T> streamPartial(ID partial, int batchSize) { Preconditions.checkArgument(1 <= batchSize && batchSize <= 5000, "batchSize must be in range [1, 5000], got %s", batchSize); Range<ID> range = partial == null ? null : Range.create(partial); markRangeRead(range); return streamPartial0(range); } private <ID extends Entity.Id<T>> Stream<T> streamPartial0(@Nullable Range<ID> range) { return (range == null ? findAll() : find(range)).stream(); } @Override public <V extends ViewId<T>> Stream<V> streamAll(Class<V> viewType, int batchSize) { return streamPartial(viewType, null, batchSize); } @Override public <ID extends Entity.Id<T>, V extends ViewId<T>> Stream<V> streamPartial( Class<V> viewType, ID partial, int batchSize ) { return streamPartial(partial, batchSize).map(e -> toView(viewType, schema, e)); } @Override public <ID extends Entity.Id<T>> Stream<ID> streamAllIds(int batchSize) { return streamPartialIds(null, batchSize); } @Override @SuppressWarnings("unchecked") public <ID extends Entity.Id<T>> Stream<ID> streamPartialIds(ID partial, int batchSize) { Preconditions.checkArgument(1 <= batchSize && batchSize <= 10000, "batchSize must be in range [1, 10000], got %s", batchSize); Range<ID> range = partial == null ? null : Range.create(partial); markRangeRead(range); return streamPartial0(range).map(e -> (ID) e.getId()); } private <ID extends Entity.Id<T>> void markRangeRead(Range<ID> range) { if (range == null) { transaction.getWatcher().markTableRead(type); } else { transaction.getWatcher().markRangeRead(type, range); } } private <ID extends Entity.Id<T>> Stream<T> readTableStream(ReadTableParams<ID> params) { if (!transaction.getOptions().getIsolationLevel().isReadOnly()) {
package tech.ydb.yoj.repository.test.inmemory; public class InMemoryTable<T extends Entity<T>> implements Table<T> { private final Class<T> type; private final EntitySchema<T> schema; private final InMemoryRepositoryTransaction transaction; public InMemoryTable(DbMemory<T> memory) { this.type = memory.type(); this.schema = EntitySchema.of(type); this.transaction = memory.transaction(); } @Override public List<T> findAll() { transaction.getWatcher().markTableRead(type); return findAll0(); } @Override public <V extends View> List<V> findAll(Class<V> viewType) { return findAll().stream() .map(entity -> toView(viewType, schema, entity)) .collect(toList()); } @Override public long countAll() { return findAll().size(); } @Override public long count(String indexName, FilterExpression<T> filter) { return find(indexName, filter, null, null, null).size(); } @Override @Deprecated public void update(Entity.Id<T> id, Changeset changeset) { T found = find(id); if (found == null) { return; } Map<String, Object> cells = new HashMap<>(schema.flatten(found)); changeset.toMap().forEach((k, v) -> { cells.putAll(schema.flattenOneField(k, v)); }); T newInstance = schema.newInstance(cells); save(newInstance); } @Override public List<T> find( @Nullable String indexName, @Nullable FilterExpression<T> filter, @Nullable OrderExpression<T> orderBy, @Nullable Integer limit, @Nullable Long offset ) { // NOTE: InMemoryTable doesn't handle index. return InMemoryQueries.find(() -> findAll().stream(), filter, orderBy, limit, offset); } @Override public <V extends View> List<V> find( Class<V> viewType, @Nullable String indexName, @Nullable FilterExpression<T> finalFilter, @Nullable OrderExpression<T> orderBy, @Nullable Integer limit, @Nullable Long offset, boolean distinct ) { Stream<V> stream = find(indexName, finalFilter, orderBy, limit, offset).stream() .map(entity -> toView(viewType, schema, entity)); if (distinct) { stream = stream.distinct(); } return stream.collect(toList()); } @Override @SuppressWarnings("unchecked") public <ID extends Entity.Id<T>> List<ID> findIds( @Nullable String indexName, @Nullable FilterExpression<T> finalFilter, @Nullable OrderExpression<T> orderBy, @Nullable Integer limit, @Nullable Long offset ) { return find(indexName, finalFilter, orderBy, limit, offset).stream() .map(entity -> (ID) entity.getId()) .collect(toList()); } @Override public <ID extends Entity.Id<T>> Stream<T> readTable(ReadTableParams<ID> params) { return readTableStream(params).map(T::postLoad); } @Override public <ID extends Entity.Id<T>> Stream<ID> readTableIds(ReadTableParams<ID> params) { return readTableStream(params).map(e -> { @SuppressWarnings("unchecked") ID id = (ID) e.getId(); return id; }); } @Override public <V extends ViewId<T>, ID extends Entity.Id<T>> Stream<V> readTable( Class<V> viewClass, ReadTableParams<ID> params ) { return readTableStream(params).map(e -> toView(viewClass, schema, e)); } @Override public Class<T> getType() { return type; } @Override public T find(Entity.Id<T> id) { if (id.isPartial()) { throw new IllegalArgumentException("Cannot use partial id in find method"); } return transaction.getTransactionLocal().firstLevelCache().get(id, __ -> { markKeyRead(id); T entity = transaction.doInTransaction("find(" + id + ")", type, shard -> shard.find(id)); return postLoad(entity); }); } @Override public <V extends View> V find(Class<V> viewType, Entity.Id<T> id) { if (id.isPartial()) { throw new IllegalArgumentException("Cannot use partial id in find method"); } FirstLevelCache cache = transaction.getTransactionLocal().firstLevelCache(); if (cache.containsKey(id)) { return cache.peek(id) .map(entity -> toView(viewType, schema, entity)) .orElse(null); } markKeyRead(id); return transaction.doInTransaction("find(" + id + ")", type, shard -> shard.find(id, viewType)); } @Override @SuppressWarnings("unchecked") public <ID extends Entity.Id<T>> List<T> find(Range<ID> range) { transaction.getWatcher().markRangeRead(type, range); return findAll0().stream() .filter(e -> range.contains((ID) e.getId())) .sorted(EntityIdSchema.SORT_ENTITY_BY_ID) .collect(toList()); } @Override @SuppressWarnings("unchecked") public <ID extends Entity.Id<T>> List<ID> findIds(Range<ID> range) { return find(range).stream() .map(e -> (ID) e.getId()) .collect(toList()); } @Override public <V extends View, ID extends Entity.Id<T>> List<V> find(Class<V> viewType, Range<ID> range) { return find(range).stream() .map(entity -> toView(viewType, schema, entity)) .collect(toList()); } @Override public <V extends View, ID extends Entity.Id<T>> List<V> find(Class<V> viewType, Set<ID> ids) { return find(viewType, ids, null, EntityExpressions.defaultOrder(getType()), null); } @Override public <V extends View, ID extends Entity.Id<T>> List<V> find( Class<V> viewType, Set<ID> ids, @Nullable FilterExpression<T> filter, @Nullable OrderExpression<T> orderBy, @Nullable Integer limit ) { if (ids.isEmpty()) { return List.of(); } return find(ids, filter, orderBy, limit).stream() .map(entity -> toView(viewType, schema, entity)) .collect(toList()); } @Override public <ID extends Entity.Id<T>> List<T> find( Set<ID> ids, @Nullable FilterExpression<T> filter, @Nullable OrderExpression<T> orderBy, @Nullable Integer limit ) { var found = findUncached(ids, filter, orderBy, limit); return postLoad(found); } @Override public <ID extends Entity.Id<T>> List<T> findUncached( Set<ID> ids, @Nullable FilterExpression<T> filter, @Nullable OrderExpression<T> orderBy, @Nullable Integer limit ) { if (ids.isEmpty()) { return List.of(); } EntityIdSchema<Entity.Id<T>> idSchema = schema.getIdSchema(); Set<Map<String, Object>> idsSet = ids.stream().map(idSchema::flatten).collect(toUnmodifiableSet()); Set<Set<String>> idFieldsSet = idsSet.stream().map(Map::keySet).collect(toUnmodifiableSet()); Preconditions.checkArgument(idFieldsSet.size() > 0, "ids must have at least one non-null field"); Preconditions.checkArgument(idFieldsSet.size() == 1, "ids must have nulls in the same fields"); Set<String> idFields = Iterables.getOnlyElement(idFieldsSet); ids.forEach(this::markKeyRead); Stream<T> result = getAllEntries().stream() .filter(e -> idsSet.contains( idSchema.flatten(e.getId()).entrySet().stream() .filter(entry -> idFields.contains(entry.getKey())) .collect(toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue)) )); if (filter != null) { result = result.filter(InMemoryQueries.toPredicate(filter)); } if (orderBy != null) { result = result.sorted(InMemoryQueries.toComparator(orderBy)); } if (limit != null) { result = result.limit(limit); } return result.toList(); } @Override public <V extends View, KEY> List<V> find( Class<V> viewType, String indexName, Set<KEY> keys, @Nullable FilterExpression<T> filter, @Nullable OrderExpression<T> orderBy, @Nullable Integer limit ) { if (keys.isEmpty()) { return List.of(); } return find(indexName, keys, filter, orderBy, limit).stream() .map(entity -> toView(viewType, schema, entity)) .toList(); } @Override public <KEY> List<T> find( String indexName, Set<KEY> keys, @Nullable FilterExpression<T> filter, @Nullable OrderExpression<T> orderBy, @Nullable Integer limit ) { if (keys.isEmpty()) { return List.of(); } @SuppressWarnings("unchecked") Class<KEY> keyType = (Class<KEY>) Iterables.getFirst(keys, null).getClass(); Schema<KEY> keySchema = ObjectSchema.of(keyType); Set<Map<String, Object>> keysSet = keys.stream().map(keySchema::flatten).collect(toUnmodifiableSet()); Set<Set<String>> keyFieldsSet = keysSet.stream().map(Map::keySet).collect(toUnmodifiableSet()); Preconditions.checkArgument(keyFieldsSet.size() != 0, "keys should have at least one non-null field"); Preconditions.checkArgument(keyFieldsSet.size() == 1, "keys should have nulls in the same fields"); Set<String> keyFields = Iterables.getOnlyElement(keyFieldsSet); Schema.Index globalIndex = schema.getGlobalIndexes().stream() .filter(i -> i.getIndexName().equals(indexName)) .findAny() .orElseThrow(() -> new IllegalArgumentException( "Entity `%s` doesn't have index `%s`".formatted(schema.getName(), indexName) )); Set<String> indexKeys = Set.copyOf(globalIndex.getFieldNames()); Set<String> missingInIndexKeys = Sets.difference(keyFields, indexKeys); Preconditions.checkArgument( missingInIndexKeys.isEmpty(), "Index `%s` of entity `%s` doesn't contain key(s): [%s]".formatted( indexName, schema.getName(), String.join(", ", missingInIndexKeys) ) ); Preconditions.checkArgument( isPrefixedFields(globalIndex.getFieldNames(), keyFields), "FindIn(keys) is allowed only by the prefix of the index key fields, index key: %s, query uses the fields: %s" .formatted(globalIndex.getFieldNames(), keyFields) ); for (Map<String, Object> id : keysSet) { transaction.getWatcher().markRangeRead(type, id); } Stream<T> result = getAllEntries().stream() .filter(e -> keysSet.contains( schema.flatten(e).entrySet().stream() .filter(field -> keyFields.contains(field.getKey())) .collect(toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue)) )); if (filter != null) { result = result.filter(InMemoryQueries.toPredicate(filter)); } if (orderBy != null) { result = result.sorted(InMemoryQueries.toComparator(orderBy)); } if (limit != null) { result = result.limit(limit); } return postLoad(result.toList()); } private boolean isPrefixedFields(List<String> keyFields, Set<String> fields) { for (var keyField : keyFields.subList(0, fields.size())) { if (!fields.contains(keyField)) { return false; } } return true; } private <ID extends Entity.Id<T>> void markKeyRead(ID id) { EntityIdSchema<Entity.Id<T>> idSchema = schema.getIdSchema(); if (idSchema.flattenFieldNames().size() != idSchema.flatten(id).size()) { // Partial key, will throw error when not searching by PK prefix transaction.getWatcher().markRangeRead(type, Range.create(id, id)); } else { transaction.getWatcher().markRowRead(type, id); } } @Override @SuppressWarnings("unchecked") public <ID extends Entity.Id<T>> List<ID> findIds(Set<ID> ids) { return find(ids).stream() .map(e -> (ID) e.getId()) .sorted(schema.getIdSchema()) .toList(); } @Override public T insert(T tt) { T t = tt.preSave(); transaction.getWatcher().markRowRead(type, t.getId()); transaction.doInWriteTransaction("insert(" + t + ")", type, shard -> shard.insert(t)); transaction.getTransactionLocal().firstLevelCache().put(t); transaction.getTransactionLocal().projectionCache().save(t); return t; } @Override public T save(T tt) { T t = tt.preSave(); transaction.doInWriteTransaction("save(" + t + ")", type, shard -> shard.save(t)); transaction.getTransactionLocal().firstLevelCache().put(t); transaction.getTransactionLocal().projectionCache().save(t); return t; } @Override public void delete(Entity.Id<T> id) { transaction.doInWriteTransaction("delete(" + id + ")", type, shard -> shard.delete(id)); transaction.getTransactionLocal().firstLevelCache().putEmpty(id); transaction.getTransactionLocal().projectionCache().delete(id); } @Override public void deleteAll() { transaction.doInWriteTransaction("deleteAll(" + type.getName() + ")", type, WriteTxDataShard::deleteAll); } private List<T> getAllEntries() { return transaction.doInTransaction("findAll(" + type.getName() + ")", type, ReadOnlyTxDataShard::findAll); } private List<T> findAll0() { List<T> all = getAllEntries(); return postLoad(all); } @Override public Stream<T> streamAll(int batchSize) { return streamPartial(null, batchSize); } @Override public <ID extends Entity.Id<T>> Stream<T> streamPartial(ID partial, int batchSize) { Preconditions.checkArgument(1 <= batchSize && batchSize <= 5000, "batchSize must be in range [1, 5000], got %s", batchSize); Range<ID> range = partial == null ? null : Range.create(partial); markRangeRead(range); return streamPartial0(range); } private <ID extends Entity.Id<T>> Stream<T> streamPartial0(@Nullable Range<ID> range) { return (range == null ? findAll() : find(range)).stream(); } @Override public <V extends ViewId<T>> Stream<V> streamAll(Class<V> viewType, int batchSize) { return streamPartial(viewType, null, batchSize); } @Override public <ID extends Entity.Id<T>, V extends ViewId<T>> Stream<V> streamPartial( Class<V> viewType, ID partial, int batchSize ) { return streamPartial(partial, batchSize).map(e -> toView(viewType, schema, e)); } @Override public <ID extends Entity.Id<T>> Stream<ID> streamAllIds(int batchSize) { return streamPartialIds(null, batchSize); } @Override @SuppressWarnings("unchecked") public <ID extends Entity.Id<T>> Stream<ID> streamPartialIds(ID partial, int batchSize) { Preconditions.checkArgument(1 <= batchSize && batchSize <= 10000, "batchSize must be in range [1, 10000], got %s", batchSize); Range<ID> range = partial == null ? null : Range.create(partial); markRangeRead(range); return streamPartial0(range).map(e -> (ID) e.getId()); } private <ID extends Entity.Id<T>> void markRangeRead(Range<ID> range) { if (range == null) { transaction.getWatcher().markTableRead(type); } else { transaction.getWatcher().markRangeRead(type, range); } } private <ID extends Entity.Id<T>> Stream<T> readTableStream(ReadTableParams<ID> params) { if (!transaction.getOptions().getIsolationLevel().isReadOnly()) {
throw new IllegalTransactionIsolationLevelException("readTable", transaction.getOptions().getIsolationLevel());
12
2023-12-05 15:57:58+00:00
24k
Vera-Firefly/PojavLauncher-Experimental-Edition
app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/lifecycle/ContextAwareDoneListener.java
[ { "identifier": "INTENT_MINECRAFT_VERSION", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/MainActivity.java", "snippet": "public static final String INTENT_MINECRAFT_VERSION = \"intent_version\";" }, { "identifier": "MainActivity", "path": "app_pojavlauncher/src/main/java/net/...
import static net.kdt.pojavlaunch.MainActivity.INTENT_MINECRAFT_VERSION; import android.app.Activity; import android.content.Context; import android.content.Intent; import net.kdt.pojavlaunch.MainActivity; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.lifecycle.ContextExecutor; import net.kdt.pojavlaunch.lifecycle.ContextExecutorTask; import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper; import net.kdt.pojavlaunch.tasks.AsyncMinecraftDownloader; import net.kdt.pojavlaunch.utils.NotificationUtils;
20,179
package net.kdt.pojavlaunch.lifecycle; public class ContextAwareDoneListener implements AsyncMinecraftDownloader.DoneListener, ContextExecutorTask { private final String mErrorString; private final String mNormalizedVersionid; public ContextAwareDoneListener(Context baseContext, String versionId) { this.mErrorString = baseContext.getString(R.string.mc_download_failed); this.mNormalizedVersionid = versionId; } private Intent createGameStartIntent(Context context) { Intent mainIntent = new Intent(context, MainActivity.class); mainIntent.putExtra(INTENT_MINECRAFT_VERSION, mNormalizedVersionid); mainIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); return mainIntent; } @Override public void onDownloadDone() { ProgressKeeper.waitUntilDone(()->ContextExecutor.execute(this)); } @Override public void onDownloadFailed(Throwable throwable) { Tools.showErrorRemote(mErrorString, throwable); } @Override public void executeWithActivity(Activity activity) { try { Intent gameStartIntent = createGameStartIntent(activity); activity.startActivity(gameStartIntent); activity.finish(); android.os.Process.killProcess(android.os.Process.myPid()); //You should kill yourself, NOW! } catch (Throwable e) { Tools.showError(activity.getBaseContext(), e); } } @Override public void executeWithApplication(Context context) { Intent gameStartIntent = createGameStartIntent(context); // Since the game is a separate process anyway, it does not matter if it gets invoked // from somewhere other than the launcher activity. // The only problem may arise if the launcher starts doing something when the user starts the notification. // So, the notification is automatically removed once there are tasks ongoing in the ProgressKeeper
package net.kdt.pojavlaunch.lifecycle; public class ContextAwareDoneListener implements AsyncMinecraftDownloader.DoneListener, ContextExecutorTask { private final String mErrorString; private final String mNormalizedVersionid; public ContextAwareDoneListener(Context baseContext, String versionId) { this.mErrorString = baseContext.getString(R.string.mc_download_failed); this.mNormalizedVersionid = versionId; } private Intent createGameStartIntent(Context context) { Intent mainIntent = new Intent(context, MainActivity.class); mainIntent.putExtra(INTENT_MINECRAFT_VERSION, mNormalizedVersionid); mainIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); return mainIntent; } @Override public void onDownloadDone() { ProgressKeeper.waitUntilDone(()->ContextExecutor.execute(this)); } @Override public void onDownloadFailed(Throwable throwable) { Tools.showErrorRemote(mErrorString, throwable); } @Override public void executeWithActivity(Activity activity) { try { Intent gameStartIntent = createGameStartIntent(activity); activity.startActivity(gameStartIntent); activity.finish(); android.os.Process.killProcess(android.os.Process.myPid()); //You should kill yourself, NOW! } catch (Throwable e) { Tools.showError(activity.getBaseContext(), e); } } @Override public void executeWithApplication(Context context) { Intent gameStartIntent = createGameStartIntent(context); // Since the game is a separate process anyway, it does not matter if it gets invoked // from somewhere other than the launcher activity. // The only problem may arise if the launcher starts doing something when the user starts the notification. // So, the notification is automatically removed once there are tasks ongoing in the ProgressKeeper
NotificationUtils.sendBasicNotification(context,
7
2023-12-01 16:16:12+00:00
24k
kawashirov/distant-horizons
common/src/main/java/com/seibel/distanthorizons/common/wrappers/worldGeneration/step/StepFeatures.java
[ { "identifier": "ChunkWrapper", "path": "common/src/main/java/com/seibel/distanthorizons/common/wrappers/chunk/ChunkWrapper.java", "snippet": "public class ChunkWrapper implements IChunkWrapper\n{\n\tprivate static final Logger LOGGER = DhLoggerBuilder.getLogger();\n\t\n\t/** useful for debugging, but c...
import net.minecraft.world.level.chunk.ProtoChunk; import net.minecraft.world.level.levelgen.Heightmap; import java.util.ArrayList; import com.seibel.distanthorizons.common.wrappers.chunk.ChunkWrapper; import com.seibel.distanthorizons.common.wrappers.worldGeneration.BatchGenerationEnvironment; import com.seibel.distanthorizons.common.wrappers.worldGeneration.ThreadedParameters; import com.seibel.distanthorizons.common.wrappers.worldGeneration.mimicObject.DhLitWorldGenRegion; import com.seibel.distanthorizons.core.util.gridList.ArrayGridList; import net.minecraft.ReportedException; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ChunkStatus;
14,965
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.common.wrappers.worldGeneration.step; #if POST_MC_1_18_2 #endif public final class StepFeatures { public static final ChunkStatus STATUS = ChunkStatus.FEATURES; private final BatchGenerationEnvironment environment; public StepFeatures(BatchGenerationEnvironment batchGenerationEnvironment) { this.environment = batchGenerationEnvironment; } public void generateGroup(
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.common.wrappers.worldGeneration.step; #if POST_MC_1_18_2 #endif public final class StepFeatures { public static final ChunkStatus STATUS = ChunkStatus.FEATURES; private final BatchGenerationEnvironment environment; public StepFeatures(BatchGenerationEnvironment batchGenerationEnvironment) { this.environment = batchGenerationEnvironment; } public void generateGroup(
ThreadedParameters tParams, DhLitWorldGenRegion worldGenRegion,
3
2023-12-04 11:41:46+00:00
24k
shawn-sheep/Activity_Diary
app/src/main/java/de/rampro/activitydiary/ui/history/HistoryActivity.java
[ { "identifier": "ActivityDiaryApplication", "path": "app/src/main/java/de/rampro/activitydiary/ActivityDiaryApplication.java", "snippet": "public class ActivityDiaryApplication extends Application {\n\n private static Context context;\n\n public void onCreate() {\n SpeechUtility.createUtili...
import android.app.LoaderManager; import android.app.SearchManager; import android.content.AsyncQueryHandler; import android.content.ContentProviderClient; import android.content.ContentValues; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import androidx.cursoradapter.widget.CursorAdapter; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.SearchView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.TextView; import android.widget.Toast; import java.text.ParseException; import java.text.SimpleDateFormat; import de.rampro.activitydiary.ActivityDiaryApplication; import de.rampro.activitydiary.R; import de.rampro.activitydiary.db.ActivityDiaryContentProvider; import de.rampro.activitydiary.db.ActivityDiaryContract; import de.rampro.activitydiary.ui.generic.BaseActivity; import de.rampro.activitydiary.ui.generic.DetailRecyclerViewAdapter; import de.rampro.activitydiary.ui.generic.EditActivity; import de.rampro.activitydiary.ui.main.NoteEditDialog;
21,327
/* * ActivityDiary * * Copyright (C) 2017-2018 Raphael Mack http://www.raphael-mack.de * Copyright (C) 2018 Bc. Ondrej Janitor * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.rampro.activitydiary.ui.history; /* * Show the history of the Diary. * */ public class HistoryActivity extends BaseActivity implements LoaderManager.LoaderCallbacks<Cursor>,
/* * ActivityDiary * * Copyright (C) 2017-2018 Raphael Mack http://www.raphael-mack.de * Copyright (C) 2018 Bc. Ondrej Janitor * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.rampro.activitydiary.ui.history; /* * Show the history of the Diary. * */ public class HistoryActivity extends BaseActivity implements LoaderManager.LoaderCallbacks<Cursor>,
NoteEditDialog.NoteEditDialogListener,
6
2023-12-02 12:36:40+00:00
24k
Ethylene9160/Chess
src/chess/main/WebStartPanel.java
[ { "identifier": "PanelBase", "path": "src/chess/panels/PanelBase.java", "snippet": "public abstract class PanelBase extends JPanel {\n public PanelType type;\n protected int ax=-1,ay=-1,bx=-1,by=-1;\n protected int currentPlayer, xOld, yOld;\n\n protected Point aOldPoint = new Point(0,0), aC...
import chess.panels.PanelBase; import chess.panels.WebButtons; import chess.panels.WebPanel; import chess.util.Constants; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import static chess.panels.PanelBase.FIRST;
16,394
package chess.main; public class WebStartPanel extends JPanel { private WebPanel webPanel; private WebButtons webButtons; public WebStartPanel(String IP, int port){ super(); webPanel = new WebPanel(new JLabel(FIRST), IP, port); webButtons = new WebButtons(webPanel);
package chess.main; public class WebStartPanel extends JPanel { private WebPanel webPanel; private WebButtons webButtons; public WebStartPanel(String IP, int port){ super(); webPanel = new WebPanel(new JLabel(FIRST), IP, port); webButtons = new WebButtons(webPanel);
webPanel.setBounds(0, 0, Constants.PANEL_WEIGHT, PanelBase.BOARD_HEIGHT);
0
2023-12-01 02:33:32+00:00
24k
ynewmark/vector-lang
compiler/src/main/java/org/vectorlang/compiler/App.java
[ { "identifier": "CodeBase", "path": "compiler/src/main/java/org/vectorlang/compiler/ast/CodeBase.java", "snippet": "public class CodeBase {\n \n private final FunctionStatement[] functions;\n\n public CodeBase(FunctionStatement[] functions) {\n this.functions = functions;\n }\n\n p...
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.List; import org.vectorlang.compiler.ast.CodeBase; import org.vectorlang.compiler.compiler.Chunk; import org.vectorlang.compiler.compiler.Compiler; import org.vectorlang.compiler.compiler.Linker; import org.vectorlang.compiler.compiler.Pruner; import org.vectorlang.compiler.compiler.TypeFailure; import org.vectorlang.compiler.compiler.Typer; import org.vectorlang.compiler.parser.Lexer; import org.vectorlang.compiler.parser.Parser; import org.vectorlang.compiler.parser.Token;
15,430
package org.vectorlang.compiler; public class App { public static void main(String[] args) { if (args.length < 1) { System.err.println("Provide a file to compile"); System.exit(1); } File file = new File(args[0]); FileReader reader; StringBuilder builder = new StringBuilder(); try { reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader); bufferedReader.lines().forEach((String line) -> { builder.append(line).append('\n'); }); bufferedReader.close(); } catch (FileNotFoundException e) { System.err.println("File " + args[0] + " not found"); System.exit(1); } catch (IOException e) { System.err.println("Failed to close file"); System.exit(1); } String code = builder.toString(); Lexer lexer = new Lexer(code); List<Token> tokens = lexer.lex(); Parser parser = new Parser(); CodeBase codeBase = parser.parse(tokens); Typer typer = new Typer(); Pruner pruner = new Pruner();
package org.vectorlang.compiler; public class App { public static void main(String[] args) { if (args.length < 1) { System.err.println("Provide a file to compile"); System.exit(1); } File file = new File(args[0]); FileReader reader; StringBuilder builder = new StringBuilder(); try { reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader); bufferedReader.lines().forEach((String line) -> { builder.append(line).append('\n'); }); bufferedReader.close(); } catch (FileNotFoundException e) { System.err.println("File " + args[0] + " not found"); System.exit(1); } catch (IOException e) { System.err.println("Failed to close file"); System.exit(1); } String code = builder.toString(); Lexer lexer = new Lexer(code); List<Token> tokens = lexer.lex(); Parser parser = new Parser(); CodeBase codeBase = parser.parse(tokens); Typer typer = new Typer(); Pruner pruner = new Pruner();
org.vectorlang.compiler.compiler.Compiler compiler = new Compiler();
2
2023-11-30 04:22:36+00:00
24k