public <P extends AbstractProject<P, B>, B extends AbstractBuild<P, B>> String getContent( AbstractBuild<P, B> build, ExtendedEmailPublisher publisher, EmailType type, Map<String, ?> args) throws IOException, InterruptedException { InputStream inputStream = null; InputStream templateStream = null; String scriptName = Args.get(args, SCRIPT_NAME_ARG, DEFAULT_SCRIPT_NAME); String templateName = Args.get(args, SCRIPT_TEMPLATE_ARG, DEFAULT_TEMPLATE_NAME); boolean runInit = Args.get(args, SCRIPT_INIT_ARG, DEFAULT_INIT_VALUE); try { inputStream = getFileInputStream(scriptName); // sanity check on template as well templateStream = getFileInputStream(templateName); IOUtils.closeQuietly(templateStream); return renderContent(build, inputStream, scriptName, templateName, runInit); } catch (FileNotFoundException e) { String missingScriptError = generateMissingFile(scriptName, templateName); LOGGER.log(Level.SEVERE, missingScriptError); return missingScriptError; } catch (ScriptException e) { LOGGER.log(Level.SEVERE, null, e); return "Exception: " + e.getMessage(); } finally { IOUtils.closeQuietly(inputStream); } }
/** * Adds the configurations for data stores whose entities will be mapped using the engine created * by this class. * * @param dataStores configurations of data stores that will have their entities mapped through * this engine. */ public final void addDataStoreConfigurations(DataStoreConfiguration... dataStores) { Args.notEmpty(dataStores, "Data stores"); for (DataStoreConfiguration config : dataStores) { Args.notNull(config, "Data store configuration"); dataStoreConfigurations.add(config); } }
/** * Adds instances of {@link CustomDataStoreFactory} that should be used by uniVocity to read any * custom {@link DataStoreConfiguration}, provided by the user in the constructor of this class, * to properly create instances of {@link CustomDataStore}. * * @param customFactories the factories that process user-provided data store configurations and * generate custom data store instances. */ public final void addCustomDataStoreFactories(CustomDataStoreFactory<?>... customFactories) { Args.notEmpty(customFactories, "Custom data store factories"); for (CustomDataStoreFactory<?> customFactory : customFactories) { Args.notNull(customFactory, "Custom data store factory"); customDataStoreFactories.add(customFactory); } }
public static String execute(String[] argsArr) throws IOException { Args args = new Args(argsArr); String user = args.get("user"); if (user == null) return "Missing username. Use '--user blahblah'."; String pass = args.get("pass"); if (pass == null) return "Missing password. Use '--pass blahblah'."; System.out.println("Logging in as '" + user + "'....."); SchoolLoop sl = null; try { sl = new SchoolLoop(user, pass); } catch (LoginException e) { return "Invalid login credentials"; } System.out.println("Session ID: " + sl.getSessionId()); if (args.getInput().equals("grades")) { System.out.println(); System.out.format("%4s%24s%12s%12s", "P", "Class", "%", "Grade"); System.out.println("\n----------------------------------------------------"); List<GradeBookEntry> grades = sl.getGrades(); for (GradeBookEntry g : grades) { System.out.format("%4s%24s%12s%12s", g.period, g.className, g.percent, g.grade); System.out.println(); } } return ""; }
@Test public void testWindowsPerfmonInputCrud() { Service service = connect(); InputCollection inputCollection = service.getInputs(); ServiceInfo info = service.getInfo(); if (info.getOsName().equals("Windows")) { String name = "sdk-input-wp"; Args args = new Args(); if (inputCollection.containsKey(name)) { inputCollection.remove(name); inputCollection.refresh(); } assertFalse(assertRoot + "#57", inputCollection.containsKey(name)); // CRUD Windows Perfmon Input args.put("interval", 600); args.put("object", "Server"); inputCollection.create(name, InputKind.WindowsPerfmon, args); assertTrue(assertRoot + "#58", inputCollection.containsKey(name)); WindowsPerfmonInput windowsPerfmonInput = (WindowsPerfmonInput) inputCollection.get(name); windowsPerfmonInput.setIndex("main"); windowsPerfmonInput.setCounters("% Privileged Time"); windowsPerfmonInput.setInstances("wininit"); windowsPerfmonInput.setObject("Process"); windowsPerfmonInput.setInterval(1200); windowsPerfmonInput.update(); assertEquals(assertRoot + "#59", 1, windowsPerfmonInput.getCounters().length); assertTrue( assertRoot + "#60", contains(windowsPerfmonInput.getCounters(), "% Privileged Time")); assertEquals(windowsPerfmonInput.getIndex(), "main"); assertTrue(assertRoot + "#61", contains(windowsPerfmonInput.getInstances(), "wininit")); assertEquals(assertRoot + "#62", 1200, windowsPerfmonInput.getInterval()); assertEquals(assertRoot + "#63", "Process", windowsPerfmonInput.getObject()); // set multi-series values and update. windowsPerfmonInput.setCounters(new String[] {"% Privileged Time", "% User Time"}); windowsPerfmonInput.setInstances(new String[] {"smss", "csrss"}); windowsPerfmonInput.update(); assertEquals(assertRoot + "#64", 2, windowsPerfmonInput.getCounters().length); assertTrue( assertRoot + "#65", contains(windowsPerfmonInput.getCounters(), "% Privileged Time")); assertTrue(assertRoot + "#66", contains(windowsPerfmonInput.getCounters(), "% User Time")); assertEquals(assertRoot + "#67", 2, windowsPerfmonInput.getInstances().length); assertTrue(assertRoot + "#68", contains(windowsPerfmonInput.getInstances(), "smss")); assertTrue(assertRoot + "#69", contains(windowsPerfmonInput.getInstances(), "csrss")); windowsPerfmonInput.remove(); inputCollection.refresh(); assertFalse(assertRoot + "#70", inputCollection.containsKey(name)); } }
/** * Converts the specified string to a byte array. If the charset is not supported the default * system charset is used. * * @param data the string to be encoded * @param charset the desired character encoding * @return The resulting byte array. */ public static byte[] getBytes(final String data, final String charset) { Args.notNull(data, "Input"); Args.notEmpty(charset, "Charset"); try { return data.getBytes(charset); } catch (final UnsupportedEncodingException e) { return data.getBytes(); } }
/** * Converts the byte array of HTTP content characters to a string. If the specified charset is not * supported, default system encoding is used. * * @param data the byte array to be encoded * @param offset the index of the first byte to encode * @param length the number of bytes to encode * @param charset the desired character encoding * @return The result of the conversion. */ public static String getString( final byte[] data, final int offset, final int length, final String charset) { Args.notNull(data, "Input"); Args.notEmpty(charset, "Charset"); try { return new String(data, offset, length, charset); } catch (final UnsupportedEncodingException e) { return new String(data, offset, length); } }
@Test public void testWindowsRegistryInputCrud() { Service service = connect(); InputCollection inputCollection = service.getInputs(); ServiceInfo info = service.getInfo(); if (info.getOsName().equals("Windows")) { String name = "sdk-input-wr"; Args args = new Args(); if (service.versionCompare("4.3") < 0) return; if (inputCollection.containsKey(name)) { inputCollection.remove(name); inputCollection.refresh(); } assertFalse(assertRoot + "#71", inputCollection.containsKey(name)); // CRUD Windows Registry Input args.put("disabled", true); args.put("baseline", false); args.put("hive", "HKEY_USERS"); args.put("proc", "*"); args.put("type", "*"); inputCollection.create(name, InputKind.WindowsRegistry, args); assertTrue(assertRoot + "#72", inputCollection.containsKey(name)); WindowsRegistryInput windowsRegistryInput = (WindowsRegistryInput) inputCollection.get(name); windowsRegistryInput.setIndex("main"); windowsRegistryInput.setMonitorSubnodes(true); windowsRegistryInput.update(); assertFalse(assertRoot + "#73", windowsRegistryInput.getBaseline()); assertEquals(assertRoot + "#74", "main", windowsRegistryInput.getIndex()); // adjust a few of the arguments windowsRegistryInput.setType("create,delete"); windowsRegistryInput.setBaseline(false); windowsRegistryInput.update(); assertEquals(assertRoot + "#75", "*", windowsRegistryInput.getProc()); assertTrue(assertRoot + "#76", windowsRegistryInput.getType().contains("create")); assertTrue(assertRoot + "#77", windowsRegistryInput.getType().contains("delete")); assertFalse(assertRoot + "#78", windowsRegistryInput.getBaseline()); windowsRegistryInput.remove(); inputCollection.refresh(); assertFalse(assertRoot + "#79", inputCollection.containsKey(name)); } }
public static void evaluateGate(Gate g, Args options) { // refreshGateAttributes(g); // simulateREU(g); evaluateGateONOFFRatio(g); if (options.is_noise_margin()) { evaluateGateNoiseMargin(g, options); } if (options.is_snr()) { evaluateGateSNR(g, options); } }
/** * Creates a new engine configuration with the essential configuration required by uniVocity for * enabling the definition and execution of data mappings. * * @param engineName the name of the new engine. The engine name is used to obtain instances of * {@link DataIntegrationEngine} and manage them using {@link Univocity} * @param dataStores optional parameter for the configurations of data stores that will have their * entities mapped through this engine. More dataStores can be added later using {@link * #addDataStoreConfigurations(DataStoreConfiguration...)} */ public EngineConfiguration(String engineName, DataStoreConfiguration... dataStores) { Args.notBlank(engineName, "Engine name"); this.engineName = engineName; if (dataStores != null && dataStores.length > 0) { addDataStoreConfigurations(dataStores); } }
/** * Defines the maximum length of this field. A value of -1 means the length is undefined. Zero is * not a valid length. * * @param length the length of this field. */ public void setLength(int length) { if (length < 0) { length = -1; } else { Args.positive(length, "Field length"); } this.length = length; }
/** gate score = smallest noise margin (distance in log(REU) of input REU to margin REU) */ public static void evaluateGateNoiseMargin(Gate g, Args options) { if (options.is_noise_margin() == false) { g.get_scores().set_noise_margin_contract(true); return; } if (g.Type == GateType.INPUT || g.Type == GateType.OUTPUT || g.Type == GateType.OUTPUT_OR) { return; } // "x" to value HashMap<String, Double> lowest_on_reu = GateUtil.getIncomingONlow(g); HashMap<String, Double> highest_off_reu = GateUtil.getIncomingOFFhigh(g); ArrayList<Double> all_margins = new ArrayList<Double>(); for (String var : highest_off_reu.keySet()) { if (g.get_variable_thresholds().get(var) != null) { // IL is the input-low threshold Double IL = g.get_variable_thresholds().get(var)[0]; // actual REU Double log_input_reu = Math.log10(highest_off_reu.get(var)); // NML is the margin/width between the actual REU and the threshold REU Double NML = Math.log10(IL) - log_input_reu; all_margins.add(NML); } } for (String var : lowest_on_reu.keySet()) { if (g.get_variable_thresholds().get(var) != null) { Double IH = g.get_variable_thresholds().get(var)[1]; Double NMH = Math.log10(lowest_on_reu.get(var)) - Math.log10(IH); all_margins.add(NMH); } } if (all_margins.isEmpty()) { g.get_scores().set_noise_margin(0.0); g.get_scores().set_noise_margin_contract(true); } else { Collections.sort(all_margins); g.get_scores().set_noise_margin(all_margins.get(0)); if (all_margins.get(0) < 0) { g.get_scores().set_noise_margin_contract(false); } else { g.get_scores().set_noise_margin_contract(true); } } }
@Test public void testScriptInputCrud() { Service service = connect(); InputCollection inputCollection = service.getInputs(); ServiceInfo info = service.getInfo(); // CRUD Script input String filename; if (info.getOsName().equals("Windows")) filename = "echo.bat"; else filename = "echo.sh"; Args args = new Args(); args.clear(); args.put("interval", "60"); if (inputCollection.get(filename) != null) { inputCollection.remove(filename); } inputCollection.create(filename, InputKind.Script, args); assertTrue(assertRoot + "#11", inputCollection.containsKey(filename)); ScriptInput scriptInput = (ScriptInput) inputCollection.get(filename); scriptInput.setHost("three.four.com"); scriptInput.setIndex("main"); scriptInput.setInterval("120"); if (service.versionCompare("4.2.4") >= 0) { scriptInput.setPassAuth("admin"); } scriptInput.setRenameSource("renamedSource"); scriptInput.setSource("source"); scriptInput.setSourcetype("script"); scriptInput.update(); assertEquals(assertRoot + "#12", "three.four.com", scriptInput.getHost()); assertEquals(assertRoot + "#13", "main", scriptInput.getIndex()); assertEquals(assertRoot + "#14", "120", scriptInput.getInterval()); if (service.versionCompare("4.2.4") >= 0) { assertEquals(assertRoot + "#15", "admin", scriptInput.getPassAuth()); } assertEquals(assertRoot + "#16", "renamedSource", scriptInput.getSource()); assertEquals(assertRoot + "#17", "script", scriptInput.getSourceType()); scriptInput.remove(); inputCollection.refresh(); assertFalse(assertRoot + "#18", inputCollection.containsKey(filename)); }
/** * The function evaluateCircuit calls other evaluate functions based on the circuit_score chose by * user. * * <p>-circuit_score onoff_ratio score = log(ON/OFF), where ON is the lowest ON in the truthtable, * and OFF is the highest off in the truthtable * * <p>-circuit_score noise_margin noise margin is computed from input REU distance from low margin * (if low) or high margin (if high) score = average noise margin of all logic gates used for * NOR/NOT only, and cannot be used if there are input gates and no logic gates * * <p>-circuit_score histogram score = 1 - overlap penalty, where overlap is from the worst pair * among ONs and OFFs in the truthtable * * <p>Circuit is evaluated by evaluating each gate, so the same function calls appear but with a * Gate parameter instead of LogicCircuit parameter */ public static void evaluateCircuit(LogicCircuit lc, GateLibrary gate_library, Args options) { refreshGateAttributes(lc, gate_library); // if sequential if (options.get_circuit_type() == DNACompiler.CircuitType.sequential) { SequentialHelper.setInitialREUs(lc, gate_library); HashMap<String, ArrayList<ArrayList<Double>>> track_reus = new HashMap<>(); for (Gate g : lc.get_Gates()) { track_reus.put(g.Name, new ArrayList<ArrayList<Double>>()); ArrayList<Double> copy_reus = new ArrayList<Double>(g.get_outreus()); track_reus.get(g.Name).add(copy_reus); track_reus.get(g.Name).add(copy_reus); } boolean converges = SequentialHelper.convergeREUs(lc, gate_library, options, track_reus); if (!converges) { lc.get_scores().set_onoff_ratio(0.0); lc.get_scores().set_noise_margin_contract(false); return; } } // if combinational else if (options.get_circuit_type() == DNACompiler.CircuitType.combinational) { simulateREU(lc, gate_library, options); } evaluateCircuitONOFFRatio(lc); if (options.is_noise_margin()) { evaluateCircuitNoiseMargin(lc, options); } if (options.is_snr()) { evaluateCircuitSNR(lc, options); } }
public static AttributeAppender prepend(final String attributeName, final IModel<?> value) { Args.notEmpty((CharSequence) attributeName, "attributeName"); return new AttributeAppender(attributeName, value) { private static final long serialVersionUID = 1L; protected String newValue(final String currentValue, final String replacementValue) { return super.newValue(replacementValue, currentValue); } }.setSeparator(" "); }
/** * histogram * * <p>Histogram overlap score worst-case = 0.0 and best-case = 1.0 */ public static void evaluateCircuitHistogramOverlap( LogicCircuit lc, GateLibrary gate_library, Args options) { // output gate _score (average) refreshGateAttributes(lc, gate_library); // if sequential if (options.get_circuit_type() == DNACompiler.CircuitType.sequential) { // set initial SequentialHelper.setInitialHistogramREUs(lc, gate_library); // track HashMap<String, ArrayList<ArrayList<double[]>>> track_reus = new HashMap<>(); for (Gate g : lc.get_Gates()) { track_reus.put(g.Name, new ArrayList<ArrayList<double[]>>()); ArrayList<double[]> copy_hist_reus = new ArrayList<double[]>(g.get_histogram_reus()); track_reus.get(g.Name).add(copy_hist_reus); track_reus.get(g.Name).add(copy_hist_reus); // looks for i-1 } // converge SequentialHelper.convergeHistogramREUs(lc, gate_library, options, track_reus); } // if combinational else if (options.get_circuit_type() == DNACompiler.CircuitType.combinational) { Evaluate.simulateHistogramREU(lc, gate_library, options); } double worst_out = Double.MAX_VALUE; for (int out = 0; out < lc.get_output_gates().size(); ++out) { Gate output = lc.get_output_gates().get(out); evaluateGateHistogramOverlap(output); if (output.get_scores().get_conv_overlap() < worst_out) { worst_out = output.get_scores().get_conv_overlap(); } } lc.get_scores().set_conv_overlap(worst_out); }
protected JobOutput executeJellyfishCount(Args args, String ecqName, File outputDir, Library lib) throws ProcessExecutionException, InterruptedException, ConanParameterException, IOException { String suffix = "jellyfish_" + ecqName + "_" + lib.getName() + ".jf31"; // Create the process JellyfishCountV11 jellyfishProcess = this.makeJellyfishCount( this.makeInputStringFromLib(lib), new File(new File(outputDir, ecqName), suffix).getAbsolutePath(), args.getOrganism(), args.getThreadsPerProcess()); File outputFile = jellyfishProcess.getArgs().getOutputFile(); // Create a job name String jobName = args.getJobPrefix() + "-count-" + suffix; // Start jellyfish final ExecutionResult id = this.conanExecutorService.executeProcess( jellyfishProcess, new File(outputDir, ecqName), jobName, args.getThreadsPerProcess(), args.getMemoryPerProcess(), args.isRunParallel()); id.setName("count-" + suffix); return new JobOutput(id, outputFile); }
protected JobOutput executeJellyfishMerger( Args args, String ecqName, Set<File> fileSet, File outputDir) throws InterruptedException, ProcessExecutionException, ConanParameterException, IOException { String suffix = "jellyfish_" + ecqName + "_all.jf31_0"; String jobName = args.getJobPrefix() + "-merge-" + suffix; List<File> files = new ArrayList<>(); files.addAll(fileSet); File outputFile = new File(outputDir, suffix); JellyfishMergeV11 jellyfishMerge = this.makeJellyfishMerge(files, outputFile, args.getOrganism()); ExecutionResult id = this.conanExecutorService.executeProcess( jellyfishMerge, args.getOutputDir(), jobName, args.getThreadsPerProcess(), args.getMemoryPerProcess(), args.isRunParallel()); id.setName("merge-" + suffix); return new JobOutput(id, outputFile); }
@Test public void onCrafted() { Player mockPlayer = mock(Player.class); when(mockPlayer.getGameMode()).thenReturn(GameMode.SURVIVAL); Args a = ArgBuilder.create().player(mockPlayer).build().processArgs(); // Test valid game mode flag.addGameMode(GameMode.SURVIVAL); flag.onCrafted(a); assertFalse(a.hasReasons()); // Test invalid game mode flag.clearGameModes(); flag.addGameMode(GameMode.CREATIVE); flag.onCrafted(a); assertTrue(a.hasReasons()); // Test Args with no player a = ArgBuilder.create().build(); flag.onCrafted(a); assertTrue(a.hasReasons()); }
public void installApplicationFromTestData(String applicationName) { String collectionName = "sdk-app-collection"; if (!service.getApplications().containsKey("sdk-app-collection")) { throw new TestDataNotInstalledException(); } String splunkHome = service.getSettings().getSplunkHome(); // This is the filename separator sequence for splunkd, not // the Splunk SDK. Therefore we can't just use File.separator here. String separator; if (splunkHome.contains("/") && splunkHome.contains("\\")) { // Windows - allows mixed paths separator = "\\"; } else if (splunkHome.contains("/")) { // Unix or Mac OS X separator = "/"; } else if (splunkHome.contains("\\")) { // Windows separator = "\\"; } else { throw new RuntimeException( "Couldn't determine what the path separator was " + "for splunkd."); } String[] pathComponents = { splunkHome, "etc", "apps", collectionName, "build", applicationName + ".tar" }; String appPath = Util.join(separator, pathComponents); Args args = new Args(); args.put("name", appPath); args.put("update", "1"); service.post("apps/appinstall", args); installedApps.add(applicationName); }
@Test public void testWindowsEventLogInputCrud() { Service service = connect(); InputCollection inputCollection = service.getInputs(); ServiceInfo info = service.getInfo(); if (info.getOsName().equals("Windows")) { String name = "sdk-input-wel"; Args args = new Args(); if (inputCollection.containsKey(name)) { inputCollection.remove(name); inputCollection.refresh(); } assertFalse(assertRoot + "#52", inputCollection.containsKey(name)); // CRUD Windows Event Log Input args.put("lookup_host", "127.0.0.1"); inputCollection.create(name, InputKind.WindowsEventLog, args); assertTrue(assertRoot + "#53", inputCollection.containsKey(name)); WindowsEventLogInput windowsEventLogInput = (WindowsEventLogInput) inputCollection.get(name); windowsEventLogInput.setIndex("main"); windowsEventLogInput.setLookupHost("127.0.0.1"); windowsEventLogInput.setHosts("one.two.three,four.five.six"); windowsEventLogInput.update(); assertEquals(assertRoot + "#54", "127.0.0.1", windowsEventLogInput.getLookupHost()); assertEquals( assertRoot + "#55", "one.two.three,four.five.six", windowsEventLogInput.getHosts()); assertEquals(assertRoot + "#55", "main", windowsEventLogInput.getIndex()); windowsEventLogInput.remove(); inputCollection.refresh(); assertFalse(assertRoot + "#56", inputCollection.containsKey(name)); } }
@Override public List<Shape<V>> caseBuiltin(Builtin builtin, Args<V> arg) { if (Debug) System.out.println("inside ShapePropgator, builtin fn is " + builtin); if (Debug) System.out.println("the number of output variables is " + arg.getNargout()); if (builtin instanceof HasShapePropagationInfo) { // call shape prop tool ShapePropTool<V> shapePropTool = new ShapePropTool<V>(); @SuppressWarnings({"unchecked"}) List<Shape<V>> result = shapePropTool.matchByValues( ((HasShapePropagationInfo<V>) builtin).getShapePropagationInfo(), arg); return result; } throw new UnsupportedOperationException(); }
/** noise_margin */ public static void evaluateCircuitNoiseMargin(LogicCircuit lc, Args options) { // initialize to true. circuit will fail if any gate fails. lc.get_scores().set_noise_margin_contract(true); if (options.is_noise_margin() == false) { return; } double sum_noise_margin = 0.0; double min_noise_margin = 999.0; for (Gate g : lc.get_logic_gates()) { // 'options' are passed in to read the _noise_margin boolean evaluateGateNoiseMargin(g, options); if (g.get_scores().get_noise_margin() < min_noise_margin) { min_noise_margin = g.get_scores().get_noise_margin(); } // g.get_noise_margin() returns the min of the NML and NMH values (noise margin low, noise // margin high) sum_noise_margin += g.get_scores().get_noise_margin(); // sum_noise_margin += g.get_scores().get_noise_margin() * g.get_distance_to_input(); /** if one gate fails, the whole circuit fails threshold analysis */ if (g.get_scores().is_noise_margin_contract() == false) { lc.get_scores().set_noise_margin_contract(false); // lc.get_scores().set_noise_margin(0.0); lc.get_scores().set_noise_margin(min_noise_margin); break; } } // noise margin value is not being used. // noise margin is only used as a pass/fail filter, not a score term. if (lc.get_scores().is_noise_margin_contract() == true) { // lc.get_scores().set_noise_margin(sum_noise_margin / lc.get_logic_gates().size()); lc.get_scores().set_noise_margin(sum_noise_margin); } }
public <P extends AbstractProject<P, B>, B extends AbstractBuild<P, B>> String getContent( AbstractBuild<P, B> build, ExtendedEmailPublisher publisher, EmailType emailType, Map<String, ?> args) { StringBuffer buffer = new StringBuffer(); // getLog() chokes and dies if called with a number <= 0. int maxLines = Math.max(Args.get(args, MAX_LINES_ARG_NAME, MAX_LINES_DEFAULT_VALUE), 1); try { List<String> lines = build.getLog(maxLines); for (String line : lines) { // TODO: show file links the same way as MailSender buffer.append(line); buffer.append('\n'); } } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } return buffer.toString(); }
@Override protected void onCrafted(Args a) { if (!a.hasLocation()) { a.addCustomReason("Needs location!"); return; } for (Customization c : spawn) { if (c.pet || c.target || (c.saddle && c.mount)) { if (!a.hasPlayer()) { a.addCustomReason("Needs player!"); return; } break; } } Location l = a.location(); if (l.getX() == l.getBlockX()) { l.add(0.5, 1.5, 0.5); } List<LivingEntity> toMount = null; for (Customization c : spawn) { if (c.chance < 100.0f && c.chance < (RecipeManager.random.nextFloat() * 100)) { continue; } List<LivingEntity> spawned = c.spawn(l, a.player()); if (toMount != null) { for (int i = 0; i < Math.min(spawned.size(), toMount.size()); i++) { spawned.get(i).setPassenger(toMount.get(i)); } } toMount = c.mountNext ? spawned : null; } }
public ShapePropMatch<V> match( boolean isPatternSide, ShapePropMatch<V> previousMatchResult, Args<V> argValues, int num) { if (isPatternSide == true) { // for matching a vertcat expression, this step should be similar to Uppercase matching, to // exam whether equals! if (previousMatchResult.getIsInsideVertcat() == true) { if (Debug) System.out.println("a lowercase inside vertcat!"); if (Debug) System.out.println(previousMatchResult.getNumInVertcat()); Value<V> argument = argValues.get(previousMatchResult.getHowManyMatched()); // get its shape information Shape<V> argumentShape = ((HasShape<V>) argument).getShape(); if (Debug) System.out.println("argument shape is " + argumentShape); if (previousMatchResult.getAllLowercase().containsKey(s)) { try { if ((previousMatchResult.getValueOfVariable(s).getValue() == argumentShape .getDimensions() .get(previousMatchResult.getNumInVertcat()) .getValue()) == false) { if (Debug) System.out.println("two lowercase value not equal, throw error shape!"); if (Debug) System.out.println("MATLAB syntax error!"); previousMatchResult.setIsError(true); HashMap<String, DimValue> lowercase = new HashMap<String, DimValue>(); lowercase.put(s, new DimValue()); ShapePropMatch<V> match = new ShapePropMatch<V>(previousMatchResult, lowercase, null); match.saveLatestMatchedLowercase(s); return match; } HashMap<String, DimValue> lowercase = new HashMap<String, DimValue>(); lowercase.put( s, new DimValue( argumentShape .getDimensions() .get(previousMatchResult.getNumInVertcat()) .getValue(), null)); ShapePropMatch<V> match = new ShapePropMatch<V>(previousMatchResult, lowercase, null); if (Debug) System.out.println(match.getAllLowercase()); match.setNumInVertcat(previousMatchResult.getNumInVertcat() + 1); return match; } catch (Exception e) { } // means one of them, the previous matched lowercase or current number in the argument, is // null if (Debug) System.out.println("there is null information in dimensions!"); previousMatchResult.setIsError(true); return previousMatchResult; } HashMap<String, DimValue> lowercase = new HashMap<String, DimValue>(); if (argumentShape.getDimensions().get(previousMatchResult.getNumInVertcat()) == null) { lowercase.put(s, new DimValue()); ShapePropMatch<V> match = new ShapePropMatch<V>(previousMatchResult, lowercase, null); if (Debug) System.out.println(match.getAllLowercase()); match.setNumInVertcat(previousMatchResult.getNumInVertcat() + 1); return match; } else { lowercase.put( s, new DimValue( argumentShape .getDimensions() .get(previousMatchResult.getNumInVertcat()) .getValue(), null)); ShapePropMatch<V> match = new ShapePropMatch<V>(previousMatchResult, lowercase, null); if (Debug) System.out.println(match.getAllLowercase()); match.setNumInVertcat(previousMatchResult.getNumInVertcat() + 1); return match; } } // for assign a lowercase's value to an ArrayIndex if (previousMatchResult.getIsArrayIndexAssignRight() == true) { if (Debug) System.out.println("trying to assign the value of " + s.toString() + " to an array!"); List<DimValue> dimensions = previousMatchResult .getShapeOfVariable(previousMatchResult.getLatestMatchedUppercase()) .getDimensions(); if (previousMatchResult.getWhetherLatestMatchedIsNum() == true) { if (Debug) System.out.println( "inside assigning a lowercase's value to array with num index!"); // i.e. M(2)=n; // deal with the case that index overflow if ((dimensions.size() - 1) < (previousMatchResult.getLatestMatchedNumber() - 1)) { if (Debug) System.out.println( "index overflow " + dimensions.size() + " " + previousMatchResult.getLatestMatchedNumber()); if (Debug) System.out.println("dimension should not be changed!"); previousMatchResult.setArrayIndexAssignRight(false); return previousMatchResult; } dimensions.remove((previousMatchResult.getLatestMatchedNumber() - 1)); if (previousMatchResult.hasValue(s)) { dimensions.add( (previousMatchResult.getLatestMatchedNumber() - 1), previousMatchResult.getValueOfVariable(s)); } else { dimensions.add((previousMatchResult.getLatestMatchedNumber() - 1), new DimValue()); } } else { if (Debug) System.out.println( "inside assigning a lowercase's value to array with lowercase index!"); // i.e. // M(n)=m; if (Debug) System.out.println( "inside assigning a num to array with lowercase index!"); // i.e. M(n)=2; // deal with the case that index overflow if ((dimensions.size() - 1) < (previousMatchResult .getValueOfVariable(previousMatchResult.getLatestMatchedLowercase()) .getValue() - 1)) { if (Debug) System.out.println( "index overflow " + dimensions.size() + " " + previousMatchResult.getValueOfVariable( previousMatchResult.getLatestMatchedLowercase())); if (Debug) System.out.println("dimension should not be changed!"); previousMatchResult.setArrayIndexAssignRight(false); return previousMatchResult; } dimensions.remove( previousMatchResult .getValueOfVariable(previousMatchResult.getLatestMatchedLowercase()) .getValue() - 1); dimensions.add( previousMatchResult .getValueOfVariable(previousMatchResult.getLatestMatchedLowercase()) .getValue() - 1, previousMatchResult.getValueOfVariable(s)); } if (Debug) System.out.println("new dimension is " + dimensions); if (Debug) System.out.println( "shape of " + previousMatchResult.getLatestMatchedUppercase() + " is " + previousMatchResult.getShapeOfVariable( previousMatchResult.getLatestMatchedUppercase())); HashMap<String, Shape<V>> uppercase = new HashMap<String, Shape<V>>(); uppercase.put( previousMatchResult.getLatestMatchedUppercase(), new ShapeFactory<V>().newShapeFromDimValues(dimensions)); if (Debug) System.out.println(uppercase); ShapePropMatch<V> match = new ShapePropMatch<V>(previousMatchResult, null, uppercase); match.setArrayIndexAssignRight(false); return match; } if (previousMatchResult.getAllLowercase().containsKey(s)) { if (Debug) System.out.println(s + " is contained in the hashmap!"); previousMatchResult.saveLatestMatchedLowercase(s); return previousMatchResult; } // for store some information in a lowercase HashMap<String, DimValue> lowercase = new HashMap<String, DimValue>(); lowercase.put(s, new DimValue()); ShapePropMatch<V> match = new ShapePropMatch<V>(previousMatchResult, lowercase, null); match.saveLatestMatchedLowercase(s); if (Debug) System.out.println( "inside SPLowercase " + match.getLatestMatchedLowercase() + ", vertcat expression now: " + match.getOutputVertcatExpr()); return match; } else { previousMatchResult.addToVertcatExpr(previousMatchResult.getValueOfVariable(s)); return previousMatchResult; } }
public CryptoMapper(final IRequestMapper wrappedMapper, final IProvider<ICrypt> cryptProvider) { super(); this.wrappedMapper = (IRequestMapper) Args.notNull((Object) wrappedMapper, "wrappedMapper"); this.cryptProvider = (IProvider<ICrypt>) Args.notNull((Object) cryptProvider, "cryptProvider"); }
/** * Converts the specified string to byte array of ASCII characters. * * @param data the string to be encoded * @return The string as a byte array. */ public static byte[] getAsciiBytes(final String data) { Args.notNull(data, "Input"); return data.getBytes(Consts.ASCII); }
void doTest(String name) throws Exception { Method m = tests.get(name); Method m_check = tests.get(name + "_check"); Class[] paramTypes = m.getParameterTypes(); Object[] params = new Object[paramTypes.length]; Class retType = m.getReturnType(); boolean isIntArray = (retType.isPrimitive() && !retType.equals(Void.TYPE)) || (retType.equals(Void.TYPE) && paramTypes[0].getComponentType().isPrimitive()) || (retType.isArray() && retType.getComponentType().isPrimitive()); Args args = m.getAnnotation(Args.class); Object src = null; switch (args.src()) { case SMALL: { if (isIntArray) { src = small_int_src; } else { src = small_a_src; } break; } case LARGE: { if (isIntArray) { src = large_int_src; } else { src = large_a_src; } break; } case ZERO: { if (isIntArray) { src = zero_int_src; } else { src = zero_a_src; } break; } } for (int i = 0; i < 20000; i++) { boolean failure = false; int p = 0; if (params.length > 0) { if (isIntArray) { params[0] = ((int[]) src).clone(); } else { params[0] = ((A[]) src).clone(); } p++; } if (params.length > 1) { switch (args.dst()) { case NEW: { if (isIntArray) { params[1] = new int[((int[]) params[0]).length]; } else { params[1] = new A[((A[]) params[0]).length]; } p++; break; } case SRC: { params[1] = params[0]; p++; break; } case NONE: break; } } for (int j = 0; j < args.extra_args().length; j++) { params[p + j] = args.extra_args()[j]; } Object res = m.invoke(null, params); if (retType.isPrimitive() && !retType.equals(Void.TYPE)) { int s = (int) res; int sum = 0; int[] int_res = (int[]) src; for (int j = 0; j < int_res.length; j++) { sum += int_res[j]; } failure = (s != sum); if (failure) { System.out.println("Test " + name + " failed: result = " + s + " != " + sum); } } else { Object dest = null; if (!retType.equals(Void.TYPE)) { dest = res; } else { dest = params[1]; } if (m_check != null) { failure = (boolean) m_check.invoke(null, new Object[] {src, dest}); } else { if (isIntArray) { int[] int_res = (int[]) src; int[] int_dest = (int[]) dest; for (int j = 0; j < int_res.length; j++) { if (int_res[j] != int_dest[j]) { System.out.println( "Test " + name + " failed for " + j + " src[" + j + "]=" + int_res[j] + ", dest[" + j + "]=" + int_dest[j]); failure = true; } } } else { Object[] object_res = (Object[]) src; Object[] object_dest = (Object[]) dest; for (int j = 0; j < object_res.length; j++) { if (object_res[j] != object_dest[j]) { System.out.println( "Test " + name + " failed for " + j + " src[" + j + "]=" + object_res[j] + ", dest[" + j + "]=" + object_dest[j]); failure = true; } } } } } if (failure) { success = false; break; } } }
/** * Creates a new user entity from a username, password, array of roles, and additional arguments. * Usernames must be unique on the system, and are used by the user to log in to Splunk. * * @param name The username for the new user entity. * @param password The password for the new user entity. * @param roles Array of roles to assign to the new user entity. * @param args A map of additional arguments for the new user entity. * @return The new user entity. */ public User create(String name, String password, String[] roles, Map args) { args = Args.create(args); args.put("password", password); args.put("roles", roles); return create(name.toLowerCase(), args); }