Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

1470
LINES

< > BotCompany Repo | #1005029 // Mocha Doom Single Source With Translator

JavaX source code [tags: use-pretranspiled] - run with: x30.jar

!1005027

// The following comes from: http://tinybrain.de:8080/tb-int/get-transpiled.php?id=1005017&raw=1

import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
public class main {


static String defaultCfg = "\nalwaysrun		true\nchatmacro0		\"No\"\nchatmacro1		\"I'm ready to kick butt!\"\nchatmacro2		\"I'm OK.\"\nchatmacro3		\"I'm not looking too good!\"\nchatmacro4		\"Help!\"\nchatmacro5		\"You suck!\"\nchatmacro6		\"Next time, scumbag...\"\nchatmacro7		\"Come here!\"\nchatmacro8		\"I'll take care of it.\"\nchatmacro9		\"Yes\"\ndetaillevel		0\nfullscreen		true\njoyb_fire		0\njoyb_speed		2\njoyb_strafe		1\njoyb_use		3\nkey_down		115\nkey_fire		157\nkey_left		172\nkey_right		174\nkey_speed		182\nkey_strafe		184\nkey_strafeleft		97\nkey_straferight		100\nkey_up		119\nkey_use		32\nmb_used		2\nmouse_sensitivity		5\nmouseb_fire		0\nmouseb_forward		2\nmouseb_strafe		1\nmusic_volume		8\nscreenblocks		10\nsfx_volume		8\nshow_messages		true\nsnd_channels		3\nuse_joystick		false\nuse_mouse		true\nusegamma		0\n";

public static void main(String[] args) throws Exception {
  renameConsole("Mocha DOOM!");
  File iwad = loadLibrary("#1005008");
  File iwad2 = prepareProgramFile("doom1.wad");
  copyFile(iwad, iwad2);
  File iwad3 = new File(iwad2.getName());
  if (!iwad3.exists())
    throw fail("We are not in the right directory! " + f2s(iwad3.getAbsoluteFile().getParentFile()) + " (should be " + f2s(programDir()) + ")");
    
  File cfgFile = prepareProgramFile("default.cfg");
  if (!cfgFile.exists())
    saveTextFile(cfgFile, defaultCfg.trim());
    
  String[] argz = {"-iwad", f2s(iwad2)};
  printStructure(argz);
  callMain(_getClass("i.Main"), argz);
}


public static void copyFile(File src, File dest) { try {
 
  mkdirsForFile(dest);
  FileInputStream inputStream = new FileInputStream(src.getPath());
  FileOutputStream outputStream = new FileOutputStream(dest.getPath());
  try {
    copyStream(inputStream, outputStream);
    inputStream.close();
  } finally {
    outputStream.close();
  }

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
  static RuntimeException fail() {
    throw new RuntimeException("fail");
  }
  
  static RuntimeException fail(Object msg) {
    throw new RuntimeException(String.valueOf(msg));
  }
  
  static RuntimeException fail(String msg) {
    throw new RuntimeException(unnull(msg));
  }
   
  // disabled for now to shorten some programs 
  /*static RuntimeException fail(S msg, O... args) {
    throw new RuntimeException(format(msg, args));
  }*/
static File loadLibrary(String snippetID) {
  return loadBinarySnippet(snippetID);
}
static File prepareProgramFile(String name) {
  return mkdirsForFile(getProgramFile(name));
}

static File prepareProgramFile(String progID, String name) {
  return mkdirsForFile(getProgramFile(progID, name));
}
static void callMain(Object c, String... args) {
  callOpt(c, "main", new Object[] {args});
}
static String f2s(File f) {
  return f == null ? null : f.getAbsolutePath();
}
  /** writes safely (to temp file, then rename) */
  public static void saveTextFile(String fileName, String contents) throws IOException {
    File file = new File(fileName);
    File parentFile = file.getParentFile();
    if (parentFile != null)
      parentFile.mkdirs();
    String tempFileName = fileName + "_temp";
    File tempFile = new File(tempFileName);
    if (contents != null) {
      if (tempFile.exists()) try {
        String saveName = tempFileName + ".saved." + now();
        copyFile(tempFile, new File(saveName));
      } catch (Throwable e) { printStackTrace(e); }
      FileOutputStream fileOutputStream = new FileOutputStream(tempFile.getPath());
      OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
      PrintWriter printWriter = new PrintWriter(outputStreamWriter);
      printWriter.print(contents);
      printWriter.close();
    }
    
    if (file.exists() && !file.delete())
      throw new IOException("Can't delete " + fileName);

    if (contents != null)
      if (!tempFile.renameTo(file))
        throw new IOException("Can't rename " + tempFile + " to " + file);
  }
  
  public static void saveTextFile(File fileName, String contents) {
    try {
      saveTextFile(fileName.getPath(), contents);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

static void renameConsole(String title) {
  setConsoleTitle(title);
}
static File programDir_mine; // set this to relocate program's data

static File programDir() {
  return programDir(getProgramID());
}

static File programDir(String snippetID) {
  if (programDir_mine != null && sameSnippetID(snippetID, programID()))
    return programDir_mine;
  return new File(javaxDataDir(), formatSnippetID(snippetID));
}

static Class<?> _getClass(String name) {
  try {
    return Class.forName(name);
  } catch (ClassNotFoundException e) {
    return null;
  }
}

static Class _getClass(Object o) {
  return o instanceof Class ? (Class) o : o.getClass();
}

static Class _getClass(Object realm, String name) { try {
 
  return getClass(realm).getClassLoader().loadClass(classNameToVM(name));

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static void printStructure(String prefix, Object o) {
  print(prefix + structure(o));
}

static void printStructure(Object o) {
  print(structure(o));
}



static Class<?> getClass(String name) {
  try {
    return Class.forName(name);
  } catch (ClassNotFoundException e) {
    return null;
  }
}

static Class getClass(Object o) {
  return o instanceof Class ? (Class) o : o.getClass();
}

static Class getClass(Object realm, String name) { try {
 
  try {
    return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
  } catch (ClassNotFoundException e) {
    return null;
  }

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
public static File mkdirsForFile(File file) {
  File dir = file.getParentFile();
  if (dir != null) // is null if file is in current dir
    dir.mkdirs();
  return file;
}

static File javaxDataDir_dir; // can be set to work on different base dir

static File javaxDataDir() {
  return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
static Object callOpt(Object o) {
  if (o == null) return null;
  return callF(o);
}

static Object callOpt(Object o, String method, Object... args) {
  try {
    if (o == null) return null;
    if (o instanceof Class) {
      Method m = callOpt_findStaticMethod((Class) o, method, args, false);
      if (m == null) return null;
      m.setAccessible(true);
      return m.invoke(null, args);
    } else {
      Method m = callOpt_findMethod(o, method, args, false);
      if (m == null) return null;
      m.setAccessible(true);
      return m.invoke(o, args);
    }
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

static Method callOpt_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
  Class _c = c;
  while (c != null) {
    for (Method m : c.getDeclaredMethods()) {
      if (debug)
        System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
      if (!m.getName().equals(method)) {
        if (debug) System.out.println("Method name mismatch: " + method);
        continue;
      }

      if ((m.getModifiers() & Modifier.STATIC) == 0 || !callOpt_checkArgs(m, args, debug))
        continue;

      return m;
    }
    c = c.getSuperclass();
  }
  return null;
}

static Method callOpt_findMethod(Object o, String method, Object[] args, boolean debug) {
  Class c = o.getClass();
  while (c != null) {
    for (Method m : c.getDeclaredMethods()) {
      if (debug)
        System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
      if (m.getName().equals(method) && callOpt_checkArgs(m, args, debug))
        return m;
    }
    c = c.getSuperclass();
  }
  return null;
}

private static boolean callOpt_checkArgs(Method m, Object[] args, boolean debug) {
  Class<?>[] types = m.getParameterTypes();
  if (types.length != args.length) {
    if (debug)
      System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
    return false;
  }
  for (int i = 0; i < types.length; i++)
    if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
      if (debug)
        System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
      return false;
    }
  return true;
}


static String programID;

static String getProgramID() {
  return nempty(programID) ? formatSnippetID(programID) : "?";
}

// TODO: ask JavaX instead
static String getProgramID(Class c) {
  String id = (String) getOpt(c, "programID");
  if (nempty(id))
    return formatSnippetID(id);
  return "?";
}

static String getProgramID(Object o) {
  return getProgramID(getMainClass(o));
}

  static String unnull(String s) {
    return s == null ? "" : s;
  }
  
  static <A> List<A> unnull(List<A> l) {
    return l == null ? emptyList() : l;
  }
  
  static <A> Iterable<A> unnull(Iterable<A> i) {
    return i == null ? emptyList() : i;
  }
  
  static Object[] unnull(Object[] a) {
    return a == null ? new Object[0] : a;
  }
static void setConsoleTitle(String title) {
  callOpt(consoleFrame_gen(), "setTitle", title);
}
static long now_virtualTime;
static long now() {
  return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}

static String formatSnippetID(String id) {
  return "#" + parseSnippetID(id);
}

static String formatSnippetID(long id) {
  return "#" + id;
}
static String programID() {
  return getProgramID();
}
static File getProgramFile(String progID, String fileName) {
  if (new File(fileName).isAbsolute())
    return new File(fileName);
  return new File(getProgramDir(progID), fileName);
}

static File getProgramFile(String fileName) {
  return getProgramFile(getProgramID(), fileName);
}

static void printStackTrace(Throwable e) {
  // we go to system.out now - system.err is nonsense
  print(getStackTrace(e));
}

static void printStackTrace() {
  printStackTrace(new Throwable());
}
static String classNameToVM(String name) {
  return name.replace(".", "$");
}
static String structure(Object o) {
  HashSet refd = new HashSet();
  return structure_2(structure_1(o, new structure_Data(refd)), refd);
}

// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;

static int structure_shareStringsLongerThan = 20;

static class structure_Data {
  int stringSizeLimit;
  IdentityHashMap<Object, Integer> seen = new IdentityHashMap<Object, Integer>();
  HashSet<Integer> refd;
  HashMap<String, Integer> strings = new HashMap<String, Integer>();
  HashSet<String> concepts = new HashSet<String>();
  Class conceptClass = findClass("Concept");
  
  structure_Data(HashSet<Integer> refd) {
  this.refd = refd;}
}

static String structure_1(Object o, structure_Data d) {
  if (o == null) return "null";
  
  // these are never back-referenced (for readability)
  
  if (o instanceof BigInteger)
    return "bigint(" + o + ")";
  
  if (o instanceof Double)
    return "d(" + quote(str(o)) + ")";
    
  if (o instanceof Float)
    return "fl " + quote(str(o));
    
  if (o instanceof Long)
    return o + "L";
  
  if (o instanceof Integer)
    return str(o);
    
  if (o instanceof Boolean)
    return ((Boolean) o).booleanValue() ? "t" : "f";
    
  if (o instanceof Character)
    return quoteCharacter((Character) o);
    
  if (o instanceof File)
    return "File " + quote(((File) o).getPath());
    
  // referencable objects follow
  
  Integer ref = d.seen.get(o);
  if (ref != null) {
    d.refd.add(ref);
    return "r" + ref;
  }
      
  if (o instanceof String && (ref = d.strings.get((String) o)) != null) {
    d.refd.add(ref);
    return "r" + ref;
  }
  
  ref = d.seen.size()+1;
  d.seen.put(o, ref);
  String r = "m" + ref + " "; // marker

  if (o instanceof String) {
    String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
    if (l(s) >= structure_shareStringsLongerThan)
      d.strings.put(s, ref);
    return r + quote(s);
  }
    
  String name = o.getClass().getName();

  StringBuilder buf = new StringBuilder();
  
  if (o instanceof HashSet)
    return r + "hashset " + structure_1(new ArrayList((Set) o), d);

  if (o instanceof TreeSet)
    return r + "treeset " + structure_1(new ArrayList((Set) o), d);
  
  if (o instanceof Collection) {
    for (Object x : (Collection) o) {
      if (buf.length() != 0) buf.append(", ");
      buf.append(structure_1(x, d));
    }
    return r + "[" + buf + "]";
  }
  
  if (o instanceof Map) {
    for (Object e : ((Map) o).entrySet()) {
      if (buf.length() != 0) buf.append(", ");
      buf.append(structure_1(((Map.Entry) e).getKey(), d));
      buf.append("=");
      buf.append(structure_1(((Map.Entry) e).getValue(), d));
    }
    return r + (o instanceof HashMap ? "hm" : "") + "{" + buf + "}";
  }
  
  if (o.getClass().isArray()) {
    if (o instanceof byte[])
      return "ba " + quote(bytesToHex((byte[]) o));

    int n = Array.getLength(o);

    if (o instanceof boolean[]) {
      String hex = boolArrayToHex((boolean[]) o);
      int i = l(hex);
      while (i > 0 && hex.charAt(i-1) == '0' && hex.charAt(i-2) == '0') i -= 2;
      return "boolarray " + n + " " + quote(substring(hex, 0, i));
    }
    
    String atype = "array", sep = ", ";

    if (o instanceof int[]) {
      //ret "intarray " + quote(intArrayToHex((int[]) o));
      atype = "intarray";
      sep = " ";
    }

    for (int i = 0; i < n; i++) {
      if (buf.length() != 0) buf.append(sep);
      buf.append(structure_1(Array.get(o, i), d));
    }
    return r + atype + "{" + buf + "}";
  }

  if (o instanceof Class)
    return r + "class(" + quote(((Class) o).getName()) + ")";
    
  if (o instanceof Throwable)
    return r + "exception(" + quote(((Throwable) o).getMessage()) + ")";
    
  if (o instanceof BitSet) {
    BitSet bs = (BitSet) o;
    for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
      if (buf.length() != 0) buf.append(", ");
       buf.append(i);
    }
    return "bitset{" + buf + "}";
  }
    
  // Need more cases? This should cover all library classes...
  if (name.startsWith("java.") || name.startsWith("javax."))
    return r + String.valueOf(o);
    
  String shortName = o.getClass().getName().replaceAll("^main\\$", "");
  
  if (shortName.equals("Lisp")) {
    buf.append("l(" + structure_1(getOpt(o, "head"), d));
    List args = (List) ( getOpt(o, "args"));
    if (nempty(args))
      for (int i = 0; i < l(args); i++) {
        buf.append(", ");
        Object arg = args.get(i);
        
        // sweet shortening
        if (arg != null && eq(arg.getClass().getName(), "main$Lisp") && isTrue(call(arg, "isEmpty")))
          arg = get(arg, "head");
          
        buf.append(structure_1(arg, d));
      }
    buf.append(")");
    return r + str(buf);
  }
    
  int numFields = 0;
  String fieldName = "";
  if (shortName.equals("DynamicObject")) {
    shortName = (String) get_raw(o, "className");
    Map<String, Object> fieldValues = (Map) get_raw(o, "fieldValues");
    
    for (String _fieldName : fieldValues.keySet()) {
      fieldName = _fieldName;
      Object value = fieldValues.get(fieldName);
      if (value != null) {
        if (buf.length() != 0) buf.append(", ");
        buf.append(fieldName + "=" + structure_1(value, d));
      }
      ++numFields;
   }
  } else {
    // regular class
    
    Class c = o.getClass();
    
    if (d.conceptClass != null && d.conceptClass.isInstance(o) && !d.concepts.contains(c.getName())) {
      d.concepts.add(c.getName());
      r += "c ";
    }
    
    while (c != Object.class) {
      List<Field> fields = asList(c.getDeclaredFields());
      for (int i = 1; i < l(fields); i++)
        if (eq(fields.get(i).getName(), "this$1")) {
          swapElements(fields, 0, i);
          break;
        }
      for (Field field : fields) {
        if ((field.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) != 0)
          continue;
        fieldName = field.getName();
        
        // skip outer object reference
        //if (fieldName.indexOf("$") >= 0) continue;
  
        Object value;
        try {
          field.setAccessible(true);
          value = field.get(o);
        } catch (Exception e) {
          value = "?";
        }
        
        // put special cases here...
    
        if (value != null) {
          if (buf.length() != 0) buf.append(", ");
          buf.append(fieldName + "=" + structure_1(value, d));
        }
        ++numFields;
      }
      c = c.getSuperclass();
    }
  }
  
  String b = buf.toString();
  
  if (numFields == 1 && structure_allowShortening)
    b = b.replaceAll("^" + fieldName + "=", ""); // drop field name if only one
  String s = shortName;
  if (buf.length() != 0)
    s += "(" + b + ")";
  return r + s;
}

// drop unused markers
static String structure_2(String s, HashSet<Integer> refd) {
  List<String> tok = javaTok(s);
  StringBuilder out = new StringBuilder();
  for (int i = 1; i < l(tok); i += 2) {
    String t = tok.get(i);
    if (t.startsWith("m") && isInteger(t.substring(1))
      && !refd.contains(parseInt(t.substring(1))))
      continue;
    out.append(t).append(tok.get(i+1));
  }
  return str(out);
}

static boolean sameSnippetID(String a, String b) {
  return a != null && b != null && parseSnippetID(a) == parseSnippetID(b);
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile StringBuffer print_log = local_log; // might be redirected, e.g. to main bot

// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
//static int print_maxLineLength = 0; // 0 = unset

static boolean print_silent; // total mute if set

static void print() {
  print("");
}

// slightly overblown signature to return original object...
static <A> A print(A o) {
  if (print_silent) return o;
  String s = String.valueOf(o) + "\n";
  // TODO if (print_maxLineLength != 0)
  StringBuffer loc = local_log;
  StringBuffer buf = print_log;
  int loc_max = print_log_max;
  if (buf != loc && buf != null) {
    print_append(buf, s, print_log_max);
    loc_max = local_log_max;
  }
  if (loc != null) 
    print_append(loc, s, loc_max);
  System.out.print(s);
  return o;
}

static void print(long l) {
  print(String.valueOf(l));
}

static void print(char c) {
  print(String.valueOf(c));
}

static void print_append(StringBuffer buf, String s, int max) {
  synchronized(buf) {
    buf.append(s);
    max /= 2;
    if (buf.length() > max) try {
      int newLength = max/2;
      int ofs = buf.length()-newLength;
      String newString = buf.substring(ofs);
      buf.setLength(0);
      buf.append("[...] ").append(newString);
    } catch (Exception e) {
      buf.setLength(0);
    }
  }
}
static void copyStream(InputStream in, OutputStream out) { try {
 
  byte[] buf = new byte[65536];
  while (true) {
    int n = in.read(buf);
    if (n <= 0) return;
    out.write(buf, 0, n);
  }

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static File loadBinarySnippet(String snippetID) { try {
 
  long id = parseSnippetID(snippetID);
  File f = DiskSnippetCache_getLibrary(id);
  if (f == null) {
    byte[] data = loadDataSnippetImpl(snippetID);
    DiskSnippetCache_putLibrary(id, data);
    f = DiskSnippetCache_getLibrary(id);
  }
  return f;

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}


static Object callF(Object f, Object... args) {
  return callFunction(f, args);
}
static <A> ArrayList<A> asList(A[] a) {
  return new ArrayList<A>(Arrays.asList(a));
}

static ArrayList<Integer> asList(int[] a) {
  ArrayList<Integer> l = new ArrayList();
  for (int i : a) l.add(i);
  return l;
}

static <A> ArrayList<A> asList(Iterable<A> s) {
  if (s instanceof ArrayList) return (ArrayList) s;
  ArrayList l = new ArrayList();
  if (s != null)
    for (A a : s)
      l.add(a);
  return l;
}
  public static String bytesToHex(byte[] bytes) {
    return bytesToHex(bytes, 0, bytes.length);
  }

  public static String bytesToHex(byte[] bytes, int ofs, int len) {
    StringBuilder stringBuilder = new StringBuilder(len*2);
    for (int i = 0; i < len; i++) {
      String s = "0" + Integer.toHexString(bytes[ofs+i]);
      stringBuilder.append(s.substring(s.length()-2, s.length()));
    }
    return stringBuilder.toString();
  }

static void swapElements(List l, int i, int j) {
  if (i == j) return;
  Object o = l.get(i);
  l.set(i, l.get(j));
  l.set(j, o);
}
static boolean isInteger(String s) {
  return s != null && Pattern.matches("\\-?\\d+", s);
}
  static String quote(String s) {
    if (s == null) return "null";
    return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n") + "\"";
  }
  
  static String quote(long l) {
    return quote("" + l);
  }
  
  static String quote(char c) {
    return quote("" + c);
  }

static String shorten(String s, int max) {
  if (s == null) return "";
  return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "...";
}
static String getStackTrace(Throwable throwable) {
  StringWriter writer = new StringWriter();
  throwable.printStackTrace(new PrintWriter(writer));
  return writer.toString();
}
static String quoteCharacter(char c) {
  if (c == '\'') return "'\\''";
  if (c == '\\') return "'\\\\'";
  return "'" + c + "'";
}

// extended over Class.isInstance() to handle primitive types
static boolean isInstanceX(Class type, Object arg) {
  if (type == boolean.class) return arg instanceof Boolean;
  if (type == int.class) return arg instanceof Integer;
  if (type == long.class) return arg instanceof Long;
  if (type == float.class) return arg instanceof Float;
  if (type == short.class) return arg instanceof Short;
  if (type == char.class) return arg instanceof Character;
  if (type == byte.class) return arg instanceof Byte;
  if (type == double.class) return arg instanceof Double;
  return type.isInstance(arg);
}
// currently finds only inner classes of class "main"
// returns null on not found
// this is the simple version that is not case-tolerant
static Class findClass(String name) {
  if (!isJavaIdentifier(name)) return null;
  try {
    return Class.forName("main$" + name);
  } catch (ClassNotFoundException e) {
    return null;
  }
}
static boolean eq(Object a, Object b) {
  if (a == null) return b == null;
  if (a.equals(b)) return true;
  if (a instanceof BigInteger) {
    if (b instanceof Integer) return a.equals(BigInteger.valueOf((Integer) b));
    if (b instanceof Long) return a.equals(BigInteger.valueOf((Long) b));
  }
  return false;
}
static String str(Object o) {
  return String.valueOf(o);
}
// get purpose 1: access a list/array (safer version of x.get(y))

static <A> A get(List<A> l, int idx) {
  return idx >= 0 && idx < l(l) ? l.get(idx) : null;
}

static <A> A get(A[] l, int idx) {
  return idx >= 0 && idx < l(l) ? l[idx] : null;
}

// default to false
static boolean get(boolean[] l, int idx) {
  return idx >= 0 && idx < l(l) ? l[idx] : false;
}

static Class get_dynamicObject = findClass("DynamicObject");

// get purpose 2: access a field by reflection or a map

static Object get(Object o, String field) {
  try {
    if (o instanceof Class) return get((Class) o, field);
    
    if (o instanceof Map)
      return ((Map) o).get(field);
      
    Field f = getOpt_findField(o.getClass(), field);
    if (f != null) {
      f.setAccessible(true);
      return f.get(o);
    }
      
    if (get_dynamicObject != null && get_dynamicObject.isInstance(o))
      return call(get_raw(o, "fieldValues"), "get", field);
  } catch (Exception e) {
    throw asRuntimeException(e);
  }
  throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}

static Object get_raw(Object o, String field) {
  try {
    Field f = get_findField(o.getClass(), field);
    f.setAccessible(true);
    return f.get(o);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

static Object get(Class c, String field) {
  try {
    Field f = get_findStaticField(c, field);
    f.setAccessible(true);
    return f.get(null);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

static Field get_findStaticField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}

static Field get_findField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field))
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static Object consoleFrame_gen() {
  return getOpt(getOpt(getJavaX(), "console"), "frame");
}
// replacement for class JavaTok
// maybe incomplete, might want to add floating point numbers
// todo also: extended multi-line strings

static int javaTok_n, javaTok_elements;
static boolean javaTok_opt;

static List<String> javaTok(String s) {
  return javaTok(s, null);
}

static List<String> javaTok(String s, List<String> existing) {
  ++javaTok_n;
  int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
  List<String> tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
  int l = s.length();
  
  int i = 0, n = 0;
  while (i < l) {
    int j = i;
    char c; String cc;
    
    // scan for whitespace
    while (j < l) {
      c = s.charAt(j);
      cc = s.substring(j, Math.min(j+2, l));
      if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
        ++j;
      else if (cc.equals("/*")) {
        do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
        j = Math.min(j+2, l);
      } else if (cc.equals("//")) {
        do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
      } else
        break;
    }
    
    if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j))
      tok.add(existing.get(n));
    else
      tok.add(quickSubstring(s, i, j));
    ++n;
    i = j;
    if (i >= l) break;
    c = s.charAt(i); // cc is not needed in rest of loop body
    cc = s.substring(i, Math.min(i+2, l));

    // scan for non-whitespace
    if (c == '\'' || c == '"') {
      char opener = c;
      ++j;
      while (j < l) {
        if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
          ++j;
          break;
        } else if (s.charAt(j) == '\\' && j+1 < l)
          j += 2;
        else
          ++j;
      }
    } else if (Character.isJavaIdentifierStart(c))
      do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
    else if (Character.isDigit(c)) {
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
      if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
    } else if (cc.equals("[[")) {
      do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
      j = Math.min(j+2, l);
    } else if (cc.equals("[=") && i+2 < l && s.charAt(i+2) == '[') {
      do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
      j = Math.min(j+3, l);
    } else
      ++j;

    if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j))
      tok.add(existing.get(n));
    else
      tok.add(quickSubstring(s, i, j));
    ++n;
    i = j;
  }
  
  if ((tok.size() % 2) == 0) tok.add("");
  javaTok_elements += tok.size();
  return tok;
}

static List<String> javaTok(List<String> tok) {
  return javaTok(join(tok), tok);
}

static boolean javaTok_isCopyable(String t, String s, int i, int j) {
  return t.length() == j-i
    && s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}
static String substring(String s, int x) {
  return safeSubstring(s, x);
}

static String substring(String s, int x, int y) {
  return safeSubstring(s, x, y);
}
  
  // Data files are immutable, use centralized cache
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
  File file = new File(getGlobalCache(), "data_" + snippetID + ".jar");
  return file.exists() ? file : null;
}

public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
  saveBinaryFile(new File(getGlobalCache(), "data_" + snippetID).getPath() + ".jar", data);
}

static byte[] loadDataSnippetImpl(String snippetID) throws IOException {
  byte[] data;
  try {
    URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_"
      + parseSnippetID(snippetID) + "&contentType=application/binary");
    System.err.println("Loading library: " + url);
    try {
      data = loadBinaryPage(url.openConnection());
    } catch (RuntimeException e) {
      data = null;
    }
    
    if (data == null || data.length == 0) {
      url = new URL("http://data.tinybrain.de/blobs/"
        + parseSnippetID(snippetID));
      System.err.println("Loading library: " + url);
      data = loadBinaryPage(url.openConnection());
    }
    System.err.println("Bytes loaded: " + data.length);
  } catch (FileNotFoundException e) {
    throw new IOException("Binary snippet #" + snippetID + " not found or not public");
  }
  return data;
}
static String _userHome;
static String userHome() {
  if (_userHome == null) {
    if (isAndroid())
      _userHome = "/storage/sdcard0/";
    else
      _userHome = System.getProperty("user.home");
    //System.out.println("userHome: " + _userHome);
  }
  return _userHome;
}

static File userHome(String path) {
  return new File(userDir(), path);
}
static List emptyList() {
  return new ArrayList();
  //ret Collections.emptyList();
}
public static long parseSnippetID(String snippetID) {
  long id = Long.parseLong(shortenSnippetID(snippetID));
  if (id == 0) throw fail("0 is not a snippet ID");
  return id;
}
static Class getMainClass() { try {
 
  return Class.forName("main");

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}

static Class getMainClass(Object o) { try {
 
  return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static boolean nempty(Collection c) {
  return !isEmpty(c);
}

static boolean nempty(CharSequence s) {
  return !isEmpty(s);
}

static boolean nempty(Object[] o) {
  return !isEmpty(o);
}

static boolean nempty(Map m) {
  return !isEmpty(m);
}

static boolean nempty(Iterator i) {
  return i != null && i.hasNext();
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); } 

static int l(Object o) {
  return l((List) o); // incomplete
}

static File getProgramDir() {
  return programDir();
}

static File getProgramDir(String snippetID) {
  return programDir(snippetID);
}
  static Object call(Object o) {
    return callFunction(o);
  }
  
  // varargs assignment fixer for a single string array argument
  static Object call(Object o, String method, String[] arg) {
    return call(o, method, new Object[] {arg});
  }
  
  static Object call(Object o, String method, Object... args) {
    try {
      if (o instanceof Class) {
        Method m = call_findStaticMethod((Class) o, method, args, false);
        m.setAccessible(true);
        return m.invoke(null, args);
      } else {
        Method m = call_findMethod(o, method, args, false);
        m.setAccessible(true);
        return m.invoke(o, args);
      }
    } catch (Exception e) {
      throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
    }
  }

  static Method call_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
    Class _c = c;
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) {
        if (debug)
          System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
        if (!m.getName().equals(method)) {
          if (debug) System.out.println("Method name mismatch: " + method);
          continue;
        }

        if ((m.getModifiers() & Modifier.STATIC) == 0 || !call_checkArgs(m, args, debug))
          continue;

        return m;
      }
      c = c.getSuperclass();
    }
    throw new RuntimeException("Method '" + method + "' (static) with " + args.length + " parameter(s) not found in " + _c.getName());
  }

  static Method call_findMethod(Object o, String method, Object[] args, boolean debug) {
    Class c = o.getClass();
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) {
        if (debug)
          System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
        if (m.getName().equals(method) && call_checkArgs(m, args, debug))
          return m;
      }
      c = c.getSuperclass();
    }
    throw new RuntimeException("Method '" + method + "' (non-static) with " + args.length + " parameter(s) not found in " + o.getClass().getName());
  }

  private static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
    Class<?>[] types = m.getParameterTypes();
    if (types.length != args.length) {
      if (debug)
        System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
      return false;
    }
    for (int i = 0; i < types.length; i++)
      if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
        if (debug)
          System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
        return false;
      }
    return true;
  }


static int parseInt(String s) {
  return empty(s) ? 0 : Integer.parseInt(s);
}
// hmm, this shouldn't call functions really. That was just
// for coroutines.
static boolean isTrue(Object o) {
  if (o instanceof Boolean)
    return ((Boolean) o).booleanValue();
  if (o == null) return false;
  return ((Boolean) callF(o)).booleanValue();
}

static boolean isTrue(Object pred, Object arg) {
  return booleanValue(callF(pred, arg));
}
static Object getOpt(Object o, String field) {
  if (o instanceof String) o = getBot ((String) o);
  if (o == null) return null;
  if (o instanceof Class) return getOpt((Class) o, field);
  
  if (o.getClass().getName().equals("main$DynamicObject"))
    return ((Map) getOpt_raw(o, "fieldValues")).get(field);
  
  if (o instanceof Map) return ((Map) o).get(field);
  
  return getOpt_raw(o, field);
}

static Object getOpt_raw(Object o, String field) {
  try {
    Field f = getOpt_findField(o.getClass(), field);
    if (f == null) return null;
    f.setAccessible(true);
    return f.get(o);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

static Object getOpt(Class c, String field) {
  try {
    if (c == null) return null;
    Field f = getOpt_findStaticField(c, field);
    if (f == null) return null;
    f.setAccessible(true);
    return f.get(null);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

static Field getOpt_findStaticField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}

static Field getOpt_findField(Class<?> c, String field) {
  Class _c = c;
  do {
    for (Field f : _c.getDeclaredFields())
      if (f.getName().equals(field))
        return f;
    _c = _c.getSuperclass();
  } while (_c != null);
  return null;
}
static String boolArrayToHex(boolean[] a) {
  return bytesToHex(boolArrayToBytes(a));
}


static Object callFunction(Object f, Object... args) {
  if (f == null) return null;
  if (f instanceof Runnable) {
    ((Runnable) f).run();
    return null;
  } else if (f instanceof String)
    return call(mc(), (String) f, args);
  else
    return call(f, "get", args);
  //else throw fail("Can't call a " + getClassName(f));
}
static boolean empty(Collection c) {
  return isEmpty(c);
}

static boolean empty(String s) {
  return isEmpty(s);
}

static boolean empty(Map map) {
  return map == null || map.isEmpty();
}

static boolean empty(Object[] o) {
  return o == null || o.length == 0;
}

static boolean empty(Object o) {
  if (o instanceof Collection) return empty((Collection) o);
  if (o instanceof String) return empty((String) o);
  if (o instanceof Map) return empty((Map) o);
  if (o instanceof Object[]) return empty((Object[]) o);
  throw fail("unknown type for 'empty': " + getType(o));
}
// hopefully covers all cases :)
static String safeSubstring(String s, int x, int y) {
  if (s == null) return null;
  if (x < 0) x = 0;
  if (x > s.length()) return "";
  if (y < x) y = x;
  if (y > s.length()) y = s.length();
  return s.substring(x, y);
}

static String safeSubstring(String s, int x) {
  return safeSubstring(s, x, l(s));
}

static RuntimeException asRuntimeException(Throwable t) {
  return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static Object getBot(String botID) {
  return callOpt(getMainBot(), "getBot", botID);
}

  public static String join(String glue, Iterable<String> strings) {
    StringBuilder buf = new StringBuilder();
    Iterator<String> i = strings.iterator();
    if (i.hasNext()) {
      buf.append(i.next());
      while (i.hasNext())
        buf.append(glue).append(i.next());
    }
    return buf.toString();
  }
  
  public static String join(String glue, String[] strings) {
    return join(glue, Arrays.asList(strings));
  }
  
  public static String join(Iterable<String> strings) {
    return join("", strings);
  }
  
  public static String join(String[] strings) {
    return join("", strings);
  }

static String shortenSnippetID(String snippetID) {
  if (snippetID.startsWith("#"))
    snippetID = snippetID.substring(1);
  String httpBlaBla = "http://tinybrain.de/";
  if (snippetID.startsWith(httpBlaBla))
    snippetID = snippetID.substring(httpBlaBla.length());
  return "" + parseLong(snippetID);
}
static byte[] boolArrayToBytes(boolean[] a) {
  byte[] b = new byte[(l(a)+7)/8];
  for (int i = 0; i < l(a); i++)
    if (a[i])
      b[i/8] |= 1 << (i & 7);
  return b;
}
static boolean booleanValue(Object o) {
  return eq(true, o);
}
static String quickSubstring(String s, int i, int j) {
  if (i == j) return "";
  return s.substring(i, j);
}
static boolean isJavaIdentifier(String s) {
  if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0)))
    return false;
  for (int i = 1; i < s.length(); i++)
    if (!Character.isJavaIdentifierPart(s.charAt(i)))
      return false;
  return true;
}
  /** writes safely (to temp file, then rename) */
  public static void saveBinaryFile(String fileName, byte[] contents) throws IOException {
    File file = new File(fileName);
    File parentFile = file.getParentFile();
    if (parentFile != null)
      parentFile.mkdirs();
    String tempFileName = fileName + "_temp";
    FileOutputStream fileOutputStream = new FileOutputStream(tempFileName);
    fileOutputStream.write(contents);
    fileOutputStream.close();
    if (file.exists() && !file.delete())
      throw new IOException("Can't delete " + fileName);

    if (!new File(tempFileName).renameTo(file))
      throw new IOException("Can't rename " + tempFileName + " to " + fileName);
  }

  static void saveBinaryFile(File fileName, byte[] contents) {
    try {
      saveBinaryFile(fileName.getPath(), contents);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
static Class __javax;

static Class getJavaX() {
  return __javax;
}
static boolean isEmpty(Collection c) {
  return c == null || c.isEmpty();
}

static boolean isEmpty(CharSequence s) {
  return s == null || s.length() == 0;
}

static boolean isEmpty(Object[] a) {
  return a == null || a.length == 0;
}

static boolean isEmpty(Map map) {
  return map == null || map.isEmpty();
}
static byte[] loadBinaryPage(String url) { try {
 
  return loadBinaryPage(new URL(url).openConnection());

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}

public static byte[] loadBinaryPage(URLConnection con) { try {
 
  //setHeaders(con);
  ByteArrayOutputStream buf = new ByteArrayOutputStream();
  InputStream inputStream = con.getInputStream();
  int n = 0;
  while (true) {
    int ch = inputStream.read();
    if (ch < 0)
      break;
    buf.write(ch);
    if (++n % 100000 == 0)
      System.err.println("  " + n + " bytes loaded.");
  }
  inputStream.close();
  return buf.toByteArray();

} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}

static File getGlobalCache() {
  File file = new File(userHome(), ".tinybrain/snippet-cache");
  file.mkdirs();
  return file;
}

static File userDir() {
  return new File(userHome());
}

static File userDir(String path) {
  return new File(userHome(), path);
}
static boolean isAndroid() { return System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0; }


static Object mc() {
  return getMainClass();
}
static String getType(Object o) {
  return getClassName(o);
}
static Object mainBot;

static Object getMainBot() {
  return mainBot;
}
static long parseLong(String s) {
  if (s == null) return 0;
  return Long.parseLong(dropSuffix("L", s));
}

static long parseLong(Object s) {
  return Long.parseLong((String) s);
}


static String getClassName(Object o) {
  return o == null ? "null" : o.getClass().getName();
}
static String dropSuffix(String suffix, String s) {
  return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}

}

!include #1005016

download  show line numbers  debug dex  old transpilations   

Travelled to 15 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, ddnzoavkxhuk, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1005029
Snippet name: Mocha Doom Single Source With Translator
Eternal ID of this version: #1005029/1
Text MD5: bd15c6305a8bdd33db8af921338fdc4d
Author: stefan
Category: javax
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-09-28 22:19:39
Source code size: 44966 bytes / 1470 lines
Pitched / IR pitched: No / No
Views / Downloads: 540 / 484
Referenced in: [show references]