code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
FORMAT: 1A # Taskify API This is the API Blueprint file for Taskify API. # Group Tasks ## Task Collection [/tasks] A collection of Tasks objects ### List all Tasks [GET] Retrieve a collection of Tasks + Response 200 (application/json) + Body [ { "id": 1, "name": "Buy some goreceries" }, { "id": 2, "name": "Dinner with Katty" } ] ### Create a new task [POST] Create a Task + Request (application/json) + Attributes (object) + Response 200 + Body { "id": 1, "name": "Buy some goreceries" } ## Tasks [/tasks/{id}] A single Tasks object with all its details ### Get single Task [GET] Retrieve a single Task by ID + Request + Parameters + id (number) + Response 200 (application/json) + Body { "id": 1, "name": "Buy some goreceries" } ### Modify single Task [PUT] Edit a single Task by ID + Request (application/json) + Attributes + id (number) + Response 200 (application/json) + Body { "id": 1, "name": "Buy some goreceries" } ### Remove single Task [DELETE] Delete a single Task by ID + Request + Attributes + id (number) + Response 204
rrgarciach/taskify-ionic
api-blueprints/taskify.md
Markdown
apache-2.0
1,461
using Google.GData.YouTube; using NUnit.Framework; namespace Google.GData.Client.UnitTests.YouTube { /// <summary> ///This is a test class for PositionTest and is intended ///to contain all PositionTest Unit Tests ///</summary> [TestFixture] [Category("YouTube")] public class PositionTest { /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get; set; } /// <summary> ///A test for Position Constructor ///</summary> [Test] public void PositionConstructorTest() { string initValue = "secret test string"; Position target = new Position(initValue); Assert.AreEqual(target.Value, initValue, "Object value should be identical after construction"); } /// <summary> ///A test for Position Constructor ///</summary> [Test] public void PositionConstructorTest1() { Position target = new Position(); Assert.IsNull(target.Value, "Object value should be null after construction"); } //You can use the following additional attributes as you write your tests: // // //Use ClassInitialize to run code before running the first test in the class //[ClassInitialize()] //public static void MyClassInitialize(TestContext testContext) //{ //} // //Use ClassCleanup to run code after all tests in a class have run //[ClassCleanup()] //public static void MyClassCleanup() //{ //} // //Use TestInitialize to run code before running each test //[TestInitialize()] //public void MyTestInitialize() //{ //} // //Use TestCleanup to run code after each test has run //[TestCleanup()] //public void MyTestCleanup() //{ //} // } }
jonny-novikov/google-gdata
src/unittests/youtube/PositionTest.cs
C#
apache-2.0
2,100
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_51) on Thu Apr 28 18:37:57 UTC 2016 --> <title>Uses of Class org.apache.cassandra.cql3.restrictions.MultiColumnRestriction.IN (apache-cassandra API)</title> <meta name="date" content="2016-04-28"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.cassandra.cql3.restrictions.MultiColumnRestriction.IN (apache-cassandra API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.IN.html" title="class in org.apache.cassandra.cql3.restrictions">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/cassandra/cql3/restrictions/class-use/MultiColumnRestriction.IN.html" target="_top">Frames</a></li> <li><a href="MultiColumnRestriction.IN.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.cassandra.cql3.restrictions.MultiColumnRestriction.IN" class="title">Uses of Class<br>org.apache.cassandra.cql3.restrictions.MultiColumnRestriction.IN</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.IN.html" title="class in org.apache.cassandra.cql3.restrictions">MultiColumnRestriction.IN</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.cassandra.cql3.restrictions">org.apache.cassandra.cql3.restrictions</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.cassandra.cql3.restrictions"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.IN.html" title="class in org.apache.cassandra.cql3.restrictions">MultiColumnRestriction.IN</a> in <a href="../../../../../../org/apache/cassandra/cql3/restrictions/package-summary.html">org.apache.cassandra.cql3.restrictions</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.IN.html" title="class in org.apache.cassandra.cql3.restrictions">MultiColumnRestriction.IN</a> in <a href="../../../../../../org/apache/cassandra/cql3/restrictions/package-summary.html">org.apache.cassandra.cql3.restrictions</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.InWithMarker.html" title="class in org.apache.cassandra.cql3.restrictions">MultiColumnRestriction.InWithMarker</a></strong></code> <div class="block">An IN restriction that uses a single marker for a set of IN values that are tuples.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.InWithValues.html" title="class in org.apache.cassandra.cql3.restrictions">MultiColumnRestriction.InWithValues</a></strong></code> <div class="block">An IN restriction that has a set of terms for in values.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.IN.html" title="class in org.apache.cassandra.cql3.restrictions">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/cassandra/cql3/restrictions/class-use/MultiColumnRestriction.IN.html" target="_top">Frames</a></li> <li><a href="MultiColumnRestriction.IN.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &copy; 2016 The Apache Software Foundation</small></p> </body> </html>
elisska/cloudera-cassandra
DATASTAX_CASSANDRA-2.2.6/javadoc/org/apache/cassandra/cql3/restrictions/class-use/MultiColumnRestriction.IN.html
HTML
apache-2.0
7,347
package org.http4s package headers class LinkSpec extends HeaderLaws { // FIXME Uri does not round trip properly: https://github.com/http4s/http4s/issues/1651 // checkAll(name = "Link", headerLaws(Link)) "parse" should { "accept format RFC 5988" in { val link = """</feed>; rel="alternate"; type="text/*"; title="main"; rev="previous"""" val parsedLinks = Link.parse(link).map(_.values) val parsedLink = parsedLinks.map(_.head) parsedLink.map(_.uri) must beRight(uri"/feed") parsedLink.map(_.rel) must beRight(Option("alternate")) parsedLink.map(_.title) must beRight(Option("main")) parsedLink.map(_.`type`) must beRight(Option(MediaRange.`text/*`)) parsedLink.map(_.rev) must beRight(Option("previous")) } "accept format RFC 8288" in { val links = List( """<https://api.github.com/search/code?q=addClass&page=1>; rel="prev"""", """<https://api.github.com/search/code?q=addClass&page=3>; rel="next"""", """<https://api.github.com/search/code?q=addClass&page=4>; rel="last"""", """<https://api.github.com/search/code?q=addClass&page=1>; rel="first"""" ) val parsedLinks = Link .parse(links.mkString(", ")) .map(_.values) parsedLinks.map(_.size) must beRight(links.size) } } "render" should { "properly format link according to RFC 5988" in { val links = Link( LinkValue( uri"/feed", rel = Some("alternate"), title = Some("main"), `type` = Some(MediaRange.`text/*`) )) links.renderString must_== "Link: </feed>; rel=alternate; title=main; type=text/*" } } }
ChristopherDavenport/http4s
tests/src/test/scala/org/http4s/headers/LinkSpec.scala
Scala
apache-2.0
1,696
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dialogflow/cx/v3beta1/advanced_settings.proto package com.google.cloud.dialogflow.cx.v3beta1; public final class AdvancedSettingsProto { private AdvancedSettingsProto() {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_LoggingSettings_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_LoggingSettings_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n:google/cloud/dialogflow/cx/v3beta1/adv" + "anced_settings.proto\022\"google.cloud.dialo" + "gflow.cx.v3beta1\032\037google/api/field_behav" + "ior.proto\"\315\001\n\020AdvancedSettings\022^\n\020loggin" + "g_settings\030\006 \001(\0132D.google.cloud.dialogfl" + "ow.cx.v3beta1.AdvancedSettings.LoggingSe" + "ttings\032Y\n\017LoggingSettings\022\"\n\032enable_stac" + "kdriver_logging\030\002 \001(\010\022\"\n\032enable_interact" + "ion_logging\030\003 \001(\010B\335\001\n&com.google.cloud.d" + "ialogflow.cx.v3beta1B\025AdvancedSettingsPr" + "otoP\001ZDgoogle.golang.org/genproto/google" + "apis/cloud/dialogflow/cx/v3beta1;cx\370\001\001\242\002" + "\002DF\252\002\"Google.Cloud.Dialogflow.Cx.V3Beta1" + "\352\002&Google::Cloud::Dialogflow::CX::V3beta" + "1b\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.api.FieldBehaviorProto.getDescriptor(), }); internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_descriptor, new java.lang.String[] { "LoggingSettings", }); internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_LoggingSettings_descriptor = internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_descriptor .getNestedTypes() .get(0); internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_LoggingSettings_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_LoggingSettings_descriptor, new java.lang.String[] { "EnableStackdriverLogging", "EnableInteractionLogging", }); com.google.api.FieldBehaviorProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
googleapis/java-dialogflow-cx
proto-google-cloud-dialogflow-cx-v3beta1/src/main/java/com/google/cloud/dialogflow/cx/v3beta1/AdvancedSettingsProto.java
Java
apache-2.0
4,476
// Copyright 2018 The Oppia Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for SuggestionThreadObjectFactory. */ // TODO(#7222): Remove the following block of unnnecessary imports once // SuggestionThreadObjectFactory.ts is upgraded to Angular 8. import { SuggestionObjectFactory } from 'domain/suggestion/SuggestionObjectFactory.ts'; // ^^^ This block is to be removed. require('domain/suggestion/SuggestionThreadObjectFactory.ts'); describe('Suggestion thread object factory', function() { beforeEach(function() { angular.mock.module('oppia'); }); beforeEach(angular.mock.module('oppia', function($provide) { $provide.value('SuggestionObjectFactory', new SuggestionObjectFactory()); })); var SuggestionThreadObjectFactory = null; var suggestionObjectFactory = null; beforeEach(angular.mock.inject(function($injector) { SuggestionThreadObjectFactory = $injector.get( 'SuggestionThreadObjectFactory'); suggestionObjectFactory = $injector.get('SuggestionObjectFactory'); })); it('should create a new suggestion thread from a backend dict.', function() { var suggestionThreadBackendDict = { last_updated: 1000, original_author_username: 'author', status: 'accepted', subject: 'sample subject', summary: 'sample summary', message_count: 10, state_name: 'state 1', thread_id: 'exploration.exp1.thread1' }; var suggestionBackendDict = { suggestion_id: 'exploration.exp1.thread1', suggestion_type: 'edit_exploration_state_content', target_type: 'exploration', target_id: 'exp1', target_version_at_submission: 1, status: 'accepted', author_name: 'author', change: { cmd: 'edit_state_property', property_name: 'content', state_name: 'state_1', new_value: { html: 'new suggestion content' }, old_value: { html: 'old suggestion content' } }, last_updated: 1000 }; var suggestionThread = SuggestionThreadObjectFactory.createFromBackendDicts( suggestionThreadBackendDict, suggestionBackendDict); expect(suggestionThread.status).toEqual('accepted'); expect(suggestionThread.subject).toEqual('sample subject'); expect(suggestionThread.summary).toEqual('sample summary'); expect(suggestionThread.originalAuthorName).toEqual('author'); expect(suggestionThread.lastUpdated).toEqual(1000); expect(suggestionThread.messageCount).toEqual(10); expect(suggestionThread.threadId).toEqual('exploration.exp1.thread1'); expect(suggestionThread.suggestion.suggestionType).toEqual( 'edit_exploration_state_content'); expect(suggestionThread.suggestion.targetType).toEqual('exploration'); expect(suggestionThread.suggestion.targetId).toEqual('exp1'); expect(suggestionThread.suggestion.suggestionId).toEqual( 'exploration.exp1.thread1'); expect(suggestionThread.suggestion.status).toEqual('accepted'); expect(suggestionThread.suggestion.authorName).toEqual('author'); expect(suggestionThread.suggestion.newValue.html).toEqual( 'new suggestion content'); expect(suggestionThread.suggestion.oldValue.html).toEqual( 'old suggestion content'); expect(suggestionThread.suggestion.lastUpdated).toEqual(1000); expect(suggestionThread.suggestion.getThreadId()).toEqual( 'exploration.exp1.thread1'); expect(suggestionThread.isSuggestionThread()).toEqual(true); expect(suggestionThread.isSuggestionHandled()).toEqual(true); suggestionThread.suggestion.status = 'review'; expect(suggestionThread.isSuggestionHandled()).toEqual(false); expect(suggestionThread.getSuggestionStatus()).toEqual('review'); expect(suggestionThread.getSuggestionStateName()).toEqual('state_1'); expect(suggestionThread.getReplacementHtmlFromSuggestion()).toEqual( 'new suggestion content'); var messages = [{ text: 'message1' }, { text: 'message2' }]; suggestionThread.setMessages(messages); expect(suggestionThread.messages).toEqual(messages); }); });
souravbadami/oppia
core/templates/dev/head/domain/suggestion/SuggestionThreadObjectFactorySpec.ts
TypeScript
apache-2.0
4,690
#!/usr/bin/env python from random import choice from python.decorators import euler_timer SQUARES = ["GO", "A1", "CC1", "A2", "T1", "R1", "B1", "CH1", "B2", "B3", "JAIL", "C1", "U1", "C2", "C3", "R2", "D1", "CC2", "D2", "D3", "FP", "E1", "CH2", "E2", "E3", "R3", "F1", "F2", "U2", "F3", "G2J", "G1", "G2", "CC3", "G3", "R4", "CH3", "H1", "T2", "H2"] def roll_die(size): first_die = choice(range(1, size + 1)) second_die = choice(range(1, size + 1)) return (first_die + second_die, (first_die == second_die)) def back(square, step): index = SQUARES.index(square) new_index = (index - step) % len(SQUARES) return SQUARES[new_index] def next_specific(square, next_type): if next_type not in ["R", "U"]: raise Exception("next_specific only intended for R and U") # R1=5, R2=15, R3=25, R4=35 index = SQUARES.index(square) if next_type == "R": if 0 <= index < 5 or 35 < index: return "R1" elif 5 < index < 15: return "R2" elif 15 < index < 25: return "R3" elif 25 < index < 35: return "R4" else: raise Exception("Case should not occur") # U1=12, U2=28 elif next_type == "U": if 0 <= index < 12 or index > 28: return "U1" elif 12 < index < 28: return "U2" else: return Exception("Case should not occur") else: raise Exception("Case should not occur") def next_square(landing_square, chance_card, chest_card): if landing_square not in ["CC1", "CC2", "CC3", "CH1", "CH2", "CH3", "G2J"]: return (landing_square, chance_card, chest_card) if landing_square == "G2J": return ("JAIL", chance_card, chest_card) elif landing_square in ["CC1", "CC2", "CC3"]: # 1/16 Go, Jail # 14/16 Stay chest_card = (chest_card + 1) % 16 if chest_card == 0: return ("GO", chance_card, chest_card) elif chest_card == 1: return ("JAIL", chance_card, chest_card) else: return (landing_square, chance_card, chest_card) elif landing_square in ["CH1", "CH2", "CH3"]: # 1/16 Go, Jail, C1, E3, H2, R1, next U, back 3 # 1/8 Next R chance_card = (chance_card + 1) % 16 if chance_card == 0: return ("GO", chance_card, chest_card) elif chance_card == 1: return ("JAIL", chance_card, chest_card) elif chance_card == 2: return ("C1", chance_card, chest_card) elif chance_card == 3: return ("E3", chance_card, chest_card) elif chance_card == 4: return ("H2", chance_card, chest_card) elif chance_card == 5: return ("R1", chance_card, chest_card) elif chance_card == 6: return (next_specific(landing_square, "U"), chance_card, chest_card) elif chance_card == 7: return next_square(back(landing_square, 3), chance_card, chest_card) elif chance_card in [8, 9]: return (next_specific(landing_square, "R"), chance_card, chest_card) else: return (landing_square, chance_card, chest_card) else: raise Exception("Case should not occur") def main(verbose=False): GAME_PLAY = 10 ** 6 dice_size = 4 visited = {"GO": 1} current = "GO" chance_card = 0 chest_card = 0 doubles = 0 for place in xrange(GAME_PLAY): total, double = roll_die(dice_size) if double: doubles += 1 else: doubles = 0 if doubles == 3: doubles = 0 current = "JAIL" else: index = SQUARES.index(current) landing_square = SQUARES[(index + total) % len(SQUARES)] (current, chance_card, chest_card) = next_square(landing_square, chance_card, chest_card) # if current is not in visited, sets to 1 # (default 0 returned by get) visited[current] = visited.get(current, 0) + 1 top_visited = sorted(visited.items(), key=lambda pair: pair[1], reverse=True) top_visited = [SQUARES.index(square[0]) for square in top_visited[:3]] return ''.join(str(index).zfill(2) for index in top_visited) if __name__ == '__main__': print euler_timer(84)(main)(verbose=True)
dhermes/project-euler
python/complete/no084.py
Python
apache-2.0
4,565
# Chlorobotryaceae FAMILY #### Status ACCEPTED #### According to Interim Register of Marine and Nonmarine Genera #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Chromista/Ochrophyta/Eustigmatophyceae/Chlorobotryaceae/README.md
Markdown
apache-2.0
181
/* * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ #pragma once #include "esp_bit_defs.h" /// Mask of interrupts sending to the host. typedef enum { SDIO_SLAVE_HOSTINT_BIT0 = BIT(0), ///< General purpose interrupt bit 0. SDIO_SLAVE_HOSTINT_BIT1 = BIT(1), SDIO_SLAVE_HOSTINT_BIT2 = BIT(2), SDIO_SLAVE_HOSTINT_BIT3 = BIT(3), SDIO_SLAVE_HOSTINT_BIT4 = BIT(4), SDIO_SLAVE_HOSTINT_BIT5 = BIT(5), SDIO_SLAVE_HOSTINT_BIT6 = BIT(6), SDIO_SLAVE_HOSTINT_BIT7 = BIT(7), SDIO_SLAVE_HOSTINT_SEND_NEW_PACKET = BIT(23), ///< New packet available } sdio_slave_hostint_t; /// Timing of SDIO slave typedef enum { SDIO_SLAVE_TIMING_PSEND_PSAMPLE = 0,/**< Send at posedge, and sample at posedge. Default value for HS mode. * Normally there's no problem using this to work in DS mode. */ SDIO_SLAVE_TIMING_NSEND_PSAMPLE ,///< Send at negedge, and sample at posedge. Default value for DS mode and below. SDIO_SLAVE_TIMING_PSEND_NSAMPLE, ///< Send at posedge, and sample at negedge SDIO_SLAVE_TIMING_NSEND_NSAMPLE, ///< Send at negedge, and sample at negedge } sdio_slave_timing_t; /// Configuration of SDIO slave mode typedef enum { SDIO_SLAVE_SEND_STREAM = 0, ///< Stream mode, all packets to send will be combined as one if possible SDIO_SLAVE_SEND_PACKET = 1, ///< Packet mode, one packets will be sent one after another (only increase packet_len if last packet sent). } sdio_slave_sending_mode_t;
espressif/esp-idf
components/hal/include/hal/sdio_slave_types.h
C
apache-2.0
1,611
package rds //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" ) // DescribeSQLLogFiles invokes the rds.DescribeSQLLogFiles API synchronously // api document: https://help.aliyun.com/api/rds/describesqllogfiles.html func (client *Client) DescribeSQLLogFiles(request *DescribeSQLLogFilesRequest) (response *DescribeSQLLogFilesResponse, err error) { response = CreateDescribeSQLLogFilesResponse() err = client.DoAction(request, response) return } // DescribeSQLLogFilesWithChan invokes the rds.DescribeSQLLogFiles API asynchronously // api document: https://help.aliyun.com/api/rds/describesqllogfiles.html // asynchronous document: https://help.aliyun.com/document_detail/66220.html func (client *Client) DescribeSQLLogFilesWithChan(request *DescribeSQLLogFilesRequest) (<-chan *DescribeSQLLogFilesResponse, <-chan error) { responseChan := make(chan *DescribeSQLLogFilesResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.DescribeSQLLogFiles(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan } // DescribeSQLLogFilesWithCallback invokes the rds.DescribeSQLLogFiles API asynchronously // api document: https://help.aliyun.com/api/rds/describesqllogfiles.html // asynchronous document: https://help.aliyun.com/document_detail/66220.html func (client *Client) DescribeSQLLogFilesWithCallback(request *DescribeSQLLogFilesRequest, callback func(response *DescribeSQLLogFilesResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *DescribeSQLLogFilesResponse var err error defer close(result) response, err = client.DescribeSQLLogFiles(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result } // DescribeSQLLogFilesRequest is the request struct for api DescribeSQLLogFiles type DescribeSQLLogFilesRequest struct { *requests.RpcRequest OwnerId requests.Integer `position:"Query" name:"OwnerId"` ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` DBInstanceId string `position:"Query" name:"DBInstanceId"` FileName string `position:"Query" name:"FileName"` PageSize requests.Integer `position:"Query" name:"PageSize"` PageNumber requests.Integer `position:"Query" name:"PageNumber"` OwnerAccount string `position:"Query" name:"OwnerAccount"` } // DescribeSQLLogFilesResponse is the response struct for api DescribeSQLLogFiles type DescribeSQLLogFilesResponse struct { *responses.BaseResponse RequestId string `json:"RequestId" xml:"RequestId"` TotalRecordCount int `json:"TotalRecordCount" xml:"TotalRecordCount"` PageNumber int `json:"PageNumber" xml:"PageNumber"` PageRecordCount int `json:"PageRecordCount" xml:"PageRecordCount"` Items ItemsInDescribeSQLLogFiles `json:"Items" xml:"Items"` } // CreateDescribeSQLLogFilesRequest creates a request to invoke DescribeSQLLogFiles API func CreateDescribeSQLLogFilesRequest() (request *DescribeSQLLogFilesRequest) { request = &DescribeSQLLogFilesRequest{ RpcRequest: &requests.RpcRequest{}, } request.InitWithApiInfo("Rds", "2014-08-15", "DescribeSQLLogFiles", "rds", "openAPI") return } // CreateDescribeSQLLogFilesResponse creates a response to parse from DescribeSQLLogFiles response func CreateDescribeSQLLogFilesResponse() (response *DescribeSQLLogFilesResponse) { response = &DescribeSQLLogFilesResponse{ BaseResponse: &responses.BaseResponse{}, } return }
xiaozhu36/terraform-provider
vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/rds/describe_sql_log_files.go
GO
apache-2.0
4,727
# # Cookbook Name:: bcpc # Recipe:: diamond # # Copyright 2013, Bloomberg Finance L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if node['bcpc']['enabled']['metrics'] then include_recipe "bcpc::default" cookbook_file "/tmp/diamond.deb" do source "bins/diamond.deb" owner "root" mode 00444 end %w{python-support python-configobj python-pip python-httplib2}.each do |pkg| package pkg do action :upgrade end end package "diamond" do provider Chef::Provider::Package::Dpkg source "/tmp/diamond.deb" action :upgrade options "--force-confold --force-confdef" end if node['bcpc']['virt_type'] == "kvm" package "ipmitool" do action :upgrade end package "smartmontools" do action :upgrade end end cookbook_file "/tmp/pyrabbit-1.0.1.tar.gz" do source "bins/pyrabbit-1.0.1.tar.gz" owner "root" mode 00444 end bash "install-pyrabbit" do code <<-EOH pip install /tmp/pyrabbit-1.0.1.tar.gz EOH not_if "pip freeze|grep pyrabbit" end bash "diamond-set-user" do user "root" code <<-EOH sed --in-place '/^DIAMOND_USER=/d' /etc/default/diamond echo 'DIAMOND_USER="root"' >> /etc/default/diamond EOH not_if "grep -e '^DIAMOND_USER=\"root\"' /etc/default/diamond" notifies :restart, "service[diamond]", :delayed end template "/etc/diamond/diamond.conf" do source "diamond.conf.erb" owner "diamond" group "root" mode 00600 variables(:servers => get_head_nodes) notifies :restart, "service[diamond]", :delayed end service "diamond" do action [:enable, :start] end end
agilemobiledev/chef-bcpc
cookbooks/bcpc/recipes/diamond.rb
Ruby
apache-2.0
2,355
import { promises as fsPromises } from 'fs'; import { expect } from 'chai'; describe('Verify stryker runs with mocha < 6', () => { let strykerLog: string; before(async () => { strykerLog = await fsPromises.readFile('./stryker.log', 'utf8'); }); it('should warn about old mocha version', async () => { expect(strykerLog).contains('DEPRECATED: Mocha < 6 detected. Please upgrade to at least Mocha version 6. Stryker will drop support for Mocha < 6 in V5'); }); });
stryker-mutator/stryker
e2e/test/mocha-old-version/verify/verify.ts
TypeScript
apache-2.0
486
# AUTOGENERATED FILE FROM balenalib/asus-tinker-edge-t-fedora:34-run ENV NODE_VERSION 16.14.0 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-arm64.tar.gz" \ && echo "82d71968c82eb391f463df62ba277563a3bd01ce43bba0e7e1c533991567b8fe node-v$NODE_VERSION-linux-arm64.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-arm64.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-arm64.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@node" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Fedora 34 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v16.14.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
resin-io-library/base-images
balena-base-images/node/asus-tinker-edge-t/fedora/34/16.14.0/run/Dockerfile
Dockerfile
apache-2.0
2,751
import React from 'react'; import RadioButton from '../RadioButton'; import { mount } from 'enzyme'; const render = (props) => mount( <RadioButton {...props} className="extra-class" name="test-name" value="test-value" /> ); describe('RadioButton', () => { describe('renders as expected', () => { const wrapper = render({ checked: true, }); const input = wrapper.find('input'); const label = wrapper.find('label'); const div = wrapper.find('div'); describe('input', () => { it('is of type radio', () => { expect(input.props().type).toEqual('radio'); }); it('has the expected class', () => { expect(input.hasClass('bx--radio-button')).toEqual(true); }); it('has a unique id set by default', () => { expect(input.props().id).toBeDefined(); }); it('should have checked set when checked is passed', () => { wrapper.setProps({ checked: true }); expect(input.props().checked).toEqual(true); }); it('should set the name prop as expected', () => { expect(input.props().name).toEqual('test-name'); }); }); describe('label', () => { it('should set htmlFor', () => { expect(label.props().htmlFor) .toEqual(input.props().id); }); it('should set the correct class', () => { expect(label.props().className).toEqual('bx--radio-button__label'); }); it('should render a span with the correct class', () => { const span = label.find('span'); expect(span.hasClass('bx--radio-button__appearance')).toEqual(true); }); it('should render label text', () => { wrapper.setProps({ labelText: 'test label text' }); expect(label.text()).toMatch(/test label text/); }); }); describe('wrapper', () => { it('should have the correct class', () => { expect(div.hasClass('radioButtonWrapper')).toEqual(true); }); it('should have extra classes applied', () => { expect(div.hasClass('extra-class')).toEqual(true); }); }); }); it('should set defaultChecked as expected', () => { const wrapper = render({ defaultChecked: true, }); const input = wrapper.find('input'); expect(input.props().defaultChecked).toEqual(true); wrapper.setProps({ defaultChecked: false }); expect(input.props().defaultChecked).toEqual(false); }); it('should set id if one is passed in', () => { const wrapper = render({ id: 'unique-id', }); const input = wrapper.find('input'); expect(input.props().id).toEqual('unique-id'); }); describe('events', () => { it('should invoke onChange with expected arguments', () => { const onChange = jest.fn(); const wrapper = render({ onChange }); const input = wrapper.find('input'); const inputElement = input.get(0); inputElement.checked = true; wrapper.find('input').simulate('change'); const call = onChange.mock.calls[0]; expect(call[0]).toEqual('test-value'); expect(call[1]).toEqual('test-name'); expect(call[2].target).toBe(inputElement); }); }); });
hellobrian/carbon-components-react
components/__tests__/RadioButton-test.js
JavaScript
apache-2.0
3,213
/** * Copyright (C) 2010-2013 Alibaba Group Holding Limited * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.rocketmq.client.impl.consumer; import com.alibaba.rocketmq.client.log.ClientLogger; import com.alibaba.rocketmq.common.message.MessageConst; import com.alibaba.rocketmq.common.message.MessageExt; import com.alibaba.rocketmq.common.protocol.body.ProcessQueueInfo; import org.slf4j.Logger; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Queue consumption snapshot * * @author shijia.wxr<[email protected]> * @since 2013-7-24 */ public class ProcessQueue { public final static long RebalanceLockMaxLiveTime = Long.parseLong(System.getProperty( "rocketmq.client.rebalance.lockMaxLiveTime", "30000")); public final static long RebalanceLockInterval = Long.parseLong(System.getProperty( "rocketmq.client.rebalance.lockInterval", "20000")); private final static long PullMaxIdleTime = Long.parseLong(System.getProperty( "rocketmq.client.pull.pullMaxIdleTime", "120000")); private final Logger log = ClientLogger.getLog(); private final ReadWriteLock lockTreeMap = new ReentrantReadWriteLock(); private final TreeMap<Long, MessageExt> msgTreeMap = new TreeMap<Long, MessageExt>(); private final AtomicLong msgCount = new AtomicLong(); private final Lock lockConsume = new ReentrantLock(); private final TreeMap<Long, MessageExt> msgTreeMapTemp = new TreeMap<Long, MessageExt>(); private final AtomicLong tryUnlockTimes = new AtomicLong(0); private volatile long queueOffsetMax = 0L; private volatile boolean dropped = false; private volatile long lastPullTimestamp = System.currentTimeMillis(); private volatile long lastConsumeTimestamp = System.currentTimeMillis(); private volatile boolean locked = false; private volatile long lastLockTimestamp = System.currentTimeMillis(); private volatile boolean consuming = false; private volatile long msgAccCnt = 0; public boolean isLockExpired() { boolean result = (System.currentTimeMillis() - this.lastLockTimestamp) > RebalanceLockMaxLiveTime; return result; } public boolean isPullExpired() { boolean result = (System.currentTimeMillis() - this.lastPullTimestamp) > PullMaxIdleTime; return result; } public boolean putMessage(final List<MessageExt> msgs) { boolean dispatchToConsume = false; try { this.lockTreeMap.writeLock().lockInterruptibly(); try { int validMsgCnt = 0; for (MessageExt msg : msgs) { MessageExt old = msgTreeMap.put(msg.getQueueOffset(), msg); if (null == old) { validMsgCnt++; this.queueOffsetMax = msg.getQueueOffset(); } } msgCount.addAndGet(validMsgCnt); if (!msgTreeMap.isEmpty() && !this.consuming) { dispatchToConsume = true; this.consuming = true; } if (!msgs.isEmpty()) { MessageExt messageExt = msgs.get(msgs.size() - 1); String property = messageExt.getProperty(MessageConst.PROPERTY_MAX_OFFSET); if (property != null) { long accTotal = Long.parseLong(property) - messageExt.getQueueOffset(); if (accTotal > 0) { this.msgAccCnt = accTotal; } } } } finally { this.lockTreeMap.writeLock().unlock(); } } catch (InterruptedException e) { log.error("putMessage exception", e); } return dispatchToConsume; } public long getMaxSpan() { try { this.lockTreeMap.readLock().lockInterruptibly(); try { if (!this.msgTreeMap.isEmpty()) { return this.msgTreeMap.lastKey() - this.msgTreeMap.firstKey(); } } finally { this.lockTreeMap.readLock().unlock(); } } catch (InterruptedException e) { log.error("getMaxSpan exception", e); } return 0; } public long removeMessage(final List<MessageExt> msgs) { long result = -1; final long now = System.currentTimeMillis(); try { this.lockTreeMap.writeLock().lockInterruptibly(); this.lastConsumeTimestamp = now; try { if (!msgTreeMap.isEmpty()) { result = this.queueOffsetMax + 1; int removedCnt = 0; for (MessageExt msg : msgs) { MessageExt prev = msgTreeMap.remove(msg.getQueueOffset()); if (prev != null) { removedCnt--; } } msgCount.addAndGet(removedCnt); if (!msgTreeMap.isEmpty()) { result = msgTreeMap.firstKey(); } } } finally { this.lockTreeMap.writeLock().unlock(); } } catch (Throwable t) { log.error("removeMessage exception", t); } return result; } public TreeMap<Long, MessageExt> getMsgTreeMap() { return msgTreeMap; } public AtomicLong getMsgCount() { return msgCount; } public boolean isDropped() { return dropped; } public void setDropped(boolean dropped) { this.dropped = dropped; } public boolean isLocked() { return locked; } public void setLocked(boolean locked) { this.locked = locked; } public void rollback() { try { this.lockTreeMap.writeLock().lockInterruptibly(); try { this.msgTreeMap.putAll(this.msgTreeMapTemp); this.msgTreeMapTemp.clear(); } finally { this.lockTreeMap.writeLock().unlock(); } } catch (InterruptedException e) { log.error("rollback exception", e); } } public long commit() { try { this.lockTreeMap.writeLock().lockInterruptibly(); try { Long offset = this.msgTreeMapTemp.lastKey(); msgCount.addAndGet(this.msgTreeMapTemp.size() * (-1)); this.msgTreeMapTemp.clear(); if (offset != null) { return offset + 1; } } finally { this.lockTreeMap.writeLock().unlock(); } } catch (InterruptedException e) { log.error("commit exception", e); } return -1; } public void makeMessageToCosumeAgain(List<MessageExt> msgs) { try { this.lockTreeMap.writeLock().lockInterruptibly(); try { for (MessageExt msg : msgs) { this.msgTreeMapTemp.remove(msg.getQueueOffset()); this.msgTreeMap.put(msg.getQueueOffset(), msg); } } finally { this.lockTreeMap.writeLock().unlock(); } } catch (InterruptedException e) { log.error("makeMessageToCosumeAgain exception", e); } } public List<MessageExt> takeMessags(final int batchSize) { List<MessageExt> result = new ArrayList<MessageExt>(batchSize); final long now = System.currentTimeMillis(); try { this.lockTreeMap.writeLock().lockInterruptibly(); this.lastConsumeTimestamp = now; try { if (!this.msgTreeMap.isEmpty()) { for (int i = 0; i < batchSize; i++) { Map.Entry<Long, MessageExt> entry = this.msgTreeMap.pollFirstEntry(); if (entry != null) { result.add(entry.getValue()); msgTreeMapTemp.put(entry.getKey(), entry.getValue()); } else { break; } } } if (result.isEmpty()) { consuming = false; } } finally { this.lockTreeMap.writeLock().unlock(); } } catch (InterruptedException e) { log.error("take Messages exception", e); } return result; } public void clear() { try { this.lockTreeMap.writeLock().lockInterruptibly(); try { this.msgTreeMap.clear(); this.msgTreeMapTemp.clear(); this.msgCount.set(0); this.queueOffsetMax = 0L; } finally { this.lockTreeMap.writeLock().unlock(); } } catch (InterruptedException e) { log.error("rollback exception", e); } } public long getLastLockTimestamp() { return lastLockTimestamp; } public void setLastLockTimestamp(long lastLockTimestamp) { this.lastLockTimestamp = lastLockTimestamp; } public Lock getLockConsume() { return lockConsume; } public long getLastPullTimestamp() { return lastPullTimestamp; } public void setLastPullTimestamp(long lastPullTimestamp) { this.lastPullTimestamp = lastPullTimestamp; } public long getMsgAccCnt() { return msgAccCnt; } public void setMsgAccCnt(long msgAccCnt) { this.msgAccCnt = msgAccCnt; } public long getTryUnlockTimes() { return this.tryUnlockTimes.get(); } public void incTryUnlockTimes() { this.tryUnlockTimes.incrementAndGet(); } public void fillProcessQueueInfo(final ProcessQueueInfo info) { try { this.lockTreeMap.readLock().lockInterruptibly(); if (!this.msgTreeMap.isEmpty()) { info.setCachedMsgMinOffset(this.msgTreeMap.firstKey()); info.setCachedMsgMaxOffset(this.msgTreeMap.lastKey()); info.setCachedMsgCount(this.msgTreeMap.size()); } if (!this.msgTreeMapTemp.isEmpty()) { info.setTransactionMsgMinOffset(this.msgTreeMapTemp.firstKey()); info.setTransactionMsgMaxOffset(this.msgTreeMapTemp.lastKey()); info.setTransactionMsgCount(this.msgTreeMapTemp.size()); } info.setLocked(this.locked); info.setTryUnlockTimes(this.tryUnlockTimes.get()); info.setLastLockTimestamp(this.lastLockTimestamp); info.setDroped(this.dropped); info.setLastPullTimestamp(this.lastPullTimestamp); info.setLastConsumeTimestamp(this.lastConsumeTimestamp); } catch (Exception e) { } finally { this.lockTreeMap.readLock().unlock(); } } public long getLastConsumeTimestamp() { return lastConsumeTimestamp; } public void setLastConsumeTimestamp(long lastConsumeTimestamp) { this.lastConsumeTimestamp = lastConsumeTimestamp; } }
tgou/RocketMQ
rocketmq-client/src/main/java/com/alibaba/rocketmq/client/impl/consumer/ProcessQueue.java
Java
apache-2.0
12,629
% Environment Variables Cargo sets and reads a number of environment variables which your code can detect or override. Here is a list of the variables Cargo sets, organized by when it interacts with them: # Environment variables Cargo reads You can override these environment variables to change Cargo's behavior on your system: * `CARGO_HOME` - Cargo maintains a local cache of the registry index and of git checkouts of crates. By default these are stored under `$HOME/.cargo`, but this variable overrides the location of this directory. Once a crate is cached it is not removed by the clean command. * `CARGO_TARGET_DIR` - Location of where to place all generated artifacts, relative to the current working directory. * `RUSTC` - Instead of running `rustc`, Cargo will execute this specified compiler instead. * `RUSTDOC` - Instead of running `rustdoc`, Cargo will execute this specified `rustdoc` instance instead. * `RUSTFLAGS` - A space-separated list of custom flags to pass to all compiler invocations that Cargo performs. In contrast with `cargo rustc`, this is useful for passing a flag to *all* compiler instances. Note that Cargo will also read environment variables for `.cargo/config` configuration values, as described in [that documentation][config-env] [config-env]: config.html#environment-variables # Environment variables Cargo sets for crates Cargo exposes these environment variables to your crate when it is compiled. To get the value of any of these variables in a Rust program, do this: ``` let version = env!("CARGO_PKG_VERSION"); ``` `version` will now contain the value of `CARGO_PKG_VERSION`. * `CARGO_MANIFEST_DIR` - The directory containing the manifest of your package. * `CARGO_PKG_VERSION` - The full version of your package. * `CARGO_PKG_VERSION_MAJOR` - The major version of your package. * `CARGO_PKG_VERSION_MINOR` - The minor version of your package. * `CARGO_PKG_VERSION_PATCH` - The patch version of your package. * `CARGO_PKG_VERSION_PRE` - The pre-release version of your package. * `CARGO_PKG_AUTHORS` - Colon seperated list of authors from the manifest of your package. * `CARGO_PKG_NAME` - The name of your package. * `CARGO_PKG_DESCRIPTION` - The description of your package. * `CARGO_PKG_HOMEPAGE` - The home page of your package. # Environment variables Cargo sets for build scripts Cargo sets several environment variables when build scripts are run. Because these variables are not yet set when the build script is compiled, the above example using `env!` won't work and instead you'll need to retrieve the values when the build script is run: ``` use std::env; let out_dir = env::var("OUT_DIR").unwrap(); ``` `out_dir` will now contain the value of `OUT_DIR`. * `CARGO_MANIFEST_DIR` - The directory containing the manifest for the package being built (the package containing the build script). Also note that this is the value of the current working directory of the build script when it starts. * `CARGO_MANIFEST_LINKS` - the manifest `links` value. * `CARGO_FEATURE_<name>` - For each activated feature of the package being built, this environment variable will be present where `<name>` is the name of the feature uppercased and having `-` translated to `_`. * `OUT_DIR` - the folder in which all output should be placed. This folder is inside the build directory for the package being built, and it is unique for the package in question. * `TARGET` - the target triple that is being compiled for. Native code should be compiled for this triple. Some more information about target triples can be found in [clang’s own documentation][clang]. * `HOST` - the host triple of the rust compiler. * `NUM_JOBS` - the parallelism specified as the top-level parallelism. This can be useful to pass a `-j` parameter to a system like `make`. * `OPT_LEVEL`, `DEBUG` - values of the corresponding variables for the profile currently being built. * `PROFILE` - name of the profile currently being built (see [profiles][profile]). * `DEP_<name>_<key>` - For more information about this set of environment variables, see build script documentation about [`links`][links]. [links]: build-script.html#the-links-manifest-key [profile]: manifest.html#the-profile-sections [clang]:http://clang.llvm.org/docs/CrossCompilation.html#target-triple
mark-buer/cargo
src/doc/environment-variables.md
Markdown
apache-2.0
4,625
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Runtime.Serialization.Json; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using FeedProcessor.Contracts; using FeedProcessor.Enums; using FeedProcessor.FeedItems; using FeedProcessor.Net; namespace FeedProcessor.Feeds { /// <summary> /// A feed which loads tweets from the twitter straming API. /// </summary> internal class TwitterStreamingFeed : Feed { /// <summary> /// A mapping of twitter user ids to user names. /// </summary> private static Dictionary<string, string> _twitterUserNameCache = new Dictionary<string, string>(); /// <summary> /// The username to use for the twitter streaming API. /// </summary> private string _twitterUsername; /// <summary> /// The password to use for the twitter streaming API. /// </summary> private string _twitterPassword; /// <summary> /// A JSON deserializer. /// </summary> private DataContractJsonSerializer _json = new DataContractJsonSerializer(typeof(TwitterJsonStatus)); /// <summary> /// The background task which is connected to the streaming API. /// </summary> private Task _task; /// <summary> /// Initializes a new instance of the <see cref="TwitterStreamingFeed"/> class. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The password.</param> internal TwitterStreamingFeed(string username, string password) : base(TimeSpan.FromDays(1), DateTime.MinValue) { _twitterUsername = username; _twitterPassword = password; SourceType = SourceType.Twitter; } /// <summary> /// Builds the query that is passed to the feed service. /// </summary> /// <returns>The query URI.</returns> internal override Uri BuildQuery() { return new Uri(string.Format(CultureInfo.InvariantCulture, "http://stream.twitter.com/1/statuses/filter.json?{0}", Query)); } /// <summary> /// Initiates a request to the feed service. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Really do want all exceptions."), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Debug.WriteLine(System.String)", Justification = "It's just a log message.")] protected override void Poll() { if (_task != null) { return; } _task = Task.Factory.StartNew(new Action(() => { HttpWebResponse webResponse = null; StreamReader responseStream = null; HttpWebRequest webRequest = null; int wait = 250; try { while (true) { try { // Connect webRequest = (HttpWebRequest)WebRequest.Create(BuildQuery()); webRequest.Credentials = new NetworkCredential(_twitterUsername, _twitterPassword); webRequest.Timeout = -1; webResponse = (HttpWebResponse)webRequest.GetResponse(); responseStream = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")); // Read the stream. while (true) { wait = 250; ProcessResponse(responseStream.ReadLine()); RetryTime(HttpStatusCode.OK); } } catch (WebException ex) { Debug.WriteLine(ex.Message); if (ex.Status == WebExceptionStatus.ProtocolError) { // -- From Twitter Docs -- // When a HTTP error (> 200) is returned, back off exponentially. // Perhaps start with a 10 second wait, double on each subsequent failure, // and finally cap the wait at 240 seconds. // Exponential Backoff if (wait < 10000) { wait = 10000; } else { if (wait < 240000) { wait = wait * 2; } } } else { // -- From Twitter Docs -- // When a network error (TCP/IP level) is encountered, back off linearly. // Perhaps start at 250 milliseconds and cap at 16 seconds. // Linear Backoff if (wait < 16000) { wait += 250; } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { if (webRequest != null) { webRequest.Abort(); } if (responseStream != null) { responseStream.Close(); responseStream = null; } if (webResponse != null) { webResponse.Close(); webResponse = null; } Debug.WriteLine("Waiting: " + wait); RetryTime(HttpStatusCode.NotAcceptable); Thread.Sleep(wait); } } } catch (Exception ex) { RetryTime(HttpStatusCode.NotAcceptable); Debug.WriteLine(ex.Message); Debug.WriteLine("Waiting: " + wait); Thread.Sleep(wait); } })); } /// <summary> /// Processes the response from the feed service. /// </summary> /// <param name="response">response from the feed service.</param> internal override void ProcessResponse(object responseObject) { string response = responseObject.ToString(); byte[] byteArray = Encoding.UTF8.GetBytes(response); TwitterJsonStatus status = null; using (MemoryStream stream = new MemoryStream(byteArray)) { status = _json.ReadObject(stream) as TwitterJsonStatus; } StatusFeedItem feedItem = new StatusFeedItem { Author = status.user.screen_name, AvatarUri = new Uri(status.user.profile_image_url), Date = DateTimeOffset.ParseExact(status.created_at, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture).DateTime, ServiceId = status.id, Uri = new Uri(string.Format(CultureInfo.InvariantCulture, "http://twitter.com/#!/{0}/status/{1}", status.user.screen_name, status.id)), Status = status.text }; RaiseGotNewFeedItem(feedItem); } /// <summary> /// Returns a time after which it's ok to make another query. /// </summary> /// <param name="httpStatusCode">The HTTP status code returned from the last attempt.</param> /// <returns> /// The time after which it's ok to make another query. /// </returns> internal override DateTime RetryTime(HttpStatusCode httpStatusCode) { RaiseSourceStatusUpdated(httpStatusCode == HttpStatusCode.OK); return DateTime.MinValue; } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #region Utility Methods #region GetFlickrUserIdFromUserName /// <summary> /// Callback for GetTwitterUserIdFromUserName. /// </summary> /// <param name="userId">The userId returned by the twitter API.</param> internal delegate void GetTwitterUserIdFromUserNameCallback(string userId); /// <summary> /// Gets the twitter user id from a username. /// </summary> /// <param name="username">The username.</param> /// <param name="callback">The callback.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Really do want all exceptions.")] internal static void GetTwitterUserIdFromUserName(string username, GetTwitterUserIdFromUserNameCallback callback) { if (_twitterUserNameCache.ContainsValue(username)) { callback((from kvp in _twitterUserNameCache where kvp.Value == username select kvp.Key).FirstOrDefault()); return; } string query = string.Format(CultureInfo.InvariantCulture, "http://api.twitter.com/1/users/show.xml?screen_name={0}", username); AsyncWebRequest request = new AsyncWebRequest(); request.Request(new Uri(query)); request.Result += (sender, e) => { if (e.Status != HttpStatusCode.OK) { callback(null); } try { string userid = XDocument.Parse(e.Response).Element("user").Element("id").Value; _twitterUserNameCache[userid] = username; callback(userid); } catch { callback(null); } }; } #endregion #endregion } }
stimulant/SocialStream
FeedProcessor/Feeds/TwitterStreamingFeed.cs
C#
apache-2.0
11,420
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Alexander Y. Kleymenov * @version $Revision$ */ package javax.crypto.spec; import java.io.Serializable; import java.security.spec.KeySpec; import java.util.Arrays; import javax.crypto.SecretKey; /** * A key specification for a <code>SecretKey</code> and also a secret key * implementation that is provider-independent. It can be used for raw secret * keys that can be specified as <code>byte[]</code>. */ public class SecretKeySpec implements SecretKey, KeySpec, Serializable { // The 5.0 spec. doesn't declare this serialVersionUID field // In order to be compatible it is explicitly declared here // for details see HARMONY-233 private static final long serialVersionUID = 6577238317307289933L; private final byte[] key; private final String algorithm; private final String format = "RAW"; /** * Creates a new <code>SecretKeySpec</code> for the specified key data and * algorithm name. * * @param key * the key data. * @param algorithm * the algorithm name. * @throws IllegalArgumentException * if the key data or the algorithm name is null or if the key * data is empty. */ public SecretKeySpec(byte[] key, String algorithm) { if (key == null) { throw new IllegalArgumentException("key == null"); } if (key.length == 0) { throw new IllegalArgumentException("key.length == 0"); } if (algorithm == null) { throw new IllegalArgumentException("algorithm == null"); } this.algorithm = algorithm; this.key = new byte[key.length]; System.arraycopy(key, 0, this.key, 0, key.length); } /** * Creates a new <code>SecretKeySpec</code> for the key data from the * specified buffer <code>key</code> starting at <code>offset</code> with * length <code>len</code> and the specified <code>algorithm</code> name. * * @param key * the key data. * @param offset * the offset. * @param len * the size of the key data. * @param algorithm * the algorithm name. * @throws IllegalArgumentException * if the key data or the algorithm name is null, the key data * is empty or <code>offset</code> and <code>len</code> do not * specify a valid chunk in the buffer <code>key</code>. * @throws ArrayIndexOutOfBoundsException * if <code>offset</code> or <code>len</code> is negative. */ public SecretKeySpec(byte[] key, int offset, int len, String algorithm) { if (key == null) { throw new IllegalArgumentException("key == null"); } if (key.length == 0) { throw new IllegalArgumentException("key.length == 0"); } // BEGIN android-changed if (len < 0 || offset < 0) { throw new ArrayIndexOutOfBoundsException("len < 0 || offset < 0"); } // END android-changed if (key.length - offset < len) { throw new IllegalArgumentException("key too short"); } if (algorithm == null) { throw new IllegalArgumentException("algorithm == null"); } this.algorithm = algorithm; this.key = new byte[len]; System.arraycopy(key, offset, this.key, 0, len); } /** * Returns the algorithm name. * * @return the algorithm name. */ public String getAlgorithm() { return algorithm; } /** * Returns the name of the format used to encode the key. * * @return the format name "RAW". */ public String getFormat() { return format; } /** * Returns the encoded form of this secret key. * * @return the encoded form of this secret key. */ public byte[] getEncoded() { byte[] result = new byte[key.length]; System.arraycopy(key, 0, result, 0, key.length); return result; } /** * Returns the hash code of this <code>SecretKeySpec</code> object. * * @return the hash code. */ @Override public int hashCode() { int result = algorithm.length(); for (byte element : key) { result += element; } return result; } /** * Compares the specified object with this <code>SecretKeySpec</code> * instance. * * @param obj * the object to compare. * @return true if the algorithm name and key of both object are equal, * otherwise false. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof SecretKeySpec)) { return false; } SecretKeySpec ks = (SecretKeySpec) obj; return (algorithm.equalsIgnoreCase(ks.algorithm)) && (Arrays.equals(key, ks.key)); } }
webos21/xi
java/jcl/src/java/javax/crypto/spec/SecretKeySpec.java
Java
apache-2.0
5,286
#!/bin/bash exec puppet agent --no-daemonize --server puppet --logdest console --verbose
ungerts/docker-puppet
agent/scripts/puppet.sh
Shell
apache-2.0
89
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode; import java.io.File; import java.io.IOException; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.fs.permission.PermissionStatus; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.hdfs.server.common.GenerationStamp; import org.apache.hadoop.hdfs.server.common.Storage; import org.apache.hadoop.hdfs.server.namenode.BlocksMap.BlockInfo; /** * * CreateEditsLog Synopsis: CreateEditsLog -f numFiles StartingBlockId * numBlocksPerFile [-r replicafactor] [-d editsLogDirectory] Default * replication factor is 1 Default edits log directory is /tmp/EditsLogOut * * Create a name node's edits log in /tmp/EditsLogOut. The file * /tmp/EditsLogOut/current/edits can be copied to a name node's * dfs.name.dir/current direcotry and the name node can be started as usual. * * The files are created in /createdViaInjectingInEditsLog The file names * contain the starting and ending blockIds; hence once can create multiple * edits logs using this command using non overlapping block ids and feed the * files to a single name node. * * See Also @link #DataNodeCluster for injecting a set of matching blocks * created with this command into a set of simulated data nodes. * */ public class CreateEditsLog { static final String BASE_PATH = "/createdViaInjectingInEditsLog"; static final String EDITS_DIR = "/tmp/EditsLogOut"; static String edits_dir = EDITS_DIR; static final public long BLOCK_GENERATION_STAMP = GenerationStamp.FIRST_VALID_STAMP; static void addFiles(FSEditLog editLog, int numFiles, short replication, int blocksPerFile, long startingBlockId, FileNameGenerator nameGenerator) { PermissionStatus p = new PermissionStatus("joeDoe", "people", new FsPermission((short) 0777)); INodeDirectory dirInode = new INodeDirectory(p, 0L); editLog.logMkDir(BASE_PATH, dirInode); long blockSize = 10; BlockInfo[] blocks = new BlockInfo[blocksPerFile]; for (int iB = 0; iB < blocksPerFile; ++iB) { blocks[iB] = new BlockInfo(new Block(0, blockSize, BLOCK_GENERATION_STAMP), replication); } long currentBlockId = startingBlockId; long bidAtSync = startingBlockId; for (int iF = 0; iF < numFiles; iF++) { for (int iB = 0; iB < blocksPerFile; ++iB) { blocks[iB].setBlockId(currentBlockId++); } try { INodeFileUnderConstruction inode = new INodeFileUnderConstruction( null, replication, 0, blockSize, blocks, p, "", "", null); // Append path to filename with information about blockIDs String path = "_" + iF + "_B" + blocks[0].getBlockId() + "_to_B" + blocks[blocksPerFile - 1].getBlockId() + "_"; String filePath = nameGenerator.getNextFileName(""); filePath = filePath + path; // Log the new sub directory in edits if ((iF % nameGenerator.getFilesPerDirectory()) == 0) { String currentDir = nameGenerator.getCurrentDir(); dirInode = new INodeDirectory(p, 0L); editLog.logMkDir(currentDir, dirInode); } editLog.logOpenFile(filePath, inode); editLog.logCloseFile(filePath, inode); if (currentBlockId - bidAtSync >= 2000) { // sync every 2K // blocks editLog.logSync(); bidAtSync = currentBlockId; } } catch (IOException e) { System.out.println("Creating trascation for file " + iF + " encountered exception " + e); } } System.out.println("Created edits log in directory " + edits_dir); System.out.println(" containing " + numFiles + " File-Creates, each file with " + blocksPerFile + " blocks"); System.out.println(" blocks range: " + startingBlockId + " to " + (currentBlockId - 1)); } static String usage = "Usage: createditlogs " + " -f numFiles startingBlockIds NumBlocksPerFile [-r replicafactor] " + "[-d editsLogDirectory]\n" + " Default replication factor is 1\n" + " Default edits log direcory is " + EDITS_DIR + "\n"; static void printUsageExit() { System.out.println(usage); System.exit(-1); } static void printUsageExit(String err) { System.out.println(err); printUsageExit(); } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { long startingBlockId = 1; int numFiles = 0; short replication = 1; int numBlocksPerFile = 0; if (args.length == 0) { printUsageExit(); } for (int i = 0; i < args.length; i++) { // parse command line if (args[i].equals("-h")) printUsageExit(); if (args[i].equals("-f")) { if (i + 3 >= args.length || args[i + 1].startsWith("-") || args[i + 2].startsWith("-") || args[i + 3].startsWith("-")) { printUsageExit("Missing num files, starting block and/or number of blocks"); } numFiles = Integer.parseInt(args[++i]); startingBlockId = Integer.parseInt(args[++i]); numBlocksPerFile = Integer.parseInt(args[++i]); if (numFiles <= 0 || numBlocksPerFile <= 0) { printUsageExit("numFiles and numBlocksPerFile most be greater than 0"); } } else if (args[i].equals("-r") || args[i + 1].startsWith("-")) { if (i + 1 >= args.length) { printUsageExit("Missing num files, starting block and/or number of blocks"); } replication = Short.parseShort(args[++i]); } else if (args[i].equals("-d")) { if (i + 1 >= args.length || args[i + 1].startsWith("-")) { printUsageExit("Missing edits logs directory"); } edits_dir = args[++i]; } else { printUsageExit(); } } File editsLogDir = new File(edits_dir); File subStructureDir = new File(edits_dir + "/" + Storage.STORAGE_DIR_CURRENT); if (!editsLogDir.exists()) { if (!editsLogDir.mkdir()) { System.out.println("cannot create " + edits_dir); System.exit(-1); } } if (!subStructureDir.exists()) { if (!subStructureDir.mkdir()) { System.out.println("cannot create subdirs of " + edits_dir); System.exit(-1); } } FSImage fsImage = new FSImage(new File(edits_dir)); FileNameGenerator nameGenerator = new FileNameGenerator(BASE_PATH, 100); FSEditLog editLog = fsImage.getEditLog(); editLog.createEditLogFile(fsImage.getFsEditName()); editLog.open(); addFiles(editLog, numFiles, replication, numBlocksPerFile, startingBlockId, nameGenerator); editLog.logSync(); editLog.close(); } }
shot/hadoop-source-reading
src/test/org/apache/hadoop/hdfs/server/namenode/CreateEditsLog.java
Java
apache-2.0
7,159
// Copyright 2015 The Cockroach Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. See the AUTHORS file // for names of contributors. // // Author: Spencer Kimball ([email protected]) package log import ( "encoding/json" "fmt" "os" "reflect" "unicode/utf8" "golang.org/x/net/context" "github.com/cockroachdb/cockroach/roachpb" "github.com/cockroachdb/cockroach/util/caller" ) // AddStructured creates a structured log entry to be written to the // specified facility of the logger. func AddStructured(ctx context.Context, s Severity, depth int, format string, args []interface{}) { file, line, _ := caller.Lookup(depth + 1) entry := LogEntry{} entry.set(ctx, format, args) logging.outputLogEntry(s, file, line, false, &entry) } // getJSON returns a JSON representation of the specified argument. // Returns nil if the type is simple and does not require a separate // JSON representation. func getJSON(arg interface{}) []byte { // Not much point in storying strings and byte slices twice, as // they're nearly always exactly specified in the format string. switch arg.(type) { case string, []byte, roachpb.Key, roachpb.EncodedKey: return nil } jsonBytes, err := json.Marshal(arg) if err != nil { return []byte(fmt.Sprintf("{\"error\": %q}", err.Error())) } return jsonBytes } func (entry *LogEntry) set(ctx context.Context, format string, args []interface{}) { entry.Format, entry.Args = parseFormatWithArgs(format, args) if ctx != nil { for i := Field(0); i < maxField; i++ { if v := ctx.Value(i); v != nil { switch vTyp := v.(type) { case roachpb.NodeID: entry.NodeID = &vTyp case roachpb.StoreID: entry.StoreID = &vTyp case roachpb.RangeID: entry.RangeID = &vTyp case roachpb.Method: entry.Method = &vTyp case roachpb.Key: entry.Key = vTyp } } } } } // parseFormatWithArgs parses the format string, matching each // format specifier with an argument from the args array. func parseFormatWithArgs(format string, args []interface{}) (string, []LogEntry_Arg) { // Process format string. var logArgs []LogEntry_Arg var buf []byte var idx int end := len(format) for i := 0; i < end; { lasti := i for i < end && format[i] != '%' { i++ } if i > lasti { buf = append(buf, format[lasti:i]...) } if i >= end { break } start := i // Process one verb. i++ F: for ; i < end; i++ { switch format[i] { case '#', '0', '+', '-', ' ': default: break F } } // TODO(spencer): should arg numbers dynamic precision be // supported? They're so rare, better to just panic here for now. if i < end && (format[i] == '[' || format[i] == '*') { panic(fmt.Sprintf("arg numbers in format not supported by logger: %s", format)) } // Read optional width. for ; i < end && format[i] >= '0' && format[i] <= '9'; i++ { } // Read optional precision. if i < end && format[i] == '.' { for i = i + 1; i < end && format[i] >= '0' && format[i] <= '9'; i++ { } } if i >= end { break } c, w := utf8.DecodeRuneInString(format[i:]) i += w // Escape and add percent directly to format buf. if c == '%' { buf = append(buf, '%', '%') continue } buf = append(buf, "%s"...) // New format string always gets %s, though we use the actual // format to generate the string here for the log argument. if idx >= len(args) { fmt.Fprintf(os.Stderr, "ERROR: insufficient parameters specified for format string %s", format) return string(append(buf, format[i:]...)), logArgs } logArgs = append(logArgs, makeLogArg(format[start:i], args[idx])) idx++ // advance to next arg index } // Add arguments which were not processed via format specifiers. for ; idx < len(args); idx++ { logArgs = append(logArgs, makeLogArg("%v", args[idx])) } return string(buf), logArgs } func makeLogArg(format string, arg interface{}) LogEntry_Arg { var tstr string if t := reflect.TypeOf(arg); t != nil { tstr = t.String() } return LogEntry_Arg{ Type: tstr, Str: fmt.Sprintf(format, arg), Json: getJSON(arg), } }
jamesgraves/cockroach
util/log/structured.go
GO
apache-2.0
4,615
# Enterovibrio Thompson et al., 2002 GENUS #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in International Journal of Systematic and Evolutionary Microbiology 52: -. [2015-2022] #### Original name null ### Remarks null
mdoering/backbone
life/Bacteria/Proteobacteria/Gammaproteobacteria/Vibrionales/Vibrionaceae/Enterovibrio/README.md
Markdown
apache-2.0
270
using System.Collections.Generic; using System.Net; using System.Text; namespace JFrog.Artifactory.Model { /// <summary> /// Artifactory MsBuild info model /// </summary> public class Build { public readonly static string STARTED_FORMAT = "{0}";//.000+0000"; public readonly static string ARTIFACTORY_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.ssszzzz"; /// <summary> /// build/assembly version /// </summary> public string version { get { return "1.0.1"; } } /// <summary> /// project name /// </summary> public string name { get; set; } /// <summary> /// build number /// </summary> public string number { get; set; } public string type { get; set; } public BuildAgent buildAgent { get; set; } public Agent agent { get; set; } /// <summary> /// Build start time /// </summary> public string started { get; set; } /// <summary> /// Build start time /// </summary> public string startedDateMillis { get; set; } /// <summary> /// Build duration in millis /// </summary> public long durationMillis { get; set; } /// <summary> /// The user who executed the build (TFS user or system user) /// </summary> public string principal { get; set; } /// <summary> /// The artifactory user used for deploythe build’s artifacts /// </summary> public string artifactoryPrincipal { get; set; } /// <summary> /// build url in the build server /// </summary> public string url { get; set; } /// <summary> /// system variables /// </summary> public IDictionary<string,string> properties { get; set; } /// <summary> /// Version control revision (Changeset number in TFS) /// </summary> public string vcsRevision { get; set; } public LicenseControl licenseControl { get; set; } public BlackDuckGovernance blackDuckGovernance { get; set; } public BuildRetention buildRetention { get; set; } /// <summary> /// A list of one or more modules produced by this build /// </summary> public List<Module> modules { get; set; } public DeployClient deployClient { set; get; } public Dictionary<string, string> getDefaultProperties() { Dictionary<string, string> result = new Dictionary<string, string>(); result.Add("build.name", name); result.Add("build.number", number); result.Add("build.timestamp", startedDateMillis); result.Add("vcs.revision", vcsRevision); return result; } /// <summary> /// Preparing the properties (Matrix params) to suitable Url Query /// </summary> /// <param name="matrixParam"></param> /// <returns></returns> public static string buildMatrixParamsString(List<KeyValuePair<string, string>> matrixParam) { StringBuilder matrix = new StringBuilder(); if (matrixParam != null) { matrixParam.ForEach( pair => matrix.Append(";").Append(WebUtility.UrlEncode(pair.Key)).Append("="). Append(WebUtility.UrlEncode(pair.Value)) ); } return matrix.ToString(); } } /// <summary> /// Build agent name and version, for example MSBuild 12.0 /// </summary> public class BuildAgent { public string name { get; set; } public string version { get; set; } } /// <summary> /// CI server name and version, for example TFS 2013 /// </summary> //public class Agent //{ // public string name { get; set; } // public string version { get; set; } //} public class LicenseControl { public string runChecks { get; set; } public string includePublishedArtifacts { get; set; } public string autoDiscover { get; set; } public List<string> licenseViolationsRecipients { get; set; } public List<string> scopes { get; set; } } public class BlackDuckGovernance { public string runChecks { get; set; } public string appName { get; set; } public string appVersion { get; set; } public string autoCreateMissingComponentRequests { get; set; } public string autoDiscardStaleComponentRequests { get; set; } public string includePublishedArtifacts { get; set; } public List<string> reportRecipients { get; set; } public List<string> scopes { get; set; } } public class BuildRetention { public int count { get; set; } public bool deleteBuildArtifacts { get; set; } public List<string> buildNumbersNotToBeDiscarded { get; set; } } /// <summary> /// build module data /// </summary> public class Module { public Module(string projectName) { Artifacts = new HashSet<Artifact>(new Artifact()); Dependencies = new List<Dependency>(); id = projectName; } /// <summary> /// module identifier /// </summary> public string id { get; set; } /// <summary> /// A list of artifacts deployed for this module /// </summary> public HashSet<Artifact> Artifacts { get; set; } /// <summary> /// A list of dependencies used when building this module /// </summary> public List<Dependency> Dependencies { get; set; } } public class Artifact : IEqualityComparer<Artifact> { public string type { get; set; } public string sha1 { get; set; } public string md5 { get; set; } public string name { get; set; } public bool Equals(Artifact a, Artifact b) { if (!a.type.Equals(b.type)) return false; if (!a.sha1.Equals(b.sha1)) return false; if (!a.md5.Equals(b.md5)) return false; if (!a.name.Equals(b.name)) return false; return true; } public int GetHashCode(Artifact obj) { int hash = 17; hash = hash * 31 + obj.type.GetHashCode(); hash = hash * 31 + obj.sha1.GetHashCode(); hash = hash * 31 + obj.md5.GetHashCode(); hash = hash * 31 + obj.name.GetHashCode(); return hash; } } public class Dependency { public string type { get; set; } public string sha1 { get; set; } public string md5 { get; set; } public string id { get; set; } public List<string> scopes { get; set; } } public class DeployClient { public int timeout { get; set; } public Proxy proxy { set; get; } } public class Proxy { private string host; private int port; private string username; private string password; private bool isCredentialsExists; public Proxy() { } public Proxy(string host, int port) { this.host = host; this.port = port; this.isCredentialsExists = false; } public Proxy(string host, int port, string username, string password) { this.host = host; this.port = port; this.username = username; this.password = password; this.isCredentialsExists = true; } public string Host { get { return this.host; } } public int Port { get { return this.port; } } public string Username { get { return this.username; } } public string Password { get { return this.password; } } public bool IsCredentialsExists { get { return this.isCredentialsExists; } } public bool IsBypass { get; set; } } //public static class Json //{ // public static const string version = "version"; // public static const string name = "name"; // public static const string number = "number"; // public static const string buildAgent = "buildAgent"; // public static const string agent = "agent"; // public static const string started = "started"; // public static const string durationMillis = "durationMillis"; // public static const string principal = "principal"; // public static const string artifactoryPrincipal = "artifactoryPrincipal"; // public static const string url = "url"; // public static const string vcsRevision = "vcsRevision"; // public static const string licenseControl = "licenseControl"; // public static const string buildRetention = "buildRetention"; // public static const string properties = "properties"; // public static const string modules = "modules"; // public static const string dependencies = "dependencies"; // public static const string artifacts = "artifacts"; // public static const string scopes = "scopes"; //} }
nilleb/msbuild-artifactory-plugin
msbuild-artifactory-plugin/Model/Build.cs
C#
apache-2.0
9,387
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.datapipeline.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.datapipeline.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import static com.fasterxml.jackson.core.JsonToken.*; /** * DeactivatePipelineResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeactivatePipelineResultJsonUnmarshaller implements Unmarshaller<DeactivatePipelineResult, JsonUnmarshallerContext> { public DeactivatePipelineResult unmarshall(JsonUnmarshallerContext context) throws Exception { DeactivatePipelineResult deactivatePipelineResult = new DeactivatePipelineResult(); return deactivatePipelineResult; } private static DeactivatePipelineResultJsonUnmarshaller instance; public static DeactivatePipelineResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DeactivatePipelineResultJsonUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-datapipeline/src/main/java/com/amazonaws/services/datapipeline/model/transform/DeactivatePipelineResultJsonUnmarshaller.java
Java
apache-2.0
1,666
/** * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spectator.placeholders; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Tag; import java.util.Map; /** * An extension of the {@link Id} interface that allows the list of tag names attached * to the Id to be declared in advance of the use of the metric. This can be used to * provide a default value for a tag or to use a TagFactory implementation that uses * context available in the execution environment to compute the value of the tag. */ public interface PlaceholderId { /** Description of the measurement that is being collected. */ String name(); /** New id with an additional tag value. */ PlaceholderId withTag(String k, String v); /** New id with an additional tag value. */ PlaceholderId withTag(Tag t); /** New id with additional tag values. */ PlaceholderId withTags(Iterable<Tag> tags); /** New id with additional tag values. */ PlaceholderId withTags(Map<String, String> tags); /** * New id with an additional tag factory. * @param factory * the factory to use to generate the values for the tag */ PlaceholderId withTagFactory(TagFactory factory); /** * New id with additional tag factories. * @param factories * a collection of factories for producing values for the tags */ PlaceholderId withTagFactories(Iterable<TagFactory> factories); /** * Invokes each of the associated tag factories to produce a Id based on the * runtime context available when this method is invoked. If an associated * TagFactory produces a non-null Tag, then the returned Id will have that * Tag associated with it. * * @return an Id that has the same name as this id and the resolved tag values attached */ Id resolveToId(); }
pstout/spectator
spectator-ext-placeholders/src/main/java/com/netflix/spectator/placeholders/PlaceholderId.java
Java
apache-2.0
2,369
# Copyright 2022 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # """add tenant_id to lcm_subscriptions and lcm_op_occs Revision ID: d6ae359ab0d6 Revises: 3ff50553e9d3 Create Date: 2022-01-06 13:35:53.868106 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'd6ae359ab0d6' down_revision = '3ff50553e9d3' def upgrade(active_plugins=None, options=None): op.add_column('vnf_lcm_subscriptions', sa.Column('tenant_id', sa.String(length=64), nullable=False)) op.add_column('vnf_lcm_op_occs', sa.Column('tenant_id', sa.String(length=64), nullable=False))
stackforge/tacker
tacker/db/migration/alembic_migrations/versions/d6ae359ab0d6_add_tenant_id_to_lcm_subscriptions_and_.py
Python
apache-2.0
1,237
# Prunus brachypoda var. eglandulosa W.C.Cheng VARIETY #### Status DOUBTFUL #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Prunus/Prunus brachypoda/Prunus brachypoda eglandulosa/README.md
Markdown
apache-2.0
202
/* * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * * Any CSS file within this directory can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the top of the * compiled file, but it's generally better to create a new file per style scope. * *= require imms.bootstrap.pack *= require imms.datatable.pack *= require_self */
arief-hidayat/imms-bootstrap
grails-app/assets/stylesheets/application.css
CSS
apache-2.0
466
/* * Copyright 2014 - 2016 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.driver; import io.aeron.driver.media.ReceiveChannelEndpoint; import io.aeron.driver.media.UdpChannel; import org.agrona.concurrent.status.ReadablePosition; import java.util.IdentityHashMap; import java.util.Map; /** * Subscription registration from a client used for liveness tracking */ public class SubscriptionLink implements DriverManagedResource { private final long registrationId; private final long clientLivenessTimeoutNs; private final int streamId; private final boolean isReliable; private final String channelUri; private final ReceiveChannelEndpoint channelEndpoint; private final AeronClient aeronClient; private final Map<PublicationImage, ReadablePosition> positionByImageMap = new IdentityHashMap<>(); private final IpcPublication ipcPublication; private final ReadablePosition ipcPublicationSubscriberPosition; private final UdpChannel spiedChannel; private NetworkPublication spiedPublication = null; private ReadablePosition spiedPosition = null; private boolean reachedEndOfLife = false; public SubscriptionLink( final long registrationId, final ReceiveChannelEndpoint channelEndpoint, final int streamId, final String channelUri, final AeronClient aeronClient, final long clientLivenessTimeoutNs, final boolean isReliable) { this.registrationId = registrationId; this.channelEndpoint = channelEndpoint; this.streamId = streamId; this.channelUri = channelUri; this.aeronClient = aeronClient; this.ipcPublication = null; this.ipcPublicationSubscriberPosition = null; this.spiedChannel = null; this.clientLivenessTimeoutNs = clientLivenessTimeoutNs; this.isReliable = isReliable; } public SubscriptionLink( final long registrationId, final int streamId, final String channelUri, final IpcPublication ipcPublication, final ReadablePosition subscriberPosition, final AeronClient aeronClient, final long clientLivenessTimeoutNs) { this.registrationId = registrationId; this.channelEndpoint = null; // will prevent matches between PublicationImages and IpcPublications this.streamId = streamId; this.channelUri = channelUri; this.aeronClient = aeronClient; this.ipcPublication = ipcPublication; ipcPublication.incRef(); this.ipcPublicationSubscriberPosition = subscriberPosition; this.spiedChannel = null; this.clientLivenessTimeoutNs = clientLivenessTimeoutNs; this.isReliable = true; } public SubscriptionLink( final long registrationId, final UdpChannel spiedChannel, final int streamId, final String channelUri, final AeronClient aeronClient, final long clientLivenessTimeoutNs) { this.registrationId = registrationId; this.channelEndpoint = null; this.streamId = streamId; this.channelUri = channelUri; this.aeronClient = aeronClient; this.ipcPublication = null; this.ipcPublicationSubscriberPosition = null; this.spiedChannel = spiedChannel; this.clientLivenessTimeoutNs = clientLivenessTimeoutNs; this.isReliable = true; } public long registrationId() { return registrationId; } public ReceiveChannelEndpoint channelEndpoint() { return channelEndpoint; } public int streamId() { return streamId; } public String channelUri() { return channelUri; } public boolean isReliable() { return isReliable; } public boolean matches(final ReceiveChannelEndpoint channelEndpoint, final int streamId) { return channelEndpoint == this.channelEndpoint && streamId == this.streamId; } public boolean matches(final NetworkPublication publication) { boolean result = false; if (null != spiedChannel) { result = streamId == publication.streamId() && publication.sendChannelEndpoint().udpChannel().canonicalForm().equals(spiedChannel.canonicalForm()); } return result; } public void addImage(final PublicationImage image, final ReadablePosition position) { positionByImageMap.put(image, position); } public void removeImage(final PublicationImage image) { positionByImageMap.remove(image); } public void addSpiedPublication(final NetworkPublication publication, final ReadablePosition position) { spiedPublication = publication; spiedPosition = position; } public void removeSpiedPublication() { spiedPublication = null; spiedPosition = null; } public void close() { positionByImageMap.forEach(PublicationImage::removeSubscriber); if (null != ipcPublication) { ipcPublication.removeSubscription(ipcPublicationSubscriberPosition); ipcPublication.decRef(); } else if (null != spiedPublication) { spiedPublication.removeSpyPosition(spiedPosition); } } public void onTimeEvent(final long time, final DriverConductor conductor) { if (time > (aeronClient.timeOfLastKeepalive() + clientLivenessTimeoutNs)) { reachedEndOfLife = true; conductor.cleanupSubscriptionLink(SubscriptionLink.this); } } public boolean hasReachedEndOfLife() { return reachedEndOfLife; } public void timeOfLastStateChange(final long time) { // not set this way } public long timeOfLastStateChange() { return aeronClient.timeOfLastKeepalive(); } public void delete() { close(); } }
tbrooks8/Aeron
aeron-driver/src/main/java/io/aeron/driver/SubscriptionLink.java
Java
apache-2.0
6,539
/* */ package com.webbuilder.interact; /* */ /* */ import com.webbuilder.controls.Query; /* */ import com.webbuilder.utils.CompressUtil; /* */ import com.webbuilder.utils.DateUtil; /* */ import com.webbuilder.utils.DbUtil; /* */ import com.webbuilder.utils.FileUtil; /* */ import com.webbuilder.utils.StringUtil; /* */ import com.webbuilder.utils.SysUtil; /* */ import com.webbuilder.utils.WebUtil; /* */ import com.webbuilder.utils.XMLParser; /* */ import java.awt.Color; /* */ import java.awt.Graphics; /* */ import java.awt.image.BufferedImage; /* */ import java.io.File; /* */ import java.io.FileInputStream; /* */ import java.io.InputStream; /* */ import java.io.PrintWriter; /* */ import java.sql.Connection; /* */ import java.sql.PreparedStatement; /* */ import java.sql.Timestamp; /* */ import java.util.Calendar; /* */ import java.util.Date; /* */ import java.util.HashMap; /* */ import java.util.HashSet; /* */ import java.util.Iterator; /* */ import javax.imageio.ImageIO; /* */ import javax.servlet.http.HttpServletRequest; /* */ import javax.servlet.http.HttpServletResponse; /* */ import javax.servlet.http.HttpSession; /* */ import javax.swing.Icon; /* */ import javax.swing.filechooser.FileSystemView; /* */ import org.dom4j.Attribute; /* */ import org.dom4j.Document; /* */ import org.dom4j.Element; /* */ import org.json.JSONArray; /* */ import org.json.JSONObject; /* */ /* */ public class Explorer /* */ { /* */ public void getRcvFilter(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 42 */ String find = StringUtil.fetchString(request, "findCombo"); /* */ /* 44 */ if (!StringUtil.isEmpty(find)) { /* 45 */ request.setAttribute("findValue", "%" + find + "%"); /* 46 */ String sql = " and WB_NAME like {?findValue?}"; /* 47 */ request.setAttribute("whereSql", sql); /* */ } else { /* 49 */ DbUtil.getDefaultWhere(request, response, "WB_DATE,WB_CODE=b", /* 50 */ false); /* */ } /* */ } /* */ /* */ public void sendFile(HttpServletRequest request, HttpServletResponse response) throws Exception { /* 55 */ Connection conn = DbUtil.fetchConnection(request, request.getAttribute( /* 56 */ "sys.jndi").toString()); /* 57 */ String depts = request.getAttribute("WB_RDEPT").toString(); /* 58 */ String roles = request.getAttribute("WB_RROLE").toString(); /* 59 */ String users = request.getAttribute("WB_RUSER").toString(); /* 60 */ String scope = request.getAttribute("sys.scope").toString(); /* 61 */ String dbType = request.getAttribute("sys.dbType").toString(); /* 62 */ HashSet userList = new HashSet(); /* */ /* 64 */ userList = DbUtil.getUserList(conn, dbType, scope, depts, roles, users); /* 65 */ conn.setAutoCommit(false); /* */ try { /* 67 */ PreparedStatement stm = null; /* 68 */ int k = 0; int l = userList.size(); /* 69 */ boolean commitAll = false; boolean added = false; /* 70 */ stm = conn /* 71 */ .prepareStatement("insert into WB_FILERECEIVE values(?,?,?,?,null)"); /* */ try { /* 73 */ stm.setString(1, scope); /* 74 */ stm.setTimestamp(2, /* 75 */ new Timestamp(DateUtil.stringToStdDate( /* 75 */ request.getAttribute("sys.now").toString()).getTime())); /* 76 */ stm.setString(3, request.getAttribute("sys.code").toString()); /* 77 */ while ( userList.iterator().hasNext()) { String s=userList.iterator().next().toString(); /* 78 */ k++; /* 79 */ stm.setString(4, s); /* 80 */ stm.addBatch(); /* 81 */ if (!added) /* 82 */ added = true; /* 83 */ if (k % 1000 == 0) { /* 84 */ if (k == l) /* 85 */ commitAll = true; /* 86 */ stm.executeBatch(); /* */ } /* */ } /* 89 */ if ((added) && (!commitAll)) /* 90 */ stm.executeBatch(); /* */ } finally { /* 92 */ DbUtil.closeStatement(stm); /* */ } /* 94 */ conn.commit(); /* */ } catch (Exception e) { /* 96 */ conn.rollback(); /* 97 */ throw new Exception(e); /* */ } finally { /* 99 */ conn.setAutoCommit(true); /* */ } /* */ } /* */ /* */ private String createUserDir(String root) throws Exception { /* 104 */ Date dt = new Date(); /* 105 */ String y = "y" + Integer.toString(DateUtil.yearOf(dt)); /* 106 */ String d = "d" + Integer.toString(DateUtil.dayOfYear(dt)); /* 107 */ String h = "h" + Integer.toString(DateUtil.hourOfDay(dt)); /* 108 */ Calendar cal = Calendar.getInstance(); /* 109 */ cal.setTime(dt); /* 110 */ int m = cal.get(12); /* 111 */ h = h + "m" + Integer.toString(m / 10); /* 112 */ String rel = y + "/" + d + "/" + h + "/"; /* 113 */ File file = FileUtil.getUniqueFile(new File(root + "/" + rel + "s" + /* 114 */ DateUtil.formatDate(dt, "ssSSS"))); /* 115 */ rel = rel + file.getName(); /* 116 */ File dir = new File(root + "/" + rel); /* 117 */ if (!dir.mkdirs()) /* 118 */ throw new Exception("不能创建目录。"); /* 119 */ return rel; /* */ } /* */ /* */ public void createPubDir(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 124 */ String root = request.getAttribute("sys.path").toString() + /* 125 */ "WEB-INF/myfile"; /* 126 */ String scope = request.getAttribute("sys.scope").toString(); /* */ /* 128 */ String sysPubDir = FileUtil.fetchPubDir(root, scope); /* 129 */ request.setAttribute("sysPubDir", sysPubDir); /* */ } /* */ /* */ public void createUserDir(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 134 */ String userPath = request.getAttribute("sys.rootpath").toString(); /* */ /* 136 */ if (StringUtil.isEmpty(userPath)) { /* 137 */ String root = request.getAttribute("sys.path").toString() + /* 138 */ "WEB-INF/myfile"; /* 139 */ String path = createUserDir(root); /* 140 */ Query query = new Query(); /* 141 */ query.setRequest(request); /* 142 */ query.type = "update"; /* 143 */ request.setAttribute("rootPath", path); /* 144 */ query.sql = "update WB_USER set ROOT_PATH={?rootPath?} where USERNAME={?sys.user?}"; /* 145 */ query.jndi = StringUtil.fetchString(request, "sys.jndi"); /* 146 */ query.setName("query.updateUser"); /* 147 */ query.create(); /* 148 */ request.getSession(false).setAttribute("sys.rootpath", /* 149 */ root + "/" + path); /* 150 */ request.setAttribute("sys.rootpath", root + "/" + path); /* */ } else { /* 152 */ File dir = new File(userPath); /* 153 */ if ((!dir.exists()) && (!dir.mkdirs())) /* 154 */ throw new Exception("不能创建用户目录。"); /* */ } /* */ } /* */ /* */ public void setOrder(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 160 */ JSONArray files = new JSONArray(request.getParameter("orderTree")); /* 161 */ int j = files.length(); /* 162 */ if (j == 0) /* 163 */ return; /* 164 */ File dir = new File(request.getParameter("orderDir")); /* */ /* 168 */ HashMap hashMap = new HashMap(); /* */ /* 170 */ XMLParser mapXml = new XMLParser(FileUtil.getUserIndex(dir, request.getAttribute( /* 171 */ "sys.scope").toString(), false)); /* 172 */ Element root = mapXml.document.getRootElement(); /* 173 */ Iterator iterator = root.elementIterator(); /* 174 */ while (iterator.hasNext()) { /* 175 */ Element el = (Element)iterator.next(); /* 176 */ hashMap.put(el.attribute("name").getText(), el); /* */ } /* 178 */ for (int i = 0; i < j; i++) { /* 179 */ String name = new JSONObject(files.getString(i)).getString("filename"); /* 180 */ Element el = (Element)hashMap.get(name); /* 181 */ if (el != null) { /* 182 */ root.add(el.createCopy()); /* 183 */ root.remove(el); /* */ } /* */ } /* 186 */ mapXml.save(); /* */ } /* */ /* */ public void getOrder(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 195 */ StringBuilder buf = new StringBuilder(); /* 196 */ boolean added = false; /* */ /* 198 */ buf.append("["); /* 199 */ File file = new File(request.getParameter("dir")); /* 200 */ File mapFile = FileUtil.getUserIndex(file, request.getAttribute("sys.scope") /* 201 */ .toString(), false); /* 202 */ if (mapFile.exists()) { /* 203 */ XMLParser mapXml = new XMLParser(mapFile); /* 204 */ Element el = mapXml.document.getRootElement(); /* 205 */ if (el != null) { /* 206 */ Iterator iterator = el.elementIterator(); /* 207 */ while (iterator.hasNext()) { /* 208 */ el = (Element)iterator.next(); /* 209 */ if (added) /* 210 */ buf.append(","); /* */ else /* 212 */ added = true; /* 213 */ buf.append("{text:\""); /* 214 */ String text = StringUtil.replaceParameters(request, el.attribute( /* 215 */ "caption").getValue()); /* 216 */ String name = el.attribute("name").getValue(); /* 217 */ if (StringUtil.isEmpty(text)) /* 218 */ text = name; /* 219 */ buf.append(StringUtil.toExpress(text)); /* 220 */ text = el.attribute("icon").getValue(); /* 221 */ if (!StringUtil.isEmpty(text)) { /* 222 */ buf.append("\",iconCls:\""); /* 223 */ buf.append(text); /* */ } /* 225 */ buf.append("\",filename:\""); /* 226 */ buf.append(name); /* 227 */ buf.append("\",leaf:true}"); /* */ } /* */ } /* */ } /* 231 */ buf.append("]"); /* 232 */ response.getWriter().print(buf); /* */ } /* */ /* */ public void getProperty(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 243 */ File file = new File(request.getParameter("fileName")); /* 244 */ File mapFile = FileUtil.getUserIndex(file.getParentFile(), request /* 245 */ .getAttribute("sys.scope").toString(), false); /* 246 */ if (mapFile.exists()) { /* 247 */ String fileName = file.getName(); /* 248 */ XMLParser mapXml = new XMLParser(mapFile); /* 249 */ Element el = mapXml.document.getRootElement(); /* 250 */ if (el != null) { /* 251 */ Iterator iterator = el.elementIterator(); /* 252 */ while (iterator.hasNext()) { /* 253 */ el = (Element)iterator.next(); /* 254 */ if (!StringUtil.isSame(el.attribute("name").getText(), /* 255 */ fileName)) continue; /* 256 */ StringBuilder buf = new StringBuilder(); /* 257 */ buf.append("{fileCaption:\""); /* 258 */ Attribute attr = el.attribute("caption"); /* 259 */ if (attr != null) /* 260 */ buf.append(StringUtil.toExpress(attr.getText())); /* 261 */ buf.append("\",fileRole:\""); /* 262 */ attr = el.attribute("role"); /* 263 */ if (attr != null) /* 264 */ buf.append(StringUtil.toExpress(attr.getText())); /* 265 */ buf.append("\",fileIcon:\""); /* 266 */ attr = el.attribute("icon"); /* 267 */ if (attr != null) /* 268 */ buf.append(attr.getText()); /* 269 */ buf.append("\",fileHint:\""); /* 270 */ attr = el.attribute("hint"); /* 271 */ if (attr != null) /* 272 */ buf.append(attr.getText()); /* 273 */ buf.append("\",fileHidden:\""); /* 274 */ attr = el.attribute("hidden"); /* 275 */ if (attr != null) /* 276 */ buf.append(StringUtil.toExpress(attr.getText())); /* */ else /* 278 */ buf.append("0"); /* 279 */ buf.append("\"}"); /* 280 */ response.getWriter().print(buf); /* 281 */ return; /* */ } /* */ } /* */ } /* */ } /* */ /* */ public void setPropertyCopy(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 290 */ innerSetProperty(request, response, true); /* */ } /* */ /* */ public void setProperty(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 295 */ innerSetProperty(request, response, false); /* */ } /* */ /* */ private void innerSetProperty(HttpServletRequest request, HttpServletResponse response, boolean createCopy) /* */ throws Exception /* */ { /* 304 */ String caption = request.getParameter("fileCaption"); /* 305 */ String role = request.getParameter("fileRole"); /* 306 */ String icon = request.getParameter("fileIcon"); /* 307 */ String hint = request.getParameter("fileHint"); /* 308 */ String hidden = request.getParameter("fileHidden"); /* 309 */ JSONArray files = new JSONArray(request.getParameter("setFile")); /* 310 */ HashMap map = new HashMap(); /* */ /* 313 */ File file = new File(files.getString(0)); /* 314 */ File dir = file.getParentFile(); /* 315 */ XMLParser mapXml = new XMLParser(FileUtil.getUserIndex(dir, request.getAttribute( /* 316 */ "sys.scope").toString(), createCopy)); /* 317 */ Element root = mapXml.document.getRootElement(); /* 318 */ if (root != null) { /* 319 */ Iterator iterator = root.elementIterator(); /* 320 */ while (iterator.hasNext()) { /* 321 */ Element el = (Element)iterator.next(); /* 322 */ String name = el.attribute("name").getText(); /* 323 */ file = new File(dir, name); /* 324 */ if ((!file.exists()) || (map.containsKey(name))) /* 325 */ root.remove(el); /* */ else /* 327 */ map.put(name, el); /* */ } /* */ } else { /* 330 */ root = mapXml.document.addElement("map"); /* 331 */ }int j = files.length(); /* 332 */ for (int i = 0; i < j; i++) { /* 333 */ String name = FileUtil.extractFileName(files.getString(i)); /* 334 */ Element el = (Element)map.get(name); /* 335 */ if (el == null) { /* 336 */ el = root.addElement("file"); /* 337 */ el.addAttribute("name", name); /* 338 */ el.addAttribute("caption", caption); /* 339 */ el.addAttribute("role", role); /* 340 */ el.addAttribute("icon", icon); /* 341 */ el.addAttribute("hint", hint); /* 342 */ el.addAttribute("hidden", hidden); /* */ } else { /* 344 */ el.attribute("name").setText(name); /* 345 */ el.attribute("caption").setText(caption); /* 346 */ el.attribute("role").setText(role); /* 347 */ el.attribute("icon").setText(icon); /* 348 */ el.attribute("hint").setText(hint); /* 349 */ el.attribute("hidden").setText(hidden); /* */ } /* */ } /* 352 */ mapXml.save(); /* */ } /* */ /* */ public void importFile(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 357 */ String importDir = request.getAttribute("importDir").toString(); /* 358 */ FileUtil.checkRight(request, new File(importDir)); /* 359 */ InputStream stream = (InputStream)request.getAttribute("importFile"); /* 360 */ String fn = request.getAttribute("importFile__file").toString(); /* */ /* 362 */ if (StringUtil.isEqual(request.getAttribute("importType").toString(), /* 363 */ "1")) { /* 364 */ if (StringUtil.isSame(FileUtil.extractFileExt(fn), "zip")) /* 365 */ CompressUtil.unzip(stream, new File(importDir), /* 366 */ (String)request.getAttribute("sys.fileCharset")); /* */ else /* 368 */ throw new Exception("请选择一个zip格式的压缩文件。"); /* */ } /* 370 */ else FileUtil.saveInputStreamToFile(stream, new File(importDir, fn)); /* */ } /* */ /* */ public void exportFile(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 375 */ String[] list = StringUtil.split(request.getParameter("exportFiles"), /* 376 */ "|"); /* 378 */ int i = 0; int j = list.length; /* */ /* 380 */ File[] files = new File[j]; /* */ /* 382 */ for (i = 0; i < j; i++) { /* 383 */ WebUtil.recordLog(request, "explorer导出:" + list[i], 1); /* 384 */ files[i] = new File(list[i]); /* 385 */ FileUtil.checkRight(request, files[i]); /* */ } /* */ String fileName; /* 387 */ if (j == 1) { /* 388 */ fileName = FileUtil.extractFileNameNoExt(files[0].getName()); /* */ } else { /* 390 */ File parentFile = files[0].getParentFile(); /* 391 */ fileName = ""; /* 392 */ if (parentFile != null) /* 393 */ fileName = FileUtil.extractFileNameNoExt(parentFile.getName()); /* 394 */ if (StringUtil.isEmpty(fileName)) /* 395 */ fileName = "data"; /* */ } /* 397 */ boolean useZip = (StringUtil.isEqual(request.getParameter("exportType"), "1")) || /* 398 */ (j > 1) || (files[0].isDirectory()); /* 399 */ response.reset(); /* 400 */ if (!useZip) { /* 401 */ response.setHeader("content-length", Long.toString(files[0] /* 402 */ .length())); /* 403 */ fileName = files[0].getName(); /* */ } else { /* 405 */ fileName = fileName + ".zip"; /* 406 */ }response.setHeader("content-type", "application/force-download"); /* 407 */ String charset = (String)request.getAttribute("sys.fileCharset"); /* 408 */ response.setHeader("content-disposition", "attachment;filename=" + /* 409 */ WebUtil.getFileName(fileName, charset)); /* 410 */ if (useZip) { /* 411 */ CompressUtil.zip(files, response.getOutputStream(), /* 412 */ (String)request.getAttribute("sys.fileCharset")); /* */ } else { /* 414 */ FileInputStream inputStream = new FileInputStream(files[0]); /* 415 */ SysUtil.inputStreamToOutputStream(inputStream, response /* 416 */ .getOutputStream()); /* 417 */ inputStream.close(); /* */ } /* */ } /* */ /* */ public void exportFile2(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* */ String root = request.getAttribute("sys.path").toString() + "WEB-INF/myfile.doc"; /* 378 */ int i = 0; int j = 1; /* */ /* 380 */ File[] files = new File[j]; /* */ /* 382 */ /* 383 */ WebUtil.recordLog(request, "explorer导出:" + root, 1); /* 384 */ files[i] = new File(root); /* 385 */ FileUtil.checkRight(request, files[i]); /* */ /* */ String fileName; /* 387 */ if (j == 1) { /* 388 */ fileName = FileUtil.extractFileNameNoExt(files[0].getName()); /* */ } else { /* 390 */ File parentFile = files[0].getParentFile(); /* 391 */ fileName = ""; /* 392 */ if (parentFile != null) /* 393 */ fileName = FileUtil.extractFileNameNoExt(parentFile.getName()); /* 394 */ if (StringUtil.isEmpty(fileName)) /* 395 */ fileName = "data"; /* */ } /* 397 */ boolean useZip = (StringUtil.isEqual(request.getParameter("exportType"), "1")) || /* 398 */ (j > 1) || (files[0].isDirectory()); /* 399 */ response.reset(); /* 400 */ if (!useZip) { /* 401 */ response.setHeader("content-length", Long.toString(files[0] /* 402 */ .length())); /* 403 */ fileName = files[0].getName(); /* */ } else { /* 405 */ fileName = fileName + ".zip"; /* 406 */ }response.setHeader("content-type", "application/force-download"); /* 407 */ String charset = (String)request.getAttribute("sys.fileCharset"); /* 408 */ response.setHeader("content-disposition", "attachment;filename=" + /* 409 */ WebUtil.getFileName(fileName, charset)); /* 410 */ if (useZip) { /* 411 */ CompressUtil.zip(files, response.getOutputStream(), /* 412 */ (String)request.getAttribute("sys.fileCharset")); /* */ } else { /* 414 */ FileInputStream inputStream = new FileInputStream(files[0]); /* 415 */ SysUtil.inputStreamToOutputStream(inputStream, response /* 416 */ .getOutputStream()); /* 417 */ inputStream.close(); /* */ } /* */ } /* */ /* */ public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 423 */ String fileName = request.getParameter("file"); /* */ try { /* 425 */ Runtime.getRuntime().exec(fileName); /* */ } catch (Exception e) { /* 427 */ throw new Exception("执行 \"" + FileUtil.extractFileName(fileName) + /* 428 */ "\"错误。"); /* */ } /* */ } /* */ /* */ public void openFile(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 434 */ FileUtil.checkRight(request, new File(request.getParameter("file"))); /* 435 */ String charset = request.getParameter("charset"); /* */ /* 437 */ if (StringUtil.isEmpty(charset)) /* 438 */ charset = (String)request.getAttribute("sys.charset"); /* 439 */ response.getWriter().print( /* 440 */ FileUtil.readText(request.getParameter("file"), charset)); /* */ } /* */ /* */ public void saveFile(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 445 */ FileUtil.checkRight(request, new File(request.getParameter("file"))); /* 446 */ String charset = request.getParameter("charset"); /* 447 */ if (StringUtil.isEmpty(charset)) /* 448 */ charset = (String)request.getAttribute("sys.charset"); /* 449 */ FileUtil.writeText(request.getParameter("file"), request /* 450 */ .getParameter("text"), charset); /* */ } /* */ /* */ public void deleteFiles(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 457 */ JSONArray files = new JSONArray(request.getParameter("files")); /* 458 */ int j = files.length(); /* */ /* 460 */ for (int i = 0; i < j; i++) { /* 461 */ String fileName = files.getString(i); /* 462 */ File file = new File(fileName); /* 463 */ FileUtil.checkRight(request, file); /* 464 */ WebUtil.recordLog(request, "explorer删除:" + fileName, 1); /* 465 */ if (file.isDirectory()) /* 466 */ FileUtil.deleteFolder(file); /* 467 */ else if (!file.delete()) /* 468 */ throw new Exception("不能删除文件 \"" + file.getName() + "\"。"); /* */ } /* */ } /* */ /* */ public void pasteFiles(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 474 */ String filesParam = request.getParameter("files"); /* 475 */ String dir = request.getParameter("dir") + "/"; /* 476 */ File destFile = new File(dir); /* 477 */ JSONArray files = new JSONArray(filesParam); /* 478 */ boolean isCut = StringUtil.getStringBool(request.getParameter("isCut")); /* 479 */ int j = files.length(); /* */ /* 481 */ for (int i = 0; i < j; i++) { /* 482 */ File file = new File(files.getString(i)); /* 483 */ File dest = new File(dir + file.getName()); /* 484 */ FileUtil.checkRight(request, file); /* 485 */ FileUtil.checkRight(request, dest); /* 486 */ WebUtil.recordLog(request, "explorer贴粘:" + (isCut ? "剪切" : "复制") + /* 487 */ "," + files.getString(i) + "至" + dir, 1); /* 488 */ if (file.isDirectory()) { /* 489 */ if (FileUtil.isSubFolder(file, destFile)) /* 490 */ throw new Exception("不能复制相同的文件夹。"); /* 491 */ FileUtil.copyFolder(file, dest, true, isCut); /* */ } else { /* 493 */ FileUtil.copyFile(file, dest, true, isCut); /* */ } /* */ } /* */ } /* */ /* */ public void rename(HttpServletRequest request, HttpServletResponse response) throws Exception { /* 499 */ String fileName = request.getParameter("fileName"); /* 500 */ String rename = request.getParameter("fileValue"); /* 501 */ File file = new File(fileName); /* 502 */ FileUtil.checkRight(request, file); /* 503 */ if ((rename.indexOf("/") > -1) || /* 504 */ (rename.indexOf("\\") > -1) || /* 505 */ (!file.renameTo( /* 506 */ new File(FileUtil.extractFilePath(fileName) + /* 506 */ rename)))) /* 507 */ throw new Exception("重命名失败。"); /* */ } /* */ /* */ public void newFile(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 512 */ String name = request.getParameter("fileValue"); /* 513 */ String fileName = request.getParameter("dir") + "/" + name; /* 514 */ String type = request.getParameter("type"); /* */ /* 517 */ File file = new File(fileName); /* 518 */ FileUtil.checkRight(request, file); /* */ boolean flag; /* */ /* 519 */ if (type.equals("dir")) /* 520 */ flag = file.mkdir(); /* */ else /* 522 */ flag = file.createNewFile(); /* 523 */ if (!flag) /* 524 */ throw new Exception("不能创建\"" + name + "\""); /* */ } /* */ /* */ public void getPubDir(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 529 */ String dir = request.getParameter("dir"); /* 530 */ StringBuilder buf = new StringBuilder(); /* 531 */ String root = request.getAttribute("sys.path").toString() + /* 532 */ "WEB-INF/myfile"; /* 533 */ String scope = request.getAttribute("sys.scope").toString(); /* */ /* 535 */ if (StringUtil.isEmpty(dir)) { /* 536 */ loadPubDir(FileUtil.fetchPubDir(root, scope), buf); /* */ } else { /* 538 */ File fl = new File(dir); /* 539 */ FileUtil.checkRight(request, fl); /* 540 */ File[] files = fl.listFiles(); /* 541 */ FileUtil.sortFiles(files); /* 542 */ loadFilesBuf(files, buf); /* */ } /* 544 */ response.getWriter().print(buf); /* */ } /* */ /* */ public void getUserDir(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 549 */ String dir = request.getParameter("dir"); /* 550 */ StringBuilder buf = new StringBuilder(); /* */ /* 552 */ if (StringUtil.isEmpty(dir)) { /* 553 */ loadUserDir((String)request.getAttribute("sys.rootpath"), buf); /* */ } else { /* 555 */ File fl = new File(dir); /* 556 */ FileUtil.checkRight(request, fl); /* 557 */ File[] files = fl.listFiles(); /* 558 */ FileUtil.sortFiles(files); /* 559 */ loadFilesBuf(files, buf); /* */ } /* 561 */ response.getWriter().print(buf); /* */ } /* */ /* */ public void getDir(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 566 */ String dir = request.getParameter("dir"); /* 567 */ boolean appRoot = StringUtil.getStringBool(request /* 568 */ .getParameter("setAppRoot")); /* 569 */ StringBuilder buf = new StringBuilder(); /* */ /* 571 */ if (StringUtil.isEmpty(dir)) { /* 572 */ if ((appRoot) || (!loadFilesBuf(File.listRoots(), buf))) { /* 573 */ buf = new StringBuilder(); /* 574 */ loadAppDir((String)request.getAttribute("sys.path"), buf); /* */ } /* */ } else { /* 577 */ File[] files = new File(dir).listFiles(); /* 578 */ FileUtil.sortFiles(files); /* 579 */ loadFilesBuf(files, buf); /* */ } /* 581 */ response.getWriter().print(buf); /* */ } /* */ /* */ public void getFile(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 586 */ String dir = request.getParameter("dir"); /* 587 */ File dirFile = new File(dir); /* 588 */ FileUtil.checkRight(request, dirFile); /* 589 */ File[] files = dirFile.listFiles(); /* 590 */ if (files == null) { /* 591 */ response.getWriter().print("{total:0,row:[]}"); /* 592 */ return; /* */ } /* 594 */ FileUtil.sortFiles(files); /* 595 */ StringBuilder buf = new StringBuilder(); /* 596 */ FileSystemView fileView = FileSystemView.getFileSystemView(); /* 597 */ boolean isFirst = true; /* 598 */ String start = request.getParameter("start"); /* 599 */ String limit = request.getParameter("limit"); /* 600 */ int count = 0; /* */ int startValue; /* */ /* 602 */ if (start == null) /* 603 */ startValue = 1; /* */ else /* 605 */ startValue = Integer.parseInt(start) + 1; /* */ int limitValue; /* */ /* 606 */ if (limit == null) /* 607 */ limitValue = 2147483647 - startValue; /* */ else /* 609 */ limitValue = Integer.parseInt(limit); /* 610 */ int end = startValue + limitValue - 1; /* 611 */ buf.append("{total:"); /* 612 */ buf.append(files.length); /* 613 */ buf.append(",row:["); /* 614 */ for (File file : files) { /* 615 */ count++; /* 616 */ if (count < startValue) /* */ continue; /* 618 */ if (count > end) /* */ break; /* 620 */ if (isFirst) /* 621 */ isFirst = false; /* */ else /* 623 */ buf.append(","); /* 624 */ boolean isDir = file.isDirectory(); /* 625 */ buf.append("{filename:\""); /* 626 */ if (isDir) /* 627 */ buf.append("0"); /* */ else /* 629 */ buf.append("1"); /* 630 */ String fileName = file.getName(); /* 631 */ buf.append(fileName); /* 632 */ buf.append("\",size:"); /* 633 */ if (isDir) /* 634 */ buf.append(-1); /* */ else /* 636 */ buf.append(file.length()); /* 637 */ buf.append(",file:\""); /* 638 */ buf.append(StringUtil.replace(file.getAbsolutePath(), "\\", "/")); /* 639 */ buf.append("\",type:\""); /* 640 */ if (isDir) { /* 641 */ buf.append("0文件夹"); } else { /* */ String type; /* */ try { type = fileView.getSystemTypeDescription(file); /* */ } /* */ catch (Exception e) /* */ { /* */ /* 646 */ type = null; /* */ } /* 648 */ if (type != null) { /* 649 */ buf.append("1" + StringUtil.toExpress(type)); /* */ } else { /* 651 */ String ext = FileUtil.extractFileExt(fileName); /* 652 */ if (StringUtil.isEmpty(ext)) { /* 653 */ buf.append("1文件"); /* */ } else { /* 655 */ buf.append("1" + ext); /* 656 */ buf.append(" 文件"); /* */ } /* */ } /* */ } /* 660 */ buf.append("\",modifyTime:\""); /* 661 */ buf.append(DateUtil.dateToString(new Date(file.lastModified()))); /* 662 */ buf.append("\"}"); /* */ } /* 664 */ buf.append("]}"); /* 665 */ response.getWriter().print(buf); /* */ } /* */ /* */ public void getIcon(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 671 */ File file = new File(new String(request.getParameter("file") /* 671 */ .getBytes("ISO-8859-1"), "utf-8")); FileSystemView fileView = FileSystemView.getFileSystemView(); Icon icon = fileView.getSystemIcon(file); response.reset(); if (icon == null) { response.setContentType("image/gif"); InputStream is = new FileInputStream(request.getAttribute("sys.path") + "webbuilder/images/file.gif"); SysUtil.inputStreamToOutputStream(is, response.getOutputStream()); is.close(); } else { response.setContentType("image/jpeg"); int width = icon.getIconWidth(); int height = icon.getIconHeight(); BufferedImage image = new BufferedImage(width, height, 1); Graphics graphics = image.getGraphics(); graphics.setColor(Color.white); graphics.fillRect(0, 0, width, height); icon.paintIcon(null, graphics, 0, 0); ImageIO.write(image, "jpeg", response.getOutputStream()); graphics.dispose(); /* */ } /* */ } /* */ /* */ private void loadPubDir(String pubDir, StringBuilder buf) /* */ { /* 697 */ buf.append("["); /* 698 */ buf.append("{text:\"公共文件\",dir:\""); /* 699 */ buf.append(StringUtil.toExpress(pubDir)); /* 700 */ buf.append("\"}"); /* 701 */ buf.append("]"); /* */ } /* */ /* */ private void loadUserDir(String userDir, StringBuilder buf) { /* 705 */ buf.append("["); /* 706 */ buf.append("{text:\"我的文件\",dir:\""); /* 707 */ buf.append(StringUtil.toExpress(userDir)); /* 708 */ buf.append("\"}"); /* 709 */ buf.append("]"); /* */ } /* */ /* */ private void loadAppDir(String appDir, StringBuilder buf) { /* 713 */ String s = FileUtil.extractFileDir(appDir); /* 714 */ buf.append("["); /* 715 */ buf.append("{text:\""); /* 716 */ buf.append(StringUtil.toExpress(s)); /* 717 */ buf.append("\",dir:\""); /* 718 */ buf.append(StringUtil.toExpress(s)); /* 719 */ buf.append("\"}"); /* 720 */ buf.append("]"); /* */ } /* */ /* */ private boolean loadFilesBuf(File[] files, StringBuilder buf) { /* 724 */ boolean isOk = false; boolean isFirst = true; /* */ /* 727 */ buf.append("["); /* 728 */ for (File file : files) { /* 729 */ if (file.isDirectory()) { /* 730 */ isOk = true; /* 731 */ if (isFirst) /* 732 */ isFirst = false; /* */ else /* 734 */ buf.append(","); /* 735 */ buf.append("{text:\""); /* 736 */ String name = file.getName(); /* 737 */ String dir = StringUtil.replace(file.getAbsolutePath(), "\\", "/"); /* 738 */ if (StringUtil.isEmpty(name)) /* 739 */ name = FileUtil.extractFileDir(dir); /* 740 */ buf.append(StringUtil.toExpress(name)); /* 741 */ buf.append("\",dir:\""); /* 742 */ buf.append(StringUtil.replace(dir, "\\", "/")); /* 743 */ if (FileUtil.hasSubFile(file, true)) /* 744 */ buf.append("\"}"); /* */ else /* 746 */ buf.append("\",leaf:true,iconCls:\"icon_folder\"}"); /* */ } /* */ } /* 749 */ buf.append("]"); /* 750 */ return isOk; /* */ } /* */ } /* Location: Z:\EXT\WebBuilderServer (1)\WEB-INF\lib\webbuilder2.jar * Qualified Name: com.webbuilder.interact.Explorer * JD-Core Version: 0.6.0 */
fuhongliang/partmanager
src/com/webbuilder/interact/Explorer.java
Java
apache-2.0
36,158
package org.fax4j.spi.email; import java.io.IOException; import javax.mail.Message; import javax.mail.Transport; import org.fax4j.FaxException; import org.fax4j.FaxJob; import org.fax4j.common.Logger; import org.fax4j.spi.AbstractFax4JClientSpi; import org.fax4j.util.Connection; import org.fax4j.util.ReflectionHelper; /** * This class implements the fax client service provider interface.<br> * This parial implementation will invoke the requests by sending emails to a mail server that supports * conversion between email messages and fax messages.<br> * The mail SPI supports persistent connection to enable to reuse the same connection for all fax * operation invocations or to create a new connection for each fax operation invocation.<br> * By default the SPI will create a new connection for each operation invocation however the * <b>org.fax4j.spi.mail.persistent.connection</b> set to true will enable to reuse the connection.<br> * To set the user/password values of the mail connection the following 2 properties must be defined: * <b>org.fax4j.spi.mail.user.name</b> and <b>org.fax4j.spi.mail.password</b><br> * All properties defined in the fax4j configuration will be passed to the mail connection therefore it is * possible to define mail specific properties (see java mail for more info) in the fax4j properties.<br> * Implementing SPI class will have to implement the createXXXFaxJobMessage methods.<br> * These methods will return the message to be sent for that fax job operation. In case the method * returns null, this class will throw an UnsupportedOperationException exception. * <br> * The configuration of the fax4j framework is made up of 3 layers.<br> * The configuration is based on simple properties.<br> * Each layer overrides the lower layers by adding/changing the property values.<br> * The first layer is the internal fax4j.properties file located in the fax4j jar.<br> * This layer contains the preconfigured values for the fax4j framework and can be changed * by updating these properties in the higher layers.<br> * The second layer is the external fax4j.properties file that is located on the classpath.<br> * This file is optional and provides the ability to override the internal configuration for the * entire fax4j framework.<br> * The top most layer is the optional java.util.Properties object provided by the external classes * when creating a new fax client.<br> * These properties enable to override the configuration of the lower 2 layers.<br> * <br> * <b>SPI Status (Draft, Beta, Stable): </b>Stable<br> * <br> * Below table describes the configuration values relevant for this class.<br> * <b>Configuration:</b> * <table summary="" border="1"> * <tr> * <td>Name</td> * <td>Description</td> * <td>Preconfigured Value</td> * <td>Default Value</td> * <td>Mandatory</td> * </tr> * <tr> * <td>org.fax4j.spi.mail.persistent.connection</td> * <td>True to reuse the same mail connection for all fax activites, false to create a * new mail connection for each fax activity.</td> * <td>false</td> * <td>false</td> * <td>false</td> * </tr> * <tr> * <td>org.fax4j.spi.mail.connection.factory.class.name</td> * <td>The connection factory class name</td> * <td>org.fax4j.spi.email.MailConnectionFactoryImpl</td> * <td>org.fax4j.spi.email.MailConnectionFactoryImpl</td> * <td>false</td> * </tr> * <tr> * <td>org.fax4j.spi.mail.user.name</td> * <td>The mail account user name.</td> * <td>none</td> * <td>none</td> * <td>false</td> * </tr> * <tr> * <td>org.fax4j.spi.mail.password</td> * <td>The mail account password.</td> * <td>none</td> * <td>none</td> * <td>false</td> * </tr> * <tr> * <td>javax mail properties</td> * <td>Any of the javax mail properties can be defined in the fax4j properties.<br> * These properties will be passed to the java mail framework.</td> * <td>mail.transport.protocol=smtp<br> * mail.smtp.port=25</td> * <td>none</td> * <td>false</td> * </tr> * </table> * <br> * <b>Limitations:</b><br> * <ul> * <li>This SPI is based on the java mail infrastructure, therefore this SPI cannot * connect to mail servers through a proxy server. * <li>This SPI provides only partial implementation (this is an abstract class). * </ul> * <br> * <b>Dependencies:</b><br> * <ul> * <li>Required jar files: mail-1.4.jar, activation-1.1.jar * </ul> * <br> * * @author Sagie Gur-Ari * @version 1.12 * @since 0.1 */ public abstract class AbstractMailFaxClientSpi extends AbstractFax4JClientSpi { /** * The use persistent connection flag which defines if the SPI will use a new * connection for each request or will reuse the same connection */ private boolean usePersistentConnection; /**The mail connection factory*/ private MailConnectionFactory connectionFactory; /**The mail connection*/ private Connection<MailResourcesHolder> connection; /** * This class holds the SPI configuration constants. * * @author Sagie Gur-Ari * @version 1.03 * @since 0.1 */ public enum FaxClientSpiConfigurationConstants { /** * The use persistent connection property key which defines if the SPI will use a new * connection for each request or will reuse the same connection */ USE_PERSISTENT_CONNECTION_PROPERTY_KEY("org.fax4j.spi.mail.persistent.connection"), /**The connection factory class name*/ CONNECTION_FACTORY_CLASS_NAME_PROPERTY_KEY("org.fax4j.spi.mail.connection.factory.class.name"), /**The user name used to connect to the mail server*/ USER_NAME_PROPERTY_KEY("org.fax4j.spi.mail.user.name"), /**The password used to connect to the mail server*/ PASSWORD_PROPERTY_KEY("org.fax4j.spi.mail.password"); /**The string value*/ private String value; /** * This is the class constructor. * * @param value * The string value */ private FaxClientSpiConfigurationConstants(String value) { this.value=value; } /** * This function returns the string value. * * @return The string value */ @Override public final String toString() { return this.value; } } /** * This is the default constructor. */ public AbstractMailFaxClientSpi() { super(); } /** * This function initializes the fax client SPI. */ @Override protected void initializeImpl() { //get logger Logger logger=this.getLogger(); //get use persistent connection value this.usePersistentConnection=Boolean.parseBoolean(this.getConfigurationValue(FaxClientSpiConfigurationConstants.USE_PERSISTENT_CONNECTION_PROPERTY_KEY)); logger.logDebug(new Object[]{"Using persistent connection: ",String.valueOf(this.usePersistentConnection)},null); //setup connection factory String className=this.getConfigurationValue(FaxClientSpiConfigurationConstants.CONNECTION_FACTORY_CLASS_NAME_PROPERTY_KEY); this.connectionFactory=this.createMailConnectionFactoryImpl(className); if(this.connectionFactory==null) { throw new FaxException("Mail connection factory is not available."); } } /** * Creates and returns the mail connection factory. * * @param className * The connection factory class name * @return The mail connection factory */ protected final MailConnectionFactory createMailConnectionFactoryImpl(String className) { String factoryClassName=className; if(factoryClassName==null) { factoryClassName=MailConnectionFactoryImpl.class.getName(); } //create new instance MailConnectionFactory factory=(MailConnectionFactory)ReflectionHelper.createInstance(factoryClassName); //initialize factory.initialize(this); return factory; } /** * Releases the connection if open. * * @throws Throwable * Any throwable */ @Override protected void finalize() throws Throwable { //get reference Connection<MailResourcesHolder> mailConnection=this.connection; //release connection this.closeMailConnection(mailConnection); super.finalize(); } /** * Creates and returns the mail connection to be used to send the fax * via mail. * * @return The mail connection */ protected Connection<MailResourcesHolder> createMailConnection() { //create new connection Connection<MailResourcesHolder> mailConnection=this.connectionFactory.createConnection(); //log debug Logger logger=this.getLogger(); logger.logInfo(new Object[]{"Created mail connection."},null); return mailConnection; } /** * This function closes the provided mail connection. * * @param mailConnection * The mail connection to close * @throws IOException * Never thrown */ protected void closeMailConnection(Connection<MailResourcesHolder> mailConnection) throws IOException { if(mailConnection!=null) { //get logger Logger logger=this.getLogger(); //release connection logger.logInfo(new Object[]{"Closing mail connection."},null); mailConnection.close(); } } /** * Returns the mail connection to be used to send the fax * via mail. * * @return The mail connection */ protected Connection<MailResourcesHolder> getMailConnection() { Connection<MailResourcesHolder> mailConnection=null; if(this.usePersistentConnection) { synchronized(this) { if(this.connection==null) { //create new connection this.connection=this.createMailConnection(); } } //get connection mailConnection=this.connection; } else { //create new connection mailConnection=this.createMailConnection(); } return mailConnection; } /** * This function will send the mail message. * * @param faxJob * The fax job object containing the needed information * @param mailConnection * The mail connection (will be released if not persistent) * @param message * The message to send */ protected void sendMail(FaxJob faxJob,Connection<MailResourcesHolder> mailConnection,Message message) { if(message==null) { this.throwUnsupportedException(); } else { //get holder MailResourcesHolder mailResourcesHolder=mailConnection.getResource(); //get transport Transport transport=mailResourcesHolder.getTransport(); try { //send message message.saveChanges(); if(transport==null) { Transport.send(message,message.getAllRecipients()); } else { transport.sendMessage(message,message.getAllRecipients()); } } catch(Throwable throwable) { throw new FaxException("Unable to send message.",throwable); } finally { if(!this.usePersistentConnection) { try { //close connection this.closeMailConnection(mailConnection); } catch(Exception exception) { //log error Logger logger=this.getLogger(); logger.logInfo(new Object[]{"Error while releasing mail connection."},exception); } } } } } /** * This function will submit a new fax job.<br> * The fax job ID may be populated by this method in the provided * fax job object. * * @param faxJob * The fax job object containing the needed information */ @Override protected void submitFaxJobImpl(FaxJob faxJob) { //get connection Connection<MailResourcesHolder> mailConnection=this.getMailConnection(); //get holder MailResourcesHolder mailResourcesHolder=mailConnection.getResource(); //create message Message message=this.createSubmitFaxJobMessage(faxJob,mailResourcesHolder); //send message this.sendMail(faxJob,mailConnection,message); } /** * This function will suspend an existing fax job. * * @param faxJob * The fax job object containing the needed information */ @Override protected void suspendFaxJobImpl(FaxJob faxJob) { //get connection Connection<MailResourcesHolder> mailConnection=this.getMailConnection(); //get holder MailResourcesHolder mailResourcesHolder=mailConnection.getResource(); //create message Message message=this.createSuspendFaxJobMessage(faxJob,mailResourcesHolder); //send message this.sendMail(faxJob,mailConnection,message); } /** * This function will resume an existing fax job. * * @param faxJob * The fax job object containing the needed information */ @Override protected void resumeFaxJobImpl(FaxJob faxJob) { //get connection Connection<MailResourcesHolder> mailConnection=this.getMailConnection(); //get holder MailResourcesHolder mailResourcesHolder=mailConnection.getResource(); //create message Message message=this.createResumeFaxJobMessage(faxJob,mailResourcesHolder); //send message this.sendMail(faxJob,mailConnection,message); } /** * This function will cancel an existing fax job. * * @param faxJob * The fax job object containing the needed information */ @Override protected void cancelFaxJobImpl(FaxJob faxJob) { //get connection Connection<MailResourcesHolder> mailConnection=this.getMailConnection(); //get holder MailResourcesHolder mailResourcesHolder=mailConnection.getResource(); //create message Message message=this.createCancelFaxJobMessage(faxJob,mailResourcesHolder); //send message this.sendMail(faxJob,mailConnection,message); } /** * This function will create the message used to invoke the fax * job action.<br> * If this method returns null, the SPI will throw an UnsupportedOperationException. * * @param faxJob * The fax job object containing the needed information * @param mailResourcesHolder * The mail resources holder * @return The message to send (if null, the SPI will throw an UnsupportedOperationException) */ protected abstract Message createSubmitFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder); /** * This function will create the message used to invoke the fax * job action.<br> * If this method returns null, the SPI will throw an UnsupportedOperationException. * * @param faxJob * The fax job object containing the needed information * @param mailResourcesHolder * The mail resources holder * @return The message to send (if null, the SPI will throw an UnsupportedOperationException) */ protected abstract Message createSuspendFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder); /** * This function will create the message used to invoke the fax * job action.<br> * If this method returns null, the SPI will throw an UnsupportedOperationException. * * @param faxJob * The fax job object containing the needed information * @param mailResourcesHolder * The mail resources holder * @return The message to send (if null, the SPI will throw an UnsupportedOperationException) */ protected abstract Message createResumeFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder); /** * This function will create the message used to invoke the fax * job action.<br> * If this method returns null, the SPI will throw an UnsupportedOperationException. * * @param faxJob * The fax job object containing the needed information * @param mailResourcesHolder * The mail resources holder * @return The message to send (if null, the SPI will throw an UnsupportedOperationException) */ protected abstract Message createCancelFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder); }
ZhernakovMikhail/fax4j
src/main/java/org/fax4j/spi/email/AbstractMailFaxClientSpi.java
Java
apache-2.0
15,447
<html><!-- Created using the cpp_pretty_printer from the dlib C++ library. See http://dlib.net for updates. --><head><title>dlib C++ Library - quantum_computing_abstract.h</title></head><body bgcolor='white'><pre> <font color='#009900'>// Copyright (C) 2008 Davis E. King ([email protected]) </font><font color='#009900'>// License: Boost Software License See LICENSE.txt for the full license. </font><font color='#0000FF'>#undef</font> DLIB_QUANTUM_COMPUTINg_ABSTRACT_ <font color='#0000FF'>#ifdef</font> DLIB_QUANTUM_COMPUTINg_ABSTRACT_ <font color='#0000FF'>#include</font> <font color='#5555FF'>&lt;</font>complex<font color='#5555FF'>&gt;</font> <font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='../matrix.h.html'>../matrix.h</a>" <font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='../rand.h.html'>../rand.h</a>" <font color='#0000FF'>namespace</font> dlib <b>{</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>typedef</font> std::complex<font color='#5555FF'>&lt;</font><font color='#0000FF'><u>double</u></font><font color='#5555FF'>&gt;</font> qc_scalar_type; <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>class</font> <b><a name='quantum_register'></a>quantum_register</b> <b>{</b> <font color='#009900'>/*! INITIAL VALUE - num_bits() == 1 - state_vector().nr() == 2 - state_vector().nc() == 1 - state_vector()(0) == 1 - state_vector()(1) == 0 - probability_of_bit(0) == 0 - i.e. This register represents a single quantum bit and it is completely in the 0 state. WHAT THIS OBJECT REPRESENTS This object represents a set of quantum bits. !*/</font> <font color='#0000FF'>public</font>: <b><a name='quantum_register'></a>quantum_register</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - this object is properly initialized !*/</font> <font color='#0000FF'><u>int</u></font> <b><a name='num_bits'></a>num_bits</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns the number of quantum bits in this register !*/</font> <font color='#0000FF'><u>void</u></font> <b><a name='set_num_bits'></a>set_num_bits</b> <font face='Lucida Console'>(</font> <font color='#0000FF'><u>int</u></font> new_num_bits <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - 1 &lt;= new_num_bits &lt;= 30 ensures - #num_bits() == new_num_bits - #state_vector().nr() == 2^new_num_bits (i.e. the size of the state_vector is exponential in the number of bits in a register) - for all valid i: - probability_of_bit(i) == 0 !*/</font> <font color='#0000FF'><u>void</u></font> <b><a name='zero_all_bits'></a>zero_all_bits</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - for all valid i: - probability_of_bit(i) == 0 !*/</font> <font color='#0000FF'><u>void</u></font> <b><a name='append'></a>append</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> quantum_register<font color='#5555FF'>&amp;</font> reg <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - #num_bits() == num_bits() + reg.num_bits() - #this-&gt;state_vector() == tensor_product(this-&gt;state_vector(), reg.state_vector()) - The original bits in *this become the high order bits of the resulting register and all the bits in reg end up as the low order bits in the resulting register. !*/</font> <font color='#0000FF'><u>double</u></font> <b><a name='probability_of_bit'></a>probability_of_bit</b> <font face='Lucida Console'>(</font> <font color='#0000FF'><u>int</u></font> bit <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! requires - 0 &lt;= bit &lt; num_bits() ensures - returns the probability of measuring the given bit and it being in the 1 state. - The returned value is also equal to the sum of norm(state_vector()(i)) for all i where the bit'th bit in i is set to 1. (note that the lowest order bit is bit 0) !*/</font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> rand_type<font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>bool</u></font> <b><a name='measure_bit'></a>measure_bit</b> <font face='Lucida Console'>(</font> <font color='#0000FF'><u>int</u></font> bit, rand_type<font color='#5555FF'>&amp;</font> rnd <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - 0 &lt;= bit &lt; num_bits() - rand_type == an implementation of dlib/rand/rand_float_abstract.h ensures - measures the given bit in this register. Let R denote the boolean result of the measurement, where true means the bit was measured to have value 1 and false means it had a value of 0. - if (R == true) then - returns true - #probability_of_bit(bit) == 1 - else - returns false - #probability_of_bit(bit) == 0 !*/</font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> rand_type<font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>bool</u></font> <b><a name='measure_and_remove_bit'></a>measure_and_remove_bit</b> <font face='Lucida Console'>(</font> <font color='#0000FF'><u>int</u></font> bit, rand_type<font color='#5555FF'>&amp;</font> rnd <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - num_bits() &gt; 1 - 0 &lt;= bit &lt; num_bits() - rand_type == an implementation of dlib/rand/rand_float_abstract.h ensures - measures the given bit in this register. Let R denote the boolean result of the measurement, where true means the bit was measured to have value 1 and false means it had a value of 0. - #num_bits() == num_bits() - 1 - removes the bit that was measured from this register. - if (R == true) then - returns true - else - returns false !*/</font> <font color='#0000FF'>const</font> matrix<font color='#5555FF'>&lt;</font>qc_scalar_type,<font color='#979000'>0</font>,<font color='#979000'>1</font><font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> <b><a name='state_vector'></a>state_vector</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns a const reference to the state vector that describes the state of the quantum bits in this register. !*/</font> matrix<font color='#5555FF'>&lt;</font>qc_scalar_type,<font color='#979000'>0</font>,<font color='#979000'>1</font><font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> <b><a name='state_vector'></a>state_vector</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - returns a non-const reference to the state vector that describes the state of the quantum bits in this register. !*/</font> <font color='#0000FF'><u>void</u></font> <b><a name='swap'></a>swap</b> <font face='Lucida Console'>(</font> quantum_register<font color='#5555FF'>&amp;</font> item <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - swaps *this and item !*/</font> <b>}</b>; <font color='#0000FF'>inline</font> <font color='#0000FF'><u>void</u></font> <b><a name='swap'></a>swap</b> <font face='Lucida Console'>(</font> quantum_register<font color='#5555FF'>&amp;</font> a, quantum_register<font color='#5555FF'>&amp;</font> b <font face='Lucida Console'>)</font> <b>{</b> a.<font color='#BB00BB'>swap</font><font face='Lucida Console'>(</font>b<font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>/*! provides a global swap function !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> T<font color='#5555FF'>&gt;</font> <font color='#0000FF'>class</font> <b><a name='gate_exp'></a>gate_exp</b> <b>{</b> <font color='#009900'>/*! REQUIREMENTS ON T T must be some object that inherits from gate_exp and implements its own version of operator() and compute_state_element(). WHAT THIS OBJECT REPRESENTS This object represents an expression that evaluates to a quantum gate that operates on T::num_bits qubits. This object makes it easy to create new types of gate objects. All you need to do is inherit from gate_exp in the proper way and then you can use your new gate objects in conjunction with all the others. !*/</font> <font color='#0000FF'>public</font>: <font color='#0000FF'>static</font> <font color='#0000FF'>const</font> <font color='#0000FF'><u>long</u></font> num_bits <font color='#5555FF'>=</font> T::num_bits; <font color='#0000FF'>static</font> <font color='#0000FF'>const</font> <font color='#0000FF'><u>long</u></font> dims <font color='#5555FF'>=</font> T::dims; <b><a name='gate_exp'></a>gate_exp</b><font face='Lucida Console'>(</font> T<font color='#5555FF'>&amp;</font> exp <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - #&amp;ref() == &amp;exp !*/</font> <font color='#0000FF'>const</font> qc_scalar_type <b><a name='operator'></a>operator</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font face='Lucida Console'>(</font> <font color='#0000FF'><u>long</u></font> r, <font color='#0000FF'><u>long</u></font> c <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! requires - 0 &lt;= r &lt; dims - 0 &lt;= c &lt; dims ensures - returns ref()(r,c) !*/</font> <font color='#0000FF'><u>void</u></font> <b><a name='apply_gate_to'></a>apply_gate_to</b> <font face='Lucida Console'>(</font> quantum_register<font color='#5555FF'>&amp;</font> reg <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! requires - reg.num_bits() == num_bits ensures - applies this quantum gate to the given quantum register - Let M represent the matrix for this quantum gate, then #reg().state_vector() = M*reg().state_vector() !*/</font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> exp<font color='#5555FF'>&gt;</font> qc_scalar_type <b><a name='compute_state_element'></a>compute_state_element</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>exp<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> reg, <font color='#0000FF'><u>long</u></font> row_idx <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! requires - reg.nr() == dims - reg.nc() == 1 - 0 &lt;= row_idx &lt; dims ensures - Let M represent the matrix for this gate, then this function returns rowm(M*reg, row_idx) (i.e. returns the row_idx row of what you get when you apply this gate to the given column vector in reg) - This function works by calling ref().compute_state_element(reg,row_idx) !*/</font> <font color='#0000FF'>const</font> T<font color='#5555FF'>&amp;</font> <b><a name='ref'></a>ref</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - returns a reference to the subexpression contained in this object !*/</font> <font color='#0000FF'>const</font> matrix<font color='#5555FF'>&lt;</font>qc_scalar_type<font color='#5555FF'>&gt;</font> <b><a name='mat'></a>mat</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns a dense matrix object that contains the matrix for this gate !*/</font> <b>}</b>; <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> T, <font color='#0000FF'>typename</font> U<font color='#5555FF'>&gt;</font> <font color='#0000FF'>class</font> <b><a name='composite_gate'></a>composite_gate</b> : <font color='#0000FF'>public</font> gate_exp<font color='#5555FF'>&lt;</font>composite_gate<font color='#5555FF'>&lt;</font>T,U<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&gt;</font> <b>{</b> <font color='#009900'>/*! REQUIREMENTS ON T AND U Both must be gate expressions that inherit from gate_exp WHAT THIS OBJECT REPRESENTS This object represents a quantum gate that is the tensor product of two other quantum gates. As an example, suppose you have 3 registers, reg_high, reg_low, and reg_all. Also suppose that reg_all is what you get when you append reg_high and reg_low, so reg_all.state_vector() == tensor_product(reg_high.state_vector(),reg_low.state_vector()). Then applying a composite gate to reg_all would give you the same thing as applying the lhs gate to reg_high and the rhs gate to reg_low and then appending the two resulting registers. So the lhs gate of a composite_gate applies to the high order bits of a regitser and the rhs gate applies to the lower order bits. !*/</font> <font color='#0000FF'>public</font>: <b><a name='composite_gate'></a>composite_gate</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> composite_gate<font color='#5555FF'>&amp;</font> g <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - *this is a copy of g !*/</font> <b><a name='composite_gate'></a>composite_gate</b><font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> gate_exp<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> lhs_, <font color='#0000FF'>const</font> gate_exp<font color='#5555FF'>&lt;</font>U<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> rhs_ <font face='Lucida Console'>)</font>: <font color='#009900'>/*! ensures - #lhs == lhs_.ref() - #rhs == rhs_.ref() - #num_bits == T::num_bits + U::num_bits - #dims == 2^num_bits - #&amp;ref() == this !*/</font> <font color='#0000FF'>const</font> qc_scalar_type <b><a name='operator'></a>operator</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font face='Lucida Console'>(</font> <font color='#0000FF'><u>long</u></font> r, <font color='#0000FF'><u>long</u></font> c <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! requires - 0 &lt;= r &lt; dims - 0 &lt;= c &lt; dims ensures - Let M denote the tensor product of lhs with rhs, then this function returns M(r,c) (i.e. returns lhs(r/U::dims,c/U::dims)*rhs(r%U::dims, c%U::dims)) !*/</font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> exp<font color='#5555FF'>&gt;</font> qc_scalar_type compute_state_element <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>exp<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> reg, <font color='#0000FF'><u>long</u></font> row_idx <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! requires - reg.nr() == dims - reg.nc() == 1 - 0 &lt;= row_idx &lt; dims ensures - Let M represent the matrix for this gate, then this function returns rowm(M*reg, row_idx) (i.e. returns the row_idx row of what you get when you apply this gate to the given column vector in reg) - This function works by calling rhs.compute_state_element() and using elements of the matrix in lhs. !*/</font> <font color='#0000FF'>static</font> <font color='#0000FF'>const</font> <font color='#0000FF'><u>long</u></font> num_bits; <font color='#0000FF'>static</font> <font color='#0000FF'>const</font> <font color='#0000FF'><u>long</u></font> dims; <font color='#0000FF'>const</font> T lhs; <font color='#0000FF'>const</font> U rhs; <b>}</b>; <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'><u>long</u></font> bits<font color='#5555FF'>&gt;</font> <font color='#0000FF'>class</font> <b><a name='gate'></a>gate</b> : <font color='#0000FF'>public</font> gate_exp<font color='#5555FF'>&lt;</font>gate<font color='#5555FF'>&lt;</font>bits<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&gt;</font> <b>{</b> <font color='#009900'>/*! REQUIREMENTS ON bits 0 &lt; bits &lt;= 30 WHAT THIS OBJECT REPRESENTS This object represents a quantum gate that operates on bits qubits. It stores its gate matrix explicitly in a dense in-memory matrix. !*/</font> <font color='#0000FF'>public</font>: <b><a name='gate'></a>gate</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - num_bits == bits - dims == 2^bits - #&amp;ref() == this - for all valid r and c: #(*this)(r,c) == 0 !*/</font> <b><a name='gate'></a>gate</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> gate<font color='#5555FF'>&amp;</font> g <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - *this is a copy of g !*/</font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> T<font color='#5555FF'>&gt;</font> <font color='#0000FF'>explicit</font> <b><a name='gate'></a>gate</b><font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> gate_exp<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> g <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - T::num_bits == num_bits ensures - num_bits == bits - dims == 2^bits - #&amp;ref() == this - for all valid r and c: #(*this)(r,c) == g(r,c) !*/</font> <font color='#0000FF'>const</font> qc_scalar_type<font color='#5555FF'>&amp;</font> <b><a name='operator'></a>operator</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font face='Lucida Console'>(</font> <font color='#0000FF'><u>long</u></font> r, <font color='#0000FF'><u>long</u></font> c <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! requires - 0 &lt;= r &lt; dims - 0 &lt;= c &lt; dims ensures - Let M denote the matrix for this gate, then this function returns a const reference to M(r,c) !*/</font> qc_scalar_type<font color='#5555FF'>&amp;</font> <b><a name='operator'></a>operator</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font face='Lucida Console'>(</font> <font color='#0000FF'><u>long</u></font> r, <font color='#0000FF'><u>long</u></font> c <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - 0 &lt;= r &lt; dims - 0 &lt;= c &lt; dims ensures - Let M denote the matrix for this gate, then this function returns a non-const reference to M(r,c) !*/</font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> exp<font color='#5555FF'>&gt;</font> qc_scalar_type <b><a name='compute_state_element'></a>compute_state_element</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>exp<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> reg, <font color='#0000FF'><u>long</u></font> row_idx <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! requires - reg.nr() == dims - reg.nc() == 1 - 0 &lt;= row_idx &lt; dims ensures - Let M represent the matrix for this gate, then this function returns rowm(M*reg, row_idx) (i.e. returns the row_idx row of what you get when you apply this gate to the given column vector in reg) !*/</font> <font color='#0000FF'>static</font> <font color='#0000FF'>const</font> <font color='#0000FF'><u>long</u></font> num_bits; <font color='#0000FF'>static</font> <font color='#0000FF'>const</font> <font color='#0000FF'><u>long</u></font> dims; <b>}</b>; <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> T, <font color='#0000FF'>typename</font> U<font color='#5555FF'>&gt;</font> <font color='#0000FF'>const</font> composite_gate<font color='#5555FF'>&lt;</font>T,U<font color='#5555FF'>&gt;</font> <b><a name='operator'></a>operator</b>, <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> gate_exp<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> lhs, <font color='#0000FF'>const</font> gate_exp<font color='#5555FF'>&lt;</font>U<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> rhs <font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>return</font> composite_gate<font color='#5555FF'>&lt;</font>T,U<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font>lhs,rhs<font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>/*! ensures - returns a composite_gate that represents the tensor product of the lhs gate with the rhs gate. !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>namespace</font> quantum_gates <b>{</b> <font color='#0000FF'>inline</font> <font color='#0000FF'>const</font> gate<font color='#5555FF'>&lt;</font><font color='#979000'>1</font><font color='#5555FF'>&gt;</font> <b><a name='hadamard'></a>hadamard</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - returns the Hadamard gate. (i.e. A gate with a matrix of |1, 1| 1/sqrt(2) * |1,-1| ) !*/</font> <font color='#0000FF'>inline</font> <font color='#0000FF'>const</font> gate<font color='#5555FF'>&lt;</font><font color='#979000'>1</font><font color='#5555FF'>&gt;</font> <b><a name='x'></a>x</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - returns the not gate. (i.e. A gate with a matrix of |0, 1| |1, 0| ) !*/</font> <font color='#0000FF'>inline</font> <font color='#0000FF'>const</font> gate<font color='#5555FF'>&lt;</font><font color='#979000'>1</font><font color='#5555FF'>&gt;</font> <b><a name='y'></a>y</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - returns the y gate. (i.e. A gate with a matrix of |0,-i| |i, 0| ) !*/</font> <font color='#0000FF'>inline</font> <font color='#0000FF'>const</font> gate<font color='#5555FF'>&lt;</font><font color='#979000'>1</font><font color='#5555FF'>&gt;</font> <b><a name='z'></a>z</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - returns the z gate. (i.e. A gate with a matrix of |1, 0| |0,-1| ) !*/</font> <font color='#0000FF'>inline</font> <font color='#0000FF'>const</font> gate<font color='#5555FF'>&lt;</font><font color='#979000'>1</font><font color='#5555FF'>&gt;</font> <b><a name='noop'></a>noop</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - returns the no-op or identity gate. (i.e. A gate with a matrix of |1, 0| |0, 1| ) !*/</font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'><u>int</u></font> control_bit, <font color='#0000FF'><u>int</u></font> target_bit <font color='#5555FF'>&gt;</font> <font color='#0000FF'>class</font> <b><a name='cnot'></a>cnot</b> : <font color='#0000FF'>public</font> gate_exp<font color='#5555FF'>&lt;</font>cnot<font color='#5555FF'>&lt;</font>control_bit, target_bit<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&gt;</font> <b>{</b> <font color='#009900'>/*! REQUIREMENTS ON control_bit AND target_bit - control_bit != target_bit WHAT THIS OBJECT REPRESENTS This object represents the controlled-not quantum gate. It is a gate that operates on abs(control_bit-target_bit)+1 qubits. In terms of the computational basis vectors, this gate maps input vectors to output vectors in the following way: - if (the input vector corresponds to a state where the control_bit qubit is 1) then - this gate outputs the computational basis vector that corresponds to the state where the target_bit has been flipped with respect to the input vector - else - this gate outputs the input vector unmodified !*/</font> <b>}</b>; <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'><u>int</u></font> control_bit1, <font color='#0000FF'><u>int</u></font> control_bit2, <font color='#0000FF'><u>int</u></font> target_bit <font color='#5555FF'>&gt;</font> <font color='#0000FF'>class</font> <b><a name='toffoli'></a>toffoli</b> : <font color='#0000FF'>public</font> gate_exp<font color='#5555FF'>&lt;</font>toffoli<font color='#5555FF'>&lt;</font>control_bit1, control_bit2, target_bit<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&gt;</font> <b>{</b> <font color='#009900'>/*! REQUIREMENTS ON control_bit1, control_bit2, AND target_bit - all the arguments denote different bits, i.e.: - control_bit1 != target_bit - control_bit2 != target_bit - control_bit1 != control_bit2 - The target bit can't be in-between the control bits, i.e.: - (control_bit1 &lt; target_bit &amp;&amp; control_bit2 &lt; target_bit) || (control_bit1 &gt; target_bit &amp;&amp; control_bit2 &gt; target_bit) WHAT THIS OBJECT REPRESENTS This object represents the toffoli variant of a controlled-not quantum gate. It is a gate that operates on max(abs(control_bit2-target_bit),abs(control_bit1-target_bit))+1 qubits. In terms of the computational basis vectors, this gate maps input vectors to output vectors in the following way: - if (the input vector corresponds to a state where the control_bit1 and control_bit2 qubits are 1) then - this gate outputs the computational basis vector that corresponds to the state where the target_bit has been flipped with respect to the input vector - else - this gate outputs the input vector unmodified !*/</font> <b>}</b>; <font color='#009900'>// ------------------------------------------------------------------------------------ </font> <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <b>}</b> <font color='#0000FF'>#endif</font> <font color='#009900'>// DLIB_QUANTUM_COMPUTINg_ABSTRACT_ </font> </pre></body></html>
Nekel-Seyew/Complex-3D-Vector-Fields
dlib-18.18/docs/dlib/quantum_computing/quantum_computing_abstract.h.html
HTML
apache-2.0
33,641
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_1435 { }
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_1435.java
Java
apache-2.0
151
/* * Hibernate Validator, declare and validate application constraints * * License: Apache License, Version 2.0 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>. */ package org.hibernate.validator.test.internal.engine.messageinterpolation; import static org.hibernate.validator.testutil.ConstraintViolationAssert.assertThat; import static org.hibernate.validator.testutil.ConstraintViolationAssert.violationOf; import static org.testng.Assert.fail; import java.util.Enumeration; import java.util.Locale; import java.util.ResourceBundle; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.MessageInterpolator; import javax.validation.Validator; import javax.validation.ValidatorFactory; import javax.validation.constraints.Max; import org.hibernate.validator.HibernateValidatorConfiguration; import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator; import org.hibernate.validator.spi.resourceloading.ResourceBundleLocator; import org.hibernate.validator.testutil.TestForIssue; import org.hibernate.validator.testutils.ValidatorUtil; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; /** * @author Hardy Ferentschik */ @TestForIssue(jiraKey = "HV-798") public class EscapedInterpolationVariableTest { private Validator validator; @BeforeTest public void setUp() { MessageInterpolator interpolator = new ResourceBundleMessageInterpolator( new ResourceBundleLocator() { @Override public ResourceBundle getResourceBundle(Locale locale) { return new ResourceBundle() { @Override protected Object handleGetObject(String key) { if ( "key-1".equals( key ) ) { return "\\{escapedParameterKey\\}"; } else if ( "key-2".equals( key ) ) { // since {} are unbalanced the original key (key-2) should be returned from the interpolation return "{escapedParameterKey\\}"; } else if ( "key-3".equals( key ) ) { // since {} are unbalanced the original key (key-3) should be returned from the interpolation return "\\{escapedParameterKey}"; } else if ( "key-4".equals( key ) ) { return "foo"; } else { fail( "Unexpected key: " + key ); } return null; } @Override public Enumeration<String> getKeys() { throw new UnsupportedOperationException(); } }; } }, false ); HibernateValidatorConfiguration config = ValidatorUtil.getConfiguration(); ValidatorFactory factory = config.messageInterpolator( interpolator ).buildValidatorFactory(); validator = factory.getValidator(); } @Test public void testEscapedOpeningAndClosingBrace() throws Exception { Set<ConstraintViolation<A>> constraintViolations = validator.validate( new A() ); assertThat( constraintViolations ).containsOnlyViolations( violationOf( Max.class ).withMessage( "{escapedParameterKey}" ) ); } @Test public void testEscapedClosingBrace() throws Exception { Set<ConstraintViolation<B>> constraintViolations = validator.validate( new B() ); assertThat( constraintViolations ).containsOnlyViolations( violationOf( Max.class ).withMessage( "{key-2}" ) ); } @Test public void testEscapedOpenBrace() throws Exception { Set<ConstraintViolation<C>> constraintViolations = validator.validate( new C() ); assertThat( constraintViolations ).containsOnlyViolations( violationOf( Max.class ).withMessage( "{key-3}" ) ); } @Test public void testMessageStaysUnchangedDueToSingleCurlyBrace() throws Exception { Set<ConstraintViolation<D>> constraintViolations = validator.validate( new D() ); assertThat( constraintViolations ).containsOnlyViolations( violationOf( Max.class ).withMessage( "{key-4} {" ) ); } private class A { @Max(value = 1, message = "{key-1}") private int a = 2; } private class B { @Max(value = 1, message = "{key-2}") private int a = 2; } private class C { @Max(value = 1, message = "{key-3}") private int a = 2; } private class D { @Max(value = 1, message = "{key-4} {") private int a = 2; } }
shahramgdz/hibernate-validator
engine/src/test/java/org/hibernate/validator/test/internal/engine/messageinterpolation/EscapedInterpolationVariableTest.java
Java
apache-2.0
4,239
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; using Cats.Helpers; using Cats.Models; using Cats.Models.PSNP; using Cats.Data; using Cats.Services.Administration; using Cats.Services.PSNP; using Cats.Services.Security; using Cats.Services.Transaction; using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; using Cats.Services.EarlyWarning; using Cats.Services.Common; using Cats.Infrastructure; using log4net; using IAdminUnitService = Cats.Services.EarlyWarning.IAdminUnitService; namespace Cats.Areas.PSNP { public class RegionalPSNPPlanController : Controller { private int _regionalPsnpId = 0; private readonly IRegionalPSNPPlanService _regionalPSNPPlanService; private readonly IAdminUnitService _adminUnitService; private readonly IRationService _rationService; private readonly IBusinessProcessService _BusinessProcessService; private readonly IBusinessProcessStateService _BusinessProcessStateService; private readonly IApplicationSettingService _ApplicationSettingService; private readonly ILog _log; private readonly IPlanService _planService; private readonly IUserAccountService _userAccountService; private readonly Cats.Services.Transaction.ITransactionService _transactionService; private readonly IUserProfileService _userProfileService; public RegionalPSNPPlanController(IRegionalPSNPPlanService regionalPSNPPlanServiceParam , IRationService rationServiceParam , IAdminUnitService adminUnitServiceParam , IBusinessProcessService BusinessProcessServiceParam , IBusinessProcessStateService BusinessProcessStateServiceParam , IApplicationSettingService ApplicationSettingParam , ILog log , IPlanService planService ,IUserAccountService userAccountService, ITransactionService transactionService, IUserProfileService userProfileService) { this._regionalPSNPPlanService = regionalPSNPPlanServiceParam; this._rationService = rationServiceParam; this._adminUnitService = adminUnitServiceParam; this._BusinessProcessService = BusinessProcessServiceParam; this._BusinessProcessStateService = BusinessProcessStateServiceParam; this._ApplicationSettingService = ApplicationSettingParam; this._log = log; this._planService = planService; this._userAccountService = userAccountService; _transactionService = transactionService; this._userProfileService = userProfileService; } public IEnumerable<RegionalPSNPPlanViewModel> toViewModel(IEnumerable<Cats.Models.RegionalPSNPPlan> list) { var datePref = _userAccountService.GetUserInfo(HttpContext.User.Identity.Name).DatePreference; try { return (from plan in list select new RegionalPSNPPlanViewModel { RegionalPSNPPlanID = plan.RegionalPSNPPlanID, Duration = plan.Duration, PlanName = plan.Plan.PlanName, Year = plan.Year, // RegionName = plan.Region.Name, RationName = plan.Ration.RefrenceNumber, From = plan.Plan.StartDate.ToCTSPreferedDateFormat(datePref), To = plan.Plan.EndDate.ToCTSPreferedDateFormat(datePref), StatusName = plan.AttachedBusinessProcess.CurrentState.BaseStateTemplate.Name, UserId = plan.User }); } catch (Exception e) { var log = new Logger(); log.LogAllErrorsMesseges(e,_log); } return new List<RegionalPSNPPlanViewModel>(); } public void LoadLookups() { ViewBag.RegionID = new SelectList(_adminUnitService.FindBy(t => t.AdminUnitTypeID == 2), "AdminUnitID", "Name"); ViewBag.RationID = new SelectList(_rationService.GetAllRation(), "RationID", "RefrenceNumber"); var psnpPlans = _planService.FindBy(p => p.ProgramID == 2); ViewBag.PlanId = new SelectList(_planService.FindBy(p => p.ProgramID == 2), "PlanID", "PlanName"); } // // GET: /PSNP/RegionalPSNPPlan/ public ActionResult Index() { IEnumerable<RegionalPSNPPlan> list = (IEnumerable<Cats.Models.RegionalPSNPPlan>)_regionalPSNPPlanService.GetAllRegionalPSNPPlan(); return View(list); } public ActionResult GetListAjax([DataSourceRequest] DataSourceRequest request) { IEnumerable<Cats.Models.RegionalPSNPPlan> list = (IEnumerable<Cats.Models.RegionalPSNPPlan>)_regionalPSNPPlanService.GetAllRegionalPSNPPlan().OrderByDescending(m=>m.RegionalPSNPPlanID); return Json(toViewModel(list).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); } public ActionResult Print(int id = 0) { if (id == 0) { RedirectToAction("Index"); } var reportPath = Server.MapPath("~/Report/PSNP/AnnualPlan.rdlc"); var reportData = _regionalPSNPPlanService.GetAnnualPlanRpt(id); var dataSourceName = "annualplan"; var result = ReportHelper.PrintReport(reportPath, reportData, dataSourceName); return File(result.RenderBytes, result.MimeType); } public ActionResult Details(int id = 0) { RegionalPSNPPlan regionalpsnpplan = _regionalPSNPPlanService.FindById(id); if (regionalpsnpplan == null) { return HttpNotFound(); } return View(regionalpsnpplan); } public ActionResult Promote(BusinessProcessState st) { var isReject = _BusinessProcessService.CheckPlanBeforeReject(st); if (isReject) { } _BusinessProcessService.PromotWorkflow(st); return RedirectToAction("Index"); } public ActionResult promotWorkflow(int id, int nextState) { RegionalPSNPPlan item = _regionalPSNPPlanService.FindById(id); item.StatusID = nextState; _regionalPSNPPlanService.UpdateRegionalPSNPPlan(item); if (item.StatusID == (int) Cats.Models.Constant.PSNPWorkFlow.Completed) PostPSNP(item); return RedirectToAction("Index"); } public void PostPSNP(RegionalPSNPPlan plan) { try { var ration = _rationService.FindBy(r => r.RationID == plan.RationID).FirstOrDefault(); _transactionService.PostPSNPPlan(plan, ration); } catch (Exception ex) { _log.Error("Error in posting psnp:",new Exception(ex.Message)); } } // // GET: /PSNP/RegionalPSNPPlan/Create public ActionResult Create() { LoadLookups(); return View(); } // // POST: /PSNP/RegionalPSNPPlan/Create [HttpPost] public ActionResult Create(RegionalPSNPPlan regionalpsnpplan) { var planName = regionalpsnpplan.Plan.PlanName; var startDate = regionalpsnpplan.Plan.StartDate; var firstDayOfTheMonth = startDate.AddDays(1 - startDate.Day); var endDate = firstDayOfTheMonth.AddMonths(regionalpsnpplan.Duration).AddDays(-1); UserProfile user = _userProfileService.GetUser(User.Identity.Name); if (ModelState.IsValid) { _regionalPSNPPlanService.AddPsnpPlan(planName, firstDayOfTheMonth, endDate); var plan = _planService.Get(m => m.PlanName == planName,null,"Program").FirstOrDefault(); regionalpsnpplan.Plan = plan; //check if this psnp plan exitsts for this year and Plan var exists = plan != null && _regionalPSNPPlanService.DoesPsnpPlanExistForThisRegion(plan.PlanID, regionalpsnpplan.Year); if (!exists) { int BP_PSNP = _ApplicationSettingService.getPSNPWorkflow(); if (BP_PSNP != 0) { BusinessProcessState createdstate = new BusinessProcessState { DatePerformed = DateTime.Now, PerformedBy = "System", Comment = "Created workflow for PSNP Plan" }; var psnpPlan= _regionalPSNPPlanService.CreatePsnpPlan(regionalpsnpplan.Year,regionalpsnpplan.Duration,regionalpsnpplan.RationID,regionalpsnpplan.StatusID,plan.PlanID,user.UserProfileID); //_planService.ChangePlanStatus(regionalpsnpplan.PlanId); BusinessProcess bp = _BusinessProcessService.CreateBusinessProcess(BP_PSNP, regionalpsnpplan. RegionalPSNPPlanID, "PSNP", createdstate); psnpPlan.StatusID = bp.BusinessProcessID; _regionalPSNPPlanService.UpdateRegionalPSNPPlan(psnpPlan); return RedirectToAction("Index"); } ViewBag.ErrorMessage1 = "The workflow assosiated with PSNP planning doesnot exist."; ViewBag.ErrorMessage2 = "Please make sure the workflow is created and configured."; } LoadLookups(); ModelState.AddModelError("Errors", @"PSNP plan already made for this period and plan Name."); return View(regionalpsnpplan); } LoadLookups(); return View(regionalpsnpplan); } // // GET: /PSNP/RegionalPSNPPlan/Edit/5 public ActionResult Edit(int id = 0) { LoadLookups(); RegionalPSNPPlan regionalpsnpplan = _regionalPSNPPlanService.FindById(id); if (regionalpsnpplan == null) { return HttpNotFound(); } return View(regionalpsnpplan); } [HttpPost] public ActionResult Edit(RegionalPSNPPlan regionalpsnpplan) { if (ModelState.IsValid) { _regionalPSNPPlanService.UpdateRegionalPSNPPlan(regionalpsnpplan); return RedirectToAction("Index"); } LoadLookups(); return View(regionalpsnpplan); } // // GET: /PSNP/RegionalPSNPPlan/Delete/5 public ActionResult Delete(int id = 0) { RegionalPSNPPlan regionalpsnpplan = _regionalPSNPPlanService.FindById(id); if (regionalpsnpplan == null) { return HttpNotFound(); } return View(regionalpsnpplan); } // // POST: /PSNP/RegionalPSNPPlan/Delete/5 [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id) { _regionalPSNPPlanService.DeleteById(id); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } }
ndrmc/cats
Web/Areas/PSNP/Controllers/RegionalPSNPPlanController.cs
C#
apache-2.0
12,466
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_80) on Thu Jun 18 14:08:33 EDT 2015 --> <title>UpdateStatement (apache-cassandra API)</title> <meta name="date" content="2015-06-18"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="UpdateStatement (apache-cassandra API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/UpdateStatement.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/apache/cassandra/cql/WhereClause.html" title="class in org.apache.cassandra.cql"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/cassandra/cql/UpdateStatement.html" target="_top">Frames</a></li> <li><a href="UpdateStatement.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_org.apache.cassandra.cql.AbstractModification">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.cassandra.cql</div> <h2 title="Class UpdateStatement" class="title">Class UpdateStatement</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">org.apache.cassandra.cql.AbstractModification</a></li> <li> <ul class="inheritance"> <li>org.apache.cassandra.cql.UpdateStatement</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="strong">UpdateStatement</span> extends <a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></pre> <div class="block">An <code>UPDATE</code> statement parsed from a CQL query statement.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <ul class="blockList"> <li class="blockList"><a name="fields_inherited_from_class_org.apache.cassandra.cql.AbstractModification"> <!-- --> </a> <h3>Fields inherited from class&nbsp;org.apache.cassandra.cql.<a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></h3> <code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html#cLevel">cLevel</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#columnFamily">columnFamily</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#defaultConsistency">defaultConsistency</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#keyName">keyName</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#keyspace">keyspace</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#timestamp">timestamp</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#timeToLive">timeToLive</a></code></li> </ul> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#UpdateStatement(java.lang.String,%20java.lang.String,%20java.lang.String,%20java.util.List,%20java.util.List,%20java.util.List,%20org.apache.cassandra.cql.Attributes)">UpdateStatement</a></strong>(java.lang.String&nbsp;keyspace, java.lang.String&nbsp;columnFamily, java.lang.String&nbsp;keyName, java.util.List&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>&gt;&nbsp;columnNames, java.util.List&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>&gt;&nbsp;columnValues, java.util.List&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>&gt;&nbsp;keys, <a href="../../../../org/apache/cassandra/cql/Attributes.html" title="class in org.apache.cassandra.cql">Attributes</a>&nbsp;attrs)</code> <div class="block">Creates a new UpdateStatement from a column family name, a consistency level, key, and lists of column names and values.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#UpdateStatement(java.lang.String,%20java.lang.String,%20java.lang.String,%20java.util.Map,%20java.util.List,%20org.apache.cassandra.cql.Attributes)">UpdateStatement</a></strong>(java.lang.String&nbsp;keyspace, java.lang.String&nbsp;columnFamily, java.lang.String&nbsp;keyName, java.util.Map&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>,<a href="../../../../org/apache/cassandra/cql/Operation.html" title="class in org.apache.cassandra.cql">Operation</a>&gt;&nbsp;columns, java.util.List&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>&gt;&nbsp;keys, <a href="../../../../org/apache/cassandra/cql/Attributes.html" title="class in org.apache.cassandra.cql">Attributes</a>&nbsp;attrs)</code> <div class="block">Creates a new UpdateStatement from a column family name, columns map, consistency level, and key term.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getColumnFamily()">getColumnFamily</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.util.List&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getColumnNames()">getColumnNames</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.util.Map&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>,<a href="../../../../org/apache/cassandra/cql/Operation.html" title="class in org.apache.cassandra.cql">Operation</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getColumns()">getColumns</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.util.List&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getColumnValues()">getColumnValues</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/apache/cassandra/db/marshal/AbstractType.html" title="class in org.apache.cassandra.db.marshal">AbstractType</a>&lt;?&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getComparator(java.lang.String)">getComparator</a></strong>(java.lang.String&nbsp;keyspace)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/apache/cassandra/db/ConsistencyLevel.html" title="enum in org.apache.cassandra.db">ConsistencyLevel</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getConsistencyLevel()">getConsistencyLevel</a></strong>()</code> <div class="block">Returns the consistency level of this <code>UPDATE</code> statement, either one parsed from the CQL statement, or the default level otherwise.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.util.List&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getKeys()">getKeys</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/apache/cassandra/db/marshal/AbstractType.html" title="class in org.apache.cassandra.db.marshal">AbstractType</a>&lt;?&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getKeyType(java.lang.String)">getKeyType</a></strong>(java.lang.String&nbsp;keyspace)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#isSetConsistencyLevel()">isSetConsistencyLevel</a></strong>()</code> <div class="block">True if an explicit consistency level was parsed from the statement.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.util.List&lt;<a href="../../../../org/apache/cassandra/db/IMutation.html" title="interface in org.apache.cassandra.db">IMutation</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#prepareRowMutations(java.lang.String,%20org.apache.cassandra.thrift.ThriftClientState,%20java.util.List)">prepareRowMutations</a></strong>(java.lang.String&nbsp;keyspace, <a href="../../../../org/apache/cassandra/thrift/ThriftClientState.html" title="class in org.apache.cassandra.thrift">ThriftClientState</a>&nbsp;clientState, java.util.List&lt;java.nio.ByteBuffer&gt;&nbsp;variables)</code> <div class="block">Convert statement into a list of mutations to apply on the server</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.util.List&lt;<a href="../../../../org/apache/cassandra/db/IMutation.html" title="interface in org.apache.cassandra.db">IMutation</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#prepareRowMutations(java.lang.String,%20org.apache.cassandra.thrift.ThriftClientState,%20java.lang.Long,%20java.util.List)">prepareRowMutations</a></strong>(java.lang.String&nbsp;keyspace, <a href="../../../../org/apache/cassandra/thrift/ThriftClientState.html" title="class in org.apache.cassandra.thrift">ThriftClientState</a>&nbsp;clientState, java.lang.Long&nbsp;timestamp, java.util.List&lt;java.nio.ByteBuffer&gt;&nbsp;variables)</code> <div class="block">Convert statement into a list of mutations to apply on the server</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#toString()">toString</a></strong>()</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_org.apache.cassandra.cql.AbstractModification"> <!-- --> </a> <h3>Methods inherited from class&nbsp;org.apache.cassandra.cql.<a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></h3> <code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html#getKeyName()">getKeyName</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#getKeyspace()">getKeyspace</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#getTimestamp(org.apache.cassandra.thrift.ThriftClientState)">getTimestamp</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#getTimeToLive()">getTimeToLive</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#isSetTimestamp()">isSetTimestamp</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="UpdateStatement(java.lang.String, java.lang.String, java.lang.String, java.util.Map, java.util.List, org.apache.cassandra.cql.Attributes)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>UpdateStatement</h4> <pre>public&nbsp;UpdateStatement(java.lang.String&nbsp;keyspace, java.lang.String&nbsp;columnFamily, java.lang.String&nbsp;keyName, java.util.Map&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>,<a href="../../../../org/apache/cassandra/cql/Operation.html" title="class in org.apache.cassandra.cql">Operation</a>&gt;&nbsp;columns, java.util.List&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>&gt;&nbsp;keys, <a href="../../../../org/apache/cassandra/cql/Attributes.html" title="class in org.apache.cassandra.cql">Attributes</a>&nbsp;attrs)</pre> <div class="block">Creates a new UpdateStatement from a column family name, columns map, consistency level, and key term.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>keyspace</code> - Keyspace (optional)</dd><dd><code>columnFamily</code> - column family name</dd><dd><code>keyName</code> - alias key name</dd><dd><code>columns</code> - a map of column name/values pairs</dd><dd><code>keys</code> - the keys to update</dd><dd><code>attrs</code> - additional attributes for statement (CL, timestamp, timeToLive)</dd></dl> </li> </ul> <a name="UpdateStatement(java.lang.String, java.lang.String, java.lang.String, java.util.List, java.util.List, java.util.List, org.apache.cassandra.cql.Attributes)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>UpdateStatement</h4> <pre>public&nbsp;UpdateStatement(java.lang.String&nbsp;keyspace, java.lang.String&nbsp;columnFamily, java.lang.String&nbsp;keyName, java.util.List&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>&gt;&nbsp;columnNames, java.util.List&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>&gt;&nbsp;columnValues, java.util.List&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>&gt;&nbsp;keys, <a href="../../../../org/apache/cassandra/cql/Attributes.html" title="class in org.apache.cassandra.cql">Attributes</a>&nbsp;attrs)</pre> <div class="block">Creates a new UpdateStatement from a column family name, a consistency level, key, and lists of column names and values. It is intended for use with the alternate update format, <code>INSERT</code>.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>keyspace</code> - Keyspace (optional)</dd><dd><code>columnFamily</code> - column family name</dd><dd><code>keyName</code> - alias key name</dd><dd><code>columnNames</code> - list of column names</dd><dd><code>columnValues</code> - list of column values (corresponds to names)</dd><dd><code>keys</code> - the keys to update</dd><dd><code>attrs</code> - additional attributes for statement (CL, timestamp, timeToLive)</dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getConsistencyLevel()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getConsistencyLevel</h4> <pre>public&nbsp;<a href="../../../../org/apache/cassandra/db/ConsistencyLevel.html" title="enum in org.apache.cassandra.db">ConsistencyLevel</a>&nbsp;getConsistencyLevel()</pre> <div class="block">Returns the consistency level of this <code>UPDATE</code> statement, either one parsed from the CQL statement, or the default level otherwise.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html#getConsistencyLevel()">getConsistencyLevel</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></code></dd> <dt><span class="strong">Returns:</span></dt><dd>the consistency level as a Thrift enum.</dd></dl> </li> </ul> <a name="isSetConsistencyLevel()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>isSetConsistencyLevel</h4> <pre>public&nbsp;boolean&nbsp;isSetConsistencyLevel()</pre> <div class="block">True if an explicit consistency level was parsed from the statement.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html#isSetConsistencyLevel()">isSetConsistencyLevel</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></code></dd> <dt><span class="strong">Returns:</span></dt><dd>true if a consistency was parsed, false otherwise.</dd></dl> </li> </ul> <a name="prepareRowMutations(java.lang.String, org.apache.cassandra.thrift.ThriftClientState, java.util.List)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>prepareRowMutations</h4> <pre>public&nbsp;java.util.List&lt;<a href="../../../../org/apache/cassandra/db/IMutation.html" title="interface in org.apache.cassandra.db">IMutation</a>&gt;&nbsp;prepareRowMutations(java.lang.String&nbsp;keyspace, <a href="../../../../org/apache/cassandra/thrift/ThriftClientState.html" title="class in org.apache.cassandra.thrift">ThriftClientState</a>&nbsp;clientState, java.util.List&lt;java.nio.ByteBuffer&gt;&nbsp;variables) throws <a href="../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a>, <a href="../../../../org/apache/cassandra/exceptions/UnauthorizedException.html" title="class in org.apache.cassandra.exceptions">UnauthorizedException</a></pre> <div class="block">Convert statement into a list of mutations to apply on the server</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html#prepareRowMutations(java.lang.String,%20org.apache.cassandra.thrift.ThriftClientState,%20java.util.List)">prepareRowMutations</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>keyspace</code> - The working keyspace</dd><dd><code>clientState</code> - current client status</dd> <dt><span class="strong">Returns:</span></dt><dd>list of the mutations</dd> <dt><span class="strong">Throws:</span></dt> <dd><code><a href="../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a></code> - on the wrong request</dd> <dd><code><a href="../../../../org/apache/cassandra/exceptions/UnauthorizedException.html" title="class in org.apache.cassandra.exceptions">UnauthorizedException</a></code></dd></dl> </li> </ul> <a name="prepareRowMutations(java.lang.String, org.apache.cassandra.thrift.ThriftClientState, java.lang.Long, java.util.List)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>prepareRowMutations</h4> <pre>public&nbsp;java.util.List&lt;<a href="../../../../org/apache/cassandra/db/IMutation.html" title="interface in org.apache.cassandra.db">IMutation</a>&gt;&nbsp;prepareRowMutations(java.lang.String&nbsp;keyspace, <a href="../../../../org/apache/cassandra/thrift/ThriftClientState.html" title="class in org.apache.cassandra.thrift">ThriftClientState</a>&nbsp;clientState, java.lang.Long&nbsp;timestamp, java.util.List&lt;java.nio.ByteBuffer&gt;&nbsp;variables) throws <a href="../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a>, <a href="../../../../org/apache/cassandra/exceptions/UnauthorizedException.html" title="class in org.apache.cassandra.exceptions">UnauthorizedException</a></pre> <div class="block">Convert statement into a list of mutations to apply on the server</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html#prepareRowMutations(java.lang.String,%20org.apache.cassandra.thrift.ThriftClientState,%20java.lang.Long,%20java.util.List)">prepareRowMutations</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>keyspace</code> - The working keyspace</dd><dd><code>clientState</code> - current client status</dd><dd><code>timestamp</code> - global timestamp to use for all mutations</dd> <dt><span class="strong">Returns:</span></dt><dd>list of the mutations</dd> <dt><span class="strong">Throws:</span></dt> <dd><code><a href="../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a></code> - on the wrong request</dd> <dd><code><a href="../../../../org/apache/cassandra/exceptions/UnauthorizedException.html" title="class in org.apache.cassandra.exceptions">UnauthorizedException</a></code></dd></dl> </li> </ul> <a name="getColumnFamily()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getColumnFamily</h4> <pre>public&nbsp;java.lang.String&nbsp;getColumnFamily()</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html#getColumnFamily()">getColumnFamily</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></code></dd> </dl> </li> </ul> <a name="getKeys()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getKeys</h4> <pre>public&nbsp;java.util.List&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>&gt;&nbsp;getKeys()</pre> </li> </ul> <a name="getColumns()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getColumns</h4> <pre>public&nbsp;java.util.Map&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>,<a href="../../../../org/apache/cassandra/cql/Operation.html" title="class in org.apache.cassandra.cql">Operation</a>&gt;&nbsp;getColumns() throws <a href="../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a></pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code><a href="../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a></code></dd></dl> </li> </ul> <a name="toString()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>toString</h4> <pre>public&nbsp;java.lang.String&nbsp;toString()</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>toString</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="getKeyType(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getKeyType</h4> <pre>public&nbsp;<a href="../../../../org/apache/cassandra/db/marshal/AbstractType.html" title="class in org.apache.cassandra.db.marshal">AbstractType</a>&lt;?&gt;&nbsp;getKeyType(java.lang.String&nbsp;keyspace)</pre> </li> </ul> <a name="getComparator(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getComparator</h4> <pre>public&nbsp;<a href="../../../../org/apache/cassandra/db/marshal/AbstractType.html" title="class in org.apache.cassandra.db.marshal">AbstractType</a>&lt;?&gt;&nbsp;getComparator(java.lang.String&nbsp;keyspace)</pre> </li> </ul> <a name="getColumnNames()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getColumnNames</h4> <pre>public&nbsp;java.util.List&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>&gt;&nbsp;getColumnNames()</pre> </li> </ul> <a name="getColumnValues()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getColumnValues</h4> <pre>public&nbsp;java.util.List&lt;<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>&gt;&nbsp;getColumnValues()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/UpdateStatement.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/apache/cassandra/cql/WhereClause.html" title="class in org.apache.cassandra.cql"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/cassandra/cql/UpdateStatement.html" target="_top">Frames</a></li> <li><a href="UpdateStatement.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_org.apache.cassandra.cql.AbstractModification">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &copy; 2015 The Apache Software Foundation</small></p> </body> </html>
anuragkapur/cassandra-2.1.2-ak-skynet
apache-cassandra-2.0.16/javadoc/org/apache/cassandra/cql/UpdateStatement.html
HTML
apache-2.0
31,563
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.giraph.benchmark; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.apache.giraph.GiraphConfiguration; import org.apache.giraph.examples.MinimumDoubleCombiner; import org.apache.giraph.graph.EdgeListVertex; import org.apache.giraph.graph.GiraphJob; import org.apache.giraph.io.PseudoRandomVertexInputFormat; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.apache.log4j.Logger; import java.io.IOException; /** * Single-source shortest paths benchmark. */ public class ShortestPathsBenchmark implements Tool { /** Class logger */ private static final Logger LOG = Logger.getLogger(ShortestPathsBenchmark.class); /** Configuration */ private Configuration conf; /** * Vertex implementation */ public static class ShortestPathsBenchmarkVertex extends EdgeListVertex<LongWritable, DoubleWritable, DoubleWritable, DoubleWritable> { @Override public void compute(Iterable<DoubleWritable> messages) throws IOException { ShortestPathsComputation.computeShortestPaths(this, messages); } } @Override public Configuration getConf() { return conf; } @Override public void setConf(Configuration conf) { this.conf = conf; } @Override public final int run(final String[] args) throws Exception { Options options = new Options(); options.addOption("h", "help", false, "Help"); options.addOption("v", "verbose", false, "Verbose"); options.addOption("w", "workers", true, "Number of workers"); options.addOption("V", "aggregateVertices", true, "Aggregate vertices"); options.addOption("e", "edgesPerVertex", true, "Edges per vertex"); options.addOption("c", "vertexClass", true, "Vertex class (0 for HashMapVertex, 1 for EdgeListVertex)"); options.addOption("nc", "noCombiner", false, "Don't use a combiner"); HelpFormatter formatter = new HelpFormatter(); if (args.length == 0) { formatter.printHelp(getClass().getName(), options, true); return 0; } CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h')) { formatter.printHelp(getClass().getName(), options, true); return 0; } if (!cmd.hasOption('w')) { LOG.info("Need to choose the number of workers (-w)"); return -1; } if (!cmd.hasOption('V')) { LOG.info("Need to set the aggregate vertices (-V)"); return -1; } if (!cmd.hasOption('e')) { LOG.info("Need to set the number of edges " + "per vertex (-e)"); return -1; } int workers = Integer.parseInt(cmd.getOptionValue('w')); GiraphJob job = new GiraphJob(getConf(), getClass().getName()); if (!cmd.hasOption('c') || (Integer.parseInt(cmd.getOptionValue('c')) == 1)) { job.getConfiguration().setVertexClass(ShortestPathsBenchmarkVertex.class); } else { job.getConfiguration().setVertexClass( HashMapVertexShortestPathsBenchmark.class); } LOG.info("Using class " + job.getConfiguration().get(GiraphConfiguration.VERTEX_CLASS)); job.getConfiguration().setVertexInputFormatClass( PseudoRandomVertexInputFormat.class); if (!cmd.hasOption("nc")) { job.getConfiguration().setVertexCombinerClass( MinimumDoubleCombiner.class); } job.getConfiguration().setWorkerConfiguration(workers, workers, 100.0f); job.getConfiguration().setLong( PseudoRandomVertexInputFormat.AGGREGATE_VERTICES, Long.parseLong(cmd.getOptionValue('V'))); job.getConfiguration().setLong( PseudoRandomVertexInputFormat.EDGES_PER_VERTEX, Long.parseLong(cmd.getOptionValue('e'))); boolean isVerbose = false; if (cmd.hasOption('v')) { isVerbose = true; } if (job.run(isVerbose)) { return 0; } else { return -1; } } /** * Execute the benchmark. * * @param args Typically the command line arguments. * @throws Exception Any exception from the computation. */ public static void main(final String[] args) throws Exception { System.exit(ToolRunner.run(new ShortestPathsBenchmark(), args)); } }
aljoscha/giraph
src/main/java/org/apache/giraph/benchmark/ShortestPathsBenchmark.java
Java
apache-2.0
5,455
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Gtk; namespace SailorsTab.Common { public class UIHelper { public static void ShowErrorDialog(Gtk.Widget parent, string message, params object[] parameters) { MessageDialog messagedialog1 = new MessageDialog(findParentWindow(parent), (DialogFlags)3, MessageType.Error, ButtonsType.Ok, message, parameters); messagedialog1.Run(); messagedialog1.Destroy(); } public static int ShowInfoDialog(Gtk.Widget parent, string message, params object[] parameters) { MessageDialog messagedialog1 = new MessageDialog(findParentWindow(parent), (DialogFlags)3, MessageType.Question, ButtonsType.YesNo, false, message, parameters); int num1 = messagedialog1.Run(); messagedialog1.Destroy(); return num1; } private static Window findParentWindow(Gtk.Widget parent) { Window window = null; do { if (parent is Window) { window = (Window)parent; } else { parent = parent.Parent; } } while (window == null); return window; } } }
reinkrul/SailorsTab
SailorsTab.Common/UIHelper.cs
C#
apache-2.0
1,446
# NetApp Data ONTAP device module [![Coverage Status](https://coveralls.io/repos/fatmcgav/fatmcgav-netapp/badge.png?branch=develop)](https://coveralls.io/r/fatmcgav/fatmcgav-netapp?branch=develop) ####Table of Contents 1. [Overview](#overview) 1. [Module Description](#module-description) 1. [Setup](#setup) * [Requirements](#requirements) * [NetApp Manageability SDK](#netapp-manageability-sdk) * [Device Proxy System Setup](#device-proxy-system-setup) 1. [Usage](#usage) * [Beginning with netapp](#beginning-with-netapp) <!-- * [NetApp operations](#netapp-operations) --> * [Classes and Defined Types](#classes-and-defined-types) * [Types and Providers](#types-and-providers) 1. [Limitations](#limitations) * [TODO](#todo) 1. [Development](#development) * [Testing](#testing) * [Contributors](#contributors) ## Overview The NetApp Data ONTAP device module is designed to add support for managing NetApp Data ONTAP configuration using Puppet and its Network Device functionality. The NetApp Data ONTAP device module has been written and tested against NetApp Data ONTAP 8.2 Cluster-mode. <!-- - It may also work on 7-mode. - It should be compatible with other ONTAP versions than just 8.2, but not tested --> ## Module Description This module uses the NetApp Manageability SDK to manage various aspects of the NetApp Data ONTAP software. The following items are supported: XXX Verify these * Creation, modification and deletion of volumes, including auto-increment, snapshot schedules and volume options. * Creation, modification and deletion of QTrees. * Creation, modification and deletion of NFS Exports, including NFS export security. * Creation, modification and deletion of users, groups and roles. * Creation, modification and deletion of Quotas. * Creation of snapmirror relationships. * Creation of snapmirror schedules. ## Setup ## Requirements Because we can not directly install Puppet on the NetApp Data ONTAP operating system, it must be managed through an intermediate proxy system running `puppet device`. The requirements for the proxy system are: * Puppet 3.7 or greater * NetApp Manageability SDK Ruby libraries * Faraday gem The proxy system must be able to connect to the Puppet master (default port of 8140) and to the NetApp Data ONTAP (default port of 443). ### NetApp Manageability SDK Due to licensing, you must download the NetApp Manageability SDK separately. The NetApp Ruby libraries are contained within the NetApp Manageability SDK, which is available for download from [NetApp NOW](http://support.netapp.com/NOW/cgi-bin/software?product=NetApp+Manageability+SDK&platform=All+Platforms). Please note that you need a NetApp NOW account to download the SDK. Once you have downloaded and extracted the SDK, the Ruby SDK libraries must be copied into the module: `$ cp netapp-manageability-sdk-5.*/lib/ruby/NetApp/*.rb [module dir]/netapp/lib/puppet/netapp_sdk/` ### Device Proxy System Setup To configure a Data ONTAP device, you must create a proxy system able to run `puppet device` and have a device.conf file that refers to the NetApp ONTAP system or vserver. Refer to the [device.conf man page](https://docs.puppetlabs.com/puppet/latest/reference/config_file_device.html) for information on the format of device.conf. The netapp module can manage two different kinds of devices: Data ONTAP cluster operating system and Data ONTAP cluster vservers. The device `type` of the device.conf entry is always `netapp`. For example, if you had a Data ONTAP operating system with the node management interface addressable by the DNS name of ontap01.example.com and credentials of admin & netapp123, the device.conf entry would be: ~~~ [ontap01.example.com] type netapp url https://admin:[email protected] ~~~ Note: The device certname must match the hostname of the node. You can also specify a virtual server to operate on by providing the connection information for a physical system which is configured with the vserver and specify a path in the url that represents the name of your vserver. For example, if the above Data ONTAP node ontap01 is configured with a vserver called "vserver01," the device entry could be: ~~~ [vserver01.example.com] type netapp url https://admin:[email protected]/vserver01 ~~~ Note: The device certname does not need to match the hostname of the node as with a system device entry. You can place the device entries in the default `${confdir}/device.conf` file or create a separate config file for each device. For example, the above examples could go in `${confdir}/device/ontap01.example.com.conf` and `${confdir}/device/vserver01.example.com.conf`. Device configurations in separate files must be specified by `puppet device --deviceconfig /path/to/device-file.conf` to be used by `puppet device` run. ## Usage ### Beginning with netapp Continuing from the example in [Device Proxy System Setup](#device-proxy-system-setup), we can define a node definition for ontap01.example.com to create a vserver with an aggregate of 6 disks and a LIF: <!-- similar to https://library.netapp.com/ecmdocs/ECMP1196798/html/GUID-6D897853-FE9E-430C-971E-47096FDD462E.html --> ~~~ node 'ontap01.example.com' { netapp_aggregate { 'aggr1': ensure => present, diskcount => '6', } netapp_vserver { 'vserver01': ensure => present, rootvol => 'vserver01_root', rootvolaggr => 'aggr1', rootvolsecstyle => 'unix', } netapp_lif { 'vserver01_lif': ensure => present, homeport => 'e0c', homenode => 'ontap01', address => '10.0.207.5', vserver => 'vserver01', netmask => '255.255.255.0', dataprotocols => ['nfs'], } } ~~~ Next we should create a node definition for the vserver with a volume that has export policies for NFS, and a qtree on the volume: ~~~ node 'vserver01.example.com' { netapp_export_policy { 'nfs_exports': ensure => present, } netapp_export_rule { 'nfs_exports:1': ensure => present, clientmatch => '10.0.0.0/8', protocol => ['nfs'], superusersecurity => 'none', rorule => ['sys','none'], rwrule => ['sys','none'], } netapp_volume { 'vserver01_root': exportpolicy => 'nfs_exports', } netapp_volume { 'nfsvol': ensure => present, aggregate => 'aggr1', initsize => '200g', exportpolicy => 'nfs_exports', junctionpath => '/nfsvol', } netapp_qtree { 'qtree1': ensure => present, volume => 'nfsvol', } netapp_nfs { 'vserver01': ensure => present, state => 'on', v3 => 'disabled', v40 => 'enabled', } } ~~~ If the device configuration are both in `$confdir/device.conf`, they can now be configured by running `puppet device --verbose --user=root`. If the device configurations are is separate files, you can use the following command to run puppet against a single device at a time: ~~~ puppet device --verbose --user=root --deviceconfig /etc/puppet/device/ontap01.example.com.conf ~~~ <!-- ### NetApp operations As part of this module, there is a define called 'netapp::vqe', which can be used to create a volume, add a qtree and create an NFS export. An example of this is: ~~~ netapp::vqe { 'volume_name': ensure => present, size => '1t', aggr => 'aggr2', spaceres => 'volume', snapresv => 20, autosize => 'grow', persistent => true } ~~~ This will create a NetApp volume called `v_volume_name` with a qtree called `q_volume_name`. The volume will have an initial size of 1 Terabyte in Aggregate aggr2. The space reservation mode will be set to volume, and snapshot space reserve will be set to 20%. The volume will be able to auto increment, and the NFS export will be persistent. You can also use any of the types individually, or create new defined types as required. -->\ ### Classes and Defined Types None as of this first release. Common operations may be encapsulated in defined resource types. ### Types and Providers [`netapp_aggregate`](#type-netapp_aggregate) [`netapp_cluster_id`](#type-netapp_cluster_id) [`netapp_cluster_peer`](#type-netapp_cluster_peer) [`netapp_export_policy`](#type-netapp_export_policy) [`netapp_export_rule`](#type-netapp_export_rule) [`netapp_group`](#type-netapp_group) [`netapp_license`](#type-netapp_license) [`netapp_lif`](#type-netapp_lif) [`netapp_lun`](#type-netapp_lun) [`netapp_lun_map`](#type-netapp_lun_map) [`netapp_nfs`](#type-netapp_nfs) [`netapp_notify`](#type-netapp_notify) [`netapp_qtree`](#type-netapp_qtree) [`netapp_quota`](#type-netapp_quota) [`netapp_role`](#type-netapp_role) [`netapp_snapmirror`](#type-netapp_snapmirror) [`netapp_user`](#type-netapp_user) [`netapp_volume`](#type-netapp_volume) [`netapp_vserver`](#type-netapp_vserver) [`netapp_vserver_option`](#type-netapp_vserver_option) [`netapp_vserver_sis_config`](#type-netapp_vserver_sis_config) ### Type: netapp_aggregate Manage Netapp Aggregate creation, modification and deletion. #### Parameters All parameters, except where otherwise noted, are optional. ##### `blocktype` The indirect block format for the aggregate. Default value: '64_bit'. Valid values are `64_bit`, `32_bit`. ##### `checksumstyle` Aggregate checksum style. Default value: 'block'. Valid values are `advanced_zoned`, `block`. ##### `diskcount` Number of disks to place in the aggregate, including parity disks. ##### `disksize` Disk size with unit to assign to aggregate. ##### `disktype` Disk types to use with aggregate. Only required when multiple disk types are connected. Valid values are `ATA`, `BSAS`, `EATA`, `FCAL`, `FSAS`, `LUN`, `MSATA`, `SAS`, `SATA`, `SCSI`, `SSD`, `XATA`, `XSAS`. ##### `ensure` The basic state that the resource should be in. Valid values are `present`, `absent`. ##### `groupselectionmode` How should Data ONTAP add disks to raidgroups. Valid values are `last`, `one`, `new`, `all`. ##### `ismirrored` Should the aggregate be mirrored (have two plexes). Defaults to false. Valid values are `true`, `false`. ##### `name` The aggregate name ##### `nodes` Target nodes to create aggregate. May be an array. ##### `raidsize` Maximum number of disks in each RAID group in aggregate. Valid values are between 2 and 28 ##### `raidtype` Raid type to use in the new aggregate. Default: raid4. Valid values are `raid4`, `raid_dp`. ##### `state` The aggregate state. Default value: 'online'. Valid values are `online`, `offline`. ##### `striping` Should the new aggregate be striped? Default: not_striped. Valid values are `striped`, `not_striped`. ### Type: netapp_cluster_id Not yet reviewed. ### Type: netapp_cluster_peer Not yet reviewed. ### Type: netapp_export_policy Manage Netapp CMode Export Policy creation and deletion. #### Parameters ##### `ensure` The basic property that the resource should be in. Valid values are `present`, `absent`. ##### `name` The export policy name. ### Type: netapp_export_rule Manage Netapp CMode Export rule creation, modification and deletion. #### Parameters ##### `allowdevenabled` Should the NFS server allow creation of devices. Defaults to true. Valid values are `true`, `false`. ##### `allowsetuid` Should the NFS server allow setuid. Defaults to true. Valid values are `true`, `false`. ##### `anonuid` User name or ID to map anonymous users to. Defaults to 65534. ##### `clientmatch` *Required*. Client match specification for the export rule. May take an fqdn, IP address, IP hyphenated range, or CIDR notation. ##### `ensure` The basic state that the resource should be in. Valid values are `present`, `absent`. ##### `exportchownmode` Change ownership mode. Defaults to 'restricted'. Valid values are `restricted`, `unrestricted`. ##### `name` The export policy. Composite name based on policy name and rule index. Must take the form of `policy_name:rule_number` where the rule number is an integer and the policy name is an existing export policy. ##### `ntfsunixsecops` Ignore/Fail Unix security operations on NTFS volumes. Defaults to 'fail'. Valid values are `ignore`, `fail`. ##### `protocol` Client access protocol. Defaults to 'any'. Valid values are `any`, `nfs2`, `nfs3`, `nfs`, `cifs`, `nfs4`, `flexcache`. ##### `rorule` Property to configure read only rules. Defaults to 'any'. Valid values are `any`, `none`, `never`, `never`, `krb5`, `ntlm`, `sys`, `spinauth`. ##### `rwrule` Property to configure read write rules. Defaults to 'any'. Valid values are `any`, `none`, `never`, `never`, `krb5`, `ntlm`, `sys`, `spinauth`. ##### `superusersecurity` Superuser security flavor. Defaults to 'any'. Valid values are `any`, `none`, `never`, `never`, `krb5`, `ntlm`, `sys`, `spinauth`. ### Type: netapp_group Not yet implemented. ### Type: netapp_igroup Manage Netapp initiator groups #### Parameters ##### name **Namevar:** If omitted, this parameter's value defaults to the resource's title. Initiator group name. ##### group_type Initiator group type. Valid values are `fcp`, `iscsi`, `mixed`. ##### members An array of initiator WWPNs or aliases to be members of the initiator group. ##### os_type OS type of the initiators within the group. The os type applies to all initiators within the group and governs the finer details of SCSI protocol interaction with these initiators. Required. Valid values are `solaris`, `windows`, `hpux`, `aix`, `linux`, `netware`, `vmware`, `openvms`, `xen`, `hyper_v`. ##### portset The name of the portset to which the igroup should be bound. A value of `false` will unbind the portset. Valid values are a string or the boolean `false` ### Type: netapp_iscsi Manage Netapp ISCSI service. There may only ever be one of these declared per VServer. #### Parameters ##### svm **Namevar:** If omitted, this parameter's value defaults to the resource's title. ISCSI service SVM. ##### target_alias ISCSI WWPN alias. May be any string that is a valid ISCSI target WWPN. ##### state ISCSI service state. Valid values are `on`, `off`. ### Type: netapp_iscsi_security Manage Netapp ISCSI initiator (client) authentication. #### Parameters ##### initiator **Namevar:** If omitted, this parameter's value defaults to the resource's title. ISCSI initiator name. ##### auth_type ISCSI initiator authentication type. Valid values are `chap`, `none`, `deny`. ##### radius ISCSI radius CHAP setting. Valid values are `true`, `false`. ##### username ISCSI initiator inbound CHAP username. ##### password ISCSI initiator inbound CHAP password. Valid values are 12-16 hexidecimal digits. ##### outbound_username ISCSI initiator outbound CHAP username. ##### outbound_password ISCSI initiator outbound CHAP password. Valid values are 12-16 hexidecimal digits. ### Type: netapp_license Not yet reviewed. ### Type: netapp_lif Manage Netapp Logical Inteface (LIF) creation, modification and deletion. #### Parameters ##### `address` LIF IP address. *Required* ##### `administrativestatus` LIF administratative status. Defaults to: 'up'. Valid values are `up`, `down`. ##### `comment` LIF comment. ##### `dataprotocols` LIF data protocols. Valid values are `nfs`, `cifs`, `iscsi`, `fcp`, `fcache`, `none`. ##### `dnsdomainname` LIF dns domain name. ##### `ensure` The basic property that the resource should be in. Valid values are `present`, `absent`. ##### `failovergroup` LIF failover group name. ##### `failoverpolicy` LIF failover policy. Defaults to: 'nextavail'. Valid values are `nextavail`, `priority`, `disabled`. ##### `firewallpolicy` LIF firewall policy. Default is based on the port role. Valid values are `mgmt`, `cluster`, `intercluster`. ##### `homenode` *Required*. LIF home node. ##### `homeport` *Required*. LIF home port. ##### `interfacename` **Namevar:** If omitted, this parameter's value defaults to the resource's title. LIF name. ##### `isautorevert` Should the LIF revert to its home node. Defaults to: `false`. Valid values are `true`, `false`. ##### `netmask` LIF netmask. *Required* if `netmasklength` is not specified. ##### `netmasklength` LIF netmask length. *Required* if `netmask` is not specified. ##### `role` LIF Role. Defaults to: 'data'. Valid values are `undef`, `cluster`, `data`, `node_mgmt`, `intercluster`, `cluster_mgmt`. ##### `routinggroupname` LIF Routing group. Valid format is {dcn}{ip address}/{subnet}. ##### `usefailovergroup` Whether the failover group should be automatically created. Defaults to: 'disabled'. Valid values are `disabled`, `enabled`, `system_defined`. ##### `vserver` *Required*. LIF Vserver name. ### Type: netapp_lun Not yet reviewed. ### Type: netapp_lun_map Not yet reviewed. ### Type: netapp_nfs Manage NetApp NFS service #### Parameters ##### `vserver` **Namevar:** If omitted, this parameter's value defaults to the resource's title. NFS service SVM. This resource can only be applied to vservers, so the title is redundant. ##### `state` NFS Service State Valid values are `on`, `off`. ##### `v3` Control NFS v3 access Valid values are `enabled`, `disabled`. ##### `v40` Control NFS v4.0 access Valid values are `enabled`, `disabled`. ##### `v41` Control NFS v4.1 access Valid values are `enabled`, `disabled`. ### Type: netapp_notify Not yet reviewed. ### Type: netapp_qtree Manage Netapp Qtree creation, modification and deletion. #### Parameters ##### `ensure` The basic property that the resource should be in. Valid values are `present`, `absent`. ##### `exportpolicy` The export policy with which the qtree is associated. (Note: Not yet implemented) ##### `name` The qtree name. ##### `volume` *Required.*. The volume to create the qtree against. ### Type: netapp_quota Not yet reviewed. ### Type: netapp_role Not yet reviewed. ### Type: netapp_sis_policy Manage Netapp sis policies. #### Parameters ##### `type` The type of policy. Valid values are `threshold`, `scheduled`. ##### `job_schedule` Job schedule name. E.g., 'daily'. ##### `duration` Job duration in hours. ##### `enabled` Manage whether the sis policy is enabled. Valid values are `true`, `false`, `yes`, `no`, `enabled`, `disabled` ##### `comment` Comment for the policy. ##### `qos_policy` QoS policy name. E.g., 'best\_effort' ### Type: netapp_snapmirror Not yet reviewed. ### Type: netapp_user Not yet reviewed. ### Type: netapp_volume Manage Netapp Volume creation, modification and deletion. #### Parameters ##### `aggregate` *Required.*. The aggregate this volume should be created in. ##### `autosize` Whether volume autosize should be grow, grow/shrink, or off. Valid values are `off`, `grow`, `grow_shrink`. ##### `ensure` The basic state that the resource should be in. Valid values are `present`, `absent`. ##### `exportpolicy` The export policy with which the volume is associated. ##### `initsize` The initial volume size. *Required.* Valid format is /[0-9]+[kmgt]/. ##### `junctionpath` The fully-qualified pathname in the owning vserver's namespace at which a volume is mounted. Valid values are absolute file paths or `false`. ##### `languagecode` The language code this volume should use. Valid values are `C`, `ar`, `cs`, `da`, `de`, `en`, `en_US`, `es`, `fi`, `fr`, `he`, `hr`, `hu`, `it`, `ja`, `ja_v1`, `ko`, `no`, `nl`, `pl`, `pt`, `ro`, `ru`, `sk`, `sl`, `sv`, `tr`, `zh`, `zh_TW`. ##### `name` The volume name. Valid characters are a-z, 1-9 & underscore. ##### `options` The volume options hash. XXX Needs more details ##### `snapreserve` The percentage of space to reserve for snapshots. ##### `snapschedule` The volume snapshot schedule, in a hash format. Valid keys are: 'minutes', 'hours', 'days', 'weeks', 'which-hours', 'which-minutes'. XXX Needs an example ##### `spaceres` The space reservation mode. Valid values are `none`, `file`, `volume`. ##### `state` The volume state. Valid values are `online`, `offline`, `restricted`. ### Type: netapp_vserver Manage Netapp Vserver creation, modification and deletion. #### Parameters ##### `aggregatelist` Vserver aggregate list. May be an array. ##### `allowedprotos` Vserver allowed protocols. Valid values are `nfs`, `cifs`, `fcp`, `iscsi`, `ndmpd`. ##### `comment` Vserver comment. ##### `ensure` The basic property that the resource should be in. Valid values are `present`, `absent`. ##### `language` Vserver language. Defaults to `c.UTF-8` Valid values are `c`, `c.UTF-8`, `ar`, `cs`, `da`, `de`, `en`, `en_us`, `es`, `fi`, `fr`, `he`, `hr`, `hu`, `it`, `ja`, `ja_v1`, `ja_jp.pck`, `ja_jp.932`, `ja_jp.pck_v2`, `ko`, `no`, `nl`, `pl`, `pt`, `ro`, `ru`, `sk`, `sl`, `sv`, `tr`, `zh`, `zh.gbk`, `zh_tw`. ##### `maxvolumes` Vserver maximum allowed volumes. ##### `name` The vserver name ##### `namemappingswitch` Vserver name mapping switch. Defaults to 'file'. Valid values are `file`, `ldap`. ##### `nameserverswitch` Vserver name server switch. Valid values are `file`, `ldap`, `nis`. ##### `quotapolicy` Vserver quota policy. ##### `rootvol` *Required.* The vserver root volume. ##### `rootvolaggr` *Required.* Vserver root volume aggregate. ##### `rootvolsecstyle` *Required.* Vserver root volume security style. Valid values are `unix`, `ntfs`, `mixed`, `unified`. ##### `snapshotpolicy` Vserver snapshot policy. ##### `state` The vserver state. Valid values are `stopped`, `running`. ### Type: netapp_vserver_option Manage Netapp Vserver option modification. #### Parameters ##### `ensure` The basic property that the resource should be in. Valid values are `present`, `absent`. ##### `name` The vserver option name. ##### `value` The vserver option value. ### Type: netapp_sis_config Manage Netapp Vserver sis config modification. #### Parameters ##### `compression` Enable compression on the sis volume. Valid options: `true`, `false`. ##### `enabled` Enable sis on a volume. Valid options: `true`, `false`. ##### `ensure` The basic property that the resource should be in. Valid values are `present`, `absent`. ##### `idd` Enables file level incompressible data detection and quick check incompressible data detection for large files. Valid options: `true`, `false`. ##### `inline_compression` Enable inline compression on the sis volume. Valid options: `true`, `false`. ##### `path` (**Namevar:** If omitted, this parameter's value defaults to the resource's title.) The full path of the sis volume, `/vol/<vol_name>`. ##### `policy` The sis policy name to be attached to the volume. ##### `quick_check_fsize` Quick check file size for Incompressible Data Detection. Accepts integers Values can match `/^\d+$/`. ##### `sis_schedule` The schedule string for the sis operation. Accepts the following formats: * `day_list[@hour_list]` * `hour_list[@day_list]` * `-` * `auto` * `manual` ## TODO The following items are yet to be implemented: * Data Fabric Manager support * Support adding/deleting/modifying cifs shares * LDAP and/or AD configuration * QA remaining resources ## Development The following section applies to developers of this module only. ### Testing You will need to install the NetApp Manageability SDK Ruby libraries for most of the tests to work. How to obtain these files is detailed in the NetApp Manageability SDK section above.
ccaum/puppetlabs-netapp
README.markdown
Markdown
apache-2.0
23,418
using FluentAssertions; using Nest.Tests.MockData.Domain; using NUnit.Framework; namespace Nest.Tests.Integration.Template { [TestFixture] public class TemplateTests : IntegrationTests { [Test] public void SimplePutAndGet() { this.Client.DeleteTemplate("put-template-with-settings"); var putResponse = this.Client.PutTemplate("put-template-with-settings", t => t .Template("donotinfluencothertests-*") .Order(42) ); Assert.IsTrue(putResponse.Acknowledged); var templateResponse = this.Client.GetTemplate("put-template-with-settings"); templateResponse.Should().NotBeNull(); templateResponse.IsValid.Should().BeTrue(); templateResponse.TemplateMapping.Should().NotBeNull(); templateResponse.TemplateMapping.Mappings.Should().NotBeNull(); var settings = templateResponse.TemplateMapping.Settings; templateResponse.TemplateMapping.Order.Should().Be(42); settings.Should().NotBeNull(); } [Test] public void PutTemplateWithSettings() { this.Client.DeleteTemplate("put-template-with-settings"); var putResponse = this.Client.PutTemplate("put-template-with-settings", t=>t .Template("donotinfluencothertests-*") .Settings(s=>s .Add("index.number_of_shards", 3) .Add("index.number_of_replicas", 2) ) ); Assert.IsTrue(putResponse.Acknowledged); var templateResponse = this.Client.GetTemplate("put-template-with-settings"); templateResponse.Should().NotBeNull(); templateResponse.IsValid.Should().BeTrue(); templateResponse.TemplateMapping.Should().NotBeNull(); templateResponse.TemplateMapping.Mappings.Should().NotBeNull(); var settings = templateResponse.TemplateMapping.Settings; settings.Should().NotBeNull(); Assert.AreEqual("3", settings["index.number_of_shards"]); Assert.AreEqual("2", settings["index.number_of_replicas"]); } [Test] public void PutTemplateWithMappings() { this.Client.DeleteTemplate("put-template-with-mappings"); var putResponse = this.Client.PutTemplate("put-template-with-mappings",t => t .Template("donotinfluencothertests") .AddMapping<ElasticsearchProject>(s=>s .AllField(a=>a.Enabled(false)) ) ); Assert.IsTrue(putResponse.Acknowledged); var templateResponse = this.Client.GetTemplate("put-template-with-mappings"); templateResponse.Should().NotBeNull(); templateResponse.IsValid.Should().BeTrue(); templateResponse.TemplateMapping.Should().NotBeNull(); templateResponse.TemplateMapping.Mappings.Should().NotBeNull().And.NotBeEmpty(); var mappings = templateResponse.TemplateMapping.Mappings; Assert.IsTrue(mappings.ContainsKey("elasticsearchprojects"), "put-template-with-mappings template should have a `mytype` mapping"); Assert.NotNull(mappings["elasticsearchprojects"].AllFieldMapping, "`mytype` mapping should contain the _all field mapping"); Assert.AreEqual(false, mappings["elasticsearchprojects"].AllFieldMapping.Enabled, "_all { enabled } should be set to false"); } [Test] public void PutTemplateWithWarmers() { this.Client.DeleteTemplate("put-template-with-warmers"); var putResponse = this.Client.PutTemplate("put-template-with-warmers", t => t .Template("donotinfluencothertests2") .AddWarmer<ElasticsearchProject>(w => w .WarmerName("matchall") .Type("elasticsearchprojects") .Search(s=>s .MatchAll() ) ) ); Assert.IsTrue(putResponse.Acknowledged); var templateResponse = this.Client.GetTemplate("put-template-with-warmers"); templateResponse.Should().NotBeNull(); templateResponse.IsValid.Should().BeTrue(); templateResponse.TemplateMapping.Should().NotBeNull(); //possible elasticsearch bug https://github.com/elasticsearch/elasticsearch/issues/2868 //templateResponse.TemplateMapping.Warmers.Should().NotBeNull().And.NotBeEmpty(); } } }
Grastveit/NEST
src/Tests/Nest.Tests.Integration/Template/TemplateTests.cs
C#
apache-2.0
3,870
// // ======================================================================== // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.spdy.parser; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.jetty.spdy.SessionException; import org.eclipse.jetty.spdy.api.SessionStatus; import org.eclipse.jetty.spdy.frames.ControlFrameType; import org.eclipse.jetty.spdy.frames.CredentialFrame; public class CredentialBodyParser extends ControlFrameBodyParser { private final List<Certificate> certificates = new ArrayList<>(); private final ControlFrameParser controlFrameParser; private State state = State.SLOT; private int totalLength; private int cursor; private short slot; private int proofLength; private byte[] proof; private int certificateLength; private byte[] certificate; public CredentialBodyParser(ControlFrameParser controlFrameParser) { this.controlFrameParser = controlFrameParser; } @Override public boolean parse(ByteBuffer buffer) { while (buffer.hasRemaining()) { switch (state) { case SLOT: { if (buffer.remaining() >= 2) { slot = buffer.getShort(); checkSlotValid(); state = State.PROOF_LENGTH; } else { state = State.SLOT_BYTES; cursor = 2; } break; } case SLOT_BYTES: { byte currByte = buffer.get(); --cursor; slot += (currByte & 0xFF) << 8 * cursor; if (cursor == 0) { checkSlotValid(); state = State.PROOF_LENGTH; } break; } case PROOF_LENGTH: { if (buffer.remaining() >= 4) { proofLength = buffer.getInt() & 0x7F_FF_FF_FF; state = State.PROOF; } else { state = State.PROOF_LENGTH_BYTES; cursor = 4; } break; } case PROOF_LENGTH_BYTES: { byte currByte = buffer.get(); --cursor; proofLength += (currByte & 0xFF) << 8 * cursor; if (cursor == 0) { proofLength &= 0x7F_FF_FF_FF; state = State.PROOF; } break; } case PROOF: { totalLength = controlFrameParser.getLength() - 2 - 4 - proofLength; proof = new byte[proofLength]; if (buffer.remaining() >= proofLength) { buffer.get(proof); state = State.CERTIFICATE_LENGTH; if (totalLength == 0) { onCredential(); return true; } } else { state = State.PROOF_BYTES; cursor = proofLength; } break; } case PROOF_BYTES: { proof[proofLength - cursor] = buffer.get(); --cursor; if (cursor == 0) { state = State.CERTIFICATE_LENGTH; if (totalLength == 0) { onCredential(); return true; } } break; } case CERTIFICATE_LENGTH: { if (buffer.remaining() >= 4) { certificateLength = buffer.getInt() & 0x7F_FF_FF_FF; state = State.CERTIFICATE; } else { state = State.CERTIFICATE_LENGTH_BYTES; cursor = 4; } break; } case CERTIFICATE_LENGTH_BYTES: { byte currByte = buffer.get(); --cursor; certificateLength += (currByte & 0xFF) << 8 * cursor; if (cursor == 0) { certificateLength &= 0x7F_FF_FF_FF; state = State.CERTIFICATE; } break; } case CERTIFICATE: { totalLength -= 4 + certificateLength; certificate = new byte[certificateLength]; if (buffer.remaining() >= certificateLength) { buffer.get(certificate); if (onCertificate()) return true; } else { state = State.CERTIFICATE_BYTES; cursor = certificateLength; } break; } case CERTIFICATE_BYTES: { certificate[certificateLength - cursor] = buffer.get(); --cursor; if (cursor == 0) { if (onCertificate()) return true; } break; } default: { throw new IllegalStateException(); } } } return false; } private void checkSlotValid() { if (slot <= 0) throw new SessionException(SessionStatus.PROTOCOL_ERROR, "Invalid slot " + slot + " for " + ControlFrameType.CREDENTIAL + " frame"); } private boolean onCertificate() { certificates.add(deserializeCertificate(certificate)); if (totalLength == 0) { onCredential(); return true; } else { certificateLength = 0; state = State.CERTIFICATE_LENGTH; } return false; } private Certificate deserializeCertificate(byte[] bytes) { try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); return certificateFactory.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException x) { throw new SessionException(SessionStatus.PROTOCOL_ERROR, x); } } private void onCredential() { CredentialFrame frame = new CredentialFrame(controlFrameParser.getVersion(), slot, Arrays.copyOf(proof, proof.length), certificates.toArray(new Certificate[certificates.size()])); controlFrameParser.onControlFrame(frame); reset(); } private void reset() { state = State.SLOT; totalLength = 0; cursor = 0; slot = 0; proofLength = 0; proof = null; certificateLength = 0; certificate = null; certificates.clear(); } public enum State { SLOT, SLOT_BYTES, PROOF_LENGTH, PROOF_LENGTH_BYTES, PROOF, PROOF_BYTES, CERTIFICATE_LENGTH, CERTIFICATE_LENGTH_BYTES, CERTIFICATE, CERTIFICATE_BYTES } }
xmpace/jetty-read
jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/parser/CredentialBodyParser.java
Java
apache-2.0
9,058
# Stephanotis acuminata Brongn. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Asclepiadaceae/Stephanotis/Stephanotis acuminata/README.md
Markdown
apache-2.0
179
package com.ctrip.xpipe.redis.core.protocal; /** * @author wenchao.meng * * 2016年3月24日 下午6:27:48 */ public interface RedisProtocol { int REDIS_PORT_DEFAULT = 6379; int KEEPER_PORT_DEFAULT = 6380; int RUN_ID_LENGTH = 40; String CRLF = "\r\n"; String OK = "OK"; String KEEPER_ROLE_PREFIX = "keeperrole"; static String booleanToString(boolean yes){ if(yes){ return "yes"; } return "no"; } }
ctripcorp/x-pipe
redis/redis-core/src/main/java/com/ctrip/xpipe/redis/core/protocal/RedisProtocol.java
Java
apache-2.0
432
<? namespace CodeCraft; use CodeCraft\Helpers\LanguageLink; class SiteRouter { private $language = []; private $defaultLanguage = 'ru'; private $languageUrlMap = []; private $languageList = ['ru' => ['ru', 'be', 'uk', 'ky', 'ab', 'mo', 'et', 'lv'], 'en' => 'en']; /** * @param array $languageUrlMap - ['language' => 'url', ..., 'default' => 'url'] */ public function __construct($languageUrlMap) { $this->setLanguageUrlMap($languageUrlMap); if (($list = strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']))) { if (preg_match_all('/([a-z]{1,8}(?:-[a-z]{1,8})?)(?:;q=([0-9.]+))?/', $list, $list)) { $this->language = array_combine($list[1], $list[2]); foreach ($this->language as $n => $v) { $this->language[$n] = $v ? $v : 1; } arsort($this->language, SORT_NUMERIC); } } else { $this->language = []; } } /** * @param array $languageUrlMap */ public function setLanguageUrlMap(array $languageUrlMap) { $this->languageUrlMap = $languageUrlMap; } /** * @return array */ public function getLanguageUrlMap() { return $this->languageUrlMap; } /** * @param array $languageList * * @return string */ private function getBestMatch(array $languageList) { $languages = array(); foreach ($languageList as $lang => $alias) { if (is_array($alias)) { foreach ($alias as $alias_lang) { $languages[strtolower($alias_lang)] = strtolower($lang); } } else { $languages[strtolower($alias)] = strtolower($lang); } } foreach ($this->language as $l => $v) { $s = strtok($l, '-'); if (isset($languages[$s])) { return $languages[$s]; } } return $this->defaultLanguage; } /** * @param array $languageList */ public function setLanguageList(array $languageList) { $this->languageList = $languageList; } /** * @param string $pathTo404 */ public function route($pathTo404 = '') { $language = $this->getBestMatch($this->languageList); $languageUrlMap = $this->getLanguageUrlMap(); LanguageLink::setRootAlternateHeader($language); if ($languageUrlMap[$language] || $languageUrlMap['default']) { LocalRedirect($languageUrlMap[$language] ?: $languageUrlMap['default'], false, '301 Moved Permanently'); } else { $this->showNotFoundPage($pathTo404); } } /** * @param string $pathTo404 * * @buffer_restart * * @require 404 page * * @die */ public function showNotFoundPage($pathTo404 = '') { if (!$pathTo404) { $pathTo404 = $_SERVER['DOCUMENT_ROOT'] . '/' . $this->getBestMatch($this->languageList) . '/404.php'; } global $APPLICATION; $APPLICATION->RestartBuffer(); try { require_once($pathTo404); } catch (\Exception $e) { \CHTTP::SetStatus('404 Not Found'); echo '<h1>404 Not Found</h1>'; } die; } }
code-craft-ru/bx-features
local/php_interface/include/classes/CodeCraft/SiteRouter.php
PHP
apache-2.0
3,685
// // YRMConst.h // Budejie // // Created by 叶仁明 on 2017/2/6. // Copyright © 2017年 叶仁明. All rights reserved. // #import <UIKit/UIKit.h> UIKIT_EXTERN CGFloat const YRMTitlesViewH; UIKIT_EXTERN CGFloat const YRMTitlesViewY; UIKIT_EXTERN CGFloat const YRMTopicCellTextY; UIKIT_EXTERN CGFloat const YRMTopicCellBottomToolBarH; UIKIT_EXTERN CGFloat const YRMTopicCellMargin; //图片最大的高度,超过该高度显示查看完整图片的按钮 UIKIT_EXTERN CGFloat const YRMTopicCellPictureMaxH; //图片超过最大高度时,显示的截取图片的高度 UIKIT_EXTERN CGFloat const YRMTopicCellPictureBreakH;
yrming/Budejie-iOS
Budejie/Budejie/Classes/Other/YRMConst.h
C
apache-2.0
636
package com.pi.xerosync.dbconnect; /** * User: thomas Date: 18/02/14 */ public interface XeroCredentials { String getXeroConsumerKey(); String getXeroConsumerSecret(); String getPrivateKeyPath(); }
tom-haines/patricia-xero-sync
patricia-xero-webapp/src/main/java/com/pi/xerosync/dbconnect/XeroCredentials.java
Java
apache-2.0
207
# Eucalyptus laevis L.A.S. Johnson & K.D. Hill SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Eucalyptus/Eucalyptus laevis/README.md
Markdown
apache-2.0
202
# Sarcophyllis J.G. Agardh, 1876 GENUS #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Rhodophyta/Florideophyceae/Gigartinales/Dumontiaceae/Sarcophyllis/README.md
Markdown
apache-2.0
186
# Melasmia spiralis Petr. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Sydowia 7(1-4): 149 (1953) #### Original name Melasmia spiralis Petr. ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Leotiomycetes/Rhytismatales/Rhytismataceae/Melasmia/Melasmia spiralis/README.md
Markdown
apache-2.0
197
# Sylphia cabellensis (Rchb.f.) Luer SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Specklinia/Specklinia cabellensis/ Syn. Sylphia cabellensis/README.md
Markdown
apache-2.0
191
# Eucalyptus hawkeri Rule SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Eucalyptus/Eucalyptus hawkeri/README.md
Markdown
apache-2.0
173
# Agaricus croceo-caeruleus Pers. SPECIES #### Status SYNONYM #### According to Index Fungorum #### Published in null #### Original name Agaricus croceo-caeruleus Pers. ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Cortinariaceae/Cortinarius/Cortinarius croceocaeruleus/ Syn. Agaricus croceo-caeruleus/README.md
Markdown
apache-2.0
190
# Flotowia Endl. GENUS #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Flotowia/README.md
Markdown
apache-2.0
162
# Scindapsus cuscuaria (Aubl.) C.Presl SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Alismatales/Araceae/Scindapsus/Scindapsus cuscuaria/README.md
Markdown
apache-2.0
194
# Urera aurantiaca Wedd. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Urticaceae/Urera/Urera aurantiaca/README.md
Markdown
apache-2.0
172
# Decaneurum epilejum DC. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Phyllocephalum scabridum/ Syn. Decaneurum epilejum/README.md
Markdown
apache-2.0
180
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_45) on Wed Aug 28 02:24:21 PDT 2013 --> <TITLE> ActivityChooserModel.ActivitySorter </TITLE> <META NAME="date" CONTENT="2013-08-28"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ActivityChooserModel.ActivitySorter"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ActivityChooserModel.ActivitySorter.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.ActivityResolveInfo.html" title="class in android.support.v7.internal.widget"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.HistoricalRecord.html" title="class in android.support.v7.internal.widget"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?android/support/v7/internal/widget/ActivityChooserModel.ActivitySorter.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ActivityChooserModel.ActivitySorter.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> android.support.v7.internal.widget</FONT> <BR> Interface ActivityChooserModel.ActivitySorter</H2> <DL> <DT><B>Enclosing class:</B><DD><A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.html" title="class in android.support.v7.internal.widget">ActivityChooserModel</A></DD> </DL> <HR> <DL> <DT><PRE>public static interface <B>ActivityChooserModel.ActivitySorter</B></DL> </PRE> <P> Defines a sorter that is responsible for sorting the activities based on the provided historical choices and an intent. <P> <P> <HR> <P> <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.ActivitySorter.html#sort(Intent, java.util.List, java.util.List)">sort</A></B>(Intent&nbsp;intent, java.util.List&lt;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.ActivityResolveInfo.html" title="class in android.support.v7.internal.widget">ActivityChooserModel.ActivityResolveInfo</A>&gt;&nbsp;activities, java.util.List&lt;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.HistoricalRecord.html" title="class in android.support.v7.internal.widget">ActivityChooserModel.HistoricalRecord</A>&gt;&nbsp;historicalRecords)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sorts the <code>activities</code> in descending order of relevance based on previous history and an intent.</TD> </TR> </TABLE> &nbsp; <P> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="sort(Intent, java.util.List, java.util.List)"><!-- --></A><H3> sort</H3> <PRE> void <B>sort</B>(Intent&nbsp;intent, java.util.List&lt;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.ActivityResolveInfo.html" title="class in android.support.v7.internal.widget">ActivityChooserModel.ActivityResolveInfo</A>&gt;&nbsp;activities, java.util.List&lt;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.HistoricalRecord.html" title="class in android.support.v7.internal.widget">ActivityChooserModel.HistoricalRecord</A>&gt;&nbsp;historicalRecords)</PRE> <DL> <DD>Sorts the <code>activities</code> in descending order of relevance based on previous history and an intent. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>intent</CODE> - The <CODE>Intent</CODE>.<DD><CODE>activities</CODE> - Activities to be sorted.<DD><CODE>historicalRecords</CODE> - Historical records.</DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ActivityChooserModel.ActivitySorter.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.ActivityResolveInfo.html" title="class in android.support.v7.internal.widget"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../android/support/v7/internal/widget/ActivityChooserModel.HistoricalRecord.html" title="class in android.support.v7.internal.widget"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?android/support/v7/internal/widget/ActivityChooserModel.ActivitySorter.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ActivityChooserModel.ActivitySorter.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
mkolbly/MortgageComparerProject
support/v7/appcompat/docs/android-support-v7-appcompat/android/support/v7/internal/widget/ActivityChooserModel.ActivitySorter.html
HTML
apache-2.0
10,363
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>AdminLTE 2 | Editors</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.6 --> <link rel="stylesheet" href="../../bootstrap/css/bootstrap.min.css"> <!-- Font Awesome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css"> <!-- Theme style --> <link rel="stylesheet" href="../../dist/css/AdminLTE.min.css"> <!-- AdminLTE Skins. Choose a skin from the css/skins folder instead of downloading all of them to reduce the load. --> <link rel="stylesheet" href="../../dist/css/skins/_all-skins.min.css"> <!-- bootstrap wysihtml5 - text editor --> <link rel="stylesheet" href="../../plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body class="hold-transition skin-blue sidebar-mini"> <div class="wrapper"> <header class="main-header"> <!-- Logo --> <a href="../../index2.html" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><b>A</b>LT</span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>Admin</b>LTE</span> </a> <!-- Header Navbar: style can be found in header.less --> <nav class="navbar navbar-static-top"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> <!-- Messages: style can be found in dropdown.less--> <li class="dropdown messages-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-envelope-o"></i> <span class="label label-success">4</span> </a> <ul class="dropdown-menu"> <li class="header">You have 4 messages</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li><!-- start message --> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> </div> <h4> Support Team <small><i class="fa fa-clock-o"></i> 5 mins</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <!-- end message --> <li> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user3-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> AdminLTE Design Team <small><i class="fa fa-clock-o"></i> 2 hours</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <li> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user4-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> Developers <small><i class="fa fa-clock-o"></i> Today</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <li> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user3-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> Sales Department <small><i class="fa fa-clock-o"></i> Yesterday</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <li> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user4-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> Reviewers <small><i class="fa fa-clock-o"></i> 2 days</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> </ul> </li> <li class="footer"><a href="#">See All Messages</a></li> </ul> </li> <!-- Notifications: style can be found in dropdown.less --> <li class="dropdown notifications-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-bell-o"></i> <span class="label label-warning">10</span> </a> <ul class="dropdown-menu"> <li class="header">You have 10 notifications</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li> <a href="#"> <i class="fa fa-users text-aqua"></i> 5 new members joined today </a> </li> <li> <a href="#"> <i class="fa fa-warning text-yellow"></i> Very long description here that may not fit into the page and may cause design problems </a> </li> <li> <a href="#"> <i class="fa fa-users text-red"></i> 5 new members joined </a> </li> <li> <a href="#"> <i class="fa fa-shopping-cart text-green"></i> 25 sales made </a> </li> <li> <a href="#"> <i class="fa fa-user text-red"></i> You changed your username </a> </li> </ul> </li> <li class="footer"><a href="#">View all</a></li> </ul> </li> <!-- Tasks: style can be found in dropdown.less --> <li class="dropdown tasks-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-flag-o"></i> <span class="label label-danger">9</span> </a> <ul class="dropdown-menu"> <li class="header">You have 9 tasks</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li><!-- Task item --> <a href="#"> <h3> Design some buttons <small class="pull-right">20%</small> </h3> <div class="progress xs"> <div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">20% Complete</span> </div> </div> </a> </li> <!-- end task item --> <li><!-- Task item --> <a href="#"> <h3> Create a nice theme <small class="pull-right">40%</small> </h3> <div class="progress xs"> <div class="progress-bar progress-bar-green" style="width: 40%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">40% Complete</span> </div> </div> </a> </li> <!-- end task item --> <li><!-- Task item --> <a href="#"> <h3> Some task I need to do <small class="pull-right">60%</small> </h3> <div class="progress xs"> <div class="progress-bar progress-bar-red" style="width: 60%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">60% Complete</span> </div> </div> </a> </li> <!-- end task item --> <li><!-- Task item --> <a href="#"> <h3> Make beautiful transitions <small class="pull-right">80%</small> </h3> <div class="progress xs"> <div class="progress-bar progress-bar-yellow" style="width: 80%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">80% Complete</span> </div> </div> </a> </li> <!-- end task item --> </ul> </li> <li class="footer"> <a href="#">View all tasks</a> </li> </ul> </li> <!-- User Account: style can be found in dropdown.less --> <li class="dropdown user user-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <img src="../../dist/img/user2-160x160.jpg" class="user-image" alt="User Image"> <span class="hidden-xs">Alexander Pierce</span> </a> <ul class="dropdown-menu"> <!-- User image --> <li class="user-header"> <img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> <p> Alexander Pierce - Web Developer <small>Member since Nov. 2012</small> </p> </li> <!-- Menu Body --> <li class="user-body"> <div class="row"> <div class="col-xs-4 text-center"> <a href="#">Followers</a> </div> <div class="col-xs-4 text-center"> <a href="#">Sales</a> </div> <div class="col-xs-4 text-center"> <a href="#">Friends</a> </div> </div> <!-- /.row --> </li> <!-- Menu Footer--> <li class="user-footer"> <div class="pull-left"> <a href="#" class="btn btn-default btn-flat">Profile</a> </div> <div class="pull-right"> <a href="#" class="btn btn-default btn-flat">Sign out</a> </div> </li> </ul> </li> <!-- Control Sidebar Toggle Button --> <li> <a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a> </li> </ul> </div> </nav> </header> <!-- Left side column. contains the logo and sidebar --> <aside class="main-sidebar"> <!-- sidebar: style can be found in sidebar.less --> <section class="sidebar"> <!-- Sidebar user panel --> <div class="user-panel"> <div class="pull-left image"> <img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> </div> <div class="pull-left info"> <p>Alexander Pierce</p> <a href="#"><i class="fa fa-circle text-success"></i> Online</a> </div> </div> <!-- search form --> <form action="#" method="get" class="sidebar-form"> <div class="input-group"> <input type="text" name="q" class="form-control" placeholder="Search..."> <span class="input-group-btn"> <button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i> </button> </span> </div> </form> <!-- /.search form --> <!-- sidebar menu: : style can be found in sidebar.less --> <ul class="sidebar-menu"> <li class="header">MAIN NAVIGATION</li> <li class="treeview"> <a href="#"> <i class="fa fa-dashboard"></i> <span>Dashboard</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../../index.html"><i class="fa fa-circle-o"></i> Dashboard v1</a></li> <li><a href="../../index2.html"><i class="fa fa-circle-o"></i> Dashboard v2</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-files-o"></i> <span>Layout Options</span> <span class="pull-right-container"> <span class="label label-primary pull-right">4</span> </span> </a> <ul class="treeview-menu"> <li><a href="../layout/top-nav.html"><i class="fa fa-circle-o"></i> Top Navigation</a></li> <li><a href="../layout/boxed.html"><i class="fa fa-circle-o"></i> Boxed</a></li> <li><a href="../layout/fixed.html"><i class="fa fa-circle-o"></i> Fixed</a></li> <li><a href="../layout/collapsed-sidebar.html"><i class="fa fa-circle-o"></i> Collapsed Sidebar</a></li> </ul> </li> <li> <a href="../widgets.html"> <i class="fa fa-th"></i> <span>Widgets</span> <span class="pull-right-container"> <small class="label pull-right bg-green">new</small> </span> </a> </li> <li class="treeview"> <a href="#"> <i class="fa fa-pie-chart"></i> <span>Charts</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../charts/chartjs.html"><i class="fa fa-circle-o"></i> ChartJS</a></li> <li><a href="../charts/morris.html"><i class="fa fa-circle-o"></i> Morris</a></li> <li><a href="../charts/flot.html"><i class="fa fa-circle-o"></i> Flot</a></li> <li><a href="../charts/inline.html"><i class="fa fa-circle-o"></i> Inline charts</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-laptop"></i> <span>UI Elements</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../UI/general.html"><i class="fa fa-circle-o"></i> General</a></li> <li><a href="../UI/icons.html"><i class="fa fa-circle-o"></i> Icons</a></li> <li><a href="../UI/buttons.html"><i class="fa fa-circle-o"></i> Buttons</a></li> <li><a href="../UI/sliders.html"><i class="fa fa-circle-o"></i> Sliders</a></li> <li><a href="../UI/timeline.html"><i class="fa fa-circle-o"></i> Timeline</a></li> <li><a href="../UI/modals.html"><i class="fa fa-circle-o"></i> Modals</a></li> </ul> </li> <li class="treeview active"> <a href="#"> <i class="fa fa-edit"></i> <span>Forms</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="general.html"><i class="fa fa-circle-o"></i> General Elements</a></li> <li><a href="advanced.html"><i class="fa fa-circle-o"></i> Advanced Elements</a></li> <li class="active"><a href="editors.html"><i class="fa fa-circle-o"></i> Editors</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-table"></i> <span>Tables</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../tables/simple.html"><i class="fa fa-circle-o"></i> Simple tables</a></li> <li><a href="../tables/data.html"><i class="fa fa-circle-o"></i> Data tables</a></li> </ul> </li> <li> <a href="../calendar.html"> <i class="fa fa-calendar"></i> <span>Calendar</span> <span class="pull-right-container"> <small class="label pull-right bg-red">3</small> <small class="label pull-right bg-blue">17</small> </span> </a> </li> <li> <a href="../mailbox/mailbox.html"> <i class="fa fa-envelope"></i> <span>Mailbox</span> <span class="pull-right-container"> <small class="label pull-right bg-yellow">12</small> <small class="label pull-right bg-green">16</small> <small class="label pull-right bg-red">5</small> </span> </a> </li> <li class="treeview"> <a href="#"> <i class="fa fa-folder"></i> <span>Examples</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../examples/invoice.html"><i class="fa fa-circle-o"></i> Invoice</a></li> <li><a href="../examples/profile.html"><i class="fa fa-circle-o"></i> Profile</a></li> <li><a href="../examples/login.html"><i class="fa fa-circle-o"></i> Login</a></li> <li><a href="../examples/register.html"><i class="fa fa-circle-o"></i> Register</a></li> <li><a href="../examples/lockscreen.html"><i class="fa fa-circle-o"></i> Lockscreen</a></li> <li><a href="../examples/404.html"><i class="fa fa-circle-o"></i> 404 Error</a></li> <li><a href="../examples/500.html"><i class="fa fa-circle-o"></i> 500 Error</a></li> <li><a href="../examples/blank.html"><i class="fa fa-circle-o"></i> Blank Page</a></li> <li><a href="../examples/pace.html"><i class="fa fa-circle-o"></i> Pace Page</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-share"></i> <span>Multilevel</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o"></i> Level One</a></li> <li> <a href="#"><i class="fa fa-circle-o"></i> Level One <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o"></i> Level Two</a></li> <li> <a href="#"><i class="fa fa-circle-o"></i> Level Two <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o"></i> Level Three</a></li> <li><a href="#"><i class="fa fa-circle-o"></i> Level Three</a></li> </ul> </li> </ul> </li> <li><a href="#"><i class="fa fa-circle-o"></i> Level One</a></li> </ul> </li> <li><a href="../../documentation/index.html"><i class="fa fa-book"></i> <span>Documentation</span></a></li> <!-- 文章管理 --> <li class="treeview"> <a href="#"> <i class="glyphicon glyphicon-list-alt"></i> <span>文章管理</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../tables/article.html"><i class="fa fa-circle-o"></i>文章管理</a></li> <li><a href="#"><i class="fa fa-circle-o"></i>铝锭走势分析</a></li> <li><a href="#"><i class="fa fa-circle-o"></i>国际铝行情</a></li> <li><a href="#"><i class="fa fa-circle-o"></i>上海铝协动态</a></li> </ul> </li> <li class="header">LABELS</li> <li><a href="#"><i class="fa fa-circle-o text-red"></i> <span>Important</span></a></li> <li><a href="#"><i class="fa fa-circle-o text-yellow"></i> <span>Warning</span></a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> <span>Information</span></a></li> </ul> </section> <!-- /.sidebar --> </aside> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Text Editors <small>Advanced form element</small> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li> <li><a href="#">Forms</a></li> <li class="active">Editors</li> </ol> </section> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-md-12"> <div class="box box-info"> <div class="box-header"> <h3 class="box-title">CK Editor <small>Advanced and full of features</small> </h3> <!-- tools box --> <div class="pull-right box-tools"> <button type="button" class="btn btn-info btn-sm" data-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fa fa-minus"></i></button> <button type="button" class="btn btn-info btn-sm" data-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fa fa-times"></i></button> </div> <!-- /. tools --> </div> <!-- /.box-header --> <div class="box-body pad"> <form> <textarea id="editor1" name="editor1" rows="10" cols="80"> This is my textarea to be replaced with CKEditor. </textarea> </form> </div> </div> <!-- /.box --> <div class="box"> <div class="box-header"> <h3 class="box-title">Bootstrap WYSIHTML5 <small>Simple and fast</small> </h3> <!-- tools box --> <div class="pull-right box-tools"> <button type="button" class="btn btn-default btn-sm" data-widget="collapse" data-toggle="tooltip" title="Collapse"> <i class="fa fa-minus"></i></button> <button type="button" class="btn btn-default btn-sm" data-widget="remove" data-toggle="tooltip" title="Remove"> <i class="fa fa-times"></i></button> </div> <!-- /. tools --> </div> <!-- /.box-header --> <div class="box-body pad"> <form> <textarea class="textarea" placeholder="Place some text here" style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea> </form> </div> </div> </div> <!-- /.col--> </div> <!-- ./row --> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <footer class="main-footer"> <div class="pull-right hidden-xs"> <b>Version</b> 2.3.6 </div> <strong>Copyright &copy; 2014-2016 <a href="http://almsaeedstudio.com">Almsaeed Studio</a>.</strong> All rights reserved. </footer> <!-- Control Sidebar --> <aside class="control-sidebar control-sidebar-dark"> <!-- Create the tabs --> <ul class="nav nav-tabs nav-justified control-sidebar-tabs"> <li><a href="#control-sidebar-home-tab" data-toggle="tab"><i class="fa fa-home"></i></a></li> <li><a href="#control-sidebar-settings-tab" data-toggle="tab"><i class="fa fa-gears"></i></a></li> </ul> <!-- Tab panes --> <div class="tab-content"> <!-- Home tab content --> <div class="tab-pane" id="control-sidebar-home-tab"> <h3 class="control-sidebar-heading">Recent Activity</h3> <ul class="control-sidebar-menu"> <li> <a href="javascript:void(0)"> <i class="menu-icon fa fa-birthday-cake bg-red"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">Langdon's Birthday</h4> <p>Will be 23 on April 24th</p> </div> </a> </li> <li> <a href="javascript:void(0)"> <i class="menu-icon fa fa-user bg-yellow"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">Frodo Updated His Profile</h4> <p>New phone +1(800)555-1234</p> </div> </a> </li> <li> <a href="javascript:void(0)"> <i class="menu-icon fa fa-envelope-o bg-light-blue"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">Nora Joined Mailing List</h4> <p>[email protected]</p> </div> </a> </li> <li> <a href="javascript:void(0)"> <i class="menu-icon fa fa-file-code-o bg-green"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">Cron Job 254 Executed</h4> <p>Execution time 5 seconds</p> </div> </a> </li> </ul> <!-- /.control-sidebar-menu --> <h3 class="control-sidebar-heading">Tasks Progress</h3> <ul class="control-sidebar-menu"> <li> <a href="javascript:void(0)"> <h4 class="control-sidebar-subheading"> Custom Template Design <span class="label label-danger pull-right">70%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-danger" style="width: 70%"></div> </div> </a> </li> <li> <a href="javascript:void(0)"> <h4 class="control-sidebar-subheading"> Update Resume <span class="label label-success pull-right">95%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-success" style="width: 95%"></div> </div> </a> </li> <li> <a href="javascript:void(0)"> <h4 class="control-sidebar-subheading"> Laravel Integration <span class="label label-warning pull-right">50%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-warning" style="width: 50%"></div> </div> </a> </li> <li> <a href="javascript:void(0)"> <h4 class="control-sidebar-subheading"> Back End Framework <span class="label label-primary pull-right">68%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-primary" style="width: 68%"></div> </div> </a> </li> </ul> <!-- /.control-sidebar-menu --> </div> <!-- /.tab-pane --> <!-- Stats tab content --> <div class="tab-pane" id="control-sidebar-stats-tab">Stats Tab Content</div> <!-- /.tab-pane --> <!-- Settings tab content --> <div class="tab-pane" id="control-sidebar-settings-tab"> <form method="post"> <h3 class="control-sidebar-heading">General Settings</h3> <div class="form-group"> <label class="control-sidebar-subheading"> Report panel usage <input type="checkbox" class="pull-right" checked> </label> <p> Some information about this general settings option </p> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> Allow mail redirect <input type="checkbox" class="pull-right" checked> </label> <p> Other sets of options are available </p> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> Expose author name in posts <input type="checkbox" class="pull-right" checked> </label> <p> Allow the user to show his name in blog posts </p> </div> <!-- /.form-group --> <h3 class="control-sidebar-heading">Chat Settings</h3> <div class="form-group"> <label class="control-sidebar-subheading"> Show me as online <input type="checkbox" class="pull-right" checked> </label> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> Turn off notifications <input type="checkbox" class="pull-right"> </label> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> Delete chat history <a href="javascript:void(0)" class="text-red pull-right"><i class="fa fa-trash-o"></i></a> </label> </div> <!-- /.form-group --> </form> </div> <!-- /.tab-pane --> </div> </aside> <!-- /.control-sidebar --> <!-- Add the sidebar's background. This div must be placed immediately after the control sidebar --> <div class="control-sidebar-bg"></div> </div> <!-- ./wrapper --> <!-- jQuery 2.2.3 --> <script src="../../plugins/jQuery/jquery-2.2.3.min.js"></script> <!-- Bootstrap 3.3.6 --> <script src="../../bootstrap/js/bootstrap.min.js"></script> <!-- FastClick --> <script src="../../plugins/fastclick/fastclick.js"></script> <!-- AdminLTE App --> <script src="../../dist/js/app.min.js"></script> <!-- AdminLTE for demo purposes --> <script src="../../dist/js/demo.js"></script> <!-- CK Editor --> <script src="https://cdn.ckeditor.com/4.5.7/standard/ckeditor.js"></script> <!-- Bootstrap WYSIHTML5 --> <script src="../../plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script> <script> $(function () { // Replace the <textarea id="editor1"> with a CKEditor // instance, using default configuration. CKEDITOR.replace('editor1'); //bootstrap WYSIHTML5 - text editor $(".textarea").wysihtml5(); }); </script> </body> </html>
Tjiahong/AdminLTE
pages/forms/editors.html
HTML
apache-2.0
34,146
# coding=utf-8 # Copyright 2022 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Base classes and utilities for image datasets.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import io import os import numpy as np from tensor2tensor.data_generators import generator_utils from tensor2tensor.data_generators import problem from tensor2tensor.data_generators import text_encoder from tensor2tensor.layers import common_layers from tensor2tensor.layers import modalities from tensor2tensor.utils import contrib from tensor2tensor.utils import metrics import tensorflow.compat.v1 as tf def matplotlib_pyplot(): import matplotlib # pylint: disable=g-import-not-at-top matplotlib.use("agg") import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top return plt def image_to_tf_summary_value(image, tag): """Converts a NumPy image to a tf.Summary.Value object. Args: image: 3-D NumPy array. tag: name for tf.Summary.Value for display in tensorboard. Returns: image_summary: A tf.Summary.Value object. """ curr_image = np.asarray(image, dtype=np.uint8) height, width, n_channels = curr_image.shape # If monochrome image, then reshape to [height, width] if n_channels == 1: curr_image = np.reshape(curr_image, [height, width]) s = io.BytesIO() matplotlib_pyplot().imsave(s, curr_image, format="png") img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(), height=height, width=width, colorspace=n_channels) return tf.Summary.Value(tag=tag, image=img_sum) def convert_predictions_to_image_summaries(hook_args): """Optionally converts images from hooks_args to image summaries. Args: hook_args: DecodeHookArgs namedtuple Returns: summaries: list of tf.Summary values if hook_args.decode_hpara """ decode_hparams = hook_args.decode_hparams if not decode_hparams.display_decoded_images: return [] predictions = hook_args.predictions[0] # Display ten random inputs and outputs so that tensorboard does not hang. all_summaries = [] rand_predictions = np.random.choice(predictions, size=10) for ind, prediction in enumerate(rand_predictions): output_summary = image_to_tf_summary_value( prediction["outputs"], tag="%d_output" % ind) input_summary = image_to_tf_summary_value( prediction["inputs"], tag="%d_input" % ind) all_summaries.append(input_summary) all_summaries.append(output_summary) return all_summaries def resize_by_area(img, size): """image resize function used by quite a few image problems.""" return tf.to_int64( tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA)) def make_multiscale(image, resolutions, resize_method=tf.image.ResizeMethod.BICUBIC, num_channels=3): """Returns list of scaled images, one for each resolution. Args: image: Tensor of shape [height, height, num_channels]. resolutions: List of heights that image's height is resized to. resize_method: tf.image.ResizeMethod. num_channels: Number of channels in image. Returns: List of Tensors, one for each resolution with shape given by [resolutions[i], resolutions[i], num_channels]. """ scaled_images = [] for height in resolutions: scaled_image = tf.image.resize_images( image, size=[height, height], # assuming that height = width method=resize_method) scaled_image = tf.to_int64(scaled_image) scaled_image.set_shape([height, height, num_channels]) scaled_images.append(scaled_image) return scaled_images def make_multiscale_dilated(image, resolutions, num_channels=3): """Returns list of scaled images, one for each resolution. Resizes by skipping every nth pixel. Args: image: Tensor of shape [height, height, num_channels]. resolutions: List of heights that image's height is resized to. The function assumes VALID padding, so the original image's height must be divisible by each resolution's height to return the exact resolution size. num_channels: Number of channels in image. Returns: List of Tensors, one for each resolution with shape given by [resolutions[i], resolutions[i], num_channels] if resolutions properly divide the original image's height; otherwise shape height and width is up to valid skips. """ image_height = common_layers.shape_list(image)[0] scaled_images = [] for height in resolutions: dilation_rate = image_height // height # assuming height = width scaled_image = image[::dilation_rate, ::dilation_rate] scaled_image = tf.to_int64(scaled_image) scaled_image.set_shape([None, None, num_channels]) scaled_images.append(scaled_image) return scaled_images class ImageProblem(problem.Problem): """Base class for problems with images.""" @property def num_channels(self): """Number of color channels.""" return 3 @property def vocab_size(self): """Number of pixel values.""" return 256 def example_reading_spec(self): data_fields = { "image/encoded": tf.FixedLenFeature((), tf.string), "image/format": tf.FixedLenFeature((), tf.string), } data_items_to_decoders = { "inputs": contrib.slim().tfexample_decoder.Image( image_key="image/encoded", format_key="image/format", channels=self.num_channels), } return data_fields, data_items_to_decoders def preprocess_example(self, example, mode, hparams): if not self._was_reversed: example["inputs"] = tf.image.per_image_standardization(example["inputs"]) return example def eval_metrics(self): eval_metrics = [ metrics.Metrics.ACC, metrics.Metrics.ACC_TOP5, metrics.Metrics.ACC_PER_SEQ, metrics.Metrics.NEG_LOG_PERPLEXITY ] if self._was_reversed: eval_metrics += [metrics.Metrics.IMAGE_SUMMARY] return eval_metrics @property def decode_hooks(self): return [convert_predictions_to_image_summaries] class Image2ClassProblem(ImageProblem): """Base class for image classification problems.""" @property def is_small(self): raise NotImplementedError() @property def num_classes(self): raise NotImplementedError() @property def train_shards(self): raise NotImplementedError() @property def dev_shards(self): return 1 @property def class_labels(self): return ["ID_%d" % i for i in range(self.num_classes)] def feature_encoders(self, data_dir): del data_dir return { "inputs": text_encoder.ImageEncoder(channels=self.num_channels), "targets": text_encoder.ClassLabelEncoder(self.class_labels) } def generator(self, data_dir, tmp_dir, is_training): raise NotImplementedError() def example_reading_spec(self): label_key = "image/class/label" data_fields, data_items_to_decoders = ( super(Image2ClassProblem, self).example_reading_spec()) data_fields[label_key] = tf.FixedLenFeature((1,), tf.int64) data_items_to_decoders["targets"] = contrib.slim().tfexample_decoder.Tensor( label_key) return data_fields, data_items_to_decoders def hparams(self, defaults, unused_model_hparams): p = defaults p.modality = {"inputs": modalities.ModalityType.IMAGE, "targets": modalities.ModalityType.CLASS_LABEL} p.vocab_size = {"inputs": 256, "targets": self.num_classes} p.batch_size_multiplier = 4 if self.is_small else 256 p.loss_multiplier = 3.0 if self.is_small else 1.0 if self._was_reversed: p.loss_multiplier = 1.0 p.input_space_id = problem.SpaceID.IMAGE p.target_space_id = problem.SpaceID.IMAGE_LABEL def generate_data(self, data_dir, tmp_dir, task_id=-1): generator_utils.generate_dataset_and_shuffle( self.generator(data_dir, tmp_dir, True), self.training_filepaths(data_dir, self.train_shards, shuffled=False), self.generator(data_dir, tmp_dir, False), self.dev_filepaths(data_dir, self.dev_shards, shuffled=False)) def encode_images_as_png(images): """Yield images encoded as pngs.""" if tf.executing_eagerly(): for image in images: yield tf.image.encode_png(image).numpy() else: (height, width, channels) = images[0].shape with tf.Graph().as_default(): image_t = tf.placeholder(dtype=tf.uint8, shape=(height, width, channels)) encoded_image_t = tf.image.encode_png(image_t) with tf.Session() as sess: for image in images: enc_string = sess.run(encoded_image_t, feed_dict={image_t: image}) yield enc_string def image_generator(images, labels): """Generator for images that takes image and labels lists and creates pngs. Args: images: list of images given as [width x height x channels] numpy arrays. labels: list of ints, same length as images. Yields: A dictionary representing the images with the following fields: * image/encoded: the string encoding the image as PNG, * image/format: the string "png" representing image format, * image/class/label: an integer representing the label, * image/height: an integer representing the height, * image/width: an integer representing the width. Every field is actually a singleton list of the corresponding type. Raises: ValueError: if images is an empty list. """ if not images: raise ValueError("Must provide some images for the generator.") width, height, _ = images[0].shape for (enc_image, label) in zip(encode_images_as_png(images), labels): yield { "image/encoded": [enc_image], "image/format": ["png"], "image/class/label": [int(label)], "image/height": [height], "image/width": [width] } class Image2TextProblem(ImageProblem): """Base class for image-to-text problems.""" @property def is_character_level(self): raise NotImplementedError() @property def vocab_problem(self): raise NotImplementedError() # Not needed if self.is_character_level. @property def target_space_id(self): raise NotImplementedError() @property def train_shards(self): raise NotImplementedError() @property def dev_shards(self): raise NotImplementedError() def generator(self, data_dir, tmp_dir, is_training): raise NotImplementedError() def example_reading_spec(self): label_key = "image/class/label" data_fields, data_items_to_decoders = ( super(Image2TextProblem, self).example_reading_spec()) data_fields[label_key] = tf.VarLenFeature(tf.int64) data_items_to_decoders["targets"] = contrib.slim().tfexample_decoder.Tensor( label_key) return data_fields, data_items_to_decoders def feature_encoders(self, data_dir): if self.is_character_level: encoder = text_encoder.ByteTextEncoder() else: vocab_filename = os.path.join( data_dir, self.vocab_problem.vocab_filename) encoder = text_encoder.SubwordTextEncoder(vocab_filename) input_encoder = text_encoder.ImageEncoder(channels=self.num_channels) return {"inputs": input_encoder, "targets": encoder} def hparams(self, defaults, unused_model_hparams): p = defaults p.modality = {"inputs": modalities.ModalityType.IMAGE, "targets": modalities.ModalityType.SYMBOL} p.vocab_size = {"inputs": 256, "targets": self._encoders["targets"].vocab_size} p.batch_size_multiplier = 256 p.loss_multiplier = 1.0 p.input_space_id = problem.SpaceID.IMAGE p.target_space_id = self.target_space_id def generate_data(self, data_dir, tmp_dir, task_id=-1): generator_utils.generate_dataset_and_shuffle( self.generator(data_dir, tmp_dir, True), self.training_filepaths(data_dir, self.train_shards, shuffled=False), self.generator(data_dir, tmp_dir, False), self.dev_filepaths(data_dir, self.dev_shards, shuffled=False)) def image_augmentation(images, do_colors=False, crop_size=None): """Image augmentation: cropping, flipping, and color transforms.""" if crop_size is None: crop_size = [299, 299] images = tf.random_crop(images, crop_size + [3]) images = tf.image.random_flip_left_right(images) if do_colors: # More augmentation, but might be slow. images = tf.image.random_brightness(images, max_delta=32. / 255.) images = tf.image.random_saturation(images, lower=0.5, upper=1.5) images = tf.image.random_hue(images, max_delta=0.2) images = tf.image.random_contrast(images, lower=0.5, upper=1.5) return images def cifar_image_augmentation(images): """Image augmentation suitable for CIFAR-10/100. As described in https://arxiv.org/pdf/1608.06993v3.pdf (page 5). Args: images: a Tensor. Returns: Tensor of the same shape as images. """ images = tf.image.resize_image_with_crop_or_pad(images, 40, 40) images = tf.random_crop(images, [32, 32, 3]) images = tf.image.random_flip_left_right(images) return images def random_shift(image, wsr=0.1, hsr=0.1): """Apply random horizontal and vertical shift to images. This is the default data-augmentation strategy used on CIFAR in Glow. Args: image: a 3-D Tensor wsr: Width shift range, as a float fraction of the width. hsr: Height shift range, as a float fraction of the width. Returns: images: images translated by the provided wsr and hsr. """ height, width, _ = common_layers.shape_list(image) width_range, height_range = wsr*width, hsr*height height_translations = tf.random_uniform((1,), -height_range, height_range) width_translations = tf.random_uniform((1,), -width_range, width_range) translations = tf.concat((height_translations, width_translations), axis=0) return contrib.image().translate(image, translations=translations)
tensorflow/tensor2tensor
tensor2tensor/data_generators/image_utils.py
Python
apache-2.0
14,495
/// <reference path='fourslash.ts' /> // @BaselineFile: bpSpan_interface.baseline // @Filename: bpSpan_interface.ts ////interface I { //// property: string; //// method(): number; //// (a: string): string; //// new (a: string): I; //// [a: number]: number; ////} ////module m { //// interface I1 { //// property: string; //// method(): number; //// (a: string): string; //// new (a: string): I; //// [a: number]: number; //// } //// export interface I2 { //// property: string; //// method(): number; //// (a: string): string; //// new (a: string): I; //// [a: number]: number; //// } ////} verify.baselineCurrentFileBreakpointLocations();
freedot/tstolua
tests/cases/fourslash/breakpointValidationInterface.ts
TypeScript
apache-2.0
738
package main.java; public class SelectionSort9 { public static <T extends Comparable<T>> void sort(final T[] a) { for (int i = 0; i < a.length - 1; i++) { int min = i; for (int j = i + 1; j < a.length; j++) { if (a[j].compareTo(a[min]) < 0) { min = j; } } if (i != min) { final T tmp = a[min]; a[min] = a[i]; a[i] = tmp; } } } }
peteriliev/kata
SelectionSort/src/main/java/SelectionSort9.java
Java
apache-2.0
381
package com.sequenceiq.environment.api.v1.environment.model.response; import java.io.Serializable; import com.sequenceiq.environment.api.doc.environment.EnvironmentModelDescription; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel("EnvironmentAuthenticationV1Response") public class EnvironmentAuthenticationResponse implements Serializable { @ApiModelProperty(EnvironmentModelDescription.PUBLIC_KEY) private String publicKey; @ApiModelProperty(EnvironmentModelDescription.PUBLIC_KEY_ID) private String publicKeyId; @ApiModelProperty(EnvironmentModelDescription.LOGIN_USER_NAME) private String loginUserName; public String getPublicKey() { return publicKey; } public void setPublicKey(String publicKey) { this.publicKey = publicKey; } public String getPublicKeyId() { return publicKeyId; } public void setPublicKeyId(String publicKeyId) { this.publicKeyId = publicKeyId; } public String getLoginUserName() { return loginUserName; } public void setLoginUserName(String loginUserName) { this.loginUserName = loginUserName; } public static Builder builder() { return new Builder(); } @Override public String toString() { return "EnvironmentAuthenticationResponse{" + "publicKey='" + publicKey + '\'' + ", publicKeyId='" + publicKeyId + '\'' + ", loginUserName='" + loginUserName + '\'' + '}'; } public static class Builder { private String publicKey; private String publicKeyId; private String loginUserName; private Builder() { } public Builder withPublicKey(String publicKey) { this.publicKey = publicKey; return this; } public Builder withPublicKeyId(String publicKeyId) { this.publicKeyId = publicKeyId; return this; } public Builder withLoginUserName(String loginUserName) { this.loginUserName = loginUserName; return this; } public EnvironmentAuthenticationResponse build() { EnvironmentAuthenticationResponse response = new EnvironmentAuthenticationResponse(); response.setLoginUserName(loginUserName); response.setPublicKey(publicKey); response.setPublicKeyId(publicKeyId); return response; } } }
hortonworks/cloudbreak
environment-api/src/main/java/com/sequenceiq/environment/api/v1/environment/model/response/EnvironmentAuthenticationResponse.java
Java
apache-2.0
2,539
/* * This file is part of "lunisolar-magma". * * (C) Copyright 2014-2022 Lunisolar (http://lunisolar.eu/). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.lunisolar.magma.func.predicate; import javax.annotation.Nonnull; // NOSONAR import javax.annotation.Nullable; // NOSONAR import javax.annotation.concurrent.NotThreadSafe; // NOSONAR import java.util.Comparator; // NOSONAR import java.util.Objects; // NOSONAR import eu.lunisolar.magma.basics.*; //NOSONAR import eu.lunisolar.magma.basics.builder.*; // NOSONAR import eu.lunisolar.magma.basics.exceptions.*; // NOSONAR import eu.lunisolar.magma.basics.meta.*; // NOSONAR import eu.lunisolar.magma.basics.meta.aType.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR import eu.lunisolar.magma.func.IA; import eu.lunisolar.magma.func.SA; import eu.lunisolar.magma.func.*; // NOSONAR import eu.lunisolar.magma.func.tuple.*; // NOSONAR import java.util.concurrent.*; // NOSONAR import java.util.function.*; // NOSONAR import java.util.*; // NOSONAR import java.lang.reflect.*; // NOSONAR import eu.lunisolar.magma.func.action.*; // NOSONAR import eu.lunisolar.magma.func.consumer.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR import eu.lunisolar.magma.func.function.*; // NOSONAR import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR import eu.lunisolar.magma.func.function.from.*; // NOSONAR import eu.lunisolar.magma.func.function.to.*; // NOSONAR import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR import eu.lunisolar.magma.func.predicate.*; // NOSONAR import eu.lunisolar.magma.func.supplier.*; // NOSONAR /** * Non-throwing functional interface (lambda) LBiObjLongPredicate for Java 8. * * Type: predicate * * Domain (lvl: 3): T1 a1,T2 a2,long a3 * * Co-domain: boolean * */ @FunctionalInterface @SuppressWarnings("UnusedDeclaration") public interface LBiObjLongPredicate<T1, T2> extends MetaPredicate, MetaInterface.NonThrowing, Codomain<aBool>, Domain3<a<T1>, a<T2>, aLong> { // NOSONAR String DESCRIPTION = "LBiObjLongPredicate: boolean test(T1 a1,T2 a2,long a3)"; // boolean test(T1 a1,T2 a2,long a3) ; default boolean test(T1 a1, T2 a2, long a3) { // return nestingTest(a1,a2,a3); try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call test(T1 a1,T2 a2,long a3) */ boolean testX(T1 a1, T2 a2, long a3) throws Throwable; default boolean tupleTest(LBiObjLongTriple<T1, T2> args) { return test(args.first(), args.second(), args.third()); } /** Function call that handles exceptions according to the instructions. */ default boolean handlingTest(T1 a1, T2 a2, long a3, HandlingInstructions<Throwable, RuntimeException> handling) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handler.handleOrNest(e, handling); } } default LBiObjLongPredicate<T1, T2> handling(HandlingInstructions<Throwable, RuntimeException> handling) { return (a1, a2, a3) -> handlingTest(a1, a2, a3, handling); } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage); } } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage, param1); } } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage, param1, param2); } } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage, param1, param2, param3); } } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage); } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage, param1); } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage, param1, param1); } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage, param1, param2, param3); } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWF<RuntimeException> factory) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory); } } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWF<RuntimeException> factory) { return (a1, a2, a3) -> test(a1, a2, a3, factory); } default boolean testThen(T1 a1, T2 a2, long a3, @Nonnull LPredicate<Throwable> handler) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR Handling.handleErrors(e); return handler.test(e); } } default LBiObjLongPredicate<T1, T2> tryingThen(@Nonnull LPredicate<Throwable> handler) { return (a1, a2, a3) -> testThen(a1, a2, a3, handler); } /** Function call that handles exceptions by always nesting checked exceptions and propagating the others as is. */ default boolean nestingTest(T1 a1, T2 a2, long a3) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** Function call that handles exceptions by always propagating them as is, even when they are undeclared checked ones. */ default boolean shovingTest(T1 a1, T2 a2, long a3) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.shoveIt(e); } } static <T1, T2> boolean shovingTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.shovingTest(a1, a2, a3); } static <T1, T2> boolean handlingTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, HandlingInstructions<Throwable, RuntimeException> handling) { // <- Null.nonNullArg(func, "func"); return func.handlingTest(a1, a2, a3, handling); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.nestingTest(a1, a2, a3); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage, param1); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage, param1, param2); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage, param1, param2, param3); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWF<RuntimeException> factory) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory); } static <T1, T2> boolean tryTestThen(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull LPredicate<Throwable> handler) { Null.nonNullArg(func, "func"); return func.testThen(a1, a2, a3, handler); } default boolean failSafeTest(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<T1, T2> failSafe) { try { return test(a1, a2, a3); } catch (Throwable e) { // NOSONAR Handling.handleErrors(e); return failSafe.test(a1, a2, a3); } } static <T1, T2> boolean failSafeTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull LBiObjLongPredicate<T1, T2> failSafe) { Null.nonNullArg(failSafe, "failSafe"); if (func == null) { return failSafe.test(a1, a2, a3); } else { return func.failSafeTest(a1, a2, a3, failSafe); } } static <T1, T2> LBiObjLongPredicate<T1, T2> failSafe(LBiObjLongPredicate<T1, T2> func, @Nonnull LBiObjLongPredicate<T1, T2> failSafe) { Null.nonNullArg(failSafe, "failSafe"); return (a1, a2, a3) -> failSafeTest(a1, a2, a3, func, failSafe); } default boolean doIf(T1 a1, T2 a2, long a3, LAction action) { Null.nonNullArg(action, "action"); if (test(a1, a2, a3)) { action.execute(); return true; } else { return false; } } static <T1, T2> boolean doIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<T1, T2> predicate, @Nonnull LAction action) { Null.nonNullArg(predicate, "predicate"); return predicate.doIf(a1, a2, a3, action); } static <T1, T2> boolean doIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<T1, T2> predicate, @Nonnull LBiObjLongConsumer<? super T1, ? super T2> consumer) { Null.nonNullArg(predicate, "predicate"); return predicate.doIf(a1, a2, a3, consumer); } default boolean doIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongConsumer<? super T1, ? super T2> consumer) { Null.nonNullArg(consumer, "consumer"); if (test(a1, a2, a3)) { consumer.accept(a1, a2, a3); return true; } else { return false; } } /** Just to mirror the method: Ensures the result is not null */ default boolean nonNullTest(T1 a1, T2 a2, long a3) { return test(a1, a2, a3); } /** For convenience, where "test()" makes things more confusing than "applyAsBoolean()". */ default boolean doApplyAsBoolean(T1 a1, T2 a2, long a3) { return test(a1, a2, a3); } /** Returns description of the functional interface. */ @Nonnull default String functionalInterfaceDescription() { return LBiObjLongPredicate.DESCRIPTION; } /** From-To. Intended to be used with non-capturing lambda. */ public static <T1, T2> void fromTo(long min_a3, long max_a3, T1 a1, T2 a2, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); if (min_a3 <= max_a3) { for (long a3 = min_a3; a3 <= max_a3; a3++) { func.test(a1, a2, a3); } } else { for (long a3 = min_a3; a3 >= max_a3; a3--) { func.test(a1, a2, a3); } } } /** From-To. Intended to be used with non-capturing lambda. */ public static <T1, T2> void fromTill(long min_a3, long max_a3, T1 a1, T2 a2, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); if (min_a3 <= max_a3) { for (long a3 = min_a3; a3 < max_a3; a3++) { func.test(a1, a2, a3); } } else { for (long a3 = min_a3; a3 > max_a3; a3--) { func.test(a1, a2, a3); } } } /** From-To. Intended to be used with non-capturing lambda. */ public static <T1, T2> void times(long max_a3, T1 a1, T2 a2, @Nonnull LBiObjLongPredicate<T1, T2> func) { if (max_a3 < 0) return; fromTill(0, max_a3, a1, a2, func); } /** Extract and apply function. */ public static <M, K, V, T2> boolean from(@Nonnull M container, LBiFunction<M, K, V> extractor, K key, T2 a2, long a3, @Nonnull LBiObjLongPredicate<V, T2> function) { Null.nonNullArg(container, "container"); Null.nonNullArg(function, "function"); V value = extractor.apply(container, key); if (value != null) { return function.test(value, a2, a3); } return false; } default LObjLongPredicate<T2> lShrink(@Nonnull LObjLongFunction<T2, T1> left) { Null.nonNullArg(left, "left"); return (a2, a3) -> test(left.apply(a2, a3), a2, a3); } default LObjLongPredicate<T2> lShrink_(T1 a1) { return (a2, a3) -> test(a1, a2, a3); } public static <T2, T1> LObjLongPredicate<T2> lShrunken(@Nonnull LObjLongFunction<T2, T1> left, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(left, "left"); Null.nonNullArg(func, "func"); return func.lShrink(left); } public static <T2, T1> LObjLongPredicate<T2> lShrunken_(T1 a1, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.lShrink_(a1); } default LBiPredicate<T1, T2> rShrink(@Nonnull LToLongBiFunction<T1, T2> right) { Null.nonNullArg(right, "right"); return (a1, a2) -> test(a1, a2, right.applyAsLong(a1, a2)); } default LBiPredicate<T1, T2> rShrink_(long a3) { return (a1, a2) -> test(a1, a2, a3); } public static <T1, T2> LBiPredicate<T1, T2> rShrunken(@Nonnull LToLongBiFunction<T1, T2> right, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(right, "right"); Null.nonNullArg(func, "func"); return func.rShrink(right); } public static <T1, T2> LBiPredicate<T1, T2> rShrunken_(long a3, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.rShrink_(a3); } /** */ public static <T1, T2> LBiObjLongPredicate<T1, T2> uncurry(@Nonnull LFunction<T1, LFunction<T2, LLongPredicate>> func) { Null.nonNullArg(func, "func"); return (T1 a1, T2 a2, long a3) -> func.apply(a1).apply(a2).test(a3); } /** Cast that removes generics. */ default LBiObjLongPredicate untyped() { return this; } /** Cast that replace generics. */ default <V2, V3> LBiObjLongPredicate<V2, V3> cast() { return untyped(); } /** Cast that replace generics. */ public static <V2, V3> LBiObjLongPredicate<V2, V3> cast(LBiObjLongPredicate<?, ?> function) { return (LBiObjLongPredicate) function; } /** Change function to consumer that ignores output. */ default LBiObjLongConsumer<T1, T2> toConsumer() { return this::test; } /** Calls domain consumer before main function. */ default LBiObjLongPredicate<T1, T2> beforeDo(@Nonnull LBiObjLongConsumer<T1, T2> before) { Null.nonNullArg(before, "before"); return (T1 a1, T2 a2, long a3) -> { before.accept(a1, a2, a3); return test(a1, a2, a3); }; } /** Calls codomain consumer after main function. */ default LBiObjLongPredicate<T1, T2> afterDo(@Nonnull LBoolConsumer after) { Null.nonNullArg(after, "after"); return (T1 a1, T2 a2, long a3) -> { final boolean retval = test(a1, a2, a3); after.accept(retval); return retval; }; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (!pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (!pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(msg, a1, a2, a3) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2, param3) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(msg, a1, a2, a3) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2, param3) + ' ' + m); } return a1; } /** Captures arguments but delays the evaluation. */ default LBoolSupplier capture(T1 a1, T2 a2, long a3) { return () -> this.test(a1, a2, a3); } /** Creates function that always returns the same value. */ static <T1, T2> LBiObjLongPredicate<T1, T2> constant(boolean r) { return (a1, a2, a3) -> r; } /** Captures single parameter function into this interface where only 1st parameter will be used. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> test1st(@Nonnull LPredicate<T1> func) { return (a1, a2, a3) -> func.test(a1); } /** Captures single parameter function into this interface where only 2nd parameter will be used. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> test2nd(@Nonnull LPredicate<T2> func) { return (a1, a2, a3) -> func.test(a2); } /** Captures single parameter function into this interface where only 3rd parameter will be used. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> test3rd(@Nonnull LLongPredicate func) { return (a1, a2, a3) -> func.test(a3); } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPred(final @Nonnull LBiObjLongPredicate<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** A completely inconvenient method in case lambda expression and generic arguments are ambiguous for the compiler. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPred(@Nullable Class<T1> c1, @Nullable Class<T2> c2, final @Nonnull LBiObjLongPredicate<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } final class S<T1, T2> implements LBiObjLongPredicate<T1, T2> { private LBiObjLongPredicate<T1, T2> target = null; @Override public boolean testX(T1 a1, T2 a2, long a3) throws Throwable { return target.testX(a1, a2, a3); } } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> recursive(final @Nonnull LFunction<LBiObjLongPredicate<T1, T2>, LBiObjLongPredicate<T1, T2>> selfLambda) { final S<T1, T2> single = new S(); LBiObjLongPredicate<T1, T2> func = selfLambda.apply(single); single.target = func; return func; } public static <T1, T2> M<T1, T2> mementoOf(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> function) { var initialValue = function.test(a1, a2, a3); return initializedMementoOf(initialValue, function); } public static <T1, T2> M<T1, T2> initializedMementoOf(boolean initialValue, LBiObjLongPredicate<T1, T2> function) { return memento(initialValue, initialValue, function, (m, x1, x2) -> x2); } public static <T1, T2> M<T1, T2> deltaOf(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> function, LLogicalBinaryOperator deltaFunction) { var initialValue = function.test(a1, a2, a3); return initializedDeltaOf(initialValue, function, deltaFunction); } public static <T1, T2> M<T1, T2> deltaOf(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> function) { var initialValue = function.test(a1, a2, a3); return initializedDeltaOf(initialValue, function, (x1, x2) -> x1 != x2); } public static <T1, T2> M<T1, T2> initializedDeltaOf(boolean initialValue, LBiObjLongPredicate<T1, T2> function, LLogicalBinaryOperator deltaFunction) { return memento(initialValue, deltaFunction.apply(initialValue, initialValue), function, (m, x1, x2) -> deltaFunction.apply(x1, x2)); } public static <T1, T2> M<T1, T2> memento(boolean initialBaseValue, boolean initialValue, LBiObjLongPredicate<T1, T2> baseFunction, LLogicalTernaryOperator mementoFunction) { return new M(initialBaseValue, initialValue, baseFunction, mementoFunction); } /** * Implementation that allows to create derivative functions (do not confuse it with math concepts). Very short name is intended to be used with parent (LBiObjLongPredicate.M) */ @NotThreadSafe final class M<T1, T2> implements LBiObjLongPredicate<T1, T2> { private final LBiObjLongPredicate<T1, T2> baseFunction; private boolean lastBaseValue; private boolean lastValue; private final LLogicalTernaryOperator mementoFunction; private M(boolean lastBaseValue, boolean lastValue, LBiObjLongPredicate<T1, T2> baseFunction, LLogicalTernaryOperator mementoFunction) { this.baseFunction = baseFunction; this.lastBaseValue = lastBaseValue; this.lastValue = lastValue; this.mementoFunction = mementoFunction; } @Override public boolean testX(T1 a1, T2 a2, long a3) throws Throwable { boolean x1 = lastBaseValue; boolean x2 = lastBaseValue = baseFunction.testX(a1, a2, a3); return lastValue = mementoFunction.apply(lastValue, x1, x2); } public boolean lastValue() { return lastValue; }; public boolean lastBaseValue() { return lastBaseValue; }; } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPredThrowing(final @Nonnull ExF<Throwable> exF) { Null.nonNullArg(exF, "exF"); return (a1, a2, a3) -> { throw exF.produce(); }; } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPredThrowing(final String message, final @Nonnull ExMF<Throwable> exF) { Null.nonNullArg(exF, "exF"); return (a1, a2, a3) -> { throw exF.produce(message); }; } // <editor-fold desc="wrap variants"> /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T1, T2> LBiObjLongPredicate.LObj0Long2Obj1Pred<T1, T2> obj0Long2Obj1Pred(final @Nonnull LBiObjLongPredicate.LObj0Long2Obj1Pred<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T2, T1> LBiObjLongPredicate.LObj1Obj0Long2Pred<T2, T1> obj1Obj0Long2Pred(final @Nonnull LBiObjLongPredicate.LObj1Obj0Long2Pred<T2, T1> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T2, T1> LBiObjLongPredicate.LObj1Long2Obj0Pred<T2, T1> obj1Long2Obj0Pred(final @Nonnull LBiObjLongPredicate.LObj1Long2Obj0Pred<T2, T1> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T1, T2> LBiObjLongPredicate.LLong2Obj0Obj1Pred<T1, T2> long2Obj0Obj1Pred(final @Nonnull LBiObjLongPredicate.LLong2Obj0Obj1Pred<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T2, T1> LBiObjLongPredicate.LLong2Obj1Obj0Pred<T2, T1> long2Obj1Obj0Pred(final @Nonnull LBiObjLongPredicate.LLong2Obj1Obj0Pred<T2, T1> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } // </editor-fold> static <T1, T2> boolean call(T1 a1, T2 a2, long a3, final @Nonnull LBiObjLongPredicate<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda.test(a1, a2, a3); } // <editor-fold desc="wrap"> // </editor-fold> // <editor-fold desc="predicate"> /** * Returns a predicate that represents the logical negation of this predicate. * * @see {@link java.util.function.Predicate#negate} */ @Nonnull default LBiObjLongPredicate<T1, T2> negate() { return (a1, a2, a3) -> !test(a1, a2, a3); } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> not(@Nonnull LBiObjLongPredicate<T1, T2> pred) { Null.nonNullArg(pred, "pred"); return pred.negate(); } /** * Returns a predicate that represents the logical AND of evaluation of this predicate and the argument one. * @see {@link java.util.function.Predicate#and()} */ @Nonnull default LBiObjLongPredicate<T1, T2> and(@Nonnull LBiObjLongPredicate<? super T1, ? super T2> other) { Null.nonNullArg(other, "other"); return (a1, a2, a3) -> test(a1, a2, a3) && other.test(a1, a2, a3); } @Nonnull public static <T1, T2> LBiObjLongPredicate<T1, T2> and(@Nonnull LBiObjLongPredicate<? super T1, ? super T2>... predicates) { Null.nonNullArg(predicates, "predicates"); return (a1, a2, a3) -> { for (LBiObjLongPredicate<? super T1, ? super T2> p : predicates) { if (!p.test(a1, a2, a3)) { return false; } } return true; }; } /** * Returns a predicate that represents the logical OR of evaluation of this predicate and the argument one. * @see {@link java.util.function.Predicate#or} */ @Nonnull default LBiObjLongPredicate<T1, T2> or(@Nonnull LBiObjLongPredicate<? super T1, ? super T2> other) { Null.nonNullArg(other, "other"); return (a1, a2, a3) -> test(a1, a2, a3) || other.test(a1, a2, a3); } @Nonnull public static <T1, T2> LBiObjLongPredicate<T1, T2> or(@Nonnull LBiObjLongPredicate<? super T1, ? super T2>... predicates) { Null.nonNullArg(predicates, "predicates"); return (a1, a2, a3) -> { for (LBiObjLongPredicate<? super T1, ? super T2> p : predicates) { if (p.test(a1, a2, a3)) { return true; } } return false; }; } /** * Returns a predicate that represents the logical XOR of evaluation of this predicate and the argument one. * @see {@link java.util.function.Predicate#or} */ @Nonnull default LBiObjLongPredicate<T1, T2> xor(@Nonnull LBiObjLongPredicate<? super T1, ? super T2> other) { Null.nonNullArg(other, "other"); return (a1, a2, a3) -> test(a1, a2, a3) ^ other.test(a1, a2, a3); } /** * Creates predicate that evaluates if an object is equal with the argument one. * @see {@link java.util.function.Predicate#isEqual() */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> isEqual(T1 v1, T2 v2, long v3) { return (a1, a2, a3) -> (a1 == null ? v1 == null : a1.equals(v1)) && (a2 == null ? v2 == null : a2.equals(v2)) && (a3 == v3); } // </editor-fold> // <editor-fold desc="compose (functional)"> /** Allows to manipulate the domain of the function. */ @Nonnull default <V1, V2> LBiObjLongPredicate<V1, V2> compose(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LLongUnaryOperator before3) { Null.nonNullArg(before1, "before1"); Null.nonNullArg(before2, "before2"); Null.nonNullArg(before3, "before3"); return (v1, v2, v3) -> this.test(before1.apply(v1), before2.apply(v2), before3.applyAsLong(v3)); } public static <V1, V2, T1, T2> LBiObjLongPredicate<V1, V2> composed(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LLongUnaryOperator before3, LBiObjLongPredicate<T1, T2> after) { return after.compose(before1, before2, before3); } /** Allows to manipulate the domain of the function. */ @Nonnull default <V1, V2, V3> LTriPredicate<V1, V2, V3> biObjLongPredCompose(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LToLongFunction<? super V3> before3) { Null.nonNullArg(before1, "before1"); Null.nonNullArg(before2, "before2"); Null.nonNullArg(before3, "before3"); return (v1, v2, v3) -> this.test(before1.apply(v1), before2.apply(v2), before3.applyAsLong(v3)); } public static <V1, V2, V3, T1, T2> LTriPredicate<V1, V2, V3> composed(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LToLongFunction<? super V3> before3, LBiObjLongPredicate<T1, T2> after) { return after.biObjLongPredCompose(before1, before2, before3); } // </editor-fold> // <editor-fold desc="then (functional)"> /** Combines two functions together in a order. */ @Nonnull default <V> LBiObjLongFunction<T1, T2, V> boolToBiObjLongFunc(@Nonnull LBoolFunction<? extends V> after) { Null.nonNullArg(after, "after"); return (a1, a2, a3) -> after.apply(this.test(a1, a2, a3)); } /** Combines two functions together in a order. */ @Nonnull default LBiObjLongPredicate<T1, T2> boolToBiObjLongPred(@Nonnull LLogicalOperator after) { Null.nonNullArg(after, "after"); return (a1, a2, a3) -> after.apply(this.test(a1, a2, a3)); } // </editor-fold> // <editor-fold desc="variant conversions"> // </editor-fold> // <editor-fold desc="interface variants"> /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LObj0Long2Obj1Pred<T1, T2> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call test(T1 a1,T2 a2,long a3) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testObj0Long2Obj1(a1, a3, a2); } // boolean testObj0Long2Obj1(T1 a1,long a3,T2 a2) ; default boolean testObj0Long2Obj1(T1 a1, long a3, T2 a2) { // return nestingTestObj0Long2Obj1(a1,a3,a2); try { return this.testObj0Long2Obj1X(a1, a3, a2); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testObj0Long2Obj1(T1 a1,long a3,T2 a2) */ boolean testObj0Long2Obj1X(T1 a1, long a3, T2 a2) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LObj1Obj0Long2Pred<T2, T1> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testObj0Long2Obj1(T1 a1,long a3,T2 a2) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testObj1Obj0Long2(a2, a1, a3); } // boolean testObj1Obj0Long2(T2 a2,T1 a1,long a3) ; default boolean testObj1Obj0Long2(T2 a2, T1 a1, long a3) { // return nestingTestObj1Obj0Long2(a2,a1,a3); try { return this.testObj1Obj0Long2X(a2, a1, a3); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testObj1Obj0Long2(T2 a2,T1 a1,long a3) */ boolean testObj1Obj0Long2X(T2 a2, T1 a1, long a3) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LObj1Long2Obj0Pred<T2, T1> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testObj1Obj0Long2(T2 a2,T1 a1,long a3) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testObj1Long2Obj0(a2, a3, a1); } // boolean testObj1Long2Obj0(T2 a2,long a3,T1 a1) ; default boolean testObj1Long2Obj0(T2 a2, long a3, T1 a1) { // return nestingTestObj1Long2Obj0(a2,a3,a1); try { return this.testObj1Long2Obj0X(a2, a3, a1); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testObj1Long2Obj0(T2 a2,long a3,T1 a1) */ boolean testObj1Long2Obj0X(T2 a2, long a3, T1 a1) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LLong2Obj0Obj1Pred<T1, T2> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testObj1Long2Obj0(T2 a2,long a3,T1 a1) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testLong2Obj0Obj1(a3, a1, a2); } // boolean testLong2Obj0Obj1(long a3,T1 a1,T2 a2) ; default boolean testLong2Obj0Obj1(long a3, T1 a1, T2 a2) { // return nestingTestLong2Obj0Obj1(a3,a1,a2); try { return this.testLong2Obj0Obj1X(a3, a1, a2); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testLong2Obj0Obj1(long a3,T1 a1,T2 a2) */ boolean testLong2Obj0Obj1X(long a3, T1 a1, T2 a2) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LLong2Obj1Obj0Pred<T2, T1> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testLong2Obj0Obj1(long a3,T1 a1,T2 a2) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testLong2Obj1Obj0(a3, a2, a1); } // boolean testLong2Obj1Obj0(long a3,T2 a2,T1 a1) ; default boolean testLong2Obj1Obj0(long a3, T2 a2, T1 a1) { // return nestingTestLong2Obj1Obj0(a3,a2,a1); try { return this.testLong2Obj1Obj0X(a3, a2, a1); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testLong2Obj1Obj0(long a3,T2 a2,T1 a1) */ boolean testLong2Obj1Obj0X(long a3, T2 a2, T1 a1) throws Throwable; } // </editor-fold> // >>> LBiObjLongPredicate<T1,T2> /** Returns TRUE. */ public static <T1, T2> boolean alwaysTrue(T1 a1, T2 a2, long a3) { return true; } /** Returns FALSE. */ public static <T1, T2> boolean alwaysFalse(T1 a1, T2 a2, long a3) { return false; } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, C3> void filterForEach(IndexedRead<C1, a<T1>> ia1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); size = Integer.min(size, ia2.size(source2)); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); size = Integer.min(size, ia3.size(source3)); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; for (; i < size; i++) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = oiFunc2.apply(source2, i); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, I1, C2, C3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); int size = ia2.size(source2); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); size = Integer.min(size, ia3.size(source3)); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; while (testFunc1.test(iterator1) && i < size) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = oiFunc2.apply(source2, i); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, I2, C3> void filterIterate(IndexedRead<C1, a<T1>> ia1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); size = Integer.min(size, ia3.size(source3)); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; while (i < size && testFunc2.test(iterator2)) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = nextFunc2.apply(iterator2); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, I1, C2, I2, C3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); int size = ia3.size(source3); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; while (testFunc1.test(iterator1) && testFunc2.test(iterator2) && i < size) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = nextFunc2.apply(iterator2); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, C3, I3> void filterIterate(IndexedRead<C1, a<T1>> ia1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); size = Integer.min(size, ia2.size(source2)); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); int i = 0; while (i < size && testFunc3.test(iterator3)) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = oiFunc2.apply(source2, i); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, I1, C2, C3, I3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); int size = ia2.size(source2); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); int i = 0; while (testFunc1.test(iterator1) && i < size && testFunc3.test(iterator3)) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = oiFunc2.apply(source2, i); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, I2, C3, I3> void filterIterate(IndexedRead<C1, a<T1>> ia1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); int i = 0; while (i < size && testFunc2.test(iterator2) && testFunc3.test(iterator3)) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = nextFunc2.apply(iterator2); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method depends highly on the arguments. */ default <C1, I1, C2, I2, C3, I3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); while (testFunc1.test(iterator1) && testFunc2.test(iterator2) && testFunc3.test(iterator3)) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = nextFunc2.apply(iterator2); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); } } }
lunisolar/magma
magma-func/src/main/java/eu/lunisolar/magma/func/predicate/LBiObjLongPredicate.java
Java
apache-2.0
60,660
/* * Copyright 2012-2018 Christophe Friederich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.devacfr.maven.skins.reflow.context; import static java.util.Objects.requireNonNull; import java.util.List; import java.util.Map; import java.util.Optional; import javax.annotation.Nonnull; import org.apache.commons.lang.builder.ToStringBuilder; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.devacfr.maven.skins.reflow.HtmlTool; import org.devacfr.maven.skins.reflow.ISkinConfig; import org.devacfr.maven.skins.reflow.model.Component; import org.devacfr.maven.skins.reflow.model.Footer; import org.devacfr.maven.skins.reflow.model.NavSideMenu; import org.devacfr.maven.skins.reflow.model.Navbar; import org.devacfr.maven.skins.reflow.model.ScrollTop; import org.devacfr.maven.skins.reflow.model.SideNavMenuItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; /** * The base class of all contexts depending type of page. * * @author Christophe Friederich * @since 2.0 * @param <T> * type of inherrit context object. */ public abstract class Context<T extends Context<?>> extends Component { /** map containing the equivalence of font awesome characters with image found in report pages. */ private static final Map<String, String> ICON_REPLACEMENTS = ImmutableMap.<String, String> builder() .put("img[src$=images/add.gif]", "<i class=\"fas fa-plus\"></i>") .put("img[src$=images/remove.gif]", "<i class=\"fas fa-minus\"></i>") .put("img[src$=images/fix.gif]", "<i class=\"fas fa-wrench\"></i>") .put("img[src$=images/update.gif]", "<i class=\"fas fa-redo\"></i>") .put("img[src$=images/icon_help_sml.gif]", "<i class=\"fas fa-question\"></i>") .put("img[src$=images/icon_success_sml.gif]", "<i class=\"fas fa-check-circle\"></i>") .put("img[src$=images/icon_warning_sml.gif]", "<i class=\"fas fa-exclamation-triangle\"></i>") .put("img[src$=images/icon_error_sml.gif]", "<i class=\"fas fa-exclamation-circle\"></i>") .put("img[src$=images/icon_info_sml.gif]", "<i class=\"fas fa-info\"></i>") .build(); /** */ private static final Logger LOGGER = LoggerFactory.getLogger(Context.class); /** */ private ContextType type; /** */ private final Navbar navbar; /** */ private final Footer footer; /** */ private final ScrollTop scrollTop; /** * Build a context depending of current type of page. * * @param config * a config (can not be {@code null}). * @return Returns a new instance of {@link Context} depending of current page. */ @Nonnull public static Context<?> buildContext(@Nonnull final ISkinConfig config) { requireNonNull(config); ContextType type = ContextType.page; final List<SideNavMenuItem> allSideNaveMenuItems = NavSideMenu.findAllSideNavMenuItems(config); if (LOGGER.isTraceEnabled()) { LOGGER.trace("findAllSideNavMenuItems: " + allSideNaveMenuItems); } final Xpp3Dom pageProperties = config.getPageProperties(); final String fileId = config.getFileId(); if (pageProperties != null) { if (pageProperties.getAttribute("type") != null) { type = ContextType.valueOf(pageProperties.getAttribute("type")); } // frame type whether page associates to document page if (allSideNaveMenuItems.stream().filter(item -> fileId.equals(item.getSlugName())).count() > 0) { type = ContextType.frame; } } // if (type== null) { // type = ContextType.page; // } Context<?> context = null; switch (type) { case doc: context = new DocumentContext(config); break; case frame: // search the parent document page final Optional<SideNavMenuItem> menuItem = allSideNaveMenuItems.stream() .filter(item -> fileId.equals(item.getSlugName())) .findFirst(); final SideNavMenuItem item = menuItem.get(); final String documentParent = item.getParent(); context = new FrameContext(config, documentParent); break; case body: context = new BodyContext(config); break; case page: default: context = new PageContext(config); break; } return context; } /** * Default constructor. * * @param config * a config (can not be {@code null}). * @param type * the type of context (can not be {@code null}). */ public Context(@Nonnull final ISkinConfig config, @Nonnull final ContextType type) { requireNonNull(config); this.withType(requireNonNull(type)); this.navbar = new Navbar(config); this.scrollTop = new ScrollTop(config); this.footer = new Footer(config); this.initialize(config); // the ordering is important for execute preRender method this.addChildren(this.navbar, this.scrollTop, this.footer); } /** * Allows to initialize the context. * @param config * a config (can not be {@code null}). */ protected void initialize(@Nonnull final ISkinConfig config) { // enable AnchorJS if(!config.not("anchorJS")) { this.addCssOptions("anchorjs-enabled"); } } /** * Allows to execute action before rendering of component. * * @param skinConfig * a config (can <b>not</b> be {@code null}). * @return Returns the {@link String} representing the transformed body content. * @since 2.1 */ public String preRender(@Nonnull final ISkinConfig skinConfig) { return onPreRender(skinConfig, getBodyContent(skinConfig)); } @Override protected String onPreRender(final ISkinConfig skinConfig, final String bodyContent) { final HtmlTool htmlTool = getHtmlTool(skinConfig); String content = bodyContent; if (!skinConfig.not("imgLightbox")) { // lightbox is enabled by default, so check for false and negate content = htmlTool.setAttr(content, "a[href$=jpg], a[href$=JPG], a[href$=jpeg], a[href$=JPEG], " + "a[href$=png], a[href$=gif],a[href$=bmp]:has(img)", "data-lightbox", "page"); } if (!skinConfig.not("imgLightbox")) { // lightbox is enabled by default, so check for false and negate content = htmlTool.setAttr(content, "a[href$=jpg], a[href$=JPG], a[href$=jpeg], a[href$=JPEG], " + "a[href$=png], a[href$=gif], a[href$=bmp]:has(img)", "data-lightbox", "page"); } if (!skinConfig.not("html5Anchor")) { // HTML5-style anchors are enabled by default, so check for false and negate content = htmlTool.headingAnchorToId(content); } if (!skinConfig.not("bootstrapCss")) { // Bootstrap CSS class conversion is enabled by default, so check for false and negate content = htmlTool .addClass(content, "table.bodyTable", Lists.newArrayList("table", "table-striped", "table-hover")); // image is responsive by default content = htmlTool.addClass(content, "img", Lists.newArrayList("img-fluid")); content = htmlTool.fixTableHeads(content); } if (!skinConfig.not("bootstrapIcons")) { // Bootstrap Icons are enabled by default, so check for false and negate content = htmlTool.replaceAll(content, ICON_REPLACEMENTS); // The <tt> tag is not supported in HTML5 (see https://www.w3schools.com/tags/tag_tt.asp). content = htmlTool.replaceWith(content, "tt", "<code class=\"literal\">"); } return super.onPreRender(skinConfig, content); } /** * @return Returns the {@link Navbar}. */ public Navbar getNavbar() { return navbar; } /** * @return Returns the {@link ScrollTop}. */ public ScrollTop getScrollTop() { return scrollTop; } /** * @return Returns the {@link Footer}. */ public Footer getFooter() { return footer; } /** * Sets the type of context. * * @param type * the of context. * @return Returns the fluent instance context. */ protected T withType(final ContextType type) { this.type = type; return self(); } /** * @return Returns the type of context of page. */ public String getType() { return type.name(); } /** * @return Returns the fluent instance. */ @SuppressWarnings("unchecked") protected T self() { return (T) this; } /** * {@inheritDoc} */ @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
devacfr/reflow-maven-skin
reflow-velocity-tools/src/main/java/org/devacfr/maven/skins/reflow/context/Context.java
Java
apache-2.0
9,918
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.ssl; import org.apache.activemq.artemis.api.core.ActiveMQSecurityException; import org.apache.activemq.artemis.api.core.QueueConfiguration; import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.apache.activemq.artemis.core.security.Role; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.settings.HierarchicalRepository; import org.apache.activemq.artemis.spi.core.security.ActiveMQJAASSecurityManager; import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.RetryRule; import org.apache.hadoop.minikdc.MiniKdc; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.File; import java.lang.management.ManagementFactory; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class CoreClientOverOneWaySSLKerb5Test extends ActiveMQTestBase { @Rule public RetryRule retryRule = new RetryRule(2); public static final SimpleString QUEUE = new SimpleString("QueueOverKrb5SSL"); public static final String CLIENT_PRINCIPAL = "client"; public static final String SNI_HOST = "sni.host"; public static final String SERVICE_PRINCIPAL = "host/" + SNI_HOST; static { String path = System.getProperty("java.security.auth.login.config"); if (path == null) { URL resource = CoreClientOverOneWaySSLKerb5Test.class.getClassLoader().getResource("login.config"); if (resource != null) { path = resource.getFile(); System.setProperty("java.security.auth.login.config", path); } } } private MiniKdc kdc; private ActiveMQServer server; private TransportConfiguration tc; private TransportConfiguration inVMTc; private String userPrincipal; @Test public void testOneWaySSLWithGoodClientCipherSuite() throws Exception { // hard coded match, default_keytab_name in minikdc-krb5.conf template File userKeyTab = new File("target/test.krb5.keytab"); kdc.createPrincipal(userKeyTab, CLIENT_PRINCIPAL, SERVICE_PRINCIPAL); createCustomSslServer(); tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true); tc.getParams().put(TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME, getSuitableCipherSuite()); tc.getParams().put(TransportConstants.SNIHOST_PROP_NAME, SNI_HOST); // static service name rather than dynamic machine name tc.getParams().put(TransportConstants.SSL_KRB5_CONFIG_PROP_NAME, "core-tls-krb5-client"); final ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); ClientSessionFactory sf = null; try { sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); session.createQueue(new QueueConfiguration(CoreClientOverOneWaySSLKerb5Test.QUEUE).setRoutingType(RoutingType.ANYCAST)); ClientProducer producer = session.createProducer(CoreClientOverOneWaySSLKerb5Test.QUEUE); final String text = RandomUtil.randomString(); ClientMessage message = createTextMessage(session, text); producer.send(message); ClientConsumer consumer = session.createConsumer(CoreClientOverOneWaySSLKerb5Test.QUEUE); session.start(); ClientMessage m = consumer.receive(1000); Assert.assertNotNull(m); Assert.assertEquals(text, m.getReadOnlyBodyBuffer().readString()); System.err.println("m:" + m + ", user:" + m.getValidatedUserID()); Assert.assertNotNull("got validated user", m.getValidatedUserID()); Assert.assertTrue("krb id in validated user", m.getValidatedUserID().contains(CLIENT_PRINCIPAL)); } finally { if (sf != null) { sf.close(); } locator.close(); } // validate only ssl creds work, try and fake the principal w/o ssl final ServerLocator inVmLocator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(inVMTc)); ClientSessionFactory inVmSf = null; try { inVmSf = createSessionFactory(inVmLocator); inVmSf.createSession(userPrincipal, "", false, false, false, false, 10); fail("supposed to throw exception"); } catch (ActiveMQSecurityException e) { // expected } finally { if (inVmSf != null) { inVmSf.close(); } inVmLocator.close(); } } public String getSuitableCipherSuite() throws Exception { return "TLS_KRB5_WITH_3DES_EDE_CBC_SHA"; } // Package protected --------------------------------------------- @Override @Before public void setUp() throws Exception { super.setUp(); kdc = new MiniKdc(MiniKdc.createConf(), temporaryFolder.newFolder("kdc")); kdc.start(); } @Override @After public void tearDown() throws Exception { try { kdc.stop(); } finally { super.tearDown(); } } private void createCustomSslServer() throws Exception { Map<String, Object> params = new HashMap<>(); params.put(TransportConstants.SSL_ENABLED_PROP_NAME, true); params.put(TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME, getSuitableCipherSuite()); params.put(TransportConstants.SSL_KRB5_CONFIG_PROP_NAME, "core-tls-krb5-server"); ConfigurationImpl config = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params, "nettySSL")); config.setPopulateValidatedUser(true); // so we can verify the kerb5 id is present config.setSecurityEnabled(true); config.addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)); ActiveMQSecurityManager securityManager = new ActiveMQJAASSecurityManager("Krb5Plus"); server = addServer(ActiveMQServers.newActiveMQServer(config, ManagementFactory.getPlatformMBeanServer(), securityManager, false)); HierarchicalRepository<Set<Role>> securityRepository = server.getSecurityRepository(); final String roleName = "ALLOW_ALL"; Role role = new Role(roleName, true, true, true, true, true, true, true, true, true, true); Set<Role> roles = new HashSet<>(); roles.add(role); securityRepository.addMatch(QUEUE.toString(), roles); server.start(); waitForServerToStart(server); // note kerberos user does not exist on the broker save as a role member in dual-authentication-roles.properties userPrincipal = CLIENT_PRINCIPAL + "@" + kdc.getRealm(); tc = new TransportConfiguration(NETTY_CONNECTOR_FACTORY); inVMTc = new TransportConfiguration(INVM_CONNECTOR_FACTORY); } }
andytaylor/activemq-artemis
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ssl/CoreClientOverOneWaySSLKerb5Test.java
Java
apache-2.0
8,618
# 3rd Year Main Project # Design Document Check out the [Wiki](https://github.com/ianburkeixiv/ThirdYearProject/wiki) for the design document # Video Click [here](https://youtu.be/jd0N7RG_bnA) to check out the video I uploaded on Youtube showing how to run the application. # Installation and Configuration Manual Download the [Install&ConfigManual](https://github.com/ianburkeixiv/ThirdYearProject/raw/master/Install%26ConfigManual.docx) word document above to install the various technologies used in this project. # User Guide Once the installation and configuration is done. Here are the following steps on how to run the the database, server and the ionic app together. Download [MyApp2/](https://github.com/ianburkeixiv/ThirdYearProject/tree/master/myApp2) folder and [Server folder](https://github.com/ianburkeixiv/ThirdYearProject/tree/master/server) above. ### Step 1: Launch MongoDB server To launch the MongoDB server, we must locate the executable files in the MongoDB Server binary folder. Open a command terminal and enter the following: ```sh $ cd/ ``` ![](https://cloud.githubusercontent.com/assets/22341150/25337063/212c8628-28f2-11e7-962a-9c059f93e79c.PNG) Cd/ will change back to the root directory. Once in the root directory, we need to go into the Program Files directory ```sh $ cd "Program Files" ``` ![](https://cloud.githubusercontent.com/assets/22341150/25337079/332561f6-28f2-11e7-87e6-18631152e20e.PNG) *A shortcut to this is typing the first few words like "pro" and then press the tab button to bring up the full word*. Once in the Program Files directory, we must go into the MongoDB directory. ```sh $ cd MongoDB ``` ![](https://cloud.githubusercontent.com/assets/22341150/25337082/3b1766b6-28f2-11e7-9ad9-79dc5891b573.PNG) Then cd into the server directory.. ```sh $ cd server ``` Use version 3.4.. ```sh $ cd 3.4 ``` cd into the bin folder which contains all the executable files. ```sh $ cd bin ``` ![](https://cloud.githubusercontent.com/assets/22341150/25337087/40f7ad0c-28f2-11e7-9a68-6b90a57805c6.PNG) Once you are inside the bin folder, enter mongod command to launch the server. ```sh $ mongod ``` ![](https://cloud.githubusercontent.com/assets/22341150/25337073/2a85d936-28f2-11e7-928a-14e1e75f4b88.PNG) ### Step 2: Launch the Node Server In the [Server](https://github.com/ianburkeixiv/ThirdYearProject/tree/master/server) folder there are two files. The package.json file is used to specify dependencies to be installed by NPM (Node Package Manager). Server.js is the actual server file. To launch the server, open up another command terminal and locate the server directory using the cd (change directory) command. Once you are in the server directory, enter the following command to launch the server: ```sh $ node server.js ``` ![](https://cloud.githubusercontent.com/assets/22341150/25339672/597db4ee-28fb-11e7-936a-90813a85b947.PNG) Once the MongoDB server and the Node server are running, we can now launch the Ionic 2 app. ### Step 3: Launh Ionic 2 First you must locate the MyApp2 directory containing the Ionic 2 project. Open up another (No.3) command terminal and cd into MyApp2 directory. Once you are inside the directory, enter the following command to run the Ionic app: - *Note: 'ionic serve' command will run the app on your local browser* - We will be using 'ionic lab'. This feature makes it easy to run the app in a phone frame and with iOS and Android platforms side by side. ```sh $ ionic lab ``` ![](https://cloud.githubusercontent.com/assets/22341150/25341218/0d8f87a6-2900-11e7-9cc2-2de0ce364e6a.PNG) 'Once the Ionic app is running, you can test it out!' ![](https://cloud.githubusercontent.com/assets/22341150/25342669/9d58dd02-2904-11e7-9af2-092630a6def2.PNG) ![](https://cloud.githubusercontent.com/assets/22341150/25342685/a46b6b46-2904-11e7-9325-7f7d3b0559ec.PNG)
ianburkeixiv/ThirdYearProject
README.md
Markdown
apache-2.0
3,883
""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def try_generate_M(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) ########## if __name__ == "__main__": output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()
ThomasBrouwer/BNMTF
data_toy/bnmf/generate_bnmf.py
Python
apache-2.0
3,430
/* Copyright IBM Corp. 2016 All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package deliver import ( "fmt" "io" "testing" "time" mockpolicies "github.com/hyperledger/fabric/common/mocks/policies" "github.com/hyperledger/fabric/common/policies" "github.com/hyperledger/fabric/common/tools/configtxgen/provisional" "github.com/hyperledger/fabric/orderer/common/ledger" ramledger "github.com/hyperledger/fabric/orderer/common/ledger/ram" cb "github.com/hyperledger/fabric/protos/common" ab "github.com/hyperledger/fabric/protos/orderer" "github.com/hyperledger/fabric/protos/utils" logging "github.com/op/go-logging" "github.com/stretchr/testify/assert" "google.golang.org/grpc" ) var genesisBlock = cb.NewBlock(0, nil) var systemChainID = "systemChain" const ledgerSize = 10 func init() { logging.SetLevel(logging.DEBUG, "") } type mockD struct { grpc.ServerStream recvChan chan *cb.Envelope sendChan chan *ab.DeliverResponse } func newMockD() *mockD { return &mockD{ recvChan: make(chan *cb.Envelope), sendChan: make(chan *ab.DeliverResponse), } } func (m *mockD) Send(br *ab.DeliverResponse) error { m.sendChan <- br return nil } func (m *mockD) Recv() (*cb.Envelope, error) { msg, ok := <-m.recvChan if !ok { return msg, io.EOF } return msg, nil } type erroneousRecvMockD struct { grpc.ServerStream } func (m *erroneousRecvMockD) Send(br *ab.DeliverResponse) error { return nil } func (m *erroneousRecvMockD) Recv() (*cb.Envelope, error) { // The point here is to simulate an error other than EOF. // We don't bother to create a new custom error type. return nil, io.ErrUnexpectedEOF } type erroneousSendMockD struct { grpc.ServerStream recvVal *cb.Envelope } func (m *erroneousSendMockD) Send(br *ab.DeliverResponse) error { // The point here is to simulate an error other than EOF. // We don't bother to create a new custom error type. return io.ErrUnexpectedEOF } func (m *erroneousSendMockD) Recv() (*cb.Envelope, error) { return m.recvVal, nil } type mockSupportManager struct { chains map[string]*mockSupport } func (mm *mockSupportManager) GetChain(chainID string) (Support, bool) { cs, ok := mm.chains[chainID] return cs, ok } type mockSupport struct { ledger ledger.ReadWriter policyManager *mockpolicies.Manager erroredChan chan struct{} configSeq uint64 } func (mcs *mockSupport) Errored() <-chan struct{} { return mcs.erroredChan } func (mcs *mockSupport) Sequence() uint64 { return mcs.configSeq } func (mcs *mockSupport) PolicyManager() policies.Manager { return mcs.policyManager } func (mcs *mockSupport) Reader() ledger.Reader { return mcs.ledger } func NewRAMLedger() ledger.ReadWriter { rlf := ramledger.New(ledgerSize + 1) rl, _ := rlf.GetOrCreate(provisional.TestChainID) rl.Append(genesisBlock) return rl } func initializeDeliverHandler() Handler { mm := newMockMultichainManager() for i := 1; i < ledgerSize; i++ { l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } return NewHandlerImpl(mm) } func newMockMultichainManager() *mockSupportManager { rl := NewRAMLedger() mm := &mockSupportManager{ chains: make(map[string]*mockSupport), } mm.chains[systemChainID] = &mockSupport{ ledger: rl, policyManager: &mockpolicies.Manager{Policy: &mockpolicies.Policy{}}, erroredChan: make(chan struct{}), } return mm } var seekOldest = &ab.SeekPosition{Type: &ab.SeekPosition_Oldest{Oldest: &ab.SeekOldest{}}} var seekNewest = &ab.SeekPosition{Type: &ab.SeekPosition_Newest{Newest: &ab.SeekNewest{}}} func seekSpecified(number uint64) *ab.SeekPosition { return &ab.SeekPosition{Type: &ab.SeekPosition_Specified{Specified: &ab.SeekSpecified{Number: number}}} } func makeSeek(chainID string, seekInfo *ab.SeekInfo) *cb.Envelope { return &cb.Envelope{ Payload: utils.MarshalOrPanic(&cb.Payload{ Header: &cb.Header{ ChannelHeader: utils.MarshalOrPanic(&cb.ChannelHeader{ ChannelId: chainID, }), SignatureHeader: utils.MarshalOrPanic(&cb.SignatureHeader{}), }, Data: utils.MarshalOrPanic(seekInfo), }), } } func TestWholeChainSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekOldest, Stop: seekNewest, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) count := uint64(0) for { select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { if deliverReply.GetStatus() != cb.Status_SUCCESS { t.Fatalf("Received an error on the reply channel") } if count != ledgerSize { t.Fatalf("Expected %d blocks but got %d", ledgerSize, count) } return } if deliverReply.GetBlock().Header.Number != count { t.Fatalf("Expected block %d but got block %d", count, deliverReply.GetBlock().Header.Number) } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } count++ } } func TestNewestSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekNewest, Stop: seekNewest, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { t.Fatalf("Received an error on the reply channel") } if deliverReply.GetBlock().Header.Number != uint64(ledgerSize-1) { t.Fatalf("Expected only the most recent block") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestSpecificSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) specifiedStart := uint64(3) specifiedStop := uint64(7) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(specifiedStart), Stop: seekSpecified(specifiedStop), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) count := uint64(0) for { select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { if deliverReply.GetStatus() != cb.Status_SUCCESS { t.Fatalf("Received an error on the reply channel") } return } if expected := specifiedStart + count; deliverReply.GetBlock().Header.Number != expected { t.Fatalf("Expected block %d but got block %d", expected, deliverReply.GetBlock().Header.Number) } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } count++ } } func TestUnauthorizedSeek(t *testing.T) { mm := newMockMultichainManager() for i := 1; i < ledgerSize; i++ { l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } mm.chains[systemChainID].policyManager.Policy.Err = fmt.Errorf("Fail to evaluate policy") m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(0)), Stop: seekSpecified(uint64(0)), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetStatus() != cb.Status_FORBIDDEN { t.Fatalf("Received wrong error on the reply channel") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestRevokedAuthorizationSeek(t *testing.T) { mm := newMockMultichainManager() for i := 1; i < ledgerSize; i++ { l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(ledgerSize - 1)), Stop: seekSpecified(ledgerSize), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: assert.NotNil(t, deliverReply.GetBlock(), "First should succeed") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } mm.chains[systemChainID].policyManager.Policy.Err = fmt.Errorf("Fail to evaluate policy") mm.chains[systemChainID].configSeq++ l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", ledgerSize+1))}})) select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_FORBIDDEN, deliverReply.GetStatus(), "Second should been forbidden ") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestOutOfBoundSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(3 * ledgerSize)), Stop: seekSpecified(uint64(3 * ledgerSize)), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetStatus() != cb.Status_NOT_FOUND { t.Fatalf("Received wrong error on the reply channel") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestFailFastSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(ledgerSize - 1)), Stop: seekSpecified(ledgerSize), Behavior: ab.SeekInfo_FAIL_IF_NOT_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { t.Fatalf("Expected to receive first block") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } select { case deliverReply := <-m.sendChan: if deliverReply.GetStatus() != cb.Status_NOT_FOUND { t.Fatalf("Expected to receive failure for second block") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestBlockingSeek(t *testing.T) { mm := newMockMultichainManager() for i := 1; i < ledgerSize; i++ { l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(ledgerSize - 1)), Stop: seekSpecified(ledgerSize), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { t.Fatalf("Expected to receive first block") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get first block") } select { case <-m.sendChan: t.Fatalf("Should not have delivered an error or second block") case <-time.After(50 * time.Millisecond): } l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", ledgerSize+1))}})) select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { t.Fatalf("Expected to receive new block") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get new block") } select { case deliverReply := <-m.sendChan: if deliverReply.GetStatus() != cb.Status_SUCCESS { t.Fatalf("Expected delivery to complete") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestErroredSeek(t *testing.T) { mm := newMockMultichainManager() ms := mm.chains[systemChainID] l := ms.ledger close(ms.erroredChan) for i := 1; i < ledgerSize; i++ { l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(ledgerSize - 1)), Stop: seekSpecified(ledgerSize), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_SERVICE_UNAVAILABLE, deliverReply.GetStatus(), "Mock support errored") case <-time.After(time.Second): t.Fatalf("Timed out waiting for error response") } } func TestErroredBlockingSeek(t *testing.T) { mm := newMockMultichainManager() ms := mm.chains[systemChainID] l := ms.ledger for i := 1; i < ledgerSize; i++ { l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(ledgerSize - 1)), Stop: seekSpecified(ledgerSize), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: assert.NotNil(t, deliverReply.GetBlock(), "Expected first block") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get first block") } close(ms.erroredChan) select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_SERVICE_UNAVAILABLE, deliverReply.GetStatus(), "Mock support errored") case <-time.After(time.Second): t.Fatalf("Timed out waiting for error response") } } func TestSGracefulShutdown(t *testing.T) { m := newMockD() ds := NewHandlerImpl(nil) close(m.recvChan) assert.NoError(t, ds.Handle(m), "Expected no error for hangup") } func TestReversedSeqSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) specifiedStart := uint64(7) specifiedStop := uint64(3) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(specifiedStart), Stop: seekSpecified(specifiedStop), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetStatus() != cb.Status_BAD_REQUEST { t.Fatalf("Received wrong error on the reply channel") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestBadStreamRecv(t *testing.T) { bh := NewHandlerImpl(nil) assert.Error(t, bh.Handle(&erroneousRecvMockD{}), "Should catch unexpected stream error") } func TestBadStreamSend(t *testing.T) { m := &erroneousSendMockD{recvVal: makeSeek(systemChainID, &ab.SeekInfo{Start: seekNewest, Stop: seekNewest, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY})} ds := initializeDeliverHandler() assert.Error(t, ds.Handle(m), "Should catch unexpected stream error") } func TestOldestSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekOldest, Stop: seekOldest, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: assert.NotEqual(t, nil, deliverReply.GetBlock(), "Received an error on the reply channel") assert.Equal(t, uint64(0), deliverReply.GetBlock().Header.Number, "Expected only the most recent block") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestNoPayloadSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- &cb.Envelope{Payload: []byte("Foo")} select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_BAD_REQUEST, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestNilPayloadHeaderSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- &cb.Envelope{Payload: utils.MarshalOrPanic(&cb.Payload{})} select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_BAD_REQUEST, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestBadChannelHeader(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- &cb.Envelope{Payload: utils.MarshalOrPanic(&cb.Payload{ Header: &cb.Header{ChannelHeader: []byte("Foo")}, })} select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_BAD_REQUEST, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestChainNotFound(t *testing.T) { mm := &mockSupportManager{ chains: make(map[string]*mockSupport), } m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekNewest, Stop: seekNewest, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_NOT_FOUND, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestBadSeekInfoPayload(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- &cb.Envelope{ Payload: utils.MarshalOrPanic(&cb.Payload{ Header: &cb.Header{ ChannelHeader: utils.MarshalOrPanic(&cb.ChannelHeader{ ChannelId: systemChainID, }), SignatureHeader: utils.MarshalOrPanic(&cb.SignatureHeader{}), }, Data: []byte("Foo"), }), } select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_BAD_REQUEST, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestMissingSeekPosition(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- &cb.Envelope{ Payload: utils.MarshalOrPanic(&cb.Payload{ Header: &cb.Header{ ChannelHeader: utils.MarshalOrPanic(&cb.ChannelHeader{ ChannelId: systemChainID, }), SignatureHeader: utils.MarshalOrPanic(&cb.SignatureHeader{}), }, Data: nil, }), } select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_BAD_REQUEST, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } }
blockc/fabric
orderer/common/deliver/deliver_test.go
GO
apache-2.0
19,021
using Artemis.System; using IHateRectangles.Screens; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace IHateRectangles { public class MenuScreen : Screen { private SpriteBatch _spriteBatch; private SpriteFont _menuFont; private ContentManager _contentManager; public event ScreenFinished OnScreenFinished; public void Initialize() { _contentManager = EntitySystem.BlackBoard.GetEntry<ContentManager>("ContentManager"); _menuFont = _contentManager.Load<SpriteFont>(@"Fonts\Hud"); _spriteBatch = EntitySystem.BlackBoard.GetEntry<SpriteBatch>("SpriteBatch"); } public void Update() { if (Keyboard.GetState().GetPressedKeys().Length > 0) if (OnScreenFinished != null) OnScreenFinished(new GameScreen()); } public void Draw() { var viewport = EntitySystem.BlackBoard.GetEntry<GraphicsDevice>("GraphicsDevice").Viewport; _spriteBatch.Begin(); _spriteBatch.DrawString(_menuFont, "I Hate Rectangles", new Vector2(viewport.Width / 2 - 100, viewport.Height / 2 - 200), Color.White); _spriteBatch.DrawString(_menuFont, "Press any key to continue.", new Vector2(viewport.Width / 2 - 138, viewport.Height / 2 - 100), Color.White); _spriteBatch.End(); } public void Destroy() { } } }
SoulBeaver/i-hate-rectangles
IHateRectangles/IHateRectangles/Screens/MenuScreen.cs
C#
apache-2.0
1,784
############################################################################### ## ## Description: ## Test with ibv_rc_pingpong, perf and rping between 2 Guests on the same Hosts ## ## Revision: ## v1.0.0 - ldu - 12/04/2018 - Build the script ## ############################################################################### <# .Synopsis Test with ibv_rc_pingpong, perf and rping between 2 Guests on the different Hosts .Description .Parameter vmName Name of the test VM. .Parameter testParams Semicolon separated list of test parameters. #> param([String] $vmName, [String] $hvServer, [String] $testParams) # # Checking the input arguments # if (-not $vmName) { "Error: VM name cannot be null!" exit 100 } if (-not $hvServer) { "Error: hvServer cannot be null!" exit 100 } if (-not $testParams) { Throw "Error: No test parameters specified" } # # Output test parameters so they are captured in log file # "TestParams : '${testParams}'" # # Parse the test parameters # $rootDir = $null $sshKey = $null $ipv4 = $null $dstHost6_7 = $null $dstHost6_5 = $null $dstDatastore = $null $params = $testParams.Split(";") foreach ($p in $params) { $fields = $p.Split("=") switch ($fields[0].Trim()) { "sshKey" { $sshKey = $fields[1].Trim() } "rootDir" { $rootDir = $fields[1].Trim() } "ipv4" { $ipv4 = $fields[1].Trim() } "dstHost6.7" { $dstHost6_7 = $fields[1].Trim()} "dstHost6.5" { $dstHost6_5 = $fields[1].Trim()} "dstDatastore" { $dstDatastore = $fields[1].Trim() } "tool" { $tool = $fields[1].Trim() } default {} } } # # Check all parameters are valid # if (-not $rootDir) { "Warn : no rootdir was specified" } else { if ( (Test-Path -Path "${rootDir}") ) { Set-Location $rootDir } else { "Warn : rootdir '${rootDir}' does not exist" } } if ($null -eq $sshKey) { "FAIL: Test parameter sshKey was not specified" return $False } if ($null -eq $ipv4) { "FAIL: Test parameter ipv4 was not specified" return $False } if ($null -eq $dstDatastore) { "FAIL: Test parameter dstDatastore was not specified" return $False } if (-not $dstHost6_7 -or -not $dstHost6_5) { "INFO: dstHost 6.7 is $dstHost6_7" "INFO: dstHost 6.5 is $dstHost6_5" "Warn : dstHost was not specified" return $false } # # Source the tcutils.ps1 file # . .\setupscripts\tcutils.ps1 PowerCLIImport ConnectToVIServer $env:ENVVISIPADDR ` $env:ENVVISUSERNAME ` $env:ENVVISPASSWORD ` $env:ENVVISPROTOCOL ############################################################################### # # Main Body # ############################################################################### $retVal = $Failed $vmObj = Get-VMHost -Name $hvServer | Get-VM -Name $vmName if (-not $vmObj) { LogPrint "ERROR: Unable to Get-VM with $vmName" DisconnectWithVIServer return $Aborted } # Specify dst host $dstHost = FindDstHost -hvServer $hvServer -Host6_5 $dstHost6_5 -Host6_7 $dstHost6_7 if ($null -eq $dstHost) { LogPrint "ERROR: Cannot find required Host" DisconnectWithVIServer return $Aborted } LogPrint "INFO: Destination Host is $dstHost" # Get the Guest version $DISTRO = GetLinuxDistro ${ipv4} ${sshKey} LogPrint "DEBUG: DISTRO: $DISTRO" if (-not $DISTRO) { LogPrint "ERROR: Guest OS version is NULL" DisconnectWithVIServer return $Aborted } LogPrint "INFO: Guest OS version is $DISTRO" # Different Guest DISTRO if ($DISTRO -ne "RedHat7" -and $DISTRO -ne "RedHat8" -and $DISTRO -ne "RedHat6") { LogPrint "ERROR: Guest OS ($DISTRO) isn't supported, MUST UPDATE in Framework / XML / Script" DisconnectWithVIServer return $Skipped } # Start another VM $GuestBName = $vmObj.Name.Split('-') # Get another VM by change Name $GuestBName[-1] = "B" $GuestBName = $GuestBName -join "-" $GuestB = Get-VMHost -Name $hvServer | Get-VM -Name $GuestBName # Add RDMA NIC for Guest B $status = AddPVrdmaNIC $GuestBName $hvServer if ( -not $status[-1]) { LogPrint "ERROR: RDMA NIC adds failed" DisconnectWithVIServer return $Aborted } # Start GuestB Start-VM -VM $GuestB -Confirm:$false -RunAsync:$true -ErrorAction SilentlyContinue if (-not $?) { LogPrint "ERROR : Cannot start VM" DisconnectWithVIServer return $Aborted } # Wait for GuestB SSH ready if ( -not (WaitForVMSSHReady $GuestBName $hvServer $sshKey 300)) { LogPrint "ERROR : Cannot start SSH" DisconnectWithVIServer return $Aborted } LogPrint "INFO: Ready SSH" # Get another VM IP addr $ipv4Addr_B = GetIPv4 -vmName $GuestBName -hvServer $hvServer $GuestB = Get-VMHost -Name $hvServer | Get-VM -Name $GuestBName # Find out new add RDMA nic for Guest B $nics += @($(FindAllNewAddNIC $ipv4Addr_B $sshKey)) if ($null -eq $nics) { LogPrint "ERROR: Cannot find new add RDMA NIC" DisconnectWithVIServer return $Failed } else { $rdmaNIC = $nics[-1] } LogPrint "INFO: New NIC is $rdmaNIC" # Config RDMA NIC IP addr for Guest B $IPAddr_guest_B = "172.31.1." + (Get-Random -Maximum 254 -Minimum 125) if ( -not (ConfigIPforNewDevice $ipv4Addr_B $sshKey $rdmaNIC ($IPAddr_guest_B + "/24"))) { LogPrint "ERROR : Guest B Config IP Failed" DisconnectWithVIServer return $Failed } LogPrint "INFO: Guest B RDMA NIC IP add is $IPAddr_guest_B" # Find out new add RDMA nic for Guest A $nics += @($(FindAllNewAddNIC $ipv4 $sshKey)) if ($null -eq $nics) { LogPrint "ERROR: Cannot find new add rdma NIC" DisconnectWithVIServer return $Failed } else { $rdmaNIC = $nics[-1] } LogPrint "INFO: New NIC is $rdmaNIC" # Config RDMA NIC IP addr for Guest A $IPAddr_guest_A = "172.31.1." + (Get-Random -Maximum 124 -Minimum 2) if ( -not (ConfigIPforNewDevice $ipv4 $sshKey $rdmaNIC ($IPAddr_guest_A + "/24"))) { LogPrint "ERROR : Guest A Config IP Failed" DisconnectWithVIServer return $Failed } LogPrint "INFO: Guest A RDMA NIC IP add is $IPAddr_guest_A" # Check can we ping GuestA from GuestB via RDMA NIC $Command = "ping $IPAddr_guest_A -c 10 -W 15 | grep ttl > /dev/null" $status = SendCommandToVM $ipv4Addr_B $sshkey $command if (-not $status) { LogPrint "ERROR : Ping test Failed" $retVal = $Failed } else { LogPrint "Pass : Ping test passed" } #For RHEL8 and RHEL7 install different package. if ($DISTRO -eq "RedHat8") { $command1 = "yum install -y opensm rdma libibverbs librdmacm librdmacm-utils ibacm libibverbs-utils infiniband-diags perftest qperf libcxgb4 libmlx4 libmlx5 rdma-core" } else { $command1 = "yum install -y opensm rdma libibverbs librdmacm librdmacm-utils ibacm libibverbs-utils infiniband-diags ibutils perftest qperf infinipath-psm libcxgb3 libcxgb4 libehca libipathverbs libmthca libmlx4 libmlx5 libnes libocrdma dapl dapl-devel dapl-utils dapl dapl-devel dapl-utils" } #install dependency package on guest B. $status = SendCommandToVM $ipv4Addr_B $sshkey $command1 if (-not $status) { LogPrint "ERROR : install package Failed" return $Aborted } #load ib related modules $command2 = "modprobe ib_umad" $status = SendCommandToVM $ipv4Addr_B $sshkey $command2 if (-not $status) { LogPrint "ERROR : load modules Failed" return $Aborted } #install dependency package on guest A. $status = SendCommandToVM $ipv4 $sshkey $command1 if (-not $status) { LogPrint "ERROR : install package Failed" return $Aborted } #load ib related modules $status = SendCommandToVM $ipv4 $sshkey $command2 if (-not $status) { LogPrint "ERROR : load modules Failed" return $Aborted } #check the test tools used for test. LogPrint "test is $tool" write-host -F Red "Test tool is $tool" if ( $tool -eq "perf" ) { #array for perftest command $perf_guestB = @("ib_send_lat -x 0 -a","ib_send_bw -x 0 -a","ib_read_lat -x 0 -a","ib_read_bw -x 0 -a","ib_write_lat -x 0 -a","ib_write_bw -x 0 -a" ) $perf_guestA = @("ib_send_lat -x 0 -a $IPAddr_guest_B","ib_send_bw -x 0 -a $IPAddr_guest_B","ib_read_lat -x 0 -a $IPAddr_guest_B","ib_read_bw -x 0 -a $IPAddr_guest_B","ib_write_lat -x 0 -a $IPAddr_guest_B","ib_write_bw -x 0 -a $IPAddr_guest_B" ) foreach($i in $perf_guestB) { $Process = Start-Process bin\plink -ArgumentList "-i ssh\${sshKey} root@${ipv4Addr_B} ${i}" -PassThru -WindowStyle Hidden write-host -F Red "the process1 id is $($Process.id) and $i" $index = $perf_guestB.IndexOf($i) $commandA = $perf_guestA[$index] $status = SendCommandToVM $ipv4 $sshkey $commandA if (-not $status) { LogPrint "ERROR : $commandA test Failed" return $Failed } else { $retVal = $Passed LogPrint "pass : $commandA test passed" } } } else { if ( $tool -eq "ibvrc" ) { $commandA = "ibv_rc_pingpong -s 1 -g 1 $IPAddr_guest_B" $commandB = "ibv_rc_pingpong -s 1 -g 1" } else { $commandA = "rping -c -a $IPAddr_guest_B -v -C 1" $commandB = "rping -s -v -V -C 1 -a $IPAddr_guest_B" } #Run test on guest B first,because guest B is test as server. $Process1 = Start-Process bin\plink -ArgumentList "-i ssh\${sshKey} root@${ipv4Addr_B} ${commandB}" -PassThru -WindowStyle Hidden write-host -F Red "$($Process1.id)" #Then run test on guest A, guest A as client. $a = "touch /root/aa" $status = SendCommandToVM $ipv4 $sshkey $a $status = SendCommandToVM $ipv4 $sshkey $commandA if (-not $status) { LogPrint "ERROR : test $commandA test Failed" DisconnectWithVIServer $retVal = $Failed } else { $retVal = $Passed LogPrint "pass : test $commandA test passed" } } DisconnectWithVIServer return $retVal
HiRoySoft/ESX-LISA
testscripts/rdma_tools_test_same_host.ps1
PowerShell
apache-2.0
9,706
package org.easyaccess.nist; import java.io.File; import java.util.HashMap; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.speech.tts.TextToSpeech.OnInitListener; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.Toast; public class HomeScreenActivity extends Activity implements OnInitListener { private static final String TAG = "HomeScreenActivity"; boolean isButtonPressed = false; int gFocusPosition = 1; int gMaxFocusableItem = 2; Context gContext = null; String gTTsOnStart = null; SpeakManager gTTS = null; Button gBtnScan = null, gBtnSkipScan = null; View rootView = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_ballotstart); gContext = this; rootView = findViewById(R.id.alrt_root_view); gBtnScan = (Button) findViewById(R.id.btn_scan); gBtnSkipScan = (Button) findViewById(R.id.btn_skip_scan); gBtnScan.setBackgroundColor(getResources().getColor(R.color.bg_button)); gBtnScan.setTextColor(getResources().getColor(android.R.color.white)); gBtnSkipScan.setBackgroundColor(getResources().getColor(R.color.bg_button)); gBtnSkipScan.setTextColor(getResources().getColor(android.R.color.white)); gBtnScan.isInTouchMode(); File directory = new File(Constants.NIST_VOTING_PROTOTYPE_DIRECTORY); if (!directory.exists()) { directory.mkdir(); } File sampleFile = new File(directory, Constants.NIST_VOTING_PROTOTYPE_FILE_SP); if (!sampleFile.exists()) { StringBuilder builder = Utils.readFile(gContext, this.getResources().openRawResource(R.raw.election_info_sp)); Utils.writeToFile(builder.toString(), directory + File.separator + Constants.NIST_VOTING_PROTOTYPE_FILE_SP, false); } sampleFile = new File(directory, Constants.NIST_VOTING_PROTOTYPE_FILE_EN); if (!sampleFile.exists()) { StringBuilder builder = Utils.readFile(gContext, this.getResources().openRawResource(R.raw.election_info_en)); Utils.writeToFile(builder.toString(), directory + File.separator + Constants.NIST_VOTING_PROTOTYPE_FILE_EN, false); } } private OnClickListener sOnClickListener = new OnClickListener() { Intent intent = null; @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_scan: launchScan(); break; case R.id.btn_skip_scan: skipScan(); break; case R.id.alrt_root_view: speakWord("", null, false); break; } } private void skipScan() { resetPreferences(); intent = new Intent(gContext, ContestActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } private void launchScan() { resetPreferences(); intent = new Intent(gContext, ScannerActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } }; private void resetPreferences() { Constants.SETTING_LANGUAGE = Constants.DEFAULT_LANG_SETTING; Constants.SETTING_TOUCH_PRESENT = Constants.DEFAULT_TOUCH_PRESENT_SETTING; Constants.SETTING_FONT_SIZE = Constants.FONT_SIZE_STD; Constants.SETTING_REVERSE_SCREEN = Constants.DEFAULT_REVERSE_SCREEN_SETTING; Constants.SETTING_TTS_VOICE = Constants.DEFAULT_TTS_VOICE; Constants.SETTING_TTS_SPEED = Constants.TTS_SPEED_STD; Constants.SETTING_SCAN_MODE = Constants.DEFAULT_SCAN_MODE_SETTING; Constants.SETTING_SCAN_MODE_SPEED = Constants.DEFAULT_SCAN_SPEED_SETTING; SharedPreferences preferences = getSharedPreferences( Constants.PREFERENCE_NAME, Context.MODE_PRIVATE); Editor editor = preferences.edit(); editor.clear(); editor.commit(); } private OnTouchListener gOnTouchListener = new OnTouchListener() { /** * on touch down announce the info if it represent text. on touch up * perform the action */ @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition = 0; switch (v.getId()) { case R.id.btn_scan: v.setBackground(getResources().getDrawable( R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnScan.getText().toString(), null, true); } break; case R.id.btn_skip_scan: v.setBackground(getResources().getDrawable( R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnSkipScan.getText().toString(), null, true); } break; } } else if (event.getAction() == MotionEvent.ACTION_UP) { switch (v.getId()) { case R.id.btn_scan: v.setBackground(null); // v.performClick(); break; case R.id.btn_skip_scan: v.setBackground(null); // v.performClick(); break; } } return false; } }; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (!isButtonPressed) { int keyPressed = -1; if (keyCode == KeyEvent.KEYCODE_UNKNOWN) { keyPressed = event.getScanCode(); } else { keyPressed = keyCode; } switch (keyPressed) { case KeyEvent.KEYCODE_TAB: if(event.isShiftPressed()){ navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition--; if (gFocusPosition <= 0) { gFocusPosition = gMaxFocusableItem; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); }else{ navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition++; if (gFocusPosition > gMaxFocusableItem) { gFocusPosition = 1; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); } break; case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_BUTTON_1: navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition--; if (gFocusPosition <= 0) { gFocusPosition = gMaxFocusableItem; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); break; case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_BUTTON_2: navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition++; if (gFocusPosition > gMaxFocusableItem) { gFocusPosition = 1; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); break; case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_BUTTON_3: selectCurrentFocusItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); break; } } isButtonPressed = true; return true; } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { isButtonPressed = false; int keyPressed = -1; if (keyCode == KeyEvent.KEYCODE_UNKNOWN) { keyPressed = event.getScanCode(); } else { keyPressed = keyCode; } switch (keyPressed) { case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_BUTTON_3: // selectCurrentFocusItem(gFocusPosition, // Constants.JUMP_FROM_CURRENT_ITEM); break; } return true; } public void selectCurrentFocusItem(int focusPosition, int pressed_released) { switch (pressed_released) { case Constants.REACH_NEW_ITEM: break; case Constants.JUMP_FROM_CURRENT_ITEM: if (gFocusPosition == 1) { gBtnScan.performClick(); } else if (gFocusPosition == 2) { gBtnSkipScan.performClick(); } break; } } public void navigateToOtherItem(int focusPosition, int reach_jump) { View view = getCurrentFocus(); Log.d(TAG, " from navigation method focus position = " + focusPosition + ", current focus = " + view ); // + ", next focus down id = " // + view.getNextFocusDownId() // + ", next focus forward id = " + view.getNextFocusForwardId() // + ", next focus left id = " + view.getNextFocusLeftId() // + ", next focus right id = " + view.getNextFocusRightId() // + ", next focus up id = " + view.getNextFocusUpId()); switch (reach_jump) { case Constants.JUMP_FROM_CURRENT_ITEM: if (focusPosition == 1) { // gBtnScan.setBackground(null); } else if (focusPosition == 2) { // gBtnSkipScan.setBackground(null); } break; case Constants.REACH_NEW_ITEM: if (focusPosition == 1) { gBtnScan.setFocusableInTouchMode(true);// for handling the ez-keypad focus gBtnSkipScan.setFocusableInTouchMode(false);// for handling the ez-keypad focus gBtnScan.requestFocus();// for handling the focus when come out of touch mode // gBtnScan.setBackground(getResources().getDrawable( // R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnScan.getText().toString() + Constants.COMMA_SPACE + getString(R.string.button), null, true); } } else if (focusPosition == 2) { gBtnScan.setFocusableInTouchMode(false);// for handling the ez-keypad focus gBtnSkipScan.setFocusableInTouchMode(true);// for handling the ez-keypad focus gBtnSkipScan.requestFocus();// for handling the focus when come out of touch mode // gBtnSkipScan.setBackground(getResources().getDrawable( // R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnSkipScan.getText().toString() + Constants.COMMA_SPACE + getString(R.string.button), null, true); } } break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.d(TAG,"resultCode = " + resultCode); if (requestCode == Constants.TTS_DATA_CHECK_CODE) { if (resultCode == SpeakManager.Engine.CHECK_VOICE_DATA_PASS) { Log.d(TAG,"Setting speak manager"); if (Constants.SETTING_TTS_VOICE == Constants.DEFAULT_TTS_VOICE) { gTTS = new SpeakManager(gContext, this, "com.svox.classic"); } else { gTTS = new SpeakManager(gContext, this, "com.ivona.tts"); } } else { Log.d(TAG,"launching intent for installing tts"); Intent ttsInstallIntent = new Intent(); ttsInstallIntent .setAction(SpeakManager.Engine.ACTION_INSTALL_TTS_DATA); startActivity(ttsInstallIntent); } } } @Override public void onInit(int status) { if (status == SpeakManager.SUCCESS) { if (Constants.SETTING_LANGUAGE == Constants.DEFAULT_LANG_SETTING) { gTTS.setLanguage(Locale.US); } else { gTTS.setLanguage(new Locale("spa", "ESP")); } gTTS.setSpeechRate(Constants.SETTING_TTS_SPEED); speakWord(gTTsOnStart, null, true); } else if (status == SpeakManager.ERROR) { Toast.makeText(gContext, getString(R.string.failed), Toast.LENGTH_SHORT).show(); } } public void speakWord(String word, HashMap<String, String> utteranceId, boolean shouldRepeat) { if (gTTS != null) { gTTS.speak(word, SpeakManager.QUEUE_FLUSH, utteranceId, shouldRepeat); } } @Override protected void onStop() { super.onStop(); if (gTTS != null) { gTTS.stop(); gTTS.shutdown(); } } @Override protected void onStart() { super.onStart(); Intent checkTTSIntent = new Intent(); checkTTSIntent.setAction(SpeakManager.Engine.ACTION_CHECK_TTS_DATA); startActivityForResult(checkTTSIntent, Constants.TTS_DATA_CHECK_CODE); gBtnScan.setText(R.string.scan_barcode); gBtnSkipScan.setText(R.string.skip_barcode); gBtnScan.setTextSize(Constants.SETTING_FONT_SIZE); gBtnSkipScan.setTextSize(Constants.SETTING_FONT_SIZE); gBtnScan.setOnClickListener(sOnClickListener); // gBtnScan.setOnTouchListener(gOnTouchListener); gBtnSkipScan.setOnClickListener(sOnClickListener); // gBtnSkipScan.setOnTouchListener(gOnTouchListener); rootView.setOnClickListener(sOnClickListener); gBtnSkipScan.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ // gBtnSkipScan.setFocusableInTouchMode(true); }else{ // gBtnSkipScan.setFocusableInTouchMode(false); } } }); gBtnScan.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ // gBtnScan.setFocusableInTouchMode(true); }else{ // gBtnScan.setFocusableInTouchMode(false); } } }); gTTsOnStart = getString(R.string.scan_barcode) + Constants.COMMA_SPACE + getString(R.string.button); // View view = getCurrentFocus(); // Log.d(TAG, "current focus = " + view // + ", next focus down id = " // + view.getNextFocusDownId() // + ", next focus forward id = " + view.getNextFocusForwardId() // + ", next focus left id = " + view.getNextFocusLeftId() // + ", next focus right id = " + view.getNextFocusRightId() // + ", next focus up id = " + view.getNextFocusUpId()); // gBtnScan.setBackgroundResource(R.drawable.focused); gBtnScan.setFocusableInTouchMode(true);// for showing focus initially gBtnScan.requestFocus(); // view = getCurrentFocus(); // Log.d(TAG, "current focus = " + view // + ", next focus down id = " // + view.getNextFocusDownId() // + ", next focus forward id = " + view.getNextFocusForwardId() // + ", next focus left id = " + view.getNextFocusLeftId() // + ", next focus right id = " + view.getNextFocusRightId() // + ", next focus up id = " + view.getNextFocusUpId()); } }
saurabh2590/NIST-Voting-Tablet
src/org/easyaccess/nist/HomeScreenActivity.java
Java
apache-2.0
13,985
// // ÀÌ ÆÄÀÏÀº JAXB(JavaTM Architecture for XML Binding) ÂüÁ¶ ±¸Çö 2.2.8-b130911.1802 ¹öÀüÀ» ÅëÇØ »ý¼ºµÇ¾ú½À´Ï´Ù. // <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>¸¦ ÂüÁ¶ÇϽʽÿÀ. // ÀÌ ÆÄÀÏÀ» ¼öÁ¤ÇÏ¸é ¼Ò½º ½ºÅ°¸¶¸¦ ÀçÄÄÆÄÀÏÇÒ ¶§ ¼öÁ¤ »çÇ×ÀÌ ¼Õ½ÇµË´Ï´Ù. // »ý¼º ³¯Â¥: 2015.07.30 ½Ã°£ 02:38:18 PM KST // package org.gs1.source.tsd; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>TSD_AttributeValuePairListType complex type¿¡ ´ëÇÑ Java Ŭ·¡½ºÀÔ´Ï´Ù. * * <p>´ÙÀ½ ½ºÅ°¸¶ ´ÜÆíÀÌ ÀÌ Å¬·¡½º¿¡ Æ÷ÇԵǴ ÇÊ¿äÇÑ ÄÜÅÙÃ÷¸¦ ÁöÁ¤ÇÕ´Ï´Ù. * * <pre> * &lt;complexType name="TSD_AttributeValuePairListType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="stringAVP" type="{urn:gs1:tsd:tsd_common:xsd:1}TSD_StringAttributeValuePairType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TSD_AttributeValuePairListType", namespace = "urn:gs1:tsd:tsd_common:xsd:1", propOrder = { "stringAVP" }) public class TSDAttributeValuePairListType { @XmlElement(required = true) protected List<TSDStringAttributeValuePairType> stringAVP; /** * Gets the value of the stringAVP property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the stringAVP property. * * <p> * For example, to add a new item, do as follows: * <pre> * getStringAVP().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TSDStringAttributeValuePairType } * * */ public List<TSDStringAttributeValuePairType> getStringAVP() { if (stringAVP == null) { stringAVP = new ArrayList<TSDStringAttributeValuePairType>(); } return this.stringAVP; } }
gs1oliot/gs1source
DataAggregator/src/main/java/org/gs1/source/tsd/TSDAttributeValuePairListType.java
Java
apache-2.0
2,392
dwtest ====== dwtest
declanwilson/dwtest
README.md
Markdown
apache-2.0
22
<!-- This comment will put IE 6, 7 and 8 in quirks mode --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>GraphBuilder 2.0 (alpha): Class Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javaScript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body onload='searchBox.OnSelectItem(0);'> <!-- Generated by Doxygen 1.6.1 --> <script type="text/javascript"><!-- var searchBox = new SearchBox("searchBox", "search",false,'Search'); --></script> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <img id="MSearchSelect" src="search/search.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </div> </li> </ul> </div> <div class="tabs"> <ul> <li><a href="annotated.html"><span>Class&nbsp;List</span></a></li> <li><a href="classes.html"><span>Class&nbsp;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&nbsp;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&nbsp;Members</span></a></li> </ul> </div> <div class="tabs"> <ul> <li class="current"><a href="functions.html"><span>All</span></a></li> <li><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> <li><a href="functions_enum.html"><span>Enumerations</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="functions.html#index_["><span>[</span></a></li> <li><a href="functions_0x5f.html#index__"><span>_</span></a></li> <li><a href="functions_0x61.html#index_a"><span>a</span></a></li> <li><a href="functions_0x62.html#index_b"><span>b</span></a></li> <li><a href="functions_0x63.html#index_c"><span>c</span></a></li> <li><a href="functions_0x64.html#index_d"><span>d</span></a></li> <li><a href="functions_0x65.html#index_e"><span>e</span></a></li> <li><a href="functions_0x66.html#index_f"><span>f</span></a></li> <li><a href="functions_0x67.html#index_g"><span>g</span></a></li> <li><a href="functions_0x68.html#index_h"><span>h</span></a></li> <li><a href="functions_0x69.html#index_i"><span>i</span></a></li> <li><a href="functions_0x6b.html#index_k"><span>k</span></a></li> <li><a href="functions_0x6c.html#index_l"><span>l</span></a></li> <li><a href="functions_0x6d.html#index_m"><span>m</span></a></li> <li><a href="functions_0x6e.html#index_n"><span>n</span></a></li> <li><a href="functions_0x6f.html#index_o"><span>o</span></a></li> <li><a href="functions_0x70.html#index_p"><span>p</span></a></li> <li><a href="functions_0x72.html#index_r"><span>r</span></a></li> <li><a href="functions_0x73.html#index_s"><span>s</span></a></li> <li><a href="functions_0x74.html#index_t"><span>t</span></a></li> <li class="current"><a href="functions_0x75.html#index_u"><span>u</span></a></li> <li><a href="functions_0x76.html#index_v"><span>v</span></a></li> <li><a href="functions_0x77.html#index_w"><span>w</span></a></li> <li><a href="functions_0x78.html#index_x"><span>x</span></a></li> <li><a href="functions_0x7a.html#index_z"><span>z</span></a></li> </ul> </div> </div> <div class="contents"> Here is a list of all class members with links to the classes they belong to: <h3><a class="anchor" id="index_u">- u -</a></h3><ul> <li>UNIQUE : <a class="el" href="classcom_1_1intel_1_1hadoop_1_1graphbuilder_1_1pipeline_1_1output_1_1titan_1_1TitanCommandLineOptions.html#a2b3b842380c2d672ce0af1107cb8ae68">com::intel::hadoop::graphbuilder::pipeline::output::titan::TitanCommandLineOptions</a> </li> <li>updateConfigurationForMapper() : <a class="el" href="interfacecom_1_1intel_1_1hadoop_1_1graphbuilder_1_1pipeline_1_1input_1_1InputConfiguration.html#a3c55b3652544452cf23a87e7c59d7c3c">com::intel::hadoop::graphbuilder::pipeline::input::InputConfiguration</a> </li> <li>updateJobForMapper() : <a class="el" href="interfacecom_1_1intel_1_1hadoop_1_1graphbuilder_1_1pipeline_1_1input_1_1InputConfiguration.html#aef237afe76e81124a0d0c83d46777a0d">com::intel::hadoop::graphbuilder::pipeline::input::InputConfiguration</a> </li> <li>usesHBase() : <a class="el" href="interfacecom_1_1intel_1_1hadoop_1_1graphbuilder_1_1pipeline_1_1input_1_1InputConfiguration.html#a9763d6094f09f379fa063297634f88b7">com::intel::hadoop::graphbuilder::pipeline::input::InputConfiguration</a> </li> </ul> </div> <!--- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&nbsp;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&nbsp;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&nbsp;</span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&nbsp;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&nbsp;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&nbsp;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&nbsp;</span>Enumerations</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <hr size="1"/><address style="text-align: right;"><small>Generated on 26 Dec 2013 for GraphBuilder 2.0 (alpha) by&nbsp; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.6.1 </small></address> </body> </html>
Cray/graphbuilder
docs/html/functions_0x75.html
HTML
apache-2.0
7,337
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.co.yahoo.dataplatform.mds.hadoop.hive.io.vector; import java.io.IOException; import org.apache.hadoop.hive.ql.exec.vector.DoubleColumnVector; import jp.co.yahoo.dataplatform.schema.objects.PrimitiveObject; public interface IDecimalPrimitiveSetter{ void set( final PrimitiveObject[] primitiveObjectArray , final DoubleColumnVector columnVector , final int index ) throws IOException; }
yahoojapan/multiple-dimension-spread
src/hive/src/main/java/jp/co/yahoo/dataplatform/mds/hadoop/hive/io/vector/IDecimalPrimitiveSetter.java
Java
apache-2.0
1,217
using System; namespace Benchy.Framework { /// <summary> /// Represents a breakdown of TimeSpan values. /// </summary> public interface IDataBreakout { /// <summary> /// The minimum value of the breakout. /// </summary> TimeSpan RangeMinValue { get; set; } /// <summary> /// The maximum value of the breakout. /// </summary> TimeSpan RangeMaxValue { get; set; } /// <summary> /// The number of items that fit between that breakout. /// </summary> int Occurences { get; set; } /// <summary> /// Represents a way to render it textually. /// </summary> /// <returns>A string representing the Breakout.</returns> string GetText(); } }
cmbrown1598/Benchy
Benchy/IDataBreakout.cs
C#
apache-2.0
818
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileTypes.impl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.ExtensionFileNameMatcher; import com.intellij.openapi.fileTypes.FileNameMatcher; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.util.InvalidDataException; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; final class RemovedMappingTracker { private static final Logger LOG = Logger.getInstance(RemovedMappingTracker.class); static final class RemovedMapping { private final FileNameMatcher myFileNameMatcher; private final String myFileTypeName; private final boolean myApproved; private RemovedMapping(@NotNull FileNameMatcher matcher, @NotNull String fileTypeName, boolean approved) { myFileNameMatcher = matcher; myFileTypeName = fileTypeName; myApproved = approved; } @NotNull FileNameMatcher getFileNameMatcher() { return myFileNameMatcher; } @NotNull String getFileTypeName() { return myFileTypeName; } boolean isApproved() { return myApproved; } @Override public String toString() { return "Removed mapping '" + myFileNameMatcher + "' -> " + myFileTypeName; } // must not look at myApproved @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RemovedMapping mapping = (RemovedMapping)o; if (!myFileNameMatcher.equals(mapping.myFileNameMatcher)) return false; return myFileTypeName.equals(mapping.myFileTypeName); } @Override public int hashCode() { int result = myFileNameMatcher.hashCode(); result = 31 * result + myFileTypeName.hashCode(); return result; } } private final MultiMap<FileNameMatcher, RemovedMapping> myRemovedMappings = new MultiMap<>(); @NonNls private static final String ELEMENT_REMOVED_MAPPING = "removed_mapping"; /** Applied for removed mappings approved by user */ @NonNls private static final String ATTRIBUTE_APPROVED = "approved"; @NonNls private static final String ATTRIBUTE_TYPE = "type"; void clear() { myRemovedMappings.clear(); } @NotNull RemovedMapping add(@NotNull FileNameMatcher matcher, @NotNull String fileTypeName, boolean approved) { RemovedMapping mapping = new RemovedMapping(matcher, fileTypeName, approved); List<RemovedMapping> mappings = (List<RemovedMapping>)myRemovedMappings.getModifiable(matcher); boolean found = false; for (int i = 0; i < mappings.size(); i++) { RemovedMapping removedMapping = mappings.get(i); if (removedMapping.getFileTypeName().equals(fileTypeName)) { mappings.set(i, mapping); found = true; break; } } if (!found) { mappings.add(mapping); } return mapping; } void load(@NotNull Element e) { myRemovedMappings.clear(); List<RemovedMapping> removedMappings = readRemovedMappings(e); Set<RemovedMapping> uniques = new LinkedHashSet<>(removedMappings.size()); for (RemovedMapping mapping : removedMappings) { if (!uniques.add(mapping)) { LOG.warn(new InvalidDataException("Duplicate <removed_mapping> tag for " + mapping)); } } for (RemovedMapping mapping : uniques) { myRemovedMappings.putValue(mapping.myFileNameMatcher, mapping); } } @NotNull static List<RemovedMapping> readRemovedMappings(@NotNull Element e) { List<Element> children = e.getChildren(ELEMENT_REMOVED_MAPPING); if (children.isEmpty()) { return Collections.emptyList(); } List<RemovedMapping> result = new ArrayList<>(); for (Element mapping : children) { String ext = mapping.getAttributeValue(AbstractFileType.ATTRIBUTE_EXT); FileNameMatcher matcher = ext == null ? FileTypeManager.parseFromString(mapping.getAttributeValue(AbstractFileType.ATTRIBUTE_PATTERN)) : new ExtensionFileNameMatcher(ext); boolean approved = Boolean.parseBoolean(mapping.getAttributeValue(ATTRIBUTE_APPROVED)); String fileTypeName = mapping.getAttributeValue(ATTRIBUTE_TYPE); if (fileTypeName == null) continue; RemovedMapping removedMapping = new RemovedMapping(matcher, fileTypeName, approved); result.add(removedMapping); } return result; } void save(@NotNull Element element) { List<RemovedMapping> removedMappings = new ArrayList<>(myRemovedMappings.values()); removedMappings.sort(Comparator.comparing((RemovedMapping mapping) -> mapping.getFileNameMatcher().getPresentableString()).thenComparing(RemovedMapping::getFileTypeName)); for (RemovedMapping mapping : removedMappings) { Element content = writeRemovedMapping(mapping.myFileTypeName, mapping.myFileNameMatcher, true, mapping.myApproved); if (content != null) { element.addContent(content); } } } void saveRemovedMappingsForFileType(@NotNull Element map, @NotNull String fileTypeName, @NotNull Collection<? extends FileNameMatcher> associations, boolean specifyTypeName) { for (FileNameMatcher matcher : associations) { Element content = writeRemovedMapping(fileTypeName, matcher, specifyTypeName, isApproved(matcher, fileTypeName)); if (content != null) { map.addContent(content); } } } boolean hasRemovedMapping(@NotNull FileNameMatcher matcher) { return myRemovedMappings.containsKey(matcher); } private boolean isApproved(@NotNull FileNameMatcher matcher, @NotNull String fileTypeName) { RemovedMapping mapping = ContainerUtil.find(myRemovedMappings.get(matcher), m -> m.getFileTypeName().equals(fileTypeName)); return mapping != null && mapping.isApproved(); } @NotNull List<RemovedMapping> getRemovedMappings() { return new ArrayList<>(myRemovedMappings.values()); } @NotNull List<FileNameMatcher> getMappingsForFileType(@NotNull String fileTypeName) { return myRemovedMappings.values().stream() .filter(mapping -> mapping.myFileTypeName.equals(fileTypeName)) .map(mapping -> mapping.myFileNameMatcher) .collect(Collectors.toList()); } @NotNull List<RemovedMapping> removeIf(@NotNull Predicate<? super RemovedMapping> predicate) { List<RemovedMapping> result = new ArrayList<>(); for (Iterator<Map.Entry<FileNameMatcher, Collection<RemovedMapping>>> iterator = myRemovedMappings.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<FileNameMatcher, Collection<RemovedMapping>> entry = iterator.next(); Collection<RemovedMapping> mappings = entry.getValue(); mappings.removeIf(mapping -> { boolean toRemove = predicate.test(mapping); if (toRemove) { result.add(mapping); } return toRemove; }); if (mappings.isEmpty()) { iterator.remove(); } } return result; } void approveUnapprovedMappings() { for (RemovedMapping mapping : new ArrayList<>(myRemovedMappings.values())) { if (!mapping.isApproved()) { myRemovedMappings.remove(mapping.getFileNameMatcher(), mapping); myRemovedMappings.putValue(mapping.getFileNameMatcher(), new RemovedMapping(mapping.getFileNameMatcher(), mapping.getFileTypeName(), true)); } } } private static Element writeRemovedMapping(@NotNull String fileTypeName, @NotNull FileNameMatcher matcher, boolean specifyTypeName, boolean approved) { Element mapping = new Element(ELEMENT_REMOVED_MAPPING); if (!AbstractFileType.writePattern(matcher, mapping)) { return null; } if (approved) { mapping.setAttribute(ATTRIBUTE_APPROVED, "true"); } if (specifyTypeName) { mapping.setAttribute(ATTRIBUTE_TYPE, fileTypeName); } return mapping; } }
mdaniel/intellij-community
platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/RemovedMappingTracker.java
Java
apache-2.0
8,518
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_11) on Fri Apr 30 11:06:46 CST 2010 --> <TITLE> com.siemens.cmiv.avt.mvt.io </TITLE> <META NAME="date" CONTENT="2010-04-30"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="com.siemens.cmiv.avt.mvt.io"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../com/siemens/cmiv/avt/mvt/datatype/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../com/siemens/cmiv/avt/mvt/outlier/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?com/siemens/cmiv/avt/mvt/io/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <H2> Package com.siemens.cmiv.avt.mvt.io </H2> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Interface Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../com/siemens/cmiv/avt/mvt/io/SubjectList.html" title="interface in com.siemens.cmiv.avt.mvt.io">SubjectList</A></B></TD> <TD>&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../com/siemens/cmiv/avt/mvt/io/SubjectListFactory.html" title="class in com.siemens.cmiv.avt.mvt.io">SubjectListFactory</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../com/siemens/cmiv/avt/mvt/io/SubjectListXml.html" title="class in com.siemens.cmiv.avt.mvt.io">SubjectListXml</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../com/siemens/cmiv/avt/mvt/io/XMLComputationList.html" title="class in com.siemens.cmiv.avt.mvt.io">XMLComputationList</A></B></TD> <TD>Parses XML document.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../com/siemens/cmiv/avt/mvt/io/XMLMeasurement.html" title="class in com.siemens.cmiv.avt.mvt.io">XMLMeasurement</A></B></TD> <TD>Parses XML document.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../com/siemens/cmiv/avt/mvt/io/XMLSubjectList.html" title="class in com.siemens.cmiv.avt.mvt.io">XMLSubjectList</A></B></TD> <TD>Parses XML document.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../com/siemens/cmiv/avt/mvt/io/XMLSubjectListImpl.html" title="class in com.siemens.cmiv.avt.mvt.io">XMLSubjectListImpl</A></B></TD> <TD>Parses XML document.</TD> </TR> </TABLE> &nbsp; <P> <DL> </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../com/siemens/cmiv/avt/mvt/datatype/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../com/siemens/cmiv/avt/mvt/outlier/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?com/siemens/cmiv/avt/mvt/io/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
OpenXIP/avt-mvt
doc/com/siemens/cmiv/avt/mvt/io/package-summary.html
HTML
apache-2.0
8,141
{% extends "soc/models/edit.html" %} {% comment %} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. {% endcomment %} {% load forms_helpers %} {% block scripts %} {{ block.super }} {% if gmaps_api_key %} <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key={{ gmaps_api_key }}" type="text/javascript"></script> <script type="text/javascript" src="/soc/content/js/map-090420.js"></script> {% endif %} {% endblock %} {% block body_tag %} {% if gmaps_api_key %} <body onLoad="role_profile_gmap.map_load()" onunload="GUnload()"> {% else %} {{ block.super }} {% endif %} {% endblock %} {% block instructions %} {{ block.super }} {% if not gmaps_api_key %} <br /><span class="error">Google Maps API key not present. Please insert your key in <a href="/site/edit">Site Settings</a>, Google Maps field. </span> {% endif %} {% endblock %} {% block form_table %} {{ block.super }} {% if gmaps_api_key %} <tr title="your location"> <td class="formfieldlabel"> <label for="id_location">Location:</label> </td> <td> <div id="role_profile_map"></div> </td> <td></td> <td></td> <td></td> </tr> {% endif %} {% endblock %}
jamslevy/gsoc
app/soc/templates/soc/role/edit.html
HTML
apache-2.0
1,685
# Phoma capreae (DC.) Höhn., 1917 SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name Sphaeria capreae DC., 1815 ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Sordariomycetes/Diaporthales/Linospora/Linospora saligna/ Syn. Phoma capreae/README.md
Markdown
apache-2.0
211
# -*- coding: utf-8 -*- # Copyright 2014, 2015 Metaswitch Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ felix.test.stub_utils ~~~~~~~~~~~~ Test utilities. """ import logging import random from collections import namedtuple CommandOutput = namedtuple('CommandOutput', ['stdout', 'stderr']) # Logger log = logging.getLogger(__name__) # The current time. test_time = 0 def set_time(value): global test_time test_time = value log.debug("Time now set to : %d" % test_time) def get_time(): return test_time def get_mac(): """ Gets a random mac address. """ mac = ("%02x:%02x:%02x:%02x:%02x:%02x" % (random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff))) return mac # Exception raised when tests reach the end. class TestOverException(Exception): pass
nbartos/calico
calico/felix/test/stub_utils.py
Python
apache-2.0
1,545
/******************************************************************************* * Copyright [2016] [Quirino Brizi ([email protected])] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.actio.modeler.domain.repository; import java.util.List; import org.actio.commons.message.model.ModelMessage; /** * @author quirino.brizi * */ public interface ModelRepository { ModelMessage add(ModelMessage model); List<ModelMessage> getAllModels(); ModelMessage getModel(String modelKey); }
quirinobrizi/actio
webservices/modeler/src/main/java/org/actio/modeler/domain/repository/ModelRepository.java
Java
apache-2.0
1,108
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.scheduler.declarative.allocator; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.jobmaster.SlotInfo; import org.apache.flink.runtime.taskmanager.LocalTaskManagerLocation; import org.apache.flink.runtime.taskmanager.TaskManagerLocation; /** Test {@link SlotInfo} implementation. */ class TestSlotInfo implements SlotInfo { private final AllocationID allocationId = new AllocationID(); @Override public AllocationID getAllocationId() { return allocationId; } @Override public TaskManagerLocation getTaskManagerLocation() { return new LocalTaskManagerLocation(); } @Override public int getPhysicalSlotNumber() { return 0; } @Override public ResourceProfile getResourceProfile() { return ResourceProfile.ANY; } @Override public boolean willBeOccupiedIndefinitely() { return false; } }
kl0u/flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/declarative/allocator/TestSlotInfo.java
Java
apache-2.0
1,853
<?php include("inc_header.php"); ?> <?php include("inc_lang_detect.php"); ?> <!-- Inner Page 4404 Error --> <div class="container"> <div class="inner-error"> <h3><strong>HTTP 404<strong></h3> <?php if (getDefaultLanguage() == "pt-br") { ?> <h3 >Objeto n&atilde;o encontrado!</h3> <p>A URL requisitada n&atilde;o foi encontrada neste servidor.</p> <p>Se o endere&ccedil;o (URL) foi digitado manualmente, pedimos a gentileza de verificar novamente a sintaxe do endere&ccedil;o.</p> <?php } else { ?> <h3 >Object not found!</h3> <p>The requested URL was not found on this server.</p> <p>If you entered the URL manually please check your spelling and try again.</p> <?php } ?> </div> </div> </div> <!-- Inner Page Content End --> <?php include("inc_footer.php"); ?>
soujava/cafe-brasil
404_HTTP_NOT_FOUND.php
PHP
apache-2.0
890
# Sarcodia platycarpa Harvey ex Grunow SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Rhodophyta/Florideophyceae/Halymeniales/Halymeniaceae/Halymenia/Halymenia platycarpa/ Syn. Sarcodia platycarpa/README.md
Markdown
apache-2.0
193
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package beans; import java.io.Serializable; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * * @author Chema */ @Component public class Persona implements Serializable { @Value("#{p.nombre}") private String nombre; @Value("#{p.apellido}") private String apellido; public Persona() { } public Persona(String nombre, String apellido) { this.nombre = nombre; this.apellido = apellido; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } }
xroca/planFormacionJava
spring/Web/AnotacionesWebMaven/src/main/java/beans/Persona.java
Java
apache-2.0
909
# Carex tristis M.Bieb. SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Fl. taur. -caucas. 3:615. 1819 #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Carex/Carex tristis/README.md
Markdown
apache-2.0
205
import { Component } from '@angular/core'; import {ROUTER_DIRECTIVES, RouteData} from '@angular/router-deprecated'; import {TravelFormComponent} from "./travel-form.component"; import {NavbarComponent} from '../../shared/index'; @Component({ selector: "home", templateUrl: 'app/home/components/home.component.html', styleUrls: ['app/home/components/home.component.css'], directives: [ROUTER_DIRECTIVES, TravelFormComponent, NavbarComponent] }) export class HomeComponent{ signInOnly: boolean; constructor(private _data: RouteData) { //when arriving directly from /login URL this.signInOnly = this._data.get('signInOnly') || true; // set default to false to re-activate the destination form } }
WALK-fr/kuzzle-walk
app/home/components/home.component.ts
TypeScript
apache-2.0
741
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package delsh.livy; /** * The enumeration types for session kind. */ public enum SessionKind { // Possible values are the following. SPARK("spark"), PYSPARK("pyspark"), SPARKR("sparkr"); private String kind; private SessionKind(String skind) { kind = skind; } public String toString() { return kind; } /** * This class finds enum value that is equivalent to a given string. * @param kind Session kind. * @return Enum value */ public static SessionKind getEnum(String str) { SessionKind[] array = SessionKind.values(); for(SessionKind enumStr : array) { if(str.equals(enumStr.kind.toString())) { return enumStr; } } return null; } }
kojish/hdinsight-spark-livy-client
src/main/java/delsh/livy/SessionKind.java
Java
apache-2.0
1,484
package com.openthinks.libs.utilities.lookup; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import com.openthinks.libs.utilities.Checker; import com.openthinks.libs.utilities.InstanceUtilities; import com.openthinks.libs.utilities.InstanceUtilities.InstanceWrapper; import com.openthinks.libs.utilities.exception.CheckerNoPassException; import com.openthinks.libs.utilities.pools.object.ObjectPool; /** * ClassName: LookupPool <br> * Function: It is used for store shared object instances and find other SPI<br> * Reason: follow the design pattern of fly weight to reduce instantiate new object. <br> * Notice: avoid store or find those object which include its own state and will be changed;<br> * Usage:<br> * * <pre> * <code> * //get gloabl instance of LookupPool * LookupPool lookupPool = LookupPools.gloabl(); * * //get a named instance of LookupPool * lookupPool = LookupPools.get("pool-1"); * * // instance by class directly * LookupInterfaceImpl instanceImpl1 = lookupPool.lookup(LookupInterfaceImpl.class); * * // instance by customized implementation class * LookupInterface instanceImpl2 = lookupPool.lookup(LookupInterface.class,InstanceWrapper.build(LookupInterfaceImpl.class)); * * // lookup shared object already existed * LookupInterface instanceImpl3 = lookupPool.lookup(LookupInterface.class); * assert instanceImpl2==instanceImpl3 ; * * // register a shared object by name * lookupPool.register("beanName1",instanceImpl1); * // lookup shared object by name * LookupInterface instanceImpl4 = lookupPool.lookup("beanName1"); * * assert instanceImpl1==instanceImpl4 ; * * // clear all shared objects and mappings * lookupPool.cleanUp(); * * </code> * </pre> * * date: Sep 8, 2017 3:15:29 PM <br> * * @author [email protected] * @version 1.0 * @since JDK 1.8 */ public abstract class LookupPool { protected final ObjectPool objectPool; protected final ReadWriteLock lock; public abstract String name(); protected LookupPool() { objectPool = new ObjectPool(); lock = new ReentrantReadWriteLock(); } /** * lookup a object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param type Class lookup key type * @param args Object[] instance constructor parameters * @return T lookup object or null */ public <T> T lookup(Class<T> type, Object... args) { return lookup(type, null, args); } /** * lookup a object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param <E> lookup object type * @param searchType Class lookup key type * @param instancewrapper Class instance type when not lookup the key * @param args Object[] instance constructor parameters * @return T lookup object or null */ public <T, E extends T> T lookup(final Class<T> searchType, InstanceWrapper<E> instancewrapper, Object... args) { T object = null; lock.readLock().lock(); try { object = objectPool.get(searchType); } finally { lock.readLock().unlock(); } if (object == null) { lock.writeLock().lock(); try { object = InstanceUtilities.create(searchType, instancewrapper, args); register(searchType, object); } finally { lock.writeLock().unlock(); } } return object; } /** * look up object by its bean name * * @param <T> lookup object type * @param beanName String lookup object mapping name * @return T lookup object or null */ public <T> T lookup(String beanName) { lock.readLock().lock(); try { return objectPool.get(beanName); } finally { lock.readLock().unlock(); } } /** * lookup a optional object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param type Class lookup key type * @param args Object[] instance constructor parameters * @return Optional of lookup object */ public <T> Optional<T> lookupIf(Class<T> type, Object... args) { return Optional.ofNullable(lookup(type, args)); } /** * lookup a optional object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param <E> lookup object type * @param searchType Class lookup key type * @param instancewrapper Class instance type when not lookup the key * @param args Object[] instance constructor parameters * @return Optional of lookup object */ public <T, E extends T> Optional<T> lookupIf(final Class<T> searchType, InstanceWrapper<E> instancewrapper, Object... args) { return Optional.ofNullable(lookup(searchType, instancewrapper, args)); } /** * look up optional object by its bean name * * @param <T> lookup object type * @param beanName String lookup object mapping name * @return Optional of lookup object */ public <T> Optional<T> lookupIf(String beanName) { return Optional.ofNullable(lookup(beanName)); } /** * * lookupSPI:this will used {@link ServiceLoader} to load SPI which defined in folder * <B>META-INF/services</B>. <br> * It will first to try to load instance from cached {@link ObjectPool}, if not found, then try to * load SPI class and instantiate it.<br> * Notice: only load and instantiate first SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param args constructor arguments * @return implementation of parameter spiInterface */ public <T> T lookupSPI(Class<T> spiInterface, Object... args) { return lookupFocusSPI(spiInterface, null, args); } /** * * lookupFocusSPI:this will used {@link ServiceLoader} to load SPI which defined in folder * <B>META-INF/services</B>. <br> * It will first to try to load instance from cached {@link ObjectPool}, if not found, then try to * load SPI class and instantiate it.<br> * Notice: only load and instantiate focused SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param focusClassName focused SPI implementation class aname * @param args constructor arguments * @return implementation of parameter spiInterface * */ public <T> T lookupFocusSPI(Class<T> spiInterface, String focusClassName, Object... args) { T object = null; lock.readLock().lock(); try { object = objectPool.get(spiInterface); } finally { lock.readLock().unlock(); } if (object == null) { lock.writeLock().lock(); try { ServiceLoader<T> serviceLoader = ServiceLoader.load(spiInterface, focusClassName, args); object = serviceLoader.iterator().next(); Checker.require(object).notNull("Cannot found SPI implementation for " + spiInterface); register(spiInterface, object); } finally { lock.writeLock().unlock(); } } return object; } /** * * lookupSPISkipCache:this will used {@link ServiceLoader} to load SPI which defined in folder * <B>META-INF/services</B>. <br> * It will do load SPI skip cache each time, not try to lookup from cache firstly.<br> * Notice: only load and instantiate first SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param args constructor arguments * @return implementation of parameter spiInterface * @throws CheckerNoPassException when not found implementation SPI */ public <T> T lookupSPISkipCache(Class<T> spiInterface, Object... args) { return lookupFocusSPISkipCache(spiInterface, null, args); } /** * * lookupFocusSPISkipCache:this will used {@link ServiceLoader} to load SPI which defined in * folder <B>META-INF/services</B>. <br> * It will do load SPI skip cache each time, not try to lookup from cache firstly.<br> * Notice: only load and instantiate focused SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param focusClassName focused SPI implementation class name * @param args constructor arguments * @return implementation of parameter spiInterface * * @throws CheckerNoPassException when not found implementation SPI */ public <T> T lookupFocusSPISkipCache(Class<T> spiInterface, String focusClassName, Object... args) { T object = null; ServiceLoader<T> serviceLoader = ServiceLoader.load(spiInterface, focusClassName, args); object = serviceLoader.iterator().next(); Checker.require(object).notNull("Cannot found SPI implementation for " + spiInterface); return object; } /** * * lookupAllSPI:fina all instance of SPI implementation. <br> * Notice:<BR> * <ul> * <li>all implementation need default constructor.</li> * <li>do not search from cache</li> * </ul> * * @param <T> SPI type * @param spiInterface SPI interface or abstract class type * @return list of all SPI implementation instance */ public <T> List<T> lookupAllSPI(Class<T> spiInterface) { List<T> list = new ArrayList<>(); ServiceLoader<T> serviceLoader = ServiceLoader.load(spiInterface); Iterator<T> iterator = serviceLoader.iterator(); while (iterator.hasNext()) { try { list.add(iterator.next()); } catch (Exception e) { // ignore } } return list; } /** * * register an instance, which key is object.getClass(). <br> * * @param <T> registered object class type * @param object instance which need registered */ public <T> void register(T object) { if (object != null) { lock.writeLock().tryLock(); try { objectPool.put(object.getClass(), object); } finally { lock.writeLock().unlock(); } } } /** * register an instance, which key is given parameter classType * * @param <T> registered object class type * @param classType Class as the key for registered instance * @param object instance which need registered */ public <T> void register(Class<T> classType, T object) { if (object != null) { lock.writeLock().tryLock(); try { objectPool.put(classType, object); } finally { lock.writeLock().unlock(); } } } /** * register object and mapping it to given bean name * * @param <T> register object type * @param beanName String bean name * @param object register object */ public <T> void register(String beanName, T object) { if (object != null) { lock.writeLock().lock(); try { objectPool.put(beanName, object); } finally { lock.writeLock().unlock(); } } } protected void cleanUp() { lock.writeLock().lock(); try { objectPool.cleanUp(); } finally { lock.writeLock().unlock(); } } }
daileyet/openlibs.utilities
src/main/java/com/openthinks/libs/utilities/lookup/LookupPool.java
Java
apache-2.0
11,805
package com.arges.sepan.argmusicplayer.Callbacks; import com.arges.sepan.argmusicplayer.Models.ArgAudio; //Interfaces public interface OnPreparedListener { void onPrepared(ArgAudio audio, int duration); }
mergehez/ArgPlayer
argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Callbacks/OnPreparedListener.java
Java
apache-2.0
211
package io.monocycle.agent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @EnableAutoConfiguration @ComponentScan @EnableAsync @EnableScheduling public class AgentApplication { private static final Logger LOGGER = LoggerFactory.getLogger(AgentApplication.class); public static void main(String[] args) { LOGGER.debug("Starting Monocycle Agent..."); SpringApplication.run(AgentApplication.class, args); } }
monocycle/monocycle-agent
src/main/java/io/monocycle/agent/AgentApplication.java
Java
apache-2.0
847
#device-check, #landing-device-check { background: #000000; } /****** landing start ******/ .landing-logo-container { width: 100%; height: 140px; margin: 0 auto 10px auto; padding-top: 15px; background: rgba(0, 0, 0, 0.5); } .landing-logo { width: 130px; height: 125px; } .landing-social-container { position: absolute; display: inline-block; width: 100%; margin: 0 auto; padding: 0 0 20px 0; bottom: 0; left: 0; text-align: center; } .landing-social-container input { height: 40px; font-size: 0.6em; font-weight: 300; padding-left: 10px; padding-right: 30px; width: 250px; text-align: center; border: none; background: rgba(0, 0, 0, 0.5); } .landing-social-container > img { display: inline-block; height: 34px; width: 30px; padding: 3px 5px; margin-left: -45px; vertical-align: bottom; cursor: pointer; background: rgba(0, 0, 0, 0.5); opacity: 0.5; } .landing-social-container > img:hover { opacity: 1; } .landing-social-container > a > img.social-icon { width: 50px; height: 50px; margin: 15px 5px 0 5px; opacity: 0.3; } .landing-social-container > a > img.social-icon:hover { opacity: 1; } /****** landing end ******/ .container { width: 100%; } .container > .logo-container > input { width: 60%; height: 50px; margin-top: 8px; } .container > .logo-container .withLeftMargin { margin-left: 5%; } nav, nav > ul, nav > ul > li { height: 50px; } nav > ul > li { padding-top: 30px; } nav > ul > li > img { width: 25px; height: 25px; } nav > ul > li.special > img { width: 32px; height: 23px; margin-top: 2px; } .container > section.page-container { height: 350px; padding-top: 30px; } .container > button { height: 70px; } .container > button > img { width: 40px; height: 30px; margin-top: 5px; } /* info page */ div#page4 #address-icon { margin-top: 25px; } div#page4 hr { margin-bottom: 10px; } div#page4 input { width: 60%; font-size: 0.8em; }
milosmns/Timecrypt
WebClient/assets/css/mobile.css
CSS
apache-2.0
1,931
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file mkldnn_batch_norm.cc * \brief * \author Tao Lv */ #ifndef MXNET_OPERATOR_NN_MKLDNN_MKLDNN_BATCH_NORM_INL_H_ #define MXNET_OPERATOR_NN_MKLDNN_MKLDNN_BATCH_NORM_INL_H_ #if MXNET_USE_MKLDNN == 1 #include <vector> #include <utility> #include <mkldnn.hpp> #include "../batch_norm-inl.h" #include "./mkldnn_ops-inl.h" #include "./mkldnn_base-inl.h" #define VARIANCE_TO_INVSTD(__var$, __eps$) (1.0/sqrt((__var$) + DType(__eps$))) #define INVSTD_TO_VARIANCE(__invstd$, __eps$) ((1.0 / ((__invstd$) * (__invstd$))) - (__eps$)) namespace mxnet { namespace op { typedef mkldnn::batch_normalization_forward::primitive_desc t_bn_f_pdesc; typedef mkldnn::batch_normalization_forward::desc t_bn_f_desc; typedef mkldnn::batch_normalization_backward::primitive_desc t_bn_b_pdesc; typedef mkldnn::batch_normalization_backward::desc t_bn_b_desc; using mkldnn::use_global_stats; using mkldnn::use_scale_shift; using mkldnn::forward_training; using mkldnn::forward_inference; inline static unsigned _GetFlags(const std::vector<NDArray> &in_data, const std::vector<NDArray> &aux_states, const BatchNormParam &param, bool is_train) { unsigned flags = 0U; if (in_data.size() == 3U) { flags |= use_scale_shift; } // aux_states[0]: inMean // aux_states[1]: inVariance if (aux_states.size() == 2U && !is_train) { flags |= use_global_stats; } return flags; } template <typename DType> inline static t_bn_f_pdesc _GetFwd(const mkldnn::memory &data_mem, bool is_train, DType eps, unsigned flags) { auto data_mpd = data_mem.get_primitive_desc(); auto data_md = data_mpd.desc(); auto engine = CpuEngine::Get()->get_engine(); if (is_train) { t_bn_f_desc bnFwd_desc(forward_training, data_md, eps, flags); return t_bn_f_pdesc(bnFwd_desc, engine); } else { t_bn_f_desc bnFwd_desc(forward_inference, data_md, eps, flags); return t_bn_f_pdesc(bnFwd_desc, engine); } } template <typename DType> inline static t_bn_b_pdesc _GetBwd(const mkldnn::memory &data_mem, const mkldnn::memory &diff_mem, DType eps, unsigned flags) { auto data_mpd = data_mem.get_primitive_desc(); auto data_md = data_mpd.desc(); auto diff_mpd = diff_mem.get_primitive_desc(); auto diff_md = diff_mpd.desc(); auto engine = CpuEngine::Get()->get_engine(); t_bn_b_desc bnBwd_desc(mkldnn::prop_kind::backward, diff_md, data_md, eps, flags); return t_bn_b_pdesc(bnBwd_desc, engine, _GetFwd(data_mem, true, eps, flags)); } typedef ParamOpSign<BatchNormParam> MKLDNNBNSignature; class MKLDNNBNForward { std::shared_ptr<const mkldnn::memory> data_m; std::shared_ptr<const mkldnn::memory> weight_m; std::shared_ptr<const mkldnn::memory> out_m; std::shared_ptr<const mkldnn::memory> mean_m; std::shared_ptr<const mkldnn::memory> var_m; std::shared_ptr<mkldnn::batch_normalization_forward> fwd; bool is_train; t_bn_f_pdesc pd; public: MKLDNNBNForward(const t_bn_f_pdesc &_pd, bool is_train): pd(_pd) { weight_m.reset(new mkldnn::memory(pd.weights_primitive_desc())); this->is_train = is_train; } const mkldnn::memory &GetWeight() const { return *weight_m; } const t_bn_f_pdesc &GetPd() const { return pd; } const mkldnn::memory &GetMean() const { return *mean_m; } const mkldnn::memory &GetVar() const { return *var_m; } void SetDataHandle(const NDArray &data, const NDArray &mean, const NDArray &var, const mkldnn::memory &out) { auto _data = data.GetMKLDNNData(); if (data_m) { data_m->set_data_handle(_data->get_data_handle()); } else { data_m.reset(new mkldnn::memory(_data->get_primitive_desc(), _data->get_data_handle())); } if (out_m) { out_m->set_data_handle(out.get_data_handle()); } else { out_m.reset(new mkldnn::memory(out.get_primitive_desc(), out.get_data_handle())); } auto mean_ptr = mean.data().dptr_; if (mean_m) { mean_m->set_data_handle(mean_ptr); } else { mean_m.reset(new mkldnn::memory(pd.mean_primitive_desc(), mean_ptr)); } auto var_ptr = var.data().dptr_; if (var_m) { var_m->set_data_handle(var_ptr); } else { var_m.reset(new mkldnn::memory(pd.variance_primitive_desc(), var_ptr)); } if (fwd == nullptr) { if (!is_train) fwd.reset(new mkldnn::batch_normalization_forward( pd, *data_m, mkldnn::primitive::at(*mean_m), mkldnn::primitive::at(*var_m), *weight_m, *out_m)); else fwd.reset(new mkldnn::batch_normalization_forward( pd, mkldnn::primitive::at(*data_m), mkldnn::primitive::at(*weight_m), *out_m, *mean_m, *var_m)); } } const mkldnn::batch_normalization_forward &GetFwd() const { return *fwd; } }; template<typename DType> static MKLDNNBNForward &GetBNForward(const BatchNormParam& param, const OpContext &ctx, const NDArray &in_data, unsigned flags) { static thread_local std::unordered_map<MKLDNNBNSignature, MKLDNNBNForward, OpHash> fwds; MKLDNNBNSignature key(param); key.AddSign(ctx.is_train); key.AddSign(in_data); auto it = fwds.find(key); if (it == fwds.end()) { auto fwd_pd = _GetFwd(*in_data.GetMKLDNNData(), ctx.is_train, (DType) param.eps, flags); MKLDNNBNForward fwd(fwd_pd, ctx.is_train); auto ins_ret = fwds.insert(std::pair<MKLDNNBNSignature, MKLDNNBNForward>( key, fwd)); CHECK(ins_ret.second); it = ins_ret.first; } return it->second; } template <typename DType> void MKLDNNBatchNormForward(const OpContext &ctx, const BatchNormParam &param, const std::vector<NDArray> &in_data, const std::vector<OpReqType> &req, const std::vector<NDArray> &out_data, const std::vector<NDArray> &aux_states) { TmpMemMgr::Get()->Init(ctx.requested[batchnorm::kTempSpace]); unsigned flags = _GetFlags(in_data, aux_states, param, ctx.is_train); const NDArray &data = in_data[batchnorm::kData]; auto &fwd = GetBNForward<DType>(param, ctx, data, flags); const NDArray &out = out_data[batchnorm::kOut]; // for output memory auto out_mem = const_cast<NDArray &>(out).CreateMKLDNNData(fwd.GetPd().dst_primitive_desc()); // mxnet will always use scale shift. // But if fix_gamma is true, then all scale elements will be set to 1.0f if (flags & use_scale_shift) { const NDArray &gamma = in_data[batchnorm::kGamma]; const NDArray &beta = in_data[batchnorm::kBeta]; CHECK_EQ(gamma.storage_type(), mxnet::kDefaultStorage); CHECK_EQ(beta.storage_type(), mxnet::kDefaultStorage); const mkldnn::memory &weight_mem = fwd.GetWeight(); DType* weight_buf = reinterpret_cast<DType *>(weight_mem.get_data_handle()); nnvm::dim_t channels_ = data.shape()[1]; CHECK(weight_mem.get_primitive_desc().get_size() == channels_ * sizeof(DType) * 2); DType* weight_ptr = gamma.data().dptr<DType>(); DType* bias_ptr = beta.data().dptr<DType>(); if (!param.fix_gamma) { #pragma omp parallel for for (int i = 0; i < channels_; i++) { weight_buf[i] = weight_ptr[i]; weight_buf[channels_ + i] = bias_ptr[i]; // bias } } else if (IsBNWriting(req[batchnorm::kGamma])) { #pragma omp parallel for for (int i = 0; i < channels_; i++) { weight_buf[i] = (DType)1.0f; weight_ptr[i] = (DType)1.0f; weight_buf[channels_ + i] = bias_ptr[i]; // bias } } else { #pragma omp parallel for for (int i = 0; i < channels_; i++) { weight_buf[i] = (DType)1.0f; weight_buf[channels_ + i] = bias_ptr[i]; // bias } } if (!ctx.is_train) { DType* omean = out_data[batchnorm::kMean].data().dptr<DType>(); DType* ovar = out_data[batchnorm::kVar].data().dptr<DType>(); DType* inmean = aux_states[batchnorm::kMovingMean].data().dptr<DType>(); DType* invar = aux_states[batchnorm::kMovingVar].data().dptr<DType>(); // to align with origin implmentation: batch_norm.cc: L164 #pragma omp parallel for for (int i = 0; i < channels_; i++) { omean[i] = inmean[i]; ovar[i] = VARIANCE_TO_INVSTD(invar[i], param.eps); } fwd.SetDataHandle(data, aux_states[batchnorm::kMovingMean], aux_states[batchnorm::kMovingVar], *out_mem); MKLDNNStream::Get()->RegisterPrim(fwd.GetFwd()); MKLDNNStream::Get()->Submit(); } else { // training const NDArray &outMean = out_data[batchnorm::kMean]; const NDArray &outVar = out_data[batchnorm::kVar]; DType* omean = outMean.data().dptr<DType>(); DType* ovar = outVar.data().dptr<DType>(); fwd.SetDataHandle(data, outMean, outVar, *out_mem); MKLDNNStream::Get()->RegisterPrim(fwd.GetFwd()); MKLDNNStream::Get()->Submit(); DType* mean_mem_ptr = reinterpret_cast<DType*>(fwd.GetMean().get_data_handle()); DType* var_mem_ptr = reinterpret_cast<DType*>(fwd.GetVar().get_data_handle()); #pragma omp parallel for for (int i = 0; i < channels_; i++) { omean[i] = mean_mem_ptr[i]; ovar[i] = VARIANCE_TO_INVSTD(var_mem_ptr[i], param.eps); } } } else { // no input gamma and beta LOG(FATAL) << "MKLDNN batch normalization: should not reach here ..."; } } template <typename DType> void MKLDNNBatchNormBackward(const OpContext &ctx, const BatchNormParam &param, const std::vector<NDArray> &out_grad, const std::vector<NDArray> &in_data, const std::vector<NDArray> &out_data, const std::vector<OpReqType> &req, const std::vector<NDArray> &in_grad, const std::vector<NDArray> &aux_states) { TmpMemMgr::Get()->Init(ctx.requested[batchnorm::kTempSpace]); CHECK_EQ(out_grad.size(), 1U); CHECK_EQ(in_data.size(), 3U); CHECK_EQ(out_data.size(), 3U); CHECK_EQ(in_grad.size(), 3U); unsigned flags = _GetFlags(in_data, aux_states, param, ctx.is_train); const NDArray &data = in_data[batchnorm::kData]; const NDArray &diff = out_grad[batchnorm::kOut]; const NDArray &gradIn = in_grad[batchnorm::kData]; const NDArray &moving_mean = aux_states[batchnorm::kMovingMean]; const NDArray &moving_var = aux_states[batchnorm::kMovingVar]; const NDArray &out_mean = out_data[batchnorm::kMean]; const NDArray &out_var = out_data[batchnorm::kVar]; CHECK(out_mean.IsDefaultData()); CHECK(out_var.IsDefaultData()); CHECK(moving_mean.IsDefaultData()); CHECK(moving_var.IsDefaultData()); auto data_mem = data.GetMKLDNNData(); auto diff_mem = diff.GetMKLDNNData(); // MKLDNN batchnorm should run on special layouts. If one of them isn't, we // should reorder them. if (data.IsDefaultData()) data_mem = data.GetMKLDNNDataReorder(diff_mem->get_primitive_desc()); else if (diff.IsDefaultData()) diff_mem = diff.GetMKLDNNDataReorder(data_mem->get_primitive_desc()); auto bwd_pd = _GetBwd(*data_mem, *diff_mem, param.eps, flags); auto gradi_mem = const_cast<NDArray &>(gradIn).CreateMKLDNNData(data_mem->get_primitive_desc()); if (flags & use_scale_shift) { const NDArray &gamma = in_data[batchnorm::kGamma]; const NDArray &beta = in_data[batchnorm::kBeta]; // TODO(tao): how to reuse this memory? std::shared_ptr<const mkldnn::memory> weight_mem( new mkldnn::memory(bwd_pd.weights_primitive_desc())); DType* weight_buf = reinterpret_cast<DType *>(weight_mem->get_data_handle()); nnvm::dim_t channels_ = data.shape()[1]; for (int i = 0; i < channels_; i++) { if (!param.fix_gamma) weight_buf[i] = (gamma.data().dptr<DType>())[i]; // weight else weight_buf[i] = (DType)1.0f; } for (int i = 0; i < channels_; i++) { weight_buf[channels_ + i] = (beta.data().dptr<DType>())[i]; // bias } std::shared_ptr<const mkldnn::memory> gradw_mem( new mkldnn::memory(bwd_pd.diff_weights_primitive_desc())); // training but no input mean and variance if (ctx.is_train && !param.use_global_stats) { DType* moving_mean_ptr = reinterpret_cast<DType *>(moving_mean.data().dptr<DType>()); DType* moving_var_ptr = reinterpret_cast<DType *>(moving_var.data().dptr<DType>()); DType* out_mean_ptr = reinterpret_cast<DType *>(out_mean.data().dptr<DType>()); DType* out_var_ptr = reinterpret_cast<DType *>(out_var.data().dptr<DType>()); mkldnn::memory var_mem(bwd_pd.variance_primitive_desc()); DType *tmp_var_ptr = reinterpret_cast<DType *>(var_mem.get_data_handle()); DType minus_mom = (1.0f - param.momentum); for (int i = 0; i < channels_; i++) { moving_mean_ptr[i] = moving_mean_ptr[i] * param.momentum + out_mean_ptr[i] * minus_mom; float variance = INVSTD_TO_VARIANCE(out_var_ptr[i], param.eps); tmp_var_ptr[i] = variance; moving_var_ptr[i] = moving_var_ptr[i] * param.momentum + variance * minus_mom; } std::shared_ptr<const mkldnn::memory> out_mean_mem( new mkldnn::memory(bwd_pd.mean_primitive_desc(), out_mean_ptr)); std::shared_ptr<const mkldnn::memory> out_var_mem( new mkldnn::memory(bwd_pd.variance_primitive_desc(), out_var_ptr)); auto bn_bwd = mkldnn::batch_normalization_backward(bwd_pd, *data_mem, mkldnn::primitive::at(*out_mean_mem), mkldnn::primitive::at(var_mem), *diff_mem, *weight_mem, *gradi_mem, *gradw_mem); MKLDNNStream::Get()->RegisterPrim(bn_bwd); MKLDNNStream::Get()->Submit(); } else { std::shared_ptr<const mkldnn::memory> imean_mem( new mkldnn::memory(bwd_pd.mean_primitive_desc(), moving_mean.data().dptr<DType>())); std::shared_ptr<const mkldnn::memory> ivar_mem( new mkldnn::memory(bwd_pd.variance_primitive_desc(), moving_var.data().dptr<DType>())); auto bn_bwd = mkldnn::batch_normalization_backward(bwd_pd, *data_mem, mkldnn::primitive::at(*imean_mem), mkldnn::primitive::at(*ivar_mem), *diff_mem, *weight_mem, *gradi_mem, *gradw_mem); MKLDNNStream::Get()->RegisterPrim(bn_bwd); MKLDNNStream::Get()->Submit(); } // copy data from gradw_mem to in_grad[1] and in_grad[2] DType* gw_buf = reinterpret_cast<DType *>(gradw_mem->get_data_handle()); for (int i = 0; i < channels_; i++) { if (!param.fix_gamma) (in_grad[1].data().dptr<DType>())[i] = gw_buf[i]; else (in_grad[1].data().dptr<DType>())[i] = 0.0f; } for (int i = 0; i < channels_; i++) { (in_grad[2].data().dptr<DType>())[i] = gw_buf[i + channels_]; } } else { LOG(FATAL) << "MKLDNN batch normalization backward: should not reach here ..."; } } } // namespace op } // namespace mxnet #endif // MXNET_USE_MKLDNN #endif // MXNET_OPERATOR_NN_MKLDNN_MKLDNN_BATCH_NORM_INL_H_
CodingCat/mxnet
src/operator/nn/mkldnn/mkldnn_batch_norm-inl.h
C
apache-2.0
17,404
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.239 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.App.My.MySettings Get Return Global.App.My.MySettings.Default End Get End Property End Module End Namespace
WillSams/aspnet_mvc3_springnhibernate
src/web/My Project/Settings.Designer.vb
Visual Basic
apache-2.0
2,894
/* * Copyright 2014 Waratek Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.waratek.spiracle.sql.servlet.oracle; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.waratek.spiracle.sql.servlet.util.ParameterNullFix; import com.waratek.spiracle.sql.util.SelectUtil; /** * Servlet implementation class Get_string_no_quote */ @WebServlet({"/Get_string_no_quote", "/MsSql_Get_string_no_quote", "/MySql_Get_string_no_quote"}) public class Get_string_no_quote extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Get_string_no_quote() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { executeRequest(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { executeRequest(request, response); } private void executeRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { ServletContext application = this.getServletConfig().getServletContext(); List<String> queryStringList = new ArrayList<String>(); queryStringList.add("name"); Map<String, String> nullSanitizedMap = ParameterNullFix.sanitizeNull(queryStringList, request); String name = nullSanitizedMap.get("name"); String sql = "SELECT * FROM users WHERE name = " + name; Boolean showErrors = true; Boolean allResults = true; Boolean showOutput = true; SelectUtil.executeQuery(sql, application, request, response, showErrors, allResults, showOutput); } }
waratek/spiracle
src/main/java/com/waratek/spiracle/sql/servlet/oracle/Get_string_no_quote.java
Java
apache-2.0
2,885
module.exports = function(fancyRequire) { fancyRequire('merchant_row'); };
loop-recur/moo-phone
Resources/views/views.js
JavaScript
apache-2.0
77
package fr.xebia.unittestwithdagger; import android.widget.TextView; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import fr.xebia.unittestwithdagger.internal.CustomRobolectricTestRunner; import static junit.framework.Assert.assertEquals; import static org.mockito.BDDMockito.given; /** * Created by florentchampigny on 12/11/2015. */ @RunWith(CustomRobolectricTestRunner.class) @Config(application = MyTestApplication.class, constants = BuildConfig.class, sdk=21) public class UserActivityTest { UserActivity activity; UserStorage userStorage; @Before public void setUp() throws Exception { activity = Robolectric.buildActivity(UserActivity.class).create().get(); userStorage = MyApplication.get().component().userStorage(); } @Test public void displayLoggedUserShoulDisplayFlorent(){ given(userStorage.loadUser()).willReturn(new User("florent")); TextView textView = (TextView)activity.findViewById(R.id.text); activity.displayLoggedUser(); assertEquals("florent", textView.getText().toString()); } }
florent37/UnitTestWithDagger
app/src/test/java/fr/xebia/unittestwithdagger/UserActivityTest.java
Java
apache-2.0
1,254
great_rsd(p1,ee1). great_rsd(g1,dd1). great_rsd(e1,x1). great_rsd(e1,f1). great_rsd(t1,m1). great_rsd(u1,t1). great_rsd(w1,dd1). great_rsd(p1,m1). great_rsd(p1,h1). great_rsd(ee1,g1). great_rsd(ee1,dd1). great_rsd(f1,hh1). great_rsd(w1,m1). great_rsd(u1,q1). great_rsd(q1,ee1). great_rsd(cc1,dd1). great_rsd(f1,g1). great_rsd(q1,c1). great_rsd(aa1,x1). great_rsd(dd1,x1). great_rsd(cc1,u1). great_rsd(p1,cc1). great_rsd(ee1,x1). great_rsd(v1,x1). great_rsd(p1,ff1). great_rsd(k1,l1). great_rsd(a1,t1). great_rsd(f1,a1). great_rsd(a1,h1). great_rsd(p1,x1). great_rsd(cc1,kk1). great_rsd(f1,kk1). great_rsd(e1,dd1). great_rsd(jj1,dd1). great_rsd(p1,kk1). great_rsd(t1,h1). great_rsd(v1,hh1). great_rsd(c1,x1). great_rsd(c1,jj1). great_rsd(v1,g1). great_rsd(p1,w1). great_rsd(u1,g1). great_rsd(u1,ee1). great_rsd(e1,p1). great_rsd(f1,ee1). great_rsd(v1,aa1). great_rsd(k1,dd1). great_rsd(cc1,z1). great_rsd(q1,ff1). great_rsd(e1,k1). great_rsd(z1,jj1). great_rsd(p1,dd1). great_rsd(e1,c1). great_rsd(e1,q1). great_rsd(l1,jj1). great_rsd(aa1,ii1). great_rsd(f1,ii1). great_rsd(p1,v1). great_rsd(k1,kk1). great_rsd(ee1,ii1). great_rsd(cc1,ff1). great_rsd(c1,z1). great_rsd(q1,h1). great_rsd(cc1,ee1). great_rsd(v1,dd1). great_rsd(f1,jj1). great_rsd(u1,hh1). great_rsd(q1,ii1). great_rsd(cc1,l1). great_rsd(u1,l1). great_rsd(h1,x1). great_rsd(cc1,c1). great_rsd(w1,ff1). great_rsd(u1,ii1). great_rsd(e1,l1). great_rsd(ee1,hh1). great_rsd(aa1,z1). great_rsd(a1,x1). great_rsd(hh1,jj1). great_rsd(cc1,ii1). great_rsd(t1,z1). great_rsd(w1,kk1). great_rsd(aa1,h1). great_rsd(v1,ff1). great_rsd(ee1,m1). great_rsd(f1,t1). great_rsd(t1,ii1).
manoelfranca/cilppp
foldsCreator/files/datasets/alzheimer_scopolamine_noiseless/incremental3/train9.f
FORTRAN
apache-2.0
1,630
import { PluginMeta } from '@savantly/sprout-api'; export const validatePluginJson = (pluginJson: any) => { if (!pluginJson.id) { throw new Error('Plugin id is missing in plugin.json'); } if (!pluginJson.info) { throw new Error('Plugin info node is missing in plugin.json'); } if (!pluginJson.info.version) { throw new Error('Plugin info.version is missing in plugin.json'); } const types = ['panel', 'datasource', 'app']; const type = pluginJson.type; if (!types.includes(type)) { throw new Error('Invalid plugin type in plugin.json: ' + type); } if (!pluginJson.id.endsWith('-' + type)) { throw new Error('[plugin.json] id should end with: -' + type); } }; export const getPluginJson = (path: string): PluginMeta => { let pluginJson; try { pluginJson = require(path); } catch (e) { throw new Error('Unable to find: ' + path); } validatePluginJson(pluginJson); return pluginJson as PluginMeta; };
savantly-net/sprout-platform
frontend/tools/sprout-toolkit/src/config/utils/pluginValidation.ts
TypeScript
apache-2.0
970