Jump to content

Botre

Members
  • Posts

    5883
  • Joined

  • Last visited

  • Days Won

    18
  • Feedback

    100%

Everything posted by Botre

  1. A very basic snippet, I keep seeing people rewriting negations manually way too often. Allows to you create inversions/negations of filters. Example final Filter<String> IS_EMPTY = s -> s.isEmpty(); final Filter<String> IS_NOT_EMPTY = negate(IS_EMPTY); Snippet /** * Returns a filter that represents the logical negation of the supplied filter. * * @return a filter that represents the logical negation of the supplied filter */ public static final <T> Filter<T> negate(Filter<T> filter) { return e -> !filter.match(e); }
  2. Some dark ones in there
  3. Use a BooleanSupplier instead of a plain boolean ^^ https://docs.oracle.com/javase/8/docs/api/java/util/function/BooleanSupplier.html
  4. WIP. Automatically check and updates a value, which is one of the most common tasks of a script. Can also be used for caching data and verifying its integrity. Example package org.botre.util; import java.util.function.Predicate; import org.botre.functional.FiPr; import org.osbot.rs07.api.model.NPC; import org.osbot.rs07.script.Script; import org.osbot.rs07.script.ScriptManifest; @ScriptManifest(author = "Botre", info = "", logo = "", name = "AutoExample", version = 0) public class AutoExample extends Script { public Predicate<NPC> VALIDATOR = npc -> npc != null && npc.exists() && npc.getName().equals("Man") && (npc.getInteracting() == null || npc.getInteracting().equals(myPlayer())) && getMap().canReach(npc.getPosition()); private Auto<NPC> target = new Auto<NPC>(() -> getNpcs().closest(FiPr.adapt(VALIDATOR.and(npc -> !npc.isUnderAttack()))), VALIDATOR); @Override public int onLoop() throws InterruptedException { if(!getCombat().isFighting() && target.validate()) { target.get().interact("Attack"); } return 500; } } Snippet: package org.botre.util; import java.util.Optional; import java.util.function.Predicate; import java.util.function.Supplier; public class Auto<T> { private Optional<T> optional; private Supplier<T> supplier; private Predicate<T> validator; public Auto(T value, Supplier<T> supplier, Predicate<T> validator) { this.optional = Optional.ofNullable(value); this.supplier = supplier; this.validator = validator; } public Auto(Supplier<T> supplier, Predicate<T> validator) { this(null, supplier, validator); } public T get() { return optional.get(); } public void supply() { optional = Optional.ofNullable(supplier.get()); } public boolean validate() { if(!optional.isPresent() || !validator.test(optional.get())) supply(); else return true; return optional.isPresent() && validator.test(optional.get()); } }
  5. No. I'm pretty sure ItemContainer's interact(slot, action) method does try to define an Item internally, probably similarly to the way you do it. So he should be fine ^^ PS: here's an old snippet of mine if you're looking for alternative patterns :p http://osbot.org/forum/topic/68138-using-certain-slots-help/?p=750312
  6. You win some, you lose some. There would be no value in botting if it were riskless.
  7. Indeed x) You can decorate strategically or just go all-in, I prefer the former approach so I don't get hugely verbose traces every time I forget a simple null check :p I personally use them mostly to decorate IOException and its sub-classes and Swing-related exceptions.
  8. Luckily enough I rarely have to rely on this information When it's usefull it tends to be very usefull and often ends up saving quite a lot of time though :p
  9. Good job! The buttons seem a bit supersized though x) I like the text balloons, how did you manage to do that in Swing?
  10. Useful to spot nasty jvm, system and memory-specific issues (outdated java, exotic operating system, incorrect memory allocation, etc...). I personally only decorate critical / fatal exceptions with this. There's no point in casually wrapping it around everything (unless you really love verbose stack traces). Example: public class Test { public static void main(String[] args) { try { System.out.println(1/0); } catch (Exception e) { ThrowableDecorator.withSystemAndMemoryInformation(e).printStackTrace(); } } } Snippet: public final class ThrowableDecorator { private ThrowableDecorator() { } public static final Throwable withSystemAndMemoryInformation(Throwable throwable) { StringBuilder sb = new StringBuilder(); //System sb.append("\n\tSystem information:"); System.getProperties().entrySet().forEach(entry -> sb.append("\n\t\t" + entry.getKey().toString() + ": " + entry.getValue().toString())); //Memory sb.append("\n\tMemory information:"); sb.append("\n\t\tAvailable processors (cores): " + Runtime.getRuntime().availableProcessors()); sb.append("\n\t\tFree memory (bytes): " + Runtime.getRuntime().freeMemory()); sb.append("\n\t\tMaximum memory (bytes): " + Runtime.getRuntime().maxMemory()); sb.append("\n\t\tTotal memory (bytes): " + Runtime.getRuntime().totalMemory()); return new Throwable(sb.toString(), throwable); } } Example trace: java.lang.Throwable: System information: java.runtime.name: Java(TM) SE Runtime Environment sun.boot.library.path: C:\Program Files\Java\jre1.8.0_77\bin java.vm.version: 25.77-b03 java.vm.vendor: Oracle Corporation java.vendor.url: http://java.oracle.com/ path.separator: ; java.vm.name: Java HotSpot(TM) 64-Bit Server VM file.encoding.pkg: sun.io user.country: GB user.script: sun.java.launcher: SUN_STANDARD sun.os.patch.level: java.vm.specification.name: Java Virtual Machine Specification user.dir: ***** java.runtime.version: 1.8.0_77-b03 java.awt.graphicsenv: sun.awt.Win32GraphicsEnvironment java.endorsed.dirs: C:\Program Files\Java\jre1.8.0_77\lib\endorsed os.arch: amd64 java.io.tmpdir: ***** line.separator: java.vm.specification.vendor: Oracle Corporation user.variant: os.name: Windows 10 sun.jnu.encoding: ****** java.library.path: ***** java.specification.name: Java Platform API Specification java.class.version: 52.0 sun.management.compiler: HotSpot 64-Bit Tiered Compilers os.version: 10.0 user.home:***** user.timezone: java.awt.printerjob: sun.awt.windows.WPrinterJob file.encoding: Cp1252 java.specification.version: 1.8 java.class.path: ***** user.name: bjorn java.vm.specification.version: 1.8 sun.java.command: org.botre.exception.Test java.home: C:\Program Files\Java\jre1.8.0_77 sun.arch.data.model: 64 user.language: en java.specification.vendor: Oracle Corporation awt.toolkit: sun.awt.windows.WToolkit java.vm.info: mixed mode java.version: 1.8.0_77 java.ext.dirs: ***** java.vendor: Oracle Corporation file.separator: \ java.vendor.url.bug: http://bugreport.sun.com/bugreport/ sun.io.unicode.encoding: UnicodeLittle sun.cpu.endian: little sun.desktop: windows sun.cpu.isalist: amd64 Memory information: Available processors (cores): 4 Free memory (bytes): 253398816 Maximum memory (bytes): 3795845120 Total memory (bytes): 257425408 at org.botre.exception.ThrowableDecorator.withSystemAndMemoryInformation(ThrowableDecorator.java:21) at org.botre.exception.Test.main(Test.java:9) Caused by: java.lang.ArithmeticException: / by zero at org.botre.exception.Test.main(Test.java:7)
  11. Will be applying for SDN approval shortly! I shall contact you all for testing once this script reaches BETA
  12. Updated to support autoscrolling
  13. Updated to use BooleanSupplier instead of Predicate, also added parameter checking for timeout decorator.
  14. Updated from: http://osbot.org/forum/topic/91630-snippet-predicate-filter-adapter/ Adapts an OSBot Filter to work as a Java Util Predicate and vice versa. Useful if you don't wan't to rewrite your Predicate and / or Filter libraries but still want to enjoy the benefits provided by both worlds. If someone has a cleaner method, please do let me know! Example: package utils; import java.util.function.Predicate; import org.osbot.rs07.api.filter.Filter; import org.osbot.rs07.api.model.NPC; public class Example { public static void main(String[] args) { Filter<NPC> filter = npc -> npc.exists(); Predicate<NPC> predicate = FilterPredicate.fromFilter(filter); filter = FilterPredicate.fromPredicate(predicate); } } Snippet: package utils; import java.util.function.Predicate; import org.osbot.rs07.api.filter.Filter; /* * Adapts an OSBot Filter to work as a Java Util Predicate and vice versa. * */ public class FilterPredicate<V> implements Filter<V>, Predicate<V> { protected boolean _test(V value) { return false; } @Override public boolean match(V value) { return _test(value); } @Override public boolean test(V value) { return _test(value); } public static final <T> FilterPredicate<T> fromFilter(Filter<T> filter) { return new FilterPredicate<T>() { @Override protected boolean _test(T value) { return filter.match(value); } }; } public static final <T> FilterPredicate<T> fromPredicate(Predicate<T> predicate) { return new FilterPredicate<T>() { @Override protected boolean _test(T value) { return predicate.test(value); } }; } }
  15. FilteredComboBox Inspiration: http://stackoverflow.com/questions/10368856/jcombobox-filter-in-java-look-and-feel-independent Example: public static void main(String[] args) { JFrame frame = new JFrame("FilteredComboBoxExample"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JPanel content = new JPanel(); frame.setContentPane(content); FilteredComboBox<Skill> filteredComboBox = new FilteredComboBox<>(Skill.values(), s -> s.toString()); filteredComboBox.setPreferredSize(new Dimension(240, 60)); content.add(filteredComboBox); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } Snippet: Not very MVC friendly but hey this is Swing after all. import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Function; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JTextField; public class FilteredComboBox<T> extends JComboBox<T> { private static final long serialVersionUID = 283907792618669032L; @SuppressWarnings("unused") private List<T> full; private List<T> filtered; @SuppressWarnings("unused") private Function<T, String> fetcher; private JTextField field; @SuppressWarnings({ "unchecked", "rawtypes" }) public FilteredComboBox(List<T> full, Function<T, String> fetcher) { setModel(new DefaultComboBoxModel(full.toArray())); this.full = full; this.fetcher = fetcher; setSelectedIndex(0); setEditable(true); field = (JTextField) getEditor().getEditorComponent(); field.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent k) { String input = field.getText(); int code = k.getKeyCode(); if(!k.isActionKey() && k.getModifiers() == 0 && code != KeyEvent.VK_ENTER && code != KeyEvent.VK_CONTROL && code != KeyEvent.VK_ESCAPE) { filtered = new ArrayList<>(); for (int i = 0; i < full.size(); i++) { if (fetcher.apply(full.get(i)).toLowerCase().contains(input.toLowerCase())) { filtered.add(full.get(i)); } } if (filtered.size() > 0) { setModel(new DefaultComboBoxModel(filtered.toArray())); setSelectedItem(input); showPopup(); } else { setModel(new DefaultComboBoxModel(full.toArray())); setSelectedItem("No result matching: \" " + input + " \""); field.selectAll(); showPopup(); } } } }); } public FilteredComboBox(T[] full, Function<T, String> fetcher) { this(Arrays.asList(full), fetcher); } }
  16. Shame on me sensei but I have not yet read up on method references. It's on my TODO list for next week though
  17. "Functional interfaces provide target types for lambda expressions and method references." https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html In order to further my functional programming adventures I wrote a couple of (arbitrary and overly simplified) examples for almost every interface from java.util.function. Hope these help you understand / recognize the package in question a bit more. package org.dreamstream.sandbox.example.function; import java.util.Random; import java.util.function.*; public class FunctionPackageExample { public static void main(String[] args) { /** * Predicate * Represents a predicate (boolean-valued function) of one or two arguments. */ final Predicate<String> IS_EMPTY = s -> s.isEmpty(); System.out.println(IS_EMPTY.test("")); // = true final BiPredicate<String, String> ARE_EQUAL = (s1, s2) -> s1.equals(s2); System.out.println(ARE_EQUAL.test("Test1", "Test2")); // = false final IntPredicate IS_EVEN = i -> i % 2 == 0; System.out.println(IS_EVEN.test(2)); // = true final LongPredicate CAN_TRUNCATE_TO_INT = l -> l >= Integer.MIN_VALUE && l <= Integer.MAX_VALUE ; System.out.println(CAN_TRUNCATE_TO_INT.test(Integer.MAX_VALUE + 1l)); // = false final DoublePredicate IS_CLOSE_TO_ZERO = d -> Math.abs(d) < 2 * Double.MIN_VALUE; System.out.println(IS_CLOSE_TO_ZERO.test(0.0)); // = true /** * Function * Represents a function that accepts one or two arguments and produces a result. */ Function<String, Integer> CAST = s -> Integer.parseInt(s); System.out.println(CAST.apply("1") + 2); // = 3 BiFunction<Integer, Integer, String> SUM_TO_STRING = (i1, i2) -> Integer.toString(i1 + i2); System.out.println(SUM_TO_STRING.apply(5, 10) + "Hi"); // = 15Hi IntFunction<Double> AS_DOUBLE = i -> i * 1d; System.out.println(AS_DOUBLE.apply(1)); // = 1.0 LongFunction<Integer> AS_INTEGER = l -> (int)l; System.out.println(AS_INTEGER.apply(Long.MAX_VALUE)); // = -1 DoubleFunction<Integer> DOUBLE_AS_INTEGER = d -> (int)d; System.out.println(DOUBLE_AS_INTEGER.apply(2.5)); // = 2 /** * Consumer * Represents an operation that accepts one or two input arguments and returns no result. */ final Consumer<String> PRINT = s -> System.out.println(s); PRINT.accept("Yes / No"); // = "Yes / No" final BiConsumer<String, Integer> PRINT_STRING_AND_INTEGER = (s, i) -> System.out.println("String: " + s + " Ingeger: " + i); PRINT_STRING_AND_INTEGER.accept("Test", 3); // = "String: Test Ingeger: 3" final IntConsumer PRINT_I = i -> System.out.println(i); PRINT_I.accept(3); // = 3 final LongConsumer PRINT_L = l -> System.out.println(l); PRINT_L.accept(2); // = 2 final DoubleConsumer PRINT_D = d -> System.out.println(d); PRINT_D.accept(2.5); // = 2.5 final ObjIntConsumer<String> PRINT_I_S = (s, i) -> System.out.println(s + " " + i); PRINT_I_S.accept("A", 1); // = "A 1" final ObjLongConsumer<String> PRINT_L_S = (s, l) -> System.out.println(s + " " + l); PRINT_L_S.accept("B", 2); // = "B 2" final ObjDoubleConsumer<String> PRINT_D_S = (s, d) -> System.out.println(s + " " + d); PRINT_D_S.accept("C", 2.5); // = "C 2.5" /** * Supplier * Represents a supplier of results of a specific type. */ final Supplier<Double> SUPPLY_RANDOM = () -> Math.random(); System.out.println(SUPPLY_RANDOM.get()); // = A double value with a positive sign, greater than or equal to 0.0 and less than 1.0 final BooleanSupplier SUPPLY_TRUE = () -> true; System.out.println(SUPPLY_TRUE.getAsBoolean()); // = true final IntSupplier SUPPLY_EVEN = () -> new Random().nextInt() & -2; System.out.println(SUPPLY_EVEN.getAsInt()); // = An even int value final LongSupplier SUPPLY_ZERO = () -> 0; System.out.println(SUPPLY_ZERO.getAsLong()); // = 0 final DoubleSupplier SUPPLY_MIN = () -> Double.MIN_VALUE; System.out.println(SUPPLY_MIN.getAsDouble()); // = 4.9E-324 /** * ToNumber * Represents functions that accept one or two two arguments and produces a value of a number-type. */ final ToIntFunction<String> CHARACTER_COUNT = s -> s.length(); System.out.println(CHARACTER_COUNT.applyAsInt("Five5")); // = 5 final ToIntBiFunction<String, String> SUM_CHARACTER_COUNT = (s1, s2) -> s1.length() + s2.length(); System.out.println(SUM_CHARACTER_COUNT.applyAsInt("AB", "C")); // = 3 final ToLongFunction<String> THOUSAND_TIMES_CHARACTER_COUNT = s -> s.toCharArray().length * 1000l; System.out.println(THOUSAND_TIMES_CHARACTER_COUNT.applyAsLong("Five5")); // = 5000 final ToLongBiFunction<Long, String> SUM = (l, s) -> l + Integer.parseInt(s); System.out.println(SUM.applyAsLong(300l, "1")); // = 301 final ToDoubleFunction<String> HALF_CHARACTER_COUNT = s -> s.length() / 2d; System.out.println(HALF_CHARACTER_COUNT.applyAsDouble("One")); // = 1.5 final ToDoubleBiFunction<String, String> AVERAGE_CHARACTER_COUNT = (s1, s2) -> (s1.length() + s2.length()) / 2d; System.out.println(AVERAGE_CHARACTER_COUNT.applyAsDouble("One", "Five")); // = 3.5 /** * Operator * Represents an operation on one or two operands of the same type, producing a result of the same type as the operand(s). */ final UnaryOperator<String> REVERSE = s -> new StringBuilder(s).reverse().toString(); System.out.println(REVERSE.apply("test")); // = "tset" final BinaryOperator<String> CONCAT = (s1, s2) -> s1.concat(s2); System.out.println(CONCAT.apply("Hello, ", "World!")); // = "Hello, World!" final IntUnaryOperator DOUBLE = i -> i * 2; System.out.println(DOUBLE.applyAsInt(5)); // = 10 final IntBinaryOperator INTEGER_SUM = (i1, i2) -> i1 + i2; System.out.println(INTEGER_SUM.applyAsInt(9, 3)); // = 12 final LongUnaryOperator NEGATE = l -> -l; System.out.println(NEGATE.applyAsLong(1)); // = -1 final LongBinaryOperator DIFFERENCE = (l1, l2) -> l1 - l2; System.out.println(DIFFERENCE.applyAsLong(1, 3)); // = -2 final DoubleUnaryOperator HALF = d -> d / 2; System.out.println(HALF.applyAsDouble(5)); // = 2.5 final DoubleBinaryOperator AVERAGE = (d1, d2) -> (d1 + d2) / 2; System.out.println(AVERAGE.applyAsDouble(1.0, 2.0)); // = 1.5 } }
  18. If only other people's daddies were as caring as ours :
  19. Some things should, but if you start spamming people with unnecessary warning messages they end up just ignoring them which makes the entire security system redundant :p Eh, agree to disagree I guess.
  20. If a script generates and compiles a second application that should obviously should raise flags The point would not be to monitor which data is sent over a connection (hard to do at compile time ), the point would be to detect at compile time whether a connection is established and warn the user of this (?). You can't micro-manage security scenarios without making life a living hell for script makers and script users So, posting some guards at the principal gates, that warn users about file modification, deletion, outgoing and incoming connections -> sure. But warning the user whenever a db request is made, whenever an image is being downloaded, whenever you're making a screenshot, whenever you are listening for keyboard shortcuts, whenever you send a key-event to the client, etc... -> please no That being said if they can do it in a way that's not too intrusive, eh why not
×
×
  • Create New...