idx int32 46 1.86M | input stringlengths 321 6.6k | target stringlengths 9 1.24k |
|---|---|---|
1,828,208 | public void storeFragment(ByteBuffer fragment, int length, boolean last) {<NEW_LINE>if (storage == null) {<NEW_LINE>int space = last ? length : length * 2;<NEW_LINE>storage = byteBufferPool.acquire(space, fragment.isDirect());<NEW_LINE>storage.clear();<NEW_LINE>}<NEW_LINE>// Grow the storage if necessary.<NEW_LINE>if (storage.remaining() < length) {<NEW_LINE>int space = last ? length : length * 2;<NEW_LINE>int capacity = storage.position() + space;<NEW_LINE>ByteBuffer newStorage = byteBufferPool.acquire(capacity, storage.isDirect());<NEW_LINE>newStorage.clear();<NEW_LINE>storage.flip();<NEW_LINE>newStorage.put(storage);<NEW_LINE>byteBufferPool.release(storage);<NEW_LINE>storage = newStorage;<NEW_LINE>}<NEW_LINE>// Copy the fragment into the storage.<NEW_LINE>int limit = fragment.limit();<NEW_LINE>fragment.limit(<MASK><NEW_LINE>storage.put(fragment);<NEW_LINE>fragment.limit(limit);<NEW_LINE>} | fragment.position() + length); |
168,340 | public static XContentParser createParser(NamedXContentRegistry xContentRegistry, DeprecationHandler deprecationHandler, BytesReference bytes) throws IOException {<NEW_LINE>Compressor compressor = CompressorFactory.compressor(bytes);<NEW_LINE>if (compressor != null) {<NEW_LINE>InputStream compressedInput = null;<NEW_LINE>try {<NEW_LINE>compressedInput = compressor.threadLocalInputStream(bytes.streamInput());<NEW_LINE>if (compressedInput.markSupported() == false) {<NEW_LINE>compressedInput = new BufferedInputStream(compressedInput);<NEW_LINE>}<NEW_LINE>final XContentType contentType = XContentFactory.xContentType(compressedInput);<NEW_LINE>return XContentFactory.xContent(contentType).<MASK><NEW_LINE>} catch (Exception e) {<NEW_LINE>if (compressedInput != null)<NEW_LINE>compressedInput.close();<NEW_LINE>throw e;<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>return XContentFactory.xContent(xContentType(bytes)).createParser(xContentRegistry, deprecationHandler, bytes.streamInput());<NEW_LINE>}<NEW_LINE>} | createParser(xContentRegistry, deprecationHandler, compressedInput); |
1,249,118 | /*<NEW_LINE>* @see java.io.OutputStream#write(byte[], int, int)<NEW_LINE>*/<NEW_LINE>public void write(byte[] b, int start, int len) throws IOException {<NEW_LINE>if (b == null) {<NEW_LINE>Tr.error(tc, "read.write.bytearray.null");<NEW_LINE>throw new NullPointerException(Tr.formatMessage(tc, "read.write.bytearray.null"));<NEW_LINE>}<NEW_LINE>if (start < 0 || len < 0 || start + len > b.length) {<NEW_LINE>Tr.error(tc, "read.write.offset.length.bytearraylength", new Object[] { start<MASK><NEW_LINE>throw new IndexOutOfBoundsException(Tr.formatMessage(tc, "read.write.offset.length.bytearraylength", new Object[] { start, len, b.length }));<NEW_LINE>}<NEW_LINE>if (this._listener != null && !checkIfCalledFromWLonError()) {<NEW_LINE>synchronized (this) {<NEW_LINE>if (this.isOutputStreamNBClosed()) {<NEW_LINE>Tr.error(tc, "stream.is.closed.no.read.write");<NEW_LINE>throw new IOException(Tr.formatMessage(tc, "stream.is.closed.no.read.write"));<NEW_LINE>}<NEW_LINE>if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())<NEW_LINE>Tr.debug(tc, "non blocking write requested, WriteListener enabled: " + this._listener);<NEW_LINE>write_NonBlocking(b, start, len);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>super.write(b, start, len);<NEW_LINE>}<NEW_LINE>} | , len, b.length }); |
806,810 | protected void cleanField(String structureInode, Field field) throws DotDataException, DotStateException, DotSecurityException {<NEW_LINE>StringBuffer sql = new StringBuffer("update contentlet set ");<NEW_LINE>if (field.getFieldContentlet().indexOf("float") != -1) {<NEW_LINE>if (DbConnectionFactory.isMySql())<NEW_LINE>sql.append(<MASK><NEW_LINE>else<NEW_LINE>sql.append("\"" + field.getFieldContentlet() + "\"" + " = ");<NEW_LINE>} else {<NEW_LINE>sql.append(field.getFieldContentlet() + " = ");<NEW_LINE>}<NEW_LINE>if (field.getFieldContentlet().indexOf("bool") != -1) {<NEW_LINE>sql.append(DbConnectionFactory.getDBFalse());<NEW_LINE>} else if (field.getFieldContentlet().indexOf("date") != -1) {<NEW_LINE>sql.append(DbConnectionFactory.getDBDateTimeFunction());<NEW_LINE>} else if (field.getFieldContentlet().indexOf("float") != -1) {<NEW_LINE>sql.append(0.0);<NEW_LINE>} else if (field.getFieldContentlet().indexOf("integer") != -1) {<NEW_LINE>sql.append(0);<NEW_LINE>} else {<NEW_LINE>sql.append("''");<NEW_LINE>}<NEW_LINE>sql.append(" where structure_inode = ?");<NEW_LINE>DotConnect dc = new DotConnect();<NEW_LINE>dc.setSQL(sql.toString());<NEW_LINE>dc.addParam(structureInode);<NEW_LINE>dc.loadResult();<NEW_LINE>// we could do a select here to figure out exactly which guys to evict<NEW_LINE>contentletCache.clearCache();<NEW_LINE>} | field.getFieldContentlet() + " = "); |
1,157,776 | protected String valueForURL(Tuple tuple) {<NEW_LINE>String url = tuple.getStringByField("url");<NEW_LINE>Metadata metadata = (Metadata) tuple.getValueByField("metadata");<NEW_LINE>// functionality deactivated<NEW_LINE>if (StringUtils.isBlank(canonicalMetadataParamName)) {<NEW_LINE>return url;<NEW_LINE>}<NEW_LINE>String canonicalValue = metadata.getFirstValue(canonicalMetadataName);<NEW_LINE>// no value found?<NEW_LINE>if (StringUtils.isBlank(canonicalValue)) {<NEW_LINE>return url;<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>URL sURL = new URL(url);<NEW_LINE>URL canonical = URLUtil.resolveURL(sURL, canonicalValue);<NEW_LINE>String sDomain = PaidLevelDomain.<MASK><NEW_LINE>String canonicalDomain = PaidLevelDomain.getPLD(canonical.getHost());<NEW_LINE>// check that the domain is the same<NEW_LINE>if (sDomain.equalsIgnoreCase(canonicalDomain)) {<NEW_LINE>return canonical.toExternalForm();<NEW_LINE>} else {<NEW_LINE>LOG.info("Canonical URL references a different domain, ignoring in {} ", url);<NEW_LINE>}<NEW_LINE>} catch (MalformedURLException e) {<NEW_LINE>LOG.error("Malformed canonical URL {} was found in {} ", canonicalValue, url);<NEW_LINE>}<NEW_LINE>return url;<NEW_LINE>} | getPLD(sURL.getHost()); |
1,248,246 | void tooltipAvailable(@Nullable String toolTip, @Nonnull MouseEvent e, @Nullable GutterMark renderer) {<NEW_LINE>myCalculatingInBackground = null;<NEW_LINE>TooltipController controller = TooltipController.getInstance();<NEW_LINE>if (toolTip == null || toolTip.isEmpty() || myEditor.isDisposed()) {<NEW_LINE>controller.cancelTooltip(GUTTER_TOOLTIP_GROUP, e, false);<NEW_LINE>} else {<NEW_LINE>final Ref<Point> t = new Ref<>(e.getPoint());<NEW_LINE>int line = myEditor.yToVisualLine(e.getY());<NEW_LINE>List<GutterMark> row = getGutterRenderers(line);<NEW_LINE>Balloon.Position ballPosition = Balloon.Position.atRight;<NEW_LINE>if (!row.isEmpty()) {<NEW_LINE>Map<Integer, GutterMark> xPos = new TreeMap<>();<NEW_LINE>final int[] currentPos = { 0 };<NEW_LINE>processIconsRow(line, row, (x, y, r) -> {<NEW_LINE>xPos.put(x, r);<NEW_LINE>if (renderer == r) {<NEW_LINE>currentPos[0] = x;<NEW_LINE>Icon icon = scaleIcon(r.getIcon());<NEW_LINE>t.set(new Point(x + icon.getIconWidth() / 2, y + icon.getIconHeight() / 2));<NEW_LINE>}<NEW_LINE>});<NEW_LINE>List<Integer> xx = new ArrayList<>(xPos.keySet());<NEW_LINE>int posIndex = xx.indexOf(currentPos[0]);<NEW_LINE>if (xPos.size() > 1 && posIndex == 0) {<NEW_LINE>ballPosition = Balloon.Position.below;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>RelativePoint showPoint = new RelativePoint(this, t.get());<NEW_LINE>TooltipRenderer tr = ((EditorMarkupModel) myEditor.getMarkupModel()).<MASK><NEW_LINE>HintHint hint = new HintHint(this, t.get()).setAwtTooltip(true).setPreferredPosition(ballPosition).setRequestFocus(ScreenReader.isActive());<NEW_LINE>if (myEditor.getComponent().getRootPane() != null) {<NEW_LINE>controller.showTooltipByMouseMove(myEditor, showPoint, tr, false, GUTTER_TOOLTIP_GROUP, hint);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | getErrorStripTooltipRendererProvider().calcTooltipRenderer(toolTip); |
621,200 | public CompletableFuture<ExecutionResult> execute(ExecutionContext executionContext, ExecutionStrategyParameters parameters) throws NonNullableFieldWasNullException {<NEW_LINE>Instrumentation instrumentation = executionContext.getInstrumentation();<NEW_LINE>InstrumentationExecutionStrategyParameters instrumentationParameters = new InstrumentationExecutionStrategyParameters(executionContext, parameters);<NEW_LINE>ExecutionStrategyInstrumentationContext executionStrategyCtx = instrumentation.beginExecutionStrategy(instrumentationParameters);<NEW_LINE>CompletableFuture<Publisher<Object>> <MASK><NEW_LINE>//<NEW_LINE>// when the upstream source event stream completes, subscribe to it and wire in our adapter<NEW_LINE>CompletableFuture<ExecutionResult> overallResult = sourceEventStream.thenApply((publisher) -> {<NEW_LINE>if (publisher == null) {<NEW_LINE>return new ExecutionResultImpl(null, executionContext.getErrors());<NEW_LINE>}<NEW_LINE>Function<Object, CompletionStage<ExecutionResult>> mapperFunction = eventPayload -> executeSubscriptionEvent(executionContext, parameters, eventPayload);<NEW_LINE>SubscriptionPublisher mapSourceToResponse = new SubscriptionPublisher(publisher, mapperFunction);<NEW_LINE>return new ExecutionResultImpl(mapSourceToResponse, executionContext.getErrors());<NEW_LINE>});<NEW_LINE>// dispatched the subscription query<NEW_LINE>executionStrategyCtx.onDispatched(overallResult);<NEW_LINE>overallResult.whenComplete(executionStrategyCtx::onCompleted);<NEW_LINE>return overallResult;<NEW_LINE>} | sourceEventStream = createSourceEventStream(executionContext, parameters); |
1,294,161 | public boolean apply(Game game, Ability source) {<NEW_LINE>Player player = game.getPlayer(source.getControllerId());<NEW_LINE>if (player != null && player.isLifeTotalCanChange()) {<NEW_LINE>Permanent perm = game.getPermanent(source.getSourceId());<NEW_LINE>if (perm != null) {<NEW_LINE>int amount = perm.getToughness().getValue();<NEW_LINE><MASK><NEW_LINE>if (life == amount) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>if (life < amount && !player.isCanGainLife()) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>if (life > amount && !player.isCanLoseLife()) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>player.setLife(amount, game, source);<NEW_LINE>game.addEffect(new SetPowerToughnessSourceEffect(Integer.MIN_VALUE, life, Duration.Custom, SubLayer.SetPT_7b), source);<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return false;<NEW_LINE>} | int life = player.getLife(); |
965,318 | private TreeItem createContainer(TreeItem parent, String name) {<NEW_LINE>TreeItem[] selection = tree.getSelection();<NEW_LINE>// boolean moveSelected = false;<NEW_LINE>if (parent == null) {<NEW_LINE>if (selection.length == 1 && selection[0].getData() == null) {<NEW_LINE>parent = selection[0];<NEW_LINE>} else if (selection.length > 0) {<NEW_LINE>parent = selection[0].getParentItem();<NEW_LINE>// moveSelected = true;<NEW_LINE>} else {<NEW_LINE>TreeItem firstItem = tree.getItemCount() > 0 ? tree.getItem(0) : null;<NEW_LINE>if (firstItem != null && firstItem.getData() == null) {<NEW_LINE>parent = firstItem;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>TreeItem item = parent == null ? new TreeItem(tree, 0, 0) : new <MASK><NEW_LINE>item.setText(new String[] { name, MessageText.getString("label.container.display") });<NEW_LINE>while (tree.getItemCount() > 1) {<NEW_LINE>TreeItem itemToMove = tree.getItem(1);<NEW_LINE>moveItem(itemToMove, item);<NEW_LINE>}<NEW_LINE>item.setExpanded(true);<NEW_LINE>return item;<NEW_LINE>} | TreeItem(parent, 0, 0); |
1,599,698 | protected View createEmbeddedView(MetaClass meta, String fqnPrefix) {<NEW_LINE>View view = new View(meta.getJavaClass(), false);<NEW_LINE>for (MetaProperty metaProperty : meta.getProperties()) {<NEW_LINE>String fqn = fqnPrefix + "." + metaProperty.getName();<NEW_LINE>if (!managedFields.containsKey(fqn)) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>switch(metaProperty.getType()) {<NEW_LINE>case DATATYPE:<NEW_LINE>case ENUM:<NEW_LINE>view.addProperty(metaProperty.getName());<NEW_LINE>break;<NEW_LINE>case ASSOCIATION:<NEW_LINE>case COMPOSITION:<NEW_LINE>View propView;<NEW_LINE>if (!metadataTools.isEmbedded(metaProperty)) {<NEW_LINE>propView = viewRepository.getView(metaProperty.getRange().<MASK><NEW_LINE>} else {<NEW_LINE>// build view for embedded property<NEW_LINE>propView = createEmbeddedView(metaProperty.getRange().asClass(), fqn);<NEW_LINE>}<NEW_LINE>// in some cases JPA loads extended entities as instance of base class which leads to ClassCastException<NEW_LINE>// loading property lazy prevents this from happening<NEW_LINE>view.addProperty(metaProperty.getName(), propView);<NEW_LINE>break;<NEW_LINE>default:<NEW_LINE>throw new IllegalStateException("unknown property type");<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return view;<NEW_LINE>} | asClass(), View.MINIMAL); |
878,361 | private // with all possible modifiers (Ctrl, Shift, Alt, etc.)<NEW_LINE>void registerSelectItemAction() {<NEW_LINE>int[] allowedModifiers = new int[] { 0, InputEvent.SHIFT_MASK, InputEvent.CTRL_MASK, InputEvent.META_MASK, InputEvent.ALT_MASK };<NEW_LINE>ShortcutSet selectShortcuts = ActionManager.getInstance().getAction(SearchEverywhereActions.SELECT_ITEM).getShortcutSet();<NEW_LINE>Collection<KeyboardShortcut> keyboardShortcuts = Arrays.stream(selectShortcuts.getShortcuts()).filter(shortcut -> shortcut instanceof KeyboardShortcut).map(shortcut -> (KeyboardShortcut) shortcut).collect(Collectors.toList());<NEW_LINE>for (int modifiers : allowedModifiers) {<NEW_LINE>Collection<Shortcut> newShortcuts = new ArrayList<>();<NEW_LINE>for (KeyboardShortcut shortcut : keyboardShortcuts) {<NEW_LINE>boolean hasSecondStroke = shortcut.getSecondKeyStroke() != null;<NEW_LINE>KeyStroke originalStroke = hasSecondStroke ? shortcut.getSecondKeyStroke<MASK><NEW_LINE>if ((originalStroke.getModifiers() & modifiers) != 0)<NEW_LINE>continue;<NEW_LINE>KeyStroke newStroke = KeyStroke.getKeyStroke(originalStroke.getKeyCode(), originalStroke.getModifiers() | modifiers);<NEW_LINE>newShortcuts.add(hasSecondStroke ? new KeyboardShortcut(shortcut.getFirstKeyStroke(), newStroke) : new KeyboardShortcut(newStroke, null));<NEW_LINE>}<NEW_LINE>if (newShortcuts.isEmpty())<NEW_LINE>continue;<NEW_LINE>ShortcutSet newShortcutSet = new CustomShortcutSet(newShortcuts.toArray(Shortcut.EMPTY_ARRAY));<NEW_LINE>DumbAwareAction.create(event -> {<NEW_LINE>int[] indices = myResultsList.getSelectedIndices();<NEW_LINE>elementsSelected(indices, modifiers);<NEW_LINE>}).registerCustomShortcutSet(newShortcutSet, this, this);<NEW_LINE>}<NEW_LINE>} | () : shortcut.getFirstKeyStroke(); |
917,186 | public ModelMapper createNew(List<Row> modelRows) {<NEW_LINE>System.out.println("update model");<NEW_LINE>FmModelMapper fmModelMapper = new FmModelMapper(getModelSchema(), getDataSchema(), params.clone());<NEW_LINE>FmModelData modelData = new FmModelData();<NEW_LINE>modelData.vectorColName = this.model.vectorColName;<NEW_LINE>modelData.featureColNames = this.model.featureColNames;<NEW_LINE>modelData.labelColName = this.model.labelColName;<NEW_LINE>modelData.task = this.model.task;<NEW_LINE>modelData.dim = this.model.dim;<NEW_LINE>modelData.vectorSize = this.model.vectorSize;<NEW_LINE>modelData.labelValues = this.model.labelValues;<NEW_LINE>modelData.fmModel = new FmDataFormat();<NEW_LINE>modelData.fmModel.factors = new double[modelData.vectorSize][];<NEW_LINE>modelData.fmModel.dim = modelData.dim;<NEW_LINE>int featureSize = model.fmModel.factors.length;<NEW_LINE>for (int i = 0; i < featureSize; ++i) {<NEW_LINE>if (model.fmModel.factors[i] != null) {<NEW_LINE>modelData.fmModel.factors[i] = model.fmModel.factors[i];<NEW_LINE>}<NEW_LINE>}<NEW_LINE>for (Row row : modelRows) {<NEW_LINE>Long featureId = (Long) row.getField(0);<NEW_LINE>if (featureId == null) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>if (featureId >= 0) {<NEW_LINE>double[] factor = JsonConverter.fromJson((String) row.getField(1), double[].class);<NEW_LINE>modelData.fmModel.factors[featureId.intValue()] = factor;<NEW_LINE>} else if (featureId == -1) {<NEW_LINE>double[] factor = JsonConverter.fromJson((String) row.getField(1), double[].class);<NEW_LINE>model.<MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>fmModelMapper.model = modelData;<NEW_LINE>return this;<NEW_LINE>} | fmModel.bias = factor[0]; |
607,515 | public static void dissectReplayNewLeadershipTerm(final ClusterEventCode eventCode, final MutableDirectBuffer buffer, final int offset, final StringBuilder builder) {<NEW_LINE>int absoluteOffset = offset;<NEW_LINE>absoluteOffset += dissectLogHeader(CONTEXT, eventCode, buffer, absoluteOffset, builder);<NEW_LINE>final int memberId = buffer.getInt(absoluteOffset, LITTLE_ENDIAN);<NEW_LINE>absoluteOffset += SIZE_OF_INT;<NEW_LINE>final boolean isInElection = 0 != buffer.getInt(absoluteOffset, LITTLE_ENDIAN);<NEW_LINE>absoluteOffset += SIZE_OF_INT;<NEW_LINE>final long leadershipTermId = buffer.getLong(absoluteOffset, LITTLE_ENDIAN);<NEW_LINE>absoluteOffset += SIZE_OF_LONG;<NEW_LINE>final long logPosition = buffer.getLong(absoluteOffset, LITTLE_ENDIAN);<NEW_LINE>absoluteOffset += SIZE_OF_LONG;<NEW_LINE>final long timestamp = buffer.getLong(absoluteOffset, LITTLE_ENDIAN);<NEW_LINE>absoluteOffset += SIZE_OF_LONG;<NEW_LINE>final long termBaseLogPosition = buffer.getLong(absoluteOffset, LITTLE_ENDIAN);<NEW_LINE>absoluteOffset += SIZE_OF_LONG;<NEW_LINE>final int appVersion = buffer.getInt(absoluteOffset, LITTLE_ENDIAN);<NEW_LINE>absoluteOffset += SIZE_OF_INT;<NEW_LINE>final int timeUnitLength = buffer.getInt(absoluteOffset, LITTLE_ENDIAN);<NEW_LINE>absoluteOffset += SIZE_OF_INT;<NEW_LINE>builder.append(": memberId=").append(memberId);<NEW_LINE>builder.append<MASK><NEW_LINE>builder.append(" leadershipTermId=").append(leadershipTermId);<NEW_LINE>builder.append(" logPosition=").append(logPosition);<NEW_LINE>builder.append(" termBaseLogPosition=").append(termBaseLogPosition);<NEW_LINE>builder.append(" appVersion=").append(appVersion);<NEW_LINE>builder.append(" timestamp=").append(timestamp);<NEW_LINE>builder.append(" timeUnit=");<NEW_LINE>buffer.getStringWithoutLengthAscii(absoluteOffset, timeUnitLength, builder);<NEW_LINE>} | (" isInElection=").append(isInElection); |
1,680,232 | protected int countByC_C_C(String companyId, String className, String classPK) throws SystemException {<NEW_LINE>Session session = null;<NEW_LINE>try {<NEW_LINE>session = openSession();<NEW_LINE>StringBuffer query = new StringBuffer();<NEW_LINE>query.append("SELECT COUNT(*) ");<NEW_LINE>query.append("FROM Address IN CLASS com.liferay.portal.ejb.AddressHBM WHERE ");<NEW_LINE>query.append("companyId = ?");<NEW_LINE>query.append(" AND ");<NEW_LINE>query.append("className = ?");<NEW_LINE>query.append(" AND ");<NEW_LINE>query.append("classPK = ?");<NEW_LINE>query.append(" ");<NEW_LINE>Query q = session.createQuery(query.toString());<NEW_LINE>int queryPos = 0;<NEW_LINE>q.setString(queryPos++, companyId);<NEW_LINE>q.setString(queryPos++, className);<NEW_LINE>q.setString(queryPos++, classPK);<NEW_LINE>Iterator itr = q<MASK><NEW_LINE>if (itr.hasNext()) {<NEW_LINE>Integer count = (Integer) itr.next();<NEW_LINE>if (count != null) {<NEW_LINE>return count.intValue();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return 0;<NEW_LINE>} catch (HibernateException he) {<NEW_LINE>throw new SystemException(he);<NEW_LINE>} finally {<NEW_LINE>HibernateUtil.closeSession(session);<NEW_LINE>}<NEW_LINE>} | .list().iterator(); |
918,219 | protected <T> T convert(Class<T> type, String value, T defaultValue) {<NEW_LINE>if (value == null) {<NEW_LINE>return defaultValue;<NEW_LINE>}<NEW_LINE>if (type == Boolean.class) {<NEW_LINE>return (T) Boolean.valueOf(value);<NEW_LINE>} else if (type == Integer.class) {<NEW_LINE>return (T) Integer.valueOf(value);<NEW_LINE>} else if (type == Long.class) {<NEW_LINE>return (T) Long.valueOf(value);<NEW_LINE>} else if (type == Short.class) {<NEW_LINE>return (T) Short.valueOf(value);<NEW_LINE>} else if (type == Float.class) {<NEW_LINE>return (T) Float.valueOf(value);<NEW_LINE>} else if (type == Double.class) {<NEW_LINE>return (<MASK><NEW_LINE>} else if (type == Byte.class) {<NEW_LINE>return (T) Byte.valueOf(value);<NEW_LINE>} else if (type == Character.class) {<NEW_LINE>return (T) (Character) value.charAt(0);<NEW_LINE>} else {<NEW_LINE>return (T) value;<NEW_LINE>}<NEW_LINE>} | T) Double.valueOf(value); |
134,341 | private PluginOperationResult executeUpdate() throws Exception {<NEW_LINE>List<String> updateablePlugins = findUpdateCandidates();<NEW_LINE>List<String> erroneousPlugins = Lists.newArrayList();<NEW_LINE>List<String> delayedPlugins = Lists.newArrayList();<NEW_LINE>// update only a specific plugin if it is updatable and provided<NEW_LINE>String forcePluginId = options.getPluginId();<NEW_LINE>logger.log(Level.FINE, "Force plugin is " + forcePluginId);<NEW_LINE>if (forcePluginId != null) {<NEW_LINE>if (updateablePlugins.contains(forcePluginId)) {<NEW_LINE>updateablePlugins = Lists.newArrayList(forcePluginId);<NEW_LINE>} else {<NEW_LINE>logger.log(Level.WARNING, "User requested to update a non-updatable plugin: " + forcePluginId);<NEW_LINE>erroneousPlugins.add(forcePluginId);<NEW_LINE>// empty list<NEW_LINE>updateablePlugins = Lists.newArrayList();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>logger.log(Level.INFO, "The following plugins can be automatically updated: " + StringUtil.join(updateablePlugins, ", "));<NEW_LINE>for (String pluginId : updateablePlugins) {<NEW_LINE>// first remove<NEW_LINE>PluginOperationResult removeResult = executeRemove(pluginId);<NEW_LINE>if (removeResult.getResultCode() == PluginResultCode.NOK) {<NEW_LINE>logger.log(Level.SEVERE, "Unable to remove " + pluginId + " during the update process");<NEW_LINE>erroneousPlugins.add(pluginId);<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>// ... and install again<NEW_LINE>if (EnvironmentUtil.isWindows()) {<NEW_LINE>logger.log(Level.FINE, "Appending jar to updatefile");<NEW_LINE>File updatefilePath = new File(<MASK><NEW_LINE>try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(updatefilePath, true)))) {<NEW_LINE>out.println(pluginId + (options.isSnapshots() ? " --snapshot" : ""));<NEW_LINE>delayedPlugins.add(pluginId);<NEW_LINE>} catch (IOException e) {<NEW_LINE>logger.log(Level.SEVERE, "Unable to append to updatefile " + updatefilePath, e);<NEW_LINE>erroneousPlugins.add(pluginId);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>PluginOperationResult installResult = executeInstallFromApiHost(pluginId);<NEW_LINE>if (installResult.getResultCode() == PluginResultCode.NOK) {<NEW_LINE>logger.log(Level.SEVERE, "Unable to install " + pluginId + " during the update process");<NEW_LINE>erroneousPlugins.add(pluginId);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (erroneousPlugins.size() > 0 && erroneousPlugins.size() == updateablePlugins.size()) {<NEW_LINE>result.setResultCode(PluginResultCode.NOK);<NEW_LINE>} else {<NEW_LINE>result.setResultCode(PluginResultCode.OK);<NEW_LINE>}<NEW_LINE>result.setUpdatedPluginIds(updateablePlugins);<NEW_LINE>result.setErroneousPluginIds(erroneousPlugins);<NEW_LINE>result.setDelayedPluginIds(delayedPlugins);<NEW_LINE>return result;<NEW_LINE>} | UserConfig.getUserConfigDir(), UPDATE_FILENAME); |
399,745 | public void execute() {<NEW_LINE>if (action == StandardActions.ABBREVIATE_DEFAULT || action == StandardActions.ABBREVIATE_MEDLINE || action == StandardActions.ABBREVIATE_SHORTEST_UNIQUE) {<NEW_LINE>dialogService.notify<MASK><NEW_LINE>stateManager.getActiveDatabase().ifPresent(databaseContext -> BackgroundTask.wrap(() -> abbreviate(stateManager.getActiveDatabase().get(), stateManager.getSelectedEntries())).onSuccess(dialogService::notify).executeWith(Globals.TASK_EXECUTOR));<NEW_LINE>} else if (action == StandardActions.UNABBREVIATE) {<NEW_LINE>dialogService.notify(Localization.lang("Unabbreviating..."));<NEW_LINE>stateManager.getActiveDatabase().ifPresent(databaseContext -> BackgroundTask.wrap(() -> unabbreviate(stateManager.getActiveDatabase().get(), stateManager.getSelectedEntries())).onSuccess(dialogService::notify).executeWith(Globals.TASK_EXECUTOR));<NEW_LINE>} else {<NEW_LINE>LOGGER.debug("Unknown action: " + action.name());<NEW_LINE>}<NEW_LINE>} | (Localization.lang("Abbreviating...")); |
780,675 | public boolean validate() throws ContractValidateException {<NEW_LINE>if (this.any == null) {<NEW_LINE>throw new ContractValidateException(ActuatorConstant.CONTRACT_NOT_EXIST);<NEW_LINE>}<NEW_LINE>if (chainBaseManager == null) {<NEW_LINE>throw new ContractValidateException("No account store or contract store!");<NEW_LINE>}<NEW_LINE>AccountStore accountStore = chainBaseManager.getAccountStore();<NEW_LINE>if (!any.is(AccountCreateContract.class)) {<NEW_LINE>throw new ContractValidateException("contract type error,expected type [AccountCreateContract],real type[" + any.getClass() + "]");<NEW_LINE>}<NEW_LINE>final AccountCreateContract contract;<NEW_LINE>try {<NEW_LINE>contract = this.any.unpack(AccountCreateContract.class);<NEW_LINE>} catch (InvalidProtocolBufferException e) {<NEW_LINE>logger.debug(e.getMessage(), e);<NEW_LINE>throw new ContractValidateException(e.getMessage());<NEW_LINE>}<NEW_LINE>// if (contract.getAccountName().isEmpty()) {<NEW_LINE>// throw new ContractValidateException("AccountName is null");<NEW_LINE>// }<NEW_LINE>byte[] ownerAddress = contract.getOwnerAddress().toByteArray();<NEW_LINE>if (!DecodeUtil.addressValid(ownerAddress)) {<NEW_LINE>throw new ContractValidateException("Invalid ownerAddress");<NEW_LINE>}<NEW_LINE>AccountCapsule accountCapsule = accountStore.get(ownerAddress);<NEW_LINE>if (accountCapsule == null) {<NEW_LINE>String <MASK><NEW_LINE>throw new ContractValidateException(ActuatorConstant.ACCOUNT_EXCEPTION_STR + readableOwnerAddress + NOT_EXIST_STR);<NEW_LINE>}<NEW_LINE>final long fee = calcFee();<NEW_LINE>if (accountCapsule.getBalance() < fee) {<NEW_LINE>throw new ContractValidateException("Validate CreateAccountActuator error, insufficient fee.");<NEW_LINE>}<NEW_LINE>byte[] accountAddress = contract.getAccountAddress().toByteArray();<NEW_LINE>if (!DecodeUtil.addressValid(accountAddress)) {<NEW_LINE>throw new ContractValidateException("Invalid account address");<NEW_LINE>}<NEW_LINE>// if (contract.getType() == null) {<NEW_LINE>// throw new ContractValidateException("Type is null");<NEW_LINE>// }<NEW_LINE>if (accountStore.has(accountAddress)) {<NEW_LINE>throw new ContractValidateException("Account has existed");<NEW_LINE>}<NEW_LINE>return true;<NEW_LINE>} | readableOwnerAddress = StringUtil.createReadableString(ownerAddress); |
671,713 | public void saveApplication() {<NEW_LINE>cmpgn = MapTool.getCampaign();<NEW_LINE>// Create the load/save dialog form.<NEW_LINE>// Populate it with maps, tables, macros, and so forth.<NEW_LINE>// Display it to the user with either a LOAD or SAVE button.<NEW_LINE>// When they're done, write the selected components out.<NEW_LINE>UIBuilder form = new UIBuilder(MapTool.getFrame());<NEW_LINE>model = form.getTreeModel();<NEW_LINE>addToRegistry(new DataTemplate() {<NEW_LINE><NEW_LINE>public String getSubsystemName() {<NEW_LINE>return "built-in";<NEW_LINE>}<NEW_LINE><NEW_LINE>public void prepareForDisplay() {<NEW_LINE>addDataObjects("Campaign/Properties/Token Properties", cmpgn.getTokenTypeMap());<NEW_LINE>addDataObjects("Campaign/Properties/Repositories", cmpgn.getRemoteRepositoryList());<NEW_LINE>addDataObjects("Campaign/Properties/Sights", cmpgn.getSightTypeMap());<NEW_LINE>addDataObjects("Campaign/Properties/Lights", cmpgn.getLightSourcesMap());<NEW_LINE>addDataObjects("Campaign/Properties/States", cmpgn.getTokenStatesMap());<NEW_LINE>addDataObjects("Campaign/Properties/Bars", cmpgn.getTokenBarsMap());<NEW_LINE>addDataObjects("Campaign/Properties/Tables", cmpgn.getLookupTableMap());<NEW_LINE>addDataObjects("Campaign/CampaignMacros", cmpgn.getMacroButtonPropertiesArray());<NEW_LINE>addDataObjects(<MASK><NEW_LINE>addDataObjects("Campaign/Maps", cmpgn.getZones());<NEW_LINE>}<NEW_LINE>});<NEW_LINE>for (String name : registry.keySet()) {<NEW_LINE>DataTemplate dt = registry.get(name);<NEW_LINE>dt.populateModel(model);<NEW_LINE>}<NEW_LINE>form.expandAndSelectAll(true);<NEW_LINE>form.pack();<NEW_LINE>form.setVisible(true);<NEW_LINE>if (form.getStatus() == JOptionPane.OK_OPTION) {<NEW_LINE>// Clicked OK to perform a load/save operation.<NEW_LINE>}<NEW_LINE>} | "Campaign/GmMacros", cmpgn.getGmMacroButtonPropertiesArray()); |
706,493 | public Map<String, BlobMetaData> listBlobsByPrefix(String account, String container, String keyPath, String prefix) throws URISyntaxException, StorageException, IOException {<NEW_LINE>// NOTE: this should be here: if (prefix == null) prefix = "";<NEW_LINE>// however, this is really inefficient since deleteBlobsByPrefix enumerates everything and<NEW_LINE>// then does a prefix match on the result; it should just call listBlobsByPrefix with the prefix!<NEW_LINE>final MapBuilder<String, BlobMetaData> blobsBuilder = MapBuilder.newMapBuilder();<NEW_LINE>final EnumSet<BlobListingDetails> enumBlobListingDetails = EnumSet.of(BlobListingDetails.METADATA);<NEW_LINE>final Tuple<CloudBlobClient, Supplier<OperationContext>> client = client(account);<NEW_LINE>final CloudBlobContainer blobContainer = client.v1().getContainerReference(container);<NEW_LINE>logger.trace(() -> new ParameterizedMessage("listing container [{}], keyPath [{}], prefix [{}]"<MASK><NEW_LINE>SocketAccess.doPrivilegedVoidException(() -> {<NEW_LINE>for (final ListBlobItem blobItem : blobContainer.listBlobs(keyPath + (prefix == null ? "" : prefix), false, enumBlobListingDetails, null, client.v2().get())) {<NEW_LINE>final URI uri = blobItem.getUri();<NEW_LINE>logger.trace(() -> new ParameterizedMessage("blob url [{}]", uri));<NEW_LINE>// uri.getPath is of the form /container/keyPath.* and we want to strip off the /container/<NEW_LINE>// this requires 1 + container.length() + 1, with each 1 corresponding to one of the /<NEW_LINE>final String blobPath = uri.getPath().substring(1 + container.length() + 1);<NEW_LINE>final BlobProperties properties = ((CloudBlockBlob) blobItem).getProperties();<NEW_LINE>final String name = blobPath.substring(keyPath.length());<NEW_LINE>logger.trace(() -> new ParameterizedMessage("blob url [{}], name [{}], size [{}]", uri, name, properties.getLength()));<NEW_LINE>blobsBuilder.put(name, new PlainBlobMetaData(name, properties.getLength()));<NEW_LINE>}<NEW_LINE>});<NEW_LINE>return blobsBuilder.immutableMap();<NEW_LINE>} | , container, keyPath, prefix)); |
847,042 | static String buildUrl(ClickHouseNode server, ClickHouseRequest<?> request) {<NEW_LINE><MASK><NEW_LINE>StringBuilder builder = new StringBuilder();<NEW_LINE>builder.append(config.isSsl() ? "https" : "http").append("://").append(server.getHost()).append(':').append(server.getPort()).append('/');<NEW_LINE>String context = (String) config.getOption(ClickHouseHttpOption.WEB_CONTEXT);<NEW_LINE>if (context != null && !context.isEmpty()) {<NEW_LINE>char prev = '/';<NEW_LINE>for (int i = 0, len = context.length(); i < len; i++) {<NEW_LINE>char ch = context.charAt(i);<NEW_LINE>if (ch != '/' || ch != prev) {<NEW_LINE>builder.append(ch);<NEW_LINE>}<NEW_LINE>prev = ch;<NEW_LINE>}<NEW_LINE>if (prev != '/') {<NEW_LINE>builder.append('/');<NEW_LINE>}<NEW_LINE>}<NEW_LINE>String query = buildQueryParams(request);<NEW_LINE>if (!query.isEmpty()) {<NEW_LINE>builder.append('?').append(query);<NEW_LINE>}<NEW_LINE>return builder.toString();<NEW_LINE>} | ClickHouseConfig config = request.getConfig(); |
528,711 | protected void translateCore(final ITranslationEnvironment environment, final IInstruction instruction, final List<ReilInstruction> instructions) throws InternalTranslationException {<NEW_LINE>final IOperandTreeNode registerOperand1 = instruction.getOperands().get(0).getRootNode().getChildren().get(0);<NEW_LINE>final IOperandTreeNode rootNode = instruction.getOperands().get(1).getRootNode();<NEW_LINE>final String registerNodeValue = (registerOperand1.getValue());<NEW_LINE>final OperandSize wd = OperandSize.WORD;<NEW_LINE>final OperandSize dw = OperandSize.DWORD;<NEW_LINE>final OperandSize bt = OperandSize.BYTE;<NEW_LINE>long baseOffset = ReilHelpers.nextReilAddress(instruction, instructions);<NEW_LINE>final Pair<String, String> resultPair = AddressingModeTwoGenerator.generate(baseOffset, <MASK><NEW_LINE>final String tmpAddress = resultPair.first();<NEW_LINE>final String negRotateVal = environment.getNextVariableString();<NEW_LINE>final String posRotateVal = environment.getNextVariableString();<NEW_LINE>final String rotateVal1 = environment.getNextVariableString();<NEW_LINE>final String rotateVal2 = environment.getNextVariableString();<NEW_LINE>final String rotResult1 = environment.getNextVariableString();<NEW_LINE>final String rotResult2 = environment.getNextVariableString();<NEW_LINE>final String tmpData1 = environment.getNextVariableString();<NEW_LINE>final String tmpRotResult = environment.getNextVariableString();<NEW_LINE>baseOffset = baseOffset + instructions.size();<NEW_LINE>instructions.add(ReilHelpers.createLdm(baseOffset++, dw, tmpAddress, dw, tmpData1));<NEW_LINE>// get rotate * 8<NEW_LINE>instructions.add(ReilHelpers.createAnd(baseOffset++, dw, tmpAddress, bt, String.valueOf(0x3L), bt, rotateVal1));<NEW_LINE>instructions.add(ReilHelpers.createMul(baseOffset++, bt, rotateVal1, bt, String.valueOf(8), wd, rotateVal2));<NEW_LINE>// subtraction to get the negative shift val<NEW_LINE>instructions.add(ReilHelpers.createSub(baseOffset++, wd, String.valueOf(0), wd, rotateVal2, dw, negRotateVal));<NEW_LINE>instructions.add(ReilHelpers.createSub(baseOffset++, wd, String.valueOf(32), wd, rotateVal2, dw, posRotateVal));<NEW_LINE>// do the rotation<NEW_LINE>instructions.add(ReilHelpers.createBsh(baseOffset++, dw, tmpData1, dw, negRotateVal, dw, rotResult1));<NEW_LINE>instructions.add(ReilHelpers.createBsh(baseOffset++, dw, tmpData1, dw, posRotateVal, dw, rotResult2));<NEW_LINE>instructions.add(ReilHelpers.createOr(baseOffset++, dw, rotResult1, dw, rotResult2, dw, tmpRotResult));<NEW_LINE>// assing it<NEW_LINE>instructions.add(ReilHelpers.createAnd(baseOffset++, dw, tmpRotResult, dw, String.valueOf(0xFFFFFFFFL), dw, registerNodeValue));<NEW_LINE>} | environment, instruction, instructions, rootNode); |
917,214 | final ConfirmProductInstanceResult executeConfirmProductInstance(ConfirmProductInstanceRequest confirmProductInstanceRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(confirmProductInstanceRequest);<NEW_LINE><MASK><NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<ConfirmProductInstanceRequest> request = null;<NEW_LINE>Response<ConfirmProductInstanceResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new ConfirmProductInstanceRequestMarshaller().marshall(super.beforeMarshalling(confirmProductInstanceRequest));<NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);<NEW_LINE>request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "EC2");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "ConfirmProductInstance");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>StaxResponseHandler<ConfirmProductInstanceResult> responseHandler = new StaxResponseHandler<ConfirmProductInstanceResult>(new ConfirmProductInstanceResultStaxUnmarshaller());<NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); |
671,691 | private CompiledQuery alterTableSetParam(CharSequence paramName, CharSequence value, int paramNameNamePosition, String tableName, int tableId) throws SqlException {<NEW_LINE>if (isMaxUncommittedRowsParam(paramName)) {<NEW_LINE>int maxUncommittedRows;<NEW_LINE>try {<NEW_LINE>maxUncommittedRows = Numbers.parseInt(value);<NEW_LINE>} catch (NumericException e) {<NEW_LINE>throw SqlException.$(paramNameNamePosition, "invalid value [value=").put(value).put(",parameter=").put(paramName).put(']');<NEW_LINE>}<NEW_LINE>if (maxUncommittedRows < 0) {<NEW_LINE>throw SqlException.$(paramNameNamePosition, "maxUncommittedRows must be non negative");<NEW_LINE>}<NEW_LINE>return compiledQuery.ofAlter(alterQueryBuilder.ofSetParamUncommittedRows(tableName, tableId, maxUncommittedRows).build());<NEW_LINE>} else if (isCommitLag(paramName)) {<NEW_LINE>long commitLag = SqlUtil.expectMicros(value, paramNameNamePosition);<NEW_LINE>if (commitLag < 0) {<NEW_LINE>throw <MASK><NEW_LINE>}<NEW_LINE>return compiledQuery.ofAlter(alterQueryBuilder.ofSetParamCommitLag(tableName, tableId, commitLag).build());<NEW_LINE>} else {<NEW_LINE>throw SqlException.$(paramNameNamePosition, "unknown parameter '").put(paramName).put('\'');<NEW_LINE>}<NEW_LINE>} | SqlException.$(paramNameNamePosition, "commitLag must be non negative"); |
433,538 | private void prepareEvaluationContext() {<NEW_LINE>StandardEvaluationContext context = getEvaluationContext();<NEW_LINE>Class<?> targetType = AopUtils.getTargetClass(this.targetObject);<NEW_LINE>if (this.method != null) {<NEW_LINE>context.registerMethodFilter(targetType, new FixedMethodFilter(ClassUtils.getMostSpecificMethod(this.method, targetType)));<NEW_LINE>if (this.expectedType != null) {<NEW_LINE>Assert.state(context.getTypeConverter().canConvert(TypeDescriptor.valueOf((this.method).getReturnType()), this.expectedType), () -> "Cannot convert to expected type (" + this.expectedType + ") from " + this.method);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>AnnotatedMethodFilter filter = new AnnotatedMethodFilter(this.annotationType, this.methodName, this.requiresReply);<NEW_LINE>Assert.state(canReturnExpectedType(filter, targetType, context.getTypeConverter()), () -> "Cannot convert to expected type (" + this.expectedType + ") from " + this.methodName);<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>context.setVariable("target", this.targetObject);<NEW_LINE>try {<NEW_LINE>context.registerFunction("requiredHeader", ParametersWrapper.class.getDeclaredMethod("getHeader", Map.class, String.class));<NEW_LINE>} catch (NoSuchMethodException ex) {<NEW_LINE>throw new IllegalStateException(ex);<NEW_LINE>}<NEW_LINE>} | context.registerMethodFilter(targetType, filter); |
1,153,881 | public DisplayNames display(String sorted, String type, String ip, TransactionReport report, String queryName) {<NEW_LINE>Map<String, TransactionType> types = report.findOrCreateMachine(ip).getTypes();<NEW_LINE>TransactionName all = new TransactionName("TOTAL");<NEW_LINE>all.setTotalPercent(1);<NEW_LINE>if (types != null) {<NEW_LINE>TransactionType names = types.get(type);<NEW_LINE>if (names != null) {<NEW_LINE>for (Entry<String, TransactionName> entry : names.getNames().entrySet()) {<NEW_LINE>String transTypeName = entry.getValue().getId();<NEW_LINE>boolean isAdd = (queryName == null || queryName.length() == 0 || isFit(queryName, transTypeName));<NEW_LINE>if (isAdd) {<NEW_LINE>m_results.add(new TransactionNameModel(entry.getKey(), entry.getValue()));<NEW_LINE>mergeName(all, entry.getValue());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (sorted == null) {<NEW_LINE>sorted = "avg";<NEW_LINE>}<NEW_LINE>Collections.sort(m_results, new TransactionNameComparator(sorted));<NEW_LINE><MASK><NEW_LINE>for (TransactionNameModel nameModel : m_results) {<NEW_LINE>TransactionName transactionName = nameModel.getDetail();<NEW_LINE>transactionName.setTotalPercent(transactionName.getTotalCount() / (double) total);<NEW_LINE>}<NEW_LINE>m_results.add(0, new TransactionNameModel("TOTAL", all));<NEW_LINE>return this;<NEW_LINE>} | long total = all.getTotalCount(); |
726,564 | public static void main(String[] args) throws Exception {<NEW_LINE>// Create and configure HTTPS client<NEW_LINE>Client client = new Client(new Context(), Protocol.HTTPS);<NEW_LINE>Series<Parameter> parameters = client.getContext().getParameters();<NEW_LINE>parameters.add("truststorePath", "src/org/restlet/example/book/restlet/ch05/clientTrust.jks");<NEW_LINE>parameters.add("truststorePassword", "password");<NEW_LINE>parameters.add("truststoreType", "JKS");<NEW_LINE>// Create and configure client resource<NEW_LINE>ClientResource clientResource = new ClientResource("https://localhost:8183/accounts/chunkylover53/mails/123");<NEW_LINE>clientResource.setNext(client);<NEW_LINE>MailResource mailClient = clientResource.wrap(MailResource.class);<NEW_LINE>try {<NEW_LINE>// Obtain the authentication options via the challenge requests<NEW_LINE>mailClient.retrieve();<NEW_LINE>} catch (ResourceException re) {<NEW_LINE>if (Status.CLIENT_ERROR_UNAUTHORIZED.equals(re.getStatus())) {<NEW_LINE>// Retrieve the HTTP Digest hints from the server<NEW_LINE>ChallengeRequest digestChallenge = null;<NEW_LINE>for (ChallengeRequest challengeRequest : clientResource.getChallengeRequests()) {<NEW_LINE>if (ChallengeScheme.HTTP_DIGEST.equals(challengeRequest.getScheme())) {<NEW_LINE>digestChallenge = challengeRequest;<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// Configure the authentication credentials<NEW_LINE>ChallengeResponse authentication = new ChallengeResponse(digestChallenge, clientResource.getResponse(), "chunkylover53", "pwd");<NEW_LINE>clientResource.setChallengeResponse(authentication);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// Communicate with remote resource<NEW_LINE>mailClient.<MASK><NEW_LINE>// Store HTTPS client<NEW_LINE>client.stop();<NEW_LINE>} | store(mailClient.retrieve()); |
1,845,302 | public static void main(String[] args) {<NEW_LINE>EdgeWeightedDigraph edgeWeightedDigraph = new EdgeWeightedDigraph(8);<NEW_LINE>edgeWeightedDigraph.addEdge(new DirectedEdge(4, 5, 0.35));<NEW_LINE>edgeWeightedDigraph.addEdge(new DirectedEdge(5, 4, 0.35));<NEW_LINE>edgeWeightedDigraph.addEdge(new DirectedEdge(4, 7, 0.37));<NEW_LINE>edgeWeightedDigraph.addEdge(new DirectedEdge(5, 7, 0.28));<NEW_LINE>edgeWeightedDigraph.addEdge(new DirectedEdge<MASK><NEW_LINE>edgeWeightedDigraph.addEdge(new DirectedEdge(5, 1, 0.32));<NEW_LINE>edgeWeightedDigraph.addEdge(new DirectedEdge(0, 4, 0.38));<NEW_LINE>edgeWeightedDigraph.addEdge(new DirectedEdge(0, 2, 0.26));<NEW_LINE>edgeWeightedDigraph.addEdge(new DirectedEdge(7, 3, 0.39));<NEW_LINE>edgeWeightedDigraph.addEdge(new DirectedEdge(1, 3, 0.29));<NEW_LINE>edgeWeightedDigraph.addEdge(new DirectedEdge(2, 7, 0.34));<NEW_LINE>edgeWeightedDigraph.addEdge(new DirectedEdge(6, 2, 0.40));<NEW_LINE>edgeWeightedDigraph.addEdge(new DirectedEdge(3, 6, 0.52));<NEW_LINE>edgeWeightedDigraph.addEdge(new DirectedEdge(6, 0, 0.58));<NEW_LINE>edgeWeightedDigraph.addEdge(new DirectedEdge(6, 4, 0.93));<NEW_LINE>HashSet<Integer> sources = new HashSet<>();<NEW_LINE>sources.add(0);<NEW_LINE>sources.add(1);<NEW_LINE>sources.add(7);<NEW_LINE>DijkstraMultisourceSP dijkstraMultisourceSP = new Exercise24_MultisourceShortestPaths().new DijkstraMultisourceSP(edgeWeightedDigraph, sources);<NEW_LINE>StdOut.println("Distance to 5: " + dijkstraMultisourceSP.distTo(5) + " Expected: 0.28");<NEW_LINE>StdOut.println("Has path to 5: " + dijkstraMultisourceSP.hasPathTo(5) + " Expected: true");<NEW_LINE>StdOut.print("Path to 5: ");<NEW_LINE>for (DirectedEdge edge : dijkstraMultisourceSP.pathTo(5)) {<NEW_LINE>StdOut.print(edge.from() + "->" + edge.to() + " ");<NEW_LINE>}<NEW_LINE>StdOut.println("\nExpected: 8->7 7->5");<NEW_LINE>StdOut.println("\nDistance to 6: " + dijkstraMultisourceSP.distTo(6) + " Expected: 0.81");<NEW_LINE>StdOut.println("Has path to 6: " + dijkstraMultisourceSP.hasPathTo(6) + " Expected: true");<NEW_LINE>StdOut.print("Path to 6: ");<NEW_LINE>for (DirectedEdge edge : dijkstraMultisourceSP.pathTo(6)) {<NEW_LINE>StdOut.print(edge.from() + "->" + edge.to() + " ");<NEW_LINE>}<NEW_LINE>StdOut.println("\nExpected: 8->1 1->3 3->6");<NEW_LINE>} | (7, 5, 0.28)); |
552,964 | protected Long handleInternally(DataObject content) {<NEW_LINE>final long guildId = content.getLong("guild_id");<NEW_LINE>if (getJDA().getGuildSetupController().isLocked(guildId))<NEW_LINE>return guildId;<NEW_LINE>GuildImpl guild = (GuildImpl) getJDA().getGuildById(guildId);<NEW_LINE>if (guild == null) {<NEW_LINE>getJDA().getEventCache().cache(EventCache.Type.GUILD, guildId, responseNumber, allContent, this::handle);<NEW_LINE>EventCache.LOG.debug("GUILD_ROLE_DELETE was received for a Guild that is not yet cached: {}", content);<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>final long roleId = content.getLong("role_id");<NEW_LINE>Role removedRole = guild.getRolesView().remove(roleId);<NEW_LINE>if (removedRole == null) {<NEW_LINE>// getJDA().getEventCache().cache(EventCache.Type.ROLE, roleId, () -> handle(responseNumber, allContent));<NEW_LINE>WebSocketClient.LOG.debug("GUILD_ROLE_DELETE was received for a Role that is not yet cached: {}", content);<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>// Now that the role is removed from the Guild, remove it from all users and emotes.<NEW_LINE>guild.getMembersView().forEach(m -> {<NEW_LINE>MemberImpl member = (MemberImpl) m;<NEW_LINE>member.getRoleSet().remove(removedRole);<NEW_LINE>});<NEW_LINE>for (Emote emote : guild.getEmoteCache()) {<NEW_LINE>EmoteImpl impl = (EmoteImpl) emote;<NEW_LINE>if (impl.canProvideRoles())<NEW_LINE>impl.getRoleSet().remove(removedRole);<NEW_LINE>}<NEW_LINE>getJDA().handleEvent(new RoleDeleteEvent(getJDA<MASK><NEW_LINE>getJDA().getEventCache().clear(EventCache.Type.ROLE, roleId);<NEW_LINE>return null;<NEW_LINE>} | (), responseNumber, removedRole)); |
609,073 | private ProposalPackage.Proposal createFabricProposal(String channelID, Chaincode.ChaincodeID chaincodeID, boolean isInit) {<NEW_LINE>if (null == transientMap) {<NEW_LINE>transientMap = Collections.emptyMap();<NEW_LINE>}<NEW_LINE>if (IS_DEBUG_LEVEL) {<NEW_LINE>for (Map.Entry<String, byte[]> tme : transientMap.entrySet()) {<NEW_LINE>logger.debug(format("transientMap('%s', '%s'))", logString(tme.getKey()), logString(new String(tme.getValue(), UTF_8))));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>ProposalPackage.ChaincodeHeaderExtension chaincodeHeaderExtension = ProposalPackage.ChaincodeHeaderExtension.newBuilder().setChaincodeId(chaincodeID).build();<NEW_LINE>Common.ChannelHeader chainHeader = createChannelHeader(Common.HeaderType.ENDORSER_TRANSACTION, context.getTxID(), channelID, context.getEpoch(), context.<MASK><NEW_LINE>Chaincode.ChaincodeInvocationSpec chaincodeInvocationSpec = createChaincodeInvocationSpec(chaincodeID, ccType, isInit);<NEW_LINE>// Convert to bytestring map.<NEW_LINE>Map<String, ByteString> bsm = Collections.emptyMap();<NEW_LINE>if (transientMap != null) {<NEW_LINE>bsm = new HashMap<>(transientMap.size());<NEW_LINE>for (Map.Entry<String, byte[]> tme : transientMap.entrySet()) {<NEW_LINE>bsm.put(tme.getKey(), ByteString.copyFrom(tme.getValue()));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>ProposalPackage.ChaincodeProposalPayload payload = ProposalPackage.ChaincodeProposalPayload.newBuilder().setInput(chaincodeInvocationSpec.toByteString()).putAllTransientMap(bsm).build();<NEW_LINE>Common.Header header = Common.Header.newBuilder().setSignatureHeader(getSignatureHeaderAsByteString(context)).setChannelHeader(chainHeader.toByteString()).build();<NEW_LINE>return ProposalPackage.Proposal.newBuilder().setHeader(header.toByteString()).setPayload(payload.toByteString()).build();<NEW_LINE>} | getFabricTimestamp(), chaincodeHeaderExtension, null); |
17,439 | public ListGameServerGroupsResult unmarshall(JsonUnmarshallerContext context) throws Exception {<NEW_LINE>ListGameServerGroupsResult listGameServerGroupsResult = new ListGameServerGroupsResult();<NEW_LINE><MASK><NEW_LINE>String currentParentElement = context.getCurrentParentElement();<NEW_LINE>int targetDepth = originalDepth + 1;<NEW_LINE>JsonToken token = context.getCurrentToken();<NEW_LINE>if (token == null)<NEW_LINE>token = context.nextToken();<NEW_LINE>if (token == VALUE_NULL) {<NEW_LINE>return listGameServerGroupsResult;<NEW_LINE>}<NEW_LINE>while (true) {<NEW_LINE>if (token == null)<NEW_LINE>break;<NEW_LINE>if (token == FIELD_NAME || token == START_OBJECT) {<NEW_LINE>if (context.testExpression("GameServerGroups", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>listGameServerGroupsResult.setGameServerGroups(new ListUnmarshaller<GameServerGroup>(GameServerGroupJsonUnmarshaller.getInstance()).unmarshall(context));<NEW_LINE>}<NEW_LINE>if (context.testExpression("NextToken", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>listGameServerGroupsResult.setNextToken(context.getUnmarshaller(String.class).unmarshall(context));<NEW_LINE>}<NEW_LINE>} else if (token == END_ARRAY || token == END_OBJECT) {<NEW_LINE>if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {<NEW_LINE>if (context.getCurrentDepth() <= originalDepth)<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>token = context.nextToken();<NEW_LINE>}<NEW_LINE>return listGameServerGroupsResult;<NEW_LINE>} | int originalDepth = context.getCurrentDepth(); |
680,197 | public ProcessStatus handleRestValidateCode(final PwmRequest pwmRequest) throws PwmUnrecoverableException, IOException, ServletException, ChaiUnavailableException {<NEW_LINE>final PwmDomain pwmDomain = pwmRequest.getPwmDomain();<NEW_LINE>final PwmSession pwmSession = pwmRequest.getPwmSession();<NEW_LINE>final OTPUserRecord otpUserRecord = pwmSession.getUserInfo().getOtpUserRecord();<NEW_LINE>final OtpService otpService = pwmDomain.getOtpService();<NEW_LINE>final String bodyString = pwmRequest.readRequestBodyAsString();<NEW_LINE>final Map<String, String> clientValues = JsonFactory.<MASK><NEW_LINE>final String code = Validator.sanitizeInputValue(pwmRequest.getAppConfig(), clientValues.get("code"), 1024);<NEW_LINE>try {<NEW_LINE>final boolean passed = otpService.validateToken(pwmRequest.getLabel(), pwmSession.getUserInfo().getUserIdentity(), otpUserRecord, code, false);<NEW_LINE>final RestResultBean restResultBean = RestResultBean.withData(passed, Boolean.class);<NEW_LINE>LOGGER.trace(pwmRequest, () -> "returning result for restValidateCode: " + JsonFactory.get().serialize(restResultBean));<NEW_LINE>pwmRequest.outputJsonResult(restResultBean);<NEW_LINE>} catch (final PwmOperationalException e) {<NEW_LINE>final String errorMsg = "error during otp code validation: " + e.getMessage();<NEW_LINE>LOGGER.error(pwmRequest, () -> errorMsg);<NEW_LINE>pwmRequest.outputJsonResult(RestResultBean.fromError(new ErrorInformation(PwmError.ERROR_INTERNAL, errorMsg), pwmRequest));<NEW_LINE>}<NEW_LINE>return ProcessStatus.Continue;<NEW_LINE>} | get().deserializeStringMap(bodyString); |
1,319,849 | public final void zoom(int centerX, int centerY, double factor) {<NEW_LINE>// Cache current fitting<NEW_LINE>boolean fitsWidth = fitsWidth();<NEW_LINE>boolean fitsHeight = fitsHeight();<NEW_LINE>// Both fits, no zoom<NEW_LINE>if (fitsWidth && fitsHeight)<NEW_LINE>return;<NEW_LINE>// Resolve current scale<NEW_LINE>double scaleX = getScaleX();<NEW_LINE>double scaleY = getScaleY();<NEW_LINE>// Bad scale, no zoom<NEW_LINE>if (scaleX * scaleY == 0)<NEW_LINE>return;<NEW_LINE>// Compute new scale<NEW_LINE>double newScaleX = zoomMode == ZOOM_Y || fitsWidth ? scaleX : scaleX * factor;<NEW_LINE>double newScaleY = zoomMode == ZOOM_X || fitsHeight ? scaleY : scaleY * factor;<NEW_LINE>// Cache data at zoom center<NEW_LINE>double dataX = getDataX(centerX);<NEW_LINE>double dataY = getDataY(centerY);<NEW_LINE>// Set new scale<NEW_LINE>setScale(newScaleX, newScaleY);<NEW_LINE>// Cache current offset<NEW_LINE>long offsetX = getOffsetX();<NEW_LINE>long offsetY = getOffsetY();<NEW_LINE>// Update x-offset to centerX if needed<NEW_LINE>if (!fitsWidth && zoomMode != ZOOM_Y) {<NEW_LINE><MASK><NEW_LINE>long viewWidth = (long) Math.ceil(getViewWidth(dataWidth));<NEW_LINE>offsetX = isRightBased() ? viewWidth - getWidth() + centerX : viewWidth - centerX;<NEW_LINE>}<NEW_LINE>// Update y-offset to centerY if needed<NEW_LINE>if (!fitsHeight && zoomMode != ZOOM_X) {<NEW_LINE>double dataHeight = dataY - getDataOffsetY();<NEW_LINE>long viewHeight = (long) Math.ceil(getViewHeight(dataHeight));<NEW_LINE>offsetY = isBottomBased() ? viewHeight - getHeight() + centerY : viewHeight - centerY;<NEW_LINE>}<NEW_LINE>// Set new offset<NEW_LINE>setOffset(offsetX, offsetY);<NEW_LINE>} | double dataWidth = dataX - getDataOffsetX(); |
1,585,775 | public String dump(LayoutContext c, String indent, int which) {<NEW_LINE>if (which != Box.DUMP_RENDER) {<NEW_LINE>throw new IllegalArgumentException();<NEW_LINE>}<NEW_LINE>StringBuilder result = new StringBuilder(indent);<NEW_LINE>result.append(this);<NEW_LINE>result.append('\n');<NEW_LINE>for (Iterator<Object> i = getInlineChildren().iterator(); i.hasNext(); ) {<NEW_LINE>Object obj = i.next();<NEW_LINE>if (obj instanceof Box) {<NEW_LINE>Box b = (Box) obj;<NEW_LINE>result.append(b.dump(c, indent + " ", which));<NEW_LINE>if (result.charAt(result.length() - 1) == '\n') {<NEW_LINE>result.deleteCharAt(result.length() - 1);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE><MASK><NEW_LINE>result.append(obj.toString());<NEW_LINE>}<NEW_LINE>if (i.hasNext()) {<NEW_LINE>result.append('\n');<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return result.toString();<NEW_LINE>} | result.append(indent + " "); |
1,547,153 | final DBInstance executeStopDBInstance(StopDBInstanceRequest stopDBInstanceRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(stopDBInstanceRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<StopDBInstanceRequest> request = null;<NEW_LINE>Response<DBInstance> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new StopDBInstanceRequestMarshaller().marshall(super.beforeMarshalling(stopDBInstanceRequest));<NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);<NEW_LINE>request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "RDS");<NEW_LINE>request.<MASK><NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>StaxResponseHandler<DBInstance> responseHandler = new StaxResponseHandler<DBInstance>(new DBInstanceStaxUnmarshaller());<NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | addHandlerContext(HandlerContextKey.OPERATION_NAME, "StopDBInstance"); |
1,634,096 | public void start() {<NEW_LINE>logger.info("RPC WebSocket enabled");<NEW_LINE>ServerBootstrap b = new ServerBootstrap();<NEW_LINE>b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>protected void initChannel(SocketChannel ch) throws Exception {<NEW_LINE><MASK><NEW_LINE>p.addLast(new HttpServerCodec());<NEW_LINE>p.addLast(new HttpObjectAggregator(maxAggregatedFrameSize));<NEW_LINE>p.addLast(new WriteTimeoutHandler(serverWriteTimeoutSeconds, TimeUnit.SECONDS));<NEW_LINE>p.addLast(new RskWebSocketServerProtocolHandler("/websocket", maxFrameSize));<NEW_LINE>p.addLast(new WebSocketFrameAggregator(maxAggregatedFrameSize));<NEW_LINE>p.addLast(webSocketJsonRpcHandler);<NEW_LINE>p.addLast(web3ServerHandler);<NEW_LINE>p.addLast(new Web3ResultWebSocketResponseHandler());<NEW_LINE>}<NEW_LINE>});<NEW_LINE>webSocketChannel = b.bind(host, port);<NEW_LINE>try {<NEW_LINE>webSocketChannel.sync();<NEW_LINE>} catch (InterruptedException e) {<NEW_LINE>logger.error("The RPC WebSocket server couldn't be started", e);<NEW_LINE>Thread.currentThread().interrupt();<NEW_LINE>}<NEW_LINE>} | ChannelPipeline p = ch.pipeline(); |
1,827,830 | private DataStreamSink<?> consume(DataStream<RowData> dataStream, boolean isBounded, DataStructureConverter converter) {<NEW_LINE>checkAcidTable(catalogTable, identifier.toObjectPath());<NEW_LINE>try (HiveMetastoreClientWrapper client = HiveMetastoreClientFactory.create(HiveConfUtils.create(jobConf), hiveVersion)) {<NEW_LINE>Table table = client.getTable(identifier.getDatabaseName(), identifier.getObjectName());<NEW_LINE>StorageDescriptor sd = table.getSd();<NEW_LINE>Class hiveOutputFormatClz = hiveShim.getHiveOutputFormatClass(Class.forName(sd.getOutputFormat()));<NEW_LINE>boolean isCompressed = jobConf.getBoolean(HiveConf.ConfVars.COMPRESSRESULT.varname, false);<NEW_LINE>HiveWriterFactory writerFactory = new HiveWriterFactory(jobConf, hiveOutputFormatClz, sd.getSerdeInfo(), tableSchema, getPartitionKeyArray(), HiveReflectionUtils.getTableMetadata(hiveShim, table), hiveShim, isCompressed);<NEW_LINE>String extension = Utilities.getFileExtension(jobConf, isCompressed, (HiveOutputFormat<?, ?>) hiveOutputFormatClz.newInstance());<NEW_LINE>OutputFileConfig.OutputFileConfigBuilder fileNamingBuilder = OutputFileConfig.builder().withPartPrefix("part-" + UUID.randomUUID().toString()).withPartSuffix(extension == null ? "" : extension);<NEW_LINE>final int parallelism = Optional.ofNullable(configuredParallelism).orElse(dataStream.getParallelism());<NEW_LINE>if (isBounded) {<NEW_LINE>OutputFileConfig fileNaming = fileNamingBuilder.build();<NEW_LINE>return createBatchSink(dataStream, converter, sd, writerFactory, fileNaming, parallelism);<NEW_LINE>} else {<NEW_LINE>if (overwrite) {<NEW_LINE>throw new IllegalStateException("Streaming mode not support overwrite.");<NEW_LINE>}<NEW_LINE>Properties tableProps = <MASK><NEW_LINE>return createStreamSink(dataStream, sd, tableProps, writerFactory, fileNamingBuilder, parallelism);<NEW_LINE>}<NEW_LINE>} catch (TException e) {<NEW_LINE>throw new CatalogException("Failed to query Hive metaStore", e);<NEW_LINE>} catch (IOException e) {<NEW_LINE>throw new FlinkRuntimeException("Failed to create staging dir", e);<NEW_LINE>} catch (ClassNotFoundException e) {<NEW_LINE>throw new FlinkHiveException("Failed to get output format class", e);<NEW_LINE>} catch (IllegalAccessException | InstantiationException e) {<NEW_LINE>throw new FlinkHiveException("Failed to instantiate output format instance", e);<NEW_LINE>}<NEW_LINE>} | HiveReflectionUtils.getTableMetadata(hiveShim, table); |
1,295,756 | final UntagResourceResult executeUntagResource(UntagResourceRequest untagResourceRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(untagResourceRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE><MASK><NEW_LINE>Request<UntagResourceRequest> request = null;<NEW_LINE>Response<UntagResourceResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new UntagResourceRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(untagResourceRequest));<NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);<NEW_LINE>request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Cognito Identity");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "UntagResource");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<UntagResourceResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new UntagResourceResultJsonUnmarshaller());<NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | awsRequestMetrics.startEvent(Field.ClientExecuteTime); |
1,007,932 | // Converts an FpML 'StubValue' to a {@code IborRateStubCalculation}.<NEW_LINE>private IborRateStubCalculation parseStubCalculation(XmlElement baseEl, FpmlDocument document) {<NEW_LINE>Optional<XmlElement> rateOptEl = baseEl.findChild("stubRate");<NEW_LINE>if (rateOptEl.isPresent()) {<NEW_LINE>return IborRateStubCalculation.ofFixedRate(document.parseDecimal(rateOptEl.get()));<NEW_LINE>}<NEW_LINE>Optional<XmlElement> amountOptEl = baseEl.findChild("stubAmount");<NEW_LINE>if (amountOptEl.isPresent()) {<NEW_LINE>return IborRateStubCalculation.ofKnownAmount(document.parseCurrencyAmount(amountOptEl.get()));<NEW_LINE>}<NEW_LINE>List<XmlElement> indicesEls = baseEl.getChildren("floatingRate");<NEW_LINE>if (indicesEls.size() == 1) {<NEW_LINE>XmlElement indexEl = indicesEls.get(0);<NEW_LINE>document.validateNotPresent(indexEl, "floatingRateMultiplierSchedule");<NEW_LINE>document.validateNotPresent(indexEl, "spreadSchedule");<NEW_LINE>document.validateNotPresent(indexEl, "rateTreatment");<NEW_LINE>document.validateNotPresent(indexEl, "capRateSchedule");<NEW_LINE>document.validateNotPresent(indexEl, "floorRateSchedule");<NEW_LINE>return IborRateStubCalculation.ofIborRate((IborIndex) document.parseIndex(indexEl));<NEW_LINE>} else if (indicesEls.size() == 2) {<NEW_LINE>XmlElement index1El = indicesEls.get(0);<NEW_LINE>document.validateNotPresent(index1El, "floatingRateMultiplierSchedule");<NEW_LINE>document.validateNotPresent(index1El, "spreadSchedule");<NEW_LINE>document.validateNotPresent(index1El, "rateTreatment");<NEW_LINE>document.validateNotPresent(index1El, "capRateSchedule");<NEW_LINE>document.validateNotPresent(index1El, "floorRateSchedule");<NEW_LINE>XmlElement index2El = indicesEls.get(1);<NEW_LINE>document.validateNotPresent(index2El, "floatingRateMultiplierSchedule");<NEW_LINE><MASK><NEW_LINE>document.validateNotPresent(index2El, "rateTreatment");<NEW_LINE>document.validateNotPresent(index2El, "capRateSchedule");<NEW_LINE>document.validateNotPresent(index2El, "floorRateSchedule");<NEW_LINE>return IborRateStubCalculation.ofIborInterpolatedRate((IborIndex) document.parseIndex(index1El), (IborIndex) document.parseIndex(index2El));<NEW_LINE>}<NEW_LINE>throw new FpmlParseException("Unknown stub structure: " + baseEl);<NEW_LINE>} | document.validateNotPresent(index2El, "spreadSchedule"); |
438,413 | private void addPressed() {<NEW_LINE>Container container = getTopLevelAncestor();<NEW_LINE>try {<NEW_LINE>DPolicyQualifierInfoChooser dPolicyQualifierInfoChooser = null;<NEW_LINE>if (container instanceof JDialog) {<NEW_LINE>dPolicyQualifierInfoChooser = new DPolicyQualifierInfoChooser((JDialog) container, title, null);<NEW_LINE>} else {<NEW_LINE>dPolicyQualifierInfoChooser = new DPolicyQualifierInfoChooser((<MASK><NEW_LINE>}<NEW_LINE>dPolicyQualifierInfoChooser.setLocationRelativeTo(container);<NEW_LINE>dPolicyQualifierInfoChooser.setVisible(true);<NEW_LINE>PolicyQualifierInfo newPolicyQualifierInfo = dPolicyQualifierInfoChooser.getPolicyQualifierInfo();<NEW_LINE>if (newPolicyQualifierInfo == null) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>policyQualifierInfo.add(newPolicyQualifierInfo);<NEW_LINE>populate();<NEW_LINE>selectPolicyQualifierInfoInTable(newPolicyQualifierInfo);<NEW_LINE>} catch (IOException ex) {<NEW_LINE>DError dError = null;<NEW_LINE>if (container instanceof JDialog) {<NEW_LINE>dError = new DError((JDialog) container, ex);<NEW_LINE>} else {<NEW_LINE>dError = new DError((JFrame) container, ex);<NEW_LINE>}<NEW_LINE>dError.setLocationRelativeTo(container);<NEW_LINE>dError.setVisible(true);<NEW_LINE>}<NEW_LINE>} | JFrame) container, title, null); |
1,747,622 | private void generateGroups(final StringBuilder sb, final List<Token> tokens, final String prefix) {<NEW_LINE>for (int i = 0, size = tokens.size(); i < size; i++) {<NEW_LINE>final Token groupToken = tokens.get(i);<NEW_LINE>if (groupToken.signal() != Signal.BEGIN_GROUP) {<NEW_LINE>throw new IllegalStateException("tokens must begin with BEGIN_GROUP: token=" + groupToken);<NEW_LINE>}<NEW_LINE>// Make a unique Group name by adding our parent<NEW_LINE>final String groupName = prefix + formatTypeName(groupToken.name());<NEW_LINE>++i;<NEW_LINE>final int groupHeaderTokenCount = tokens.get(i).componentTokenCount();<NEW_LINE>i += groupHeaderTokenCount;<NEW_LINE>final List<Token> fields = new ArrayList<>();<NEW_LINE>i = collectFields(tokens, i, fields);<NEW_LINE>generateFields(sb, groupName, fields);<NEW_LINE>final List<Token> groups = new ArrayList<>();<NEW_LINE>i = collectGroups(tokens, i, groups);<NEW_LINE>generateGroups(sb, groups, groupName);<NEW_LINE>final List<Token> <MASK><NEW_LINE>i = collectVarData(tokens, i, varData);<NEW_LINE>generateVarData(sb, formatTypeName(groupName), varData);<NEW_LINE>}<NEW_LINE>} | varData = new ArrayList<>(); |
612,973 | @ApiOperation(value = "Delete an extractor")<NEW_LINE>@Path("/{extractorId}")<NEW_LINE>@ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid request."), @ApiResponse(code = 404, message = "Input not found."), @ApiResponse(code = 404, message = "Extractor not found.") })<NEW_LINE>@Produces(MediaType.APPLICATION_JSON)<NEW_LINE>@AuditEvent(type = AuditEventTypes.EXTRACTOR_DELETE)<NEW_LINE>public void terminate(@ApiParam(name = "inputId", required = true) @PathParam("inputId") String inputId, @ApiParam(name = "extractorId", required = true) @PathParam("extractorId") String extractorId) throws NotFoundException {<NEW_LINE><MASK><NEW_LINE>final MessageInput input = persistedInputs.get(inputId);<NEW_LINE>if (input == null) {<NEW_LINE>LOG.error("Input <{}> not found.", inputId);<NEW_LINE>throw new javax.ws.rs.NotFoundException("Couldn't find input " + inputId);<NEW_LINE>}<NEW_LINE>// Remove from Mongo.<NEW_LINE>final Input mongoInput = inputService.find(input.getPersistId());<NEW_LINE>final Extractor extractor = inputService.getExtractor(mongoInput, extractorId);<NEW_LINE>inputService.removeExtractor(mongoInput, extractor.getId());<NEW_LINE>final String msg = "Deleted extractor <" + extractorId + "> of type [" + extractor.getType() + "] " + "from input <" + inputId + ">.";<NEW_LINE>LOG.info(msg);<NEW_LINE>activityWriter.write(new Activity(msg, InputsResource.class));<NEW_LINE>} | checkPermission(RestPermissions.INPUTS_EDIT, inputId); |
493,730 | public static void validateSettings(Settings settings) {<NEW_LINE>// wan means all node restrictions are off the table<NEW_LINE>if (settings.getNodesWANOnly()) {<NEW_LINE>Assert.isTrue(!settings.getNodesDiscovery(), "Discovery cannot be enabled when running in WAN mode");<NEW_LINE>Assert.isTrue(!settings.getNodesClientOnly(), "Client-only nodes cannot be enabled when running in WAN mode");<NEW_LINE>Assert.isTrue(!settings.getNodesDataOnly(), "Data-only nodes cannot be enabled when running in WAN mode");<NEW_LINE>Assert.isTrue(!settings.getNodesIngestOnly(), "Ingest-only nodes cannot be enabled when running in WAN mode");<NEW_LINE>}<NEW_LINE>// pick between data or client or ingest only nodes<NEW_LINE>boolean alreadyRestricted = false;<NEW_LINE>boolean[] restrictions = { settings.getNodesClientOnly(), settings.getNodesDataOnly(), settings.getNodesIngestOnly() };<NEW_LINE>for (boolean restriction : restrictions) {<NEW_LINE>Assert.isTrue((alreadyRestricted && restriction) == false, "Use either client-only or data-only or ingest-only nodes but not a combination");<NEW_LINE>alreadyRestricted = alreadyRestricted || restriction;<NEW_LINE>}<NEW_LINE>// field inclusion/exclusion + input as json does not mix and the user should be informed.<NEW_LINE>if (settings.getInputAsJson()) {<NEW_LINE>Assert.isTrue(settings.getMappingIncludes().isEmpty(), "When writing data as JSON, the field inclusion feature is ignored. This is most likely not what the user intended. Bailing out...");<NEW_LINE>Assert.isTrue(settings.getMappingExcludes().isEmpty(), "When writing data as JSON, the field exclusion feature is ignored. This is most likely not what the user intended. Bailing out...");<NEW_LINE>}<NEW_LINE>// check the configuration is coherent in order to use the delete operation<NEW_LINE>if (ConfigurationOptions.ES_OPERATION_DELETE.equals(settings.getOperation())) {<NEW_LINE>Assert.isTrue(!<MASK><NEW_LINE>Assert.isTrue(settings.getMappingIncludes().isEmpty(), "When using delete operation, the field inclusion feature is ignored. This is most likely not what the user intended. Bailing out...");<NEW_LINE>Assert.isTrue(settings.getMappingExcludes().isEmpty(), "When using delete operation, the field exclusion feature is ignored. This is most likely not what the user intended. Bailing out...");<NEW_LINE>Assert.isTrue(settings.getMappingId() != null && !StringUtils.EMPTY.equals(settings.getMappingId()), "When using delete operation, the property " + ConfigurationOptions.ES_MAPPING_ID + " must be set and must not be empty since we need the document id in order to delete it. Bailing out...");<NEW_LINE>}<NEW_LINE>// Check to make sure user doesn't specify more than one script type<NEW_LINE>boolean hasScript = false;<NEW_LINE>String[] scripts = { settings.getUpdateScriptInline(), settings.getUpdateScriptFile(), settings.getUpdateScriptStored() };<NEW_LINE>for (String script : scripts) {<NEW_LINE>boolean isSet = StringUtils.hasText(script);<NEW_LINE>Assert.isTrue((hasScript && isSet) == false, "Multiple scripts are specified. Please specify only one via [es.update.script.inline], [es.update.script.file], or [es.update.script.stored]");<NEW_LINE>hasScript = hasScript || isSet;<NEW_LINE>}<NEW_LINE>// Early attempt to catch the internal field filtering clashing with user specified field filtering<NEW_LINE>// ignore return, just checking for the throw.<NEW_LINE>SettingsUtils.determineSourceFields(settings);<NEW_LINE>} | settings.getInputAsJson(), "When using delete operation, providing data as JSON is not coherent because this operation does not need document as a payload. This is most likely not what the user intended. Bailing out..."); |
464,786 | private void generateCircleTemplate_() {<NEW_LINE>if (!m_circle_template.isEmpty()) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>int N = m_circle_template_size;<NEW_LINE>assert (N >= 4);<NEW_LINE>int real_size <MASK><NEW_LINE>double dA = (Math.PI * 0.5) / real_size;<NEW_LINE>m_dA = dA;<NEW_LINE>for (int i = 0; i < real_size * 4; i++) m_circle_template.add(null);<NEW_LINE>double dcos = Math.cos(dA);<NEW_LINE>double dsin = Math.sin(dA);<NEW_LINE>Point2D pt = new Point2D(0.0, 1.0);<NEW_LINE>for (int i = 0; i < real_size; i++) {<NEW_LINE>m_circle_template.set(i + real_size * 0, new Point2D(pt.y, -pt.x));<NEW_LINE>m_circle_template.set(i + real_size * 1, new Point2D(-pt.x, -pt.y));<NEW_LINE>m_circle_template.set(i + real_size * 2, new Point2D(-pt.y, pt.x));<NEW_LINE>m_circle_template.set(i + real_size * 3, pt);<NEW_LINE>pt = new Point2D(pt.x, pt.y);<NEW_LINE>pt.rotateReverse(dcos, dsin);<NEW_LINE>}<NEW_LINE>// the template is filled with the index 0 corresponding to the point<NEW_LINE>// (0, 0), following clockwise direction (0, -1), (-1, 0), (1, 0)<NEW_LINE>} | = (N + 3) / 4; |
1,266,406 | public void process(Heartbeat heartbeat, EventEmitter<Response> emitter) throws Exception {<NEW_LINE>RequestHeader header = heartbeat.getHeader();<NEW_LINE>if (!ServiceUtils.validateHeader(header)) {<NEW_LINE>ServiceUtils.sendRespAndDone(StatusCode.EVENTMESH_PROTOCOL_HEADER_ERR, emitter);<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>if (!ServiceUtils.validateHeartBeat(heartbeat)) {<NEW_LINE>ServiceUtils.sendRespAndDone(StatusCode.EVENTMESH_PROTOCOL_BODY_ERR, emitter);<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>doAclCheck(heartbeat);<NEW_LINE>} catch (AclException e) {<NEW_LINE>aclLogger.warn("CLIENT HAS NO PERMISSION, HeartbeatProcessor failed", e);<NEW_LINE>ServiceUtils.sendRespAndDone(StatusCode.EVENTMESH_ACL_ERR, <MASK><NEW_LINE>return;<NEW_LINE>}<NEW_LINE>// only handle heartbeat for consumers<NEW_LINE>ClientType clientType = heartbeat.getClientType();<NEW_LINE>if (!ClientType.SUB.equals(clientType)) {<NEW_LINE>ServiceUtils.sendRespAndDone(StatusCode.EVENTMESH_PROTOCOL_BODY_ERR, emitter);<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>ConsumerManager consumerManager = eventMeshGrpcServer.getConsumerManager();<NEW_LINE>String consumerGroup = heartbeat.getConsumerGroup();<NEW_LINE>// update clients' timestamp in the heartbeat items<NEW_LINE>for (Heartbeat.HeartbeatItem item : heartbeat.getHeartbeatItemsList()) {<NEW_LINE>ConsumerGroupClient hbClient = ConsumerGroupClient.builder().env(header.getEnv()).idc(header.getIdc()).sys(header.getSys()).ip(header.getIp()).pid(header.getPid()).consumerGroup(consumerGroup).topic(item.getTopic()).lastUpTime(new Date()).build();<NEW_LINE>consumerManager.updateClientTime(hbClient);<NEW_LINE>}<NEW_LINE>ServiceUtils.sendRespAndDone(StatusCode.SUCCESS, "heartbeat success", emitter);<NEW_LINE>} | e.getMessage(), emitter); |
1,789,633 | public static EPCompiled read(File file) throws IOException {<NEW_LINE>JarFile jarFile = new JarFile(file);<NEW_LINE>Attributes attributes = jarFile.getManifest().getMainAttributes();<NEW_LINE>String compilerVersion = getAttribute(attributes, MANIFEST_COMPILER_VERSION);<NEW_LINE>if (compilerVersion == null) {<NEW_LINE>throw new IOException("Manifest is missing " + MANIFEST_COMPILER_VERSION);<NEW_LINE>}<NEW_LINE>String moduleProvider = getAttribute(attributes, MANIFEST_MODULEPROVIDERCLASSNAME);<NEW_LINE>String queryProvider = getAttribute(attributes, MANIFEST_QUERYPROVIDERCLASSNAME);<NEW_LINE>if (moduleProvider == null && queryProvider == null) {<NEW_LINE>throw new IOException("Manifest is missing both " + MANIFEST_MODULEPROVIDERCLASSNAME + " and " + MANIFEST_QUERYPROVIDERCLASSNAME);<NEW_LINE>}<NEW_LINE>String targetHAStr = getAttribute(attributes, MANIFEST_TARGETHA);<NEW_LINE>boolean targetHA = targetHAStr != null && Boolean.parseBoolean(targetHAStr);<NEW_LINE>Map<String, byte[]> classes = new HashMap<>();<NEW_LINE>try {<NEW_LINE>Enumeration<JarEntry> entries = jarFile.entries();<NEW_LINE>while (entries.hasMoreElements()) {<NEW_LINE>read(jarFile, <MASK><NEW_LINE>}<NEW_LINE>} finally {<NEW_LINE>jarFile.close();<NEW_LINE>}<NEW_LINE>return new EPCompiled(classes, new EPCompiledManifest(compilerVersion, moduleProvider, queryProvider, targetHA));<NEW_LINE>} | entries.nextElement(), classes); |
206,008 | private static Map<String, ? super Object> toMap(final V8Object v8Object, final V8Map<Object> cache, final TypeAdapter adapter) {<NEW_LINE>if (v8Object == null) {<NEW_LINE>return Collections.emptyMap();<NEW_LINE>}<NEW_LINE>if (cache.containsKey(v8Object)) {<NEW_LINE>return (Map<String, ? super Object>) cache.get(v8Object);<NEW_LINE>}<NEW_LINE>Map<String, ? super Object> result = new V8PropertyMap<Object>();<NEW_LINE>cache.put(v8Object, result);<NEW_LINE>String[] keys = v8Object.getKeys();<NEW_LINE>for (String key : keys) {<NEW_LINE>Object object = null;<NEW_LINE>int type = V8Value.UNDEFINED;<NEW_LINE>try {<NEW_LINE>object = v8Object.get(key);<NEW_LINE>type = v8Object.getType(key);<NEW_LINE>Object value = getValue(<MASK><NEW_LINE>if (value != IGNORE) {<NEW_LINE>result.put(key, value);<NEW_LINE>}<NEW_LINE>} finally {<NEW_LINE>if (object instanceof Releasable) {<NEW_LINE>((Releasable) object).release();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return result;<NEW_LINE>} | object, type, cache, adapter); |
1,697,075 | public io.kubernetes.client.proto.V1alpha1Admission.AdmissionReview buildPartial() {<NEW_LINE>io.kubernetes.client.proto.V1alpha1Admission.AdmissionReview result = new io.kubernetes.client.proto.V1alpha1Admission.AdmissionReview(this);<NEW_LINE>int from_bitField0_ = bitField0_;<NEW_LINE>int to_bitField0_ = 0;<NEW_LINE>if (((from_bitField0_ & 0x00000001) == 0x00000001)) {<NEW_LINE>to_bitField0_ |= 0x00000001;<NEW_LINE>}<NEW_LINE>if (specBuilder_ == null) {<NEW_LINE>result.spec_ = spec_;<NEW_LINE>} else {<NEW_LINE>result.spec_ = specBuilder_.build();<NEW_LINE>}<NEW_LINE>if (((from_bitField0_ & 0x00000002) == 0x00000002)) {<NEW_LINE>to_bitField0_ |= 0x00000002;<NEW_LINE>}<NEW_LINE>if (statusBuilder_ == null) {<NEW_LINE>result.status_ = status_;<NEW_LINE>} else {<NEW_LINE>result<MASK><NEW_LINE>}<NEW_LINE>result.bitField0_ = to_bitField0_;<NEW_LINE>onBuilt();<NEW_LINE>return result;<NEW_LINE>} | .status_ = statusBuilder_.build(); |
972,283 | private void activatePanelElements(TournamentTypeView tournamentType) {<NEW_LINE>this.pnlDraftOptions.setVisible(tournamentType.isDraft());<NEW_LINE>this.lblNumRounds.setVisible<MASK><NEW_LINE>this.spnNumRounds.setVisible(!tournamentType.isElimination());<NEW_LINE>this.lblConstructionTime.setVisible(tournamentType.isLimited());<NEW_LINE>this.spnConstructTime.setVisible(tournamentType.isLimited());<NEW_LINE>this.lbDeckType.setVisible(!tournamentType.isLimited());<NEW_LINE>this.cbDeckType.setVisible(!tournamentType.isLimited());<NEW_LINE>this.lblGameType.setVisible(!tournamentType.isLimited());<NEW_LINE>this.cbGameType.setVisible(!tournamentType.isLimited());<NEW_LINE>this.player1Panel.showDeckElements(!tournamentType.isLimited());<NEW_LINE>if (tournamentType.isLimited()) {<NEW_LINE>if (tournamentType.isCubeBooster()) {<NEW_LINE>this.lblDraftCube.setVisible(true);<NEW_LINE>this.cbDraftCube.setVisible(true);<NEW_LINE>this.lblPacks.setVisible(false);<NEW_LINE>this.pnlPacks.setVisible(false);<NEW_LINE>this.pnlRandomPacks.setVisible(false);<NEW_LINE>} else if (tournamentType.isRandom() || tournamentType.isRichMan()) {<NEW_LINE>this.lblDraftCube.setVisible(false);<NEW_LINE>this.cbDraftCube.setVisible(false);<NEW_LINE>this.lblPacks.setVisible(true);<NEW_LINE>this.pnlRandomPacks.setVisible(true);<NEW_LINE>this.pnlPacks.setVisible(false);<NEW_LINE>} else {<NEW_LINE>this.lblDraftCube.setVisible(false);<NEW_LINE>this.cbDraftCube.setVisible(false);<NEW_LINE>this.lblPacks.setVisible(true);<NEW_LINE>this.pnlPacks.setVisible(true);<NEW_LINE>this.pnlRandomPacks.setVisible(false);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>// construced<NEW_LINE>this.lblDraftCube.setVisible(false);<NEW_LINE>this.cbDraftCube.setVisible(false);<NEW_LINE>this.pnlPacks.setVisible(false);<NEW_LINE>this.pnlPacks.setVisible(false);<NEW_LINE>this.pnlRandomPacks.setVisible(false);<NEW_LINE>}<NEW_LINE>} | (!tournamentType.isElimination()); |
258,553 | public DisableEnhancedMonitoringResult unmarshall(JsonUnmarshallerContext context) throws Exception {<NEW_LINE>DisableEnhancedMonitoringResult disableEnhancedMonitoringResult = new DisableEnhancedMonitoringResult();<NEW_LINE><MASK><NEW_LINE>reader.beginObject();<NEW_LINE>while (reader.hasNext()) {<NEW_LINE>String name = reader.nextName();<NEW_LINE>if (name.equals("StreamName")) {<NEW_LINE>disableEnhancedMonitoringResult.setStreamName(StringJsonUnmarshaller.getInstance().unmarshall(context));<NEW_LINE>} else if (name.equals("CurrentShardLevelMetrics")) {<NEW_LINE>disableEnhancedMonitoringResult.setCurrentShardLevelMetrics(new ListUnmarshaller<String>(StringJsonUnmarshaller.getInstance()).unmarshall(context));<NEW_LINE>} else if (name.equals("DesiredShardLevelMetrics")) {<NEW_LINE>disableEnhancedMonitoringResult.setDesiredShardLevelMetrics(new ListUnmarshaller<String>(StringJsonUnmarshaller.getInstance()).unmarshall(context));<NEW_LINE>} else {<NEW_LINE>reader.skipValue();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>reader.endObject();<NEW_LINE>return disableEnhancedMonitoringResult;<NEW_LINE>} | AwsJsonReader reader = context.getReader(); |
46,829 | static Map<Address, List<Shard>> assignShards(Collection<Shard> shards, Collection<Address> addresses) {<NEW_LINE>Map<String, List<Shard>> nodeCandidates = shards.stream().collect(groupingBy(Shard::getIp));<NEW_LINE>Map<Address, List<Shard>> nodeAssigned = new HashMap<>();<NEW_LINE>if (!addresses.stream().map(Address::getHost).collect(toSet()).containsAll(nodeCandidates.keySet())) {<NEW_LINE>throw new JetException("Shard locations are not equal to Hazelcast members locations, " + "shards=" + nodeCandidates.keySet() + ", Hazelcast members=" + addresses);<NEW_LINE>}<NEW_LINE>int uniqueShards = (int) shards.stream().map(Shard::indexShard).distinct().count();<NEW_LINE>Set<String> assignedShards = new HashSet<>();<NEW_LINE><MASK><NEW_LINE>// Same as Math.ceil for float div<NEW_LINE>int iterations = (uniqueShards + candidatesSize - 1) / candidatesSize;<NEW_LINE>for (int i = 0; i < iterations; i++) {<NEW_LINE>for (Address address : addresses) {<NEW_LINE>String host = address.getHost();<NEW_LINE>List<Shard> thisNodeCandidates = nodeCandidates.getOrDefault(host, emptyList());<NEW_LINE>if (thisNodeCandidates.isEmpty()) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>Shard shard = thisNodeCandidates.remove(0);<NEW_LINE>List<Shard> nodeShards = nodeAssigned.computeIfAbsent(address, (key) -> new ArrayList<>());<NEW_LINE>nodeShards.add(shard);<NEW_LINE>nodeCandidates.values().forEach(candidates -> candidates.removeIf(next -> next.indexShard().equals(shard.indexShard())));<NEW_LINE>assignedShards.add(shard.indexShard());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (assignedShards.size() != uniqueShards) {<NEW_LINE>throw new JetException("Not all shards have been assigned");<NEW_LINE>}<NEW_LINE>return nodeAssigned;<NEW_LINE>} | int candidatesSize = nodeCandidates.size(); |
44,716 | private void fillLookupTable(Map<DSMRMeterType, Integer> mapping) {<NEW_LINE>for (OBISMsgType t : OBISMsgType.values()) {<NEW_LINE>OBISIdentifier obisId = t.obisId;<NEW_LINE>if (obisId.getGroupB() == null) {<NEW_LINE>DSMRMeterType meterType = t.meterType;<NEW_LINE>if (mapping.containsKey(meterType)) {<NEW_LINE>Integer channel = mapping.get(t.meterType);<NEW_LINE>logger.debug("Change OBIS-identifier {} for meter {} on channel {}", t.obisId, t.meterType, channel);<NEW_LINE>obisId = new OBISIdentifier(obisId.getGroupA(), channel, obisId.getGroupC(), obisId.getGroupD(), obisId.getGroupE(), obisId.getGroupF());<NEW_LINE>} else {<NEW_LINE>logger.debug("Mapping does not contain a channel for {}", meterType);<NEW_LINE>obisId = null;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (obisId != null) {<NEW_LINE>if (!obisLookupTable.containsKey(obisId)) {<NEW_LINE>obisLookupTable.put(obisId, <MASK><NEW_LINE>}<NEW_LINE>obisLookupTable.get(obisId).add(t);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | new LinkedList<OBISMsgType>()); |
1,664,535 | final ListKafkaVersionsResult executeListKafkaVersions(ListKafkaVersionsRequest listKafkaVersionsRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(listKafkaVersionsRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<ListKafkaVersionsRequest> request = null;<NEW_LINE>Response<ListKafkaVersionsResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new ListKafkaVersionsRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(listKafkaVersionsRequest));<NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);<NEW_LINE>request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Kafka");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "ListKafkaVersions");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<ListKafkaVersionsResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(<MASK><NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | false), new ListKafkaVersionsResultJsonUnmarshaller()); |
755,053 | final ListFeaturesResult executeListFeatures(ListFeaturesRequest listFeaturesRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(listFeaturesRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<ListFeaturesRequest> request = null;<NEW_LINE>Response<ListFeaturesResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new ListFeaturesRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(listFeaturesRequest));<NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);<NEW_LINE>request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Evidently");<NEW_LINE>request.<MASK><NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<ListFeaturesResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new ListFeaturesResultJsonUnmarshaller());<NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | addHandlerContext(HandlerContextKey.OPERATION_NAME, "ListFeatures"); |
1,367,339 | final TagResourceResult executeTagResource(TagResourceRequest tagResourceRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(tagResourceRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<TagResourceRequest> request = null;<NEW_LINE>Response<TagResourceResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new TagResourceRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(tagResourceRequest));<NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);<NEW_LINE>request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "WorkMail");<NEW_LINE>request.<MASK><NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<TagResourceResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new TagResourceResultJsonUnmarshaller());<NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | addHandlerContext(HandlerContextKey.OPERATION_NAME, "TagResource"); |
240,434 | public static void main(String[] args) {<NEW_LINE>Exercise31_MSTWeights mstWeights = new Exercise31_MSTWeights();<NEW_LINE>EdgeWeightedGraph edgeWeightedGraph = new EdgeWeightedGraph(5);<NEW_LINE>edgeWeightedGraph.addEdge(new Edge(0, 1, 0.42));<NEW_LINE>edgeWeightedGraph.addEdge(new Edge(0, 3, 0.5));<NEW_LINE>edgeWeightedGraph.addEdge(new Edge(1, 2, 0.12));<NEW_LINE>edgeWeightedGraph.addEdge(new Edge(1, 4, 0.91));<NEW_LINE>edgeWeightedGraph.addEdge(new Edge(2, 3, 0.72));<NEW_LINE>edgeWeightedGraph.addEdge(new Edge(3, 4, 0.8));<NEW_LINE>edgeWeightedGraph.addEdge(new Edge(3, 4, 0.82));<NEW_LINE>edgeWeightedGraph.addEdge(new Edge(4, 4, 0.1));<NEW_LINE>Exercise31_MSTWeights.LazyPrimMSTWeight lazyPrimMSTWeight = mstWeights.new LazyPrimMSTWeight(edgeWeightedGraph);<NEW_LINE>Exercise31_MSTWeights.PrimMSTWeight primMSTWeight = mstWeights.new PrimMSTWeight(edgeWeightedGraph);<NEW_LINE>Exercise31_MSTWeights.KruskalMSTWeight kruskalMSTWeight = mstWeights.new KruskalMSTWeight(edgeWeightedGraph);<NEW_LINE>StdOut.println("Expected MST weight: 1.84\n");<NEW_LINE>StdOut.println("Lazy Prim MST lazy weight: " + lazyPrimMSTWeight.lazyWeight());<NEW_LINE>StdOut.println("Lazy Prim MST eager weight: " + lazyPrimMSTWeight.eagerWeight());<NEW_LINE>StdOut.println(<MASK><NEW_LINE>StdOut.println("Eager Prim MST eager weight: " + primMSTWeight.eagerWeight());<NEW_LINE>StdOut.println("Kruskal MST lazy weight: " + kruskalMSTWeight.lazyWeight());<NEW_LINE>StdOut.println("Kruskal MST eager weight: " + kruskalMSTWeight.eagerWeight());<NEW_LINE>} | "Eager Prim MST lazy weight: " + primMSTWeight.lazyWeight()); |
1,711,031 | public void marshall(AwsRedshiftClusterRestoreStatus awsRedshiftClusterRestoreStatus, ProtocolMarshaller protocolMarshaller) {<NEW_LINE>if (awsRedshiftClusterRestoreStatus == null) {<NEW_LINE>throw new SdkClientException("Invalid argument passed to marshall(...)");<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>protocolMarshaller.marshall(awsRedshiftClusterRestoreStatus.getCurrentRestoreRateInMegaBytesPerSecond(), CURRENTRESTORERATEINMEGABYTESPERSECOND_BINDING);<NEW_LINE>protocolMarshaller.marshall(<MASK><NEW_LINE>protocolMarshaller.marshall(awsRedshiftClusterRestoreStatus.getEstimatedTimeToCompletionInSeconds(), ESTIMATEDTIMETOCOMPLETIONINSECONDS_BINDING);<NEW_LINE>protocolMarshaller.marshall(awsRedshiftClusterRestoreStatus.getProgressInMegaBytes(), PROGRESSINMEGABYTES_BINDING);<NEW_LINE>protocolMarshaller.marshall(awsRedshiftClusterRestoreStatus.getSnapshotSizeInMegaBytes(), SNAPSHOTSIZEINMEGABYTES_BINDING);<NEW_LINE>protocolMarshaller.marshall(awsRedshiftClusterRestoreStatus.getStatus(), STATUS_BINDING);<NEW_LINE>} catch (Exception e) {<NEW_LINE>throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);<NEW_LINE>}<NEW_LINE>} | awsRedshiftClusterRestoreStatus.getElapsedTimeInSeconds(), ELAPSEDTIMEINSECONDS_BINDING); |
1,847,089 | public CacheParameterGroup unmarshall(StaxUnmarshallerContext context) throws Exception {<NEW_LINE>CacheParameterGroup cacheParameterGroup = new CacheParameterGroup();<NEW_LINE>int originalDepth = context.getCurrentDepth();<NEW_LINE>int targetDepth = originalDepth + 1;<NEW_LINE>if (context.isStartOfDocument())<NEW_LINE>targetDepth += 3;<NEW_LINE>while (true) {<NEW_LINE>XMLEvent xmlEvent = context.nextEvent();<NEW_LINE>if (xmlEvent.isEndDocument())<NEW_LINE>return cacheParameterGroup;<NEW_LINE>if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {<NEW_LINE>if (context.testExpression("CacheParameterGroupName", targetDepth)) {<NEW_LINE>cacheParameterGroup.setCacheParameterGroupName(StringStaxUnmarshaller.getInstance().unmarshall(context));<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>if (context.testExpression("CacheParameterGroupFamily", targetDepth)) {<NEW_LINE>cacheParameterGroup.setCacheParameterGroupFamily(StringStaxUnmarshaller.getInstance().unmarshall(context));<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>if (context.testExpression("Description", targetDepth)) {<NEW_LINE>cacheParameterGroup.setDescription(StringStaxUnmarshaller.getInstance().unmarshall(context));<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>if (context.testExpression("IsGlobal", targetDepth)) {<NEW_LINE>cacheParameterGroup.setIsGlobal(BooleanStaxUnmarshaller.getInstance<MASK><NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>if (context.testExpression("ARN", targetDepth)) {<NEW_LINE>cacheParameterGroup.setARN(StringStaxUnmarshaller.getInstance().unmarshall(context));<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>} else if (xmlEvent.isEndElement()) {<NEW_LINE>if (context.getCurrentDepth() < originalDepth) {<NEW_LINE>return cacheParameterGroup;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | ().unmarshall(context)); |
134,597 | private StainVector grabHandle(double x, double y) {<NEW_LINE>ColorDeconvolutionStains stains = stainsWrapper == null ? null : stainsWrapper.getStains();<NEW_LINE>if (stains == null)<NEW_LINE>return null;<NEW_LINE>StainVector <MASK><NEW_LINE>StainVector s2 = stains.getStain(2);<NEW_LINE>double d1 = Point2D.distanceSq(x, y, dataXtoComponentX(getStainX(s1)), dataYtoComponentY(getStainY(s1)));<NEW_LINE>double d2 = Point2D.distanceSq(x, y, dataXtoComponentX(getStainX(s2)), dataYtoComponentY(getStainY(s2)));<NEW_LINE>if (d1 <= d2 && d1 <= handleSize * handleSize)<NEW_LINE>return s1;<NEW_LINE>if (d2 < d1 && d2 <= handleSize * handleSize)<NEW_LINE>return s2;<NEW_LINE>return null;<NEW_LINE>} | s1 = stains.getStain(1); |
551,434 | final TerminateTargetInstancesResult executeTerminateTargetInstances(TerminateTargetInstancesRequest terminateTargetInstancesRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(terminateTargetInstancesRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE><MASK><NEW_LINE>Request<TerminateTargetInstancesRequest> request = null;<NEW_LINE>Response<TerminateTargetInstancesResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new TerminateTargetInstancesRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(terminateTargetInstancesRequest));<NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);<NEW_LINE>request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "mgn");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "TerminateTargetInstances");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<TerminateTargetInstancesResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new TerminateTargetInstancesResultJsonUnmarshaller());<NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | awsRequestMetrics.startEvent(Field.ClientExecuteTime); |
1,714,215 | public void encode(Writer writer) throws IOException {<NEW_LINE>String renderer = this.getRenderer();<NEW_LINE>AxisType xaxis = this.getXaxis();<NEW_LINE><MASK><NEW_LINE>writer.write("{");<NEW_LINE>writer.write("label:\"" + EscapeUtils.forJavaScript(this.getLabel()) + "\"");<NEW_LINE>writer.write(",renderer: $.jqplot." + renderer);<NEW_LINE>if (xaxis != null)<NEW_LINE>writer.write(",xaxis:\"" + xaxis + "\"");<NEW_LINE>if (yaxis != null)<NEW_LINE>writer.write(",yaxis:\"" + yaxis + "\"");<NEW_LINE>if (disableStack)<NEW_LINE>writer.write(",disableStack:true");<NEW_LINE>if (fill) {<NEW_LINE>writer.write(",fill:true");<NEW_LINE>writer.write(",fillAlpha:" + this.getFillAlpha());<NEW_LINE>}<NEW_LINE>writer.write(",showLine:" + this.isShowLine());<NEW_LINE>writer.write(",markerOptions:{show:" + this.isShowMarker() + ", style:'" + this.getMarkerStyle() + "'}");<NEW_LINE>if (smoothLine) {<NEW_LINE>writer.write(",rendererOptions:{smooth: true }");<NEW_LINE>}<NEW_LINE>writer.write("}");<NEW_LINE>} | AxisType yaxis = this.getYaxis(); |
1,447,978 | Object Z_set(@SuppressWarnings("unused") FieldSet setfunc, PtrValue ptr, Object v, @SuppressWarnings("unused") int size, @Cached CastToJavaStringNode toString, @Cached GetNameNode getNameNode, @Cached GetClassNode getClassNode, @Cached PyLongCheckNode longCheckNode) {<NEW_LINE>// CTYPES_UNICODE<NEW_LINE>Object value = v;<NEW_LINE>if (value == PNone.NONE) {<NEW_LINE>ptr.toNil();<NEW_LINE>return value;<NEW_LINE>}<NEW_LINE>if (value instanceof PythonNativeVoidPtr) {<NEW_LINE>value = ((PythonNativeVoidPtr) value).getPointerObject();<NEW_LINE>// ptr.writePrimitive(setfunc.ffiType, v);<NEW_LINE>// return PNone.NONE;<NEW_LINE>} else if (longCheckNode.execute(value)) {<NEW_LINE>// *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongMask(value);<NEW_LINE>throw raise(PythonBuiltinClassType.NotImplementedError);<NEW_LINE>}<NEW_LINE>if (!PGuards.isString(value)) {<NEW_LINE>throw raise(TypeError, "unicode string or integer address expected instead of %s instance", getNameNode.execute(getClassNode.execute(value)));<NEW_LINE>}<NEW_LINE>String buffer = toString.execute(value);<NEW_LINE>char[] chars = BytesUtils.stringToChars(buffer);<NEW_LINE>ptr.<MASK><NEW_LINE>for (int i = 0; i < chars.length; i++) {<NEW_LINE>ptr.writeArrayElement(FieldDesc.u.pffi_type, i * 2, (short) chars[i]);<NEW_LINE>}<NEW_LINE>return buffer;<NEW_LINE>} | ensureCapacity(chars.length * 2); |
890,934 | private void addDerivedTypes() {<NEW_LINE>Iterator<DefinedType> typeIter = schema.getTypes().iterator();<NEW_LINE>while (typeIter.hasNext()) {<NEW_LINE>DefinedType type = typeIter.next();<NEW_LINE>// debug (type.getName()+":"+type.getDomain(true).toString());<NEW_LINE>// if ((type.getDomain() instanceof SimpleType)==false &&<NEW_LINE>// (type instanceof EnumerationType)==false &&<NEW_LINE>// (type instanceof SelectType)==false){<NEW_LINE>if (type.getName().equalsIgnoreCase("IfcCompoundPlaneAngleMeasure")) {<NEW_LINE>EClass testType = getOrCreateEClass(type.getName());<NEW_LINE>DefinedType type2 = new DefinedType("Integer");<NEW_LINE>type2.setDomain(new IntegerType());<NEW_LINE>modifySimpleType(type2, testType);<NEW_LINE>testType.getEAnnotations().add(createWrappedAnnotation());<NEW_LINE>} else if (type.getDomain() instanceof DefinedType) {<NEW_LINE>if (schemaPack.getEClassifier(type.getName()) != null) {<NEW_LINE>EClass testType = (EClass) schemaPack.getEClassifier(type.getName());<NEW_LINE>DefinedType domain = (DefinedType) type.getDomain();<NEW_LINE>EClassifier classifier = schemaPack.getEClassifier(domain.getName());<NEW_LINE>testType.getESuperTypes()<MASK><NEW_LINE>testType.setInstanceClass(classifier.getInstanceClass());<NEW_LINE>} else {<NEW_LINE>EClass testType = getOrCreateEClass(type.getName());<NEW_LINE>DefinedType domain = (DefinedType) type.getDomain();<NEW_LINE>if (simpleTypeReplacementMap.containsKey(domain.getName())) {<NEW_LINE>// We can't subclass because it's a 'primitive' type<NEW_LINE>simpleTypeReplacementMap.put(type.getName(), simpleTypeReplacementMap.get(domain.getName()));<NEW_LINE>} else {<NEW_LINE>EClass classifier = getOrCreateEClass(domain.getName());<NEW_LINE>testType.getESuperTypes().add((EClass) classifier);<NEW_LINE>if (classifier.getEAnnotation("wrapped") != null) {<NEW_LINE>testType.getEAnnotations().add(createWrappedAnnotation());<NEW_LINE>}<NEW_LINE>testType.setInstanceClass(classifier.getInstanceClass());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | .add((EClass) classifier); |
1,504,288 | private ConfigurationDocument createConfigFile(StringToStringMap values) {<NEW_LINE>ConfigurationDocument configDocument = ConfigurationDocument.Factory.newInstance();<NEW_LINE>ConfigurationType config = configDocument.addNewConfiguration();<NEW_LINE>JavaToWsdlType java2Wsdl = config.addNewJavaWsdl();<NEW_LINE>ServiceType service = java2Wsdl.addNewService();<NEW_LINE>service.setEndpoint(values.get(ENDPOINT));<NEW_LINE>service.setStyle(Style.Enum.forString(values.get(STYLE)));<NEW_LINE>service.setParameterStyle(ParameterStyle.Enum.forString(values.get(PARAMETER_STYLE)));<NEW_LINE>service.setName(values.get(SERVICE_NAME));<NEW_LINE>MappingType mapping = java2Wsdl.addNewMapping();<NEW_LINE>mapping.setFile(values.get(MAPPING));<NEW_LINE><MASK><NEW_LINE>namespaces.setTargetNamespace(values.get(TARGET_NAMESPACE));<NEW_LINE>namespaces.setTypeNamespace(values.get(TYPES_NAMESPACE));<NEW_LINE>WsxmlType webservices = java2Wsdl.addNewWebservices();<NEW_LINE>if (values.get(EJB_LINK) != null && values.get(EJB_LINK).length() > 0) {<NEW_LINE>webservices.setEjbLink(values.get(EJB_LINK));<NEW_LINE>}<NEW_LINE>if (values.get(SERVLET_LINK) != null && values.get(SERVLET_LINK).length() > 0) {<NEW_LINE>webservices.setServletLink(values.get(SERVLET_LINK));<NEW_LINE>}<NEW_LINE>return configDocument;<NEW_LINE>} | NamespacesType namespaces = java2Wsdl.addNewNamespaces(); |
437,529 | public OResultSet syncPull(OCommandContext ctx, int nRecords) throws OTimeoutException {<NEW_LINE>getPrev().ifPresent(x -> x.syncPull(ctx, nRecords));<NEW_LINE>return new OResultSet() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public boolean hasNext() {<NEW_LINE>return !executed;<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public OResult next() {<NEW_LINE>if (executed) {<NEW_LINE>throw new IllegalStateException();<NEW_LINE>}<NEW_LINE>long begin = profilingEnabled <MASK><NEW_LINE>try {<NEW_LINE>OIndex idx = ctx.getDatabase().getMetadata().getIndexManager().getIndex(target.getIndexName());<NEW_LINE>Object val = idx.getDefinition().createValue(keyValue.execute(new OResultInternal(), ctx));<NEW_LINE>long size = idx.getInternal().getRids(val).distinct().count();<NEW_LINE>executed = true;<NEW_LINE>OResultInternal result = new OResultInternal();<NEW_LINE>result.setProperty(alias, size);<NEW_LINE>return result;<NEW_LINE>} finally {<NEW_LINE>count += (System.nanoTime() - begin);<NEW_LINE>}<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void close() {<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public Optional<OExecutionPlan> getExecutionPlan() {<NEW_LINE>return Optional.empty();<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public Map<String, Long> getQueryStats() {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void reset() {<NEW_LINE>CountFromIndexWithKeyStep.this.reset();<NEW_LINE>}<NEW_LINE>};<NEW_LINE>} | ? System.nanoTime() : 0; |
1,092,531 | public static void YUV420pToRGBH2H(byte yh, byte yl, byte uh, byte ul, byte vh, byte vl, int nlbi, byte[] data, byte[] lowBits, int nlbo, int off) {<NEW_LINE>int clipMax = ((1 << nlbo) << 8) - 1;<NEW_LINE>int round = (1 << nlbo) >> 1;<NEW_LINE>int c = ((yh + 128) << nlbi) + yl - 64;<NEW_LINE>int d = ((uh + 128) << nlbi) + ul - 512;<NEW_LINE>int e = ((vh + 128) << nlbi) + vl - 512;<NEW_LINE>int r = MathUtil.clip((298 * c + 409 * e + 128) >> 8, 0, clipMax);<NEW_LINE>int g = MathUtil.clip((298 * c - 100 * d - 208 * e + 128) >> 8, 0, clipMax);<NEW_LINE>int b = MathUtil.clip((298 * c + 516 * d + 128) >> 8, 0, clipMax);<NEW_LINE>int valR = MathUtil.clip((r + round) >> nlbo, 0, 255);<NEW_LINE>data[off] = <MASK><NEW_LINE>lowBits[off] = (byte) (r - (valR << nlbo));<NEW_LINE>int valG = MathUtil.clip((g + round) >> nlbo, 0, 255);<NEW_LINE>data[off + 1] = (byte) (valG - 128);<NEW_LINE>lowBits[off + 1] = (byte) (g - (valG << nlbo));<NEW_LINE>int valB = MathUtil.clip((b + round) >> nlbo, 0, 255);<NEW_LINE>data[off + 2] = (byte) (valB - 128);<NEW_LINE>lowBits[off + 2] = (byte) (b - (valB << nlbo));<NEW_LINE>} | (byte) (valR - 128); |
1,001,663 | public ManifestIdentifier identify(Config config) {<NEW_LINE>final String manifestPath = config.manifest();<NEW_LINE>if (manifestPath.equals(Config.NONE)) {<NEW_LINE>return new ManifestIdentifier((String) null, null, null, null, null);<NEW_LINE>}<NEW_LINE>// Try to locate the manifest file as a classpath resource; fallback to using the base dir.<NEW_LINE>final Path manifestFile;<NEW_LINE>final String resourceName = manifestPath.startsWith("/") ? manifestPath : ("/" + manifestPath);<NEW_LINE>final URL resourceUrl = getClass().getResource(resourceName);<NEW_LINE>if (resourceUrl != null && "file".equals(resourceUrl.getProtocol())) {<NEW_LINE>// Construct a path to the manifest file relative to the current working directory.<NEW_LINE>final Path workingDirectory = Paths.get<MASK><NEW_LINE>final Path absolutePath = Fs.fromUrl(resourceUrl);<NEW_LINE>manifestFile = workingDirectory.relativize(absolutePath);<NEW_LINE>} else {<NEW_LINE>manifestFile = getBaseDir().resolve(manifestPath);<NEW_LINE>}<NEW_LINE>final Path baseDir = manifestFile.getParent();<NEW_LINE>final Path resDir = baseDir.resolve(config.resourceDir());<NEW_LINE>final Path assetDir = baseDir.resolve(config.assetDir());<NEW_LINE>List<ManifestIdentifier> libraries;<NEW_LINE>if (config.libraries().length == 0) {<NEW_LINE>// If there is no library override, look through subdirectories.<NEW_LINE>try {<NEW_LINE>libraries = findLibraries(resDir);<NEW_LINE>} catch (IOException e) {<NEW_LINE>throw new RuntimeException(e);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>libraries = new ArrayList<>();<NEW_LINE>for (String libraryDirName : config.libraries()) {<NEW_LINE>Path libDir = baseDir.resolve(libraryDirName);<NEW_LINE>libraries.add(new ManifestIdentifier(null, libDir.resolve(Config.DEFAULT_MANIFEST_NAME), libDir.resolve(Config.DEFAULT_RES_FOLDER), libDir.resolve(Config.DEFAULT_ASSET_FOLDER), null));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return new ManifestIdentifier(config.packageName(), manifestFile, resDir, assetDir, libraries);<NEW_LINE>} | (System.getProperty("user.dir")); |
241,439 | private String createStringForMultipleUse(List<UsePart> useParts, String indentString) {<NEW_LINE>StringBuilder insertString = new StringBuilder();<NEW_LINE>UsePart.Type lastUsePartType = null;<NEW_LINE>for (Iterator<UsePart> it = useParts.iterator(); it.hasNext(); ) {<NEW_LINE>UsePart usePart = it.next();<NEW_LINE>if (lastUsePartType != null) {<NEW_LINE>if (lastUsePartType == usePart.getType()) {<NEW_LINE>insertString.append(COMMA).append(NEW_LINE).append(indentString);<NEW_LINE>} else {<NEW_LINE>insertString.append(SEMICOLON);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (lastUsePartType != usePart.getType()) {<NEW_LINE>lastUsePartType = usePart.getType();<NEW_LINE>switch(usePart.getType()) {<NEW_LINE>case TYPE:<NEW_LINE>insertString.append(USE_PREFIX);<NEW_LINE>break;<NEW_LINE>case CONST:<NEW_LINE>insertString.append(USE_CONST_PREFIX);<NEW_LINE>break;<NEW_LINE>case FUNCTION:<NEW_LINE>insertString.append(USE_FUNCTION_PREFIX);<NEW_LINE>break;<NEW_LINE>default:<NEW_LINE>insertString.append(USE_PREFIX);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>insertString.<MASK><NEW_LINE>}<NEW_LINE>if (!useParts.isEmpty()) {<NEW_LINE>insertString.append(SEMICOLON);<NEW_LINE>}<NEW_LINE>return insertString.toString();<NEW_LINE>} | append(usePart.getTextPart()); |
450,828 | @Produces(MediaType.APPLICATION_JSON)<NEW_LINE>@ApiOperation(value = "Validate table config for a table", notes = "This API returns the table config that matches the one you get from 'GET /tables/{tableName}'." + " This allows us to validate table config before apply.")<NEW_LINE>public String checkTableConfig(String tableConfigStr, @ApiParam(value = "comma separated list of validation type(s) to skip. supported types: (ALL|TASK|UPSERT)") @QueryParam("validationTypesToSkip") @Nullable String typesToSkip) {<NEW_LINE>TableConfig tableConfig;<NEW_LINE>try {<NEW_LINE>tableConfig = JsonUtils.stringToObject(tableConfigStr, TableConfig.class);<NEW_LINE>} catch (IOException e) {<NEW_LINE>String msg = <MASK><NEW_LINE>throw new ControllerApplicationException(LOGGER, msg, Response.Status.BAD_REQUEST, e);<NEW_LINE>}<NEW_LINE>return validateConfig(tableConfig, _pinotHelixResourceManager.getSchemaForTableConfig(tableConfig), typesToSkip);<NEW_LINE>} | String.format("Invalid table config json string: %s", tableConfigStr); |
1,438,554 | public // getPersistentHashcode()<NEW_LINE>void testEquals(Object ddrObject, Object jextractObject, int members) {<NEW_LINE>JavaObject ddrJavaObject = (JavaObject) ddrObject;<NEW_LINE>JavaObject jextractJavaObject = (JavaObject) jextractObject;<NEW_LINE>// isArray()<NEW_LINE>if ((IS_ARRAY & members) != 0)<NEW_LINE>testJavaEquals(ddrJavaObject, jextractJavaObject, "isArray");<NEW_LINE>// getArraySize()<NEW_LINE>if ((ARRAY_SIZE & members) != 0) {<NEW_LINE>try {<NEW_LINE>if (ddrJavaObject.isArray()) {<NEW_LINE>testJavaEquals(ddrJavaObject, jextractJavaObject, "getArraySize");<NEW_LINE>}<NEW_LINE>} catch (CorruptDataException e) {<NEW_LINE>fail(String.format("Problem comparing JavaObject %s", ddrJavaObject));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// getID()<NEW_LINE>if ((ID & members) != 0)<NEW_LINE>new ImagePointerComparator().testComparatorEquals(ddrJavaObject, jextractJavaObject, "getID");<NEW_LINE>// getJavaClass()<NEW_LINE>if ((JAVA_CLASS & members) != 0)<NEW_LINE>new JavaClassComparator().testComparatorEquals(ddrJavaObject, jextractJavaObject, "getJavaClass");<NEW_LINE>// getReferences()<NEW_LINE>if ((REFERENCES & members) != 0)<NEW_LINE>new JavaReferenceComparator().testComparatorIteratorEquals(ddrJavaObject, jextractJavaObject, "getReferences", JavaReference.class);<NEW_LINE>// getSections()<NEW_LINE>if ((SECTIONS & members) != 0)<NEW_LINE>new ImageSectionComparator().testComparatorIteratorEquals(ddrJavaObject, jextractJavaObject, "getSections", ImageSection.class);<NEW_LINE>// getHeap()<NEW_LINE>if ((HEAP & members) != 0)<NEW_LINE>new JavaHeapComparator().<MASK><NEW_LINE>} | testComparatorEquals(ddrJavaObject, jextractJavaObject, "getHeap"); |
1,337,304 | private Optional<String> findRemoteBranchHeadCommit(List<String> lines, String branch) {<NEW_LINE>// 42958134b46b814ac54a740b784dcd67afae282c not-for-merge branch 'master' of github.com:gradle/gradle<NEW_LINE>// ef7f1b475b1309a47e98acdf7183bf8e0c65b729 not-for-merge branch 'oehme/performance/config-time' of github.com:gradle/gradle<NEW_LINE>// 42958134b46b814ac54a740b784dcd67afae282c branch 'master' of github.com:gradle/gradle<NEW_LINE>Pattern pattern = "master".equals(branch) ? FETCH_HEAD_MASTER_PATTERN : Pattern.compile("([0-9a-f]+)[\\s\\w-]+branch '" + branch + "' of");<NEW_LINE>for (String line : lines) {<NEW_LINE>Matcher <MASK><NEW_LINE>if (matcher.find()) {<NEW_LINE>return Optional.of(matcher.group(1));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return Optional.empty();<NEW_LINE>} | matcher = pattern.matcher(line); |
1,169,964 | public void sendRequest(final Exchange exchange) {<NEW_LINE>// for observe request.<NEW_LINE>Request request = exchange.getCurrentRequest();<NEW_LINE>if (request.isObserve() && 0 == exchange.getFailedTransmissionCount()) {<NEW_LINE>if (exchangeStore.assignMessageId(request) != Message.NONE) {<NEW_LINE>registerObserve(request);<NEW_LINE>} else {<NEW_LINE>LOGGER.debug("message IDs exhausted, could not register outbound observe request for tracking");<NEW_LINE>request.<MASK><NEW_LINE>return;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>if (exchangeStore.registerOutboundRequest(exchange)) {<NEW_LINE>exchange.setRemoveHandler(exchangeRemoveHandler);<NEW_LINE>LOGGER.debug("tracking open request [{}, {}]", exchange.getKeyMID(), exchange.getKeyToken());<NEW_LINE>} else {<NEW_LINE>LOGGER.debug("message IDs exhausted, could not register outbound request for tracking");<NEW_LINE>request.setSendError(new IllegalStateException("automatic message IDs exhausted"));<NEW_LINE>}<NEW_LINE>} catch (IllegalArgumentException ex) {<NEW_LINE>request.setSendError(ex);<NEW_LINE>}<NEW_LINE>} | setSendError(new IllegalStateException("automatic message IDs exhausted")); |
1,842,050 | public boolean visit(final PrivateGatewayRules privateGW) throws ResourceUnavailableException {<NEW_LINE>final VirtualRouter router = privateGW.getRouter();<NEW_LINE>final NicProfile nicProfile = privateGW.getNicProfile();<NEW_LINE>final boolean isAddOperation = privateGW.isAddOperation();<NEW_LINE>if (router.getState() == State.Running) {<NEW_LINE>final PrivateIpVO ipVO = privateGW.retrivePrivateIP(this);<NEW_LINE>final Network network = privateGW.retrievePrivateNetwork(this);<NEW_LINE>final String netmask = NetUtils.getCidrNetmask(network.getCidr());<NEW_LINE>final PrivateIpAddress ip = new PrivateIpAddress(ipVO, network.getBroadcastUri().toString(), network.getGateway(), netmask, nicProfile.getMacAddress());<NEW_LINE>final List<PrivateIpAddress> privateIps = new ArrayList<PrivateIpAddress>(1);<NEW_LINE>privateIps.add(ip);<NEW_LINE>final Commands cmds = new Commands(Command.OnError.Stop);<NEW_LINE>_commandSetupHelper.createVpcAssociatePrivateIPCommands(router, privateIps, cmds, isAddOperation);<NEW_LINE>try {<NEW_LINE>if (_networkGeneralHelper.sendCommandsToRouter(router, cmds)) {<NEW_LINE>s_logger.debug("Successfully applied ip association for ip " + ip + " in vpc network " + network);<NEW_LINE>return true;<NEW_LINE>} else {<NEW_LINE>s_logger.warn("Failed to associate ip address " + ip + " in vpc network " + network);<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>} catch (final Exception ex) {<NEW_LINE>s_logger.warn("Failed to send " + (isAddOperation ? "add " : "delete ") + " private network " + network + " commands to rotuer ");<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>} else if (router.getState() == State.Stopped || router.getState() == State.Stopping) {<NEW_LINE>s_logger.debug("Router " + router.getInstanceName() + " is in " + <MASK><NEW_LINE>} else {<NEW_LINE>s_logger.warn("Unable to setup private gateway, virtual router " + router + " is not in the right state " + router.getState());<NEW_LINE>throw new ResourceUnavailableException("Unable to setup Private gateway on the backend," + " virtual router " + router + " is not in the right state", DataCenter.class, router.getDataCenterId());<NEW_LINE>}<NEW_LINE>return true;<NEW_LINE>} | router.getState() + ", so not sending setup private network command to the backend"); |
704,461 | public Code clearCustomInstallationId(long projectNumber, @NonNull String apiKey, @NonNull String firebaseInstanceId, @NonNull String firebaseInstanceIdToken) {<NEW_LINE>String resourceName = String.format(CLEAR_REQUEST_RESOURCE_NAME_FORMAT, projectNumber, firebaseInstanceId);<NEW_LINE>try {<NEW_LINE>URL url = new URL(String.format("https://%s/%s/%s?key=%s", FIREBASE_SEGMENTATION_API_DOMAIN<MASK><NEW_LINE>HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();<NEW_LINE>httpsURLConnection.setDoOutput(true);<NEW_LINE>httpsURLConnection.setRequestMethod("POST");<NEW_LINE>httpsURLConnection.addRequestProperty("Authorization", "FIREBASE_INSTALLATIONS_AUTH " + firebaseInstanceIdToken);<NEW_LINE>httpsURLConnection.addRequestProperty(CONTENT_TYPE_HEADER_KEY, JSON_CONTENT_TYPE);<NEW_LINE>httpsURLConnection.addRequestProperty(CONTENT_ENCODING_HEADER_KEY, GZIP_CONTENT_ENCODING);<NEW_LINE>httpsURLConnection.addRequestProperty(X_ANDROID_PACKAGE_HEADER_KEY, context.getPackageName());<NEW_LINE>httpsURLConnection.addRequestProperty(X_ANDROID_CERT_HEADER_KEY, getFingerprintHashForPackage());<NEW_LINE>GZIPOutputStream gzipOutputStream = new GZIPOutputStream(httpsURLConnection.getOutputStream());<NEW_LINE>try {<NEW_LINE>gzipOutputStream.write(buildClearCustomSegmentationDataRequestBody(resourceName).toString().getBytes("UTF-8"));<NEW_LINE>} catch (JSONException e) {<NEW_LINE>throw new IllegalStateException(e);<NEW_LINE>} finally {<NEW_LINE>gzipOutputStream.close();<NEW_LINE>}<NEW_LINE>int httpResponseCode = httpsURLConnection.getResponseCode();<NEW_LINE>switch(httpResponseCode) {<NEW_LINE>case 200:<NEW_LINE>return Code.OK;<NEW_LINE>case 401:<NEW_LINE>return Code.UNAUTHORIZED;<NEW_LINE>default:<NEW_LINE>if (httpResponseCode / 100 == 4) {<NEW_LINE>return Code.HTTP_CLIENT_ERROR;<NEW_LINE>}<NEW_LINE>return Code.SERVER_ERROR;<NEW_LINE>}<NEW_LINE>} catch (IOException e) {<NEW_LINE>return Code.NETWORK_ERROR;<NEW_LINE>}<NEW_LINE>} | , FIREBASE_SEGMENTATION_API_VERSION, resourceName, apiKey)); |
1,644,895 | public IHarvestResult harvestBlock(@Nonnull IFarmer farm, @Nonnull final BlockPos pos, @Nonnull IBlockState state) {<NEW_LINE>if (!canHarvest(farm, pos, state) || !farm.checkAction(FarmingAction.HARVEST, FarmingTool.HOE)) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>if (!farm.hasTool(FarmingTool.HOE)) {<NEW_LINE>farm.setNotification(FarmNotification.NO_HOE);<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>final World world = farm.getWorld();<NEW_LINE>final IHarvestResult res = new HarvestResult(pos);<NEW_LINE>final EntityPlayerMP fakePlayer = farm.startUsingItem(FarmingTool.HOE);<NEW_LINE>final int fortune = farm.getLootingValue(FarmingTool.HOE);<NEW_LINE><MASK><NEW_LINE>NNList<ItemStack> drops = new NNList<>();<NEW_LINE>state.getBlock().getDrops(drops, world, pos, state, fortune);<NEW_LINE>float chance = ForgeEventFactory.fireBlockHarvesting(drops, world, pos, state, fortune, 1.0F, false, fakePlayer);<NEW_LINE>farm.registerAction(FarmingAction.HARVEST, FarmingTool.HOE, state, pos);<NEW_LINE>for (ItemStack stack : drops) {<NEW_LINE>if (stack != null && Prep.isValid(stack) && world.rand.nextFloat() <= chance) {<NEW_LINE>if (Prep.isInvalid(removedPlantable) && isPlantableForBlock(farm, stack, state.getBlock())) {<NEW_LINE>removedPlantable = stack.copy();<NEW_LINE>removedPlantable.setCount(1);<NEW_LINE>stack.shrink(1);<NEW_LINE>}<NEW_LINE>if (Prep.isValid(stack)) {<NEW_LINE>res.addDrop(pos, stack.copy());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>NNList.wrap(farm.endUsingItem(FarmingTool.HOE)).apply(new Callback<ItemStack>() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void apply(@Nonnull ItemStack drop) {<NEW_LINE>res.addDrop(pos, drop.copy());<NEW_LINE>}<NEW_LINE>});<NEW_LINE>if (Prep.isValid(removedPlantable)) {<NEW_LINE>if (!plant(farm, world, pos, (IPlantable) removedPlantable.getItem())) {<NEW_LINE>res.addDrop(pos, removedPlantable.copy());<NEW_LINE>world.setBlockState(pos, Blocks.AIR.getDefaultState(), 1 | 2);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>world.setBlockState(pos, Blocks.AIR.getDefaultState(), 1 | 2);<NEW_LINE>}<NEW_LINE>return res;<NEW_LINE>} | ItemStack removedPlantable = Prep.getEmpty(); |
50,344 | public DescribeIdentityPoolResult describeIdentityPool(DescribeIdentityPoolRequest describeIdentityPoolRequest) throws AmazonServiceException, AmazonClientException {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(describeIdentityPoolRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<DescribeIdentityPoolRequest> request = null;<NEW_LINE>Response<DescribeIdentityPoolResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new DescribeIdentityPoolRequestMarshaller().marshall(describeIdentityPoolRequest);<NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>Unmarshaller<DescribeIdentityPoolResult, JsonUnmarshallerContext> unmarshaller = new DescribeIdentityPoolResultJsonUnmarshaller();<NEW_LINE>JsonResponseHandler<DescribeIdentityPoolResult> responseHandler = new JsonResponseHandler<DescribeIdentityPoolResult>(unmarshaller);<NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.ClientExecuteTime);<NEW_LINE>endClientExecution(<MASK><NEW_LINE>}<NEW_LINE>} | awsRequestMetrics, request, response, LOGGING_AWS_REQUEST_METRIC); |
275,919 | public void initialize() {<NEW_LINE>gridRow = bsqBalanceUtil.addGroup(root, gridRow);<NEW_LINE>tableView = new TableView<>();<NEW_LINE>tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);<NEW_LINE>addDateColumn();<NEW_LINE>addTxIdColumn();<NEW_LINE>addInformationColumn();<NEW_LINE>addAmountColumn();<NEW_LINE>addConfidenceColumn();<NEW_LINE>addTxTypeColumn();<NEW_LINE>chainSyncIndicator = new JFXProgressBar();<NEW_LINE>chainSyncIndicator.setPrefWidth(120);<NEW_LINE>if (DevEnv.isDaoActivated())<NEW_LINE>chainSyncIndicator.setProgress(-1);<NEW_LINE>else<NEW_LINE>chainSyncIndicator.setProgress(0);<NEW_LINE>chainSyncIndicator.setPadding(new Insets(-6, 0, -10, 5));<NEW_LINE>chainHeightLabel = FormBuilder.addLabel(root, ++gridRow, "");<NEW_LINE>chainHeightLabel.setId("num-offers");<NEW_LINE>chainHeightLabel.setPadding(new Insets(-5, 0, -10, 5));<NEW_LINE>exportButton = new AutoTooltipButton();<NEW_LINE>exportButton.updateText(Res.get("shared.exportCSV"));<NEW_LINE>Region spacer = new Region();<NEW_LINE>HBox.setHgrow(spacer, Priority.ALWAYS);<NEW_LINE>HBox hBox = new HBox();<NEW_LINE>hBox.setSpacing(10);<NEW_LINE>hBox.getChildren().addAll(chainHeightLabel, chainSyncIndicator, spacer, exportButton);<NEW_LINE>VBox vBox = new VBox();<NEW_LINE>vBox.setSpacing(10);<NEW_LINE>GridPane.setVgrow(vBox, Priority.ALWAYS);<NEW_LINE>GridPane.setRowIndex(vBox, ++gridRow);<NEW_LINE>GridPane.setColumnSpan(vBox, 3);<NEW_LINE>GridPane.setRowSpan(vBox, 2);<NEW_LINE>GridPane.setMargin(vBox, new Insets(40, -10, 5, -10));<NEW_LINE>vBox.getChildren(<MASK><NEW_LINE>VBox.setVgrow(tableView, Priority.ALWAYS);<NEW_LINE>root.getChildren().add(vBox);<NEW_LINE>walletChainHeightListener = (observable, oldValue, newValue) -> {<NEW_LINE>walletChainHeight = bsqWalletService.getBestChainHeight();<NEW_LINE>onUpdateAnyChainHeight();<NEW_LINE>};<NEW_LINE>} | ).addAll(tableView, hBox); |
824,049 | private void enqueue(Exclusion exclusion, ReferenceNode parent, Instance child, String referenceName, ReferenceTraceElement.Type referenceType) {<NEW_LINE>if (child == null) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>if (isPrimitiveOrWrapperArray(child) || isPrimitiveWrapper(child)) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>// Whether we want to visit now or later, we should skip if this is already to visit.<NEW_LINE>if (toVisitSet.contains(child)) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>boolean visitNow = exclusion == null;<NEW_LINE>if (!visitNow && toVisitIfNoPathSet.contains(child)) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>if (canIgnoreStrings && isString(child)) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>if (visitedSet.contains(child)) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>ReferenceNode childNode = new ReferenceNode(exclusion, <MASK><NEW_LINE>if (visitNow) {<NEW_LINE>toVisitSet.add(child);<NEW_LINE>toVisitQueue.add(childNode);<NEW_LINE>} else {<NEW_LINE>toVisitIfNoPathSet.add(child);<NEW_LINE>toVisitIfNoPathQueue.add(childNode);<NEW_LINE>}<NEW_LINE>} | child, parent, referenceName, referenceType); |
114,586 | private boolean doOpenProject(@NonNull final Project p) {<NEW_LINE>LOGGER.log(<MASK><NEW_LINE>final AtomicBoolean alreadyOpen = new AtomicBoolean();<NEW_LINE>boolean recentProjectsChanged = MUTEX.writeAccess(new Mutex.Action<Boolean>() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public Boolean run() {<NEW_LINE>log(Level.FINER, "already opened: {0} ", openProjects);<NEW_LINE>for (Project existing : openProjects) {<NEW_LINE>if (p.equals(existing) || existing.equals(p)) {<NEW_LINE>alreadyOpen.set(true);<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>openProjects.add(p);<NEW_LINE>addModuleInfo(p);<NEW_LINE>// initially opened projects need to have these listeners also added.<NEW_LINE>p.getProjectDirectory().addFileChangeListener(deleteListener);<NEW_LINE>p.getProjectDirectory().addFileChangeListener(nbprojectDeleteListener);<NEW_LINE>return recentProjects.remove(p);<NEW_LINE>}<NEW_LINE>});<NEW_LINE>if (alreadyOpen.get()) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>// NOI18N<NEW_LINE>logProjects("doOpenProject(): openProjects == ", openProjects.toArray(new Project[0]));<NEW_LINE>// Notify projects opened<NEW_LINE>notifyOpened(p);<NEW_LINE>OPENING_RP.post(new Runnable() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void run() {<NEW_LINE>ProjectUtilities.openProjectFiles(p);<NEW_LINE>}<NEW_LINE>});<NEW_LINE>return recentProjectsChanged;<NEW_LINE>} | Level.FINER, "doOpenProject: {0}", p); |
561,130 | public List<EStep> calculateArtifactProbabilities(final VariantContext vc, final Mutect2FilteringEngine filteringEngine) {<NEW_LINE>// for each allele, forward and reverse count<NEW_LINE>List<List<Integer>> sbs = StrandBiasUtils.getSBsForAlleles(vc);<NEW_LINE>if (sbs == null || sbs.isEmpty() || sbs.size() <= 1) {<NEW_LINE>return Collections.emptyList();<NEW_LINE>}<NEW_LINE>// remove symbolic alleles<NEW_LINE>if (vc.hasSymbolicAlleles()) {<NEW_LINE>sbs = GATKVariantContextUtils.removeDataForSymbolicAlleles(vc, sbs);<NEW_LINE>}<NEW_LINE>final List<Integer> indelSizes = vc.getAlternateAlleles().stream().map(alt -> Math.abs(vc.getReference().length() - alt.length())).collect(Collectors.toList());<NEW_LINE>int totalFwd = sbs.stream().map(sb -> sb.get(0)).mapToInt(i -> i).sum();<NEW_LINE>int totalRev = sbs.stream().map(sb -> sb.get(1)).mapToInt(<MASK><NEW_LINE>// skip the reference<NEW_LINE>final List<List<Integer>> altSBs = sbs.subList(1, sbs.size());<NEW_LINE>return IntStream.range(0, altSBs.size()).mapToObj(i -> {<NEW_LINE>final List<Integer> altSB = altSBs.get(i);<NEW_LINE>final int altIndelSize = indelSizes.get(i);<NEW_LINE>if (altSB.stream().mapToInt(Integer::intValue).sum() == 0 || altIndelSize > LONGEST_STRAND_ARTIFACT_INDEL_SIZE) {<NEW_LINE>return new EStep(0, 0, totalFwd, totalRev, altSB.get(0), altSB.get(1));<NEW_LINE>} else {<NEW_LINE>return strandArtifactProbability(strandArtifactPrior, totalFwd, totalRev, altSB.get(0), altSB.get(1), altIndelSize);<NEW_LINE>}<NEW_LINE>}).collect(Collectors.toList());<NEW_LINE>} | i -> i).sum(); |
200,515 | public long handle(Emulator<?> emulator) {<NEW_LINE>RegisterContext context = emulator.getContext();<NEW_LINE>UnidbgPointer object = context.getPointerArg(1);<NEW_LINE>Pointer isCopy = context.getPointerArg(2);<NEW_LINE>StringObject string = getObject(object.toIntPeer());<NEW_LINE>if (isCopy != null) {<NEW_LINE>isCopy.setInt(0, JNI_TRUE);<NEW_LINE>}<NEW_LINE>String value = Objects.requireNonNull(string).getValue();<NEW_LINE>byte[] bytes = new byte[value.length() * 2];<NEW_LINE>ByteBuffer buffer = ByteBuffer.wrap(bytes);<NEW_LINE>buffer.order(ByteOrder.LITTLE_ENDIAN);<NEW_LINE>for (char c : value.toCharArray()) {<NEW_LINE>buffer.putChar(c);<NEW_LINE>}<NEW_LINE>if (log.isDebugEnabled()) {<NEW_LINE>log.debug("GetStringUTFChars string=" + string + ", isCopy=" + isCopy + ", value=" + value + <MASK><NEW_LINE>}<NEW_LINE>if (verbose) {<NEW_LINE>System.out.printf("JNIEnv->GetStringUTFChars(\"%s\") was called from %s%n", string, context.getLRPointer());<NEW_LINE>}<NEW_LINE>byte[] data = Arrays.copyOf(bytes, bytes.length + 1);<NEW_LINE>UnidbgPointer pointer = string.allocateMemoryBlock(emulator, data.length);<NEW_LINE>pointer.write(0, data, 0, data.length);<NEW_LINE>return pointer.toIntPeer();<NEW_LINE>} | ", lr=" + context.getLRPointer()); |
39,590 | public Builder mergeFrom(com.didiglobal.booster.aapt2.Resources.Plural other) {<NEW_LINE>if (other == com.didiglobal.booster.aapt2.Resources.Plural.getDefaultInstance())<NEW_LINE>return this;<NEW_LINE>if (entryBuilder_ == null) {<NEW_LINE>if (!other.entry_.isEmpty()) {<NEW_LINE>if (entry_.isEmpty()) {<NEW_LINE>entry_ = other.entry_;<NEW_LINE>bitField0_ = (bitField0_ & ~0x00000001);<NEW_LINE>} else {<NEW_LINE>ensureEntryIsMutable();<NEW_LINE>entry_.addAll(other.entry_);<NEW_LINE>}<NEW_LINE>onChanged();<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>if (!other.entry_.isEmpty()) {<NEW_LINE>if (entryBuilder_.isEmpty()) {<NEW_LINE>entryBuilder_.dispose();<NEW_LINE>entryBuilder_ = null;<NEW_LINE>entry_ = other.entry_;<NEW_LINE>bitField0_ = (bitField0_ & ~0x00000001);<NEW_LINE>entryBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getEntryFieldBuilder() : null;<NEW_LINE>} else {<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>this.mergeUnknownFields(other.unknownFields);<NEW_LINE>onChanged();<NEW_LINE>return this;<NEW_LINE>} | entryBuilder_.addAllMessages(other.entry_); |
1,642,784 | public void emitInvoke(Invoke x) {<NEW_LINE>LoweredCallTargetNode callTargetNode = (LoweredCallTargetNode) x.callTarget();<NEW_LINE>final Stamp stamp = x.asNode().stamp(NodeView.DEFAULT);<NEW_LINE>LIRKind lirKind = resolveStamp(stamp);<NEW_LINE>AllocatableValue result = Value.ILLEGAL;<NEW_LINE>if (lirKind != LIRKind.Illegal) {<NEW_LINE>result = gen.newVariable(lirKind);<NEW_LINE>} else if (stamp instanceof VoidStamp) {<NEW_LINE>Logger.traceBuildLIR(Logger.BACKEND.SPIRV, "Generating Void Type Variable for function");<NEW_LINE>result = gen.newVariable(LIRKind.value(SPIRVKind.OP_TYPE_VOID));<NEW_LINE>}<NEW_LINE>CallingConvention callingConvention = new CallingConvention(0, result);<NEW_LINE>gen.getResult().getFrameMapBuilder().callsMethod(callingConvention);<NEW_LINE>Value[] parameters = visitInvokeArguments(<MASK><NEW_LINE>LIRFrameState callState = stateWithExceptionEdge(x, null);<NEW_LINE>if (callTargetNode instanceof DirectCallTargetNode) {<NEW_LINE>emitDirectCall((DirectCallTargetNode) callTargetNode, result, parameters, AllocatableValue.NONE, callState);<NEW_LINE>} else if (callTargetNode instanceof IndirectCallTargetNode) {<NEW_LINE>throw new RuntimeException("Not supported");<NEW_LINE>} else {<NEW_LINE>throw new RuntimeException("Not supported");<NEW_LINE>}<NEW_LINE>if (isLegal(result)) {<NEW_LINE>setResult(x.asNode(), result);<NEW_LINE>}<NEW_LINE>} | callingConvention, callTargetNode.arguments()); |
1,006,196 | private void taskFinished(TaskInstance taskInstance) {<NEW_LINE>logger.info("work flow {} task id:{} code:{} state:{} ", processInstance.getId(), taskInstance.getId(), taskInstance.getTaskCode(), taskInstance.getState());<NEW_LINE>activeTaskProcessorMaps.remove(taskInstance.getTaskCode());<NEW_LINE>stateWheelExecuteThread.removeTask4TimeoutCheck(processInstance, taskInstance);<NEW_LINE><MASK><NEW_LINE>stateWheelExecuteThread.removeTask4StateCheck(processInstance, taskInstance);<NEW_LINE>if (taskInstance.getState().typeIsSuccess()) {<NEW_LINE>completeTaskMap.put(taskInstance.getTaskCode(), taskInstance.getId());<NEW_LINE>processService.saveProcessInstance(processInstance);<NEW_LINE>if (!processInstance.isBlocked()) {<NEW_LINE>submitPostNode(Long.toString(taskInstance.getTaskCode()));<NEW_LINE>}<NEW_LINE>} else if (taskInstance.taskCanRetry() && processInstance.getState() != ExecutionStatus.READY_STOP) {<NEW_LINE>// retry task<NEW_LINE>retryTaskInstance(taskInstance);<NEW_LINE>} else if (taskInstance.getState().typeIsFailure()) {<NEW_LINE>completeTaskMap.put(taskInstance.getTaskCode(), taskInstance.getId());<NEW_LINE>if (taskInstance.isConditionsTask() || DagHelper.haveConditionsAfterNode(Long.toString(taskInstance.getTaskCode()), dag) || DagHelper.haveBlockingAfterNode(Long.toString(taskInstance.getTaskCode()), dag)) {<NEW_LINE>submitPostNode(Long.toString(taskInstance.getTaskCode()));<NEW_LINE>} else {<NEW_LINE>errorTaskMap.put(taskInstance.getTaskCode(), taskInstance.getId());<NEW_LINE>if (processInstance.getFailureStrategy() == FailureStrategy.END) {<NEW_LINE>killAllTasks();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} else if (taskInstance.getState().typeIsFinished()) {<NEW_LINE>completeTaskMap.put(taskInstance.getTaskCode(), taskInstance.getId());<NEW_LINE>}<NEW_LINE>this.updateProcessInstanceState();<NEW_LINE>} | stateWheelExecuteThread.removeTask4RetryCheck(processInstance, taskInstance); |
239,820 | public Optional<AggregationProjectionSegment> convertToSQLSegment(final SqlBasicCall sqlBasicCall) {<NEW_LINE>if (null == sqlBasicCall) {<NEW_LINE>return Optional.empty();<NEW_LINE>}<NEW_LINE>if (isAsOperatorAggregationType(sqlBasicCall)) {<NEW_LINE>SqlBasicCall subSqlBasicCall = (SqlBasicCall) sqlBasicCall.getOperandList().get(0);<NEW_LINE>AggregationType aggregationType = AggregationType.valueOf(subSqlBasicCall.getOperator().getName().toUpperCase());<NEW_LINE>String innerExpression = getInnerExpression(subSqlBasicCall);<NEW_LINE>AliasSegment aliasSegment = new AliasSegment(getStartIndex(sqlBasicCall.getOperandList().get(1)), getStopIndex(sqlBasicCall.getOperandList().get(1)), new IdentifierValue(((SqlIdentifier) sqlBasicCall.getOperandList().get(1)).names.get(0)));<NEW_LINE>if (null != subSqlBasicCall.getFunctionQuantifier() && SqlSelectKeyword.DISTINCT == subSqlBasicCall.getFunctionQuantifier().getValue()) {<NEW_LINE>return Optional.of(getAggregationDistinctProjectionSegment(subSqlBasicCall, aggregationType, aliasSegment));<NEW_LINE>}<NEW_LINE>AggregationProjectionSegment aggregationProjectionSegment = new AggregationProjectionSegment(getStartIndex(subSqlBasicCall), getStopIndex(subSqlBasicCall), aggregationType, innerExpression);<NEW_LINE>aggregationProjectionSegment.setAlias(aliasSegment);<NEW_LINE>return Optional.of(aggregationProjectionSegment);<NEW_LINE>}<NEW_LINE>AggregationType aggregationType = AggregationType.valueOf(sqlBasicCall.<MASK><NEW_LINE>if (null != sqlBasicCall.getFunctionQuantifier() && SqlSelectKeyword.DISTINCT == sqlBasicCall.getFunctionQuantifier().getValue()) {<NEW_LINE>return Optional.of(getAggregationDistinctProjectionSegment(sqlBasicCall, aggregationType, null));<NEW_LINE>}<NEW_LINE>String innerExpression = getInnerExpression(sqlBasicCall);<NEW_LINE>return Optional.of(new AggregationProjectionSegment(getStartIndex(sqlBasicCall), getStopIndex(sqlBasicCall), aggregationType, innerExpression));<NEW_LINE>} | getOperator().getName()); |
946,544 | private final void logSecretKeyInitResult() {<NEW_LINE>ArrayList<Secret> secretSet = m_secretSet;<NEW_LINE>if (secretSet == null) {<NEW_LINE>if (s_logger.isErrorEnabled()) {<NEW_LINE>s_logger.error("error.sip.outbound.failure", null, null);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>if (s_logger.isInfoEnabled()) {<NEW_LINE>s_logger.info("info.sip.outbound.initialized", null);<NEW_LINE>}<NEW_LINE>if (s_logger.isTraceDebugEnabled()) {<NEW_LINE>StringBuilder b = new StringBuilder(1024);<NEW_LINE>int size = secretSet.size();<NEW_LINE>b.append("Flow token security initialized with [" + size + "] key(s):\r\n");<NEW_LINE>for (int i = 0; i < size; i++) {<NEW_LINE>Secret secret = secretSet.get(i);<NEW_LINE>b.append(i).append(": ").append(secret.toString()).append("\r\n");<NEW_LINE>}<NEW_LINE>s_logger.traceDebug(this, <MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | "logSecretKeyInitResult", b.toString()); |
613,608 | public Expression combine(Expression left, Expression right) {<NEW_LINE>if (!(left instanceof Call)) {<NEW_LINE>// regular and<NEW_LINE>return and(<MASK><NEW_LINE>}<NEW_LINE>Call root = (Call) left;<NEW_LINE>if (root.operator() == Operators.OR) {<NEW_LINE>// change right-most child<NEW_LINE>// a.is(1)<NEW_LINE>// .or()<NEW_LINE>// .b.is(2).c.is(3)<NEW_LINE>List<Expression> args = // skip last<NEW_LINE>root.arguments().stream().// skip last<NEW_LINE>limit(root.arguments().size() - 1).collect(Collectors.toList());<NEW_LINE>Expression last = root.arguments().get(root.arguments().size() - 1);<NEW_LINE>Expression newLast = combine(last, right);<NEW_LINE>args.add(newLast);<NEW_LINE>return Expressions.or(args);<NEW_LINE>}<NEW_LINE>// simple 2 arg AND call<NEW_LINE>return and().combine(left, right);<NEW_LINE>} | ).combine(left, right); |
946,573 | private static DownloadInfo add(Builder b) {<NEW_LINE>Context context = b.mContext;<NEW_LINE>removeAllForUrl(context, b.mUrl);<NEW_LINE>if (!b.mDialog) {<NEW_LINE>synchronized (mCallbacks) {<NEW_LINE>mCallbacks.put(b.mUrl, b.mCallback);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>Request request = new Request(Uri.parse(b.mUrl));<NEW_LINE><MASK><NEW_LINE>request.setMimeType(b.mMimeType.toString());<NEW_LINE>if (b.mDestination != null) {<NEW_LINE>b.mDestination.getParentFile().mkdirs();<NEW_LINE>removeAllForLocalFile(context, b.mDestination);<NEW_LINE>request.setDestinationUri(Uri.fromFile(b.mDestination));<NEW_LINE>}<NEW_LINE>request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);<NEW_LINE>DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);<NEW_LINE>long id = dm.enqueue(request);<NEW_LINE>if (b.mDialog) {<NEW_LINE>showDownloadDialog(b, id);<NEW_LINE>}<NEW_LINE>return getById(context, id);<NEW_LINE>} | request.setTitle(b.mTitle); |
752,564 | private void openSelectionInEditor() {<NEW_LINE>DBPDataSourceContainer dsContainer = null;<NEW_LINE>StringBuilder sql = new StringBuilder();<NEW_LINE>TableItem[] items = logTable.getSelection();<NEW_LINE>for (TableItem item : items) {<NEW_LINE>QMEvent event = <MASK><NEW_LINE>QMMObject object = event.getObject();<NEW_LINE>if (object instanceof QMMStatementExecuteInfo) {<NEW_LINE>QMMStatementExecuteInfo stmtExec = (QMMStatementExecuteInfo) object;<NEW_LINE>if (dsContainer == null) {<NEW_LINE>QMMConnectionInfo session = stmtExec.getStatement().getConnection();<NEW_LINE>DBPProject project = session.getProject();<NEW_LINE>String containerId = session.getContainerId();<NEW_LINE>if (project != null) {<NEW_LINE>dsContainer = project.getDataSourceRegistry().getDataSource(containerId);<NEW_LINE>} else {<NEW_LINE>dsContainer = DBUtils.findDataSource(containerId);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>String queryString = stmtExec.getQueryString();<NEW_LINE>if (!CommonUtils.isEmptyTrimmed(queryString)) {<NEW_LINE>if (sql.length() > 0) {<NEW_LINE>// $NON-NLS-1$<NEW_LINE>sql.append("\n");<NEW_LINE>}<NEW_LINE>queryString = queryString.trim();<NEW_LINE>sql.append(queryString);<NEW_LINE>if (!queryString.endsWith(SQLConstants.DEFAULT_STATEMENT_DELIMITER)) {<NEW_LINE>// $NON-NLS-1$<NEW_LINE>sql.append(SQLConstants.DEFAULT_STATEMENT_DELIMITER).append("\n");<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (sql.length() > 0) {<NEW_LINE>// $NON-NLS-1$<NEW_LINE>SQLEditorHandlerOpenEditor.// $NON-NLS-1$<NEW_LINE>openSQLConsole(// $NON-NLS-1$<NEW_LINE>UIUtils.getActiveWorkbenchWindow(), // $NON-NLS-1$<NEW_LINE>new SQLNavigatorContext(dsContainer), "QueryManager", sql.toString());<NEW_LINE>}<NEW_LINE>} | (QMEvent) item.getData(); |
1,252,315 | final DeleteAnomalyMonitorResult executeDeleteAnomalyMonitor(DeleteAnomalyMonitorRequest deleteAnomalyMonitorRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(deleteAnomalyMonitorRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<DeleteAnomalyMonitorRequest> request = null;<NEW_LINE>Response<DeleteAnomalyMonitorResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new DeleteAnomalyMonitorRequestProtocolMarshaller(protocolFactory).marshall<MASK><NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);<NEW_LINE>request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Cost Explorer");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "DeleteAnomalyMonitor");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<DeleteAnomalyMonitorResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new DeleteAnomalyMonitorResultJsonUnmarshaller());<NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | (super.beforeMarshalling(deleteAnomalyMonitorRequest)); |
627,558 | public void testXAOptionARequired() throws Exception {<NEW_LINE>String deliveryID = "MD_test1a";<NEW_LINE>prepareTRA();<NEW_LINE>// construct a FVTMessage<NEW_LINE>FVTMessage message = new FVTMessage();<NEW_LINE><MASK><NEW_LINE>// Add a FVTXAResourceImpl for this delivery.<NEW_LINE>message.addXAResource("CMTNonJMSRequired", 11, new FVTXAResourceImpl());<NEW_LINE>// Add a option A delivery.<NEW_LINE>Method m = MessageListener.class.getMethod("onStringMessage", new Class[] { String.class });<NEW_LINE>message.add("CMTNonJMSRequired", "message1", m, 11);<NEW_LINE>message.add("CMTNonJMSRequired", "message2", m, 11);<NEW_LINE>System.out.println(message.toString());<NEW_LINE>baseProvider.sendDirectMessage(deliveryID, message);<NEW_LINE>MessageEndpointTestResults results = baseProvider.getTestResult(deliveryID);<NEW_LINE>assertTrue("isDeliveryTransacted returns true for a method with the Required attribute.", results.isDeliveryTransacted());<NEW_LINE>assertTrue("Number of messages delivered is 2", results.getNumberOfMessagesDelivered() == 2);<NEW_LINE>assertTrue("Delivery option A is used for this test.", results.optionAMessageDeliveryUsed());<NEW_LINE>// assertTrue("This message delivery is in a global transaction context.", results.mdbInvokedInGlobalTransactionContext());<NEW_LINE>assertTrue("The commit is driven on the XAResource provided by TRA.", results.raXaResourceCommitWasDriven());<NEW_LINE>assertTrue("The RA XAResource should be enlisted in the global transaction.", results.raXaResourceEnlisted());<NEW_LINE>baseProvider.releaseDeliveryId(deliveryID);<NEW_LINE>} | message.addTestResult("CMTNonJMSRequired", 11); |
1,730,779 | private File unpackFromJarURL(URL url, String fileName, ClassLoader cl) {<NEW_LINE>ZipFile zip = null;<NEW_LINE>try {<NEW_LINE><MASK><NEW_LINE>int idx1 = path.lastIndexOf(".jar!");<NEW_LINE>if (idx1 == -1) {<NEW_LINE>idx1 = path.lastIndexOf(".zip!");<NEW_LINE>}<NEW_LINE>int idx2 = path.lastIndexOf(".jar!", idx1 - 1);<NEW_LINE>if (idx2 == -1) {<NEW_LINE>idx2 = path.lastIndexOf(".zip!", idx1 - 1);<NEW_LINE>}<NEW_LINE>if (idx2 == -1) {<NEW_LINE>File file = new File(decodeURIComponent(path.substring(5, idx1 + 4), false));<NEW_LINE>zip = new ZipFile(file);<NEW_LINE>} else {<NEW_LINE>String s = path.substring(idx2 + 6, idx1 + 4);<NEW_LINE>File file = resolveFile(s);<NEW_LINE>zip = new ZipFile(file);<NEW_LINE>}<NEW_LINE>Enumeration<? extends ZipEntry> entries = zip.entries();<NEW_LINE>while (entries.hasMoreElements()) {<NEW_LINE>ZipEntry entry = entries.nextElement();<NEW_LINE>String name = entry.getName();<NEW_LINE>if (name.startsWith(fileName)) {<NEW_LINE>if (name.endsWith("/")) {<NEW_LINE>// Directory<NEW_LINE>cache.cacheDir(name);<NEW_LINE>} else {<NEW_LINE>try (InputStream is = zip.getInputStream(entry)) {<NEW_LINE>cache.cacheFile(name, is, !enableCaching);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} catch (IOException e) {<NEW_LINE>throw new VertxException(FileSystemImpl.getFileAccessErrorMessage("unpack", url.toString()), e);<NEW_LINE>} finally {<NEW_LINE>closeQuietly(zip);<NEW_LINE>}<NEW_LINE>return cache.getFile(fileName);<NEW_LINE>} | String path = url.getPath(); |
508,441 | public Num pow(Num n) {<NEW_LINE>// There is no BigDecimal.pow(BigDecimal). We could do:<NEW_LINE>// double Math.pow(double delegate.doubleValue(), double n)<NEW_LINE>// But that could overflow any of the three doubles.<NEW_LINE>// Instead perform:<NEW_LINE>// x^(a+b) = x^a * x^b<NEW_LINE>// Where:<NEW_LINE>// n = a+b<NEW_LINE>// a is a whole number (make sure it doesn't overflow int)<NEW_LINE>// remainder 0 <= b < 1<NEW_LINE>// So:<NEW_LINE>// x^a uses PrecisionNum ((PrecisionNum) x).pow(int a) cannot overflow Num<NEW_LINE>// x^b uses double Math.pow(double x, double b) cannot overflow double because b<NEW_LINE>// < 1.<NEW_LINE>// As suggested: https://stackoverflow.com/a/3590314<NEW_LINE>// get n = a+b, same precision as n<NEW_LINE>BigDecimal aplusb = (((DecimalNum) n).delegate);<NEW_LINE>// get the remainder 0 <= b < 1, looses precision as double<NEW_LINE>BigDecimal b = aplusb.remainder(BigDecimal.ONE);<NEW_LINE>// bDouble looses precision<NEW_LINE><MASK><NEW_LINE>// get the whole number a<NEW_LINE>BigDecimal a = aplusb.subtract(b);<NEW_LINE>// convert a to an int, fails on overflow<NEW_LINE>int aInt = a.intValueExact();<NEW_LINE>// use BigDecimal pow(int)<NEW_LINE>BigDecimal xpowa = delegate.pow(aInt);<NEW_LINE>// use double pow(double, double)<NEW_LINE>double xpowb = Math.pow(delegate.doubleValue(), bDouble);<NEW_LINE>// use PrecisionNum.multiply(PrecisionNum)<NEW_LINE>BigDecimal result = xpowa.multiply(new BigDecimal(xpowb));<NEW_LINE>return new DecimalNum(result.toString());<NEW_LINE>} | double bDouble = b.doubleValue(); |
1,631,059 | static void render(final Comment comment, final RenderContext renderContext, final int depth) throws FrameworkException {<NEW_LINE>String _content = comment.getContent();<NEW_LINE>// Avoid rendering existing @structr comments since those comments are<NEW_LINE>// created depending on the visiblity settings of individual nodes. If<NEW_LINE>// those comments are rendered, there will be duplicates in a round-<NEW_LINE>// trip export/import test.<NEW_LINE>if (!_content.contains("@structr:")) {<NEW_LINE>try {<NEW_LINE>final SecurityContext securityContext = comment.getSecurityContext();<NEW_LINE>final RenderContext.EditMode edit = renderContext.getEditMode(securityContext.getUser(false));<NEW_LINE>final <MASK><NEW_LINE>if (RenderContext.EditMode.DEPLOYMENT.equals(edit)) {<NEW_LINE>DOMNode.renderDeploymentExportComments(comment, buf, true);<NEW_LINE>} else {<NEW_LINE>_content = comment.getPropertyWithVariableReplacement(renderContext, StructrApp.key(Content.class, "content"));<NEW_LINE>}<NEW_LINE>buf.append("<!--").append(_content).append("-->");<NEW_LINE>} catch (Throwable t) {<NEW_LINE>// catch exception to prevent ugly status 500 error pages in frontend.<NEW_LINE>final Logger logger = LoggerFactory.getLogger(Content.class);<NEW_LINE>logger.error("", t);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | AsyncBuffer buf = renderContext.getBuffer(); |
687,413 | protected void merge(double mindist, int x, int y) {<NEW_LINE><MASK><NEW_LINE>// more efficient<NEW_LINE>assert y < x;<NEW_LINE>final int xx = mat.clustermap[x], yy = mat.clustermap[y];<NEW_LINE>final int sizex = builder.getSize(xx), sizey = builder.getSize(yy);<NEW_LINE>int zz = builder.strictAdd(xx, linkage.restore(mindist, builder.isSquared), yy);<NEW_LINE>assert builder.getSize(zz) == sizex + sizey;<NEW_LINE>// Since y < x, prefer keeping y, dropping x.<NEW_LINE>mat.clustermap[y] = zz;<NEW_LINE>// deactivate<NEW_LINE>mat.clustermap[x] = -1;<NEW_LINE>updateMatrix(mindist, x, y, sizex, sizey);<NEW_LINE>} | assert x >= 0 && y >= 0; |
691,260 | private static DiffElement createDiffElement(@Nonnull DiffContent content) {<NEW_LINE>if (content instanceof EmptyContent) {<NEW_LINE>return new DiffElement() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public String getPath() {<NEW_LINE>return "";<NEW_LINE>}<NEW_LINE><NEW_LINE>@Nonnull<NEW_LINE>@Override<NEW_LINE>public String getName() {<NEW_LINE>return "Nothing";<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public long getSize() {<NEW_LINE>return -1;<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public long getTimeStamp() {<NEW_LINE>return -1;<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public boolean isContainer() {<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public DiffElement[] getChildren() throws IOException {<NEW_LINE>return EMPTY_ARRAY;<NEW_LINE>}<NEW_LINE><NEW_LINE>@Nullable<NEW_LINE>@Override<NEW_LINE>public byte[] getContent() throws IOException {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public Object getValue() {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>};<NEW_LINE>}<NEW_LINE>if (content instanceof DirectoryContent) {<NEW_LINE>return new VirtualFileDiffElement(((DirectoryContent) content).getFile());<NEW_LINE>}<NEW_LINE>if (content instanceof FileContent && content.getContentType() instanceof ArchiveFileType) {<NEW_LINE>return new ArchiveFileDiffElement(((FileContent) content).getFile());<NEW_LINE>}<NEW_LINE>throw new IllegalArgumentException(content.getClass() + <MASK><NEW_LINE>} | " " + content.getContentType()); |
345,400 | public final Response containerContents(@Context final HttpServletRequest req, @Context final HttpServletResponse res, @QueryParam("containerId") final String containerId, @QueryParam("contentInode") final String contentInode) throws DotDataException, IOException {<NEW_LINE>final InitDataObject initData = webResource.init(req, res, true);<NEW_LINE>final User user = initData.getUser();<NEW_LINE>try {<NEW_LINE>final PageMode mode = PageMode.get(req);<NEW_LINE>final Container container = APILocator.getContainerAPI().find(containerId, user, !mode.isAdmin);<NEW_LINE>final org.apache.velocity.context.Context context = VelocityUtil.getWebContext(req, res);<NEW_LINE>final Contentlet contentlet = APILocator.getContentletAPI().find(contentInode, user, !mode.isAdmin);<NEW_LINE>final StringWriter inputWriter = new StringWriter();<NEW_LINE>final StringWriter outputWriter = new StringWriter();<NEW_LINE>inputWriter.append("#set ($contentletList").append(container.getIdentifier()).append(" = [").append(contentlet.getIdentifier()).append("] )").append("#set ($totalSize").append(container.getIdentifier()).append("=").append("1").append(")").append("#parseContainer(\"").append(container.getIdentifier()).append("\")");<NEW_LINE>VelocityUtil.getEngine().evaluate(context, outputWriter, this.getClass().getName(), IOUtils.toInputStream(inputWriter.toString()));<NEW_LINE>final Map<String, String> <MASK><NEW_LINE>response.put("render", outputWriter.toString());<NEW_LINE>return Response.ok(response).build();<NEW_LINE>} catch (DotSecurityException e) {<NEW_LINE>throw new ForbiddenException(e);<NEW_LINE>}<NEW_LINE>} | response = new HashMap<>(); |
1,138,965 | private static String[] resolveHttpProxy(final String httpProxy) {<NEW_LINE>final URI proxyUri = URI.create(httpProxy);<NEW_LINE>int port = proxyUri.getPort();<NEW_LINE>if (port == -1) {<NEW_LINE>if (Objects.equals("http", proxyUri.getScheme())) {<NEW_LINE>port = 80;<NEW_LINE>}<NEW_LINE>if (Objects.equals("https", proxyUri.getScheme())) {<NEW_LINE>port = 443;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>final String hostUrl = proxyUri.getScheme() + "://" + proxyUri.getHost() + ":" + port;<NEW_LINE>final String usernamePassword = proxyUri.getUserInfo();<NEW_LINE>if (StringUtils.isNotBlank(usernamePassword)) {<NEW_LINE>final String username;<NEW_LINE>final String password;<NEW_LINE>final int <MASK><NEW_LINE>if (atColon >= 0) {<NEW_LINE>username = usernamePassword.substring(0, atColon);<NEW_LINE>password = usernamePassword.substring(atColon + 1);<NEW_LINE>} else {<NEW_LINE>username = usernamePassword;<NEW_LINE>password = null;<NEW_LINE>}<NEW_LINE>return new String[] { hostUrl, username, password };<NEW_LINE>} else {<NEW_LINE>return new String[] { hostUrl };<NEW_LINE>}<NEW_LINE>} | atColon = usernamePassword.indexOf(':'); |
960,884 | private static TscOutput parseTscOutput(String outputString) {<NEW_LINE>Matcher m = errorRE.matcher(outputString);<NEW_LINE>TscOutput error = new TscOutput();<NEW_LINE>if (m.matches()) {<NEW_LINE>String[] pos = m.group(2).split(",");<NEW_LINE>error.position = new SourcePosition(new File(m.group(1)), null, Integer.parseInt(pos[0]), Integer.parseInt(pos[1]));<NEW_LINE>StringBuilder sb = new StringBuilder<MASK><NEW_LINE>sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));<NEW_LINE>if (sb.charAt(sb.length() - 1) == '.') {<NEW_LINE>sb.deleteCharAt(sb.length() - 1);<NEW_LINE>}<NEW_LINE>error.message = sb.toString();<NEW_LINE>} else {<NEW_LINE>error.message = outputString;<NEW_LINE>}<NEW_LINE>return error;<NEW_LINE>} | (m.group(3)); |
515,150 | private void loadFromAttributes(@Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {<NEW_LINE>TypedArray a = ThemeEnforcement.obtainStyledAttributes(context, attrs, R.styleable.Tooltip, defStyleAttr, defStyleRes);<NEW_LINE>arrowSize = context.getResources().getDimensionPixelSize(R.dimen.mtrl_tooltip_arrowSize);<NEW_LINE>setShapeAppearanceModel(getShapeAppearanceModel().toBuilder().setBottomEdge(createMarkerEdge<MASK><NEW_LINE>setText(a.getText(R.styleable.Tooltip_android_text));<NEW_LINE>TextAppearance textAppearance = MaterialResources.getTextAppearance(context, a, R.styleable.Tooltip_android_textAppearance);<NEW_LINE>if (textAppearance != null && a.hasValue(R.styleable.Tooltip_android_textColor)) {<NEW_LINE>textAppearance.setTextColor(MaterialResources.getColorStateList(context, a, R.styleable.Tooltip_android_textColor));<NEW_LINE>}<NEW_LINE>setTextAppearance(textAppearance);<NEW_LINE>int onBackground = MaterialColors.getColor(context, R.attr.colorOnBackground, TooltipDrawable.class.getCanonicalName());<NEW_LINE>int background = MaterialColors.getColor(context, android.R.attr.colorBackground, TooltipDrawable.class.getCanonicalName());<NEW_LINE>int backgroundTintDefault = MaterialColors.layer(ColorUtils.setAlphaComponent(background, (int) (0.9f * 255)), ColorUtils.setAlphaComponent(onBackground, (int) (0.6f * 255)));<NEW_LINE>setFillColor(ColorStateList.valueOf(a.getColor(R.styleable.Tooltip_backgroundTint, backgroundTintDefault)));<NEW_LINE>setStrokeColor(ColorStateList.valueOf(MaterialColors.getColor(context, R.attr.colorSurface, TooltipDrawable.class.getCanonicalName())));<NEW_LINE>padding = a.getDimensionPixelSize(R.styleable.Tooltip_android_padding, 0);<NEW_LINE>minWidth = a.getDimensionPixelSize(R.styleable.Tooltip_android_minWidth, 0);<NEW_LINE>minHeight = a.getDimensionPixelSize(R.styleable.Tooltip_android_minHeight, 0);<NEW_LINE>layoutMargin = a.getDimensionPixelSize(R.styleable.Tooltip_android_layout_margin, 0);<NEW_LINE>a.recycle();<NEW_LINE>} | ()).build()); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.