idx int32 46 1.86M | input stringlengths 321 6.6k | target stringlengths 9 1.24k |
|---|---|---|
1,824,246 | public static DescribeAntChainContractProjectsResponse unmarshall(DescribeAntChainContractProjectsResponse describeAntChainContractProjectsResponse, UnmarshallerContext _ctx) {<NEW_LINE>describeAntChainContractProjectsResponse.setRequestId(_ctx.stringValue("DescribeAntChainContractProjectsResponse.RequestId"));<NEW_LINE>Result result = new Result();<NEW_LINE>Pagination pagination = new Pagination();<NEW_LINE>pagination.setPageSize(_ctx.integerValue("DescribeAntChainContractProjectsResponse.Result.Pagination.PageSize"));<NEW_LINE>pagination.setPageNumber(_ctx.integerValue("DescribeAntChainContractProjectsResponse.Result.Pagination.PageNumber"));<NEW_LINE>pagination.setTotalCount<MASK><NEW_LINE>result.setPagination(pagination);<NEW_LINE>List<ContractProjectsItem> contractProjects = new ArrayList<ContractProjectsItem>();<NEW_LINE>for (int i = 0; i < _ctx.lengthValue("DescribeAntChainContractProjectsResponse.Result.ContractProjects.Length"); i++) {<NEW_LINE>ContractProjectsItem contractProjectsItem = new ContractProjectsItem();<NEW_LINE>contractProjectsItem.setUpdateTime(_ctx.longValue("DescribeAntChainContractProjectsResponse.Result.ContractProjects[" + i + "].UpdateTime"));<NEW_LINE>contractProjectsItem.setConsortiumId(_ctx.stringValue("DescribeAntChainContractProjectsResponse.Result.ContractProjects[" + i + "].ConsortiumId"));<NEW_LINE>contractProjectsItem.setCreateTime(_ctx.longValue("DescribeAntChainContractProjectsResponse.Result.ContractProjects[" + i + "].CreateTime"));<NEW_LINE>contractProjectsItem.setProjectId(_ctx.stringValue("DescribeAntChainContractProjectsResponse.Result.ContractProjects[" + i + "].ProjectId"));<NEW_LINE>contractProjectsItem.setProjectName(_ctx.stringValue("DescribeAntChainContractProjectsResponse.Result.ContractProjects[" + i + "].ProjectName"));<NEW_LINE>contractProjectsItem.setProjectVersion(_ctx.stringValue("DescribeAntChainContractProjectsResponse.Result.ContractProjects[" + i + "].ProjectVersion"));<NEW_LINE>contractProjectsItem.setProjectDescription(_ctx.stringValue("DescribeAntChainContractProjectsResponse.Result.ContractProjects[" + i + "].ProjectDescription"));<NEW_LINE>contractProjects.add(contractProjectsItem);<NEW_LINE>}<NEW_LINE>result.setContractProjects(contractProjects);<NEW_LINE>describeAntChainContractProjectsResponse.setResult(result);<NEW_LINE>return describeAntChainContractProjectsResponse;<NEW_LINE>} | (_ctx.integerValue("DescribeAntChainContractProjectsResponse.Result.Pagination.TotalCount")); |
1,744,626 | private FileEntry readEntry(final BufferedReader reader) throws IOException {<NEW_LINE>final String name = reader.readLine();<NEW_LINE>if (name != null) {<NEW_LINE>final <MASK><NEW_LINE>final boolean directory = Boolean.parseBoolean(reader.readLine());<NEW_LINE>if (directory) {<NEW_LINE>final boolean empty = Boolean.parseBoolean(reader.readLine());<NEW_LINE>final long modified = Long.parseLong(reader.readLine());<NEW_LINE>final int permissions = Integer.parseInt(reader.readLine(), 8);<NEW_LINE>return new FileEntry(file, empty, modified, permissions);<NEW_LINE>} else {<NEW_LINE>final long size = Long.parseLong(reader.readLine());<NEW_LINE>final String md5 = reader.readLine();<NEW_LINE>final boolean jarFile = Boolean.parseBoolean(reader.readLine());<NEW_LINE>final boolean packed = Boolean.parseBoolean(reader.readLine());<NEW_LINE>final boolean signed = Boolean.parseBoolean(reader.readLine());<NEW_LINE>final long modified = Long.parseLong(reader.readLine());<NEW_LINE>final int permissions = Integer.parseInt(reader.readLine(), 8);<NEW_LINE>return new FileEntry(file, size, md5, jarFile, packed, signed, modified, permissions);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return null;<NEW_LINE>} | File file = new File(name); |
933,906 | // auto-generated, see spoon.generating.CloneVisitorGenerator<NEW_LINE>public <T> void visitCtConstructor(final spoon.reflect.declaration.CtConstructor<T> c) {<NEW_LINE>spoon.reflect.declaration.CtConstructor<T> aCtConstructor = c.getFactory().Core().createConstructor();<NEW_LINE>this.builder.copy(c, aCtConstructor);<NEW_LINE>aCtConstructor.setAnnotations(this.cloneHelper.clone(c.getAnnotations()));<NEW_LINE>aCtConstructor.setParameters(this.cloneHelper.clone<MASK><NEW_LINE>aCtConstructor.setThrownTypes(this.cloneHelper.clone(c.getThrownTypes()));<NEW_LINE>aCtConstructor.setFormalCtTypeParameters(this.cloneHelper.clone(c.getFormalCtTypeParameters()));<NEW_LINE>aCtConstructor.setBody(this.cloneHelper.clone(c.getBody()));<NEW_LINE>aCtConstructor.setComments(this.cloneHelper.clone(c.getComments()));<NEW_LINE>this.cloneHelper.tailor(c, aCtConstructor);<NEW_LINE>this.other = aCtConstructor;<NEW_LINE>} | (c.getParameters())); |
8,904 | private Value emitCompareAndSwap(boolean isLogic, LIRKind accessKind, Value address, Value expectedValue, Value newValue, Value trueValue, Value falseValue) {<NEW_LINE>ValueKind<?<MASK><NEW_LINE>assert kind.equals(expectedValue.getValueKind());<NEW_LINE>AMD64AddressValue addressValue = asAddressValue(address);<NEW_LINE>LIRKind integerAccessKind = accessKind;<NEW_LINE>Value reinterpretedExpectedValue = expectedValue;<NEW_LINE>Value reinterpretedNewValue = newValue;<NEW_LINE>boolean isXmm = ((AMD64Kind) accessKind.getPlatformKind()).isXMM();<NEW_LINE>if (isXmm) {<NEW_LINE>if (accessKind.getPlatformKind().equals(AMD64Kind.SINGLE)) {<NEW_LINE>integerAccessKind = LIRKind.fromJavaKind(target().arch, JavaKind.Int);<NEW_LINE>} else {<NEW_LINE>integerAccessKind = LIRKind.fromJavaKind(target().arch, JavaKind.Long);<NEW_LINE>}<NEW_LINE>reinterpretedExpectedValue = arithmeticLIRGen.emitReinterpret(integerAccessKind, expectedValue);<NEW_LINE>reinterpretedNewValue = arithmeticLIRGen.emitReinterpret(integerAccessKind, newValue);<NEW_LINE>}<NEW_LINE>AMD64Kind memKind = (AMD64Kind) integerAccessKind.getPlatformKind();<NEW_LINE>RegisterValue aRes = AMD64.rax.asValue(integerAccessKind);<NEW_LINE>AllocatableValue allocatableNewValue = asAllocatable(reinterpretedNewValue, integerAccessKind);<NEW_LINE>emitMove(aRes, reinterpretedExpectedValue);<NEW_LINE>append(new CompareAndSwapOp(memKind, aRes, addressValue, aRes, allocatableNewValue));<NEW_LINE>if (isLogic) {<NEW_LINE>assert trueValue.getValueKind().equals(falseValue.getValueKind());<NEW_LINE>return emitCondMoveOp(Condition.EQ, trueValue, falseValue, false, false);<NEW_LINE>} else {<NEW_LINE>if (isXmm) {<NEW_LINE>return arithmeticLIRGen.emitReinterpret(accessKind, aRes);<NEW_LINE>} else {<NEW_LINE>Variable result = newVariable(kind);<NEW_LINE>emitMove(result, aRes);<NEW_LINE>return result;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | > kind = newValue.getValueKind(); |
812,688 | public void loadImages() {<NEW_LINE>// gameplay-specific images<NEW_LINE>if (isGameplay()) {<NEW_LINE>// combo burst images<NEW_LINE>if (GameImage.COMBO_BURST.hasBeatmapSkinImages() || (!GameImage.COMBO_BURST.hasBeatmapSkinImage() && GameImage.COMBO_BURST.getImages() != null))<NEW_LINE>comboBurstImages = GameImage.COMBO_BURST.getImages();<NEW_LINE>else<NEW_LINE>comboBurstImages = new Image[] { GameImage.COMBO_BURST.getImage() };<NEW_LINE>// scorebar-colour animation<NEW_LINE>scorebarColour = null;<NEW_LINE>if (GameImage.SCOREBAR_COLOUR.getImages() != null)<NEW_LINE>scorebarColour = GameImage.SCOREBAR_COLOUR.getAnimation();<NEW_LINE>// default symbol images<NEW_LINE>defaultSymbols = new Image[10];<NEW_LINE>defaultSymbols[0] = GameImage.DEFAULT_0.getImage();<NEW_LINE>defaultSymbols[1] = GameImage.DEFAULT_1.getImage();<NEW_LINE>defaultSymbols[2] = GameImage.DEFAULT_2.getImage();<NEW_LINE>defaultSymbols[3] = GameImage.DEFAULT_3.getImage();<NEW_LINE>defaultSymbols[4] = GameImage.DEFAULT_4.getImage();<NEW_LINE>defaultSymbols[5] = GameImage.DEFAULT_5.getImage();<NEW_LINE>defaultSymbols[6] = GameImage.DEFAULT_6.getImage();<NEW_LINE>defaultSymbols[7] = GameImage.DEFAULT_7.getImage();<NEW_LINE>defaultSymbols[8] = GameImage.DEFAULT_8.getImage();<NEW_LINE>defaultSymbols[9] = GameImage.DEFAULT_9.getImage();<NEW_LINE>}<NEW_LINE>// score symbol images<NEW_LINE>scoreSymbols = new HashMap<Character, Image>(14);<NEW_LINE>scoreSymbols.put('0', GameImage.SCORE_0.getImage());<NEW_LINE>scoreSymbols.put('1', GameImage.SCORE_1.getImage());<NEW_LINE>scoreSymbols.put('2', GameImage.SCORE_2.getImage());<NEW_LINE>scoreSymbols.put('3', GameImage.SCORE_3.getImage());<NEW_LINE>scoreSymbols.put('4', GameImage.SCORE_4.getImage());<NEW_LINE>scoreSymbols.put('5', GameImage.SCORE_5.getImage());<NEW_LINE>scoreSymbols.put('6', GameImage.SCORE_6.getImage());<NEW_LINE>scoreSymbols.put('7', GameImage.SCORE_7.getImage());<NEW_LINE>scoreSymbols.put('8', GameImage.SCORE_8.getImage());<NEW_LINE>scoreSymbols.put('9', GameImage.SCORE_9.getImage());<NEW_LINE>scoreSymbols.put(',', GameImage.SCORE_COMMA.getImage());<NEW_LINE>scoreSymbols.put('.', <MASK><NEW_LINE>scoreSymbols.put('%', GameImage.SCORE_PERCENT.getImage());<NEW_LINE>scoreSymbols.put('x', GameImage.SCORE_X.getImage());<NEW_LINE>// hit result images<NEW_LINE>hitResults = new Image[HIT_MAX];<NEW_LINE>hitResults[HIT_MISS] = GameImage.HIT_MISS.getImage();<NEW_LINE>hitResults[HIT_50] = GameImage.HIT_50.getImage();<NEW_LINE>hitResults[HIT_100] = GameImage.HIT_100.getImage();<NEW_LINE>hitResults[HIT_300] = GameImage.HIT_300.getImage();<NEW_LINE>hitResults[HIT_100K] = GameImage.HIT_100K.getImage();<NEW_LINE>hitResults[HIT_300K] = GameImage.HIT_300K.getImage();<NEW_LINE>hitResults[HIT_300G] = GameImage.HIT_300G.getImage();<NEW_LINE>hitResults[HIT_SLIDER10] = GameImage.HIT_SLIDER10.getImage();<NEW_LINE>hitResults[HIT_SLIDER30] = GameImage.HIT_SLIDER30.getImage();<NEW_LINE>} | GameImage.SCORE_DOT.getImage()); |
1,437,087 | public static void main(String[] args) {<NEW_LINE>if (args.length < minArgs) {<NEW_LINE>System.out.println(usage.toString());<NEW_LINE>System.exit(-1);<NEW_LINE>}<NEW_LINE>TreebankLangParserParams tlpp = new EnglishTreebankParserParams();<NEW_LINE>DiskTreebank tb = null;<NEW_LINE>String encoding = "UTF-8";<NEW_LINE>TregexPattern rootMatch = null;<NEW_LINE>for (int i = 0; i < args.length; i++) {<NEW_LINE>if (args[i].startsWith("-")) {<NEW_LINE>switch(args[i]) {<NEW_LINE>case "-l":<NEW_LINE>Language lang = Language.valueOf(args[++i].trim());<NEW_LINE>tlpp = lang.params;<NEW_LINE>break;<NEW_LINE>case "-e":<NEW_LINE>encoding = args[++i];<NEW_LINE>break;<NEW_LINE>default:<NEW_LINE>System.out.println(usage.toString());<NEW_LINE>System.exit(-1);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>rootMatch = TregexPattern.compile("@" + args[i++]);<NEW_LINE>if (tb == null) {<NEW_LINE>if (tlpp == null) {<NEW_LINE>System.out.println(usage.toString());<NEW_LINE>System.exit(-1);<NEW_LINE>} else {<NEW_LINE>tlpp.setInputEncoding(encoding);<NEW_LINE>tlpp.setOutputEncoding(encoding);<NEW_LINE>tb = tlpp.diskTreebank();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>tb.loadPath(args[i++]);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>Counter<String> rhsCounter = new ClassicCounter<>();<NEW_LINE>for (Tree t : tb) {<NEW_LINE>TregexMatcher m = rootMatch.matcher(t);<NEW_LINE>while (m.findNextMatchingNode()) {<NEW_LINE>Tree match = m.getMatch();<NEW_LINE>StringBuilder sb = new StringBuilder();<NEW_LINE>for (Tree kid : match.children()) sb.append(kid.value()).append(" ");<NEW_LINE>rhsCounter.incrementCount(sb.<MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>List<String> biggestKeys = new ArrayList<>(rhsCounter.keySet());<NEW_LINE>Collections.sort(biggestKeys, Counters.toComparatorDescending(rhsCounter));<NEW_LINE>PrintWriter pw = tlpp.pw();<NEW_LINE>for (String rhs : biggestKeys) pw.printf("%s\t%d%n", rhs, (int) rhsCounter.getCount(rhs));<NEW_LINE>pw.close();<NEW_LINE>} | toString().trim()); |
362,682 | public void read(org.apache.thrift.protocol.TProtocol iprot, add_filter_result struct) throws org.apache.thrift.TException {<NEW_LINE>org.<MASK><NEW_LINE>iprot.readStructBegin();<NEW_LINE>while (true) {<NEW_LINE>schemeField = iprot.readFieldBegin();<NEW_LINE>if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>switch(schemeField.id) {<NEW_LINE>case // EX<NEW_LINE>1:<NEW_LINE>if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {<NEW_LINE>if (struct.ex == null) {<NEW_LINE>struct.ex = new rpc_management_exception();<NEW_LINE>}<NEW_LINE>struct.ex.read(iprot);<NEW_LINE>struct.setExIsSet(true);<NEW_LINE>} else {<NEW_LINE>org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);<NEW_LINE>}<NEW_LINE>break;<NEW_LINE>default:<NEW_LINE>org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);<NEW_LINE>}<NEW_LINE>iprot.readFieldEnd();<NEW_LINE>}<NEW_LINE>iprot.readStructEnd();<NEW_LINE>// check for required fields of primitive type, which can't be checked in the validate method<NEW_LINE>struct.validate();<NEW_LINE>} | apache.thrift.protocol.TField schemeField; |
422,368 | public Object execute(Object iThis, final OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParams, OCommandContext iContext) {<NEW_LINE>Object value = iParams[0];<NEW_LINE>if (value instanceof OSQLFilterItemVariable)<NEW_LINE>value = ((OSQLFilterItemVariable) value).getValue(iCurrentRecord, iCurrentResult, iContext);<NEW_LINE>if (value == null)<NEW_LINE>return Collections.emptySet();<NEW_LINE>if (iParams.length == 1) {<NEW_LINE>// AGGREGATION MODE (STATEFUL)<NEW_LINE>if (context == null) {<NEW_LINE>// ADD ALL THE ITEMS OF THE FIRST COLLECTION<NEW_LINE>if (value instanceof Collection) {<NEW_LINE>context = ((<MASK><NEW_LINE>} else if (value instanceof Iterator) {<NEW_LINE>context = (Iterator) value;<NEW_LINE>} else if (value instanceof Iterable) {<NEW_LINE>context = ((Iterable) value).iterator();<NEW_LINE>} else {<NEW_LINE>context = Arrays.asList(value).iterator();<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>Iterator contextIterator = null;<NEW_LINE>if (context instanceof Iterator) {<NEW_LINE>contextIterator = (Iterator) context;<NEW_LINE>} else if (OMultiValue.isMultiValue(context)) {<NEW_LINE>contextIterator = OMultiValue.getMultiValueIterator(context);<NEW_LINE>}<NEW_LINE>context = intersectWith(contextIterator, value);<NEW_LINE>}<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>// IN-LINE MODE (STATELESS)<NEW_LINE>Iterator iterator = OMultiValue.getMultiValueIterator(value, false);<NEW_LINE>for (int i = 1; i < iParams.length; ++i) {<NEW_LINE>value = iParams[i];<NEW_LINE>if (value instanceof OSQLFilterItemVariable)<NEW_LINE>value = ((OSQLFilterItemVariable) value).getValue(iCurrentRecord, iCurrentResult, iContext);<NEW_LINE>if (value != null) {<NEW_LINE>value = intersectWith(iterator, value);<NEW_LINE>iterator = OMultiValue.getMultiValueIterator(value, false);<NEW_LINE>} else {<NEW_LINE>return new ArrayList().iterator();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>List result = new ArrayList();<NEW_LINE>while (iterator.hasNext()) {<NEW_LINE>result.add(iterator.next());<NEW_LINE>}<NEW_LINE>return result;<NEW_LINE>} | Collection) value).iterator(); |
1,849,831 | public void analyze(Program program) {<NEW_LINE>Graph cfg = ProgramUtils.buildControlFlowGraph(program);<NEW_LINE>Graph dom = GraphUtils.buildDominatorGraph(GraphUtils.buildDominatorTree(cfg), cfg.size());<NEW_LINE>DefinitionExtractor defExtractor = new DefinitionExtractor();<NEW_LINE>UsageExtractor useExtractor = new UsageExtractor();<NEW_LINE>IntegerStack stack = new IntegerStack(program.basicBlockCount());<NEW_LINE>stack.push(0);<NEW_LINE>ConstantExtractor constantExtractor = new ConstantExtractor(constants);<NEW_LINE>while (!stack.isEmpty()) {<NEW_LINE>int node = stack.pop();<NEW_LINE>BasicBlock block = program.basicBlockAt(node);<NEW_LINE>if (block.getExceptionVariable() != null) {<NEW_LINE>writes[block.getExceptionVariable<MASK><NEW_LINE>reads[block.getExceptionVariable().getIndex()]++;<NEW_LINE>}<NEW_LINE>for (Instruction insn : block) {<NEW_LINE>insn.acceptVisitor(defExtractor);<NEW_LINE>insn.acceptVisitor(useExtractor);<NEW_LINE>for (Variable var : defExtractor.getDefinedVariables()) {<NEW_LINE>writes[var.getIndex()]++;<NEW_LINE>}<NEW_LINE>for (Variable var : useExtractor.getUsedVariables()) {<NEW_LINE>reads[var.getIndex()]++;<NEW_LINE>}<NEW_LINE>insn.acceptVisitor(constantExtractor);<NEW_LINE>}<NEW_LINE>for (Phi phi : block.getPhis()) {<NEW_LINE>writes[phi.getReceiver().getIndex()] += phi.getIncomings().size();<NEW_LINE>for (Incoming incoming : phi.getIncomings()) {<NEW_LINE>if (writes[incoming.getValue().getIndex()] == 0) {<NEW_LINE>reads[incoming.getValue().getIndex()]++;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>for (int succ : dom.outgoingEdges(node)) {<NEW_LINE>stack.push(succ);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | ().getIndex()]++; |
1,119,106 | protected PortalInfo findDimensionEntryPoint(ServerLevel level) {<NEW_LINE>PortalInfo portalinfo = super.findDimensionEntryPoint(level);<NEW_LINE>level = portalinfo == null || ((PortalInfoBridge) portalinfo).bridge$getWorld() == null ? level : ((PortalInfoBridge) portalinfo).bridge$getWorld();<NEW_LINE>if (portalinfo != null && ((WorldBridge) this.level).bridge$getTypeKey() == LevelStem.OVERWORLD && ((WorldBridge) level).bridge$getTypeKey() == LevelStem.END) {<NEW_LINE>Vec3 vector3d = portalinfo.pos.add(0.0D, -1.0D, 0.0D);<NEW_LINE>PortalInfo newInfo = new PortalInfo(vector3d, <MASK><NEW_LINE>((PortalInfoBridge) newInfo).bridge$setWorld(level);<NEW_LINE>((PortalInfoBridge) newInfo).bridge$setPortalEventInfo(((PortalInfoBridge) portalinfo).bridge$getPortalEventInfo());<NEW_LINE>return newInfo;<NEW_LINE>} else {<NEW_LINE>return portalinfo;<NEW_LINE>}<NEW_LINE>} | Vec3.ZERO, 90.0F, 0.0F); |
1,486,622 | public List<ImageResults> computeErrors() {<NEW_LINE>List<ImageResults> errors = new ArrayList<>();<NEW_LINE>double[] parameters = new double[structure.getParameterCount()];<NEW_LINE>double[] residuals = new double[observations.getObservationCount() * 2];<NEW_LINE>CodecSceneStructureMetric codec = new CodecSceneStructureMetric();<NEW_LINE>codec.encode(structure, parameters);<NEW_LINE>BundleAdjustmentMetricResidualFunction function = new BundleAdjustmentMetricResidualFunction();<NEW_LINE>function.configure(structure, observations);<NEW_LINE>function.process(parameters, residuals);<NEW_LINE>int idx = 0;<NEW_LINE>for (int i = 0; i < observations.viewsRigid.size; i++) {<NEW_LINE>SceneObservations.View v = observations.viewsRigid.data[i];<NEW_LINE>ImageResults r = new ImageResults(v.size());<NEW_LINE>double sumX = 0;<NEW_LINE>double sumY = 0;<NEW_LINE>double meanErrorMag = 0;<NEW_LINE>double maxError = 0;<NEW_LINE>for (int j = 0; j < v.size(); j++) {<NEW_LINE>double x = r.residuals[j * 2] = residuals[idx++];<NEW_LINE>double y = r.residuals[j * 2 + 1] = residuals[idx++];<NEW_LINE>double nerr = r.pointError[j] = Math.sqrt(x * x + y * y);<NEW_LINE>meanErrorMag += nerr;<NEW_LINE>maxError = <MASK><NEW_LINE>sumX += x;<NEW_LINE>sumY += y;<NEW_LINE>}<NEW_LINE>r.biasX = sumX / v.size();<NEW_LINE>r.biasY = sumY / v.size();<NEW_LINE>r.meanError = meanErrorMag / v.size();<NEW_LINE>r.maxError = maxError;<NEW_LINE>errors.add(r);<NEW_LINE>}<NEW_LINE>return errors;<NEW_LINE>} | Math.max(maxError, nerr); |
991,607 | public IRubyObject sync(ThreadContext context, IRubyObject string) {<NEW_LINE>if (flater.avail_in > 0) {<NEW_LINE>switch(flater.sync()) {<NEW_LINE>case com.jcraft.jzlib.JZlib.Z_OK:<NEW_LINE>flater.setInput(string.convertToString().getByteList(<MASK><NEW_LINE>return context.tru;<NEW_LINE>case com.jcraft.jzlib.JZlib.Z_DATA_ERROR:<NEW_LINE>break;<NEW_LINE>default:<NEW_LINE>throw RubyZlib.newStreamError(getRuntime(), "stream error");<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (string.convertToString().getByteList().length() <= 0) {<NEW_LINE>return context.fals;<NEW_LINE>}<NEW_LINE>flater.setInput(string.convertToString().getByteList().bytes(), true);<NEW_LINE>switch(flater.sync()) {<NEW_LINE>case com.jcraft.jzlib.JZlib.Z_OK:<NEW_LINE>return context.tru;<NEW_LINE>case com.jcraft.jzlib.JZlib.Z_DATA_ERROR:<NEW_LINE>return context.fals;<NEW_LINE>default:<NEW_LINE>throw RubyZlib.newStreamError(getRuntime(), "stream error");<NEW_LINE>}<NEW_LINE>} | ).bytes(), true); |
380,286 | public ASTNode visitTableConstraintDef(final TableConstraintDefContext ctx) {<NEW_LINE>ConstraintDefinitionSegment result = new ConstraintDefinitionSegment(ctx.getStart().getStartIndex(), ctx.getStop().getStopIndex());<NEW_LINE>if (null != ctx.constraintClause() && null != ctx.constraintClause().constraintName()) {<NEW_LINE>result.setConstraintName((ConstraintSegment) visit(ctx.constraintClause().constraintName()));<NEW_LINE>}<NEW_LINE>if (null != ctx.KEY() && null != ctx.PRIMARY()) {<NEW_LINE>result.getPrimaryKeyColumns().addAll(getKeyColumnsFromKeyListWithExpression<MASK><NEW_LINE>return result;<NEW_LINE>}<NEW_LINE>if (null != ctx.FOREIGN()) {<NEW_LINE>result.setReferencedTable((SimpleTableSegment) visit(ctx.referenceDefinition()));<NEW_LINE>return result;<NEW_LINE>}<NEW_LINE>if (null != ctx.UNIQUE()) {<NEW_LINE>result.getIndexColumns().addAll(getKeyColumnsFromKeyListWithExpression(ctx.keyListWithExpression()));<NEW_LINE>if (null != ctx.indexName()) {<NEW_LINE>result.setIndexName((IndexSegment) visit(ctx.indexName()));<NEW_LINE>}<NEW_LINE>return result;<NEW_LINE>}<NEW_LINE>if (null != ctx.checkConstraint()) {<NEW_LINE>return result;<NEW_LINE>}<NEW_LINE>result.getIndexColumns().addAll(getKeyColumnsFromKeyListWithExpression(ctx.keyListWithExpression()));<NEW_LINE>if (null != ctx.indexName()) {<NEW_LINE>result.setIndexName((IndexSegment) visit(ctx.indexName()));<NEW_LINE>}<NEW_LINE>return result;<NEW_LINE>} | (ctx.keyListWithExpression())); |
1,005,240 | private Map<String, Boolean> deal(SysSite site, String path) {<NEW_LINE>path = path.replace("\\", CommonConstants.SEPARATOR).replace("//", CommonConstants.SEPARATOR);<NEW_LINE>Map<String, Boolean> <MASK><NEW_LINE>List<FileInfo> list = CmsFileUtils.getFileList(siteComponent.getWebTemplateFilePath(site, path), null);<NEW_LINE>for (FileInfo fileInfo : list) {<NEW_LINE>String filePath = path + fileInfo.getFileName();<NEW_LINE>if (fileInfo.isDirectory()) {<NEW_LINE>map.putAll(deal(site, filePath + CommonConstants.SEPARATOR));<NEW_LINE>} else {<NEW_LINE>CmsPageMetadata metadata = metadataComponent.getTemplateMetadata(siteComponent.getWebTemplateFilePath(site, filePath));<NEW_LINE>if (null != metadata && CommonUtils.notEmpty(metadata.getPublishPath())) {<NEW_LINE>try {<NEW_LINE>String templatePath = SiteComponent.getFullTemplatePath(site, filePath);<NEW_LINE>CmsPageData data = metadataComponent.getTemplateData(siteComponent.getCurrentSiteWebTemplateFilePath(site, filePath));<NEW_LINE>templateComponent.createStaticFile(site, templatePath, metadata.getPublishPath(), null, metadata.getAsMap(data), null);<NEW_LINE>map.put(filePath, true);<NEW_LINE>} catch (IOException | TemplateException e) {<NEW_LINE>map.put(filePath, false);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return map;<NEW_LINE>} | map = new LinkedHashMap<>(); |
837,699 | static void clearCaches(@Nonnull PsiFile injected, @Nonnull DocumentWindowImpl documentWindow) {<NEW_LINE>VirtualFileWindowImpl virtualFile = (VirtualFileWindowImpl) injected.getVirtualFile();<NEW_LINE>PsiManagerEx psiManagerEx = (PsiManagerEx) injected.getManager();<NEW_LINE>if (psiManagerEx.getProject().isDisposed())<NEW_LINE>return;<NEW_LINE>DebugUtil.performPsiModification("injected clearCaches", () -> psiManagerEx.getFileManager()<MASK><NEW_LINE>VirtualFile delegate = virtualFile.getDelegate();<NEW_LINE>if (!delegate.isValid())<NEW_LINE>return;<NEW_LINE>FileViewProvider viewProvider = psiManagerEx.getFileManager().findCachedViewProvider(delegate);<NEW_LINE>if (viewProvider == null)<NEW_LINE>return;<NEW_LINE>for (PsiFile hostFile : ((AbstractFileViewProvider) viewProvider).getCachedPsiFiles()) {<NEW_LINE>// modification of cachedInjectedDocuments must be under InjectedLanguageManagerImpl.ourInjectionPsiLock<NEW_LINE>synchronized (InjectedLanguageManagerImpl.ourInjectionPsiLock) {<NEW_LINE>List<DocumentWindow> cachedInjectedDocuments = getCachedInjectedDocuments(hostFile);<NEW_LINE>for (int i = cachedInjectedDocuments.size() - 1; i >= 0; i--) {<NEW_LINE>DocumentWindow cachedInjectedDocument = cachedInjectedDocuments.get(i);<NEW_LINE>if (cachedInjectedDocument == documentWindow) {<NEW_LINE>cachedInjectedDocuments.remove(i);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | .setViewProvider(virtualFile, null)); |
41,307 | public TypeSpec generateAdapterForCustomType(Type type) {<NEW_LINE>NameAllocator nameAllocator = nameAllocators.getUnchecked(type);<NEW_LINE>ClassName adapterTypeName = abstractAdapterName(type.getType());<NEW_LINE>ClassName typeName = (ClassName) typeName(type.getType());<NEW_LINE>TypeSpec.Builder adapter;<NEW_LINE>if (type instanceof MessageType) {<NEW_LINE>adapter = messageAdapter(nameAllocator, (MessageType) type, typeName, adapterTypeName, null).toBuilder();<NEW_LINE>} else {<NEW_LINE>adapter = enumAdapter(nameAllocator, (EnumType) type, typeName, adapterTypeName).toBuilder();<NEW_LINE>}<NEW_LINE>if (adapterTypeName.enclosingClassName() != null)<NEW_LINE>adapter.addModifiers(STATIC);<NEW_LINE>for (Type nestedType : type.getNestedTypes()) {<NEW_LINE>if (profile.getAdapter(nestedType.getType()) == null) {<NEW_LINE>throw new IllegalArgumentException("Missing custom proto adapter for " + nestedType.getType().getEnclosingTypeOrPackage() + "." + nestedType.getType().getSimpleName() + " when enclosing proto has custom proto adapter.");<NEW_LINE>}<NEW_LINE>adapter<MASK><NEW_LINE>}<NEW_LINE>return adapter.build();<NEW_LINE>} | .addType(generateAdapterForCustomType(nestedType)); |
27,856 | public void run(RegressionEnvironment env) {<NEW_LINE>sendCurrentTime(env, "2002-02-01T09:00:00.000");<NEW_LINE>String epl = "@name('s0') select * from SupportBean#lastevent output first every 1 month";<NEW_LINE>env.compileDeploy<MASK><NEW_LINE>env.sendEventBean(new SupportBean("E1", 1));<NEW_LINE>env.assertListenerInvoked("s0");<NEW_LINE>env.sendEventBean(new SupportBean("E2", 2));<NEW_LINE>sendCurrentTimeWithMinus(env, "2002-03-01T09:00:00.000", 1);<NEW_LINE>env.sendEventBean(new SupportBean("E3", 3));<NEW_LINE>env.assertListenerNotInvoked("s0");<NEW_LINE>sendCurrentTime(env, "2002-03-01T09:00:00.000");<NEW_LINE>env.sendEventBean(new SupportBean("E4", 4));<NEW_LINE>env.assertPropsPerRowLastNew("s0", "theString".split(","), new Object[][] { { "E4" } });<NEW_LINE>env.undeployAll();<NEW_LINE>} | (epl).addListener("s0"); |
712,118 | // submit the map/reduce job.<NEW_LINE>public int run(final String[] args) throws Exception {<NEW_LINE>if (args.length != 5) {<NEW_LINE>return printUsage();<NEW_LINE>}<NEW_LINE>int i;<NEW_LINE>edge_path = new Path(args[0] + "/pr_edge_block");<NEW_LINE>vector_path = new Path(args[0] + "/pr_iv_block");<NEW_LINE>tempmv_path = new Path(args[0] + "/pr_tempmv_block");<NEW_LINE>output_path = new Path(args[0] + "/pr_output_block");<NEW_LINE>vector_unfold_path = new Path(args[0] + "/pr_vector");<NEW_LINE>minmax_path = new Path(args[0] + "/pr_minmax");<NEW_LINE>distr_path = new Path(args[0] + "/pr_distr");<NEW_LINE>number_nodes = Integer.parseInt(args[1]);<NEW_LINE>nreducers = Integer.parseInt(args[2]);<NEW_LINE>niteration = Integer.parseInt(args[3]);<NEW_LINE>block_width = Integer.parseInt(args[4]);<NEW_LINE>local_output_path = args[0] + "/pr_tempmv_block_temp";<NEW_LINE>converge_threshold = ((double) 1.0 / (double) number_nodes) / 50;<NEW_LINE>System.out.println("\n-----===[PEGASUS: A Peta-Scale Graph Mining System]===-----\n");<NEW_LINE>System.out.println("[PEGASUS] Computing PageRank using block method. Max iteration = " + niteration + ", threshold = " + converge_threshold + "\n");<NEW_LINE>fs = FileSystem.get(getConf());<NEW_LINE>// Iteratively calculate neighborhood function.<NEW_LINE>for (i = 0; i < niteration; i++) {<NEW_LINE><MASK><NEW_LINE>RunningJob job = JobClient.runJob(configStage2());<NEW_LINE>Counters c = job.getCounters();<NEW_LINE>long changed = c.getCounter(PrCounters.CONVERGE_CHECK);<NEW_LINE>System.out.println("Iteration = " + i + ", changed reducer = " + changed);<NEW_LINE>if (changed == 0) {<NEW_LINE>System.out.println("PageRank vector converged. Now preparing to finish...");<NEW_LINE>fs.delete(vector_path);<NEW_LINE>fs.delete(tempmv_path);<NEW_LINE>fs.rename(output_path, vector_path);<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>// rotate directory<NEW_LINE>fs.delete(vector_path);<NEW_LINE>fs.delete(tempmv_path);<NEW_LINE>fs.rename(output_path, vector_path);<NEW_LINE>}<NEW_LINE>if (i == niteration) {<NEW_LINE>System.out.println("Reached the max iteration. Now preparing to finish...");<NEW_LINE>}<NEW_LINE>// unfold the block PageRank to plain format<NEW_LINE>System.out.println("Unfolding the block PageRank to plain format...");<NEW_LINE>JobClient.runJob(configStage25());<NEW_LINE>// find min/max of pageranks<NEW_LINE>// System.out.println("Finding minimum and maximum pageranks...");<NEW_LINE>// JobClient.runJob(configStage3());<NEW_LINE>// FileUtil.fullyDelete( FileSystem.getLocal(getConf()), new Path(local_output_path));<NEW_LINE>// String new_path = local_output_path + "/" ;<NEW_LINE>// fs.copyToLocalFile(minmax_path, new Path(new_path) ) ;<NEW_LINE>// MinMaxInfo mmi = PagerankNaive.readMinMax( new_path );<NEW_LINE>// System.out.println("min = " + mmi.min + ", max = " + mmi.max );<NEW_LINE>// find distribution of pageranks<NEW_LINE>// JobClient.runJob(configStage4(mmi.min, mmi.max));<NEW_LINE>System.out.println("\n[PEGASUS] PageRank computed.");<NEW_LINE>System.out.println("[PEGASUS] The final PageRanks are in the HDFS pr_vector.");<NEW_LINE>// System.out.println("[PEGASUS] The minium and maximum PageRanks are in the HDFS pr_minmax.");<NEW_LINE>// System.out.println("[PEGASUS] The histogram of PageRanks in 1000 bins between min_PageRank and max_PageRank are in the HDFS pr_distr.\n");<NEW_LINE>return 0;<NEW_LINE>} | JobClient.runJob(configStage1()); |
403,718 | private void testAdaptableApiSimple(PrintWriter writer) throws UnableToAdaptException {<NEW_LINE>ArtifactContainer artifactContainer = getContainerForDirectory();<NEW_LINE>com.ibm.wsspi.adaptable.module.Container adaptableContainer = amf.getContainer(new File(cacheDirAdapt), new File(cacheDirOverlay), artifactContainer);<NEW_LINE>if (adaptableContainer == null) {<NEW_LINE>writer.println("FAIL: Failed to create adaptable container");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>com.ibm.wsspi.adaptable.module.Entry adaptEntry = adaptableContainer.getEntry("/a/a.txt");<NEW_LINE>if (adaptEntry == null) {<NEW_LINE>writer.println("FAIL: Failed to obtain entry [ /a/a.txt ]");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>Integer entryInteger = adaptEntry.adapt(Integer.class);<NEW_LINE>if (entryInteger == null) {<NEW_LINE>writer.println("FAIL: Failed to adapt entry to Integer");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>if (entryInteger.intValue() != adaptEntry.getName().length()) {<NEW_LINE>writer.println("FAIL: Adapted value [ " + entryInteger + " ]" + " should be [ " + Integer.valueOf(adaptEntry.getName().length()) + " ]");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>com.ibm.wsspi.adaptable.module.Container adaptParent = adaptEntry.getEnclosingContainer();<NEW_LINE>if (adaptParent == null) {<NEW_LINE>writer.println("FAIL: Failed to obtain adaptable parent");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>Integer containerInteger = <MASK><NEW_LINE>if (containerInteger == null) {<NEW_LINE>writer.println("FAIL: Failed to adapt container to Integer");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>if (containerInteger.intValue() != adaptParent.getPath().length()) {<NEW_LINE>writer.println("FAIL: Adapted value [ " + containerInteger + " ]" + " should be [ " + Integer.valueOf(adaptParent.getName().length()) + " ]");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>writer.println("PASS");<NEW_LINE>} | adaptParent.adapt(Integer.class); |
822,875 | default void decodeColumnDisplayOrderState(FacesContext context) {<NEW_LINE>Map<String, String> params = context.getExternalContext().getRequestParameterMap();<NEW_LINE>String columnOrderParam = params.get(getClientId(context) + "_columnOrder");<NEW_LINE>if (LangUtils.isBlank(columnOrderParam)) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>Map<String, ColumnMeta> columMeta = getColumnMeta();<NEW_LINE>columMeta.values().stream().forEach(s -> s.setDisplayPriority(0));<NEW_LINE>String[] <MASK><NEW_LINE>for (int i = 0; i < columnKeys.length; i++) {<NEW_LINE>String columnKey = columnKeys[i];<NEW_LINE>if (LangUtils.isBlank(columnKey)) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>ColumnMeta meta = columMeta.computeIfAbsent(columnKey, k -> new ColumnMeta(k));<NEW_LINE>meta.setDisplayPriority(i);<NEW_LINE>}<NEW_LINE>if (isMultiViewState()) {<NEW_LINE>UITableState ts = getMultiViewState(true);<NEW_LINE>ts.setColumnMeta(columMeta);<NEW_LINE>}<NEW_LINE>} | columnKeys = columnOrderParam.split(","); |
805,734 | private Mono<PagedResponse<VirtualNetworkInner>> listByResourceGroupSinglePageAsync(String resourceGroupName, Context context) {<NEW_LINE>if (this.client.getEndpoint() == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null."));<NEW_LINE>}<NEW_LINE>if (this.client.getSubscriptionId() == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter this.client.getSubscriptionId() is required and cannot be null."));<NEW_LINE>}<NEW_LINE>if (resourceGroupName == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));<NEW_LINE>}<NEW_LINE>final String accept = "application/json";<NEW_LINE>context = <MASK><NEW_LINE>return service.listByResourceGroup(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, this.client.getApiVersion(), accept, context).map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null));<NEW_LINE>} | this.client.mergeContext(context); |
1,663,526 | public VpcDestinationConfiguration unmarshall(JsonUnmarshallerContext context) throws Exception {<NEW_LINE>AwsJsonReader reader = context.getReader();<NEW_LINE>if (!reader.isContainer()) {<NEW_LINE>reader.skipValue();<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>VpcDestinationConfiguration vpcDestinationConfiguration = new VpcDestinationConfiguration();<NEW_LINE>reader.beginObject();<NEW_LINE>while (reader.hasNext()) {<NEW_LINE>String name = reader.nextName();<NEW_LINE>if (name.equals("subnetIds")) {<NEW_LINE>vpcDestinationConfiguration.setSubnetIds(new ListUnmarshaller<String>(StringJsonUnmarshaller.getInstance()).unmarshall(context));<NEW_LINE>} else if (name.equals("securityGroups")) {<NEW_LINE>vpcDestinationConfiguration.setSecurityGroups(new ListUnmarshaller<String>(StringJsonUnmarshaller.getInstance()).unmarshall(context));<NEW_LINE>} else if (name.equals("vpcId")) {<NEW_LINE>vpcDestinationConfiguration.setVpcId(StringJsonUnmarshaller.getInstance().unmarshall(context));<NEW_LINE>} else if (name.equals("roleArn")) {<NEW_LINE>vpcDestinationConfiguration.setRoleArn(StringJsonUnmarshaller.getInstance<MASK><NEW_LINE>} else {<NEW_LINE>reader.skipValue();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>reader.endObject();<NEW_LINE>return vpcDestinationConfiguration;<NEW_LINE>} | ().unmarshall(context)); |
266,040 | public void initialize(SurfaceTexture surfaceTexture, final Runnable completionCallback) {<NEW_LINE>if (mGLThread != null) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>mGLThread = new GLThread(surfaceTexture);<NEW_LINE>mGLThread.start();<NEW_LINE>// On JS thread, get JavaScriptCore context, create EXGL context, call JS callback<NEW_LINE>final GLContext glContext = this;<NEW_LINE>ModuleRegistry moduleRegistry = mManager.getModuleRegistry();<NEW_LINE>final UIManager uiManager = moduleRegistry.getModule(UIManager.class);<NEW_LINE>final JavaScriptContextProvider jsContextProvider = <MASK><NEW_LINE>final RuntimeEnvironmentInterface environment = moduleRegistry.getModule(RuntimeEnvironmentInterface.class);<NEW_LINE>EXGLRegisterThread();<NEW_LINE>uiManager.runOnClientCodeQueueThread(new Runnable() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void run() {<NEW_LINE>long jsContextRef = jsContextProvider.getJavaScriptContextRef();<NEW_LINE>synchronized (uiManager) {<NEW_LINE>if (jsContextRef != 0) {<NEW_LINE>mEXGLCtxId = EXGLContextCreate();<NEW_LINE>EXGLRegisterThread();<NEW_LINE>EXGLContextPrepare(jsContextRef, mEXGLCtxId, glContext);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>mManager.saveContext(glContext);<NEW_LINE>completionCallback.run();<NEW_LINE>}<NEW_LINE>});<NEW_LINE>} | moduleRegistry.getModule(JavaScriptContextProvider.class); |
1,017,990 | private static // parse the index and default fixed leg day count<NEW_LINE>FloatingRateIndex parseIndex(CsvRow row, String leg) {<NEW_LINE>Optional<String> fixedRateOpt = findValue(row, leg, FIXED_RATE_FIELD);<NEW_LINE>Optional<String> indexOpt = findValue(row, leg, INDEX_FIELD);<NEW_LINE>Optional<String> knownAmountOpt = findValue(row, leg, KNOWN_AMOUNT_FIELD);<NEW_LINE>if (fixedRateOpt.isPresent() || knownAmountOpt.isPresent()) {<NEW_LINE>if (fixedRateOpt.isPresent() && knownAmountOpt.isPresent()) {<NEW_LINE>throw new IllegalArgumentException("Swap leg must not define both '" + leg + FIXED_RATE_FIELD + "' and '" + leg + KNOWN_AMOUNT_FIELD + "'");<NEW_LINE>} else if (indexOpt.isPresent()) {<NEW_LINE>throw new IllegalArgumentException("Swap leg must not define both '" + leg + FIXED_RATE_FIELD + "' or '" + leg + KNOWN_AMOUNT_FIELD + "' and '" + leg + INDEX_FIELD + "'");<NEW_LINE>}<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>if (!indexOpt.isPresent()) {<NEW_LINE>throw new IllegalArgumentException("Swap leg must define either '" + leg + FIXED_RATE_FIELD + "' or '" + leg + KNOWN_AMOUNT_FIELD + "' or '" + leg + INDEX_FIELD + "'");<NEW_LINE>}<NEW_LINE>// use FloatingRateName to identify Ibor vs other<NEW_LINE>String indexStr = indexOpt.get();<NEW_LINE>FloatingRateName <MASK><NEW_LINE>if (frn.getType() == FloatingRateType.IBOR) {<NEW_LINE>// re-parse Ibor using tenor, which ensures tenor picked up from indexStr if present<NEW_LINE>Frequency freq = Frequency.parse(getValue(row, leg, FREQUENCY_FIELD));<NEW_LINE>Tenor iborTenor = freq.isTerm() ? frn.getDefaultTenor() : Tenor.of(freq.getPeriod());<NEW_LINE>return FloatingRateIndex.parse(indexStr, iborTenor);<NEW_LINE>}<NEW_LINE>return frn.toFloatingRateIndex();<NEW_LINE>} | frn = FloatingRateName.parse(indexStr); |
465,331 | public void fullRedraw() {<NEW_LINE>setupCanvas();<NEW_LINE>DBIDSelection selContext = context.getSelection();<NEW_LINE>if (selContext == null) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>final StyleLibrary style = context.getStyleLibrary();<NEW_LINE>// Class for the dot markers<NEW_LINE>if (!svgp.getCSSClassManager().contains(MARKER)) {<NEW_LINE>CSSClass cls = new CSSClass(this, MARKER);<NEW_LINE>cls.setStatement(SVGConstants.CSS_FILL_PROPERTY, style.getColor(StyleLibrary.SELECTION));<NEW_LINE>cls.setStatement(SVGConstants.CSS_OPACITY_PROPERTY, style.getOpacity(StyleLibrary.SELECTION));<NEW_LINE>svgp.addCSSClassOrLogError(cls);<NEW_LINE>}<NEW_LINE>final double size = <MASK><NEW_LINE>for (DBIDIter iter = selContext.getSelectedIds().iter(); iter.valid(); iter.advance()) {<NEW_LINE>try {<NEW_LINE>double[] v = proj.fastProjectDataToRenderSpace(rel.get(iter));<NEW_LINE>if (v[0] != v[0] || v[1] != v[1]) {<NEW_LINE>// NaN!<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>Element dot = svgp.svgCircle(v[0], v[1], size);<NEW_LINE>SVGUtil.addCSSClass(dot, MARKER);<NEW_LINE>layer.appendChild(dot);<NEW_LINE>} catch (ObjectNotFoundException e) {<NEW_LINE>// ignore<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | style.getSize(StyleLibrary.SELECTION); |
141,525 | private void handlePeerAdded(CallPeer callPeer) {<NEW_LINE>CallRecord callRecord = findCallRecord(callPeer.getCall());<NEW_LINE>// no such call<NEW_LINE>if (callRecord == null)<NEW_LINE>return;<NEW_LINE>callPeer.addCallPeerListener(new CallPeerAdapter() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void peerStateChanged(CallPeerChangeEvent evt) {<NEW_LINE>if (evt.getNewValue().equals(CallPeerState.DISCONNECTED))<NEW_LINE>return;<NEW_LINE>else {<NEW_LINE>CallPeerRecordImpl peerRecord = findPeerRecord(evt.getSourceCallPeer());<NEW_LINE>if (peerRecord == null)<NEW_LINE>return;<NEW_LINE>CallPeerState newState = (CallPeerState) evt.getNewValue();<NEW_LINE>if (newState.equals(CallPeerState.CONNECTED) && !CallPeerState.isOnHold((CallPeerState) evt.getOldValue()))<NEW_LINE>peerRecord.setStartTime(new Date());<NEW_LINE>peerRecord.setState(newState);<NEW_LINE>// Disconnected / Busy<NEW_LINE>// Disconnected / Connecting - fail<NEW_LINE>// Disconnected / Connected<NEW_LINE>}<NEW_LINE>}<NEW_LINE>});<NEW_LINE>Date startDate = new Date();<NEW_LINE>CallPeerRecordImpl newRec = new CallPeerRecordImpl(callPeer.getAddress(), startDate, startDate);<NEW_LINE>newRec.setDisplayName(callPeer.getDisplayName());<NEW_LINE>callRecord.getPeerRecords().add(newRec);<NEW_LINE>fireCallHistoryRecordReceivedEvent(new CallHistoryPeerRecordEvent(callPeer.getAddress(), startDate<MASK><NEW_LINE>} | , callPeer.getProtocolProvider())); |
1,797,768 | // findInitialAvailableActionsByContentType.<NEW_LINE>@WrapInTransaction<NEW_LINE>public WorkflowScheme saveOrUpdate(final String schemeId, final WorkflowSchemeForm workflowSchemeForm, final User user) throws AlreadyExistException, DotDataException, DotSecurityException {<NEW_LINE>final WorkflowScheme newScheme = new WorkflowScheme();<NEW_LINE>if (StringUtils.isSet(schemeId)) {<NEW_LINE>try {<NEW_LINE>final WorkflowScheme origScheme = this.workflowAPI.findScheme(schemeId);<NEW_LINE>BeanUtils.copyProperties(newScheme, origScheme);<NEW_LINE>} catch (Exception e) {<NEW_LINE>Logger.debug(this.getClass(), () -> "Unable to find scheme" + schemeId);<NEW_LINE>throw new DoesNotExistException(e.getMessage(), e);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>newScheme.setArchived(workflowSchemeForm.isSchemeArchived());<NEW_LINE>newScheme.setDescription(workflowSchemeForm.getSchemeDescription());<NEW_LINE>newScheme.setName(workflowSchemeForm.getSchemeName());<NEW_LINE>this.<MASK><NEW_LINE>return newScheme;<NEW_LINE>} | workflowAPI.saveScheme(newScheme, user); |
1,819,727 | public static ListRdsDBInstancesResponse unmarshall(ListRdsDBInstancesResponse listRdsDBInstancesResponse, UnmarshallerContext _ctx) {<NEW_LINE>listRdsDBInstancesResponse.setRequestId(_ctx.stringValue("ListRdsDBInstancesResponse.RequestId"));<NEW_LINE>listRdsDBInstancesResponse.setTotalCount(_ctx.integerValue("ListRdsDBInstancesResponse.TotalCount"));<NEW_LINE>listRdsDBInstancesResponse.setSuccess(_ctx.stringValue("ListRdsDBInstancesResponse.Success"));<NEW_LINE>List<DBInstance> rdsInstances = new ArrayList<DBInstance>();<NEW_LINE>for (int i = 0; i < _ctx.lengthValue("ListRdsDBInstancesResponse.RdsInstances.Length"); i++) {<NEW_LINE>DBInstance dBInstance = new DBInstance();<NEW_LINE>dBInstance.setDBInstanceId(_ctx.stringValue("ListRdsDBInstancesResponse.RdsInstances[" + i + "].DBInstanceId"));<NEW_LINE>dBInstance.setDBInstanceDescription(_ctx.stringValue("ListRdsDBInstancesResponse.RdsInstances[" + i + "].DBInstanceDescription"));<NEW_LINE>dBInstance.setRegionId(_ctx.stringValue("ListRdsDBInstancesResponse.RdsInstances[" + i + "].RegionId"));<NEW_LINE>dBInstance.setDBInstanceType(_ctx.stringValue("ListRdsDBInstancesResponse.RdsInstances[" + i + "].DBInstanceType"));<NEW_LINE>dBInstance.setDBInstanceStatus(_ctx.stringValue("ListRdsDBInstancesResponse.RdsInstances[" + i + "].DBInstanceStatus"));<NEW_LINE>dBInstance.setEngine(_ctx.stringValue("ListRdsDBInstancesResponse.RdsInstances[" + i + "].Engine"));<NEW_LINE>dBInstance.setEngineVersion(_ctx.stringValue("ListRdsDBInstancesResponse.RdsInstances[" + i + "].EngineVersion"));<NEW_LINE>dBInstance.setDBInstanceNetType(_ctx.stringValue("ListRdsDBInstancesResponse.RdsInstances[" + i + "].DBInstanceNetType"));<NEW_LINE>dBInstance.setLockMode(_ctx.stringValue("ListRdsDBInstancesResponse.RdsInstances[" + i + "].LockMode"));<NEW_LINE>dBInstance.setInstanceNetworkType(_ctx.stringValue("ListRdsDBInstancesResponse.RdsInstances[" + i + "].InstanceNetworkType"));<NEW_LINE>dBInstance.setVpcCloudInstanceId(_ctx.stringValue("ListRdsDBInstancesResponse.RdsInstances[" + i + "].VpcCloudInstanceId"));<NEW_LINE>dBInstance.setVpcId(_ctx.stringValue("ListRdsDBInstancesResponse.RdsInstances[" + i + "].VpcId"));<NEW_LINE>dBInstance.setVSwitchId(_ctx.stringValue("ListRdsDBInstancesResponse.RdsInstances[" + i + "].VSwitchId"));<NEW_LINE>dBInstance.setZoneId(_ctx.stringValue<MASK><NEW_LINE>dBInstance.setMutriORsignle(_ctx.booleanValue("ListRdsDBInstancesResponse.RdsInstances[" + i + "].MutriORsignle"));<NEW_LINE>dBInstance.setResourceGroupId(_ctx.stringValue("ListRdsDBInstancesResponse.RdsInstances[" + i + "].ResourceGroupId"));<NEW_LINE>rdsInstances.add(dBInstance);<NEW_LINE>}<NEW_LINE>listRdsDBInstancesResponse.setRdsInstances(rdsInstances);<NEW_LINE>return listRdsDBInstancesResponse;<NEW_LINE>} | ("ListRdsDBInstancesResponse.RdsInstances[" + i + "].ZoneId")); |
782,136 | public static void showPopup(JComponent content, String title, int x, int y) {<NEW_LINE>if (popupWindow != null) {<NEW_LINE>// Content already showing<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>Toolkit.getDefaultToolkit().addAWTEventListener(hideListener, AWTEvent.MOUSE_EVENT_MASK);<NEW_LINE>// NOT using PopupFactory<NEW_LINE>// 1. on linux, creates mediumweight popup taht doesn't refresh behind visible glasspane<NEW_LINE>// 2. on mac, needs an owner frame otherwise hiding tooltip also hides the popup. (linux requires no owner frame to force heavyweight)<NEW_LINE>// 3. the created window is not focusable window<NEW_LINE>popupWindow = new JDialog(getMainWindow());<NEW_LINE>popupWindow.setName(POPUP_NAME);<NEW_LINE>popupWindow.setUndecorated(true);<NEW_LINE>popupWindow.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ESC_KEY_STROKE, CLOSE_KEY);<NEW_LINE>popupWindow.getRootPane().getActionMap().put(CLOSE_KEY, CLOSE_ACTION);<NEW_LINE>// set a11y<NEW_LINE>String a11yName = content.getAccessibleContext().getAccessibleName();<NEW_LINE>if (a11yName != null && !a11yName.equals(""))<NEW_LINE>popupWindow.getAccessibleContext().setAccessibleName(a11yName);<NEW_LINE>String a11yDesc = content.getAccessibleContext().getAccessibleDescription();<NEW_LINE>if (a11yDesc != null && !a11yDesc.equals(""))<NEW_LINE>popupWindow.<MASK><NEW_LINE>popupWindow.getContentPane().add(content);<NEW_LINE>WindowManager.getDefault().getMainWindow().addWindowStateListener(hideListener);<NEW_LINE>WindowManager.getDefault().getMainWindow().addComponentListener(hideListener);<NEW_LINE>resizePopup();<NEW_LINE>if (x != (-1)) {<NEW_LINE>Point p = fitToScreen(x, y, 0);<NEW_LINE>popupWindow.setLocation(p.x, p.y);<NEW_LINE>}<NEW_LINE>popupWindow.setVisible(true);<NEW_LINE>content.requestFocus();<NEW_LINE>content.requestFocusInWindow();<NEW_LINE>} | getAccessibleContext().setAccessibleDescription(a11yDesc); |
238,631 | final ListNotificationRulesResult executeListNotificationRules(ListNotificationRulesRequest listNotificationRulesRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(listNotificationRulesRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<ListNotificationRulesRequest> request = null;<NEW_LINE>Response<ListNotificationRulesResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new ListNotificationRulesRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(listNotificationRulesRequest));<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.<MASK><NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "ListNotificationRules");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<ListNotificationRulesResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new ListNotificationRulesResultJsonUnmarshaller());<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.SERVICE_ID, "codestar notifications"); |
890,978 | // calculate the last fixing date<NEW_LINE>private LocalDate calculateLastFixingDate(LocalDate valuationDate, ReferenceData refData) {<NEW_LINE>SwapTrade trade = template.createTrade(valuationDate, BuySell.BUY, 1, 1, refData);<NEW_LINE>SwapLeg iborLeg = trade.getProduct().getLegs(SwapLegType.IBOR).get(1);<NEW_LINE>// Select the 'second' Ibor leg, i.e. the flat floating leg<NEW_LINE>ResolvedSwapLeg iborLegExpanded = iborLeg.resolve(refData);<NEW_LINE>List<SwapPaymentPeriod> periods = iborLegExpanded.getPaymentPeriods();<NEW_LINE><MASK><NEW_LINE>RatePaymentPeriod lastPeriod = (RatePaymentPeriod) periods.get(nbPeriods - 1);<NEW_LINE>List<RateAccrualPeriod> accruals = lastPeriod.getAccrualPeriods();<NEW_LINE>int nbAccruals = accruals.size();<NEW_LINE>IborRateComputation ibor = (IborRateComputation) accruals.get(nbAccruals - 1).getRateComputation();<NEW_LINE>return ibor.getFixingDate();<NEW_LINE>} | int nbPeriods = periods.size(); |
716,052 | final ReceiveMessageResult executeReceiveMessage(ReceiveMessageRequest receiveMessageRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(receiveMessageRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<ReceiveMessageRequest> request = null;<NEW_LINE>Response<ReceiveMessageResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new ReceiveMessageRequestMarshaller().marshall(super.beforeMarshalling(receiveMessageRequest));<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, "SQS");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "ReceiveMessage");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>StaxResponseHandler<ReceiveMessageResult> responseHandler = new StaxResponseHandler<ReceiveMessageResult>(new ReceiveMessageResultStaxUnmarshaller());<NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>} | endClientExecution(awsRequestMetrics, request, response); |
861,811 | public static PileupElement createNonIndelPileupElement(final int offsetIntoRead, final Allele newAllele, final int lengthOfRead) {<NEW_LINE><MASK><NEW_LINE>ParamUtils.inRange(offsetIntoRead, 0, lengthOfRead - 1, "offset into read is invalid for creating an artificial read, must be 0-" + (lengthOfRead - 1) + ".");<NEW_LINE>Utils.nonNull(newAllele);<NEW_LINE>final String cigarString = lengthOfRead + "M";<NEW_LINE>final Cigar cigar = TextCigarCodec.decode(cigarString);<NEW_LINE>final GATKRead gatkRead = ArtificialReadUtils.createArtificialRead(cigar);<NEW_LINE>final byte[] newBases = gatkRead.getBases();<NEW_LINE>final int upperBound = Math.min(offsetIntoRead + newAllele.getBases().length, lengthOfRead);<NEW_LINE>for (int i = offsetIntoRead; i < upperBound; i++) {<NEW_LINE>newBases[i] = newAllele.getBases()[i - offsetIntoRead];<NEW_LINE>}<NEW_LINE>gatkRead.setBases(newBases);<NEW_LINE>return PileupElement.createPileupForReadAndOffset(gatkRead, offsetIntoRead);<NEW_LINE>} | ParamUtils.isPositive(lengthOfRead, "length of read is invalid for creating an artificial read, must be greater than 0."); |
1,284,078 | public Impl createHtmlBrowserImpl() {<NEW_LINE>return new Impl() {<NEW_LINE><NEW_LINE>private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);<NEW_LINE><NEW_LINE>private URL url;<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void setURL(URL url) {<NEW_LINE>this.url = url;<NEW_LINE>URL url2 = externalize(url);<NEW_LINE>try {<NEW_LINE>desktop.<MASK><NEW_LINE>} catch (Exception x) {<NEW_LINE>Logger.getLogger(NbURLDisplayer.class.getName()).log(Level.INFO, "showing: " + url2, x);<NEW_LINE>}<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public URL getURL() {<NEW_LINE>return url;<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void reloadDocument() {<NEW_LINE>setURL(url);<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void addPropertyChangeListener(PropertyChangeListener l) {<NEW_LINE>pcs.addPropertyChangeListener(l);<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void removePropertyChangeListener(PropertyChangeListener l) {<NEW_LINE>pcs.removePropertyChangeListener(l);<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public Component getComponent() {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void stopLoading() {<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public String getStatusMessage() {<NEW_LINE>return "";<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public String getTitle() {<NEW_LINE>return "";<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public boolean isForward() {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void forward() {<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public boolean isBackward() {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void backward() {<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public boolean isHistory() {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void showHistory() {<NEW_LINE>}<NEW_LINE>};<NEW_LINE>} | browse(url2.toURI()); |
1,123,759 | private int parseIntegerLiteral() {<NEW_LINE>String value = mToken.getContent();<NEW_LINE>String type = "xs:integer";<NEW_LINE>if (is(TokenType.VALUE, false)) {<NEW_LINE>// is at least decimal literal (could also be a double literal)<NEW_LINE>if (mToken.getType() == TokenType.POINT) {<NEW_LINE>// TODO: not so nice, try to find a better solution<NEW_LINE>final boolean isDouble = mScanner.lookUpTokens(2).getType() == TokenType.E_NUMBER;<NEW_LINE>value = parseDecimalLiteral(value);<NEW_LINE>type = isDouble ? "xs:double" : "xs:decimal";<NEW_LINE>}<NEW_LINE>// values containing an 'e' are double literals<NEW_LINE>if (mToken.getType() == TokenType.E_NUMBER) {<NEW_LINE>value = parseDoubleLiteral(value);<NEW_LINE>type = "xs:double";<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>// decimal literal that starts with a "."<NEW_LINE>final boolean isDouble = mScanner.lookUpTokens(2).getType() == TokenType.E_NUMBER;<NEW_LINE>value = parseDecimalLiteral("");<NEW_LINE>type = isDouble ? "xs:double" : "xs:decimal";<NEW_LINE>}<NEW_LINE><MASK><NEW_LINE>final AtomicValue intLiteral = new AtomicValue(TypedValue.getBytes(value), getTransaction().keyForName(type));<NEW_LINE>return getTransaction().getItemList().addItem(intLiteral);<NEW_LINE>} | is(TokenType.SPACE, true); |
1,382,502 | private void fixReservationsForEvent(Event event, List<String> reservations) {<NEW_LINE>var byReservationId = ticketSearchRepository.loadAllReservationsWithTickets(event.getId(), reservations).stream().collect(groupingBy(trt -> trt.getTicketReservation().getId()));<NEW_LINE>log.trace("found {} reservations to fix for event {}", byReservationId.size(), event.getShortName());<NEW_LINE>if (!byReservationId.isEmpty()) {<NEW_LINE>var additionalServices = additionalServiceRepository.<MASK><NEW_LINE>var reservationsToUpdate = byReservationId.values().stream().map(ticketsReservationAndTransactions -> {<NEW_LINE>var tickets = ticketsReservationAndTransactions.stream().map(TicketWithReservationAndTransaction::getTicket).collect(toList());<NEW_LINE>var ticketReservation = ticketsReservationAndTransactions.get(0).getTicketReservation();<NEW_LINE>var promoCodeDiscountId = ticketReservation.getPromoCodeDiscountId();<NEW_LINE>var discount = promoCodeDiscountId != null ? promoCodeDiscountRepository.findById(promoCodeDiscountId) : null;<NEW_LINE>var additionalServiceItems = additionalServiceItemRepository.findByReservationUuid(ticketReservation.getId());<NEW_LINE>var calculator = new ReservationPriceCalculator(ticketReservation, discount, tickets, additionalServiceItems, additionalServices, event, List.of(), Optional.empty());<NEW_LINE>var currencyCode = calculator.getCurrencyCode();<NEW_LINE>return new MapSqlParameterSource("reservationId", calculator.reservation.getId()).addValue("srcPrice", calculator.getSrcPriceCts()).addValue("finalPrice", MonetaryUtil.unitToCents(calculator.getFinalPrice(), currencyCode)).addValue("discount", MonetaryUtil.unitToCents(calculator.getAppliedDiscount(), currencyCode)).addValue("vat", MonetaryUtil.unitToCents(calculator.getVAT(), currencyCode)).addValue("currencyCode", currencyCode);<NEW_LINE>}).toArray(MapSqlParameterSource[]::new);<NEW_LINE>log.trace("updating {} reservations", reservationsToUpdate.length);<NEW_LINE>int[] results = jdbc.batchUpdate("update tickets_reservation set src_price_cts = :srcPrice, final_price_cts = :finalPrice, discount_cts = :discount, vat_cts = :vat, currency_code = :currencyCode where id = :reservationId", reservationsToUpdate);<NEW_LINE>int sum = IntStream.of(results).sum();<NEW_LINE>if (sum != reservationsToUpdate.length) {<NEW_LINE>log.warn("Expected {} reservations to be affected, actual number: {}", reservationsToUpdate.length, sum);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | loadAllForEvent(event.getId()); |
879,833 | public Request<UpdateContinuousBackupsRequest> marshall(UpdateContinuousBackupsRequest updateContinuousBackupsRequest) {<NEW_LINE>if (updateContinuousBackupsRequest == null) {<NEW_LINE>throw new AmazonClientException("Invalid argument passed to marshall(UpdateContinuousBackupsRequest)");<NEW_LINE>}<NEW_LINE>Request<UpdateContinuousBackupsRequest> request = new DefaultRequest<UpdateContinuousBackupsRequest>(updateContinuousBackupsRequest, "AmazonDynamoDB");<NEW_LINE>String target = "DynamoDB_20120810.UpdateContinuousBackups";<NEW_LINE><MASK><NEW_LINE>request.setHttpMethod(HttpMethodName.POST);<NEW_LINE>String uriResourcePath = "/";<NEW_LINE>request.setResourcePath(uriResourcePath);<NEW_LINE>try {<NEW_LINE>StringWriter stringWriter = new StringWriter();<NEW_LINE>AwsJsonWriter jsonWriter = JsonUtils.getJsonWriter(stringWriter);<NEW_LINE>jsonWriter.beginObject();<NEW_LINE>if (updateContinuousBackupsRequest.getTableName() != null) {<NEW_LINE>String tableName = updateContinuousBackupsRequest.getTableName();<NEW_LINE>jsonWriter.name("TableName");<NEW_LINE>jsonWriter.value(tableName);<NEW_LINE>}<NEW_LINE>if (updateContinuousBackupsRequest.getPointInTimeRecoverySpecification() != null) {<NEW_LINE>PointInTimeRecoverySpecification pointInTimeRecoverySpecification = updateContinuousBackupsRequest.getPointInTimeRecoverySpecification();<NEW_LINE>jsonWriter.name("PointInTimeRecoverySpecification");<NEW_LINE>PointInTimeRecoverySpecificationJsonMarshaller.getInstance().marshall(pointInTimeRecoverySpecification, jsonWriter);<NEW_LINE>}<NEW_LINE>jsonWriter.endObject();<NEW_LINE>jsonWriter.close();<NEW_LINE>String snippet = stringWriter.toString();<NEW_LINE>byte[] content = snippet.getBytes(UTF8);<NEW_LINE>request.setContent(new StringInputStream(snippet));<NEW_LINE>request.addHeader("Content-Length", Integer.toString(content.length));<NEW_LINE>} catch (Throwable t) {<NEW_LINE>throw new AmazonClientException("Unable to marshall request to JSON: " + t.getMessage(), t);<NEW_LINE>}<NEW_LINE>if (!request.getHeaders().containsKey("Content-Type")) {<NEW_LINE>request.addHeader("Content-Type", "application/x-amz-json-1.0");<NEW_LINE>}<NEW_LINE>return request;<NEW_LINE>} | request.addHeader("X-Amz-Target", target); |
1,506,030 | public boolean onActivate(Item item, Player player) {<NEW_LINE>this.level.getServer().getPluginManager().callEvent(new BlockRedstoneEvent(this, isPowerOn() ? 15 : 0, isPowerOn() ? 0 : 15));<NEW_LINE>this.setDamage(<MASK><NEW_LINE>this.getLevel().setBlock(this, this, false, true);<NEW_LINE>// TODO: coorect pitcj<NEW_LINE>this.getLevel().addSound(this, Sound.RANDOM_CLICK);<NEW_LINE>LeverOrientation orientation = LeverOrientation.byMetadata(this.isPowerOn() ? this.getDamage() ^ 0x08 : this.getDamage());<NEW_LINE>BlockFace face = orientation.getFacing();<NEW_LINE>// this.level.updateAroundRedstone(this, null);<NEW_LINE>this.level.updateAroundRedstone(this.getLocation().getSide(face.getOpposite()), isPowerOn() ? face : null);<NEW_LINE>return true;<NEW_LINE>} | this.getDamage() ^ 0x08); |
1,230,828 | public final RowImpl20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> valuesRow() {<NEW_LINE>return new RowImpl20<>(Tools.field(value1(), field1()), Tools.field(value2(), field2()), Tools.field(value3(), field3()), Tools.field(value4(), field4()), Tools.field(value5(), field5()), Tools.field(value6(), field6()), Tools.field(value7(), field7()), Tools.field(value8(), field8()), Tools.field(value9(), field9()), Tools.field(value10(), field10()), Tools.field(value11(), field11()), Tools.field(value12(), field12()), Tools.field(value13(), field13()), Tools.field(value14(), field14()), Tools.field(value15(), field15()), Tools.field(value16(), field16()), Tools.field(value17(), field17()), Tools.field(value18(), field18()), Tools.field(value19(), field19()), Tools.field(value20<MASK><NEW_LINE>} | (), field20())); |
682,983 | private PKeyword[] evaluateKeywords(VirtualFrame frame, Object callable, PRaiseNode raise, BranchProfile keywordsError) {<NEW_LINE>PKeyword[] result;<NEW_LINE>if (keywordArguments == null) {<NEW_LINE>result = PKeyword.EMPTY_KEYWORDS;<NEW_LINE>} else {<NEW_LINE>try {<NEW_LINE>result = keywordArguments.execute(frame);<NEW_LINE>} catch (SameDictKeyException ex) {<NEW_LINE>keywordsError.enter();<NEW_LINE>if (castToStringNode == null) {<NEW_LINE>CompilerDirectives.transferToInterpreterAndInvalidate();<NEW_LINE>castToStringNode = insert(StringNodes.CastToJavaStringCheckedNode.create());<NEW_LINE>}<NEW_LINE>Object functionName = getNameAttributeNode(<MASK><NEW_LINE>String keyName = castToStringNode.execute(ex.getKey(), ErrorMessages.KEYWORDS_S_MUST_BE_STRINGS, new Object[] { functionName });<NEW_LINE>throw raise.raise(PythonBuiltinClassType.TypeError, ErrorMessages.GOT_MULTIPLE_VALUES_FOR_ARG, functionName, keyName);<NEW_LINE>} catch (NonMappingException ex) {<NEW_LINE>keywordsError.enter();<NEW_LINE>throw raise.raise(PythonBuiltinClassType.TypeError, ErrorMessages.ARG_AFTER_MUST_BE_MAPPING, getNameAttributeNode().executeObject(frame, callable), ex.getObject());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return result;<NEW_LINE>} | ).executeObject(frame, callable); |
1,441,955 | public void marshall(CreateDomainConfigurationRequest createDomainConfigurationRequest, ProtocolMarshaller protocolMarshaller) {<NEW_LINE>if (createDomainConfigurationRequest == null) {<NEW_LINE>throw new SdkClientException("Invalid argument passed to marshall(...)");<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>protocolMarshaller.marshall(createDomainConfigurationRequest.getDomainConfigurationName(), DOMAINCONFIGURATIONNAME_BINDING);<NEW_LINE>protocolMarshaller.marshall(createDomainConfigurationRequest.getDomainName(), DOMAINNAME_BINDING);<NEW_LINE>protocolMarshaller.marshall(<MASK><NEW_LINE>protocolMarshaller.marshall(createDomainConfigurationRequest.getValidationCertificateArn(), VALIDATIONCERTIFICATEARN_BINDING);<NEW_LINE>protocolMarshaller.marshall(createDomainConfigurationRequest.getAuthorizerConfig(), AUTHORIZERCONFIG_BINDING);<NEW_LINE>protocolMarshaller.marshall(createDomainConfigurationRequest.getServiceType(), SERVICETYPE_BINDING);<NEW_LINE>protocolMarshaller.marshall(createDomainConfigurationRequest.getTags(), TAGS_BINDING);<NEW_LINE>} catch (Exception e) {<NEW_LINE>throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);<NEW_LINE>}<NEW_LINE>} | createDomainConfigurationRequest.getServerCertificateArns(), SERVERCERTIFICATEARNS_BINDING); |
884,993 | private BigDecimal sellItem(final User user, final ItemStack is, final String[] args, final boolean isBulkSell) throws Exception {<NEW_LINE>final int amount = ess.getWorth().getAmount(ess, user, is, args, isBulkSell);<NEW_LINE>final BigDecimal worth = ess.getWorth().getPrice(ess, is);<NEW_LINE>if (worth == null) {<NEW_LINE>throw new Exception(tl("itemCannotBeSold"));<NEW_LINE>}<NEW_LINE>if (amount <= 0) {<NEW_LINE>if (!isBulkSell) {<NEW_LINE>user.sendMessage(tl("itemSold", NumberUtil.displayCurrency(BigDecimal.ZERO, ess), BigDecimal.ZERO, is.getType().toString().toLowerCase(Locale.ENGLISH), NumberUtil.displayCurrency(worth, ess)));<NEW_LINE>}<NEW_LINE>return BigDecimal.ZERO;<NEW_LINE>}<NEW_LINE>final BigDecimal result = worth.multiply(BigDecimal.valueOf(amount));<NEW_LINE>// TODO: Prices for Enchantments<NEW_LINE>final ItemStack ris = is.clone();<NEW_LINE>ris.setAmount(amount);<NEW_LINE>if (!user.getBase().getInventory().containsAtLeast(ris, amount)) {<NEW_LINE>// This should never happen.<NEW_LINE>throw new IllegalStateException("Trying to remove more items than are available.");<NEW_LINE>}<NEW_LINE>user.getBase().getInventory().removeItem(ris);<NEW_LINE>user.getBase().updateInventory();<NEW_LINE>Trade.log("Command", "Sell", "Item", user.getName(), new Trade(ris, ess), user.getName(), new Trade(result, ess), user.getLocation(), user.getMoney(), ess);<NEW_LINE>user.giveMoney(result, null, UserBalanceUpdateEvent.Cause.COMMAND_SELL);<NEW_LINE>user.sendMessage(tl("itemSold", NumberUtil.displayCurrency(result, ess), amount, is.getType().toString().toLowerCase(Locale.ENGLISH), NumberUtil.displayCurrency(worth, ess)));<NEW_LINE>logger.log(Level.INFO, tl("itemSoldConsole", user.getName(), is.getType().toString().toLowerCase(Locale.ENGLISH), NumberUtil.displayCurrency(result, ess), amount, NumberUtil.displayCurrency(worth, ess)<MASK><NEW_LINE>return result;<NEW_LINE>} | , user.getDisplayName())); |
1,265,074 | public String generateDbRuleArrayStr(PartitionByType type, String idText, int start, int groups, int tablesPerGroup, DBPartitionDefinition dbPartitionDefinition) {<NEW_LINE>if (!PartitionByTypeUtils.isSupportedDbPartitionByType(type)) {<NEW_LINE>throw new IllegalArgumentException(String.format("Date column not support %s method", type.toString()));<NEW_LINE>}<NEW_LINE>int totalTables = groups * tablesPerGroup;<NEW_LINE>StringBuilder rule = new StringBuilder();<NEW_LINE>genMiddleRuleStr(type, idText, start, rule, tablesPerGroup, groups, true, dbPartitionDefinition.getStartWith(), dbPartitionDefinition.getEndWith());<NEW_LINE>if (PartitionByTypeUtils.isOptimizedPartitionByType(type)) {<NEW_LINE>rule.append(").longValue() % ").append(groups).append(")");<NEW_LINE>} else {<NEW_LINE>rule.append(").longValue() % ").append(totalTables).append(")");<NEW_LINE>rule.append(".intdiv(").append<MASK><NEW_LINE>}<NEW_LINE>return rule.toString();<NEW_LINE>} | (tablesPerGroup).append(")"); |
793,878 | public <PSI> Match wait(PSI target, double timeout) throws FindFailed {<NEW_LINE>lastMatch = null;<NEW_LINE>String shouldAbort = "";<NEW_LINE>RepeatableFind rf = new RepeatableFind(target, null);<NEW_LINE>Image img = rf._image;<NEW_LINE>String targetStr = img.getName();<NEW_LINE>Boolean response = true;<NEW_LINE>if (!img.isText() && !img.isValid() && img.hasIOException()) {<NEW_LINE>// wait<NEW_LINE>response = handleImageMissing(img, false);<NEW_LINE>if (response == null) {<NEW_LINE>if (Settings.SwitchToText) {<NEW_LINE>log(logLevel, "wait: image missing: switching to text search (deprecated - use text methods)");<NEW_LINE>response = true;<NEW_LINE>img.setIsText(true);<NEW_LINE>rf.setTarget("\t" + target + "\t");<NEW_LINE>} else {<NEW_LINE>throw new RuntimeException(String.format("SikuliX: wait: ImageMissing: %s", target));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>while (null != response && response) {<NEW_LINE>log(logLevel, "wait: waiting %.1f secs for %s to appear in %s", timeout, targetStr, this.toStringShort());<NEW_LINE>if (rf.repeat(timeout)) {<NEW_LINE>lastMatch = rf.getMatch();<NEW_LINE>// lastMatch.setImage(img);<NEW_LINE>if (isOtherScreen()) {<NEW_LINE>lastMatch.setOtherScreen();<NEW_LINE>} else if (img != null) {<NEW_LINE>img.setLastSeen(lastMatch.getRect(), lastMatch.getScore());<NEW_LINE>}<NEW_LINE>log(logLevel, "wait: %s appeared (%s)", img.getName(), lastMatch);<NEW_LINE>return lastMatch;<NEW_LINE>} else {<NEW_LINE><MASK><NEW_LINE>if (null == response) {<NEW_LINE>shouldAbort = FindFailed.createErrorMessage(this, img);<NEW_LINE>break;<NEW_LINE>} else if (response) {<NEW_LINE>if (img.isRecaptured()) {<NEW_LINE>rf = new RepeatableFind(target, img);<NEW_LINE>}<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>log(logLevel, "wait: %s did not appear [%d msec]", targetStr, new Date().getTime() - lastFindTime);<NEW_LINE>if (!shouldAbort.isEmpty()) {<NEW_LINE>throw new FindFailed(shouldAbort);<NEW_LINE>}<NEW_LINE>return lastMatch;<NEW_LINE>} | response = handleFindFailed(target, img); |
382,004 | public void validate() {<NEW_LINE>super.validate();<NEW_LINE>if (body() != null) {<NEW_LINE>body().validate();<NEW_LINE>}<NEW_LINE>if (from() != null) {<NEW_LINE>from().validate();<NEW_LINE>}<NEW_LINE>if (newParticipants() != null) {<NEW_LINE>newParticipants().forEach(e -> e.validate());<NEW_LINE>}<NEW_LINE>if (sender() != null) {<NEW_LINE>sender().validate();<NEW_LINE>}<NEW_LINE>if (attachments() != null) {<NEW_LINE>attachments().forEach(e -> e.validate());<NEW_LINE>}<NEW_LINE>if (extensions() != null) {<NEW_LINE>extensions().forEach(<MASK><NEW_LINE>}<NEW_LINE>if (inReplyTo() != null) {<NEW_LINE>inReplyTo().validate();<NEW_LINE>}<NEW_LINE>if (multiValueExtendedProperties() != null) {<NEW_LINE>multiValueExtendedProperties().forEach(e -> e.validate());<NEW_LINE>}<NEW_LINE>if (singleValueExtendedProperties() != null) {<NEW_LINE>singleValueExtendedProperties().forEach(e -> e.validate());<NEW_LINE>}<NEW_LINE>} | e -> e.validate()); |
561,429 | public AliasAST visit(int lineNo, String line) throws ASTParseException {<NEW_LINE>try {<NEW_LINE>String[] trim = line.trim().split("\\s+");<NEW_LINE>if (trim.length < 2)<NEW_LINE>throw new ASTParseException(lineNo, "Not enough paramters");<NEW_LINE>int start = line.indexOf(trim[0]);<NEW_LINE>// op<NEW_LINE>OpcodeParser opParser = new OpcodeParser();<NEW_LINE>opParser.setOffset(line.indexOf(trim[0]));<NEW_LINE>OpcodeAST op = opParser.visit(lineNo, trim[0]);<NEW_LINE>// name<NEW_LINE>NameParser nameParser = new NameParser(this);<NEW_LINE>nameParser.setOffset(line.indexOf(trim[1]));<NEW_LINE>NameAST name = nameParser.visit(lineNo, trim[1]);<NEW_LINE>// content<NEW_LINE>StringParser stringParser = new StringParser();<NEW_LINE>stringParser.setOffset(line.indexOf("\""));<NEW_LINE>StringAST content = stringParser.visit(lineNo, line.substring(<MASK><NEW_LINE>return new AliasAST(lineNo, start, op, name, content);<NEW_LINE>} catch (Exception ex) {<NEW_LINE>throw new ASTParseException(ex, lineNo, "Bad format for var instruction");<NEW_LINE>}<NEW_LINE>} | line.indexOf("\""))); |
1,675,780 | public boolean visit(MySqlUpdateStatement x) {<NEW_LINE>if (x.getTableSource().getClass() != SQLExprTableSource.class) {<NEW_LINE>throw new UnsupportedOperationException("Support single table only for SqlUpdate statement of calcite.");<NEW_LINE>}<NEW_LINE>SQLExprTableSource tableSource = (SQLExprTableSource) x.getTableSource();<NEW_LINE>SqlNode targetTable = convertToSqlNode(tableSource.getExpr());<NEW_LINE>List<SqlNode> columns = new ArrayList<SqlNode>();<NEW_LINE>List<SqlNode> values = new ArrayList<SqlNode>();<NEW_LINE>for (SQLUpdateSetItem item : x.getItems()) {<NEW_LINE>columns.add(convertToSqlNode(item.getColumn()));<NEW_LINE>values.add(convertToSqlNode(item.getValue()));<NEW_LINE>}<NEW_LINE>SqlNodeList targetColumnList = new SqlNodeList(columns, SqlParserPos.ZERO);<NEW_LINE>SqlNodeList sourceExpressList = new SqlNodeList(values, SqlParserPos.ZERO);<NEW_LINE>SqlNode condition = convertToSqlNode(x.getWhere());<NEW_LINE>SqlIdentifier alias = null;<NEW_LINE>if (x.getTableSource().getAlias() != null) {<NEW_LINE>alias = new SqlIdentifier(tableSource.getAlias(), SqlParserPos.ZERO);<NEW_LINE>}<NEW_LINE>sqlNode = new SqlUpdate(SqlParserPos.ZERO, targetTable, targetColumnList, <MASK><NEW_LINE>return false;<NEW_LINE>} | sourceExpressList, condition, null, alias); |
984,208 | ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, String modelFlag, String workId) throws Exception {<NEW_LINE>logger.debug(effectivePerson, "modelFlag:{}, workId:{}.", modelFlag, workId);<NEW_LINE>try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {<NEW_LINE>ActionResult<List<Wo>> result = new ActionResult<>();<NEW_LINE>Business business = new Business(emc);<NEW_LINE>Model model = emc.flag(modelFlag, Model.class);<NEW_LINE>if (null == model) {<NEW_LINE>throw new ExceptionEntityNotExist(modelFlag, Model.class);<NEW_LINE>}<NEW_LINE>if (StringUtils.isEmpty(model.getNnet())) {<NEW_LINE>throw new ExceptionModelNotReady(model.getName());<NEW_LINE>}<NEW_LINE>NeuralNetwork<MomentumBackpropagation> neuralNetwork = null;<NEW_LINE>CacheKey cacheKey = new CacheKey(this.getClass(), model.getId());<NEW_LINE>Optional<?> optional = CacheManager.get(cache, cacheKey);<NEW_LINE>if (optional.isPresent()) {<NEW_LINE>neuralNetwork = ((NeuralNetwork<MomentumBackpropagation>) optional.get());<NEW_LINE>} else {<NEW_LINE>if (StringUtils.isEmpty(model.getNnet())) {<NEW_LINE>throw new <MASK><NEW_LINE>}<NEW_LINE>neuralNetwork = model.createNeuralNetwork();<NEW_LINE>NeuralNetworkCODEC.array2network(DoubleTools.byteToDoubleArray(ByteTools.decompressBase64String(model.getNnet())), neuralNetwork);<NEW_LINE>CacheManager.put(cache, cacheKey, neuralNetwork);<NEW_LINE>}<NEW_LINE>Wo wo = new Wo();<NEW_LINE>Work work = emc.flag(workId, Work.class);<NEW_LINE>if (null == work) {<NEW_LINE>throw new ExceptionEntityNotExist(workId, Work.class);<NEW_LINE>}<NEW_LINE>TreeSet<String> inValue = this.convert(business, model, work);<NEW_LINE>double[] inputs = this.inputData(business, model, inValue);<NEW_LINE>neuralNetwork.setInput(inputs);<NEW_LINE>neuralNetwork.calculate();<NEW_LINE>double[] outputs = neuralNetwork.getOutput();<NEW_LINE>// double mean = StatUtils.mean(outputs);<NEW_LINE>List<Pair> pairs = new ArrayList<>();<NEW_LINE>for (int i = 0; i < outputs.length; i++) {<NEW_LINE>// if (outputs[i] > mean) {<NEW_LINE>Pair p = new Pair();<NEW_LINE>p.setOut(outputs[i]);<NEW_LINE>p.setSerial(i);<NEW_LINE>pairs.add(p);<NEW_LINE>// }<NEW_LINE>}<NEW_LINE>pairs = pairs.stream().sorted(Comparator.comparing(Pair::getOut).reversed()).collect(Collectors.toList());<NEW_LINE>Integer maxResult = MapTools.getInteger(model.getPropertyMap(), Model.PROPERTY_MLP_MAXRESULT, Model.DEFAULT_MLP_MAXRESULT);<NEW_LINE>if (pairs.size() > maxResult) {<NEW_LINE>pairs = pairs.stream().limit(maxResult).collect(Collectors.toList());<NEW_LINE>}<NEW_LINE>List<Wo> wos = this.outputData(business, model, pairs);<NEW_LINE>result.setData(wos);<NEW_LINE>return result;<NEW_LINE>}<NEW_LINE>} | ExceptionModelNotReady(model.getName()); |
513,739 | public static void bindEventFields(BoundStatement bound, IDeviceEvent event) throws SiteWhereException {<NEW_LINE>bound.setUUID(FIELD_DEVICE_ID, event.getDeviceId());<NEW_LINE>bound.setUUID(FIELD_EVENT_ID, event.getId());<NEW_LINE>if (event.getAlternateId() != null) {<NEW_LINE>bound.setString(FIELD_ALTERNATE_ID, event.getAlternateId());<NEW_LINE>}<NEW_LINE>bound.setByte(FIELD_EVENT_TYPE, getIndicatorForEventType(event.getEventType()));<NEW_LINE>bound.setUUID(<MASK><NEW_LINE>if (event.getCustomerId() != null) {<NEW_LINE>bound.setUUID(FIELD_CUSTOMER_ID, event.getCustomerId());<NEW_LINE>}<NEW_LINE>if (event.getAreaId() != null) {<NEW_LINE>bound.setUUID(FIELD_AREA_ID, event.getAreaId());<NEW_LINE>}<NEW_LINE>if (event.getAssetId() != null) {<NEW_LINE>bound.setUUID(FIELD_ASSET_ID, event.getAssetId());<NEW_LINE>}<NEW_LINE>bound.setTimestamp(FIELD_EVENT_DATE, event.getEventDate());<NEW_LINE>bound.setTimestamp(FIELD_RECEIVED_DATE, event.getReceivedDate());<NEW_LINE>} | FIELD_ASSIGNMENT_ID, event.getDeviceAssignmentId()); |
1,844,474 | private JSDynamicObject initializeLocaleUsingJString(JSDynamicObject localeObject, String tagArg, Object optionsArg) {<NEW_LINE>try {<NEW_LINE>JSDynamicObject <MASK><NEW_LINE>String tag = applyOptionsToTag(tagArg, options);<NEW_LINE>String optCalendar = getCalendarOption.executeValue(options);<NEW_LINE>if (optCalendar != null) {<NEW_LINE>IntlUtil.validateUnicodeLocaleIdentifierType(optCalendar, errorBranch);<NEW_LINE>}<NEW_LINE>String optCollation = getCollationOption.executeValue(options);<NEW_LINE>if (optCollation != null) {<NEW_LINE>IntlUtil.validateUnicodeLocaleIdentifierType(optCollation, errorBranch);<NEW_LINE>}<NEW_LINE>String optHourCycle = getHourCycleOption.executeValue(options);<NEW_LINE>String optCaseFirst = getCaseFirstOption.executeValue(options);<NEW_LINE>Boolean optNumeric = getNumericOption.executeValue(options);<NEW_LINE>String optNumberingSystem = getNumberingSystemOption.executeValue(options);<NEW_LINE>if (optNumberingSystem != null) {<NEW_LINE>IntlUtil.validateUnicodeLocaleIdentifierType(optNumberingSystem, errorBranch);<NEW_LINE>}<NEW_LINE>Locale locale = applyUnicodeExtensionToTag(tag, optCalendar, optCollation, optHourCycle, optCaseFirst, optNumeric, optNumberingSystem);<NEW_LINE>JSLocale.InternalState state = JSLocale.getInternalState(localeObject);<NEW_LINE>JSLocale.setupInternalState(state, locale);<NEW_LINE>} catch (MissingResourceException e) {<NEW_LINE>errorBranch.enter();<NEW_LINE>throw Errors.createICU4JDataError(e);<NEW_LINE>}<NEW_LINE>return localeObject;<NEW_LINE>} | options = coerceOptionsToObjectNode.execute(optionsArg); |
1,070,295 | public boolean save() {<NEW_LINE>// Add<NEW_LINE>p_properties.setProperty("ADEMPIERE_MAIN_VERSION", Adempiere.MAIN_VERSION);<NEW_LINE>p_properties.setProperty("ADEMPIERE_DATE_VERSION", Adempiere.DATE_VERSION);<NEW_LINE>p_properties.setProperty("ADEMPIERE_DB_VERSION", Adempiere.DB_VERSION);<NEW_LINE>// Create Connection<NEW_LINE>String ccType = Database.DB_ORACLE;<NEW_LINE>for (String dbType : DBTYPE) {<NEW_LINE>if (getDatabaseType().equals(dbType)) {<NEW_LINE>ccType = dbType;<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>CConnection cc = null;<NEW_LINE>try {<NEW_LINE>cc = CConnection.get(ccType, getDatabaseServer(), getDatabasePort(), getDatabaseName(), getDatabaseUser(), getDatabasePassword());<NEW_LINE>cc.setAppsHost(getAppsServer());<NEW_LINE>cc.setAppsPort(getAppsServerJNPPort());<NEW_LINE>cc.setConnectionProfile(CConnection.PROFILE_LAN);<NEW_LINE>} catch (Exception e) {<NEW_LINE>log.log(Level.SEVERE, "connection", e);<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>p_properties.setProperty(Ini.P_CONNECTION, SecureEngine.encrypt(cc.toStringLong()));<NEW_LINE>log.finest(p_properties.toString());<NEW_LINE>// Before we save, load Ini<NEW_LINE>Ini.setClient(false);<NEW_LINE>String fileName = m_adempiereHome.getAbsolutePath() + File.separator + Ini.ADEMPIERE_PROPERTY_FILE;<NEW_LINE>Ini.loadProperties(fileName);<NEW_LINE>// Save Environment<NEW_LINE>fileName = m_adempiereHome.getAbsolutePath() + File.separator + ADEMPIERE_ENV_FILE;<NEW_LINE>try {<NEW_LINE>FileOutputStream fos = new FileOutputStream(new File(fileName));<NEW_LINE>p_properties.store(fos, ADEMPIERE_ENV_FILE);<NEW_LINE>fos.flush();<NEW_LINE>fos.close();<NEW_LINE>} catch (Exception e) {<NEW_LINE>log.severe("Cannot save Properties to " + fileName + " - " + e.toString());<NEW_LINE>if (p_panel != null)<NEW_LINE>JOptionPane.showConfirmDialog(p_panel, ConfigurationPanel.res.getString("ErrorSave"), ConfigurationPanel.res.getString("AdempiereServerSetup"), <MASK><NEW_LINE>else<NEW_LINE>System.err.println(ConfigurationPanel.res.getString("ErrorSave"));<NEW_LINE>return false;<NEW_LINE>} catch (Throwable t) {<NEW_LINE>log.severe("Cannot save Properties to " + fileName + " - " + t.toString());<NEW_LINE>if (p_panel != null)<NEW_LINE>JOptionPane.showConfirmDialog(p_panel, ConfigurationPanel.res.getString("ErrorSave"), ConfigurationPanel.res.getString("AdempiereServerSetup"), JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);<NEW_LINE>else<NEW_LINE>System.err.println(ConfigurationPanel.res.getString("ErrorSave"));<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>log.info(fileName);<NEW_LINE>return saveIni();<NEW_LINE>} | JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE); |
1,401,460 | protected static long deserializePrimitiveField(TaggedDeserializationContext context, StructBondType.StructField<Long> field) throws IOException {<NEW_LINE>// an uint64 value may be deserialized from BT_UINT64, BT_UINT32, BT_UINT16 or BT_UINT8<NEW_LINE>if (context.readFieldResult.type.value != BondDataType.BT_UINT64.value) {<NEW_LINE>if (context.readFieldResult.type.value == BondDataType.BT_UINT32.value) {<NEW_LINE>return context.reader.readUInt32();<NEW_LINE>} else if (context.readFieldResult.type.value == BondDataType.BT_UINT16.value) {<NEW_LINE>return context.reader.readUInt16();<NEW_LINE>} else if (context.readFieldResult.type.value == BondDataType.BT_UINT8.value) {<NEW_LINE>return context.reader.readUInt8();<NEW_LINE>}<NEW_LINE>// throws<NEW_LINE>Throw.raiseFieldTypeIsNotCompatibleDeserializationError(<MASK><NEW_LINE>}<NEW_LINE>return context.reader.readUInt64();<NEW_LINE>} | context.readFieldResult.type, field); |
213,504 | public static DescribeRestoreJobsResponse unmarshall(DescribeRestoreJobsResponse describeRestoreJobsResponse, UnmarshallerContext _ctx) {<NEW_LINE>describeRestoreJobsResponse.setRequestId(_ctx.stringValue("DescribeRestoreJobsResponse.RequestId"));<NEW_LINE>describeRestoreJobsResponse.setSuccess(_ctx.booleanValue("DescribeRestoreJobsResponse.Success"));<NEW_LINE>describeRestoreJobsResponse.setCode(_ctx.stringValue("DescribeRestoreJobsResponse.Code"));<NEW_LINE>describeRestoreJobsResponse.setMessage(_ctx.stringValue("DescribeRestoreJobsResponse.Message"));<NEW_LINE>describeRestoreJobsResponse.setTotalCount(_ctx.integerValue("DescribeRestoreJobsResponse.TotalCount"));<NEW_LINE>describeRestoreJobsResponse.setPageSize(_ctx.integerValue("DescribeRestoreJobsResponse.PageSize"));<NEW_LINE>describeRestoreJobsResponse.setPageNumber(_ctx.integerValue("DescribeRestoreJobsResponse.PageNumber"));<NEW_LINE>List<RestoreJob> restoreJobs = new ArrayList<RestoreJob>();<NEW_LINE>for (int i = 0; i < _ctx.lengthValue("DescribeRestoreJobsResponse.RestoreJobs.Length"); i++) {<NEW_LINE>RestoreJob restoreJob = new RestoreJob();<NEW_LINE>restoreJob.setCreatedTime(_ctx.longValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].CreatedTime"));<NEW_LINE>restoreJob.setUpdatedTime(_ctx.longValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].UpdatedTime"));<NEW_LINE>restoreJob.setRestoreId(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].RestoreId"));<NEW_LINE>restoreJob.setClientId(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].ClientId"));<NEW_LINE>restoreJob.setVaultId(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].VaultId"));<NEW_LINE>restoreJob.setSnapshotId(_ctx.stringValue<MASK><NEW_LINE>restoreJob.setSnapshotHash(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].SnapshotHash"));<NEW_LINE>restoreJob.setRestoreName(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].RestoreName"));<NEW_LINE>restoreJob.setSource(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].Source"));<NEW_LINE>restoreJob.setTarget(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].Target"));<NEW_LINE>restoreJob.setStatus(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].Status"));<NEW_LINE>restoreJob.setRestoreType(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].RestoreType"));<NEW_LINE>restoreJob.setInstanceId(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].InstanceId"));<NEW_LINE>restoreJob.setExtra(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].Extra"));<NEW_LINE>restoreJob.setSpeed(_ctx.longValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].Speed"));<NEW_LINE>restoreJob.setDuration(_ctx.longValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].Duration"));<NEW_LINE>restoreJob.setCompleteTime(_ctx.longValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].CompleteTime"));<NEW_LINE>restoreJob.setErrorCount(_ctx.longValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].ErrorCount"));<NEW_LINE>restoreJob.setBytesDone(_ctx.longValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].BytesDone"));<NEW_LINE>restoreJob.setBytesTotal(_ctx.longValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].BytesTotal"));<NEW_LINE>restoreJob.setItemsDone(_ctx.longValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].ItemsDone"));<NEW_LINE>restoreJob.setItemsTotal(_ctx.longValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].ItemsTotal"));<NEW_LINE>restoreJob.setActualBytes(_ctx.longValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].ActualBytes"));<NEW_LINE>restoreJob.setPercentage(_ctx.integerValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].Percentage"));<NEW_LINE>restoreJob.setExitCode(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].ExitCode"));<NEW_LINE>restoreJob.setInstanceName(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].InstanceName"));<NEW_LINE>restoreJob.setErrorType(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].ErrorType"));<NEW_LINE>restoreJob.setSourceClientId(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].SourceClientId"));<NEW_LINE>restoreJob.setGatewayId(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].GatewayId"));<NEW_LINE>restoreJob.setGatewayName(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].GatewayName"));<NEW_LINE>restoreJob.setErrorMessage(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].ErrorMessage"));<NEW_LINE>restoreJob.setErrorFile(_ctx.stringValue("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].ErrorFile"));<NEW_LINE>restoreJobs.add(restoreJob);<NEW_LINE>}<NEW_LINE>describeRestoreJobsResponse.setRestoreJobs(restoreJobs);<NEW_LINE>return describeRestoreJobsResponse;<NEW_LINE>} | ("DescribeRestoreJobsResponse.RestoreJobs[" + i + "].SnapshotId")); |
144,153 | private static MethodHandle createNoPermissionsInvoker() {<NEW_LINE>final String className = "NoPermissionsInvoker";<NEW_LINE>final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);<NEW_LINE>cw.visit(Opcodes.V1_7, ACC_PUBLIC | ACC_SUPER | ACC_FINAL, className, null, "java/lang/Object", null);<NEW_LINE>final Type objectType = Type.getType(Object.class);<NEW_LINE>final Type methodHandleType = Type.getType(MethodHandle.class);<NEW_LINE>final InstructionAdapter mv = new InstructionAdapter(cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "invoke", Type.getMethodDescriptor(Type.VOID_TYPE, methodHandleType, objectType), null, null));<NEW_LINE>mv.visitCode();<NEW_LINE>mv.visitVarInsn(ALOAD, 0);<NEW_LINE><MASK><NEW_LINE>mv.invokevirtual(methodHandleType.getInternalName(), "invokeExact", Type.getMethodDescriptor(Type.VOID_TYPE, objectType), false);<NEW_LINE>mv.visitInsn(RETURN);<NEW_LINE>mv.visitMaxs(0, 0);<NEW_LINE>mv.visitEnd();<NEW_LINE>cw.visitEnd();<NEW_LINE>final byte[] bytes = cw.toByteArray();<NEW_LINE>final ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public ClassLoader run() {<NEW_LINE>return new SecureClassLoader(null) {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>protected Class<?> findClass(final String name) throws ClassNotFoundException {<NEW_LINE>if (name.equals(className)) {<NEW_LINE>return defineClass(name, bytes, 0, bytes.length, new ProtectionDomain(new CodeSource(null, (CodeSigner[]) null), new Permissions()));<NEW_LINE>}<NEW_LINE>throw new ClassNotFoundException(name);<NEW_LINE>}<NEW_LINE>};<NEW_LINE>}<NEW_LINE>});<NEW_LINE>try {<NEW_LINE>return MethodHandles.lookup().findStatic(Class.forName(className, true, loader), "invoke", MethodType.methodType(void.class, MethodHandle.class, Object.class));<NEW_LINE>} catch (final ReflectiveOperationException e) {<NEW_LINE>throw new AssertionError(e.getMessage(), e);<NEW_LINE>}<NEW_LINE>} | mv.visitVarInsn(ALOAD, 1); |
466,533 | private Set<String> checkSteps(final Set<String> schemeIds, final List<WorkflowStep> steps) throws AlreadyExistException {<NEW_LINE>final ImmutableSet.Builder<String> setBuilder = new ImmutableSet.Builder<>();<NEW_LINE>for (final WorkflowStep step : steps) {<NEW_LINE>WorkflowStep repeatStep = null;<NEW_LINE>try {<NEW_LINE>repeatStep = this.workflowAPI.findStep(step.getId());<NEW_LINE>} catch (Exception e) {<NEW_LINE>repeatStep = null;<NEW_LINE>}<NEW_LINE>if (null != repeatStep) {<NEW_LINE>throw new AlreadyExistException("Already exist a step with the same id (" + repeatStep.getId() + "). Create different step with the same id is not allowed. Please change your workflow step id.");<NEW_LINE>}<NEW_LINE>if (!schemeIds.contains(step.getSchemeId())) {<NEW_LINE>throw new IllegalArgumentException("Does not exists the scheme " + step.getSchemeId() + " on the step " + step.getId() + ". Create a step with a right scheme id.");<NEW_LINE>}<NEW_LINE>setBuilder.<MASK><NEW_LINE>}<NEW_LINE>return setBuilder.build();<NEW_LINE>} | add(step.getId()); |
1,744,453 | // snippet-start:[iam.java2.create_user.main]<NEW_LINE>public static String createIAMUser(IamClient iam, String username) {<NEW_LINE>try {<NEW_LINE>// Create an IamWaiter object<NEW_LINE>IamWaiter iamWaiter = iam.waiter();<NEW_LINE>CreateUserRequest request = CreateUserRequest.builder().<MASK><NEW_LINE>CreateUserResponse response = iam.createUser(request);<NEW_LINE>// Wait until the user is created<NEW_LINE>GetUserRequest userRequest = GetUserRequest.builder().userName(response.user().userName()).build();<NEW_LINE>WaiterResponse<GetUserResponse> waitUntilUserExists = iamWaiter.waitUntilUserExists(userRequest);<NEW_LINE>waitUntilUserExists.matched().response().ifPresent(System.out::println);<NEW_LINE>return response.user().userName();<NEW_LINE>} catch (IamException e) {<NEW_LINE>System.err.println(e.awsErrorDetails().errorMessage());<NEW_LINE>System.exit(1);<NEW_LINE>}<NEW_LINE>return "";<NEW_LINE>} | userName(username).build(); |
1,457,312 | private void createPlayers(int numPlayers) {<NEW_LINE>// add missing player panels<NEW_LINE>if (numPlayers > players.size()) {<NEW_LINE>while (players.size() != numPlayers) {<NEW_LINE>TablePlayerPanel playerPanel = new TablePlayerPanel();<NEW_LINE>PlayerType playerType = PlayerType.HUMAN;<NEW_LINE>if (prefPlayerTypes.size() >= players.size() && !players.isEmpty()) {<NEW_LINE>playerType = prefPlayerTypes.get(players.size() - 1);<NEW_LINE>}<NEW_LINE>playerPanel.init(players.size() + 2, playerType);<NEW_LINE>players.add(playerPanel);<NEW_LINE>playerPanel.addPlayerTypeEventListener((Listener<Event>) event -> drawPlayers());<NEW_LINE>}<NEW_LINE>} else // remove player panels no longer needed<NEW_LINE>if (numPlayers < players.size()) {<NEW_LINE>while (players.size() != numPlayers) {<NEW_LINE>players.remove(<MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>drawPlayers();<NEW_LINE>} | players.size() - 1); |
1,098,083 | private static Result constructResult(Pair leftPair, Pair rightPair) {<NEW_LINE>long symbolValue = 4537077L * leftPair.getValue() + rightPair.getValue();<NEW_LINE>String text = String.valueOf(symbolValue);<NEW_LINE>StringBuffer buffer = new StringBuffer(14);<NEW_LINE>for (int i = 13 - text.length(); i > 0; i--) {<NEW_LINE>buffer.append('0');<NEW_LINE>}<NEW_LINE>buffer.append(text);<NEW_LINE>int checkDigit = 0;<NEW_LINE>for (int i = 0; i < 13; i++) {<NEW_LINE>int digit = buffer.charAt(i) - '0';<NEW_LINE>checkDigit += (((i & 0x01) == 0<MASK><NEW_LINE>}<NEW_LINE>checkDigit = 10 - (checkDigit % 10);<NEW_LINE>if (checkDigit == 10) {<NEW_LINE>checkDigit = 0;<NEW_LINE>}<NEW_LINE>buffer.append(checkDigit);<NEW_LINE>ResultPoint[] leftPoints = leftPair.getFinderPattern().getResultPoints();<NEW_LINE>ResultPoint[] rightPoints = rightPair.getFinderPattern().getResultPoints();<NEW_LINE>return new Result(String.valueOf(buffer.toString()), null, new ResultPoint[] { leftPoints[0], leftPoints[1], rightPoints[0], rightPoints[1] }, BarcodeFormat.RSS14);<NEW_LINE>} | ) ? 3 * digit : digit); |
625,196 | protected static Member[] expandMultiPositionSlicerMembers(Member[] members, Evaluator evaluator) {<NEW_LINE>Map<Hierarchy, Set<Member>> mapOfSlicerMembers = null;<NEW_LINE>if (evaluator instanceof RolapEvaluator) {<NEW_LINE>// get the slicer members from the evaluator<NEW_LINE>mapOfSlicerMembers = ((<MASK><NEW_LINE>}<NEW_LINE>if (mapOfSlicerMembers != null) {<NEW_LINE>List<Member> listOfMembers = new ArrayList<Member>();<NEW_LINE>// Iterate the given list of members, removing any whose hierarchy<NEW_LINE>// has multiple members on the slicer axis<NEW_LINE>for (Member member : members) {<NEW_LINE>Hierarchy hierarchy = member.getHierarchy();<NEW_LINE>if (!mapOfSlicerMembers.containsKey(hierarchy) || mapOfSlicerMembers.get(hierarchy).size() < 2 || member instanceof RolapResult.CompoundSlicerRolapMember) {<NEW_LINE>listOfMembers.add(member);<NEW_LINE>} else {<NEW_LINE>listOfMembers.addAll(mapOfSlicerMembers.get(hierarchy));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>members = listOfMembers.toArray(new Member[listOfMembers.size()]);<NEW_LINE>}<NEW_LINE>return members;<NEW_LINE>} | RolapEvaluator) evaluator).getSlicerMembersByHierarchy(); |
1,552,755 | public void marshall(AlarmModelVersionSummary alarmModelVersionSummary, ProtocolMarshaller protocolMarshaller) {<NEW_LINE>if (alarmModelVersionSummary == null) {<NEW_LINE>throw new SdkClientException("Invalid argument passed to marshall(...)");<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>protocolMarshaller.marshall(alarmModelVersionSummary.getAlarmModelName(), ALARMMODELNAME_BINDING);<NEW_LINE>protocolMarshaller.marshall(alarmModelVersionSummary.getAlarmModelArn(), ALARMMODELARN_BINDING);<NEW_LINE>protocolMarshaller.marshall(alarmModelVersionSummary.getAlarmModelVersion(), ALARMMODELVERSION_BINDING);<NEW_LINE>protocolMarshaller.marshall(alarmModelVersionSummary.getRoleArn(), ROLEARN_BINDING);<NEW_LINE>protocolMarshaller.marshall(alarmModelVersionSummary.getCreationTime(), CREATIONTIME_BINDING);<NEW_LINE>protocolMarshaller.marshall(<MASK><NEW_LINE>protocolMarshaller.marshall(alarmModelVersionSummary.getStatus(), STATUS_BINDING);<NEW_LINE>protocolMarshaller.marshall(alarmModelVersionSummary.getStatusMessage(), STATUSMESSAGE_BINDING);<NEW_LINE>} catch (Exception e) {<NEW_LINE>throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);<NEW_LINE>}<NEW_LINE>} | alarmModelVersionSummary.getLastUpdateTime(), LASTUPDATETIME_BINDING); |
1,020,238 | public void resize(int width, int height, int dx, int dy) {<NEW_LINE>Tile[][] newMap = new Tile[height][width];<NEW_LINE>int[][] newFlags = <MASK><NEW_LINE>HashMap<Object, Properties> newTileInstanceProperties = new HashMap<>();<NEW_LINE>int maxX = Math.min(width, this.width + dx);<NEW_LINE>int maxY = Math.min(height, this.height + dy);<NEW_LINE>for (int x = Math.max(0, dx); x < maxX; x++) {<NEW_LINE>for (int y = Math.max(0, dy); y < maxY; y++) {<NEW_LINE>newMap[y][x] = getTileAt(x - dx, y - dy);<NEW_LINE>newFlags[y][x] = getFlagsAt(x - dx, y - dy);<NEW_LINE>Properties tip = getTileInstancePropertiesAt(x - dx, y - dy);<NEW_LINE>if (tip != null) {<NEW_LINE>newTileInstanceProperties.put(new Point(x, y), tip);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>tileMap = newMap;<NEW_LINE>flags = newFlags;<NEW_LINE>tileInstanceProperties = newTileInstanceProperties;<NEW_LINE>this.width = width;<NEW_LINE>this.height = height;<NEW_LINE>} | new int[height][width]; |
1,398,530 | private State buildState() {<NEW_LINE>State state = new State();<NEW_LINE>List<ProjectInternal> orderedProjects = Ordering.usingToString().sortedCopy(projectRegistry.getAllProjects());<NEW_LINE>for (ProjectInternal project : orderedProjects) {<NEW_LINE>if (project.getPlugins().hasPlugin(ComponentModelBasePlugin.class)) {<NEW_LINE>ModelRegistry modelRegistry = projectModelResolver.resolveProjectModel(project.getPath());<NEW_LINE>ModelMap<NativeComponentSpec> components = modelRegistry.realize("components", ModelTypes.modelMap(NativeComponentSpec.class));<NEW_LINE>for (NativeBinarySpecInternal binary : allBinariesOf(components.withType(VariantComponentSpec.class))) {<NEW_LINE>state.registerBinary(binary);<NEW_LINE>}<NEW_LINE>ModelMap<Object> testSuites = modelRegistry.find("testSuites", ModelTypes.modelMap(Object.class));<NEW_LINE>if (testSuites != null) {<NEW_LINE>for (NativeBinarySpecInternal binary : allBinariesOf(testSuites.withType(NativeComponentSpec.class).withType(VariantComponentSpec.class))) {<NEW_LINE>state.registerBinary(binary);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>for (NativeBinarySpecInternal nativeBinary : state.dependencies.keySet()) {<NEW_LINE>for (NativeLibraryBinary libraryBinary : nativeBinary.getDependentBinaries()) {<NEW_LINE>// Skip prebuilt libraries<NEW_LINE>if (libraryBinary instanceof NativeBinarySpecInternal) {<NEW_LINE>// Unfortunate cast! see LibraryBinaryLocator<NEW_LINE>state.dependencies.get(nativeBinary).add((NativeBinarySpecInternal) libraryBinary);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (testSupport != null) {<NEW_LINE>state.dependencies.get(nativeBinary).addAll<MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>return state;<NEW_LINE>} | (testSupport.getTestDependencies(nativeBinary)); |
1,730,198 | public Object execute(CommandLine commandLine) throws Exception {<NEW_LINE>IInterpreterManager manager = InterpreterManagersAPI.getPythonInterpreterManager();<NEW_LINE>IInterpreterInfo[] existing = manager.getInterpreterInfos();<NEW_LINE>HashSet<String> skip = new HashSet<String>();<NEW_LINE>for (IInterpreterInfo info : existing) {<NEW_LINE>skip.add(info.getExecutableOrJar());<NEW_LINE>}<NEW_LINE>String path = commandLine.getValue(Options.PATH_OPTION);<NEW_LINE>if (!skip.contains(path)) {<NEW_LINE>IInterpreterInfo info = manager.createInterpreterInfo(path, new NullProgressMonitor(), false);<NEW_LINE>if (commandLine.hasOption(Options.NAME_OPTION)) {<NEW_LINE>info.setName(commandLine.getValue(Options.NAME_OPTION));<NEW_LINE>} else {<NEW_LINE>info.setName(FileUtils.getBaseName(path).replace(".exe", ""));<NEW_LINE>}<NEW_LINE>IInterpreterInfo[] updated = new <MASK><NEW_LINE>System.arraycopy(existing, 0, updated, 0, existing.length);<NEW_LINE>updated[updated.length - 1] = info;<NEW_LINE>manager.setInfos(updated, skip, new NullProgressMonitor());<NEW_LINE>return Services.getMessage("python.interpreter.added", path);<NEW_LINE>}<NEW_LINE>return Services.getMessage("python.interpreter.exists", path);<NEW_LINE>} | IInterpreterInfo[existing.length + 1]; |
969,529 | public boolean deny(RealmModel realm, String userCode) {<NEW_LINE>try {<NEW_LINE>OAuth2DeviceCodeModel deviceCode = findDeviceCodeByUserCode(realm, userCode);<NEW_LINE>if (deviceCode == null) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>OAuth2DeviceCodeModel denied = deviceCode.deny();<NEW_LINE>BasicCache<String, ActionTokenValueEntity<MASK><NEW_LINE>cache.replace(denied.serializeKey(), new ActionTokenValueEntity(denied.toMap()));<NEW_LINE>return true;<NEW_LINE>} catch (HotRodClientException re) {<NEW_LINE>// No need to retry. The hotrod (remoteCache) has some retries in itself in case of some random network error happened.<NEW_LINE>// In case of lock conflict, we don't want to retry anyway as there was likely an attempt to remove the code from different place.<NEW_LINE>if (logger.isDebugEnabled()) {<NEW_LINE>logger.debugf(re, "Failed when denying device user code %s", userCode);<NEW_LINE>}<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>} | > cache = codeCache.get(); |
1,360,744 | private void drawLineRange(GC gc, int startLine, int endLine, int x, int w) {<NEW_LINE>final int viewPortWidth = fTextWidget.getClientArea().width;<NEW_LINE>for (int line = startLine; line <= endLine; line++) {<NEW_LINE>int lineOffset = fTextWidget.getOffsetAtLine(line);<NEW_LINE>// line end offset including line delimiter<NEW_LINE>int lineEndOffset;<NEW_LINE>if (line < fTextWidget.getLineCount() - 1) {<NEW_LINE>lineEndOffset = fTextWidget.getOffsetAtLine(line + 1);<NEW_LINE>} else {<NEW_LINE>lineEndOffset = fTextWidget.getCharCount();<NEW_LINE>}<NEW_LINE>// line length excluding line delimiter<NEW_LINE>int lineLength = lineEndOffset - lineOffset;<NEW_LINE>while (lineLength > 0) {<NEW_LINE>char c = fTextWidget.getTextRange(lineOffset + lineLength - 1, 1).charAt(0);<NEW_LINE>if (c != '\r' && c != '\n') {<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>--lineLength;<NEW_LINE>}<NEW_LINE>// compute coordinates of last character on line<NEW_LINE>Point endOfLine = fTextWidget.getLocationAtOffset(lineOffset + lineLength);<NEW_LINE>if (x - endOfLine.x > viewPortWidth) {<NEW_LINE>// line is not visible<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>// Y-coordinate of line<NEW_LINE>int <MASK><NEW_LINE>// compute first visible char offset<NEW_LINE>int startOffset;<NEW_LINE>try {<NEW_LINE>startOffset = fTextWidget.getOffsetAtLocation(new Point(x, y)) - 1;<NEW_LINE>if (startOffset - 2 <= lineOffset) {<NEW_LINE>startOffset = lineOffset;<NEW_LINE>}<NEW_LINE>} catch (IllegalArgumentException iae) {<NEW_LINE>startOffset = lineOffset;<NEW_LINE>}<NEW_LINE>// compute last visible char offset<NEW_LINE>int endOffset;<NEW_LINE>if (x + w >= endOfLine.x) {<NEW_LINE>// line end is visible<NEW_LINE>endOffset = lineEndOffset;<NEW_LINE>} else {<NEW_LINE>try {<NEW_LINE>endOffset = fTextWidget.getOffsetAtLocation(new Point(x + w - 1, y)) + 1;<NEW_LINE>if (endOffset + 2 >= lineEndOffset) {<NEW_LINE>endOffset = lineEndOffset;<NEW_LINE>}<NEW_LINE>} catch (IllegalArgumentException iae) {<NEW_LINE>endOffset = lineEndOffset;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// draw character range<NEW_LINE>if (endOffset > startOffset) {<NEW_LINE>drawCharRange(gc, startOffset, endOffset);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | y = fTextWidget.getLinePixel(line); |
1,641,531 | private List<ImmutablePair<String, Object>> buildStatistics() {<NEW_LINE>Summary heap = getJVMMemory(MemoryType.HEAP);<NEW_LINE>Summary nonHeap = getJVMMemory(MemoryType.NON_HEAP);<NEW_LINE>List<ImmutablePair<String, Object>> memoryStatistics = new ArrayList<>();<NEW_LINE>memoryStatistics.add(ImmutablePair.of("mockServerPort", getPort()));<NEW_LINE>memoryStatistics.add(ImmutablePair.of("eventLogSize", currentLogEntriesCount.get()));<NEW_LINE>memoryStatistics.add(ImmutablePair.of("maxLogEntries", configuration.maxLogEntries()));<NEW_LINE>memoryStatistics.add(ImmutablePair.of("expectationsSize", currentExpectationsCount.get()));<NEW_LINE>memoryStatistics.add(ImmutablePair.of("maxExpectations", configuration.maxExpectations()));<NEW_LINE>memoryStatistics.add(ImmutablePair.of("heapInitialAllocation", heap.getNet().getInit()));<NEW_LINE>memoryStatistics.add(ImmutablePair.of("heapUsed", heap.getNet().getUsed()));<NEW_LINE>memoryStatistics.add(ImmutablePair.of("heapCommitted", heap.getNet<MASK><NEW_LINE>memoryStatistics.add(ImmutablePair.of("heapMaxAllowed", heap.getNet().getMax()));<NEW_LINE>memoryStatistics.add(ImmutablePair.of("nonHeapInitialAllocation", nonHeap.getNet().getInit()));<NEW_LINE>memoryStatistics.add(ImmutablePair.of("nonHeapUsed", nonHeap.getNet().getUsed()));<NEW_LINE>memoryStatistics.add(ImmutablePair.of("nonHeapCommitted", nonHeap.getNet().getCommitted()));<NEW_LINE>memoryStatistics.add(ImmutablePair.of("nonHeapMaxAllowed", nonHeap.getNet().getMax()));<NEW_LINE>return memoryStatistics;<NEW_LINE>} | ().getCommitted())); |
695,530 | public void onBindViewHolder(@NonNull ViewHolder holder, int position) {<NEW_LINE>if (holder.getBindingAdapterPosition() == statusList.size()) {<NEW_LINE>holder.name.setText(R.string.add);<NEW_LINE>holder.color.setVisibility(View.INVISIBLE);<NEW_LINE>holder.color.setBackgroundColor(Color.TRANSPARENT);<NEW_LINE>holder.cancel.setImageResource(R.drawable.ic_add);<NEW_LINE>Global.setTint(holder.cancel.getDrawable());<NEW_LINE>holder.cancel.setOnClickListener(null);<NEW_LINE>holder.master.setOnClickListener(v -> updateStatus(null));<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>Status status = statusList.get(holder.getBindingAdapterPosition());<NEW_LINE>holder.name.setText(status.name);<NEW_LINE>holder.color.setVisibility(View.VISIBLE);<NEW_LINE>holder.color.setBackgroundColor(status.opaqueColor());<NEW_LINE>holder.cancel.setImageResource(R.drawable.ic_close);<NEW_LINE>holder.master.setOnClickListener(v -> updateStatus(status));<NEW_LINE>holder.cancel.setOnClickListener(v -> {<NEW_LINE>StatusManager.remove(status);<NEW_LINE>notifyItemRemoved<MASK><NEW_LINE>statusList.remove(status);<NEW_LINE>});<NEW_LINE>} | (statusList.indexOf(status)); |
870,763 | final GetFlowLogsIntegrationTemplateResult executeGetFlowLogsIntegrationTemplate(GetFlowLogsIntegrationTemplateRequest getFlowLogsIntegrationTemplateRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(getFlowLogsIntegrationTemplateRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<GetFlowLogsIntegrationTemplateRequest> request = null;<NEW_LINE>Response<GetFlowLogsIntegrationTemplateResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new GetFlowLogsIntegrationTemplateRequestMarshaller().marshall(super.beforeMarshalling(getFlowLogsIntegrationTemplateRequest));<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, "GetFlowLogsIntegrationTemplate");<NEW_LINE>request.<MASK><NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>StaxResponseHandler<GetFlowLogsIntegrationTemplateResult> responseHandler = new StaxResponseHandler<GetFlowLogsIntegrationTemplateResult>(new GetFlowLogsIntegrationTemplateResultStaxUnmarshaller());<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.ADVANCED_CONFIG, advancedConfig); |
240,427 | public static void main(String[] args) {<NEW_LINE>String file1 = UtilIO.pathExample("stitch/kayak_01.jpg");<NEW_LINE>String file2 = UtilIO.pathExample("stitch/kayak_02.jpg");<NEW_LINE>InterestPointDetector<GrayF32> detector = FactoryInterestPoint.fastHessian(new ConfigFastHessian(1, 10, -1, 2, 9, 4, 4), GrayF32.class);<NEW_LINE>DescribePointRadiusAngle<GrayF32, TupleDesc_F64> describeA = (DescribePointRadiusAngle) FactoryDescribePointRadiusAngle.surfStable(null, GrayF32.class);<NEW_LINE>ConvertTupleDesc<TupleDesc_F64, TupleDesc_S8> converter = FactoryConvertTupleDesc.real_F64_S8(describeA.createDescription().size());<NEW_LINE>DescribePointRadiusAngle<GrayF32, TupleDesc_S8> describeB = new DescribePointRadiusAngleConvertTuple<>(describeA, converter);<NEW_LINE>ScoreAssociation<TupleDesc_F64> scoreA = FactoryAssociation.scoreSad(TupleDesc_F64.class);<NEW_LINE>ScoreAssociation<TupleDesc_S8> scoreB = FactoryAssociation.scoreSad(TupleDesc_S8.class);<NEW_LINE>BufferedImage image1 = Objects.requireNonNull(UtilImageIO.loadImage(file1));<NEW_LINE>BufferedImage image2 = Objects.requireNonNull<MASK><NEW_LINE>visualize("Original", image1, image2, detector, describeA, scoreA);<NEW_LINE>visualize("Modified", image1, image2, detector, describeB, scoreB);<NEW_LINE>System.out.println("Done");<NEW_LINE>} | (UtilImageIO.loadImage(file2)); |
1,285,855 | public MergeCartResponse mergeCart(Customer customer, Order anonymousCart, boolean priceOrder) throws PricingException {<NEW_LINE>MergeCartResponse mergeCartResponse = new MergeCartResponse();<NEW_LINE>// reconstruct cart items (make sure they are valid)<NEW_LINE>ReconstructCartResponse reconstructCartResponse = reconstructCart(customer, false);<NEW_LINE>mergeCartResponse.setRemovedItems(reconstructCartResponse.getRemovedItems());<NEW_LINE>Order customerCart = reconstructCartResponse.getOrder();<NEW_LINE>if (anonymousCart != null && customerCart != null && anonymousCart.getId().equals(customerCart.getId())) {<NEW_LINE>mergeCartResponse.setMerged(false);<NEW_LINE>} else {<NEW_LINE>mergeCartResponse.setMerged(customerCart != null && customerCart.getOrderItems().size() > 0);<NEW_LINE>}<NEW_LINE>// add anonymous cart items (make sure they are valid)<NEW_LINE>if (anonymousCart != null && (customerCart == null || !customerCart.getId().equals(anonymousCart.getId()))) {<NEW_LINE>if (anonymousCart != null && anonymousCart.getOrderItems() != null && !anonymousCart.getOrderItems().isEmpty()) {<NEW_LINE>if (customerCart == null) {<NEW_LINE>customerCart = orderService.createNewCartForCustomer(customer);<NEW_LINE>}<NEW_LINE>Map<OrderItem, OrderItem> oldNewItemMap = new <MASK><NEW_LINE>customerCart = mergeRegularOrderItems(anonymousCart, mergeCartResponse, customerCart, oldNewItemMap);<NEW_LINE>customerCart = mergeOfferCodes(anonymousCart, customerCart);<NEW_LINE>customerCart = removeExpiredGiftWrapOrderItems(mergeCartResponse, customerCart, oldNewItemMap);<NEW_LINE>customerCart = mergeGiftWrapOrderItems(mergeCartResponse, customerCart, oldNewItemMap);<NEW_LINE>orderService.cancelOrder(anonymousCart);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// copy the customer's email to this order, overriding any previously set email<NEW_LINE>if (customerCart != null && StringUtils.isNotBlank(customer.getEmailAddress())) {<NEW_LINE>customerCart.setEmailAddress(customer.getEmailAddress());<NEW_LINE>customerCart = orderService.save(customerCart, priceOrder);<NEW_LINE>}<NEW_LINE>mergeCartResponse.setOrder(customerCart);<NEW_LINE>return mergeCartResponse;<NEW_LINE>} | HashMap<OrderItem, OrderItem>(); |
522,225 | private boolean completedMockingEndPoints(String httpUrl, String requestJson, String methodName, Object bodyContent) throws java.io.IOException {<NEW_LINE>if (httpUrl.contains("/$MOCK") && methodName.equals("$USE.WIREMOCK")) {<NEW_LINE>MockSteps mockSteps = smartUtils.getMapper().readValue(requestJson, MockSteps.class);<NEW_LINE>if (mockPort > 0) {<NEW_LINE>createWithWireMock(mockSteps, mockPort);<NEW_LINE>LOGGER.info("#SUCCESS: End points simulated via wiremock.");<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>LOGGER.error("\n\n#DISABLED: Mocking was not activated as there was no port configured in the properties file. \n\n " + "Usage: e.g. in your <env host config .properties> file provide- \n " + "mock.api.port=8888\n\n");<NEW_LINE>return false;<NEW_LINE>} else if (httpUrl.contains("/$MOCK") && methodName.equals("$USE.VIRTUOSO")) {<NEW_LINE><MASK><NEW_LINE>// read the content of the "request". This contains the complete rest API.<NEW_LINE>createWithVirtuosoMock(bodyContent != null ? bodyContent.toString() : null);<NEW_LINE>LOGGER.info("#SUCCESS: End point simulated via virtuoso.");<NEW_LINE>return true;<NEW_LINE>} else if (httpUrl.contains("/$MOCK") && methodName.equals("$USE.SIMULATOR")) {<NEW_LINE>LOGGER.info("\n#body:\n" + bodyContent);<NEW_LINE>// read the content of the "request". This contains the complete rest API.<NEW_LINE>createWithLocalMock(bodyContent != null ? bodyContent.toString() : null);<NEW_LINE>LOGGER.info("#SUCCESS: End point simulated via local simulator.");<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>return false;<NEW_LINE>} | LOGGER.info("\n#body:\n" + bodyContent); |
599,310 | private static Bitmap createBorderedBitmap(Bitmap source, int width, int height) {<NEW_LINE>Bitmap dst = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);<NEW_LINE>Canvas canvas = new Canvas(dst);<NEW_LINE>if (DEBUG_PAINT) {<NEW_LINE>Paint dpaint = new Paint();<NEW_LINE>dpaint.setColor(0xff0000ff);<NEW_LINE>dpaint.setStyle(Paint.Style.FILL);<NEW_LINE>canvas.drawPaint(dpaint);<NEW_LINE>}<NEW_LINE>BitmapShader shader = new BitmapShader(source, Shader.TileMode.<MASK><NEW_LINE>Paint paint = new Paint();<NEW_LINE>paint.setAntiAlias(true);<NEW_LINE>paint.setShader(shader);<NEW_LINE>RectF rect = new RectF(0.0f, 0.0f, source.getWidth(), source.getHeight());<NEW_LINE>float radius = 12;<NEW_LINE>canvas.translate((height - source.getHeight()) / 2, (width - source.getWidth()) / 2);<NEW_LINE>canvas.drawRoundRect(rect, radius, radius, paint);<NEW_LINE>return dst;<NEW_LINE>} | CLAMP, Shader.TileMode.CLAMP); |
1,639,172 | public boolean canApprove() {<NEW_LINE>if (!isCopy()) {<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>File f = FileUtil.normalizeFile(new File(copyTo.getText()));<NEW_LINE>if (!f.getPath().equals(sharedLibrariesFolder.getPath()) && !(f.getPath()).startsWith(sharedLibrariesFolder.getPath() + File.separatorChar)) {<NEW_LINE>DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(FileChooserAccessory_warning1(sharedLibrariesFolder.getPath())));<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>final File[] files = getSelectedFiles();<NEW_LINE>if (f.exists()) {<NEW_LINE>for (File file : files) {<NEW_LINE>File testFile = new File(<MASK><NEW_LINE>if (testFile.exists()) {<NEW_LINE>if (NotifyDescriptor.YES_OPTION != DialogDisplayer.getDefault().notify(new NotifyDescriptor.Confirmation(FileChooserAccessory_warning3()))) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>if (NotifyDescriptor.YES_OPTION != DialogDisplayer.getDefault().notify(new NotifyDescriptor.Confirmation(FileChooserAccessory_warning2(f.getPath())))) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>for (File file : files) {<NEW_LINE>if (file.isDirectory()) {<NEW_LINE>if (NotifyDescriptor.YES_OPTION != DialogDisplayer.getDefault().notify(new NotifyDescriptor.Confirmation(FileChooserAccessory_warning4()))) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return true;<NEW_LINE>} | f, file.getName()); |
1,572,202 | public List<ColuAccountContext> loadAccountContexts() {<NEW_LINE>List<ColuAccountContext> list = new ArrayList<>();<NEW_LINE>Cursor cursor = null;<NEW_LINE>try {<NEW_LINE>SQLiteQueryWithBlobs blobQuery = new SQLiteQueryWithBlobs(_database);<NEW_LINE>cursor = blobQuery.query(false, "single", new String[] { "id", "addresses", "archived", "blockheight", "coinId" }, null, null, null, null, null, null);<NEW_LINE>while (cursor.moveToNext()) {<NEW_LINE>UUID id = SQLiteQueryWithBlobs.uuidFromBytes(cursor.getBlob(0));<NEW_LINE>boolean isArchived = <MASK><NEW_LINE>int blockHeight = cursor.getInt(3);<NEW_LINE>String coinId = cursor.getString(4);<NEW_LINE>if (coinId == null) {<NEW_LINE>Log.w(LOG_TAG, "Asset not registered in system, and not imported, skipping...");<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>ColuMain coinType = ColuUtils.getColuCoin(coinId);<NEW_LINE>if (coinType == null) {<NEW_LINE>Log.w(LOG_TAG, String.format("Asset with id=%s, skipping...", coinId));<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>Type type = new TypeToken<Collection<String>>() {<NEW_LINE>}.getType();<NEW_LINE>Collection<String> addressStringsList = gson.fromJson(cursor.getString(1), type);<NEW_LINE>Map<AddressType, BtcAddress> addresses = new ArrayMap<>(3);<NEW_LINE>if (addressStringsList != null) {<NEW_LINE>for (String addressString : addressStringsList) {<NEW_LINE>BitcoinAddress address = BitcoinAddress.fromString(addressString);<NEW_LINE>addresses.put(address.getType(), new BtcAddress(coinType, address));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>list.add(new ColuAccountContext(id, coinType, addresses, isArchived, blockHeight));<NEW_LINE>}<NEW_LINE>} finally {<NEW_LINE>if (cursor != null) {<NEW_LINE>cursor.close();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return list;<NEW_LINE>} | cursor.getInt(2) == 1; |
748,960 | private void createCombinedContext(final Image loadedImage, final int major, final int minor, final ImageAddressSpace space, final ImageProcess proc, final JavaRuntime rt, String coreFilePath) {<NEW_LINE>// take the DTFJ context and attempt to combine it with a DDR interactive one<NEW_LINE>Object obj = ctx.getProperties().get(SessionProperties.SESSION_PROPERTY);<NEW_LINE>if (obj == null) {<NEW_LINE>logger.fine("Could not create a new context as the session property has not been set");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>if (!(obj instanceof ISession)) {<NEW_LINE>logger.fine("Could not create a new context as the session type was not recognised [" + obj.getClass().getName() + "]");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>JdmpviewContextManager mgr = (JdmpviewContextManager) ((ISession) obj).getContextManager();<NEW_LINE>CombinedContext cc = (CombinedContext) mgr.createContext(loadedImage, major, <MASK><NEW_LINE>cc.startDDRInteractiveSession(loadedImage, out);<NEW_LINE>cc.getProperties().put(CORE_FILE_PATH_PROPERTY, coreFilePath);<NEW_LINE>cc.getProperties().put(IMAGE_FACTORY_PROPERTY, getFactory());<NEW_LINE>if (ctx.hasPropertyBeenSet(VERBOSE_MODE_PROPERTY)) {<NEW_LINE>cc.getProperties().put(VERBOSE_MODE_PROPERTY, "true");<NEW_LINE>}<NEW_LINE>if (rt != null && cc.isDDRAvailable()) {<NEW_LINE>// attempt to retrieve the system property "java.vm.name"<NEW_LINE>// from the VM that produced the core file<NEW_LINE>try {<NEW_LINE>String vmName = rt.getSystemProperty("java.vm.name");<NEW_LINE>if (vmName != null) {<NEW_LINE>ctx.getProperties().put("java.vm.name", vmName);<NEW_LINE>}<NEW_LINE>} catch (CorruptDataException | DataUnavailable e) {<NEW_LINE>// ignore<NEW_LINE>}<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>// flag to indicate if native libs are required but not present<NEW_LINE>boolean hasLibError = true;<NEW_LINE>String os = cc.getImage().getSystemType().toLowerCase();<NEW_LINE>if (os.contains("linux") || os.contains("aix")) {<NEW_LINE>if (cc.getProcess() != null) {<NEW_LINE>Iterator<?> modules = cc.getProcess().getLibraries();<NEW_LINE>if (modules.hasNext()) {<NEW_LINE>obj = modules.next();<NEW_LINE>if (obj instanceof ImageModule) {<NEW_LINE>// there is at least one native lib available<NEW_LINE>hasLibError = false;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>hasLibError = false;<NEW_LINE>}<NEW_LINE>if (hasLibError) {<NEW_LINE>out.println("Warning: native libraries are not available for " + coreFilePath);<NEW_LINE>}<NEW_LINE>} catch (DataUnavailable e) {<NEW_LINE>logger.log(Level.FINE, "Warning: native libraries are not available for " + coreFilePath);<NEW_LINE>} catch (Exception e) {<NEW_LINE>logger.log(Level.FINE, "Error determining if native libraries are required for " + coreFilePath, e);<NEW_LINE>}<NEW_LINE>} | minor, space, proc, rt); |
1,550,973 | public static void main(String[] args) {<NEW_LINE>// Create an OSSClient instance.<NEW_LINE>OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);<NEW_LINE>try {<NEW_LINE>// Specify the policyText.<NEW_LINE>String policyText = "{\"Statement\": [{\"Effect\": \"Allow\", \"Action\": [\"oss:GetObject\", \"oss:ListObjects\"], \"Resource\": [\"acs:oss:*:*:*/user1/*\"]}], \"Version\": \"1\"}";<NEW_LINE>// Configure the bucket policy.<NEW_LINE>ossClient.setBucketPolicy(bucketName, policyText);<NEW_LINE>// Query bucket policies<NEW_LINE>GetBucketPolicyResult result = ossClient.getBucketPolicy(bucketName);<NEW_LINE>System.out.println("policyText:" + result.getPolicyText());<NEW_LINE>// Delete the policies configured for the bucket.<NEW_LINE>ossClient.deleteBucketPolicy(bucketName);<NEW_LINE>} catch (OSSException oe) {<NEW_LINE>System.out.println(<MASK><NEW_LINE>System.out.println("Error Code: " + oe.getErrorCode());<NEW_LINE>System.out.println("Request ID: " + oe.getRequestId());<NEW_LINE>System.out.println("Host ID: " + oe.getHostId());<NEW_LINE>} catch (ClientException ce) {<NEW_LINE>System.out.println("Error Message: " + ce.getMessage());<NEW_LINE>} finally {<NEW_LINE>ossClient.shutdown();<NEW_LINE>}<NEW_LINE>} | "Error Message: " + oe.getErrorMessage()); |
1,312,953 | public JSONObject toJSON() {<NEW_LINE>JSONObject json = new JSONObject();<NEW_LINE>if (originalLocation != null) {<NEW_LINE>json.put("lat", String.format(Locale.US, "%.5f", originalLocation.getLatitude()));<NEW_LINE>json.put("lon", String.format(Locale.US, "%.5f", originalLocation.getLongitude()));<NEW_LINE>}<NEW_LINE>if (regionLang != null) {<NEW_LINE>json.put("regionLang", regionLang);<NEW_LINE>}<NEW_LINE>json.put("radiusLevel", radiusLevel);<NEW_LINE>json.put("totalLimit", totalLimit);<NEW_LINE>json.put("lang", lang);<NEW_LINE>json.put("transliterateIfMissing", transliterateIfMissing);<NEW_LINE><MASK><NEW_LINE>json.put("sortByName", sortByName);<NEW_LINE>if (searchTypes != null && searchTypes.length > 0) {<NEW_LINE>JSONArray searchTypesArr = new JSONArray();<NEW_LINE>for (ObjectType type : searchTypes) {<NEW_LINE>searchTypesArr.put(type.name());<NEW_LINE>}<NEW_LINE>json.put("searchTypes", searchTypes);<NEW_LINE>}<NEW_LINE>return json;<NEW_LINE>} | json.put("emptyQueryAllowed", emptyQueryAllowed); |
454,356 | private static Single<Response> request(final String method, final String uri, @Nullable final Parameters params, @Nullable final Parameters headers, @Nullable final File cacheFile) {<NEW_LINE>final Builder builder = new Builder();<NEW_LINE>if ("GET".equals(method)) {<NEW_LINE>final HttpUrl.Builder urlBuilder = HttpUrl.parse(uri).newBuilder();<NEW_LINE>if (params != null) {<NEW_LINE>urlBuilder.encodedQuery(params.toString());<NEW_LINE>}<NEW_LINE>builder.url(urlBuilder.build());<NEW_LINE>} else {<NEW_LINE>builder.url(uri);<NEW_LINE>final FormBody.Builder body = new FormBody.Builder();<NEW_LINE>if (params != null) {<NEW_LINE>for (final ImmutablePair<String, String> param : params) {<NEW_LINE>body.add(<MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>if ("PATCH".equals(method)) {<NEW_LINE>builder.patch(body.build());<NEW_LINE>} else {<NEW_LINE>builder.post(body.build());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>addHeaders(builder, headers, cacheFile);<NEW_LINE>final Request request = builder.build();<NEW_LINE>if (Log.isDebug()) {<NEW_LINE>Log.d("HTTP-" + request.method() + ": " + request.url());<NEW_LINE>}<NEW_LINE>return RxOkHttpUtils.request(OK_HTTP_CLIENT, builder.build());<NEW_LINE>} | param.left, param.right); |
1,279,450 | private Common.Payload createTransactionCommonPayload(ProposalPackage.Proposal chaincodeProposal, ByteString proposalResponsePayload, Collection<ProposalResponsePackage.Endorsement> endorsements) throws InvalidProtocolBufferException {<NEW_LINE>TransactionPackage.ChaincodeEndorsedAction.Builder chaincodeEndorsedActionBuilder = TransactionPackage.ChaincodeEndorsedAction.newBuilder();<NEW_LINE>chaincodeEndorsedActionBuilder.setProposalResponsePayload(proposalResponsePayload);<NEW_LINE>chaincodeEndorsedActionBuilder.addAllEndorsements(endorsements);<NEW_LINE>// ChaincodeActionPayload<NEW_LINE>TransactionPackage.ChaincodeActionPayload.Builder chaincodeActionPayloadBuilder = TransactionPackage.ChaincodeActionPayload.newBuilder();<NEW_LINE>chaincodeActionPayloadBuilder.setAction(chaincodeEndorsedActionBuilder.build());<NEW_LINE>// We need to remove any transient fields - they are not part of what the peer uses to calculate hash.<NEW_LINE>ProposalPackage.ChaincodeProposalPayload.Builder chaincodeProposalPayloadNoTransBuilder = ProposalPackage.ChaincodeProposalPayload.newBuilder();<NEW_LINE>chaincodeProposalPayloadNoTransBuilder.mergeFrom(chaincodeProposal.getPayload());<NEW_LINE>chaincodeProposalPayloadNoTransBuilder.clearTransientMap();<NEW_LINE>chaincodeActionPayloadBuilder.setChaincodeProposalPayload(chaincodeProposalPayloadNoTransBuilder.build().toByteString());<NEW_LINE>TransactionPackage.TransactionAction.Builder transactionActionBuilder = TransactionPackage.TransactionAction.newBuilder();<NEW_LINE>Common.Header header = Common.Header.parseFrom(chaincodeProposal.getHeader());<NEW_LINE>if (config.extraLogLevel(10)) {<NEW_LINE>if (null != diagnosticFileDumper) {<NEW_LINE><MASK><NEW_LINE>sb.append("transaction header bytes:" + Arrays.toString(header.toByteArray()));<NEW_LINE>sb.append("\n");<NEW_LINE>sb.append("transaction header sig bytes:" + Arrays.toString(header.getSignatureHeader().toByteArray()));<NEW_LINE>logger.trace("transaction header: " + diagnosticFileDumper.createDiagnosticFile(sb.toString()));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>transactionActionBuilder.setHeader(header.getSignatureHeader());<NEW_LINE>TransactionPackage.ChaincodeActionPayload chaincodeActionPayload = chaincodeActionPayloadBuilder.build();<NEW_LINE>if (config.extraLogLevel(10)) {<NEW_LINE>if (null != diagnosticFileDumper) {<NEW_LINE>logger.trace("transactionActionBuilder.setPayload: " + diagnosticFileDumper.createDiagnosticFile(Arrays.toString(chaincodeActionPayload.toByteString().toByteArray())));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>transactionActionBuilder.setPayload(chaincodeActionPayload.toByteString());<NEW_LINE>// Transaction<NEW_LINE>TransactionPackage.Transaction.Builder transactionBuilder = TransactionPackage.Transaction.newBuilder();<NEW_LINE>transactionBuilder.addActions(transactionActionBuilder.build());<NEW_LINE>Common.Payload.Builder payload = Common.Payload.newBuilder();<NEW_LINE>payload.setHeader(header);<NEW_LINE>payload.setData(transactionBuilder.build().toByteString());<NEW_LINE>return payload.build();<NEW_LINE>} | StringBuilder sb = new StringBuilder(10000); |
1,414,550 | public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {<NEW_LINE>HandleContext<Handler> handleContext = (HandleContext<Handler>) msg;<NEW_LINE>try {<NEW_LINE>Handler handler = handleContext<MASK><NEW_LINE>Object[] args = handleContext.getArgs();<NEW_LINE>Object handleResult = handler.execute(args);<NEW_LINE>FullHttpResponse httpResponse = handleContext.getHttpResponse();<NEW_LINE>if (null != handleResult) {<NEW_LINE>String mimeType = HttpUtil.getMimeType(handler.getProducing()).toString();<NEW_LINE>ResponseBodySerializer serializer = ResponseBodySerializerFactory.getResponseBodySerializer(mimeType);<NEW_LINE>byte[] bodyBytes = serializer.serialize(handleResult);<NEW_LINE>populateHttpResponse(httpResponse, handler.getProducing(), bodyBytes, handler.getHttpStatusCode());<NEW_LINE>} else {<NEW_LINE>populateHttpResponse(httpResponse, handler.getProducing(), new byte[0], handler.getHttpStatusCode());<NEW_LINE>}<NEW_LINE>ctx.writeAndFlush(httpResponse);<NEW_LINE>} finally {<NEW_LINE>ReferenceCountUtil.release(handleContext.getHttpRequest());<NEW_LINE>}<NEW_LINE>} | .getMappingContext().payload(); |
271,699 | private Mono<PagedResponse<ConnectorSettingInner>> listSinglePageAsync() {<NEW_LINE>if (this.client.getEndpoint() == null) {<NEW_LINE>return Mono.<MASK><NEW_LINE>}<NEW_LINE>if (this.client.getSubscriptionId() == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter this.client.getSubscriptionId() is required and cannot be null."));<NEW_LINE>}<NEW_LINE>final String apiVersion = "2020-01-01-preview";<NEW_LINE>final String accept = "application/json";<NEW_LINE>return FluxUtil.withContext(context -> service.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), accept, context)).<PagedResponse<ConnectorSettingInner>>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)).contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));<NEW_LINE>} | error(new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); |
1,040,447 | private void templateDetailsInitIfNotExist(long id, String name, String value) {<NEW_LINE>TransactionLegacy txn = TransactionLegacy.currentTxn();<NEW_LINE>PreparedStatement stmt = null;<NEW_LINE>PreparedStatement stmtInsert = null;<NEW_LINE>boolean insert = false;<NEW_LINE>try {<NEW_LINE>txn.start();<NEW_LINE>stmt = txn.prepareAutoCloseStatement("SELECT id FROM vm_template_details WHERE template_id=? and name=?");<NEW_LINE>stmt.setLong(1, id);<NEW_LINE>stmt.setString(2, name);<NEW_LINE>ResultSet rs = stmt.executeQuery();<NEW_LINE>if (rs == null || !rs.next()) {<NEW_LINE>insert = true;<NEW_LINE>}<NEW_LINE>stmt.close();<NEW_LINE>if (insert) {<NEW_LINE><MASK><NEW_LINE>stmtInsert.setLong(1, id);<NEW_LINE>stmtInsert.setString(2, name);<NEW_LINE>stmtInsert.setString(3, value);<NEW_LINE>if (stmtInsert.executeUpdate() < 1) {<NEW_LINE>throw new CloudRuntimeException("Unable to init template " + id + " datails: " + name);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>txn.commit();<NEW_LINE>} catch (Exception e) {<NEW_LINE>s_logger.warn("Unable to init template " + id + " datails: " + name, e);<NEW_LINE>throw new CloudRuntimeException("Unable to init template " + id + " datails: " + name);<NEW_LINE>}<NEW_LINE>} | stmtInsert = txn.prepareAutoCloseStatement("INSERT INTO vm_template_details(template_id, name, value) VALUES(?, ?, ?)"); |
686,156 | public Object run() throws Exception {<NEW_LINE>Preferences fromPrjPrefs = ProjectUtils.getPreferences(prjFrom, IndentUtils.class, true);<NEW_LINE>if (!fromPrjPrefs.nodeExists(CODE_STYLE_PROFILE) || fromPrjPrefs.node(CODE_STYLE_PROFILE).get(USED_PROFILE, null) == null) {<NEW_LINE>// NOI18N<NEW_LINE>return NbBundle.getMessage(FormattingCustomizerPanel.class, "MSG_No_CodeStyle_Info_To_Import");<NEW_LINE>}<NEW_LINE>ProjectPreferencesFactory newPrefsFactory = new <MASK><NEW_LINE>Preferences toPrjPrefs = newPrefsFactory.projectPrefs;<NEW_LINE>removeAllKidsAndKeys(toPrjPrefs);<NEW_LINE>deepCopy(fromPrjPrefs, toPrjPrefs);<NEW_LINE>// XXX: detect somehow if the basic options are overriden in fromPrjPrefs<NEW_LINE>// and set the flag accordingly in toPrjPrefs<NEW_LINE>// dump(fromPrjPrefs, "fromPrjPrefs");<NEW_LINE>// dump(toPrjPrefs, "toPrjPrefs");<NEW_LINE>return newPrefsFactory;<NEW_LINE>} | ProjectPreferencesFactory(pf.getProject()); |
1,173,890 | private void ensureParentDirectoryExists(ChannelSftp channel, URI uri) {<NEW_LINE>String parentPath = FilenameUtils.<MASK><NEW_LINE>if (parentPath.equals("/")) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>URI parent = uri.resolve(parentPath);<NEW_LINE>try {<NEW_LINE>channel.lstat(parentPath);<NEW_LINE>return;<NEW_LINE>} catch (com.jcraft.jsch.SftpException e) {<NEW_LINE>if (e.id != ChannelSftp.SSH_FX_NO_SUCH_FILE) {<NEW_LINE>throw new ResourceException(parent, String.format("Could not lstat resource '%s'.", parent), e);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>ensureParentDirectoryExists(channel, parent);<NEW_LINE>try {<NEW_LINE>channel.mkdir(parentPath);<NEW_LINE>} catch (com.jcraft.jsch.SftpException e) {<NEW_LINE>throw new ResourceException(parent, String.format("Could not create resource '%s'.", parent), e);<NEW_LINE>}<NEW_LINE>} | getFullPathNoEndSeparator(uri.getPath()); |
1,846,025 | public void enterSssgd_member(A10Parser.Sssgd_memberContext ctx) {<NEW_LINE>Optional<String> maybeName = toString(ctx, ctx.slb_server_name());<NEW_LINE>if (!maybeName.isPresent()) {<NEW_LINE>// dummy<NEW_LINE>_currentServiceGroupMember = new ServiceGroupMember(ctx.slb_server_name().getText(), -1);<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>String name = maybeName.get();<NEW_LINE>// Extract port number<NEW_LINE>Optional<Integer> maybePort;<NEW_LINE>// ACOS v2 - port is embedded in the reference "word"<NEW_LINE>if (ctx.sssgd_member_tail().sssgd_member_acos2_tail() != null) {<NEW_LINE>if (!name.contains(":")) {<NEW_LINE>warn(ctx, "Member reference must include port when not specified separately");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>maybePort = toPortNumber(ctx, name.substring(name.lastIndexOf(":") + 1));<NEW_LINE>name = name.substring(0, name.lastIndexOf(":"));<NEW_LINE>} else {<NEW_LINE>// ACOS v4+ - port is specified separately<NEW_LINE>assert ctx.sssgd_member_tail().sssgd_member_port_number() != null;<NEW_LINE>maybePort = toInteger(ctx, ctx.sssgd_member_tail().sssgd_member_port_number().port_number());<NEW_LINE>}<NEW_LINE>if (!maybePort.isPresent()) {<NEW_LINE>// dummy<NEW_LINE>_currentServiceGroupMember = new ServiceGroupMember(name, -1);<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>int port = maybePort.get();<NEW_LINE>Server server = _c.getServers().get(name);<NEW_LINE>if (server == null) {<NEW_LINE>warn(ctx, String.format("Specified server '%s' does not exist.", name));<NEW_LINE>// dummy<NEW_LINE>_currentServiceGroupMember = new ServiceGroupMember(name, port);<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>_currentServiceGroupMember = _currentServiceGroup.getOrCreateMember(name, port);<NEW_LINE>// Create port for specified server if it doesn't already exist<NEW_LINE>if (!server.getPorts().containsKey(new ServerPort.ServerPortAndType(port, _currentServiceGroup.getType()))) {<NEW_LINE>_c.defineStructure(SERVER, name, ctx);<NEW_LINE>server.createPort(<MASK><NEW_LINE>}<NEW_LINE>_c.referenceStructure(SERVER, name, SERVICE_GROUP_MEMBER, ctx.start.getLine());<NEW_LINE>} | port, _currentServiceGroup.getType()); |
10,048 | public void flush() {<NEW_LINE>// TODO: add a feature to Management Center to sync cache to db completely<NEW_LINE>try {<NEW_LINE>MapOperation mapFlushOperation = operationProvider.createMapFlushOperation(name);<NEW_LINE>BinaryOperationFactory operationFactory = new BinaryOperationFactory(mapFlushOperation, getNodeEngine());<NEW_LINE>Map<Integer, Object> results = <MASK><NEW_LINE>List<Future> futures = new ArrayList<>();<NEW_LINE>for (Entry<Integer, Object> entry : results.entrySet()) {<NEW_LINE>Integer partitionId = entry.getKey();<NEW_LINE>Long count = ((Long) entry.getValue());<NEW_LINE>if (count != 0) {<NEW_LINE>Operation operation = new AwaitMapFlushOperation(name, count);<NEW_LINE>futures.add(operationService.invokeOnPartition(MapService.SERVICE_NAME, operation, partitionId));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>for (Future future : futures) {<NEW_LINE>future.get();<NEW_LINE>}<NEW_LINE>} catch (Throwable t) {<NEW_LINE>throw rethrow(t);<NEW_LINE>}<NEW_LINE>} | operationService.invokeOnAllPartitions(SERVICE_NAME, operationFactory); |
1,546,624 | public static Long round(Long n, Long precision) throws ArithmeticException {<NEW_LINE>long nLong = n.longValue();<NEW_LINE>if (nLong == 0L || precision >= 0) {<NEW_LINE>return n;<NEW_LINE>}<NEW_LINE>long digitsToRound = -precision;<NEW_LINE>int digits = (int) (Math.log10(Math.abs(n.<MASK><NEW_LINE>if (digits <= digitsToRound) {<NEW_LINE>return 0L;<NEW_LINE>}<NEW_LINE>long tenAtScale = (long) tenPower(digitsToRound);<NEW_LINE>long middleResult = nLong / tenAtScale;<NEW_LINE>long remainder = nLong % tenAtScale;<NEW_LINE>if (remainder >= 5 * (long) tenPower(digitsToRound - 1)) {<NEW_LINE>middleResult++;<NEW_LINE>} else if (remainder <= -5 * (long) tenPower(digitsToRound - 1)) {<NEW_LINE>middleResult--;<NEW_LINE>}<NEW_LINE>long result = middleResult * tenAtScale;<NEW_LINE>if (Long.signum(result) == Long.signum(nLong)) {<NEW_LINE>return result;<NEW_LINE>} else {<NEW_LINE>throw new ArithmeticException("long overflow");<NEW_LINE>}<NEW_LINE>} | doubleValue())) + 1); |
732,613 | private void internalRegionMultiGet(final Region region, final List<byte[]> subKeys, final boolean readOnlySafe, final CompletableFuture<Map<ByteArray, byte[]>> future, final int retriesLeft, final Errors lastCause, final boolean requireLeader) {<NEW_LINE>final RegionEngine regionEngine = getRegionEngine(<MASK><NEW_LINE>// require leader on retry<NEW_LINE>final RetryRunner retryRunner = retryCause -> internalRegionMultiGet(region, subKeys, readOnlySafe, future, retriesLeft - 1, retryCause, true);<NEW_LINE>final FailoverClosure<Map<ByteArray, byte[]>> closure = new FailoverClosureImpl<>(future, false, retriesLeft, retryRunner);<NEW_LINE>if (regionEngine != null) {<NEW_LINE>if (ensureOnValidEpoch(region, regionEngine, closure)) {<NEW_LINE>final RawKVStore rawKVStore = getRawKVStore(regionEngine);<NEW_LINE>if (this.kvDispatcher == null) {<NEW_LINE>rawKVStore.multiGet(subKeys, readOnlySafe, closure);<NEW_LINE>} else {<NEW_LINE>this.kvDispatcher.execute(() -> rawKVStore.multiGet(subKeys, readOnlySafe, closure));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>final MultiGetRequest request = new MultiGetRequest();<NEW_LINE>request.setKeys(subKeys);<NEW_LINE>request.setReadOnlySafe(readOnlySafe);<NEW_LINE>request.setRegionId(region.getId());<NEW_LINE>request.setRegionEpoch(region.getRegionEpoch());<NEW_LINE>this.rheaKVRpcService.callAsyncWithRpc(request, closure, lastCause, requireLeader);<NEW_LINE>}<NEW_LINE>} | region.getId(), requireLeader); |
948,999 | private static Notification createOrbotNotification(Context context) {<NEW_LINE>NotificationChannelManager.getInstance(context).createNotificationChannelsIfNecessary();<NEW_LINE>NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NotificationChannelManager.ORBOT);<NEW_LINE>builder.setSmallIcon(R.drawable.ic_stat_notify_24dp).setLargeIcon(ResourceUtils.getDrawableAsNotificationBitmap(context, R.mipmap.ic_launcher)).setContentTitle(context.getString(R.string.keyserver_sync_orbot_notif_title)).setContentText(context.getString(R.string.<MASK><NEW_LINE>Intent startOrbotIntent = new Intent(context, OrbotRequiredDialogActivity.class);<NEW_LINE>startOrbotIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);<NEW_LINE>startOrbotIntent.putExtra(OrbotRequiredDialogActivity.EXTRA_START_ORBOT, true);<NEW_LINE>PendingIntent startOrbotPi = PendingIntent.getActivity(context, 0, startOrbotIntent, PendingIntent.FLAG_CANCEL_CURRENT);<NEW_LINE>builder.addAction(R.drawable.ic_stat_tor, context.getString(R.string.keyserver_sync_orbot_notif_start), startOrbotPi);<NEW_LINE>builder.setContentIntent(startOrbotPi);<NEW_LINE>return builder.build();<NEW_LINE>} | keyserver_sync_orbot_notif_msg)).setAutoCancel(true); |
642,896 | private static File prepare() throws IOException {<NEW_LINE>File distributionDirectory = ContainerPathManager.get().getAppHomeDirectory();<NEW_LINE>String name = ApplicationNamesInfo.getInstance().getFullProductName();<NEW_LINE>final String iconPath = AppUIUtil.findIcon(distributionDirectory.getPath());<NEW_LINE>if (iconPath == null) {<NEW_LINE>throw new RuntimeException(ApplicationBundle.message("desktop.entry.icon.missing"<MASK><NEW_LINE>}<NEW_LINE>final File execPath = new File(distributionDirectory, "consulo.sh");<NEW_LINE>if (!execPath.exists()) {<NEW_LINE>throw new RuntimeException(ApplicationBundle.message("desktop.entry.script.missing", distributionDirectory.getPath()));<NEW_LINE>}<NEW_LINE>final String wmClass = AppUIUtil.getFrameClass();<NEW_LINE>final String content = ExecUtil.loadTemplate(CreateDesktopEntryAction.class.getClassLoader(), "entry.desktop", ContainerUtil.newHashMap(Arrays.asList("$NAME$", "$SCRIPT$", "$ICON$", "$WM_CLASS$"), Arrays.asList(name, execPath.getPath(), iconPath, wmClass)));<NEW_LINE>final String entryName = wmClass + ".desktop";<NEW_LINE>final File entryFile = new File(FileUtil.getTempDirectory(), entryName);<NEW_LINE>FileUtil.writeToFile(entryFile, content);<NEW_LINE>entryFile.deleteOnExit();<NEW_LINE>return entryFile;<NEW_LINE>} | , distributionDirectory.getPath())); |
1,810,142 | ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag, JsonElement jsonElement) throws Exception {<NEW_LINE>try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {<NEW_LINE>ActionResult<Wo> result = new ActionResult<>();<NEW_LINE>Business business = new Business(emc);<NEW_LINE>Process process = emc.flag(flag, Process.class);<NEW_LINE>if (null == process) {<NEW_LINE>throw new ExceptionEntityNotExist(flag, Process.class);<NEW_LINE>}<NEW_LINE>Application application = emc.flag(process.getApplication(), Application.class);<NEW_LINE>if (null == application) {<NEW_LINE>throw new ExceptionEntityNotExist(process.getApplication(), Application.class);<NEW_LINE>}<NEW_LINE>if (!business.editable(effectivePerson, application)) {<NEW_LINE>throw new <MASK><NEW_LINE>}<NEW_LINE>Wo wo = new Wo();<NEW_LINE>if (XGsonBuilder.isJsonArray(process.getProjection())) {<NEW_LINE>if (!ThisApplication.projectionExecuteQueue.contains(process.getId())) {<NEW_LINE>ThisApplication.projectionExecuteQueue.send(process.getId());<NEW_LINE>wo.setValue(true);<NEW_LINE>} else {<NEW_LINE>throw new ExceptionAlreadyAddQueue();<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>wo.setValue(false);<NEW_LINE>}<NEW_LINE>result.setData(wo);<NEW_LINE>return result;<NEW_LINE>}<NEW_LINE>} | ExceptionAccessDenied(effectivePerson.getDistinguishedName()); |
861,274 | public static void main(String[] args) {<NEW_LINE>final String USAGE = "\n" + "Usage:\n" + " SetAcl <bucket> [object] <email> <permission>\n\n" + "Where:\n" + " bucket - the bucket to grant permissions on\n" + " object - (optional) the object grant permissions on\n" + " If object is specified, granted permissions will be\n" + " for the object, not the bucket.\n" + " email - The email of the user to set permissions for\n" + " permission - The permission(s) to set. Can be one of:\n" + " FullControl, Read, Write, ReadAcp, WriteAcp\n\n" + "Examples:\n" + " SetAcl testbucket user@example.com read\n" + " SetAcl testbucket testobject user@example.com write\n\n";<NEW_LINE>if (args.length < 3) {<NEW_LINE>System.out.println(USAGE);<NEW_LINE>System.exit(1);<NEW_LINE>}<NEW_LINE>int cur_arg = 0;<NEW_LINE>String bucket_name = args[cur_arg++];<NEW_LINE>String object_key = (args.length > 3) ? args[cur_arg++] : null;<NEW_LINE><MASK><NEW_LINE>String access = args[cur_arg++];<NEW_LINE>if (object_key != null) {<NEW_LINE>setObjectAcl(bucket_name, object_key, email, access);<NEW_LINE>} else {<NEW_LINE>setBucketAcl(bucket_name, email, access);<NEW_LINE>}<NEW_LINE>System.out.println("Done!");<NEW_LINE>} | String email = args[cur_arg++]; |
1,135,938 | protected Object readState(IProject project) throws CoreException {<NEW_LINE>File file = getSerializationFile(project);<NEW_LINE>if (file != null && file.exists()) {<NEW_LINE>try (DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file)))) {<NEW_LINE>String pluginID = in.readUTF();<NEW_LINE>if (!pluginID.equals(JavaCore.PLUGIN_ID))<NEW_LINE>throw new IOException(Messages.build_wrongFileFormat);<NEW_LINE>String kind = in.readUTF();<NEW_LINE>if (// $NON-NLS-1$<NEW_LINE>!kind.equals("STATE"))<NEW_LINE>throw new IOException(Messages.build_wrongFileFormat);<NEW_LINE>if (in.readBoolean())<NEW_LINE>return JavaBuilder.readState(project, in);<NEW_LINE>if (JavaBuilder.DEBUG)<NEW_LINE>// $NON-NLS-1$<NEW_LINE>System.out.println("Saved state thinks last build failed for " + project.getName());<NEW_LINE>} catch (Exception e) {<NEW_LINE>e.printStackTrace();<NEW_LINE>// $NON-NLS-1$<NEW_LINE>throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project " + project.getName(), e));<NEW_LINE>}<NEW_LINE>} else if (JavaBuilder.DEBUG) {<NEW_LINE>if (file == null)<NEW_LINE>// $NON-NLS-1$<NEW_LINE>System.<MASK><NEW_LINE>else<NEW_LINE>// $NON-NLS-1$ //$NON-NLS-2$<NEW_LINE>System.out.println("Build state file " + file.getPath() + " does not exist");<NEW_LINE>}<NEW_LINE>return null;<NEW_LINE>} | out.println("Project does not exist: " + project); |
1,320,097 | private void handleException(Throwable e, Request req, Response resp) throws ServletException, IOException {<NEW_LINE>String location;<NEW_LINE>Class<?> cls = e.getClass();<NEW_LINE>while (cls != null && !cls.equals(Throwable.class)) {<NEW_LINE>location = exception2location_.get(cls.getName());<NEW_LINE>if (location != null) {<NEW_LINE>trace("Exception " + e + " matched. Error page location: " + location);<NEW_LINE>req.setAttribute_(RequestDispatcher.ERROR_EXCEPTION, e);<NEW_LINE>req.setAttribute_(RequestDispatcher.ERROR_EXCEPTION_TYPE, e.getClass());<NEW_LINE>req.setAttribute_(RequestDispatcher.ERROR_REQUEST_URI, req.getRequestURI());<NEW_LINE>req.setAttribute_(RequestDispatcher.ERROR_STATUS_CODE, resp.SC_INTERNAL_SERVER_ERROR);<NEW_LINE><MASK><NEW_LINE>return;<NEW_LINE>}<NEW_LINE>cls = cls.getSuperclass();<NEW_LINE>}<NEW_LINE>if (ServletException.class.isAssignableFrom(e.getClass())) {<NEW_LINE>ServletException se = (ServletException) e;<NEW_LINE>handleException(se.getRootCause(), req, resp);<NEW_LINE>}<NEW_LINE>} | handleError(location, req, resp); |
1,730,897 | public ExitCode run(CommandEnv commandEnv) throws ValidationException, IOException, RepoException {<NEW_LINE>ConfigFileArgs configFileArgs = commandEnv.parseConfigFileArgs(this, /*useSourceRef*/<NEW_LINE>false);<NEW_LINE>Console console = commandEnv.getOptions().get(GeneralOptions.class).console();<NEW_LINE>ConfigWithDependencies config = configLoaderProvider.newLoader(configFileArgs.getConfigPath(), configFileArgs.getSourceRef()).loadWithDependencies(console);<NEW_LINE>if (commandEnv.getOptions().get(GeneralOptions.class).infoListOnly) {<NEW_LINE>listMigrations(commandEnv, config.getConfig());<NEW_LINE>return ExitCode.SUCCESS;<NEW_LINE>}<NEW_LINE>if (configFileArgs.hasWorkflowName()) {<NEW_LINE>ImmutableMap<String, String> context = contextProvider.getContext(config, configFileArgs, configLoaderProvider, commandEnv.getOptions(), console);<NEW_LINE>infoWithFailureHandling(commandEnv.getOptions(), config.getConfig(), <MASK><NEW_LINE>} else {<NEW_LINE>showAllMigrations(commandEnv, config.getConfig());<NEW_LINE>}<NEW_LINE>return ExitCode.SUCCESS;<NEW_LINE>} | configFileArgs.getWorkflowName(), context); |
1,239,680 | private boolean isSystemVmIsoCopyNeeded(File srcIso, File destIso) {<NEW_LINE>if (!destIso.exists()) {<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>boolean copyNeeded = false;<NEW_LINE>try {<NEW_LINE>String srcIsoMd5 = DigestUtils.md5Hex(new FileInputStream(srcIso));<NEW_LINE>String destIsoMd5 = DigestUtils.md5Hex(new FileInputStream(destIso));<NEW_LINE>copyNeeded = !<MASK><NEW_LINE>if (copyNeeded) {<NEW_LINE>s_logger.debug(String.format("MD5 checksum: %s for source ISO: %s is different from MD5 checksum: %s from destination ISO: %s", srcIsoMd5, srcIso.getAbsolutePath(), destIsoMd5, destIso.getAbsolutePath()));<NEW_LINE>}<NEW_LINE>} catch (IOException e) {<NEW_LINE>s_logger.debug(String.format("Unable to compare MD5 checksum for systemvm.iso at source: %s and destination: %s", srcIso.getAbsolutePath(), destIso.getAbsolutePath()), e);<NEW_LINE>}<NEW_LINE>return copyNeeded;<NEW_LINE>} | StringUtils.equals(srcIsoMd5, destIsoMd5); |
384,438 | /*<NEW_LINE>* Initializes the FlowController for this aggregate.<NEW_LINE>*/<NEW_LINE>protected void initFlowController(FlowControllerDeclaration aFlowControllerDeclaration, UimaContextAdmin aParentContext, AnalysisEngineMetaData aAggregateMetadata) throws ResourceInitializationException {<NEW_LINE>String key = aFlowControllerDeclaration.getKey();<NEW_LINE>if (key == null || key.length() == 0) {<NEW_LINE>// default key<NEW_LINE>key = "_FlowController";<NEW_LINE>}<NEW_LINE>Map<String, Object> flowControllerParams = new HashMap<String, Object>(mInitParams);<NEW_LINE>// retrieve the sofa mappings for the FlowControler<NEW_LINE>Map<String, String> sofamap = new TreeMap<String, String>();<NEW_LINE>if (mSofaMappings != null && mSofaMappings.length > 0) {<NEW_LINE>for (int s = 0; s < mSofaMappings.length; s++) {<NEW_LINE>// the mapping is for this analysis engine<NEW_LINE>if (mSofaMappings[s].getComponentKey().equals(key)) {<NEW_LINE>// if component sofa name is null, replace it with the default for TCAS sofa name<NEW_LINE>// This is to support single-view annotators.<NEW_LINE>if (mSofaMappings[s].getComponentSofaName() == null)<NEW_LINE>mSofaMappings[s<MASK><NEW_LINE>sofamap.put(mSofaMappings[s].getComponentSofaName(), mSofaMappings[s].getAggregateSofaName());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>FlowControllerContext ctxt = new FlowControllerContext_impl(aParentContext, key, sofamap, getComponentAnalysisEngineMetaData(), aAggregateMetadata);<NEW_LINE>flowControllerParams.put(PARAM_UIMA_CONTEXT, ctxt);<NEW_LINE>flowControllerParams.put(PARAM_RESOURCE_MANAGER, getResourceManager());<NEW_LINE>mFlowControllerContainer = new FlowControllerContainer();<NEW_LINE>mFlowControllerContainer.initialize(aFlowControllerDeclaration.getSpecifier(), flowControllerParams);<NEW_LINE>} | ].setComponentSofaName(CAS.NAME_DEFAULT_SOFA); |
381,304 | public VirtualMachine attach(String hostName, int port) throws IOException, IllegalConnectorArgumentsException {<NEW_LINE>AttachingConnector socketAttachingConnector = Bootstrap.virtualMachineManager().attachingConnectors().stream().filter(ac -> ac.name().equals(SOCKET_CONNECTOR_NAME)).findFirst().orElseThrow(() -> new RuntimeException("Unable to locate SocketAttachingConnector"));<NEW_LINE>Map<String, Connector.Argument> connectorArgs = socketAttachingConnector.defaultArguments();<NEW_LINE>if (!hostName.isEmpty()) {<NEW_LINE>connectorArgs.get<MASK><NEW_LINE>}<NEW_LINE>connectorArgs.get(CONNECTOR_ARGS_PORT).setValue(String.valueOf(port));<NEW_LINE>LOGGER.info(String.format("Debugger is attaching to: %s:%d", hostName, port));<NEW_LINE>attachedVm = socketAttachingConnector.attach(connectorArgs);<NEW_LINE>this.host = !hostName.isEmpty() ? hostName : LOCAL_HOST;<NEW_LINE>this.port = port;<NEW_LINE>// Todo - enable for launch-mode after implementing debug server client logger<NEW_LINE>if (server.getClientConfigHolder().getKind() == ClientConfigHolder.ClientConfigKind.ATTACH_CONFIG) {<NEW_LINE>server.getOutputLogger().sendDebugServerOutput((String.format("Connected to the target VM, address: " + "'%s:%s'", host, port)));<NEW_LINE>}<NEW_LINE>return attachedVm;<NEW_LINE>} | (CONNECTOR_ARGS_HOST).setValue(hostName); |
514,367 | public void clusterStateProcessed(ClusterState oldState, ClusterState newState) {<NEW_LINE>initializingClones.remove(targetSnapshot);<NEW_LINE>if (updatedEntry != null) {<NEW_LINE>final Snapshot target = updatedEntry.snapshot();<NEW_LINE>final <MASK><NEW_LINE>for (Map.Entry<RepositoryShardId, ShardSnapshotStatus> indexClone : updatedEntry.shardsByRepoShardId().entrySet()) {<NEW_LINE>final ShardSnapshotStatus shardStatusBefore = indexClone.getValue();<NEW_LINE>if (shardStatusBefore.state() != ShardState.INIT) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>final RepositoryShardId repoShardId = indexClone.getKey();<NEW_LINE>runReadyClone(target, sourceSnapshot, shardStatusBefore, repoShardId, repository);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>// Extremely unlikely corner case of master failing over between between starting the clone and<NEW_LINE>// starting shard clones.<NEW_LINE>logger.warn("Did not find expected entry [{}] in the cluster state", cloneEntry);<NEW_LINE>}<NEW_LINE>} | SnapshotId sourceSnapshot = updatedEntry.source(); |
934,015 | public static void main(String[] args) {<NEW_LINE>// create an arbitrary transform from world to camera reference frames<NEW_LINE>Se3_F64 worldToCamera = new Se3_F64();<NEW_LINE>worldToCamera.getT().setTo(5, 10, -7);<NEW_LINE>ConvertRotation3D_F64.eulerToMatrix(EulerType.XYZ, 0.1, -0.3, <MASK><NEW_LINE>ExamplePnP app = new ExamplePnP();<NEW_LINE>// Let's generate observations with no outliers<NEW_LINE>// NOTE: Image observations are in normalized image coordinates NOT pixels<NEW_LINE>List<Point2D3D> observations = app.createObservations(worldToCamera, 100);<NEW_LINE>System.out.println("Truth:");<NEW_LINE>worldToCamera.print();<NEW_LINE>System.out.println();<NEW_LINE>System.out.println("Estimated, assumed no outliers:");<NEW_LINE>app.estimateNoOutliers(observations).print();<NEW_LINE>System.out.println("Estimated, assumed that there are outliers:");<NEW_LINE>app.estimateOutliers(observations).print();<NEW_LINE>System.out.println();<NEW_LINE>System.out.println("Adding outliers");<NEW_LINE>System.out.println();<NEW_LINE>// add a bunch of outliers<NEW_LINE>app.addOutliers(observations, 50);<NEW_LINE>System.out.println("Estimated, assumed no outliers:");<NEW_LINE>app.estimateNoOutliers(observations).print();<NEW_LINE>System.out.println("Estimated, assumed that there are outliers:");<NEW_LINE>app.estimateOutliers(observations).print();<NEW_LINE>} | 0, worldToCamera.getR()); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.