idx int32 46 1.86M | input stringlengths 321 6.6k | target stringlengths 9 1.24k |
|---|---|---|
618,264 | protected List findByCompanyId(String companyId, int begin, int end, OrderByComparator obc) throws SystemException {<NEW_LINE>Session session = null;<NEW_LINE>try {<NEW_LINE>session = openSession();<NEW_LINE>StringBuffer query = new StringBuffer();<NEW_LINE>query.append("FROM AdminConfig IN CLASS com.liferay.portlet.admin.ejb.AdminConfigHBM WHERE ");<NEW_LINE>query.append("companyId = ?");<NEW_LINE>query.append(" ");<NEW_LINE>if (obc != null) {<NEW_LINE>query.append("ORDER BY " + obc.getOrderBy());<NEW_LINE>}<NEW_LINE>Query q = session.createQuery(query.toString());<NEW_LINE>int queryPos = 0;<NEW_LINE>q<MASK><NEW_LINE>List list = new ArrayList();<NEW_LINE>if (getDialect().supportsLimit()) {<NEW_LINE>q.setMaxResults(end - begin);<NEW_LINE>q.setFirstResult(begin);<NEW_LINE>Iterator itr = q.list().iterator();<NEW_LINE>while (itr.hasNext()) {<NEW_LINE>AdminConfigHBM adminConfigHBM = (AdminConfigHBM) itr.next();<NEW_LINE>list.add(AdminConfigHBMUtil.model(adminConfigHBM));<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>ScrollableResults sr = q.scroll();<NEW_LINE>if (sr.first() && sr.scroll(begin)) {<NEW_LINE>for (int i = begin; i < end; i++) {<NEW_LINE>AdminConfigHBM adminConfigHBM = (AdminConfigHBM) sr.get(0);<NEW_LINE>list.add(AdminConfigHBMUtil.model(adminConfigHBM));<NEW_LINE>if (!sr.next()) {<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return list;<NEW_LINE>} catch (HibernateException he) {<NEW_LINE>throw new SystemException(he);<NEW_LINE>} finally {<NEW_LINE>HibernateUtil.closeSession(session);<NEW_LINE>}<NEW_LINE>} | .setString(queryPos++, companyId); |
516,562 | public static GetCustomFieldsByTemplateIdResponse unmarshall(GetCustomFieldsByTemplateIdResponse getCustomFieldsByTemplateIdResponse, UnmarshallerContext _ctx) {<NEW_LINE>getCustomFieldsByTemplateIdResponse.setRequestId(_ctx.stringValue("GetCustomFieldsByTemplateIdResponse.RequestId"));<NEW_LINE>getCustomFieldsByTemplateIdResponse.setCode(_ctx.integerValue("GetCustomFieldsByTemplateIdResponse.Code"));<NEW_LINE>getCustomFieldsByTemplateIdResponse.setSuccess(_ctx.booleanValue("GetCustomFieldsByTemplateIdResponse.Success"));<NEW_LINE>List<DataItem> data = new ArrayList<DataItem>();<NEW_LINE>for (int i = 0; i < _ctx.lengthValue("GetCustomFieldsByTemplateIdResponse.Data.Length"); i++) {<NEW_LINE>DataItem dataItem = new DataItem();<NEW_LINE>dataItem.setCreatedAt(_ctx.longValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].CreatedAt"));<NEW_LINE>dataItem.setDefaultValue(_ctx.stringValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].DefaultValue"));<NEW_LINE>dataItem.setDescription(_ctx.stringValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].Description"));<NEW_LINE>dataItem.setDynamic(_ctx.booleanValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].Dynamic"));<NEW_LINE>dataItem.setEditable(_ctx.booleanValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].Editable"));<NEW_LINE>dataItem.setFieldFormat(_ctx.stringValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].FieldFormat"));<NEW_LINE>dataItem.setId(_ctx.integerValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].Id"));<NEW_LINE>dataItem.setIsDelete(_ctx.booleanValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].IsDelete"));<NEW_LINE>dataItem.setIsRemember(_ctx.booleanValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].IsRemember"));<NEW_LINE>dataItem.setIsRequired(_ctx.booleanValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].IsRequired"));<NEW_LINE>dataItem.setMaxLength(_ctx.integerValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].MaxLength"));<NEW_LINE>dataItem.setMinLength(_ctx.integerValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].MinLength"));<NEW_LINE>dataItem.setName(_ctx.stringValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].Name"));<NEW_LINE>dataItem.setNameI18N(_ctx.stringValue<MASK><NEW_LINE>dataItem.setOther(_ctx.stringValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].Other"));<NEW_LINE>dataItem.setPossibleValues(_ctx.stringValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].PossibleValues"));<NEW_LINE>dataItem.setType(_ctx.stringValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].Type"));<NEW_LINE>dataItem.setUpdatedAt(_ctx.longValue("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].UpdatedAt"));<NEW_LINE>data.add(dataItem);<NEW_LINE>}<NEW_LINE>getCustomFieldsByTemplateIdResponse.setData(data);<NEW_LINE>return getCustomFieldsByTemplateIdResponse;<NEW_LINE>} | ("GetCustomFieldsByTemplateIdResponse.Data[" + i + "].NameI18N")); |
318,066 | public boolean onReceiveMessage(Message message) {<NEW_LINE>mHistoryMessages.add(message);<NEW_LINE>OtrChatManager cm = OtrChatManager.getInstance();<NEW_LINE>if (cm != null) {<NEW_LINE>SessionStatus otrStatus = cm.getSessionStatus(message.getTo().getAddress(), message.getFrom().getAddress());<NEW_LINE>SessionID sId = cm.getSessionId(message.getTo().getAddress(), message.getFrom().getAddress());<NEW_LINE>if (otrStatus == SessionStatus.ENCRYPTED) {<NEW_LINE>boolean verified = cm.getKeyManager().isVerified(sId);<NEW_LINE>if (verified) {<NEW_LINE>message.setType(Imps.MessageType.INCOMING_ENCRYPTED_VERIFIED);<NEW_LINE>} else {<NEW_LINE>message.<MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (mListener != null)<NEW_LINE>mListener.onIncomingMessage(this, message);<NEW_LINE>return true;<NEW_LINE>} | setType(Imps.MessageType.INCOMING_ENCRYPTED); |
1,197,557 | public static PrefixMapping calcInUsePrefixMapping(Graph graph, PrefixMapping prefixMapping) {<NEW_LINE>// Map prefix to URI.<NEW_LINE>Map<String, String> pmap = prefixMapping.getNsPrefixMap();<NEW_LINE>// Map URI to prefix, with partial lookup (all uri keys that partly match the URI)<NEW_LINE>Trie<String> trie = new Trie<>();<NEW_LINE>// Change this to "add(uri, uri)" to calculate the uris.<NEW_LINE>pmap.forEach((prefix, uri) -> trie.add(uri, prefix));<NEW_LINE>// Prefixes in use.<NEW_LINE>// (URIs if "add(uri, uri)")<NEW_LINE>Set<String> <MASK><NEW_LINE>ExtendedIterator<Triple> iter = graph.find(null, null, null);<NEW_LINE>try {<NEW_LINE>while (iter.hasNext()) {<NEW_LINE>Triple triple = iter.next();<NEW_LINE>process(triple, inUse, trie);<NEW_LINE>if (pmap.size() == inUse.size())<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>} finally {<NEW_LINE>iter.close();<NEW_LINE>}<NEW_LINE>if (pmap.size() == inUse.size())<NEW_LINE>return prefixMapping;<NEW_LINE>// Build result.<NEW_LINE>PrefixMapping pmap2 = new PrefixMappingImpl();<NEW_LINE>inUse.forEach((prefix) -> pmap2.setNsPrefix(prefix, prefixMapping.getNsPrefixURI(prefix)));<NEW_LINE>return pmap2;<NEW_LINE>} | inUse = new HashSet<>(); |
1,097,141 | private Mono<Response<NetworkRuleSetListResultInner>> listNetworkRuleSetWithResponseAsync(String resourceGroupName, String namespaceName, 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 (resourceGroupName == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));<NEW_LINE>}<NEW_LINE>if (namespaceName == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter namespaceName 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>final String accept = "application/json";<NEW_LINE>context = this.client.mergeContext(context);<NEW_LINE>return service.listNetworkRuleSet(this.client.getEndpoint(), resourceGroupName, namespaceName, this.client.getApiVersion(), this.client.<MASK><NEW_LINE>} | getSubscriptionId(), accept, context); |
1,314,645 | public static int long2bytes(final long value, final OutputStream iStream) throws IOException {<NEW_LINE>final int beginOffset = iStream instanceof OMemoryStream ? ((OMemoryStream) iStream).getPosition() : -1;<NEW_LINE>iStream.write((int) (value >>> 56) & 0xFF);<NEW_LINE>iStream.write((int) (value >>> 48) & 0xFF);<NEW_LINE>iStream.write((int) (value >>> 40) & 0xFF);<NEW_LINE>iStream.write((int) (value >>> 32) & 0xFF);<NEW_LINE>iStream.write((int) (value <MASK><NEW_LINE>iStream.write((int) (value >>> 16) & 0xFF);<NEW_LINE>iStream.write((int) (value >>> 8) & 0xFF);<NEW_LINE>iStream.write((int) (value >>> 0) & 0xFF);<NEW_LINE>return beginOffset;<NEW_LINE>} | >>> 24) & 0xFF); |
441,947 | private void updateTextDisplayName(final Hashtable<CallPeer, String> peerNamesTable) {<NEW_LINE>if (!SwingUtilities.isEventDispatchThread()) {<NEW_LINE>SwingUtilities.invokeLater(new Runnable() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void run() {<NEW_LINE>updateTextDisplayName(peerNamesTable);<NEW_LINE>}<NEW_LINE>});<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>boolean hasMorePeers = false;<NEW_LINE>String textDisplayName = "";<NEW_LINE>Iterator<? extends CallPeer> peersIter = incomingCall.getCallPeers();<NEW_LINE>JLabel <MASK><NEW_LINE>while (peersIter.hasNext()) {<NEW_LINE>final CallPeer peer = peersIter.next();<NEW_LINE>// More peers.<NEW_LINE>if (peersIter.hasNext()) {<NEW_LINE>textDisplayName = label.getText() + peerNamesTable.get(peer) + ", ";<NEW_LINE>hasMorePeers = true;<NEW_LINE>} else // Only one peer.<NEW_LINE>{<NEW_LINE>textDisplayName = GuiActivator.getResources().getI18NString("service.gui.IS_CALLING", new String[] { peerNamesTable.get(peer) });<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (hasMorePeers)<NEW_LINE>textDisplayName = GuiActivator.getResources().getI18NString("service.gui.ARE_CALLING", new String[] { textDisplayName });<NEW_LINE>label.setText(textDisplayName);<NEW_LINE>} | label = getCallLabels()[1]; |
409,108 | public void putDouble(long t, double v) {<NEW_LINE>if (writeCurArrayIndex == capacity) {<NEW_LINE>if (capacity >= CAPACITY_THRESHOLD) {<NEW_LINE>timeRet.add(new long[capacity]);<NEW_LINE>doubleRet.add(new double[capacity]);<NEW_LINE>writeCurListIndex++;<NEW_LINE>writeCurArrayIndex = 0;<NEW_LINE>} else {<NEW_LINE>int newCapacity = capacity << 1;<NEW_LINE>long[] newTimeData = new long[newCapacity];<NEW_LINE>double[] newValueData = new double[newCapacity];<NEW_LINE>System.arraycopy(timeRet.get(0), 0, newTimeData, 0, capacity);<NEW_LINE>System.arraycopy(doubleRet.get(0), <MASK><NEW_LINE>timeRet.set(0, newTimeData);<NEW_LINE>doubleRet.set(0, newValueData);<NEW_LINE>capacity = newCapacity;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>timeRet.get(writeCurListIndex)[writeCurArrayIndex] = t;<NEW_LINE>doubleRet.get(writeCurListIndex)[writeCurArrayIndex] = v;<NEW_LINE>writeCurArrayIndex++;<NEW_LINE>count++;<NEW_LINE>} | 0, newValueData, 0, capacity); |
1,434,939 | public void assertHasPublicMethods(AssertionInfo info, Class<?> actual, String... methods) {<NEW_LINE>assertNotNull(info, actual);<NEW_LINE>Method[] actualMethods = actual.getMethods();<NEW_LINE>SortedSet<String> expectedMethodNames = newTreeSet(methods);<NEW_LINE>SortedSet<MASK><NEW_LINE>Map<String, Integer> methodNamesWithModifier = methodsToNameAndModifier(actualMethods);<NEW_LINE>if (methods.length == 0 && hasPublicMethods(actualMethods)) {<NEW_LINE>throw failures.failure(info, shouldNotHaveMethods(actual, Modifier.toString(Modifier.PUBLIC), false, getMethodsWithModifier(newLinkedHashSet(actualMethods), Modifier.PUBLIC)));<NEW_LINE>}<NEW_LINE>if (!noMissingElement(methodNamesWithModifier.keySet(), expectedMethodNames, missingMethodNames)) {<NEW_LINE>throw failures.failure(info, shouldHaveMethods(actual, false, expectedMethodNames, missingMethodNames));<NEW_LINE>}<NEW_LINE>Map<String, String> nonMatchingModifiers = new LinkedHashMap<>();<NEW_LINE>if (!noNonMatchingModifier(expectedMethodNames, methodNamesWithModifier, nonMatchingModifiers, Modifier.PUBLIC)) {<NEW_LINE>throw failures.failure(info, shouldHaveMethods(actual, false, expectedMethodNames, Modifier.toString(Modifier.PUBLIC), nonMatchingModifiers));<NEW_LINE>}<NEW_LINE>} | <String> missingMethodNames = newTreeSet(); |
1,285,282 | public static void printExceptionTraceback(PythonContext context, PBaseException pythonException) {<NEW_LINE>Object type = GetClassNode.getUncached().execute(pythonException);<NEW_LINE>Object tb = GetExceptionTracebackNode.getUncached().execute(pythonException);<NEW_LINE>Object hook = context.lookupBuiltinModule("sys"<MASK><NEW_LINE>if (hook != PNone.NO_VALUE) {<NEW_LINE>try {<NEW_LINE>// Note: it is important to pass frame 'null' because that will cause the<NEW_LINE>// CallNode to tread the invoke like a foreign call and access the top frame ref<NEW_LINE>// in the context.<NEW_LINE>CallNode.getUncached().execute(null, hook, new Object[] { type, pythonException, tb }, PKeyword.EMPTY_KEYWORDS);<NEW_LINE>} catch (PException internalError) {<NEW_LINE>// More complex handling of errors in exception printing is done in our<NEW_LINE>// Python code, if we get here, we just fall back to the launcher<NEW_LINE>throw pythonException.getExceptionForReraise(pythonException.getTraceback());<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>try {<NEW_LINE>context.getEnv().err().write("sys.excepthook is missing\n".getBytes());<NEW_LINE>} catch (IOException ioException) {<NEW_LINE>ioException.printStackTrace();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | ).getAttribute(BuiltinNames.EXCEPTHOOK); |
995,219 | public IndependentSequenceModel<T> train(SequenceDataset<T> sequenceExamples, Map<String, Provenance> runProvenance) {<NEW_LINE>if (sequenceExamples.getOutputInfo().getUnknownCount() > 0) {<NEW_LINE>throw new IllegalArgumentException("The supplied Dataset contained unknown Outputs, and this Trainer is supervised.");<NEW_LINE>}<NEW_LINE>// Generates the provenance and increments the trainInvocationCounter.<NEW_LINE>TrainerProvenance trainerProvenance;<NEW_LINE>synchronized (this) {<NEW_LINE>trainerProvenance = getProvenance();<NEW_LINE>trainInvocationCounter++;<NEW_LINE>}<NEW_LINE>Dataset<T> flatDataset = sequenceExamples.getFlatDataset();<NEW_LINE>logger.info(String.format("Training inner trainer with %d examples"<MASK><NEW_LINE>Model<T> model = innerTrainer.train(flatDataset);<NEW_LINE>ModelProvenance provenance = new ModelProvenance(IndependentSequenceModel.class.getName(), OffsetDateTime.now(), sequenceExamples.getProvenance(), trainerProvenance, runProvenance);<NEW_LINE>return new IndependentSequenceModel<>("independent-sequence-model", provenance, model);<NEW_LINE>} | , flatDataset.size())); |
1,083,834 | public static void main(String[] args) {<NEW_LINE>Exercise26_CriticalEdges criticalEdges = new Exercise26_CriticalEdges();<NEW_LINE>EdgeWeightedGraph edgeWeightedGraph1 = new EdgeWeightedGraph(4);<NEW_LINE>// Critical edge<NEW_LINE>edgeWeightedGraph1.addEdge(new Edge(0, 1, 1));<NEW_LINE>edgeWeightedGraph1.addEdge(new Edge<MASK><NEW_LINE>// Critical edge<NEW_LINE>edgeWeightedGraph1.addEdge(new Edge(2, 3, 2));<NEW_LINE>edgeWeightedGraph1.addEdge(new Edge(3, 0, 3));<NEW_LINE>StdOut.println("Critical edges 1:");<NEW_LINE>Queue<Edge> criticalEdges1 = criticalEdges.findCriticalEdges(edgeWeightedGraph1);<NEW_LINE>for (Edge edge : criticalEdges1) {<NEW_LINE>StdOut.println(edge);<NEW_LINE>}<NEW_LINE>StdOut.println("Expected:\n" + "0-1 1.00000\n" + "2-3 2.00000\n");<NEW_LINE>EdgeWeightedGraph edgeWeightedGraph2 = new EdgeWeightedGraph(4);<NEW_LINE>edgeWeightedGraph2.addEdge(new Edge(0, 1, 5));<NEW_LINE>edgeWeightedGraph2.addEdge(new Edge(1, 2, 5));<NEW_LINE>edgeWeightedGraph2.addEdge(new Edge(0, 2, 5));<NEW_LINE>// Critical edge<NEW_LINE>edgeWeightedGraph2.addEdge(new Edge(2, 3, 3));<NEW_LINE>StdOut.println("Critical edges 2:");<NEW_LINE>Queue<Edge> criticalEdges2 = criticalEdges.findCriticalEdges(edgeWeightedGraph2);<NEW_LINE>for (Edge edge : criticalEdges2) {<NEW_LINE>StdOut.println(edge);<NEW_LINE>}<NEW_LINE>StdOut.println("Expected:\n" + "2-3 3.00000");<NEW_LINE>} | (1, 2, 3)); |
354,783 | public void showRolePermissions(final RequestContext context) {<NEW_LINE>final String roleId = context.pathVar("roleId");<NEW_LINE>final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "admin/role-permissions.ftl");<NEW_LINE>final Map<String, Object> dataModel = renderer.getDataModel();<NEW_LINE>final JSONObject role = roleQueryService.getRole(roleId);<NEW_LINE>dataModel.put(Role.ROLE, role);<NEW_LINE>final Map<String, List<JSONObject>> categories = new TreeMap<>();<NEW_LINE>final List<JSONObject> permissions = roleQueryService.getPermissionsGrant(roleId);<NEW_LINE>for (final JSONObject permission : permissions) {<NEW_LINE>final String label = permission.optString(Keys.OBJECT_ID) + "PermissionLabel";<NEW_LINE>permission.put(Permission.PERMISSION_T_LABEL, langPropsService.get(label));<NEW_LINE>String category = permission.optString(Permission.PERMISSION_CATEGORY);<NEW_LINE>category = langPropsService.get(category + "PermissionLabel");<NEW_LINE>final List<JSONObject> categoryPermissions = categories.computeIfAbsent(category, k -> new ArrayList<>());<NEW_LINE>categoryPermissions.add(permission);<NEW_LINE>}<NEW_LINE>dataModel.put(Permission.PERMISSION_T_CATEGORIES, categories);<NEW_LINE><MASK><NEW_LINE>} | dataModelService.fillHeaderAndFooter(context, dataModel); |
568,944 | public void decreaseStreamRetentionPeriod(DecreaseStreamRetentionPeriodRequest decreaseStreamRetentionPeriodRequest) throws AmazonServiceException, AmazonClientException {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(decreaseStreamRetentionPeriodRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<DecreaseStreamRetentionPeriodRequest> request = null;<NEW_LINE>Response<Void> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new DecreaseStreamRetentionPeriodRequestMarshaller().marshall(decreaseStreamRetentionPeriodRequest);<NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>JsonResponseHandler<Void> responseHandler = <MASK><NEW_LINE>invoke(request, responseHandler, executionContext);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.ClientExecuteTime);<NEW_LINE>endClientExecution(awsRequestMetrics, request, response, LOGGING_AWS_REQUEST_METRIC);<NEW_LINE>}<NEW_LINE>} | new JsonResponseHandler<Void>(null); |
677,174 | public void addDistanceText(Graphics2D g, ZonePoint point, float size, double distance, double distanceWithoutTerrain) {<NEW_LINE>if (distance == 0) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>Grid grid = zone.getGrid();<NEW_LINE>double cwidth = grid.getCellWidth() * getScale();<NEW_LINE>double cheight = grid.getCellHeight() * getScale();<NEW_LINE>double iwidth = cwidth * size;<NEW_LINE>double iheight = cheight * size;<NEW_LINE>ScreenPoint sp = ScreenPoint.fromZonePoint(this, point);<NEW_LINE>int cellX = (int) (sp.x - iwidth / 2);<NEW_LINE>int cellY = (int) (sp.y - iheight / 2);<NEW_LINE>// Draw distance for each cell<NEW_LINE>// Font size of 12 at grid size 50 is default<NEW_LINE>double fontScale = (double) grid.getSize() / 50;<NEW_LINE>int fontSize = (int) (getScale() * 12 * fontScale);<NEW_LINE>// 7 pixels at 100% zoom & grid size of 50<NEW_LINE>int textOffset = (int) (getScale() * 7 * fontScale);<NEW_LINE>String distanceText = NumberFormat.getInstance().format(distance);<NEW_LINE>if (log.isDebugEnabled() || showAstarDebugging) {<NEW_LINE>distanceText += " (" + NumberFormat.getInstance().format(distanceWithoutTerrain) + ")";<NEW_LINE>fontSize = <MASK><NEW_LINE>}<NEW_LINE>Font font = new Font(Font.DIALOG, Font.BOLD, fontSize);<NEW_LINE>Font originalFont = g.getFont();<NEW_LINE>FontMetrics fm = g.getFontMetrics(font);<NEW_LINE>int textWidth = fm.stringWidth(distanceText);<NEW_LINE>g.setFont(font);<NEW_LINE>g.setColor(Color.BLACK);<NEW_LINE>// log.info("Text: [" + distanceText + "], width: " + textWidth + ", font size: " + fontSize +<NEW_LINE>// ", offset: " + textOffset + ", fontScale: " + fontScale+ ", getScale(): " + getScale());<NEW_LINE>g.drawString(distanceText, (int) (cellX + cwidth - textWidth - textOffset), (int) (cellY + cheight - textOffset));<NEW_LINE>g.setFont(originalFont);<NEW_LINE>} | (int) (fontSize * 0.75); |
383,181 | protected void onCreate(Bundle savedInstanceState) {<NEW_LINE>super.onCreate(savedInstanceState);<NEW_LINE>_shareUtil = new ShareUtil(this);<NEW_LINE>setContentView(R.layout.main__activity);<NEW_LINE>ButterKnife.bind(this);<NEW_LINE>setSupportActionBar(findViewById(R.id.toolbar));<NEW_LINE>optShowRate();<NEW_LINE>try {<NEW_LINE>if (_appSettings.isAppCurrentVersionFirstStart(true)) {<NEW_LINE>SimpleMarkdownParser smp = SimpleMarkdownParser.get().setDefaultSmpFilter(SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW);<NEW_LINE>String html = "";<NEW_LINE>html += smp.parse(getString(R.string.copyright_license_text_official).replace("\n", " \n"), "").getHtml();<NEW_LINE>html += "<br/><br/><br/><big><big>" + getString(R.string.changelog) + "</big></big><br/>" + smp.parse(getResources().openRawResource(R.raw.changelog), "", SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW);<NEW_LINE>html += "<br/><br/><br/><big><big>" + getString(R.string.licenses) + "</big></big><br/>" + smp.parse(getResources().openRawResource(R.raw.licenses_3rd_party), "").getHtml();<NEW_LINE>ActivityUtils _au = new ActivityUtils(this);<NEW_LINE>_au.showDialogWithHtmlTextView(0, html);<NEW_LINE>}<NEW_LINE>} catch (IOException e) {<NEW_LINE>e.printStackTrace();<NEW_LINE>}<NEW_LINE>IntroActivity.optStart(this);<NEW_LINE>// Setup viewpager<NEW_LINE>_viewPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());<NEW_LINE>_viewPager.setAdapter(_viewPagerAdapter);<NEW_LINE>_viewPager.setOffscreenPageLimit(4);<NEW_LINE>_bottomNav.setOnNavigationItemSelectedListener(this);<NEW_LINE>// noinspection PointlessBooleanExpression - Send Test intent<NEW_LINE>if (BuildConfig.IS_TEST_BUILD && false) {<NEW_LINE>DocumentActivity.launch(this, new File("/sdcard/Documents/mordor/aa-beamer.md"), true, null, null);<NEW_LINE>}<NEW_LINE>(new ActivityUtils(this)).<MASK><NEW_LINE>// Switch to tab if specific folder _not_ requested, and not recreating from saved instance<NEW_LINE>final int startTab = _appSettings.getAppStartupTab();<NEW_LINE>if (startTab != R.id.nav_notebook && savedInstanceState == null && getIntentDir(getIntent(), null) == null) {<NEW_LINE>_bottomNav.postDelayed(() -> _bottomNav.setSelectedItemId(startTab), 10);<NEW_LINE>}<NEW_LINE>} | applySpecialLaunchersVisibility(_appSettings.isSpecialFileLaunchersEnabled()); |
420,884 | protected void scripts() {<NEW_LINE>String psUuid = q(VolumeVO.class).select(VolumeVO_.primaryStorageUuid).eq(VolumeVO_.<MASK><NEW_LINE>if (psUuid == null) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>if (!q(PrimaryStorageVO.class).eq(PrimaryStorageVO_.uuid, psUuid).eq(PrimaryStorageVO_.type, NfsPrimaryStorageConstant.NFS_PRIMARY_STORAGE_TYPE).isExists()) {<NEW_LINE>// not NFS<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>if (!q(PrimaryStorageClusterRefVO.class).eq(PrimaryStorageClusterRefVO_.primaryStorageUuid, psUuid).isExists()) {<NEW_LINE>throw new OperationFailureException(operr("the NFS primary storage[uuid:%s] is not attached" + " to any clusters, and cannot expunge the root volume[uuid:%s] of the VM[uuid:%s]", psUuid, vmUuid, volumeUuid));<NEW_LINE>}<NEW_LINE>} | uuid, volumeUuid).findValue(); |
869,940 | private Value invokeRemoteMethod(BVariable resultVar) throws EvaluationException {<NEW_LINE><MASK><NEW_LINE>String className = resultVar.getDapVariable().getValue();<NEW_LINE>Optional<ClassSymbol> classDef = classDefResolver.findBalClassDefWithinModule(className);<NEW_LINE>if (classDef.isEmpty()) {<NEW_LINE>// Resolves the JNI signature to see if the object/class is defined with a dependency module.<NEW_LINE>String signature = resultVar.getJvmValue().type().signature();<NEW_LINE>if (!signature.startsWith(QUALIFIED_TYPE_SIGNATURE_PREFIX)) {<NEW_LINE>throw createEvaluationException(CLASS_NOT_FOUND, className);<NEW_LINE>}<NEW_LINE>String[] signatureParts = signature.substring(1).split(JNI_SIGNATURE_SEPARATOR);<NEW_LINE>if (signatureParts.length < 2) {<NEW_LINE>throw createEvaluationException(CLASS_NOT_FOUND, className);<NEW_LINE>}<NEW_LINE>String orgName = signatureParts[0];<NEW_LINE>String packageName = signatureParts[1];<NEW_LINE>classDef = classDefResolver.findBalClassDefWithinDependencies(orgName, packageName, className);<NEW_LINE>}<NEW_LINE>if (classDef.isEmpty()) {<NEW_LINE>throw createEvaluationException(CLASS_NOT_FOUND, className);<NEW_LINE>}<NEW_LINE>Optional<MethodSymbol> objectMethodDef = findObjectMethodInClass(classDef.get(), methodName);<NEW_LINE>if (objectMethodDef.isEmpty()) {<NEW_LINE>throw createEvaluationException(REMOTE_METHOD_NOT_FOUND, syntaxNode.methodName().toString().trim(), className);<NEW_LINE>}<NEW_LINE>GeneratedInstanceMethod objectMethod = getRemoteMethodByName(resultVar, objectMethodDef.get());<NEW_LINE>Map<String, Value> argValueMap = generateNamedArgs(context, methodName, objectMethodDef.get().typeDescriptor(), argEvaluators);<NEW_LINE>objectMethod.setNamedArgValues(argValueMap);<NEW_LINE>return objectMethod.invokeSafely();<NEW_LINE>} | ClassDefinitionResolver classDefResolver = new ClassDefinitionResolver(context); |
801,450 | private boolean onPaste(boolean isPastedAsPlainText) {<NEW_LINE>ClipboardManager clipboardManager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);<NEW_LINE>StringBuilder text = new StringBuilder();<NEW_LINE>StringBuilder html = new StringBuilder();<NEW_LINE>if (clipboardManager != null && clipboardManager.hasPrimaryClip()) {<NEW_LINE>ClipData clipData = clipboardManager.getPrimaryClip();<NEW_LINE>int itemCount = clipData.getItemCount();<NEW_LINE>for (int i = 0; i < itemCount; i++) {<NEW_LINE>Item item = clipData.getItemAt(i);<NEW_LINE>text.append(item.coerceToText(getContext()));<NEW_LINE>if (!isPastedAsPlainText) {<NEW_LINE>html.append(item.coerceToHtmlText(getContext()));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// temporarily disable listener during call to toHtml()<NEW_LINE>disableTextChangedListener();<NEW_LINE>String content = toHtml(getText(), false);<NEW_LINE>int cursorPositionStart = getSelectionStart();<NEW_LINE>int cursorPositionEnd = getSelectionEnd();<NEW_LINE>enableTextChangedListener();<NEW_LINE>ReactContext reactContext = (ReactContext) getContext();<NEW_LINE>EventDispatcher eventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher();<NEW_LINE>eventDispatcher.dispatchEvent(new ReactAztecPasteEvent(getId(), content, cursorPositionStart, cursorPositionEnd, text.toString()<MASK><NEW_LINE>return true;<NEW_LINE>} | , html.toString())); |
56,422 | public static BigInteger modOddInverse(BigInteger M, BigInteger X) {<NEW_LINE>if (!M.testBit(0)) {<NEW_LINE>throw new IllegalArgumentException("'M' must be odd");<NEW_LINE>}<NEW_LINE>if (M.signum() != 1) {<NEW_LINE>throw new ArithmeticException("BigInteger: modulus not positive");<NEW_LINE>}<NEW_LINE>if (X.signum() < 0 || X.compareTo(M) >= 0) {<NEW_LINE>X = X.mod(M);<NEW_LINE>}<NEW_LINE>int bits = M.bitLength();<NEW_LINE>int[] m = Nat.fromBigInteger(bits, M);<NEW_LINE>int[] x = <MASK><NEW_LINE>int len = m.length;<NEW_LINE>int[] z = Nat.create(len);<NEW_LINE>if (0 == Mod.modOddInverse(m, x, z)) {<NEW_LINE>throw new ArithmeticException("BigInteger not invertible.");<NEW_LINE>}<NEW_LINE>return Nat.toBigInteger(len, z);<NEW_LINE>} | Nat.fromBigInteger(bits, X); |
295,586 | protected void paintTabBackground(Graphics g, int index, int x, int y, int width, int height) {<NEW_LINE>// shrink rectangle - don't affect border and tab header<NEW_LINE>y += 3;<NEW_LINE>width -= 1;<NEW_LINE>height -= 4;<NEW_LINE>// background body, colored according to state<NEW_LINE>boolean selected = isSelected(index);<NEW_LINE>boolean focused = selected && isActive();<NEW_LINE>boolean attention = isAttention(index);<NEW_LINE>if (focused && !attention) {<NEW_LINE>ColorUtil.xpFillRectGradient((Graphics2D) g, x, y, width, height, focusFillBrightC, focusFillDarkC);<NEW_LINE>} else if (selected && isMoreThanOne() && !attention) {<NEW_LINE>g.setColor(selFillC);<NEW_LINE>g.fillRect(x, y, width, height);<NEW_LINE>} else if (attention) {<NEW_LINE>Color a = new Color(255, 255, 128);<NEW_LINE>Color b = new Color(230, 200, 64);<NEW_LINE>ColorUtil.xpFillRectGradient((Graphics2D) g, x, y, <MASK><NEW_LINE>} else {<NEW_LINE>ColorUtil.xpFillRectGradient((Graphics2D) g, x, y, width, height, unselFillBrightC, unselFillDarkC);<NEW_LINE>}<NEW_LINE>} | width, height, a, b); |
774,118 | private void copyFromLocalFile(AlluxioURI srcPath, AlluxioURI dstPath) throws AlluxioException, IOException {<NEW_LINE>File src = new File(srcPath.getPath());<NEW_LINE>if (src.isDirectory()) {<NEW_LINE>throw new IOException("Source " + src.getAbsolutePath() + " is not a file.");<NEW_LINE>}<NEW_LINE>// If the dstPath is a directory, then it should be updated to be the path of the file where<NEW_LINE>// src will be copied to.<NEW_LINE>if (mFileSystem.exists(dstPath) && mFileSystem.getStatus(dstPath).isFolder()) {<NEW_LINE>dstPath = dstPath.<MASK><NEW_LINE>}<NEW_LINE>FileOutStream os = null;<NEW_LINE>try (Closer closer = Closer.create()) {<NEW_LINE>os = closer.register(mFileSystem.createFile(dstPath));<NEW_LINE>FileInputStream in = closer.register(new FileInputStream(src));<NEW_LINE>FileChannel channel = closer.register(in.getChannel());<NEW_LINE>ByteBuffer buf = ByteBuffer.allocate(mCopyFromLocalBufferSize);<NEW_LINE>while (channel.read(buf) != -1) {<NEW_LINE>buf.flip();<NEW_LINE>os.write(buf.array(), 0, buf.limit());<NEW_LINE>}<NEW_LINE>} catch (Exception e) {<NEW_LINE>// Close the out stream and delete the file, so we don't have an incomplete file lying<NEW_LINE>// around.<NEW_LINE>if (os != null) {<NEW_LINE>os.cancel();<NEW_LINE>if (mFileSystem.exists(dstPath)) {<NEW_LINE>mFileSystem.delete(dstPath);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>throw e;<NEW_LINE>}<NEW_LINE>} | join(src.getName()); |
1,569,563 | public boolean readExtensions(GPXFile res, XmlPullParser parser) throws IOException, XmlPullParserException {<NEW_LINE>if (ITINERARY_GROUP.equalsIgnoreCase(parser.getName())) {<NEW_LINE>ItineraryGroupInfo groupInfo = new ItineraryGroupInfo();<NEW_LINE>int tok;<NEW_LINE>while ((tok = parser.next()) != XmlPullParser.END_DOCUMENT) {<NEW_LINE>if (tok == XmlPullParser.START_TAG) {<NEW_LINE>String tagName = parser.getName().toLowerCase();<NEW_LINE>if ("name".equals(tagName)) {<NEW_LINE>groupInfo.name = readText(parser, tagName);<NEW_LINE>} else if ("type".equals(tagName)) {<NEW_LINE>groupInfo.type = readText(parser, tagName);<NEW_LINE>} else if ("path".equals(tagName)) {<NEW_LINE>groupInfo.<MASK><NEW_LINE>} else if ("alias".equals(tagName)) {<NEW_LINE>groupInfo.alias = readText(parser, tagName);<NEW_LINE>} else if ("categories".equals(tagName)) {<NEW_LINE>groupInfo.categories = readText(parser, tagName);<NEW_LINE>}<NEW_LINE>} else if (tok == XmlPullParser.END_TAG) {<NEW_LINE>if (ITINERARY_GROUP.equalsIgnoreCase(parser.getName())) {<NEW_LINE>groupInfos.add(groupInfo);<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return false;<NEW_LINE>} | path = readText(parser, tagName); |
1,259,300 | private void addObjectRecord(final String name) throws IOException {<NEW_LINE>assert name != null;<NEW_LINE>final ObjectRecordValue<?> value = getObjectRecordValue();<NEW_LINE>final long key;<NEW_LINE>switch(insert) {<NEW_LINE>case AS_FIRST_CHILD:<NEW_LINE>if (parents.peek() == Fixed.NULL_NODE_KEY.getStandardProperty()) {<NEW_LINE>key = wtx.insertObjectRecordAsFirstChild(name, value).getNodeKey();<NEW_LINE>} else {<NEW_LINE>key = wtx.insertObjectRecordAsRightSibling(name, value).getNodeKey();<NEW_LINE>}<NEW_LINE>break;<NEW_LINE>case AS_LAST_CHILD:<NEW_LINE>if (parents.peek() == Fixed.NULL_NODE_KEY.getStandardProperty()) {<NEW_LINE>key = wtx.insertObjectRecordAsLastChild(name, value).getNodeKey();<NEW_LINE>} else {<NEW_LINE>key = wtx.insertObjectRecordAsRightSibling(name, value).getNodeKey();<NEW_LINE>}<NEW_LINE>break;<NEW_LINE>case AS_LEFT_SIBLING:<NEW_LINE>key = wtx.insertObjectRecordAsLeftSibling(name, value).getNodeKey();<NEW_LINE>break;<NEW_LINE>case AS_RIGHT_SIBLING:<NEW_LINE>key = wtx.insertObjectRecordAsRightSibling(name, value).getNodeKey();<NEW_LINE>break;<NEW_LINE>default:<NEW_LINE>// Should not happen<NEW_LINE>throw new AssertionError();<NEW_LINE>}<NEW_LINE>parents.pop();<NEW_LINE>parents.push(wtx.getParentKey());<NEW_LINE>parents.push(Fixed.NULL_NODE_KEY.getStandardProperty());<NEW_LINE>if (wtx.getKind() == NodeKind.OBJECT || wtx.getKind() == NodeKind.ARRAY) {<NEW_LINE>parents.pop();<NEW_LINE>parents.push(key);<NEW_LINE>parents.push(<MASK><NEW_LINE>} else {<NEW_LINE>final boolean isNextTokenParentToken = reader.peek() == JsonToken.NAME || reader.peek() == JsonToken.END_OBJECT;<NEW_LINE>adaptTrxPosAndStack(isNextTokenParentToken, key);<NEW_LINE>}<NEW_LINE>} | Fixed.NULL_NODE_KEY.getStandardProperty()); |
913,293 | private JPanel parallelTab(final ComponentAssembly boosters) {<NEW_LINE>JPanel motherPanel = new JPanel(new MigLayout("fill"));<NEW_LINE>// radial distance method<NEW_LINE>JLabel radiusMethodLabel = new JLabel(trans.get("RocketComponent.Position.Method.Radius.Label"));<NEW_LINE>motherPanel.add(radiusMethodLabel, "align left");<NEW_LINE>final EnumModel<RadiusMethod> radiusMethodModel = new EnumModel<RadiusMethod>(boosters, "RadiusMethod", RadiusMethod.choices());<NEW_LINE>final JComboBox<RadiusMethod> radiusMethodCombo = new JComboBox<RadiusMethod>(radiusMethodModel);<NEW_LINE>motherPanel.add(radiusMethodCombo, "align left, wrap");<NEW_LINE>// set radial distance<NEW_LINE>JLabel radiusLabel = new JLabel(trans.get("StageConfig.parallel.radius"));<NEW_LINE>motherPanel.add(radiusLabel, "align left");<NEW_LINE>// radiusMethodModel.addEnableComponent(radiusLabel, false);<NEW_LINE>DoubleModel radiusModel = new DoubleModel(boosters, "RadiusOffset", UnitGroup.UNITS_LENGTH, 0);<NEW_LINE>JSpinner radiusSpinner = new JSpinner(radiusModel.getSpinnerModel());<NEW_LINE>radiusSpinner.setEditor(new SpinnerEditor(radiusSpinner));<NEW_LINE>motherPanel.add(radiusSpinner, "growx 1, align right");<NEW_LINE>// autoRadOffsModel.addEnableComponent(radiusSpinner, false);<NEW_LINE>UnitSelector radiusUnitSelector = new UnitSelector(radiusModel);<NEW_LINE>motherPanel.add(radiusUnitSelector, "growx 1, wrap");<NEW_LINE>// autoRadOffsModel.addEnableComponent(radiusUnitSelector, false);<NEW_LINE>// // set location angle around the primary stage<NEW_LINE>// JLabel angleMethodLabel = new JLabel(trans.get("RocketComponent.Position.Method.Angle.Label"));<NEW_LINE>// motherPanel.add( angleMethodLabel, "align left");<NEW_LINE>// EnumModel<AngleMethod> angleMethodModel = new EnumModel<AngleMethod>( boosters, "AngleMethod", AngleMethod.choices() );<NEW_LINE>// final JComboBox<AngleMethod> angleMethodCombo = new JComboBox<AngleMethod>( angleMethodModel );<NEW_LINE>// motherPanel.add( angleMethodCombo, "align left, wrap");<NEW_LINE>JLabel angleLabel = new JLabel<MASK><NEW_LINE>motherPanel.add(angleLabel, "align left");<NEW_LINE>DoubleModel angleModel = new DoubleModel(boosters, "AngleOffset", 1.0, UnitGroup.UNITS_ANGLE, 0.0, Math.PI * 2);<NEW_LINE>JSpinner angleSpinner = new JSpinner(angleModel.getSpinnerModel());<NEW_LINE>angleSpinner.setEditor(new SpinnerEditor(angleSpinner));<NEW_LINE>motherPanel.add(angleSpinner, "growx 1");<NEW_LINE>UnitSelector angleUnitSelector = new UnitSelector(angleModel);<NEW_LINE>motherPanel.add(angleUnitSelector, "growx 1, wrap");<NEW_LINE>// set multiplicity<NEW_LINE>JLabel countLabel = new JLabel(trans.get("StageConfig.parallel.count"));<NEW_LINE>motherPanel.add(countLabel, "align left");<NEW_LINE>IntegerModel countModel = new IntegerModel(boosters, "InstanceCount", 1);<NEW_LINE>JSpinner countSpinner = new JSpinner(countModel.getSpinnerModel());<NEW_LINE>countSpinner.setEditor(new SpinnerEditor(countSpinner));<NEW_LINE>motherPanel.add(countSpinner, "growx 1, wrap");<NEW_LINE>// setPositions relative to parent component<NEW_LINE>JLabel positionLabel = new JLabel(trans.get("LaunchLugCfg.lbl.Posrelativeto"));<NEW_LINE>motherPanel.add(positionLabel);<NEW_LINE>ComboBoxModel<AxialMethod> axialPositionMethodModel = new EnumModel<AxialMethod>(component, "AxialMethod", AxialMethod.axialOffsetMethods);<NEW_LINE>JComboBox<?> positionMethodCombo = new JComboBox<AxialMethod>(axialPositionMethodModel);<NEW_LINE>motherPanel.add(positionMethodCombo, "spanx 2, growx, wrap");<NEW_LINE>// relative offset labels<NEW_LINE>JLabel positionPlusLabel = new JLabel(trans.get("StageConfig.parallel.offset"));<NEW_LINE>motherPanel.add(positionPlusLabel);<NEW_LINE>DoubleModel axialOffsetModel = new DoubleModel(boosters, "AxialOffset", UnitGroup.UNITS_LENGTH);<NEW_LINE>JSpinner axPosSpin = new JSpinner(axialOffsetModel.getSpinnerModel());<NEW_LINE>axPosSpin.setEditor(new SpinnerEditor(axPosSpin));<NEW_LINE>motherPanel.add(axPosSpin, "growx");<NEW_LINE>UnitSelector axialOffsetUnitSelector = new UnitSelector(axialOffsetModel);<NEW_LINE>motherPanel.add(axialOffsetUnitSelector, "growx 1, wrap");<NEW_LINE>// For DEBUG purposes<NEW_LINE>// System.err.println(assembly.getRocket().toDebugTree());<NEW_LINE>return motherPanel;<NEW_LINE>} | (trans.get("StageConfig.parallel.angle")); |
1,848,447 | protected void onDraw(Canvas canvas) {<NEW_LINE>canvas.save();<NEW_LINE>if (processing != null)<NEW_LINE>processing.onDraw(canvas);<NEW_LINE>// Draw how fast it is running<NEW_LINE>long current = System.currentTimeMillis();<NEW_LINE>long elapsed = current - previous;<NEW_LINE>previous = current;<NEW_LINE>history[historyNum++] = 1000.0 / elapsed;<NEW_LINE>historyNum %= history.length;<NEW_LINE>double meanFps = 0;<NEW_LINE>for (int i = 0; i < history.length; i++) {<NEW_LINE>meanFps += history[i];<NEW_LINE>}<NEW_LINE>meanFps /= history.length;<NEW_LINE>// work around an issue in marshmallow<NEW_LINE>try {<NEW_LINE>canvas.restore();<NEW_LINE>} catch (IllegalStateException e) {<NEW_LINE>@Nullable<NEW_LINE><MASK><NEW_LINE>if (message != null && !message.contains("Underflow in restore - more restores than saves"))<NEW_LINE>throw e;<NEW_LINE>}<NEW_LINE>if (showFPS)<NEW_LINE>canvas.drawText(String.format("FPS = %5.2f", meanFps), 50, 50, textPaint);<NEW_LINE>} | String message = e.getMessage(); |
998,331 | public static void yv12ToPlanarRgb_U8(byte[] dataYV, Planar<GrayU8> output) {<NEW_LINE>GrayU8 R = output.getBand(0);<NEW_LINE>GrayU8 G = output.getBand(1);<NEW_LINE>GrayU8 B = output.getBand(2);<NEW_LINE>final int yStride = output.width;<NEW_LINE>final int uvStride = output.width / 2;<NEW_LINE>final int startU = yStride * output.height;<NEW_LINE>final int offsetV = uvStride * (output.height / 2);<NEW_LINE>// CONCURRENT_BELOW BoofConcurrency.loopFor(0, output.height, row -> {<NEW_LINE>for (int row = 0; row < output.height; row++) {<NEW_LINE>int indexY = row * yStride;<NEW_LINE>int indexU = startU + (row / 2) * uvStride;<NEW_LINE>int indexOut = output.startIndex + row * output.stride;<NEW_LINE>for (int col = 0; col < output.width; col++, indexOut++) {<NEW_LINE>int y = 1191 * ((dataYV[indexY++] & 0xFF) - 16);<NEW_LINE>int cb = (dataYV[indexU] & 0xFF) - 128;<NEW_LINE>int cr = (dataYV[indexU + offsetV] & 0xFF) - 128;<NEW_LINE>// if( y < 0 ) y = 0;<NEW_LINE>y = ((y >>> 31) ^ 1) * y;<NEW_LINE>int r = (y + 1836 * cr) >> 10;<NEW_LINE>int g = (y - 547 * cr <MASK><NEW_LINE>int b = (y + 2165 * cb) >> 10;<NEW_LINE>// if( r < 0 ) r = 0; else if( r > 255 ) r = 255;<NEW_LINE>// if( g < 0 ) g = 0; else if( g > 255 ) g = 255;<NEW_LINE>// if( b < 0 ) b = 0; else if( b > 255 ) b = 255;<NEW_LINE>r *= ((r >>> 31) ^ 1);<NEW_LINE>g *= ((g >>> 31) ^ 1);<NEW_LINE>b *= ((b >>> 31) ^ 1);<NEW_LINE>// The bitwise code below isn't faster than than the if statement below<NEW_LINE>// r |= (((255-r) >>> 31)*0xFF);<NEW_LINE>// g |= (((255-g) >>> 31)*0xFF);<NEW_LINE>// b |= (((255-b) >>> 31)*0xFF);<NEW_LINE>if (r > 255)<NEW_LINE>r = 255;<NEW_LINE>if (g > 255)<NEW_LINE>g = 255;<NEW_LINE>if (b > 255)<NEW_LINE>b = 255;<NEW_LINE>R.data[indexOut] = (byte) r;<NEW_LINE>G.data[indexOut] = (byte) g;<NEW_LINE>B.data[indexOut] = (byte) b;<NEW_LINE>indexU += col & 0x1;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// CONCURRENT_ABOVE });<NEW_LINE>} | - 218 * cb) >> 10; |
1,129,423 | private void superPostActivate(InvocationContext inv) {<NEW_LINE>try {<NEW_LINE>Object resultsObject = getResultsObject(inv);<NEW_LINE>addPostActivate(resultsObject, CLASS_NAME, "superPostActivate");<NEW_LINE>// Validate and update context data.<NEW_LINE>Map<String, Object> map = inv.getContextData();<NEW_LINE>String data;<NEW_LINE>if (map.containsKey("PostActivate")) {<NEW_LINE>data = (String) map.get("PostActivate");<NEW_LINE>data = data + ":" + CLASS_NAME;<NEW_LINE>} else {<NEW_LINE>data = CLASS_NAME;<NEW_LINE>}<NEW_LINE>map.put("PostActivate", data);<NEW_LINE>setPostActivateContextData(resultsObject, data);<NEW_LINE>// Verify around invoke does not see any context data from lifecycle<NEW_LINE>// callback events.<NEW_LINE>if (map.containsKey("PostConstruct")) {<NEW_LINE>throw new IllegalStateException("PostConstruct context data shared with PostActivate interceptor");<NEW_LINE>} else if (map.containsKey("AroundInvoke")) {<NEW_LINE>throw new IllegalStateException("AroundInvoke context data shared with PostActivate interceptor");<NEW_LINE>} else if (map.containsKey("PrePassivate")) {<NEW_LINE>throw new IllegalStateException("PrePassivate context data shared with PostActivate interceptor");<NEW_LINE>} else if (map.containsKey("PreDestroy")) {<NEW_LINE>throw new IllegalStateException("PreDestroy context data shared with PostActivate interceptor");<NEW_LINE>}<NEW_LINE>// Verify same InvocationContext passed to each PostActivate<NEW_LINE>// interceptor method.<NEW_LINE>InvocationContext ctxData;<NEW_LINE>if (map.containsKey("InvocationContext")) {<NEW_LINE>ctxData = (InvocationContext) map.get("InvocationContext");<NEW_LINE>if (inv != ctxData) {<NEW_LINE>throw new IllegalStateException("Same InvocationContext not passed to each PostActivate interceptor");<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>map.put("InvocationContext", inv);<NEW_LINE>}<NEW_LINE>inv.proceed();<NEW_LINE>} catch (Exception e) {<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>} | throw new EJBException("unexpected Throwable", e); |
616,126 | public static EventType resolve(String name, String moduleName, NameAccessModifier accessModifier, EventTypeNameResolver publics, Map<String, EventType> locals, PathRegistry<String, EventType> path) {<NEW_LINE>EventType type;<NEW_LINE>// public can only see public<NEW_LINE>if (accessModifier == NameAccessModifier.PRECONFIGURED) {<NEW_LINE>type = publics.getTypeByName(name);<NEW_LINE>// for create-schema the type may be defined by the same module<NEW_LINE>if (type == null) {<NEW_LINE>type = locals.get(name);<NEW_LINE>}<NEW_LINE>} else if (accessModifier == NameAccessModifier.PUBLIC || accessModifier == NameAccessModifier.PROTECTED) {<NEW_LINE>// path-visibility can be provided as local<NEW_LINE>EventType local = locals.get(name);<NEW_LINE>if (local != null) {<NEW_LINE>if (local.getMetadata().getAccessModifier() == NameAccessModifier.PUBLIC || local.getMetadata().getAccessModifier() == NameAccessModifier.PROTECTED) {<NEW_LINE>return local;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>Pair<EventType, String> pair = path.getAnyModuleExpectSingle(name, Collections.singleton(moduleName));<NEW_LINE>type = pair == null <MASK><NEW_LINE>} catch (PathException e) {<NEW_LINE>throw new EPException(e.getMessage(), e);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>type = locals.get(name);<NEW_LINE>}<NEW_LINE>if (type == null) {<NEW_LINE>throw new EPException("Failed to find event type '" + name + "' among public types, modules-in-path or the current module itself");<NEW_LINE>}<NEW_LINE>return type;<NEW_LINE>} | ? null : pair.getFirst(); |
732,125 | public TsiFrameProtector createFrameProtector(int maxFrameSize, ByteBufAllocator alloc) {<NEW_LINE>Preconditions.checkState<MASK><NEW_LINE>byte[] key = handshaker.getKey();<NEW_LINE>Preconditions.checkState(key.length == AltsChannelCrypter.getKeyLength(), "Bad key length.");<NEW_LINE>// Frame size negotiation is not performed if the peer does not send max frame size (e.g. peer<NEW_LINE>// is gRPC Go or peer uses an old binary).<NEW_LINE>int peerMaxFrameSize = handshaker.getResult().getMaxFrameSize();<NEW_LINE>if (peerMaxFrameSize != 0) {<NEW_LINE>maxFrameSize = Math.min(peerMaxFrameSize, AltsTsiFrameProtector.getMaxFrameSize());<NEW_LINE>maxFrameSize = Math.max(AltsTsiFrameProtector.getMinFrameSize(), maxFrameSize);<NEW_LINE>}<NEW_LINE>logger.log(ChannelLogLevel.INFO, "Maximum frame size value is {0}.", maxFrameSize);<NEW_LINE>return new AltsTsiFrameProtector(maxFrameSize, new AltsChannelCrypter(key, isClient), alloc);<NEW_LINE>} | (!isInProgress(), "Handshake is not complete."); |
356,300 | public void publishAdditionalModelData(JavaSparkContext sparkContext, PMML pmml, JavaRDD<String> newData, JavaRDD<String> pastData, Path modelParentPath, TopicProducer<String, String> modelUpdateTopic) {<NEW_LINE>// Send item updates first, before users. That way, user-based endpoints like /recommend<NEW_LINE>// may take longer to not return 404, but when they do, the result will be more complete.<NEW_LINE>log.info("Sending item / Y data as model updates");<NEW_LINE>String yPathString = AppPMMLUtils.getExtensionValue(pmml, "Y");<NEW_LINE>JavaPairRDD<String, float[]> productRDD = readFeaturesRDD(sparkContext, new Path(modelParentPath, yPathString));<NEW_LINE>String updateBroker = modelUpdateTopic.getUpdateBroker();<NEW_LINE>String topic = modelUpdateTopic.getTopic();<NEW_LINE>// For now, there is no use in sending known users for each item<NEW_LINE>productRDD.foreachPartition(new EnqueueFeatureVecsFn("Y", updateBroker, topic));<NEW_LINE>log.info("Sending user / X data as model updates");<NEW_LINE>String xPathString = AppPMMLUtils.getExtensionValue(pmml, "X");<NEW_LINE>JavaPairRDD<String, float[]> userRDD = readFeaturesRDD(sparkContext, new Path(modelParentPath, xPathString));<NEW_LINE>if (noKnownItems) {<NEW_LINE>userRDD.foreachPartition(new EnqueueFeatureVecsFn("X", updateBroker, topic));<NEW_LINE>} else {<NEW_LINE>log.info("Sending known item data with model updates");<NEW_LINE>JavaRDD<String[]> allData = (pastData == null ? newData : newData.union(pastData)).map(MLFunctions.PARSE_FN);<NEW_LINE>JavaPairRDD<String, Collection<String>> knownItems = knownsRDD(allData, true);<NEW_LINE>userRDD.join(knownItems).foreachPartition(new EnqueueFeatureVecsAndKnownItemsFn<MASK><NEW_LINE>}<NEW_LINE>} | ("X", updateBroker, topic)); |
722,321 | public OutboundSseEvent buildEvent(Builder eventBuilder, Set<String> itemNames) {<NEW_LINE>Map<String, StateDTO> payload = new HashMap<<MASK><NEW_LINE>for (String itemName : itemNames) {<NEW_LINE>try {<NEW_LINE>Item item = itemRegistry.getItem(itemName);<NEW_LINE>StateDTO stateDto = new StateDTO();<NEW_LINE>stateDto.state = item.getState().toString();<NEW_LINE>String displayState = getDisplayState(item, Locale.getDefault());<NEW_LINE>// Only include the display state if it's different than the raw state<NEW_LINE>if (stateDto.state != null && !stateDto.state.equals(displayState)) {<NEW_LINE>stateDto.displayState = displayState;<NEW_LINE>}<NEW_LINE>payload.put(itemName, stateDto);<NEW_LINE>} catch (ItemNotFoundException e) {<NEW_LINE>logger.warn("Attempting to send a state update of an item which doesn't exist: {}", itemName);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (!payload.isEmpty()) {<NEW_LINE>return eventBuilder.mediaType(MediaType.APPLICATION_JSON_TYPE).data(payload).build();<NEW_LINE>}<NEW_LINE>return null;<NEW_LINE>} | >(itemNames.size()); |
492,766 | public Answer execute(final SecurityGroupRulesCmd command, final LibvirtComputingResource libvirtComputingResource) {<NEW_LINE>String vif = null;<NEW_LINE>String brname = null;<NEW_LINE>try {<NEW_LINE>final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();<NEW_LINE>final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());<NEW_LINE>final List<InterfaceDef> nics = libvirtComputingResource.getInterfaces(conn, command.getVmName());<NEW_LINE>vif = nics.get(0).getDevName();<NEW_LINE>brname = nics.get(0).getBrName();<NEW_LINE>final <MASK><NEW_LINE>if (!libvirtComputingResource.applyDefaultNetworkRules(conn, vm, true)) {<NEW_LINE>s_logger.warn("Failed to program default network rules for vm " + command.getVmName());<NEW_LINE>return new SecurityGroupRuleAnswer(command, false, "programming default network rules failed");<NEW_LINE>}<NEW_LINE>} catch (final LibvirtException e) {<NEW_LINE>return new SecurityGroupRuleAnswer(command, false, e.toString());<NEW_LINE>}<NEW_LINE>final boolean result = libvirtComputingResource.addNetworkRules(command.getVmName(), Long.toString(command.getVmId()), command.getGuestIp(), command.getGuestIp6(), command.getSignature(), Long.toString(command.getSeqNum()), command.getGuestMac(), command.stringifyRules(), vif, brname, command.getSecIpsString());<NEW_LINE>if (!result) {<NEW_LINE>s_logger.warn("Failed to program network rules for vm " + command.getVmName());<NEW_LINE>return new SecurityGroupRuleAnswer(command, false, "programming network rules failed");<NEW_LINE>} else {<NEW_LINE>s_logger.debug("Programmed network rules for vm " + command.getVmName() + " guestIp=" + command.getGuestIp() + ",ingress numrules=" + command.getIngressRuleSet().size() + ",egress numrules=" + command.getEgressRuleSet().size());<NEW_LINE>return new SecurityGroupRuleAnswer(command);<NEW_LINE>}<NEW_LINE>} | VirtualMachineTO vm = command.getVmTO(); |
1,817,465 | public void removeOAuthApproval(String clientId, String xSdsAuthToken) throws ApiException {<NEW_LINE>Object localVarPostBody = null;<NEW_LINE>// verify the required parameter 'clientId' is set<NEW_LINE>if (clientId == null) {<NEW_LINE>throw new ApiException(400, "Missing the required parameter 'clientId' when calling removeOAuthApproval");<NEW_LINE>}<NEW_LINE>// create path and map variables<NEW_LINE>String localVarPath = "/v4/user/oauth/approvals/{client_id}".replaceAll("\\{" + "client_id" + "\\}", apiClient.escapeString(clientId.toString()));<NEW_LINE>// query params<NEW_LINE>List<Pair> localVarQueryParams <MASK><NEW_LINE>Map<String, String> localVarHeaderParams = new HashMap<String, String>();<NEW_LINE>Map<String, Object> localVarFormParams = new HashMap<String, Object>();<NEW_LINE>if (xSdsAuthToken != null)<NEW_LINE>localVarHeaderParams.put("X-Sds-Auth-Token", apiClient.parameterToString(xSdsAuthToken));<NEW_LINE>final String[] localVarAccepts = { "application/json" };<NEW_LINE>final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);<NEW_LINE>final String[] localVarContentTypes = {};<NEW_LINE>final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);<NEW_LINE>String[] localVarAuthNames = new String[] { "oauth2" };<NEW_LINE>apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null);<NEW_LINE>} | = new ArrayList<Pair>(); |
436,922 | private Mono<Response<Flux<ByteBuffer>>> deletePortMirroringWithResponseAsync(String resourceGroupName, String portMirroringId, String privateCloudName, Context context) {<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>if (resourceGroupName == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));<NEW_LINE>}<NEW_LINE>if (portMirroringId == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter portMirroringId is required and cannot be null."));<NEW_LINE>}<NEW_LINE>if (privateCloudName == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter privateCloudName is required and cannot be null."));<NEW_LINE>}<NEW_LINE>final String accept = "application/json";<NEW_LINE>context = this.client.mergeContext(context);<NEW_LINE>return service.deletePortMirroring(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, this.client.getApiVersion(), portMirroringId, privateCloudName, accept, context);<NEW_LINE>} | error(new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); |
1,818,935 | protected TestSuiteChromosome createMergedSolution(TestSuiteChromosome solution) {<NEW_LINE>// Deactivate in case a test is executed and would access the archive as this might cause a<NEW_LINE>// concurrent access<NEW_LINE>Properties.TEST_ARCHIVE = false;<NEW_LINE>TestSuiteChromosome mergedSolution = solution.clone();<NEW_LINE>// to avoid adding the same solution to 'mergedSolution' suite<NEW_LINE>Set<TestChromosome> <MASK><NEW_LINE>for (TestFitnessFunction target : this.archive.keySet()) {<NEW_LINE>// does solution cover target?<NEW_LINE>if (!target.isCoveredBy(mergedSolution)) {<NEW_LINE>Population population = this.archive.get(target);<NEW_LINE>// is there any solution in the archive that covers it?<NEW_LINE>TestChromosome t = population.getBestSolutionIfAny();<NEW_LINE>if (t != null) {<NEW_LINE>// has t been considered?<NEW_LINE>if (!solutionsSampledFromArchive.contains(t)) {<NEW_LINE>solutionsSampledFromArchive.add(t);<NEW_LINE>TestChromosome tClone = t.clone();<NEW_LINE>mergedSolution.addTest(tClone);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// re-evaluate merged solution<NEW_LINE>for (FitnessFunction<TestSuiteChromosome> ff : solution.getFitnessValues().keySet()) {<NEW_LINE>ff.getFitness(mergedSolution);<NEW_LINE>}<NEW_LINE>// re-active it<NEW_LINE>Properties.TEST_ARCHIVE = true;<NEW_LINE>logger.info("Final test suite size from archive: " + mergedSolution);<NEW_LINE>return mergedSolution;<NEW_LINE>} | solutionsSampledFromArchive = new LinkedHashSet<>(); |
356,156 | /*<NEW_LINE>* (non-Javadoc)<NEW_LINE>*<NEW_LINE>* @see com.vaadin.ui.AbstractComponent#readDesign(org.jsoup.nodes .Element,<NEW_LINE>* com.vaadin.ui.declarative.DesignContext)<NEW_LINE>*/<NEW_LINE>@Override<NEW_LINE>public void readDesign(Element design, DesignContext designContext) {<NEW_LINE>// handle default attributes<NEW_LINE>super.readDesign(design, designContext);<NEW_LINE>// handle custom attributes, use default values if no explicit value<NEW_LINE>// set<NEW_LINE>// There is no setter for reversed, so it will be handled using<NEW_LINE>// setSplitPosition.<NEW_LINE>boolean reversed = false;<NEW_LINE>if (design.hasAttr("reversed")) {<NEW_LINE>reversed = DesignAttributeHandler.readAttribute("reversed", design.attributes(), Boolean.class);<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>if (design.hasAttr("split-position")) {<NEW_LINE>SizeWithUnit splitPosition = SizeWithUnit.parseStringSize(design.attr("split-position"), Unit.PERCENTAGE);<NEW_LINE>setSplitPosition(splitPosition.getSize(), splitPosition.getUnit(), reversed);<NEW_LINE>}<NEW_LINE>if (design.hasAttr("min-split-position")) {<NEW_LINE>SizeWithUnit minSplitPosition = SizeWithUnit.parseStringSize(design.attr("min-split-position"), Unit.PERCENTAGE);<NEW_LINE>setMinSplitPosition(minSplitPosition.getSize(), minSplitPosition.getUnit());<NEW_LINE>}<NEW_LINE>if (design.hasAttr("max-split-position")) {<NEW_LINE>SizeWithUnit maxSplitPosition = SizeWithUnit.parseStringSize(design.attr("max-split-position"), Unit.PERCENTAGE);<NEW_LINE>setMaxSplitPosition(maxSplitPosition.getSize(), maxSplitPosition.getUnit());<NEW_LINE>}<NEW_LINE>// handle children<NEW_LINE>if (design.children().size() > 2) {<NEW_LINE>throw new DesignException("A split panel can contain at most two components.");<NEW_LINE>}<NEW_LINE>for (Element childElement : design.children()) {<NEW_LINE>Component childComponent = designContext.readDesign(childElement);<NEW_LINE>if (childElement.hasAttr(":second")) {<NEW_LINE>setSecondComponent(childComponent);<NEW_LINE>} else {<NEW_LINE>addComponent(childComponent);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | setSplitPosition(getSplitPosition(), reversed); |
1,434,916 | public void onScrolled(@NonNull @NotNull RecyclerView recyclerView, int dx, int dy) {<NEW_LINE>super.onScrolled(recyclerView, dx, dy);<NEW_LINE>mEmojiPalettesAdapter.onPageScrolled();<NEW_LINE>final int offset = recyclerView.computeVerticalScrollOffset();<NEW_LINE>final <MASK><NEW_LINE>final int range = recyclerView.computeVerticalScrollRange();<NEW_LINE>final float percentage = offset / (float) (range - extent);<NEW_LINE>final int currentCategorySize = mEmojiCategory.getCurrentCategoryPageCount();<NEW_LINE>final int a = (int) (percentage * currentCategorySize);<NEW_LINE>final float b = percentage * currentCategorySize - a;<NEW_LINE>mEmojiCategoryPageIndicatorView.setCategoryPageId(currentCategorySize, a, b);<NEW_LINE>final int firstCompleteVisibleBoard = mEmojiLayoutManager.findFirstCompletelyVisibleItemPosition();<NEW_LINE>final int firstVisibleBoard = mEmojiLayoutManager.findFirstVisibleItemPosition();<NEW_LINE>mEmojiCategory.setCurrentCategoryPageId(firstCompleteVisibleBoard > 0 ? firstCompleteVisibleBoard : firstVisibleBoard);<NEW_LINE>} | int extent = recyclerView.computeVerticalScrollExtent(); |
915,924 | final GetChannelPolicyResult executeGetChannelPolicy(GetChannelPolicyRequest getChannelPolicyRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(getChannelPolicyRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<GetChannelPolicyRequest> request = null;<NEW_LINE>Response<GetChannelPolicyResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new GetChannelPolicyRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(getChannelPolicyRequest));<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(<MASK><NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "MediaTailor");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "GetChannelPolicy");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<GetChannelPolicyResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new GetChannelPolicyResultJsonUnmarshaller());<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>} | HandlerContextKey.SIGNING_REGION, getSigningRegion()); |
721,157 | private boolean areVariablesFormattersEqual(VariablesFormatter savedFormatter, VariablesFormatter currentFormatter) {<NEW_LINE>return savedFormatter.getName().equals(currentFormatter.getName()) && savedFormatter.getChildrenExpandTestCode().equals(currentFormatter.getChildrenExpandTestCode()) && savedFormatter.getChildrenFormatCode().equals(currentFormatter.getChildrenFormatCode()) && savedFormatter.getChildrenVariables().equals(currentFormatter.getChildrenVariables()) && Arrays.equals(savedFormatter.getClassTypes(), currentFormatter.getClassTypes()) && savedFormatter.getClassTypesCommaSeparated().equals(currentFormatter.getClassTypesCommaSeparated()) && savedFormatter.getValueFormatCode().equals(currentFormatter.getValueFormatCode()) && savedFormatter.isDefault() == currentFormatter.isDefault() && savedFormatter.isEnabled() == currentFormatter.isEnabled() && savedFormatter.isIncludeSubTypes() == currentFormatter.isIncludeSubTypes() && savedFormatter.isUseChildrenVariables<MASK><NEW_LINE>} | () == currentFormatter.isUseChildrenVariables(); |
1,374,029 | public static void decisionListDemo() {<NEW_LINE>try {<NEW_LINE>System.out.println(Util<MASK><NEW_LINE>System.out.println("DecisionList Demo - Inducing a DecisionList from the Restaurant DataSet\n ");<NEW_LINE>System.out.println(Util.ntimes("*", 100));<NEW_LINE>DataSet ds = DataSetFactory.getRestaurantDataSet();<NEW_LINE>DecisionListLearner learner = new DecisionListLearner("Yes", "No", new DLTestFactory());<NEW_LINE>learner.train(ds);<NEW_LINE>System.out.println("The Induced DecisionList is");<NEW_LINE>System.out.println(learner.getDecisionList());<NEW_LINE>int[] result = learner.test(ds);<NEW_LINE>System.out.println("\nThis Decision List classifies the data set with " + result[0] + " successes" + " and " + result[1] + " failures");<NEW_LINE>System.out.println("\n");<NEW_LINE>} catch (Exception e) {<NEW_LINE>System.out.println("Decision ListDemo Failed");<NEW_LINE>}<NEW_LINE>} | .ntimes("*", 100)); |
1,541,068 | public void connect(String hostName, int port) throws IOException {<NEW_LINE>try {<NEW_LINE>// logmet seems to have a keepalive of about 20-30 seconds.<NEW_LINE>// Proactively close our connection if this connection hasn't been used in a while<NEW_LINE>boolean refreshingConnection = false;<NEW_LINE>if (lumberjackClient.isSocketAvailable() && lumberjackClient.isConnectionStale()) {<NEW_LINE>if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())<NEW_LINE>Tr.event(tc, "Connection has timed out - will reconnect before trying to use it");<NEW_LINE>// avoid printing any info messages in this case -- would be too verbose to do so<NEW_LINE>// no change to connectionInitialized<NEW_LINE>lumberjackClient.close();<NEW_LINE>refreshingConnection = true;<NEW_LINE>connectionInitialized = false;<NEW_LINE>}<NEW_LINE>// We are re-trying to connect because of a connection failure<NEW_LINE>// or a bad connection configuration, pause for a short while.<NEW_LINE>if (connectionRetry) {<NEW_LINE>try {<NEW_LINE>Thread.sleep(CONNECTION_RETRY_WAIT_TIME);<NEW_LINE>} catch (InterruptedException e) {<NEW_LINE>// Ignore and continue<NEW_LINE>}<NEW_LINE>}<NEW_LINE>lumberjackClient.connect(hostName, port);<NEW_LINE>if (!connectionInitialized) {<NEW_LINE>if (!refreshingConnection)<NEW_LINE>Tr.info(tc, "LOGSTASH_CONNECTION_ESTABLISHED", hostName<MASK><NEW_LINE>connectionInitialized = true;<NEW_LINE>}<NEW_LINE>connectionRetry = false;<NEW_LINE>} catch (IOException e) {<NEW_LINE>if (!connectionRetry) {<NEW_LINE>connectionRetry = true;<NEW_LINE>Tr.warning(tc, "LOGSTASH_CONNECTION_FAILED", hostName, String.valueOf(port));<NEW_LINE>}<NEW_LINE>throw e;<NEW_LINE>}<NEW_LINE>} | , String.valueOf(port)); |
432,776 | public double score(Mention antecedent, Mention anaphor, Counter<String> antecedentFeatures, Counter<String> anaphorFeatures, Counter<String> pairFeatures, Map<Integer, SimpleMatrix> antecedentCache, Map<Integer, SimpleMatrix> anaphorCache) {<NEW_LINE>SimpleMatrix antecedentVector = NARepresentation;<NEW_LINE>if (antecedent != null) {<NEW_LINE>antecedentVector = antecedentCache.get(antecedent.mentionID);<NEW_LINE>if (antecedentVector == null) {<NEW_LINE>antecedentVector = antecedentKernel.mult(NeuralUtils.concatenate(embeddingExtractor.getMentionEmbeddingsForFast(antecedent), makeFeatureVector(antecedentFeatures, mentionFeatureIds))).plus(antecedentBias);<NEW_LINE>antecedentCache.put(antecedent.mentionID, antecedentVector);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>SimpleMatrix anaphorVector = anaphorCache.get(anaphor.mentionID);<NEW_LINE>if (anaphorVector == null) {<NEW_LINE>anaphorVector = anaphorKernel.mult(NeuralUtils.concatenate(embeddingExtractor.getMentionEmbeddingsForFast(anaphor), makeFeatureVector(anaphorFeatures, mentionFeatureIds))).plus(anaphorBias);<NEW_LINE>anaphorCache.put(anaphor.mentionID, anaphorVector);<NEW_LINE>}<NEW_LINE>SimpleMatrix pairFeaturesVector = pairFeaturesKernel.mult(pairFeatures == null ? new SimpleMatrix(pairFeatureIds.size() + 23, 1) : addDistanceFeatures(makeFeatureVector(pairFeatures, pairFeatureIds), antecedent, <MASK><NEW_LINE>SimpleMatrix pairVector = antecedentVector.concatRows(anaphorVector).concatRows(pairFeaturesVector);<NEW_LINE>pairVector = NeuralUtils.elementwiseApplyReLU(pairVector);<NEW_LINE>for (int i = 0; i < networkLayers.size(); i += 2) {<NEW_LINE>pairVector = networkLayers.get(i).mult(pairVector).plus(networkLayers.get(i + 1));<NEW_LINE>if (networkLayers.get(i).numRows() > 1) {<NEW_LINE>pairVector = NeuralUtils.elementwiseApplyReLU(pairVector);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return pairVector.elementSum();<NEW_LINE>} | anaphor)).plus(pairFeaturesBias); |
1,710,664 | public Concrete.FunctionDefinition function(@NotNull ArendRef ref, @NotNull FunctionKind kind, @NotNull Collection<? extends ConcreteParameter> parameters, @Nullable ConcreteExpression resultType, @Nullable ConcreteExpression resultTypeLevel, @NotNull ConcreteFunctionBody body) {<NEW_LINE>if (!(ref instanceof ConcreteLocatedReferable)) {<NEW_LINE>throw new IllegalArgumentException("The reference must be a global reference with a parent");<NEW_LINE>}<NEW_LINE>if (kind.isUse() || kind.isCoclause()) {<NEW_LINE>throw new IllegalArgumentException("\\use definitions and coclause functions are not supported yet");<NEW_LINE>}<NEW_LINE>if (!((resultType == null || resultType instanceof Concrete.Expression) && (resultTypeLevel == null || resultTypeLevel instanceof Concrete.Expression) && body instanceof Concrete.FunctionBody)) {<NEW_LINE>throw new IllegalArgumentException();<NEW_LINE>}<NEW_LINE>ConcreteLocatedReferable cRef = (ConcreteLocatedReferable) ref;<NEW_LINE>cRef.setKind<MASK><NEW_LINE>Concrete.FunctionDefinition result = new Concrete.FunctionDefinition(kind, cRef, parameters(parameters), (Concrete.Expression) resultType, (Concrete.Expression) resultTypeLevel, (Concrete.FunctionBody) body);<NEW_LINE>cRef.setDefinition(result);<NEW_LINE>return result;<NEW_LINE>} | (GlobalReferable.kindFromFunction(kind)); |
584,144 | /* Sample generated code:<NEW_LINE>*<NEW_LINE>* @com.ibm.j9ddr.GeneratedFieldAccessor(offsetFieldName="_ramConstantPoolOffset_", declaredType="UDATA*")<NEW_LINE>* public UDATAPointer ramConstantPool() throws CorruptDataException {<NEW_LINE>* return UDATAPointer.cast(getPointerAtOffset(J9Class._ramConstantPoolOffset_));<NEW_LINE>* }<NEW_LINE>*/<NEW_LINE>private void doPointerMethod(FieldDescriptor field) {<NEW_LINE>String targetType = getTargetType(removeTypeTags(field.getType()));<NEW_LINE>String qualifiedTargetType = qualifyPointerType(targetType);<NEW_LINE>String castDesc = Type.getMethodDescriptor(Type.getObjectType(qualifiedTargetType), Type.LONG_TYPE);<NEW_LINE>String returnType = generalizeSimpleType(targetType);<NEW_LINE>String qualifiedReturnType = qualifyPointerType(returnType);<NEW_LINE>String returnDesc = Type.getMethodDescriptor(Type.getObjectType(qualifiedReturnType));<NEW_LINE>MethodVisitor method = beginAnnotatedMethod(field, field.getName(), returnDesc);<NEW_LINE>method.visitCode();<NEW_LINE>if (checkPresent(field, method)) {<NEW_LINE>method.visitVarInsn(ALOAD, 0);<NEW_LINE>loadLong(method, field.getOffset());<NEW_LINE>method.visitMethodInsn(INVOKEVIRTUAL, <MASK><NEW_LINE>method.visitMethodInsn(INVOKESTATIC, qualifiedTargetType, "cast", castDesc, false);<NEW_LINE>method.visitInsn(ARETURN);<NEW_LINE>}<NEW_LINE>method.visitMaxs(3, 1);<NEW_LINE>method.visitEnd();<NEW_LINE>doEAMethod("Pointer", field);<NEW_LINE>} | className, "getPointerAtOffset", longFromLong, false); |
853,954 | private void openStream() throws IOException {<NEW_LINE>ServiceException lastException = null;<NEW_LINE>String errorMessage = String.format("Failed to open key: %s bucket: %s", mKey, mBucketName);<NEW_LINE>while (mRetryPolicy.attempt()) {<NEW_LINE>try {<NEW_LINE>GSObject object;<NEW_LINE>if (mPos > 0) {<NEW_LINE>object = mClient.getObject(mBucketName, mKey, null, null, <MASK><NEW_LINE>} else {<NEW_LINE>object = mClient.getObject(mBucketName, mKey);<NEW_LINE>}<NEW_LINE>mInputStream = new BufferedInputStream(object.getDataInputStream());<NEW_LINE>return;<NEW_LINE>} catch (ServiceException e) {<NEW_LINE>errorMessage = String.format("Failed to open key: %s bucket: %s attempts: %d error: %s", mKey, mBucketName, mRetryPolicy.getAttemptCount(), e.getMessage());<NEW_LINE>if (e.getResponseCode() != HttpStatus.SC_NOT_FOUND) {<NEW_LINE>throw new IOException(errorMessage, e);<NEW_LINE>}<NEW_LINE>// Key does not exist<NEW_LINE>lastException = e;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// Failed after retrying key does not exist<NEW_LINE>throw new IOException(errorMessage, lastException);<NEW_LINE>} | null, null, mPos, null); |
886,753 | static CodeRangeable strDeleteBang(CodeRangeable rubyString, boolean[] squeeze, TrTables tables, Encoding enc) {<NEW_LINE>rubyString.modify();<NEW_LINE>rubyString.keepCodeRange();<NEW_LINE>final ByteList value = rubyString.getByteList();<NEW_LINE>int s = value.getBegin();<NEW_LINE>int t = s;<NEW_LINE>int send = s + value.getRealSize();<NEW_LINE>byte[] bytes = value.getUnsafeBytes();<NEW_LINE>boolean modify = false;<NEW_LINE>boolean asciiCompatible = enc.isAsciiCompatible();<NEW_LINE>int cr = asciiCompatible ? CR_7BIT : CR_VALID;<NEW_LINE>while (s < send) {<NEW_LINE>int c;<NEW_LINE>if (asciiCompatible && Encoding.isAscii(c = bytes[s] & 0xff)) {<NEW_LINE>if (squeeze[c]) {<NEW_LINE>modify = true;<NEW_LINE>} else {<NEW_LINE>if (t != s)<NEW_LINE>bytes[t] = (byte) c;<NEW_LINE>t++;<NEW_LINE>}<NEW_LINE>s++;<NEW_LINE>} else {<NEW_LINE>c = codePoint(enc, bytes, s, send);<NEW_LINE>int cl = codeLength(enc, c);<NEW_LINE>if (trFind(c, squeeze, tables)) {<NEW_LINE>modify = true;<NEW_LINE>} else {<NEW_LINE>if (t != s)<NEW_LINE>enc.codeToMbc(c, bytes, t);<NEW_LINE>t += cl;<NEW_LINE>if (cr == CR_7BIT)<NEW_LINE>cr = CR_VALID;<NEW_LINE>}<NEW_LINE>s += cl;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>value.setRealSize(<MASK><NEW_LINE>rubyString.setCodeRange(cr);<NEW_LINE>return modify ? rubyString : null;<NEW_LINE>} | t - value.getBegin()); |
1,386,792 | public AwsJobExponentialRolloutRate 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>AwsJobExponentialRolloutRate awsJobExponentialRolloutRate = new AwsJobExponentialRolloutRate();<NEW_LINE>reader.beginObject();<NEW_LINE>while (reader.hasNext()) {<NEW_LINE>String name = reader.nextName();<NEW_LINE>if (name.equals("baseRatePerMinute")) {<NEW_LINE>awsJobExponentialRolloutRate.setBaseRatePerMinute(IntegerJsonUnmarshaller.getInstance().unmarshall(context));<NEW_LINE>} else if (name.equals("incrementFactor")) {<NEW_LINE>awsJobExponentialRolloutRate.setIncrementFactor(DoubleJsonUnmarshaller.getInstance().unmarshall(context));<NEW_LINE>} else if (name.equals("rateIncreaseCriteria")) {<NEW_LINE>awsJobExponentialRolloutRate.setRateIncreaseCriteria(AwsJobRateIncreaseCriteriaJsonUnmarshaller.getInstance<MASK><NEW_LINE>} else {<NEW_LINE>reader.skipValue();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>reader.endObject();<NEW_LINE>return awsJobExponentialRolloutRate;<NEW_LINE>} | ().unmarshall(context)); |
1,543,809 | private void writeOp(SelectionKey key, RapidoidConnection conn, SocketChannel socketChannel) throws IOException {<NEW_LINE>synchronized (conn.outgoing) {<NEW_LINE>if (conn.outgoing.hasRemaining()) {<NEW_LINE>conn.log("WRITING");<NEW_LINE>// conn.log(conn.outgoing.asText());<NEW_LINE><MASK><NEW_LINE>int wrote = conn.outgoing.writeTo(socketChannel);<NEW_LINE>conn.outgoing.deleteBefore(wrote);<NEW_LINE>BufUtil.doneWriting(conn.outgoing);<NEW_LINE>conn.log("DONE WRITING");<NEW_LINE>}<NEW_LINE>}<NEW_LINE>boolean finishedWriting, closeAfterWrite;<NEW_LINE>synchronized (conn) {<NEW_LINE>finishedWriting = conn.finishedWriting();<NEW_LINE>closeAfterWrite = conn.closeAfterWrite();<NEW_LINE>}<NEW_LINE>if (finishedWriting && closeAfterWrite) {<NEW_LINE>close(conn);<NEW_LINE>} else {<NEW_LINE>if (finishedWriting) {<NEW_LINE>key.interestOps(conn.mode != 0 ? conn.mode : conn.nextOp);<NEW_LINE>processNext(conn, false, true);<NEW_LINE>} else {<NEW_LINE>key.interestOps(conn.mode != 0 ? conn.mode : (SelectionKey.OP_READ + SelectionKey.OP_WRITE));<NEW_LINE>}<NEW_LINE>conn.wrote(finishedWriting);<NEW_LINE>}<NEW_LINE>} | BufUtil.startWriting(conn.outgoing); |
1,645,587 | public void navigate(AnActionEvent e, boolean openLibraryEditor) {<NEW_LINE>final OrderEntry entry = getSelectedEntry();<NEW_LINE>ProjectStructureSelector selector = e.getData(ProjectStructureSelector.KEY);<NEW_LINE>if (entry instanceof ModuleOrderEntry) {<NEW_LINE>Module module = ((ModuleOrderEntry) entry).getModule();<NEW_LINE>if (module != null) {<NEW_LINE>selector.select(module.getName(), null, true);<NEW_LINE>}<NEW_LINE>} else if (entry instanceof LibraryOrderEntry) {<NEW_LINE>if (!openLibraryEditor) {<NEW_LINE>selector.select((LibraryOrderEntry) entry, true);<NEW_LINE>} else {<NEW_LINE>myEditButton.actionPerformed(ActionUtil.createEmptyEvent());<NEW_LINE>}<NEW_LINE>} else if (entry instanceof ModuleExtensionWithSdkOrderEntry) {<NEW_LINE>Sdk sdk = ((ModuleExtensionWithSdkOrderEntry) entry).getSdk();<NEW_LINE>if (sdk != null) {<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | selector.select(sdk, true); |
288,706 | public DeviceFleetSummary unmarshall(JsonUnmarshallerContext context) throws Exception {<NEW_LINE>DeviceFleetSummary deviceFleetSummary = new DeviceFleetSummary();<NEW_LINE>int originalDepth = context.getCurrentDepth();<NEW_LINE>String currentParentElement = context.getCurrentParentElement();<NEW_LINE>int targetDepth = originalDepth + 1;<NEW_LINE><MASK><NEW_LINE>if (token == null)<NEW_LINE>token = context.nextToken();<NEW_LINE>if (token == VALUE_NULL) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>while (true) {<NEW_LINE>if (token == null)<NEW_LINE>break;<NEW_LINE>if (token == FIELD_NAME || token == START_OBJECT) {<NEW_LINE>if (context.testExpression("DeviceFleetArn", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>deviceFleetSummary.setDeviceFleetArn(context.getUnmarshaller(String.class).unmarshall(context));<NEW_LINE>}<NEW_LINE>if (context.testExpression("DeviceFleetName", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>deviceFleetSummary.setDeviceFleetName(context.getUnmarshaller(String.class).unmarshall(context));<NEW_LINE>}<NEW_LINE>if (context.testExpression("CreationTime", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>deviceFleetSummary.setCreationTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));<NEW_LINE>}<NEW_LINE>if (context.testExpression("LastModifiedTime", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>deviceFleetSummary.setLastModifiedTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));<NEW_LINE>}<NEW_LINE>} else if (token == END_ARRAY || token == END_OBJECT) {<NEW_LINE>if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {<NEW_LINE>if (context.getCurrentDepth() <= originalDepth)<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>token = context.nextToken();<NEW_LINE>}<NEW_LINE>return deviceFleetSummary;<NEW_LINE>} | JsonToken token = context.getCurrentToken(); |
1,642,190 | public List<Product> readProductsByIds(List<Long> productIds) {<NEW_LINE>if (productIds == null || productIds.size() == 0) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>if (productIds.size() > 100) {<NEW_LINE>logger.warn("Not recommended to use the readProductsByIds method for long lists of productIds, since " + "Hibernate is required to transform the distinct results. The list of requested" + "product ids was (" + productIds.size() + ") in length.");<NEW_LINE>}<NEW_LINE>// Set up the criteria query that specifies we want to return Products<NEW_LINE>CriteriaBuilder builder = em.getCriteriaBuilder();<NEW_LINE>CriteriaQuery<Product> criteria = <MASK><NEW_LINE>Root<ProductImpl> product = criteria.from(ProductImpl.class);<NEW_LINE>product.fetch("defaultSku", JoinType.LEFT);<NEW_LINE>criteria.select(product);<NEW_LINE>// We only want results that match the product IDs<NEW_LINE>criteria.where(product.get("id").as(Long.class).in(sandBoxHelper.mergeCloneIds(ProductImpl.class, productIds.toArray(new Long[productIds.size()]))));<NEW_LINE>TypedQuery<Product> query = em.createQuery(criteria);<NEW_LINE>query.setHint(QueryHints.HINT_CACHEABLE, true);<NEW_LINE>query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");<NEW_LINE>return query.getResultList();<NEW_LINE>} | builder.createQuery(Product.class); |
482,633 | protected Session createSession(Host hc, String user, String host, int port, FS fs) throws JSchException {<NEW_LINE>Session session = super.createSession(hc, <MASK><NEW_LINE>try {<NEW_LINE>List<Proxy> proxies = ProxySelector.getDefault().select(new URI("socket", null, host, port == -1 ? 22 : port, null, null, null));<NEW_LINE>if (proxies.size() > 0) {<NEW_LINE>Proxy p = proxies.iterator().next();<NEW_LINE>if (p.type() == Proxy.Type.DIRECT) {<NEW_LINE>session.setProxy(null);<NEW_LINE>} else {<NEW_LINE>SocketAddress addr = p.address();<NEW_LINE>if (addr instanceof InetSocketAddress) {<NEW_LINE>InetSocketAddress inetAddr = (InetSocketAddress) addr;<NEW_LINE>String proxyHost = inetAddr.getHostName();<NEW_LINE>int proxyPort = inetAddr.getPort();<NEW_LINE>session.setProxy(createProxy(proxyHost, proxyPort));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} catch (URISyntaxException ex) {<NEW_LINE>Logger.getLogger(JGitSshSessionFactory.class.getName()).log(Level.INFO, "Invalid URI: " + host + ":" + port, ex);<NEW_LINE>}<NEW_LINE>return session;<NEW_LINE>} | user, host, port, fs); |
822,991 | protected RelDataType deriveRowType() {<NEW_LINE>final RelDataTypeFactory typeFactory = getCluster().getTypeFactory();<NEW_LINE>List<RelDataTypeFieldImpl> columns = new ArrayList<>();<NEW_LINE>columns.add(new RelDataTypeFieldImpl("NODE", 0, typeFactory.createSqlType(SqlTypeName.VARCHAR)));<NEW_LINE>columns.add(new RelDataTypeFieldImpl("CONN_ID", 1, typeFactory.createSqlType(SqlTypeName.VARCHAR)));<NEW_LINE>columns.add(new RelDataTypeFieldImpl("TRX_ID", 2, typeFactory.createSqlType(SqlTypeName.BIGINT)));<NEW_LINE>columns.add(new RelDataTypeFieldImpl("TRACE_ID", 3, typeFactory.createSqlType(SqlTypeName.VARCHAR)));<NEW_LINE>columns.add(new RelDataTypeFieldImpl("SCHEMA", 4, typeFactory.<MASK><NEW_LINE>columns.add(new RelDataTypeFieldImpl("TABLE", 5, typeFactory.createSqlType(SqlTypeName.VARCHAR)));<NEW_LINE>columns.add(new RelDataTypeFieldImpl("TYPE", 6, typeFactory.createSqlType(SqlTypeName.VARCHAR)));<NEW_LINE>columns.add(new RelDataTypeFieldImpl("DURATION", 7, typeFactory.createSqlType(SqlTypeName.VARCHAR)));<NEW_LINE>columns.add(new RelDataTypeFieldImpl("VALIDATE", 8, typeFactory.createSqlType(SqlTypeName.INTEGER)));<NEW_LINE>columns.add(new RelDataTypeFieldImpl("FRONTEND", 9, typeFactory.createSqlType(SqlTypeName.VARCHAR)));<NEW_LINE>columns.add(new RelDataTypeFieldImpl("SQL", 10, typeFactory.createSqlType(SqlTypeName.VARCHAR)));<NEW_LINE>return typeFactory.createStructType(columns);<NEW_LINE>} | createSqlType(SqlTypeName.VARCHAR))); |
1,164,178 | private boolean tryAbortTransactions(String keyspace, TransactionsTableInteraction txnInteraction, Statement abortStatement, Statement checkStatement, long startTs, long commitTs) {<NEW_LINE>log.info("Aborting transaction", SafeArg.of("startTs", startTs), SafeArg.of("commitTs", commitTs), SafeArg.of("keyspace", keyspace));<NEW_LINE>ResultSet abortResultSet = cqlSession.execute(abortStatement);<NEW_LINE>if (abortResultSet.wasApplied()) {<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>log.debug("Executing check statement", SafeArg.of("startTs", startTs), SafeArg.of("commitTs", commitTs), SafeArg.of("keyspace", keyspace));<NEW_LINE>ResultSet checkResultSet = cqlSession.execute(checkStatement);<NEW_LINE>Row result = Iterators.getOnlyElement(checkResultSet.<MASK><NEW_LINE>TransactionTableEntry transactionTableEntry = txnInteraction.extractTimestamps(result);<NEW_LINE>if (isAborted(transactionTableEntry)) {<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>log.warn("Retrying abort statement", SafeArg.of("startTs", startTs), SafeArg.of("commitTs", commitTs), SafeArg.of("keyspace", keyspace));<NEW_LINE>return false;<NEW_LINE>} | all().iterator()); |
1,601,438 | ActionResult<Wo> execute(EffectivePerson effectivePerson, String id) 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>Folder2 folder = emc.find(id, Folder2.class);<NEW_LINE>if (null == folder) {<NEW_LINE>throw new ExceptionFolderNotExist(id);<NEW_LINE>}<NEW_LINE>if (!StringUtils.equals(folder.getPerson(), effectivePerson.getDistinguishedName())) {<NEW_LINE>throw new Exception("person{name:" + effectivePerson.getDistinguishedName() + "} access folder{id:" + id + "} denied.");<NEW_LINE>}<NEW_LINE>String zipName = folder.getName() + ".zip";<NEW_LINE>List<Folder2> folderList = new ArrayList<>();<NEW_LINE>folderList.add(folder);<NEW_LINE>try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {<NEW_LINE>this.fileCommonService.downToZip(emc, null, folderList, os);<NEW_LINE>byte[<MASK><NEW_LINE>Wo wo = new Wo(bs, this.contentType(false, zipName), this.contentDisposition(false, zipName));<NEW_LINE>result.setData(wo);<NEW_LINE>}<NEW_LINE>return result;<NEW_LINE>}<NEW_LINE>} | ] bs = os.toByteArray(); |
1,315,395 | public boolean onOptionsItemSelected(final MenuItem item) {<NEW_LINE>if (MenuDoubleTabUtil.shouldIgnoreTap()) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>switch(item.getItemId()) {<NEW_LINE>case android.R.id.home:<NEW_LINE>deleteAccountAndReturnIfNecessary();<NEW_LINE>break;<NEW_LINE>case R.id.action_show_block_list:<NEW_LINE>final Intent showBlocklistIntent = new Intent(this, BlocklistActivity.class);<NEW_LINE>showBlocklistIntent.putExtra(EXTRA_ACCOUNT, mAccount.<MASK><NEW_LINE>startActivity(showBlocklistIntent);<NEW_LINE>break;<NEW_LINE>case R.id.action_server_info_show_more:<NEW_LINE>changeMoreTableVisibility(!item.isChecked());<NEW_LINE>break;<NEW_LINE>case R.id.action_share_barcode:<NEW_LINE>shareBarcode();<NEW_LINE>break;<NEW_LINE>case R.id.action_share_http:<NEW_LINE>shareLink(true);<NEW_LINE>break;<NEW_LINE>case R.id.action_share_uri:<NEW_LINE>shareLink(false);<NEW_LINE>break;<NEW_LINE>case R.id.action_change_password_on_server:<NEW_LINE>gotoChangePassword(null);<NEW_LINE>break;<NEW_LINE>case R.id.action_mam_prefs:<NEW_LINE>editMamPrefs();<NEW_LINE>break;<NEW_LINE>case R.id.action_renew_certificate:<NEW_LINE>renewCertificate();<NEW_LINE>break;<NEW_LINE>case R.id.action_change_presence:<NEW_LINE>changePresence();<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>return super.onOptionsItemSelected(item);<NEW_LINE>} | getJid().toEscapedString()); |
984,344 | /*<NEW_LINE>* No need to process SwitchKey TODO test and reason<NEW_LINE>*/<NEW_LINE>@Override<NEW_LINE>public DavaFlowSet processASTSwitchNode(ASTSwitchNode node, DavaFlowSet input) {<NEW_LINE>if (DEBUG) {<NEW_LINE>System.out.println("Processing switch node");<NEW_LINE>}<NEW_LINE>if (!isReachable(input)) {<NEW_LINE>// this sequence is not reachable hence simply return inset<NEW_LINE>return input;<NEW_LINE>}<NEW_LINE>// if reachable<NEW_LINE>List<Object> indexList = node.getIndexList();<NEW_LINE>Map<Object, List<Object>> index2BodyList = node.getIndex2BodyList();<NEW_LINE>DavaFlowSet initialIn = cloneFlowSet(input);<NEW_LINE>DavaFlowSet out = null;<NEW_LINE>DavaFlowSet defaultOut = null;<NEW_LINE>List<DavaFlowSet> toMergeBreaks = new ArrayList<DavaFlowSet>();<NEW_LINE>Iterator<Object> it = indexList.iterator();<NEW_LINE>while (it.hasNext()) {<NEW_LINE>// going through all the cases of the switch statement<NEW_LINE>Object currentIndex = it.next();<NEW_LINE>List body = index2BodyList.get(currentIndex);<NEW_LINE>if (body == null) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>// although the input is usually the merge of the out of previous<NEW_LINE>// but since we know this case is always reachable as switch is reachable<NEW_LINE>// there is no need to merge<NEW_LINE>out = process(body, cloneFlowSet(initialIn));<NEW_LINE>toMergeBreaks.add(cloneFlowSet(out));<NEW_LINE>if (currentIndex instanceof String) {<NEW_LINE>// this is the default<NEW_LINE>defaultOut = out;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// have to handle the case when no case matches. The input is the output<NEW_LINE>DavaFlowSet output = initialIn;<NEW_LINE>if (out != null) {<NEW_LINE>// just to make sure that there were some cases present<NEW_LINE>if (defaultOut != null) {<NEW_LINE>output = merge(defaultOut, out);<NEW_LINE>} else {<NEW_LINE>output = merge(initialIn, out);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// handle break<NEW_LINE>String label = getLabel(node);<NEW_LINE>// have to handleBreaks for all the different cases<NEW_LINE>List<DavaFlowSet> outList = new ArrayList<DavaFlowSet>();<NEW_LINE>// handling breakLists of each of the toMergeBreaks<NEW_LINE>for (DavaFlowSet tmb : toMergeBreaks) {<NEW_LINE>outList.add(handleBreak<MASK><NEW_LINE>}<NEW_LINE>// merge all outList elements. since these are the outputs with breaks handled<NEW_LINE>DavaFlowSet finalOut = output;<NEW_LINE>for (DavaFlowSet fo : outList) {<NEW_LINE>finalOut = merge(finalOut, fo);<NEW_LINE>}<NEW_LINE>return finalOut;<NEW_LINE>} | (label, tmb, node)); |
406,414 | final EngineDefaults executeDescribeEngineDefaultClusterParameters(DescribeEngineDefaultClusterParametersRequest describeEngineDefaultClusterParametersRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(describeEngineDefaultClusterParametersRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<DescribeEngineDefaultClusterParametersRequest> request = null;<NEW_LINE>Response<EngineDefaults> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new DescribeEngineDefaultClusterParametersRequestMarshaller().marshall(super.beforeMarshalling(describeEngineDefaultClusterParametersRequest));<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, "Neptune");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "DescribeEngineDefaultClusterParameters");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>StaxResponseHandler<EngineDefaults> responseHandler = new StaxResponseHandler<EngineDefaults>(new EngineDefaultsStaxUnmarshaller());<NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | awsRequestMetrics.endEvent(Field.RequestMarshallTime); |
1,374,282 | private Dimension calcPreferredSize(HtmlRendererImpl r) {<NEW_LINE>Insets ins = r.getInsets();<NEW_LINE>Dimension prefSize = new java.awt.Dimension(ins.left + ins.right, ins.top + ins.bottom);<NEW_LINE>String text = r.getText();<NEW_LINE>Graphics g = r.getGraphics();<NEW_LINE>Icon icon = r.getIcon();<NEW_LINE>Font font = font(r);<NEW_LINE>if (text != null) {<NEW_LINE>FontMetrics fm = g.getFontMetrics(font);<NEW_LINE>prefSize.height += (fm.getMaxAscent() + fm.getMaxDescent());<NEW_LINE>}<NEW_LINE>if (icon != null) {<NEW_LINE>if (r.isCentered()) {<NEW_LINE>prefSize.height += (icon.getIconHeight() + r.getIconTextGap());<NEW_LINE>prefSize.width += icon.getIconWidth();<NEW_LINE>} else {<NEW_LINE>prefSize.height = Math.max(icon.getIconHeight() + ins.top + ins.bottom, prefSize.height);<NEW_LINE>prefSize.width += (icon.getIconWidth() + r.getIconTextGap());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// Antialiasing affects the text metrics, so use it if needed when<NEW_LINE>// calculating preferred size or the result here will be narrower<NEW_LINE>// than the space actually needed<NEW_LINE>GraphicsUtils.configureDefaultRenderingHints(g);<NEW_LINE>int textwidth = textWidth(text, g, font, <MASK><NEW_LINE>if (r.isCentered()) {<NEW_LINE>prefSize.width = Math.max(prefSize.width, textwidth + ins.right + ins.left);<NEW_LINE>} else {<NEW_LINE>prefSize.width += (textwidth + r.getIndent());<NEW_LINE>}<NEW_LINE>if (FIXED_HEIGHT > 0) {<NEW_LINE>prefSize.height = FIXED_HEIGHT;<NEW_LINE>}<NEW_LINE>return prefSize;<NEW_LINE>} | r.isHtml()) + 4; |
548,954 | public RelRoot expandView(RelDataType rowType, String queryString, List<String> schemaPath, List<String> viewPath) {<NEW_LINE>SqlParser parser = <MASK><NEW_LINE>SqlNode sqlNode;<NEW_LINE>try {<NEW_LINE>sqlNode = parser.parseQuery();<NEW_LINE>} catch (SqlParseException e) {<NEW_LINE>throw new RuntimeException("parse failed", e);<NEW_LINE>}<NEW_LINE>final SqlConformance conformance = conformance();<NEW_LINE>final CalciteCatalogReader catalogReader = createCatalogReader().withSchemaPath(schemaPath);<NEW_LINE>final SqlValidator validator = new CalciteSqlValidator(operatorTable, catalogReader, typeFactory, conformance);<NEW_LINE>validator.setIdentifierExpansion(true);<NEW_LINE>final SqlNode validatedSqlNode = validator.validate(sqlNode);<NEW_LINE>final RexBuilder rexBuilder = createRexBuilder();<NEW_LINE>final RelOptCluster cluster = RelOptCluster.create(planner, rexBuilder);<NEW_LINE>final SqlToRelConverter.Config config = SqlToRelConverter.configBuilder().withConfig(sqlToRelConverterConfig).withTrimUnusedFields(false).withConvertTableAccess(false).build();<NEW_LINE>final SqlToRelConverter sqlToRelConverter = new SqlToRelConverter(new ViewExpanderImpl(), validator, catalogReader, cluster, convertletTable, config);<NEW_LINE>root = sqlToRelConverter.convertQuery(validatedSqlNode, true, false);<NEW_LINE>root = root.withRel(sqlToRelConverter.flattenTypes(root.rel, true));<NEW_LINE>root = root.withRel(RelDecorrelator.decorrelateQuery(root.rel));<NEW_LINE>return PlannerImpl.this.root;<NEW_LINE>} | SqlParser.create(queryString, parserConfig); |
1,443,321 | public SenderIdFilter unmarshall(JsonUnmarshallerContext context) throws Exception {<NEW_LINE>SenderIdFilter senderIdFilter = new SenderIdFilter();<NEW_LINE>int originalDepth = context.getCurrentDepth();<NEW_LINE>String currentParentElement = context.getCurrentParentElement();<NEW_LINE>int targetDepth = originalDepth + 1;<NEW_LINE>JsonToken token = context.getCurrentToken();<NEW_LINE>if (token == null)<NEW_LINE>token = context.nextToken();<NEW_LINE>if (token == VALUE_NULL) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>while (true) {<NEW_LINE>if (token == null)<NEW_LINE>break;<NEW_LINE>if (token == FIELD_NAME || token == START_OBJECT) {<NEW_LINE>if (context.testExpression("Name", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>senderIdFilter.setName(context.getUnmarshaller(String.<MASK><NEW_LINE>}<NEW_LINE>if (context.testExpression("Values", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>senderIdFilter.setValues(new ListUnmarshaller<String>(context.getUnmarshaller(String.class)).unmarshall(context));<NEW_LINE>}<NEW_LINE>} else if (token == END_ARRAY || token == END_OBJECT) {<NEW_LINE>if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {<NEW_LINE>if (context.getCurrentDepth() <= originalDepth)<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>token = context.nextToken();<NEW_LINE>}<NEW_LINE>return senderIdFilter;<NEW_LINE>} | class).unmarshall(context)); |
1,752,078 | static WebServer startServer(Routing routing) {<NEW_LINE>WebServer server = WebServer.create(routing);<NEW_LINE>long t = System.nanoTime();<NEW_LINE>CountDownLatch cdl = new CountDownLatch(1);<NEW_LINE>server.start().thenAccept(webServer -> {<NEW_LINE>long time = System.nanoTime() - t;<NEW_LINE>System.out.printf("Server started in %d ms ms%n", TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS));<NEW_LINE>System.out.printf("Started server on localhost:%d%n", webServer.port());<NEW_LINE>System.out.println();<NEW_LINE>System.out.println("Users:");<NEW_LINE>System.out.println("Jack/password in roles: user, admin");<NEW_LINE>System.out.println("Jill/password in roles: user");<NEW_LINE>System.out.println("John/password in no roles");<NEW_LINE>System.out.println();<NEW_LINE>System.out.println("***********************");<NEW_LINE>System.out.println("** Endpoints: **");<NEW_LINE>System.out.println("***********************");<NEW_LINE>System.out.println("No authentication:");<NEW_LINE>System.out.printf(" http://localhost:%1$d/public%n", webServer.port());<NEW_LINE>System.out.println("No roles required, authenticated:");<NEW_LINE>System.out.printf(" http://localhost:%1$d/noRoles%n", webServer.port());<NEW_LINE><MASK><NEW_LINE>System.out.printf(" http://localhost:%1$d/user%n", webServer.port());<NEW_LINE>System.out.println("Admin role required:");<NEW_LINE>System.out.printf(" http://localhost:%1$d/admin%n", webServer.port());<NEW_LINE>System.out.println("Always forbidden (uses role nobody is in), audited:");<NEW_LINE>System.out.printf(" http://localhost:%1$d/deny%n", webServer.port());<NEW_LINE>System.out.println("Admin role required, authenticated, authentication optional, audited (always forbidden - challenge is not " + "returned as authentication is optional):");<NEW_LINE>System.out.printf(" http://localhost:%1$d/noAuthn%n", webServer.port());<NEW_LINE>System.out.println();<NEW_LINE>cdl.countDown();<NEW_LINE>});<NEW_LINE>try {<NEW_LINE>cdl.await(START_TIMEOUT_SECONDS, TimeUnit.SECONDS);<NEW_LINE>} catch (InterruptedException e) {<NEW_LINE>throw new RuntimeException("Failed to start server within defined timeout: " + START_TIMEOUT_SECONDS + " seconds", e);<NEW_LINE>}<NEW_LINE>return server;<NEW_LINE>} | System.out.println("User role required:"); |
1,383,952 | private static void copySymbols(Project project, File outDir, ICanceled canceled) throws IOException, CompileExceptionError {<NEW_LINE>final boolean has_symbols = project.hasOption("with-symbols");<NEW_LINE>if (!has_symbols) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>File symbolsDir = new File(outDir, getProjectTitle(project) + ".apk.symbols");<NEW_LINE>symbolsDir.mkdirs();<NEW_LINE><MASK><NEW_LINE>final String extenderExeDir = getExtenderExeDir(project);<NEW_LINE>final List<Platform> architectures = getArchitectures(project);<NEW_LINE>final String variant = project.option("variant", Bob.VARIANT_RELEASE);<NEW_LINE>for (Platform architecture : architectures) {<NEW_LINE>List<File> bundleExe = Bob.getNativeExtensionEngineBinaries(architecture, extenderExeDir);<NEW_LINE>if (bundleExe == null) {<NEW_LINE>bundleExe = Bob.getDefaultDmengineFiles(architecture, variant);<NEW_LINE>}<NEW_LINE>File exe = bundleExe.get(0);<NEW_LINE>File symbolExe = new File(symbolsDir, FilenameUtils.concat("lib/" + platformToLibMap.get(architecture), "lib" + exeName + ".so"));<NEW_LINE>log("Copy debug symbols " + symbolExe);<NEW_LINE>BundleHelper.throwIfCanceled(canceled);<NEW_LINE>FileUtils.copyFile(exe, symbolExe);<NEW_LINE>}<NEW_LINE>BundleHelper.throwIfCanceled(canceled);<NEW_LINE>File proguardMapping = new File(FilenameUtils.concat(extenderExeDir, FilenameUtils.concat(architectures.get(0).getExtenderPair(), "mapping.txt")));<NEW_LINE>if (proguardMapping.exists()) {<NEW_LINE>File symbolMapping = new File(symbolsDir, proguardMapping.getName());<NEW_LINE>FileUtils.copyFile(proguardMapping, symbolMapping);<NEW_LINE>}<NEW_LINE>} | final String exeName = getBinaryNameFromProject(project); |
719,885 | public void register(Iterable<Row<?>> rows, boolean overwrite) {<NEW_LINE>registeredRows.getAndUpdate(oldRows -> {<NEW_LINE>// for some reason the compiler needs type assistance by creating this intermediate variable.<NEW_LINE>Stream<Meter.Id> idStream = StreamSupport.stream(rows.spliterator(), false).map(row -> {<NEW_LINE>Row r = row;<NEW_LINE>Meter.Id rowId = <MASK><NEW_LINE>boolean previouslyDefined = oldRows.contains(rowId);<NEW_LINE>if (overwrite && previouslyDefined) {<NEW_LINE>registry.removeByPreFilterId(rowId);<NEW_LINE>}<NEW_LINE>if (overwrite || !previouslyDefined) {<NEW_LINE>registry.gauge(rowId, row.obj, new StrongReferenceGaugeFunction<>(r.obj, r.valueFunction));<NEW_LINE>}<NEW_LINE>return rowId;<NEW_LINE>});<NEW_LINE>Set<Meter.Id> newRows = idStream.collect(toSet());<NEW_LINE>for (Meter.Id oldRow : oldRows) {<NEW_LINE>if (!newRows.contains(oldRow))<NEW_LINE>registry.removeByPreFilterId(oldRow);<NEW_LINE>}<NEW_LINE>return newRows;<NEW_LINE>});<NEW_LINE>} | commonId.withTags(row.uniqueTags); |
1,562,050 | public void updateVisuals() {<NEW_LINE>new Thread(() -> {<NEW_LINE>double max;<NEW_LINE>switch(whichDeriv) {<NEW_LINE>case 0 -><NEW_LINE>VisualizeImageData.colorizeGradient(derivX, derivY, -1, renderedImage);<NEW_LINE>case 1 -><NEW_LINE>{<NEW_LINE><MASK><NEW_LINE>VisualizeImageData.colorizeSign(derivX, renderedImage, max);<NEW_LINE>}<NEW_LINE>case 2 -><NEW_LINE>{<NEW_LINE>max = GImageStatistics.maxAbs(derivY);<NEW_LINE>VisualizeImageData.colorizeSign(derivY, renderedImage, max);<NEW_LINE>}<NEW_LINE>case 3 -><NEW_LINE>{<NEW_LINE>max = GImageStatistics.maxAbs(derivXX);<NEW_LINE>VisualizeImageData.colorizeSign(derivXX, renderedImage, max);<NEW_LINE>}<NEW_LINE>case 4 -><NEW_LINE>{<NEW_LINE>max = GImageStatistics.maxAbs(derivYY);<NEW_LINE>VisualizeImageData.colorizeSign(derivYY, renderedImage, max);<NEW_LINE>}<NEW_LINE>case 5 -><NEW_LINE>{<NEW_LINE>max = GImageStatistics.maxAbs(derivXY);<NEW_LINE>VisualizeImageData.colorizeSign(derivXY, renderedImage, max);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>SwingUtilities.invokeLater(() -> {<NEW_LINE>gui.setImageRepaint(renderedImage);<NEW_LINE>});<NEW_LINE>}).start();<NEW_LINE>} | max = GImageStatistics.maxAbs(derivX); |
1,770,475 | private Optional<LiteSession> initSession(String modelPath, MSConfig msConfig, boolean isDynamicInferModel) {<NEW_LINE>if (modelPath == null) {<NEW_LINE>logger.severe(Common.addTag("modelPath cannot be empty"));<NEW_LINE>return Optional.empty();<NEW_LINE>}<NEW_LINE>// only lite session support dynamic shape<NEW_LINE>if (isDynamicInferModel) {<NEW_LINE>Model model = new Model();<NEW_LINE>boolean isSuccess = model.loadModel(modelPath);<NEW_LINE>if (!isSuccess) {<NEW_LINE>logger.severe(Common.addTag("load model failed:" + modelPath + " ,please check model is valid or disk" + "space is enough,please check lite log for detail."));<NEW_LINE>return Optional.empty();<NEW_LINE>}<NEW_LINE>trainSession = LiteSession.createSession(msConfig);<NEW_LINE>if (trainSession == null) {<NEW_LINE>logger.severe(Common.addTag("init session failed.please check lite log for detail."));<NEW_LINE>msConfig.free();<NEW_LINE>model.free();<NEW_LINE>return Optional.empty();<NEW_LINE>}<NEW_LINE>msConfig.free();<NEW_LINE>isSuccess = trainSession.compileGraph(model);<NEW_LINE>if (!isSuccess) {<NEW_LINE>logger.severe(Common.addTag("compile graph failed,please check lite log for detail."));<NEW_LINE>model.free();<NEW_LINE>trainSession.free();<NEW_LINE>return Optional.empty();<NEW_LINE>}<NEW_LINE>model.free();<NEW_LINE>return Optional.of(trainSession);<NEW_LINE>} else {<NEW_LINE>trainSession = TrainSession.<MASK><NEW_LINE>if (trainSession == null) {<NEW_LINE>logger.severe(Common.addTag("init session failed,please check model :" + modelPath + " is valid or " + "disk space is enough.please check lite log for detail."));<NEW_LINE>return Optional.empty();<NEW_LINE>}<NEW_LINE>return Optional.of(trainSession);<NEW_LINE>}<NEW_LINE>} | createTrainSession(modelPath, msConfig, false); |
1,769,922 | public boolean write_specctra_session_file(BoardFrame p_board_frame) {<NEW_LINE>final java.util.ResourceBundle resources = java.util.ResourceBundle.getBundle("app.freerouting.gui.BoardMenuFile", p_board_frame.get_locale());<NEW_LINE>String design_file_name = this.get_name();<NEW_LINE>String[] file_name_parts = design_file_name.split("\\.", 2);<NEW_LINE>String design_name = file_name_parts[0];<NEW_LINE>{<NEW_LINE>String output_file_name = design_name + ".ses";<NEW_LINE>FRLogger.info("Saving '" + output_file_name + "'...");<NEW_LINE>java.io.File curr_output_file = new java.io.File(get_parent(), output_file_name);<NEW_LINE>java.io.OutputStream output_stream;<NEW_LINE>try {<NEW_LINE>output_stream = new java.io.FileOutputStream(curr_output_file);<NEW_LINE>} catch (Exception e) {<NEW_LINE>output_stream = null;<NEW_LINE>}<NEW_LINE>if (p_board_frame.board_panel.board_handling.export_specctra_session_file(design_file_name, output_stream)) {<NEW_LINE>p_board_frame.screen_messages.set_status_message(resources.getString("message_11") + " " + output_file_name + " " + resources.getString("message_12"));<NEW_LINE>} else {<NEW_LINE>p_board_frame.screen_messages.set_status_message(resources.getString("message_13") + " " + output_file_name + " " <MASK><NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (WindowMessage.confirm(resources.getString("confirm"))) {<NEW_LINE>return write_rules_file(design_name, p_board_frame.board_panel.board_handling);<NEW_LINE>}<NEW_LINE>return true;<NEW_LINE>} | + resources.getString("message_7")); |
1,489,839 | public void initRedirect() {<NEW_LINE>Debug.log(3, "EditorConsolePane: starting redirection to message area");<NEW_LINE>int npipes = 2;<NEW_LINE>// npipes * Runner.getRunners().size() + npipes;<NEW_LINE>NUM_PIPES = npipes;<NEW_LINE>pin = new PipedInputStream[NUM_PIPES];<NEW_LINE>reader = new Thread[NUM_PIPES];<NEW_LINE>for (int i = 0; i < NUM_PIPES; i++) {<NEW_LINE>pin[i] = new PipedInputStream();<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>// redirect System IO to IDE message area<NEW_LINE>PipedOutputStream oout = new PipedOutputStream(pin[0]);<NEW_LINE>PrintStream ops = new PrintStream(oout, true);<NEW_LINE>System.setOut(ops);<NEW_LINE>reader[0] = new Thread(EditorConsolePane.this);<NEW_LINE>reader[0].setDaemon(true);<NEW_LINE>reader[0].start();<NEW_LINE>PipedOutputStream eout = new PipedOutputStream(pin[1]);<NEW_LINE>PrintStream eps = new PrintStream(eout, true);<NEW_LINE>System.setErr(eps);<NEW_LINE>reader[1] = new Thread(EditorConsolePane.this);<NEW_LINE>reader<MASK><NEW_LINE>reader[1].start();<NEW_LINE>} catch (IOException e1) {<NEW_LINE>Debug.log(-1, "Redirecting System IO failed", e1.getMessage());<NEW_LINE>}<NEW_LINE>} | [1].setDaemon(true); |
1,539,037 | protected JComponent createCenterPanel() {<NEW_LINE>Splitter splitter = new Splitter(false, (float) 0.6);<NEW_LINE>JPanel result = new JPanel(new BorderLayout());<NEW_LINE>if (myTree == null) {<NEW_LINE>myTree = createTree();<NEW_LINE>} else {<NEW_LINE>final CheckedTreeNode root = (CheckedTreeNode) myTree.getModel().getRoot();<NEW_LINE>myRoot = (MethodNodeBase) root.getFirstChild();<NEW_LINE>}<NEW_LINE>myTreeSelectionListener = new TreeSelectionListener() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void valueChanged(TreeSelectionEvent e) {<NEW_LINE>final TreePath path = e.getPath();<NEW_LINE>if (path != null) {<NEW_LINE>final MethodNodeBase<M> node = (MethodNodeBase) path.getLastPathComponent();<NEW_LINE>myAlarm.cancelAllRequests();<NEW_LINE>myAlarm.addRequest(new Runnable() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void run() {<NEW_LINE>updateEditorTexts(node);<NEW_LINE>}<NEW_LINE>}, 300);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>};<NEW_LINE>myTree.getSelectionModel().addTreeSelectionListener(myTreeSelectionListener);<NEW_LINE>JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTree);<NEW_LINE>splitter.setFirstComponent(scrollPane);<NEW_LINE>final JComponent callSitesViewer = createCallSitesViewer();<NEW_LINE>TreePath selectionPath = myTree.getSelectionPath();<NEW_LINE>if (selectionPath == null) {<NEW_LINE>selectionPath = new TreePath(myRoot.getPath());<NEW_LINE>myTree.getSelectionModel().addSelectionPath(selectionPath);<NEW_LINE>}<NEW_LINE>final MethodNodeBase<M> node = <MASK><NEW_LINE>updateEditorTexts(node);<NEW_LINE>splitter.setSecondComponent(callSitesViewer);<NEW_LINE>result.add(splitter);<NEW_LINE>return result;<NEW_LINE>} | (MethodNodeBase) selectionPath.getLastPathComponent(); |
455,169 | private ThrustCurveMotor selectMotor(ThrustCurveMotorSet set) {<NEW_LINE>if (set.getMotorCount() == 0) {<NEW_LINE>throw new BugException("Attempting to select motor from empty ThrustCurveMotorSet: " + set);<NEW_LINE>}<NEW_LINE>if (set.getMotorCount() == 1) {<NEW_LINE>return set.getMotors().get(0);<NEW_LINE>}<NEW_LINE>// Find which motor has been used the most recently<NEW_LINE>List<ThrustCurveMotor> list = set.getMotors();<NEW_LINE>Preferences prefs = ((SwingPreferences) Application.getPreferences()).getNode(net.sf.openrocket.startup.Preferences.PREFERRED_THRUST_CURVE_MOTOR_NODE);<NEW_LINE>for (ThrustCurveMotor m : list) {<NEW_LINE>String digest = m.getDigest();<NEW_LINE>if (prefs.getBoolean(digest, false)) {<NEW_LINE>return m;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// No motor has been used<NEW_LINE><MASK><NEW_LINE>return list.get(0);<NEW_LINE>} | Collections.sort(list, MOTOR_COMPARATOR); |
1,243,228 | public void onClick(View v) {<NEW_LINE>switch(v.getId()) {<NEW_LINE>case R.id.tvInnerDemo:<NEW_LINE>AssetsChooserActivity.startActivity(this, "inner_demo");<NEW_LINE>break;<NEW_LINE>case R.id.tvCourse:<NEW_LINE>WebActivity.startActivity(this, URL_COURSE);<NEW_LINE>break;<NEW_LINE>case R.id.tvInstance:<NEW_LINE>WebActivity.startActivity(this, URL_INSTANCE);<NEW_LINE>break;<NEW_LINE>case R.id.tvConsult:<NEW_LINE>WebActivity.startActivity(this, URL_CONSULT);<NEW_LINE>break;<NEW_LINE>case R.id.tvAbout:<NEW_LINE>WebActivity.startActivity(this, URL_ABOUT);<NEW_LINE>break;<NEW_LINE>case R.id.tvDevDebug:<NEW_LINE>HotReloadHelper.setConnectListener(this);<NEW_LINE>startTeach(true);<NEW_LINE>break;<NEW_LINE>case R.id.tvDemo:<NEW_LINE>Intent intent = new Intent(this, LuaViewActivity.class);<NEW_LINE>String path = Globals.isIs32bit() ? Constants.ASSETS_PREFIX <MASK><NEW_LINE>InitData initData = MLSBundleUtils.createInitData(path);<NEW_LINE>intent.putExtras(MLSBundleUtils.createBundle(initData));<NEW_LINE>startActivity(intent);<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>} | + "gallery/meilishuo.lua" : Constants.ASSETS_PREFIX + "gallery_x64/meilishuo.lua"; |
252,914 | private Object[] readObjectArrayForListModel(DataInputStream in, Resources res) throws IOException {<NEW_LINE>Object[] elements = new Object[in.readInt()];<NEW_LINE>int elen = elements.length;<NEW_LINE>for (int iter = 0; iter < elen; iter++) {<NEW_LINE>switch(in.readByte()) {<NEW_LINE>case // String<NEW_LINE>1:<NEW_LINE>elements[iter] = in.readUTF();<NEW_LINE>break;<NEW_LINE>case // hashtable of Strings<NEW_LINE>2:<NEW_LINE>int hashSize = in.readInt();<NEW_LINE>Hashtable val = new Hashtable();<NEW_LINE>elements[iter] = val;<NEW_LINE>for (int i = 0; i < hashSize; i++) {<NEW_LINE>int type = in.readInt();<NEW_LINE>if (type == 1) {<NEW_LINE>// String<NEW_LINE>String key = in.readUTF();<NEW_LINE>Object value = in.readUTF();<NEW_LINE>if (key.equals("$navigation")) {<NEW_LINE>Command cmd = createCommandImpl((String) value, null, -1, (String) value, false, "");<NEW_LINE>cmd.putClientProperty(COMMAND_ACTION, (String) value);<NEW_LINE>value = cmd;<NEW_LINE>}<NEW_LINE><MASK><NEW_LINE>} else {<NEW_LINE>val.put(in.readUTF(), res.getImage(in.readUTF()));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return elements;<NEW_LINE>} | val.put(key, value); |
1,545,800 | public TopologyAPI.InputStream.Builder buildStream(String componentName, String streamId) {<NEW_LINE>TopologyAPI.InputStream.Builder bldr <MASK><NEW_LINE>bldr.setStream(TopologyAPI.StreamId.newBuilder().setId(streamId).setComponentName(componentName));<NEW_LINE>bldr.setGtype(TopologyAPI.Grouping.FIELDS);<NEW_LINE>TopologyAPI.StreamSchema.Builder gfbldr = TopologyAPI.StreamSchema.newBuilder();<NEW_LINE>for (int i = 0; i < fields.size(); ++i) {<NEW_LINE>TopologyAPI.StreamSchema.KeyType.Builder ktBldr = TopologyAPI.StreamSchema.KeyType.newBuilder();<NEW_LINE>ktBldr.setKey(fields.get(i));<NEW_LINE>ktBldr.setType(TopologyAPI.Type.OBJECT);<NEW_LINE>gfbldr.addKeys(ktBldr);<NEW_LINE>}<NEW_LINE>bldr.setGroupingFields(gfbldr);<NEW_LINE>return bldr;<NEW_LINE>} | = TopologyAPI.InputStream.newBuilder(); |
1,374,835 | private void updateViews() {<NEW_LINE>if (!mDebugging) {<NEW_LINE>mViewDebug.setVisibility(View.GONE);<NEW_LINE>mLvDebug.setVisibility(View.GONE);<NEW_LINE>if (mIsLoading && !mSharedPrefs.getBoolean("pref_disable_splash", false)) {<NEW_LINE><MASK><NEW_LINE>mImageLoading.setVisibility(View.VISIBLE);<NEW_LINE>} else {<NEW_LINE>mIitcWebView.setVisibility(View.VISIBLE);<NEW_LINE>mImageLoading.setVisibility(View.GONE);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>// if the debug container is invisible (and we are about to show it), select the text box<NEW_LINE>final boolean select = mViewDebug.getVisibility() != View.VISIBLE;<NEW_LINE>// never show splash screen while debugging<NEW_LINE>mImageLoading.setVisibility(View.GONE);<NEW_LINE>mViewDebug.setVisibility(View.VISIBLE);<NEW_LINE>if (select) {<NEW_LINE>mEditCommand.requestFocus();<NEW_LINE>mEditCommand.selectAll();<NEW_LINE>}<NEW_LINE>if (mShowMapInDebug) {<NEW_LINE>mBtnToggleMap.setImageResource(R.drawable.ic_action_view_as_list);<NEW_LINE>mIitcWebView.setVisibility(View.VISIBLE);<NEW_LINE>mLvDebug.setVisibility(View.GONE);<NEW_LINE>} else {<NEW_LINE>mBtnToggleMap.setImageResource(R.drawable.ic_action_map);<NEW_LINE>mIitcWebView.setVisibility(View.GONE);<NEW_LINE>mLvDebug.setVisibility(View.VISIBLE);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | mIitcWebView.setVisibility(View.GONE); |
432,407 | protected void okPressed() {<NEW_LINE>// Set props<NEW_LINE>driver.setName(driverNameText.getText());<NEW_LINE>driver.setDescription(CommonUtils.notEmpty(driverDescText.getText()));<NEW_LINE>driver.setDriverClassName(driverClassText.getText());<NEW_LINE>driver.setSampleURL(driverURLText.getText());<NEW_LINE>driver.setDriverDefaultPort(driverPortText.getText());<NEW_LINE>driver.setDriverDefaultDatabase(driverDatabaseText.getText());<NEW_LINE>driver.setDriverDefaultUser(driverUserText.getText());<NEW_LINE>driver.setEmbedded(embeddedDriverCheck.getSelection());<NEW_LINE>driver.setAnonymousAccess(anonymousDriverCheck.getSelection());<NEW_LINE>driver.setAllowsEmptyPassword(allowsEmptyPasswordCheck.getSelection());<NEW_LINE>driver.setInstantiable<MASK><NEW_LINE>// driver.setAnonymousAccess(anonymousCheck.getSelection());<NEW_LINE>driver.setModified(true);<NEW_LINE>driver.setDriverParameters(driverPropertySource.getPropertiesWithDefaults());<NEW_LINE>driver.setConnectionProperties(connectionPropertySource.getPropertyValues());<NEW_LINE>// Store client homes<NEW_LINE>if (clientHomesPanel != null) {<NEW_LINE>driver.setNativeClientLocations(clientHomesPanel.getLocalLocations());<NEW_LINE>}<NEW_LINE>DriverDescriptor oldDriver = provider.getDriverByName(driver.getCategory(), driver.getName());<NEW_LINE>if (oldDriver != null && oldDriver != driver && !oldDriver.isDisabled() && oldDriver.getReplacedBy() == null) {<NEW_LINE>UIUtils.showMessageBox(getShell(), UIConnectionMessages.dialog_edit_driver_dialog_save_exists_title, NLS.bind(UIConnectionMessages.dialog_edit_driver_dialog_save_exists_message, driver.getName()), SWT.ICON_ERROR);<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>// Finish<NEW_LINE>if (provider.getDriver(driver.getId()) == null) {<NEW_LINE>provider.addDriver(driver);<NEW_LINE>}<NEW_LINE>provider.getRegistry().saveDrivers();<NEW_LINE>super.okPressed();<NEW_LINE>} | (!nonInstantiableCheck.getSelection()); |
907,843 | public boolean update(BookmarkBase bookmark) {<NEW_LINE>// start a transaction<NEW_LINE>SQLiteDatabase db = getWritableDatabase();<NEW_LINE>db.beginTransaction();<NEW_LINE>// bookmark settings<NEW_LINE>ContentValues values = new ContentValues();<NEW_LINE>values.put(BookmarkDB.<MASK><NEW_LINE>values.put(BookmarkDB.DB_KEY_BOOKMARK_USERNAME, bookmark.getUsername());<NEW_LINE>values.put(BookmarkDB.DB_KEY_BOOKMARK_PASSWORD, bookmark.getPassword());<NEW_LINE>values.put(BookmarkDB.DB_KEY_BOOKMARK_DOMAIN, bookmark.getDomain());<NEW_LINE>// update screen and performance settings settings<NEW_LINE>updateScreenSettings(db, bookmark);<NEW_LINE>updatePerformanceFlags(db, bookmark);<NEW_LINE>// advanced settings<NEW_LINE>values.put(BookmarkDB.DB_KEY_BOOKMARK_3G_ENABLE, bookmark.getAdvancedSettings().getEnable3GSettings());<NEW_LINE>// update 3G screen and 3G performance settings settings<NEW_LINE>updateScreenSettings3G(db, bookmark);<NEW_LINE>updatePerformanceFlags3G(db, bookmark);<NEW_LINE>values.put(BookmarkDB.DB_KEY_BOOKMARK_REDIRECT_SDCARD, bookmark.getAdvancedSettings().getRedirectSDCard());<NEW_LINE>values.put(BookmarkDB.DB_KEY_BOOKMARK_REDIRECT_SOUND, bookmark.getAdvancedSettings().getRedirectSound());<NEW_LINE>values.put(BookmarkDB.DB_KEY_BOOKMARK_REDIRECT_MICROPHONE, bookmark.getAdvancedSettings().getRedirectMicrophone());<NEW_LINE>values.put(BookmarkDB.DB_KEY_BOOKMARK_SECURITY, bookmark.getAdvancedSettings().getSecurity());<NEW_LINE>values.put(BookmarkDB.DB_KEY_BOOKMARK_CONSOLE_MODE, bookmark.getAdvancedSettings().getConsoleMode());<NEW_LINE>values.put(BookmarkDB.DB_KEY_BOOKMARK_REMOTE_PROGRAM, bookmark.getAdvancedSettings().getRemoteProgram());<NEW_LINE>values.put(BookmarkDB.DB_KEY_BOOKMARK_WORK_DIR, bookmark.getAdvancedSettings().getWorkDir());<NEW_LINE>values.put(BookmarkDB.DB_KEY_BOOKMARK_ASYNC_CHANNEL, bookmark.getDebugSettings().getAsyncChannel());<NEW_LINE>values.put(BookmarkDB.DB_KEY_BOOKMARK_ASYNC_UPDATE, bookmark.getDebugSettings().getAsyncUpdate());<NEW_LINE>values.put(BookmarkDB.DB_KEY_BOOKMARK_DEBUG_LEVEL, bookmark.getDebugSettings().getDebugLevel());<NEW_LINE>addBookmarkSpecificColumns(bookmark, values);<NEW_LINE>// update bookmark<NEW_LINE>boolean res = (db.update(getBookmarkTableName(), values, BookmarkDB.ID + " = " + bookmark.getId(), null) == 1);<NEW_LINE>// commit<NEW_LINE>db.setTransactionSuccessful();<NEW_LINE>db.endTransaction();<NEW_LINE>return res;<NEW_LINE>} | DB_KEY_BOOKMARK_LABEL, bookmark.getLabel()); |
513,420 | public void onStartup(Set<Class<?>> set, ServletContext ctx) throws ServletException {<NEW_LINE>MetricsServiceConfiguration configuration = Globals.getDefaultBaseServiceLocator().getService(MetricsServiceConfiguration.class);<NEW_LINE>if (!"".equals(ctx.getContextPath())) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>// Check if there is already a servlet for metrics<NEW_LINE>Map<String, ? extends ServletRegistration> registrations = ctx.getServletRegistrations();<NEW_LINE>for (ServletRegistration reg : registrations.values()) {<NEW_LINE>if (reg.getClass().equals(MetricsResource.class)) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>String virtualServers = configuration.getVirtualServers();<NEW_LINE>if (!isEmpty(virtualServers) && !asList(virtualServers.split(",")).contains(ctx.getVirtualServerName())) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>// Register a servlet with url patterns of metrics handlers<NEW_LINE>ServletRegistration.Dynamic reg = ctx.<MASK><NEW_LINE>reg.addMapping("/" + configuration.getEndpoint() + "/*");<NEW_LINE>if (Boolean.parseBoolean(configuration.getSecurityEnabled())) {<NEW_LINE>String[] roles = configuration.getRoles().split(",");<NEW_LINE>reg.setServletSecurity(new ServletSecurityElement(new HttpConstraintElement(CONFIDENTIAL, roles)));<NEW_LINE>ctx.declareRoles(roles);<NEW_LINE>if (Boolean.getBoolean(CREATE_INSECURE_ENDPOINT_TEST)) {<NEW_LINE>ServletRegistration.Dynamic insecureReg = ctx.addServlet("microprofile-metrics-resource-insecure", MetricsResource.class);<NEW_LINE>insecureReg.addMapping("/" + configuration.getEndpoint() + "-insecure/*");<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | addServlet("microprofile-metrics-resource", MetricsResource.class); |
508,618 | public int readCodedBlockFlagLuma64(MDecoder decoder, int blkX, int blkY, int comp, MBType left, MBType top, boolean leftAvailable, boolean topAvailable, int leftCBPLuma, int topCBPLuma, int curCBPLuma, MBType cur, boolean is8x8Left, boolean is8x8Top) {<NEW_LINE>int blkOffLeft = blkX & 3, blkOffTop = blkY & 3;<NEW_LINE>int tLeft;<NEW_LINE>if (blkOffLeft == 0)<NEW_LINE>tLeft = condTerm(cur, leftAvailable, left, left != null && left != I_PCM && is8x8Left && cbp(leftCBPLuma, 3, blkOffTop), codedBlkLeft[comp][blkOffTop]);<NEW_LINE>else<NEW_LINE>tLeft = condTerm(cur, true, cur, cbp(curCBPLuma, blkOffLeft - 1, blkOffTop), codedBlkLeft[comp][blkOffTop]);<NEW_LINE>int tTop;<NEW_LINE>if (blkOffTop == 0)<NEW_LINE>tTop = condTerm(cur, topAvailable, top, top != null && top != I_PCM && is8x8Top && cbp(topCBPLuma, blkOffLeft, 3), codedBlkTop[comp][blkX]);<NEW_LINE>else<NEW_LINE>tTop = condTerm(cur, true, cur, cbp(curCBPLuma, blkOffLeft, blkOffTop - 1), codedBlkTop[comp][blkX]);<NEW_LINE>int decoded = decoder.decodeBin(BlockType.LUMA_64.<MASK><NEW_LINE>codedBlkLeft[comp][blkOffTop] = decoded;<NEW_LINE>codedBlkTop[comp][blkX] = decoded;<NEW_LINE>return decoded;<NEW_LINE>} | codedBlockCtxOff + tLeft + 2 * tTop); |
571,538 | private boolean initNetwork(List<String> options, List<String> parameters) {<NEW_LINE>if (options.contains("-setname")) {<NEW_LINE>if (!isValidArgument(options, parameters, 1, 1, 1, Command.INIT_NETWORK)) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>_currContainerName = _workHelper.initNetwork(parameters.get(0), null);<NEW_LINE>} else {<NEW_LINE>if (!isValidArgument(options, parameters, 0, 0, 1, Command.INIT_NETWORK)) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>String containerPrefix = parameters.isEmpty() ? DEFAULT_NETWORK_PREFIX : parameters.get(0);<NEW_LINE>_currContainerName = <MASK><NEW_LINE>}<NEW_LINE>if (_currContainerName == null) {<NEW_LINE>_logger.errorf("Could not init network\n");<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>_logger.output("Active network is set");<NEW_LINE>_logger.infof(" to %s\n", _currContainerName);<NEW_LINE>_logger.output("\n");<NEW_LINE>return true;<NEW_LINE>} | _workHelper.initNetwork(null, containerPrefix); |
136,546 | public byte[] decrypt(final byte[] ciphertext, final byte[] contextInfo) throws GeneralSecurityException {<NEW_LINE>int modSizeInBytes = RsaKem.bigIntSizeInBytes(recipientPrivateKey.getModulus());<NEW_LINE>if (ciphertext.length < modSizeInBytes) {<NEW_LINE>throw new GeneralSecurityException(String.format("Ciphertext must be of at least size %d bytes, but got %d"<MASK><NEW_LINE>}<NEW_LINE>// Decrypt the token to obtain the raw shared secret.<NEW_LINE>ByteBuffer cipherBuffer = ByteBuffer.wrap(ciphertext);<NEW_LINE>byte[] token = new byte[modSizeInBytes];<NEW_LINE>cipherBuffer.get(token);<NEW_LINE>Cipher rsaCipher = Cipher.getInstance("RSA/ECB/NoPadding");<NEW_LINE>rsaCipher.init(Cipher.DECRYPT_MODE, recipientPrivateKey);<NEW_LINE>byte[] sharedSecret = rsaCipher.doFinal(token);<NEW_LINE>// KDF: derive a DEM key from the shared secret, salt, and contextInfo.<NEW_LINE>byte[] demKey = Hkdf.computeHkdf(hkdfHmacAlgo, sharedSecret, hkdfSalt, contextInfo, aeadFactory.getKeySizeInBytes());<NEW_LINE>// DEM: decrypt the payload.<NEW_LINE>Aead aead = aeadFactory.createAead(demKey);<NEW_LINE>byte[] demPayload = new byte[cipherBuffer.remaining()];<NEW_LINE>cipherBuffer.get(demPayload);<NEW_LINE>return aead.decrypt(demPayload, RsaKem.EMPTY_AAD);<NEW_LINE>} | , modSizeInBytes, ciphertext.length)); |
1,436,089 | final SetUserSettingsResult executeSetUserSettings(SetUserSettingsRequest setUserSettingsRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(setUserSettingsRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<SetUserSettingsRequest> request = null;<NEW_LINE>Response<SetUserSettingsResult> response = null;<NEW_LINE>try {<NEW_LINE><MASK><NEW_LINE>try {<NEW_LINE>request = new SetUserSettingsRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(setUserSettingsRequest));<NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);<NEW_LINE>request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Cognito Identity Provider");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "SetUserSettings");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<SetUserSettingsResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new SetUserSettingsResultJsonUnmarshaller());<NEW_LINE>response = anonymousInvoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | awsRequestMetrics.startEvent(Field.RequestMarshallTime); |
1,825,618 | // ========== static ==========<NEW_LINE>public static void main(String... args) throws Exception {<NEW_LINE>if (ArrayUtils.getLength(args) < 2) {<NEW_LINE>// LOGGER.warn("Expected 2 argument: [0]-server, [1]-<path to config yaml file>");<NEW_LINE>String foundConf = null;<NEW_LINE>for (String p : DEFAULT_CONF_LOCATIONS) {<NEW_LINE>File confLocation = new File(p).getAbsoluteFile();<NEW_LINE>if (confLocation.exists()) {<NEW_LINE>foundConf = confLocation.getAbsolutePath();<NEW_LINE>LOGGER.info("Found conf path: {}", foundConf);<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (foundConf != null) {<NEW_LINE>LOGGER.warn("Running with default arguments: \"server\" \"{}\"", foundConf);<NEW_LINE>args = new String[] { "server", foundConf };<NEW_LINE>} else {<NEW_LINE>throw new RuntimeException("No explicit config provided and cannot find in one of the default locations: " + Arrays.toString(DEFAULT_CONF_LOCATIONS));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>LOGGER.info("Configuration file: {}", new File(args[1]).getAbsolutePath());<NEW_LINE>new <MASK><NEW_LINE>} | GrobidServiceApplication().run(args); |
254,879 | private static void put(final RheaKVStore rheaKVStore) {<NEW_LINE>final CompletableFuture<Boolean> r1 = rheaKVStore.put("compareAndPut", writeUtf8("compareAndPutExpect"));<NEW_LINE>if (FutureHelper.get(r1)) {<NEW_LINE>LOG.info("Async put compareAndPut {} success.", readUtf8(rheaKVStore.bGet("compareAndPut")));<NEW_LINE>}<NEW_LINE>final CompletableFuture<Boolean> f1 = rheaKVStore.compareAndPut(writeUtf8("compareAndPut"), writeUtf8("compareAndPutExpect"), writeUtf8("compareAndPutUpdate"));<NEW_LINE>if (FutureHelper.get(f1)) {<NEW_LINE>LOG.info("Compare compareAndPutExpect and set {} success.", readUtf8(rheaKVStore.bGet("compareAndPut")));<NEW_LINE>}<NEW_LINE>final CompletableFuture<Boolean> f2 = rheaKVStore.compareAndPut("compareAndPut", writeUtf8(<MASK><NEW_LINE>if (FutureHelper.get(f2)) {<NEW_LINE>LOG.info("Compare compareAndPutUpdate and set {} success.", readUtf8(rheaKVStore.bGet("compareAndPut")));<NEW_LINE>}<NEW_LINE>final Boolean b1 = rheaKVStore.bCompareAndPut(writeUtf8("compareAndPut1"), writeUtf8("compareAndPutUpdate2"), writeUtf8("compareAndPutUpdate3"));<NEW_LINE>if (b1) {<NEW_LINE>LOG.info("Compare compareAndPutUpdate2 and set {} success.", readUtf8(rheaKVStore.bGet("compareAndPut")));<NEW_LINE>}<NEW_LINE>final Boolean b2 = rheaKVStore.bCompareAndPut(writeUtf8("compareAndPut1"), writeUtf8("compareAndPutUpdate3"), writeUtf8("compareAndPutUpdate4"));<NEW_LINE>if (b2) {<NEW_LINE>LOG.info("Compare compareAndPutUpdate3 and set {} success.", readUtf8(rheaKVStore.bGet("compareAndPut")));<NEW_LINE>}<NEW_LINE>} | "compareAndPutUpdate"), writeUtf8("compareAndPutUpdate2")); |
1,520,886 | public DynamicInvokeResult tryInvokeMethod(String name, Object... arguments) {<NEW_LINE>DynamicInvokeResult result = super.tryInvokeMethod(name, arguments);<NEW_LINE>if (result.isFound()) {<NEW_LINE>return result;<NEW_LINE>}<NEW_LINE>DynamicInvokeResult propertyResult = tryGetProperty(name);<NEW_LINE>if (propertyResult.isFound()) {<NEW_LINE>Object property = propertyResult.getValue();<NEW_LINE>if (property instanceof Closure) {<NEW_LINE>Closure closure = (Closure) property;<NEW_LINE><MASK><NEW_LINE>BeanDynamicObject dynamicObject = new BeanDynamicObject(closure);<NEW_LINE>result = dynamicObject.tryInvokeMethod("doCall", arguments);<NEW_LINE>if (!result.isFound() && !(closure instanceof GeneratedClosure)) {<NEW_LINE>return DynamicInvokeResult.found(closure.call(arguments));<NEW_LINE>}<NEW_LINE>return result;<NEW_LINE>}<NEW_LINE>if (property instanceof NamedDomainObjectContainer && arguments.length == 1 && arguments[0] instanceof Closure) {<NEW_LINE>((NamedDomainObjectContainer) property).configure((Closure) arguments[0]);<NEW_LINE>return DynamicInvokeResult.found();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return DynamicInvokeResult.notFound();<NEW_LINE>} | closure.setResolveStrategy(Closure.DELEGATE_FIRST); |
693,538 | public void removeDeployment(String deploymentId, boolean cascade) {<NEW_LINE>DeploymentEntityManager deploymentEntityManager = Context.getCommandContext().getDeploymentEntityManager();<NEW_LINE>DeploymentEntity <MASK><NEW_LINE>if (deployment == null) {<NEW_LINE>throw new ActivitiObjectNotFoundException("Could not find a deployment with id '" + deploymentId + "'.", DeploymentEntity.class);<NEW_LINE>}<NEW_LINE>// Remove any process definition from the cache<NEW_LINE>List<ProcessDefinition> processDefinitions = new ProcessDefinitionQueryImpl(Context.getCommandContext()).deploymentId(deploymentId).list();<NEW_LINE>FlowableEventDispatcher eventDispatcher = Context.getProcessEngineConfiguration().getEventDispatcher();<NEW_LINE>for (ProcessDefinition processDefinition : processDefinitions) {<NEW_LINE>// Since all process definitions are deleted by a single query, we should dispatch the events in this loop<NEW_LINE>if (eventDispatcher.isEnabled()) {<NEW_LINE>eventDispatcher.dispatchEvent(ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, processDefinition), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// Delete data<NEW_LINE>deploymentEntityManager.deleteDeployment(deploymentId, cascade);<NEW_LINE>// Since we use a delete by query, delete-events are not automatically dispatched<NEW_LINE>if (eventDispatcher.isEnabled()) {<NEW_LINE>eventDispatcher.dispatchEvent(ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, deployment), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG);<NEW_LINE>}<NEW_LINE>for (ProcessDefinition processDefinition : processDefinitions) {<NEW_LINE>processDefinitionCache.remove(processDefinition.getId());<NEW_LINE>}<NEW_LINE>} | deployment = deploymentEntityManager.findDeploymentById(deploymentId); |
809,340 | public void renderIndexPaging(String indexFile) throws Exception {<NEW_LINE>long totalPosts = db.getPublishedCount("post");<NEW_LINE>int postsPerPage = config.getPostsPerPage();<NEW_LINE>if (totalPosts == 0) {<NEW_LINE>// paging makes no sense. render single index file instead<NEW_LINE>renderIndex(indexFile);<NEW_LINE>} else {<NEW_LINE>PagingHelper pagingHelper <MASK><NEW_LINE>TemplateModel model = new TemplateModel();<NEW_LINE>model.setRenderer(renderingEngine);<NEW_LINE>model.setNumberOfPages(pagingHelper.getNumberOfPages());<NEW_LINE>try {<NEW_LINE>db.setLimit(postsPerPage);<NEW_LINE>for (int pageStart = 0, page = 1; pageStart < totalPosts; pageStart += postsPerPage, page++) {<NEW_LINE>String fileName = indexFile;<NEW_LINE>db.setStart(pageStart);<NEW_LINE>model.setCurrentPageNuber(page);<NEW_LINE>String previous = pagingHelper.getPreviousFileName(page);<NEW_LINE>model.setPreviousFilename(previous);<NEW_LINE>String nextFileName = pagingHelper.getNextFileName(page);<NEW_LINE>model.setNextFileName(nextFileName);<NEW_LINE>DocumentModel contentModel = buildSimpleModel(MASTERINDEX_TEMPLATE_NAME);<NEW_LINE>if (page > 1) {<NEW_LINE>contentModel.setRootPath("../");<NEW_LINE>}<NEW_LINE>model.setContent(contentModel);<NEW_LINE>// Add page number to file name<NEW_LINE>fileName = pagingHelper.getCurrentFileName(page, fileName);<NEW_LINE>ModelRenderingConfig renderConfig = new ModelRenderingConfig(fileName, model, MASTERINDEX_TEMPLATE_NAME);<NEW_LINE>render(renderConfig);<NEW_LINE>}<NEW_LINE>db.resetPagination();<NEW_LINE>} catch (Exception e) {<NEW_LINE>throw new Exception("Failed to render index. Cause: " + e.getMessage(), e);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | = new PagingHelper(totalPosts, postsPerPage); |
894,777 | public void createEncryptedPdf(View v) {<NEW_LINE>String path = root.getAbsolutePath() + "/crypt.pdf";<NEW_LINE>// 128 bit is the highest currently supported<NEW_LINE>int keyLength = 128;<NEW_LINE>// Limit permissions of those without the password<NEW_LINE>AccessPermission ap = new AccessPermission();<NEW_LINE>ap.setCanPrint(false);<NEW_LINE>// Sets the owner password and user password<NEW_LINE>StandardProtectionPolicy spp = new <MASK><NEW_LINE>// Setups up the encryption parameters<NEW_LINE>spp.setEncryptionKeyLength(keyLength);<NEW_LINE>spp.setPermissions(ap);<NEW_LINE>BouncyCastleProvider provider = new BouncyCastleProvider();<NEW_LINE>Security.addProvider(provider);<NEW_LINE>PDFont font = PDType1Font.HELVETICA;<NEW_LINE>PDDocument document = new PDDocument();<NEW_LINE>PDPage page = new PDPage();<NEW_LINE>document.addPage(page);<NEW_LINE>try {<NEW_LINE>PDPageContentStream contentStream = new PDPageContentStream(document, page);<NEW_LINE>// Write Hello World in blue text<NEW_LINE>contentStream.beginText();<NEW_LINE>contentStream.setNonStrokingColor(15, 38, 192);<NEW_LINE>contentStream.setFont(font, 12);<NEW_LINE>contentStream.newLineAtOffset(100, 700);<NEW_LINE>contentStream.showText("Hello World");<NEW_LINE>contentStream.endText();<NEW_LINE>contentStream.close();<NEW_LINE>// Save the final pdf document to a file<NEW_LINE>// Apply the protections to the PDF<NEW_LINE>document.protect(spp);<NEW_LINE>document.save(path);<NEW_LINE>document.close();<NEW_LINE>tv.setText("Successfully wrote PDF to " + path);<NEW_LINE>} catch (IOException e) {<NEW_LINE>Log.e("PdfBox-Android-Sample", "Exception thrown while creating PDF for encryption", e);<NEW_LINE>}<NEW_LINE>} | StandardProtectionPolicy("12345", "hi", ap); |
1,299,601 | protected void mapResources(int index) {<NEW_LINE>NV_ENC_MAP_INPUT_RESOURCE mapInputResource = new NV_ENC_MAP_INPUT_RESOURCE();<NEW_LINE>mapInputResource.version(NV_ENC_MAP_INPUT_RESOURCE_VER);<NEW_LINE>mapInputResource.registeredResource(this.registeredResources.get(index));<NEW_LINE>try {<NEW_LINE>checkNvCodecApiCall(this.nvEncodeApiFunctionList.nvEncMapInputResource().call(this.encoder, mapInputResource));<NEW_LINE>} catch (NvCodecException e) {<NEW_LINE>e.printStackTrace();<NEW_LINE>}<NEW_LINE>this.mappedInputBuffers.set(<MASK><NEW_LINE>if (this.motionEstimationOnly) {<NEW_LINE>mapInputResource.registeredResource(this.registeredResourcesForReference.get(index));<NEW_LINE>try {<NEW_LINE>checkNvCodecApiCall(this.nvEncodeApiFunctionList.nvEncMapInputResource().call(this.encoder, mapInputResource));<NEW_LINE>} catch (NvCodecException e) {<NEW_LINE>e.printStackTrace();<NEW_LINE>}<NEW_LINE>this.mappedRefBuffers.set(index, mapInputResource.mappedResource());<NEW_LINE>}<NEW_LINE>} | index, mapInputResource.mappedResource()); |
1,821,568 | private static RetryPolicy retryPolicy(Map<String, ?> retryPolicy, int maxAttemptsLimit) {<NEW_LINE>int maxAttempts = checkNotNull(ServiceConfigUtil<MASK><NEW_LINE>checkArgument(maxAttempts >= 2, "maxAttempts must be greater than 1: %s", maxAttempts);<NEW_LINE>maxAttempts = Math.min(maxAttempts, maxAttemptsLimit);<NEW_LINE>long initialBackoffNanos = checkNotNull(ServiceConfigUtil.getInitialBackoffNanosFromRetryPolicy(retryPolicy), "initialBackoff cannot be empty");<NEW_LINE>checkArgument(initialBackoffNanos > 0, "initialBackoffNanos must be greater than 0: %s", initialBackoffNanos);<NEW_LINE>long maxBackoffNanos = checkNotNull(ServiceConfigUtil.getMaxBackoffNanosFromRetryPolicy(retryPolicy), "maxBackoff cannot be empty");<NEW_LINE>checkArgument(maxBackoffNanos > 0, "maxBackoff must be greater than 0: %s", maxBackoffNanos);<NEW_LINE>double backoffMultiplier = checkNotNull(ServiceConfigUtil.getBackoffMultiplierFromRetryPolicy(retryPolicy), "backoffMultiplier cannot be empty");<NEW_LINE>checkArgument(backoffMultiplier > 0, "backoffMultiplier must be greater than 0: %s", backoffMultiplier);<NEW_LINE>Long perAttemptRecvTimeout = ServiceConfigUtil.getPerAttemptRecvTimeoutNanosFromRetryPolicy(retryPolicy);<NEW_LINE>checkArgument(perAttemptRecvTimeout == null || perAttemptRecvTimeout >= 0, "perAttemptRecvTimeout cannot be negative: %s", perAttemptRecvTimeout);<NEW_LINE>Set<Code> retryableCodes = ServiceConfigUtil.getRetryableStatusCodesFromRetryPolicy(retryPolicy);<NEW_LINE>checkArgument(perAttemptRecvTimeout != null || !retryableCodes.isEmpty(), "retryableStatusCodes cannot be empty without perAttemptRecvTimeout");<NEW_LINE>return new RetryPolicy(maxAttempts, initialBackoffNanos, maxBackoffNanos, backoffMultiplier, perAttemptRecvTimeout, retryableCodes);<NEW_LINE>} | .getMaxAttemptsFromRetryPolicy(retryPolicy), "maxAttempts cannot be empty"); |
1,073,758 | public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {<NEW_LINE>Object child = listAdapter.getChild(groupPosition, childPosition);<NEW_LINE>if (child instanceof DownloadResourceGroup) {<NEW_LINE>String uniqueId = ((DownloadResourceGroup) child).getUniqueId();<NEW_LINE>final DownloadResourceGroupFragment regionDialogFragment = DownloadResourceGroupFragment.createInstance(uniqueId);<NEW_LINE>((DownloadActivity) getActivity()).showDialog(getActivity(), regionDialogFragment);<NEW_LINE>return true;<NEW_LINE>} else if (child instanceof CustomIndexItem) {<NEW_LINE>String regionId = group.getGroupByIndex(groupPosition).getUniqueId();<NEW_LINE>DownloadItemFragment downloadItemFragment = <MASK><NEW_LINE>((DownloadActivity) getActivity()).showDialog(getActivity(), downloadItemFragment);<NEW_LINE>} else if (child instanceof DownloadItem) {<NEW_LINE>DownloadItem downloadItem = (DownloadItem) child;<NEW_LINE>ItemViewHolder vh = (ItemViewHolder) v.getTag();<NEW_LINE>OnClickListener ls = vh.getRightButtonAction(downloadItem, vh.getClickAction(downloadItem));<NEW_LINE>ls.onClick(v);<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>return false;<NEW_LINE>} | DownloadItemFragment.createInstance(regionId, childPosition); |
1,806,952 | private void addErrorPayload(Map<String, Object> resultMap, String message, String path, int line, int column, Map<String, Object> extensions) {<NEW_LINE>LinkedList<Map<String, Object>> errorList = (LinkedList<Map<String, Object>>) resultMap.computeIfAbsent(ERRORS, it -> new LinkedList<Map<String, Object>>());<NEW_LINE>Map<String, Object> newErrorMap = new HashMap<>();<NEW_LINE>// inner map<NEW_LINE><MASK><NEW_LINE>if (line != -1 && column != -1) {<NEW_LINE>ArrayList<Map<String, Object>> listLocations = new ArrayList<>();<NEW_LINE>listLocations.add(Map.of(LINE, line, COLUMN, column));<NEW_LINE>newErrorMap.put(LOCATIONS, listLocations);<NEW_LINE>}<NEW_LINE>if (extensions != null && extensions.size() > 0) {<NEW_LINE>newErrorMap.put(EXTENSIONS, extensions);<NEW_LINE>}<NEW_LINE>if (path != null) {<NEW_LINE>newErrorMap.put(PATH, List.of(path));<NEW_LINE>}<NEW_LINE>errorList.add(newErrorMap);<NEW_LINE>} | newErrorMap.put(MESSAGE, message); |
744,663 | public OUser authenticate(ODatabaseSession session, final String username, final String password) {<NEW_LINE>if (delegate == null)<NEW_LINE><MASK><NEW_LINE>if (session == null)<NEW_LINE>throw new OSecurityAccessException("OSymmetricKeySecurity.authenticate() Database is null for username: " + username);<NEW_LINE>final String dbName = session.getName();<NEW_LINE>OUser user = delegate.getUser(session, username);<NEW_LINE>if (user == null)<NEW_LINE>throw new OSecurityAccessException(dbName, "OSymmetricKeySecurity.authenticate() Username or Key is invalid for username: " + username);<NEW_LINE>if (user.getAccountStatus() != OSecurityUser.STATUSES.ACTIVE)<NEW_LINE>throw new OSecurityAccessException(dbName, "OSymmetricKeySecurity.authenticate() User '" + username + "' is not active");<NEW_LINE>try {<NEW_LINE>OUserSymmetricKeyConfig userConfig = new OUserSymmetricKeyConfig(user.getDocument());<NEW_LINE>OSymmetricKey sk = OSymmetricKey.fromConfig(userConfig);<NEW_LINE>String decryptedUsername = sk.decryptAsString(password);<NEW_LINE>if (OSecurityManager.checkPassword(username, decryptedUsername))<NEW_LINE>return user;<NEW_LINE>} catch (Exception ex) {<NEW_LINE>throw OException.wrapException(new OSecurityAccessException(dbName, "OSymmetricKeySecurity.authenticate() Exception for session: " + dbName + ", username: " + username + " " + ex.getMessage()), ex);<NEW_LINE>}<NEW_LINE>throw new OSecurityAccessException(dbName, "OSymmetricKeySecurity.authenticate() Username or Key is invalid for session: " + dbName + ", username: " + username);<NEW_LINE>} | throw new OSecurityAccessException("OSymmetricKeySecurity.authenticate() Delegate is null for username: " + username); |
1,328,520 | public InputStream requestStream(ApiResource.RequestMethod method, String url, Map<String, Object> params, RequestOptions options) throws StripeException {<NEW_LINE>StripeRequest request = new StripeRequest(method, url, params, options);<NEW_LINE>StripeResponseStream responseStream = httpClient.requestStreamWithRetries(request);<NEW_LINE>int responseCode = responseStream.code();<NEW_LINE>if (responseCode < 200 || responseCode >= 300) {<NEW_LINE>StripeResponse response;<NEW_LINE>try {<NEW_LINE>response = responseStream.unstream();<NEW_LINE>} catch (IOException e) {<NEW_LINE>throw new ApiConnectionException(String.format("IOException during API request to Stripe (%s): %s " + "Please check your internet connection and try again. If this problem persists," + "you should check Stripe's service status at https://twitter.com/stripestatus," + " or let us know at support@stripe.com.", Stripe.getApiBase(), e<MASK><NEW_LINE>}<NEW_LINE>handleApiError(response);<NEW_LINE>}<NEW_LINE>return responseStream.body();<NEW_LINE>} | .getMessage()), e); |
1,518,663 | private void loadCache() throws Exception {<NEW_LINE>TransactionMonitor.DEFAULT.logTransaction("MetaCache", "load", new Task() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void go() throws Exception {<NEW_LINE>List<DcTbl> dcs = dcService.findAllDcNames();<NEW_LINE>List<DcMeta> dcMetas = new LinkedList<>();<NEW_LINE>for (DcTbl dc : dcs) {<NEW_LINE>dcMetas.add(dcMetaService.getDcMeta(dc.getDcName()));<NEW_LINE>}<NEW_LINE>List<RedisCheckRuleTbl<MASK><NEW_LINE>List<RedisCheckRuleMeta> redisCheckRuleMetas = new LinkedList<>();<NEW_LINE>for (RedisCheckRuleTbl redisCheckRuleTbl : redisCheckRuleTbls) {<NEW_LINE>RedisCheckRuleMeta redisCheckRuleMeta = new RedisCheckRuleMeta();<NEW_LINE>redisCheckRuleMeta.setId(redisCheckRuleTbl.getId()).setCheckType(redisCheckRuleTbl.getCheckType()).setParam(redisCheckRuleTbl.getParam());<NEW_LINE>redisCheckRuleMetas.add(redisCheckRuleMeta);<NEW_LINE>}<NEW_LINE>refreshClusterParts();<NEW_LINE>XpipeMeta xpipeMeta = createXpipeMeta(dcMetas, redisCheckRuleMetas);<NEW_LINE>refreshMeta(xpipeMeta);<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public Map getData() {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>});<NEW_LINE>} | > redisCheckRuleTbls = redisCheckRuleService.getAllRedisCheckRules(); |
1,610,817 | public void run(RegressionEnvironment env) {<NEW_LINE>// prepare<NEW_LINE>RegressionPath path = preloadData(env, false);<NEW_LINE>// test join<NEW_LINE>String eplJoin = "@name('s0') select * from SupportBean_S0 as s0 unidirectional, AWindow(p00='x') as aw where aw.id = s0.id";<NEW_LINE>env.compileDeploy(eplJoin, path).addListener("s0");<NEW_LINE>assertEquals(2, SupportCountAccessEvent.getAndResetCountGetterCalled());<NEW_LINE>env.sendEventBean(new SupportBean_S0(-1, "x"));<NEW_LINE>env.assertListenerInvoked("s0");<NEW_LINE>// test subquery no-index-share<NEW_LINE>String eplSubqueryNoIndexShare = "@name('s1') select (select id from AWindow(p00='x') as aw where aw.id = s0.id) " + "from SupportBean_S0 as s0 unidirectional";<NEW_LINE>env.compileDeploy(eplSubqueryNoIndexShare, path).addListener("s1");<NEW_LINE>assertEquals(2, SupportCountAccessEvent.getAndResetCountGetterCalled());<NEW_LINE>env.sendEventBean(new SupportBean_S0(-1, "x"));<NEW_LINE>env.undeployAll();<NEW_LINE>// test subquery with index share<NEW_LINE>path = preloadData(env, true);<NEW_LINE>String eplSubqueryWithIndexShare = "@name('s2') select (select id from AWindow(p00='x') as aw where aw.id = s0.id) " + "from SupportBean_S0 as s0 unidirectional";<NEW_LINE>env.compileDeploy(eplSubqueryWithIndexShare, path).addListener("s2");<NEW_LINE>assertEquals(<MASK><NEW_LINE>env.sendEventBean(new SupportBean_S0(-1, "x"));<NEW_LINE>env.assertListenerInvoked("s2");<NEW_LINE>env.undeployAll();<NEW_LINE>} | 2, SupportCountAccessEvent.getAndResetCountGetterCalled()); |
1,687,370 | public boolean apply(Game game, Ability source) {<NEW_LINE>Player player = game.getPlayer(source.getControllerId());<NEW_LINE>if (player == null) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>new TreasureToken().putOntoBattlefield(player.rollDice(outcome, source, game, 4), game, source, source.getControllerId());<NEW_LINE>Permanent <MASK><NEW_LINE>if (permanent == null) {<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>UUID playerToRightId = game.getState().getPlayersInRange(source.getControllerId(), game).stream().reduce((u1, u2) -> u2).orElse(null);<NEW_LINE>if (playerToRightId == null) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>game.addEffect(new GainControlTargetEffect(Duration.Custom, true, playerToRightId).setTargetPointer(new FixedTarget(permanent, game)), source);<NEW_LINE>return true;<NEW_LINE>} | permanent = source.getSourcePermanentIfItStillExists(game); |
6,301 | public static ByteProcessor limitedOpeningByReconstruction(final ImageProcessor ip, final ImageProcessor ipBackground, final double radius, final double maxBackground) {<NEW_LINE>// Apply (initial) morphological opening<NEW_LINE>final RankFilters rf = new RankFilters();<NEW_LINE>ipBackground.setRoi(ip.getRoi());<NEW_LINE>rf.rank(<MASK><NEW_LINE>// Mask out any above-threshold background pixels & their surroundings<NEW_LINE>ByteProcessor bpMask = null;<NEW_LINE>if (!Double.isNaN(maxBackground) && maxBackground > 0) {<NEW_LINE>int w = ip.getWidth();<NEW_LINE>int h = ip.getHeight();<NEW_LINE>for (int i = 0; i < w * h; i++) {<NEW_LINE>if (ipBackground.getf(i) > maxBackground) {<NEW_LINE>if (bpMask == null)<NEW_LINE>bpMask = new ByteProcessor(w, h);<NEW_LINE>bpMask.setf(i, 1f);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// Apply mask if required<NEW_LINE>if (bpMask != null) {<NEW_LINE>rf.rank(bpMask, radius * 2, RankFilters.MAX);<NEW_LINE>for (int i = 0; i < w * h; i++) {<NEW_LINE>if (bpMask.getf(i) != 0f) {<NEW_LINE>ipBackground.setf(i, Float.NEGATIVE_INFINITY);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// } else {<NEW_LINE>// // Don't return a mask - all pixels are ok<NEW_LINE>// System.out.println("Skipping background mask!");<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// Apply the morphological reconstruction<NEW_LINE>MorphologicalReconstruction.morphologicalReconstruction(ipBackground, ip);<NEW_LINE>return bpMask;<NEW_LINE>} | ipBackground, radius, RankFilters.MIN); |
1,224,925 | public void execute() throws BuildException {<NEW_LINE>try {<NEW_LINE>// XXX workaround for http://issues.apache.org/bugzilla/show_bug.cgi?id=43398<NEW_LINE>pseudoTests = new LinkedHashMap<>();<NEW_LINE>if (getProject().getProperty("allmodules") != null) {<NEW_LINE>modules = new TreeSet<>(Arrays.asList(getProject().getProperty("allmodules").split("[, ]+")));<NEW_LINE>modules.add("nbbuild");<NEW_LINE>} else {<NEW_LINE>Path nbAllPath = nball.toPath();<NEW_LINE>modules = new TreeSet<>(Files.walk(nbAllPath).filter(p -> Files.exists(p.resolve("external/binaries-list"))).map(p -> nbAllPath.relativize(p)).map(p -> p.toString()).collect<MASK><NEW_LINE>}<NEW_LINE>try {<NEW_LINE>testNoStrayThirdPartyBinaries();<NEW_LINE>testLicenseFilesAreProperlyFormattedPhysically();<NEW_LINE>testLicenses();<NEW_LINE>testBinaryUniqueness();<NEW_LINE>testLicenseinfo();<NEW_LINE>} catch (IOException x) {<NEW_LINE>throw new BuildException(x, getLocation());<NEW_LINE>}<NEW_LINE>JUnitReportWriter.writeReport(this, null, reportFile, pseudoTests);<NEW_LINE>if (haltonfailure && pseudoTests.values().stream().anyMatch(err -> err != null)) {<NEW_LINE>throw new BuildException("Failed VerifyLibsAndLicenses test(s):\n" + pseudoTests.values().stream().filter(err -> err != null).collect(Collectors.joining("\n")), getLocation());<NEW_LINE>}<NEW_LINE>} catch (NullPointerException | IOException x) {<NEW_LINE>x.printStackTrace();<NEW_LINE>throw new BuildException(x);<NEW_LINE>}<NEW_LINE>} | (Collectors.toSet())); |
1,040,697 | private Optional<JsonResponseUpsert> persistForBPartnerWithinTrx(@Nullable final String orgCode, @NonNull final ExternalIdentifier bpartnerIdentifier, @NonNull final JsonRequestContactUpsert jsonContactUpsert, @NonNull final SyncAdvise parentSyncAdvise) {<NEW_LINE>final OrgId orgId = retrieveOrgIdOrDefault(orgCode);<NEW_LINE>final Optional<BPartnerComposite> optBPartnerComposite = jsonRetrieverService.getBPartnerComposite(orgId, bpartnerIdentifier);<NEW_LINE>if (!optBPartnerComposite.isPresent()) {<NEW_LINE>// 404<NEW_LINE>return Optional.empty();<NEW_LINE>}<NEW_LINE>final BPartnerComposite bpartnerComposite = optBPartnerComposite.get();<NEW_LINE>final ShortTermContactIndex shortTermIndex = new ShortTermContactIndex(bpartnerComposite);<NEW_LINE>final SyncAdvise effectiveSyncAdvise = coalesceNotNull(jsonContactUpsert.getSyncAdvise(), parentSyncAdvise);<NEW_LINE>final Map<String, JsonResponseUpsertItemBuilder> identifierToBuilder = new HashMap<>();<NEW_LINE>for (final JsonRequestContactUpsertItem requestItem : jsonContactUpsert.getRequestItems()) {<NEW_LINE>final JsonResponseUpsertItemBuilder responseItemBuilder = syncJsonContact(bpartnerComposite.getOrgId(), requestItem, effectiveSyncAdvise, shortTermIndex);<NEW_LINE>// we don't know the metasfreshId yet, so for now just store what we know into the map<NEW_LINE>identifierToBuilder.put(requestItem.getContactIdentifier(), responseItemBuilder);<NEW_LINE>}<NEW_LINE><MASK><NEW_LINE>final JsonResponseUpsertBuilder response = JsonResponseUpsert.builder();<NEW_LINE>for (final JsonRequestContactUpsertItem requestItem : jsonContactUpsert.getRequestItems()) {<NEW_LINE>final BPartnerContact bpartnerContact = bpartnerComposite.extractContactByHandle(requestItem.getContactIdentifier()).get();<NEW_LINE>final JsonMetasfreshId metasfreshId = JsonMetasfreshId.of(BPartnerContactId.toRepoId(bpartnerContact.getId()));<NEW_LINE>final ExternalIdentifier externalIdentifier = ExternalIdentifier.of(requestItem.getContactIdentifier());<NEW_LINE>handleExternalReference(externalIdentifier, metasfreshId, ExternalUserReferenceType.USER_ID);<NEW_LINE>final JsonResponseUpsertItem responseItem = identifierToBuilder.get(requestItem.getContactIdentifier()).metasfreshId(JsonMetasfreshId.of(BPartnerContactId.toRepoId(bpartnerContact.getId()))).build();<NEW_LINE>response.responseItem(responseItem);<NEW_LINE>}<NEW_LINE>return Optional.of(response.build());<NEW_LINE>} | bpartnerCompositeRepository.save(bpartnerComposite, true); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.