text
stringlengths
2
1.04M
meta
dict
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.duplicateArgMessage = duplicateArgMessage; exports.UniqueArgumentNames = UniqueArgumentNames; var _error = require('../../error'); function duplicateArgMessage(argName) { return 'There can be only one argument named "' + argName + '".'; } /** * Unique argument names * * A GraphQL field or directive is only valid if all supplied arguments are * uniquely named. */ function UniqueArgumentNames(context) { var knownArgNames = Object.create(null); return { Field: function Field() { knownArgNames = Object.create(null); }, Directive: function Directive() { knownArgNames = Object.create(null); }, Argument: function Argument(node) { var argName = node.name.value; if (knownArgNames[argName]) { context.reportError(new _error.GraphQLError(duplicateArgMessage(argName), [knownArgNames[argName], node.name])); } else { knownArgNames[argName] = node.name; } return false; } }; }
{ "content_hash": "dc6b3ddc340ae0dd8712f9da0946c287", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 120, "avg_line_length": 25.238095238095237, "alnum_prop": 0.6735849056603773, "repo_name": "Khan/khan-linter", "id": "e1d268716726cee5dde887f500524662ebf67f74", "size": "1256", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/graphql/validation/rules/UniqueArgumentNames.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "473" }, { "name": "JavaScript", "bytes": "9867" }, { "name": "Makefile", "bytes": "1397" }, { "name": "Python", "bytes": "409986" }, { "name": "Shell", "bytes": "5543" } ], "symlink_target": "" }
module ByzantionChess class FenHelper LETTER = {"ByzantionChess::King" => "k", "ByzantionChess::Queen" => "q","ByzantionChess::Rook" => "r", "ByzantionChess::Bishop" => "b","ByzantionChess::Knight" => "n","ByzantionChess::Pawn" => "p"} def initialize(board) @board = board end def readFEN(fen) board, color_to_move, castles, en_passant, halfmove_clock, move_number = fen.strip.split(" ") board.split("/").each_with_index do |line, index| column = 0 line.each_char do |char| column +=1 field = Field.new(column, 8-index) case char when '1','2','3','4','5','6','7','8' column += char.to_i-1 when 'k' piece = King.new(field, BLACK, @board) when 'q' piece = Queen.new(field, BLACK, @board) when 'r' piece = Rook.new(field, BLACK, @board) when 'b' piece = Bishop.new(field, BLACK, @board) when 'n' piece = Knight.new(field, BLACK, @board) when 'p' piece = Pawn.new(field, BLACK, @board) when 'K' piece = King.new(field, WHITE, @board) when 'Q' piece = Queen.new(field, WHITE, @board) when 'R' piece = Rook.new(field, WHITE, @board) when 'B' piece = Bishop.new(field, WHITE, @board) when 'N' piece = Knight.new(field, WHITE, @board) when 'P' piece = Pawn.new(field, WHITE, @board) end @board.add_piece(piece) end end end def writeFEN result = '' 8.downto(1) do |i| pieces = sort_pieces_by_verical_line(pieces_from_line(@board.pieces, i)) one_line = create_fen_line(prepare_format(pieces)) result << one_line result << '/' unless i == 1 end result.concat(additional_info) result end private def prepare_format(pieces) pieces.map{|p| {:klass => p.class, :color => p.color, :line => p.vertical_line}} end def pieces_from_line(pieces, line) pieces.select{|piece| piece.field.horizontal_line == line} end def sort_pieces_by_verical_line(pieces) pieces.sort{|p1,p2| p1.field.vertical_line <=> p2.field.vertical_line} end def piece_to_literal(klass,color) letter = LETTER[klass] ByzantionChess::WHITE == color ? letter.upcase : letter end def create_fen_line(pieces) result = '' border = 1 pieces.each do |piece| border_offset = piece[:line] - border result.concat(border_offset.to_s) if border_offset > 0 result.concat(piece_to_literal(piece[:klass].to_s, piece[:color])) border = piece[:line] + 1 end result.concat((9-border).to_s) if 9-border > 0 result end def additional_info result = ' ' color = @board.to_move == WHITE ? 'w' : 'b' result.concat(color).concat(castle_info) if @board.en_passant result.concat(@board.en_passant.field.to_s) else result.concat('-') end result.concat(" #{@board.moves_upto_draw} #{@board.move_number}") result end def castle_info result = ' ' wc = @board.white_castle_possible bc = @board.black_castle_possible result.concat('K') if wc[:short] result.concat('Q') if wc[:long] result.concat('k') if bc[:short] result.concat('q') if bc[:long] result.concat('-') if !wc[:long] && !wc[:short] && !bc[:long] && !bc[:short] result.concat(' ') result end end end
{ "content_hash": "5ac937ac1471f44ea979b421e47c91dc", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 106, "avg_line_length": 30.418032786885245, "alnum_prop": 0.5375909458367018, "repo_name": "PadawanBreslau/byzantion_chess", "id": "e171177abf723e92eedce7794213a500d376613b", "size": "3711", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/byzantion_chess/fen_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "39731" }, { "name": "Ruby", "bytes": "78374" } ], "symlink_target": "" }
([ 我爱中文 ](./README_CN.md)) A light toggle view for Android in Kotlin, with only 1 file, it acts like ios toggle style in default settings, also you can design it using all the given attributes. The toggle view acts differently while touching different ranges around the button, it performs good experience for user. ## ScreenShots ![easytoggle](https://github.com/huzenan/EasyToggle/blob/master/screeshots/easytoggle.gif) ## Usage Add to your root build.gradle: ```xml allprojects { repositories { ... maven { url 'https://jitpack.io' } } } ``` Add the dependency: ```xml dependencies { compile 'com.github.huzenan:EasyToggle:v1.0.0' } ``` >layout The layout is very simple, if you want exactly a ios style toggle, nothing need to be set in your layout file. ```xml <com.hzn.lib.EasyToggle android:id="@+id/et" android:layout_width="wrap_content" android:layout_height="wrap_content" /> ``` >Activity Using lambda, setting the listener is also very easy. ```kotlin et.setOnToggledListener { tv.text = if (it) "on" else "off" } ``` ## Attributes | name | description | | ------------------- | ------------- | | etLength | button extensional length(without raidus) | | etRadius | radius of the button | | etRange | range that changes the acting of the toggle view | | etBgOffColor | background color when off | | etBgOnColor | background color when on | | etBgStrokeWidth | background stroke width | | etBgTopColor | color above the backgroud | | etButtonColor | color of the button | | etButtonStrokeColor | color of stroke of the button | | etButtonStrokeWidth | stroke width of the button | | etShadowOffsetY | offsetY of shadow, greater than 0 |
{ "content_hash": "56a0d277c8714c805d4ea7e6e46dd59b", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 288, "avg_line_length": 31.448275862068964, "alnum_prop": 0.6546052631578947, "repo_name": "huzenan/EasyToggle", "id": "12cf0d3eac13109055768262dd37edbc6f16890d", "size": "1846", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2256" }, { "name": "Kotlin", "bytes": "18406" } ], "symlink_target": "" }
using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Data; namespace GoG.WinRT.Common { /// <summary> /// Value converter that translates true to <see cref="Visibility.Visible"/> and false to /// <see cref="Visibility.Collapsed"/>. /// </summary> public sealed class BooleanToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { return (value is bool && (bool)value) ? Visibility.Visible : Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, string language) { return value is Visibility && (Visibility)value == Visibility.Visible; } } }
{ "content_hash": "f3a6c5e03492ffecdd5b7ac8fc360a58", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 99, "avg_line_length": 33.52173913043478, "alnum_prop": 0.6601815823605707, "repo_name": "cbordeman/gameofgo", "id": "51ebde197c57dca511d7542e52c8e7c8b814afbf", "size": "773", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GoG.WinRT/Common/BooleanToVisibilityConverter.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1561" }, { "name": "C", "bytes": "185564" }, { "name": "C#", "bytes": "571008" }, { "name": "C++", "bytes": "114101755" }, { "name": "M4", "bytes": "9738" }, { "name": "Perl", "bytes": "6080" }, { "name": "Shell", "bytes": "728" } ], "symlink_target": "" }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/eventarc/v1/channel_connection.proto package com.google.cloud.eventarc.v1; /** * * * <pre> * A representation of the ChannelConnection resource. * A ChannelConnection is a resource which event providers create during the * activation process to establish a connection between the provider and the * subscriber channel. * </pre> * * Protobuf type {@code google.cloud.eventarc.v1.ChannelConnection} */ public final class ChannelConnection extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.eventarc.v1.ChannelConnection) ChannelConnectionOrBuilder { private static final long serialVersionUID = 0L; // Use ChannelConnection.newBuilder() to construct. private ChannelConnection(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ChannelConnection() { name_ = ""; uid_ = ""; channel_ = ""; activationToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ChannelConnection(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.eventarc.v1.ChannelConnectionProto .internal_static_google_cloud_eventarc_v1_ChannelConnection_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.eventarc.v1.ChannelConnectionProto .internal_static_google_cloud_eventarc_v1_ChannelConnection_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.eventarc.v1.ChannelConnection.class, com.google.cloud.eventarc.v1.ChannelConnection.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; private volatile java.lang.Object name_; /** * * * <pre> * Required. The name of the connection. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Required. The name of the connection. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int UID_FIELD_NUMBER = 2; private volatile java.lang.Object uid_; /** * * * <pre> * Output only. Server assigned ID of the resource. * The server guarantees uniqueness and immutability until deleted. * </pre> * * <code>string uid = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return The uid. */ @java.lang.Override public java.lang.String getUid() { java.lang.Object ref = uid_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uid_ = s; return s; } } /** * * * <pre> * Output only. Server assigned ID of the resource. * The server guarantees uniqueness and immutability until deleted. * </pre> * * <code>string uid = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return The bytes for uid. */ @java.lang.Override public com.google.protobuf.ByteString getUidBytes() { java.lang.Object ref = uid_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); uid_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CHANNEL_FIELD_NUMBER = 5; private volatile java.lang.Object channel_; /** * * * <pre> * Required. The name of the connected subscriber Channel. * This is a weak reference to avoid cross project and cross accounts * references. This must be in * `projects/{project}/location/{location}/channels/{channel_id}` format. * </pre> * * <code> * string channel = 5 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The channel. */ @java.lang.Override public java.lang.String getChannel() { java.lang.Object ref = channel_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); channel_ = s; return s; } } /** * * * <pre> * Required. The name of the connected subscriber Channel. * This is a weak reference to avoid cross project and cross accounts * references. This must be in * `projects/{project}/location/{location}/channels/{channel_id}` format. * </pre> * * <code> * string channel = 5 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for channel. */ @java.lang.Override public com.google.protobuf.ByteString getChannelBytes() { java.lang.Object ref = channel_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); channel_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CREATE_TIME_FIELD_NUMBER = 6; private com.google.protobuf.Timestamp createTime_; /** * * * <pre> * Output only. The creation time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the createTime field is set. */ @java.lang.Override public boolean hasCreateTime() { return createTime_ != null; } /** * * * <pre> * Output only. The creation time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The createTime. */ @java.lang.Override public com.google.protobuf.Timestamp getCreateTime() { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } /** * * * <pre> * Output only. The creation time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { return getCreateTime(); } public static final int UPDATE_TIME_FIELD_NUMBER = 7; private com.google.protobuf.Timestamp updateTime_; /** * * * <pre> * Output only. The last-modified time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 7 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the updateTime field is set. */ @java.lang.Override public boolean hasUpdateTime() { return updateTime_ != null; } /** * * * <pre> * Output only. The last-modified time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 7 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The updateTime. */ @java.lang.Override public com.google.protobuf.Timestamp getUpdateTime() { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } /** * * * <pre> * Output only. The last-modified time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 7 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder() { return getUpdateTime(); } public static final int ACTIVATION_TOKEN_FIELD_NUMBER = 8; private volatile java.lang.Object activationToken_; /** * * * <pre> * Input only. Activation token for the channel. The token will be used * during the creation of ChannelConnection to bind the channel with the * provider project. This field will not be stored in the provider resource. * </pre> * * <code>string activation_token = 8 [(.google.api.field_behavior) = INPUT_ONLY];</code> * * @return The activationToken. */ @java.lang.Override public java.lang.String getActivationToken() { java.lang.Object ref = activationToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); activationToken_ = s; return s; } } /** * * * <pre> * Input only. Activation token for the channel. The token will be used * during the creation of ChannelConnection to bind the channel with the * provider project. This field will not be stored in the provider resource. * </pre> * * <code>string activation_token = 8 [(.google.api.field_behavior) = INPUT_ONLY];</code> * * @return The bytes for activationToken. */ @java.lang.Override public com.google.protobuf.ByteString getActivationTokenBytes() { java.lang.Object ref = activationToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); activationToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(uid_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, uid_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(channel_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 5, channel_); } if (createTime_ != null) { output.writeMessage(6, getCreateTime()); } if (updateTime_ != null) { output.writeMessage(7, getUpdateTime()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(activationToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 8, activationToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(uid_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, uid_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(channel_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, channel_); } if (createTime_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(6, getCreateTime()); } if (updateTime_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(7, getUpdateTime()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(activationToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(8, activationToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.eventarc.v1.ChannelConnection)) { return super.equals(obj); } com.google.cloud.eventarc.v1.ChannelConnection other = (com.google.cloud.eventarc.v1.ChannelConnection) obj; if (!getName().equals(other.getName())) return false; if (!getUid().equals(other.getUid())) return false; if (!getChannel().equals(other.getChannel())) return false; if (hasCreateTime() != other.hasCreateTime()) return false; if (hasCreateTime()) { if (!getCreateTime().equals(other.getCreateTime())) return false; } if (hasUpdateTime() != other.hasUpdateTime()) return false; if (hasUpdateTime()) { if (!getUpdateTime().equals(other.getUpdateTime())) return false; } if (!getActivationToken().equals(other.getActivationToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + UID_FIELD_NUMBER; hash = (53 * hash) + getUid().hashCode(); hash = (37 * hash) + CHANNEL_FIELD_NUMBER; hash = (53 * hash) + getChannel().hashCode(); if (hasCreateTime()) { hash = (37 * hash) + CREATE_TIME_FIELD_NUMBER; hash = (53 * hash) + getCreateTime().hashCode(); } if (hasUpdateTime()) { hash = (37 * hash) + UPDATE_TIME_FIELD_NUMBER; hash = (53 * hash) + getUpdateTime().hashCode(); } hash = (37 * hash) + ACTIVATION_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getActivationToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.eventarc.v1.ChannelConnection parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.eventarc.v1.ChannelConnection parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.eventarc.v1.ChannelConnection parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.eventarc.v1.ChannelConnection parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.eventarc.v1.ChannelConnection parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.eventarc.v1.ChannelConnection parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.eventarc.v1.ChannelConnection parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.eventarc.v1.ChannelConnection parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.eventarc.v1.ChannelConnection parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.eventarc.v1.ChannelConnection parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.eventarc.v1.ChannelConnection parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.eventarc.v1.ChannelConnection parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.eventarc.v1.ChannelConnection prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * A representation of the ChannelConnection resource. * A ChannelConnection is a resource which event providers create during the * activation process to establish a connection between the provider and the * subscriber channel. * </pre> * * Protobuf type {@code google.cloud.eventarc.v1.ChannelConnection} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.eventarc.v1.ChannelConnection) com.google.cloud.eventarc.v1.ChannelConnectionOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.eventarc.v1.ChannelConnectionProto .internal_static_google_cloud_eventarc_v1_ChannelConnection_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.eventarc.v1.ChannelConnectionProto .internal_static_google_cloud_eventarc_v1_ChannelConnection_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.eventarc.v1.ChannelConnection.class, com.google.cloud.eventarc.v1.ChannelConnection.Builder.class); } // Construct using com.google.cloud.eventarc.v1.ChannelConnection.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); name_ = ""; uid_ = ""; channel_ = ""; if (createTimeBuilder_ == null) { createTime_ = null; } else { createTime_ = null; createTimeBuilder_ = null; } if (updateTimeBuilder_ == null) { updateTime_ = null; } else { updateTime_ = null; updateTimeBuilder_ = null; } activationToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.eventarc.v1.ChannelConnectionProto .internal_static_google_cloud_eventarc_v1_ChannelConnection_descriptor; } @java.lang.Override public com.google.cloud.eventarc.v1.ChannelConnection getDefaultInstanceForType() { return com.google.cloud.eventarc.v1.ChannelConnection.getDefaultInstance(); } @java.lang.Override public com.google.cloud.eventarc.v1.ChannelConnection build() { com.google.cloud.eventarc.v1.ChannelConnection result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.eventarc.v1.ChannelConnection buildPartial() { com.google.cloud.eventarc.v1.ChannelConnection result = new com.google.cloud.eventarc.v1.ChannelConnection(this); result.name_ = name_; result.uid_ = uid_; result.channel_ = channel_; if (createTimeBuilder_ == null) { result.createTime_ = createTime_; } else { result.createTime_ = createTimeBuilder_.build(); } if (updateTimeBuilder_ == null) { result.updateTime_ = updateTime_; } else { result.updateTime_ = updateTimeBuilder_.build(); } result.activationToken_ = activationToken_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.eventarc.v1.ChannelConnection) { return mergeFrom((com.google.cloud.eventarc.v1.ChannelConnection) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.eventarc.v1.ChannelConnection other) { if (other == com.google.cloud.eventarc.v1.ChannelConnection.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } if (!other.getUid().isEmpty()) { uid_ = other.uid_; onChanged(); } if (!other.getChannel().isEmpty()) { channel_ = other.channel_; onChanged(); } if (other.hasCreateTime()) { mergeCreateTime(other.getCreateTime()); } if (other.hasUpdateTime()) { mergeUpdateTime(other.getUpdateTime()); } if (!other.getActivationToken().isEmpty()) { activationToken_ = other.activationToken_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { name_ = input.readStringRequireUtf8(); break; } // case 10 case 18: { uid_ = input.readStringRequireUtf8(); break; } // case 18 case 42: { channel_ = input.readStringRequireUtf8(); break; } // case 42 case 50: { input.readMessage(getCreateTimeFieldBuilder().getBuilder(), extensionRegistry); break; } // case 50 case 58: { input.readMessage(getUpdateTimeFieldBuilder().getBuilder(), extensionRegistry); break; } // case 58 case 66: { activationToken_ = input.readStringRequireUtf8(); break; } // case 66 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private java.lang.Object name_ = ""; /** * * * <pre> * Required. The name of the connection. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The name of the connection. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The name of the connection. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * * * <pre> * Required. The name of the connection. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * * * <pre> * Required. The name of the connection. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } private java.lang.Object uid_ = ""; /** * * * <pre> * Output only. Server assigned ID of the resource. * The server guarantees uniqueness and immutability until deleted. * </pre> * * <code>string uid = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return The uid. */ public java.lang.String getUid() { java.lang.Object ref = uid_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uid_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Output only. Server assigned ID of the resource. * The server guarantees uniqueness and immutability until deleted. * </pre> * * <code>string uid = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return The bytes for uid. */ public com.google.protobuf.ByteString getUidBytes() { java.lang.Object ref = uid_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); uid_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Output only. Server assigned ID of the resource. * The server guarantees uniqueness and immutability until deleted. * </pre> * * <code>string uid = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @param value The uid to set. * @return This builder for chaining. */ public Builder setUid(java.lang.String value) { if (value == null) { throw new NullPointerException(); } uid_ = value; onChanged(); return this; } /** * * * <pre> * Output only. Server assigned ID of the resource. * The server guarantees uniqueness and immutability until deleted. * </pre> * * <code>string uid = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return This builder for chaining. */ public Builder clearUid() { uid_ = getDefaultInstance().getUid(); onChanged(); return this; } /** * * * <pre> * Output only. Server assigned ID of the resource. * The server guarantees uniqueness and immutability until deleted. * </pre> * * <code>string uid = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @param value The bytes for uid to set. * @return This builder for chaining. */ public Builder setUidBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); uid_ = value; onChanged(); return this; } private java.lang.Object channel_ = ""; /** * * * <pre> * Required. The name of the connected subscriber Channel. * This is a weak reference to avoid cross project and cross accounts * references. This must be in * `projects/{project}/location/{location}/channels/{channel_id}` format. * </pre> * * <code> * string channel = 5 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The channel. */ public java.lang.String getChannel() { java.lang.Object ref = channel_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); channel_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The name of the connected subscriber Channel. * This is a weak reference to avoid cross project and cross accounts * references. This must be in * `projects/{project}/location/{location}/channels/{channel_id}` format. * </pre> * * <code> * string channel = 5 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for channel. */ public com.google.protobuf.ByteString getChannelBytes() { java.lang.Object ref = channel_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); channel_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The name of the connected subscriber Channel. * This is a weak reference to avoid cross project and cross accounts * references. This must be in * `projects/{project}/location/{location}/channels/{channel_id}` format. * </pre> * * <code> * string channel = 5 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The channel to set. * @return This builder for chaining. */ public Builder setChannel(java.lang.String value) { if (value == null) { throw new NullPointerException(); } channel_ = value; onChanged(); return this; } /** * * * <pre> * Required. The name of the connected subscriber Channel. * This is a weak reference to avoid cross project and cross accounts * references. This must be in * `projects/{project}/location/{location}/channels/{channel_id}` format. * </pre> * * <code> * string channel = 5 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearChannel() { channel_ = getDefaultInstance().getChannel(); onChanged(); return this; } /** * * * <pre> * Required. The name of the connected subscriber Channel. * This is a weak reference to avoid cross project and cross accounts * references. This must be in * `projects/{project}/location/{location}/channels/{channel_id}` format. * </pre> * * <code> * string channel = 5 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for channel to set. * @return This builder for chaining. */ public Builder setChannelBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); channel_ = value; onChanged(); return this; } private com.google.protobuf.Timestamp createTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> createTimeBuilder_; /** * * * <pre> * Output only. The creation time. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the createTime field is set. */ public boolean hasCreateTime() { return createTimeBuilder_ != null || createTime_ != null; } /** * * * <pre> * Output only. The creation time. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The createTime. */ public com.google.protobuf.Timestamp getCreateTime() { if (createTimeBuilder_ == null) { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } else { return createTimeBuilder_.getMessage(); } } /** * * * <pre> * Output only. The creation time. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } createTime_ = value; onChanged(); } else { createTimeBuilder_.setMessage(value); } return this; } /** * * * <pre> * Output only. The creation time. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setCreateTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (createTimeBuilder_ == null) { createTime_ = builderForValue.build(); onChanged(); } else { createTimeBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Output only. The creation time. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder mergeCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (createTime_ != null) { createTime_ = com.google.protobuf.Timestamp.newBuilder(createTime_).mergeFrom(value).buildPartial(); } else { createTime_ = value; } onChanged(); } else { createTimeBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Output only. The creation time. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder clearCreateTime() { if (createTimeBuilder_ == null) { createTime_ = null; onChanged(); } else { createTime_ = null; createTimeBuilder_ = null; } return this; } /** * * * <pre> * Output only. The creation time. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.protobuf.Timestamp.Builder getCreateTimeBuilder() { onChanged(); return getCreateTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Output only. The creation time. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { if (createTimeBuilder_ != null) { return createTimeBuilder_.getMessageOrBuilder(); } else { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } } /** * * * <pre> * Output only. The creation time. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getCreateTimeFieldBuilder() { if (createTimeBuilder_ == null) { createTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getCreateTime(), getParentForChildren(), isClean()); createTime_ = null; } return createTimeBuilder_; } private com.google.protobuf.Timestamp updateTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> updateTimeBuilder_; /** * * * <pre> * Output only. The last-modified time. * </pre> * * <code> * .google.protobuf.Timestamp update_time = 7 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the updateTime field is set. */ public boolean hasUpdateTime() { return updateTimeBuilder_ != null || updateTime_ != null; } /** * * * <pre> * Output only. The last-modified time. * </pre> * * <code> * .google.protobuf.Timestamp update_time = 7 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The updateTime. */ public com.google.protobuf.Timestamp getUpdateTime() { if (updateTimeBuilder_ == null) { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } else { return updateTimeBuilder_.getMessage(); } } /** * * * <pre> * Output only. The last-modified time. * </pre> * * <code> * .google.protobuf.Timestamp update_time = 7 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setUpdateTime(com.google.protobuf.Timestamp value) { if (updateTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateTime_ = value; onChanged(); } else { updateTimeBuilder_.setMessage(value); } return this; } /** * * * <pre> * Output only. The last-modified time. * </pre> * * <code> * .google.protobuf.Timestamp update_time = 7 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setUpdateTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (updateTimeBuilder_ == null) { updateTime_ = builderForValue.build(); onChanged(); } else { updateTimeBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Output only. The last-modified time. * </pre> * * <code> * .google.protobuf.Timestamp update_time = 7 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder mergeUpdateTime(com.google.protobuf.Timestamp value) { if (updateTimeBuilder_ == null) { if (updateTime_ != null) { updateTime_ = com.google.protobuf.Timestamp.newBuilder(updateTime_).mergeFrom(value).buildPartial(); } else { updateTime_ = value; } onChanged(); } else { updateTimeBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Output only. The last-modified time. * </pre> * * <code> * .google.protobuf.Timestamp update_time = 7 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder clearUpdateTime() { if (updateTimeBuilder_ == null) { updateTime_ = null; onChanged(); } else { updateTime_ = null; updateTimeBuilder_ = null; } return this; } /** * * * <pre> * Output only. The last-modified time. * </pre> * * <code> * .google.protobuf.Timestamp update_time = 7 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.protobuf.Timestamp.Builder getUpdateTimeBuilder() { onChanged(); return getUpdateTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Output only. The last-modified time. * </pre> * * <code> * .google.protobuf.Timestamp update_time = 7 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder() { if (updateTimeBuilder_ != null) { return updateTimeBuilder_.getMessageOrBuilder(); } else { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } } /** * * * <pre> * Output only. The last-modified time. * </pre> * * <code> * .google.protobuf.Timestamp update_time = 7 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getUpdateTimeFieldBuilder() { if (updateTimeBuilder_ == null) { updateTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getUpdateTime(), getParentForChildren(), isClean()); updateTime_ = null; } return updateTimeBuilder_; } private java.lang.Object activationToken_ = ""; /** * * * <pre> * Input only. Activation token for the channel. The token will be used * during the creation of ChannelConnection to bind the channel with the * provider project. This field will not be stored in the provider resource. * </pre> * * <code>string activation_token = 8 [(.google.api.field_behavior) = INPUT_ONLY];</code> * * @return The activationToken. */ public java.lang.String getActivationToken() { java.lang.Object ref = activationToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); activationToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Input only. Activation token for the channel. The token will be used * during the creation of ChannelConnection to bind the channel with the * provider project. This field will not be stored in the provider resource. * </pre> * * <code>string activation_token = 8 [(.google.api.field_behavior) = INPUT_ONLY];</code> * * @return The bytes for activationToken. */ public com.google.protobuf.ByteString getActivationTokenBytes() { java.lang.Object ref = activationToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); activationToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Input only. Activation token for the channel. The token will be used * during the creation of ChannelConnection to bind the channel with the * provider project. This field will not be stored in the provider resource. * </pre> * * <code>string activation_token = 8 [(.google.api.field_behavior) = INPUT_ONLY];</code> * * @param value The activationToken to set. * @return This builder for chaining. */ public Builder setActivationToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } activationToken_ = value; onChanged(); return this; } /** * * * <pre> * Input only. Activation token for the channel. The token will be used * during the creation of ChannelConnection to bind the channel with the * provider project. This field will not be stored in the provider resource. * </pre> * * <code>string activation_token = 8 [(.google.api.field_behavior) = INPUT_ONLY];</code> * * @return This builder for chaining. */ public Builder clearActivationToken() { activationToken_ = getDefaultInstance().getActivationToken(); onChanged(); return this; } /** * * * <pre> * Input only. Activation token for the channel. The token will be used * during the creation of ChannelConnection to bind the channel with the * provider project. This field will not be stored in the provider resource. * </pre> * * <code>string activation_token = 8 [(.google.api.field_behavior) = INPUT_ONLY];</code> * * @param value The bytes for activationToken to set. * @return This builder for chaining. */ public Builder setActivationTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); activationToken_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.eventarc.v1.ChannelConnection) } // @@protoc_insertion_point(class_scope:google.cloud.eventarc.v1.ChannelConnection) private static final com.google.cloud.eventarc.v1.ChannelConnection DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.eventarc.v1.ChannelConnection(); } public static com.google.cloud.eventarc.v1.ChannelConnection getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ChannelConnection> PARSER = new com.google.protobuf.AbstractParser<ChannelConnection>() { @java.lang.Override public ChannelConnection parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ChannelConnection> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ChannelConnection> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.eventarc.v1.ChannelConnection getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
{ "content_hash": "5ce766f4517f155879cff46c91786c6e", "timestamp": "", "source": "github", "line_count": 1764, "max_line_length": 110, "avg_line_length": 30.200113378684808, "alnum_prop": 0.6198261783642746, "repo_name": "googleapis/java-eventarc", "id": "283a2179aba8fc2458f8a6a770adaea65aa272cc", "size": "53867", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "proto-google-cloud-eventarc-v1/src/main/java/com/google/cloud/eventarc/v1/ChannelConnection.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "801" }, { "name": "Java", "bytes": "2040176" }, { "name": "Python", "bytes": "787" }, { "name": "Shell", "bytes": "20447" } ], "symlink_target": "" }
copyright: years: 2015, 2016 --- {:shortdesc: .shortdesc} # Protegendo recursos de backend com o serviço {{site.data.keyword.amashort}} {: #protecting-resources} *Última atualização: 30 de abril de 2016* {: .last-updated} Com o serviço {{site.data.keyword.amashort}}, é possível proteger seus aplicativos backend Node.js e baseados em Java que estão em execução no {{site.data.keyword.Bluemix_notm}} com a segurança e o monitoramento de OAuth ativados pelo dispositivo móvel. {:shortdesc} ## Antes de iniciar {: #before-you-begin} Antes de iniciar, assegure-se de criar o serviço Node.js. ## Filtro de autorização {: #auth-filter} O {{site.data.keyword.amashort}} server SDK tem filtros de autorização que podem ser usados para proteger seus aplicativos backend. O filtro de autorização intercepta solicitações recebidas e valida se um cabeçalho de autorização estiver presente. Se o cabeçalho de autorização não estiver presente ou for inválido, o filtro retorna uma resposta com HTTP 401. O {{site.data.keyword.amashort}} client SDK sabe como interceptar uma resposta HTTP 401 que é retornada pelo {{site.data.keyword.amashort}} server SDK e aciona o fluxo de autenticação. ## Cabeçalho de autorização {: #auth-header} O cabeçalho de autorização na solicitação recebida consiste em três partes: Condutor, Token de acesso e Token do ID, que são separados por espaços em branco. `Token de acesso` é um componente obrigatório, enquanto que `Token do ID` é opcional. O cabeçalho de autorização recebido é processado pelo respectivo filtro de autorização. O filtro valida as assinaturas do token de acesso e do token do ID, a data de expiração e a integridade estrutural. Depois que a validação é aprovada, um objeto de contexto de segurança é incluído no objeto da solicitação. É possível obter uma referência para o contexto de segurança usando uma API respectiva. O contexto de segurança contém o assunto, o usuário, o dispositivo e as informações do aplicativo armazenadas com uma estrutura a seguir: ```JSON { "imf.sub":"myclientid", "imf.user": { "id":"user-name", "authBy":"myrealm", "displayName":"display-name" }, "imf.device": { "id":"device-id", "platform":"iOSnative", "model":"device-model", "osVersion":"device-os" }, "imf.application": { "id":"ios.bundle.id", "version":"1.0" } } ``` * `imf.sub`: especificará o assunto do token do ID ou o ID exclusivo do cliente se nenhum token de ID existir. * `imf.user`: especifica a identidade do usuário que é extraída do token do ID. Se não existir nenhum token de ID, esse campo reterá um objeto vazio. * `imf.device`: especifica a identidade do dispositivo que é extraída do token do ID. Se não existir nenhum token de ID, esse campo reterá um objeto vazio. * `imf.application`: especifica a identidade do aplicativo que é extraída do token do ID. Se não existir nenhum token de ID, esse campo reterá um objeto em branco. ## Próximas etapas {: #next-steps} * [Protegendo recursos de Node.js](protecting-resources-nodejs.html) * [Protegendo os recursos do Liberty for Java&trade;](protecting-resources-java.html) * [Desenvolvimento local](protecting-resources-local.html)
{ "content_hash": "b5637481f343a72f73477ba8d1b74d06", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 544, "avg_line_length": 52.25806451612903, "alnum_prop": 0.7422839506172839, "repo_name": "jergirl/MCAProd", "id": "c6796f605f5843d5647064cfedb434c81e3769b5", "size": "3331", "binary": false, "copies": "1", "ref": "refs/heads/Staging2Prod20160714", "path": "services/nl/pt/BR/mobileaccess/protecting-resources.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace WellCommerce\Bundle\PaymentBundle\Visitor; use WellCommerce\Bundle\OrderBundle\Entity\OrderInterface; use WellCommerce\Bundle\OrderBundle\Visitor\OrderVisitorInterface; /** * Class PaymentMethodOrderVisitor * * @author Adam Piotrowski <adam@wellcommerce.org> */ final class PaymentMethodOrderVisitor implements OrderVisitorInterface { /** * {@inheritdoc} */ public function visitOrder(OrderInterface $order) { if (false === $order->hasShippingMethod()) { $order->setPaymentMethod(null); return; } $shippingMethod = $order->getShippingMethod(); $paymentMethods = $shippingMethod->getPaymentMethods(); if (false === $order->hasPaymentMethod() || false === $paymentMethods->contains($order->getPaymentMethod())) { $order->setPaymentMethod($paymentMethods->first()); } } }
{ "content_hash": "974b5b44c4c4b3a6f824cdcfed04b26a", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 118, "avg_line_length": 27.5, "alnum_prop": 0.6491978609625668, "repo_name": "WellCommerce/PaymentBundle", "id": "921258f89976bcc258f585f52283a262ffcf476b", "size": "1224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Visitor/PaymentMethodOrderVisitor.php", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "1581" }, { "name": "PHP", "bytes": "117968" } ], "symlink_target": "" }
from google.cloud import bigquery_storage_v1 async def sample_batch_commit_write_streams(): # Create a client client = bigquery_storage_v1.BigQueryWriteAsyncClient() # Initialize request argument(s) request = bigquery_storage_v1.BatchCommitWriteStreamsRequest( parent="parent_value", write_streams=["write_streams_value1", "write_streams_value2"], ) # Make the request response = await client.batch_commit_write_streams(request=request) # Handle the response print(response) # [END bigquerystorage_v1_generated_BigQueryWrite_BatchCommitWriteStreams_async]
{ "content_hash": "663c79813a8b09fc481eb35c113e7e52", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 80, "avg_line_length": 29.285714285714285, "alnum_prop": 0.7317073170731707, "repo_name": "googleapis/python-bigquery-storage", "id": "da8d31415e7e32085de9c0cb58127386b7a84162", "size": "2038", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "samples/generated_samples/bigquerystorage_v1_generated_big_query_write_batch_commit_write_streams_async.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2050" }, { "name": "Python", "bytes": "1136897" }, { "name": "Shell", "bytes": "30690" } ], "symlink_target": "" }
require 'cisco_node_utils' if Puppet.features.cisco_node_utils? begin require 'puppet_x/cisco/autogen' rescue LoadError # seen on master, not on agent # See longstanding Puppet issues #4248, #7316, #14073, #14149, etc. Ugh. require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', 'puppet_x', 'cisco', 'autogen.rb')) end Puppet::Type.type(:cisco_vpc_domain).provide(:cisco) do desc 'The Cisco provider.' confine feature: :cisco_node_utils defaultfor operatingsystem: :nexus mk_resource_methods VPC_NON_BOOL_PROPS = [ :auto_recovery_reload_delay, :delay_restore, :delay_restore_interface_vlan, :dual_active_exclude_interface_vlan_bridge_domain, :fabricpath_emulated_switch_id, :peer_keepalive_dest, :peer_keepalive_hold_timeout, :peer_keepalive_interval, :peer_keepalive_interval_timeout, :peer_keepalive_precedence, :peer_keepalive_src, :peer_keepalive_udp_port, :peer_keepalive_vrf, :peer_gateway_exclude_bridge_domain, :peer_gateway_exclude_vlan, :role_priority, :system_mac, :system_priority, ] # There are multiple BOOL arrays due to dependency requirements. The order of # these property arrays is important for proper processing by properties_set. VPC_BOOL_PROPS1 = [ :arp_synchronize, :auto_recovery, :nd_synchronize, :peer_gateway, :peer_switch, ] VPC_BOOL_PROPS2 = [ :fabricpath_multicast_load_balance, :graceful_consistency_check, :layer3_peer_routing, :port_channel_limit, :self_isolation, :shutdown, ] VPC_PROPS = VPC_BOOL_PROPS1 + VPC_NON_BOOL_PROPS + VPC_BOOL_PROPS2 PuppetX::Cisco::AutoGen.mk_puppet_methods(:non_bool, self, '@vpc_domain', VPC_NON_BOOL_PROPS) PuppetX::Cisco::AutoGen.mk_puppet_methods(:bool, self, '@vpc_domain', VPC_BOOL_PROPS1) PuppetX::Cisco::AutoGen.mk_puppet_methods(:bool, self, '@vpc_domain', VPC_BOOL_PROPS2) def initialize(value={}) super(value) @vpc_domain = Cisco::Vpc.domains[@property_hash[:name]] @property_flush = {} debug 'Created provider instance of cisco_vpc_domain.' end def self.properties_get(domain_id, v) current_state = { domain: domain_id, name: domain_id, ensure: :present, } # Call node_utils getter for each property VPC_PROPS.each do |prop| current_state[prop] = v.send(prop) end new(current_state) end # self.properties_get def self.instances domains = [] Cisco::Vpc.domains.each do |domain_id, obj| domains << properties_get(domain_id, obj) end domains end def self.prefetch(resources) domains = instances resources.keys.each do |id| provider = domains.find { |domain| domain.instance_name == id } resources[id].provider = provider unless provider.nil? end end # self.prefetch def exists? (@property_hash[:ensure] == :present) end def create @property_flush[:ensure] = :present end def destroy @property_flush[:ensure] = :absent end def instance_name domain end def properties_set(new_vpc_domain=false) VPC_PROPS.each do |prop| next unless @resource[prop] send("#{prop}=", @resource[prop]) if new_vpc_domain unless @property_flush[prop].nil? @vpc_domain.send("#{prop}=", @property_flush[prop]) if @vpc_domain.respond_to?("#{prop}=") end end peer_keepalive_custom_set end def peer_keepalive_any? @property_flush[:peer_keepalive_dest] || @property_flush[:peer_keepalive_hold_timeout] || @property_flush[:peer_keepalive_interval] || @property_flush[:peer_keepalive_interval_timeout] || @property_flush[:peer_keepalive_precedence] || @property_flush[:peer_keepalive_src] || @property_flush[:peer_keepalive_udp_port] || @property_flush[:peer_keepalive_vrf] end # rubocop:disable Metrics/MethodLength def peer_keepalive_custom_set return unless peer_keepalive_any? if @property_flush[:peer_keepalive_dest] pka_dest = @property_flush[:peer_keepalive_dest] else pka_dest = @vpc_domain.peer_keepalive_dest end if @property_flush[:peer_keepalive_hold_timeout] pka_hold_timeout = @property_flush[:peer_keepalive_hold_timeout] else pka_hold_timeout = @vpc_domain.peer_keepalive_hold_timeout end if @property_flush[:peer_keepalive_interval] pka_interval = @property_flush[:peer_keepalive_interval] else pka_interval = @vpc_domain.peer_keepalive_interval end if @property_flush[:peer_keepalive_interval_timeout] pka_timeout = @property_flush[:peer_keepalive_interval_timeout] else pka_timeout = @vpc_domain.peer_keepalive_interval_timeout end if @property_flush[:peer_keepalive_precedence] pka_prec = @property_flush[:peer_keepalive_precedence] else pka_prec = @vpc_domain.peer_keepalive_precedence end if @property_flush[:peer_keepalive_src] pka_src = @property_flush[:peer_keepalive_src] else pka_src = @vpc_domain.peer_keepalive_src end if @property_flush[:peer_keepalive_udp_port] pka_udp_port = @property_flush[:peer_keepalive_udp_port] else pka_udp_port = @vpc_domain.peer_keepalive_udp_port end if @property_flush[:peer_keepalive_vrf] pka_vrf = @property_flush[:peer_keepalive_vrf] else pka_vrf = @vpc_domain.peer_keepalive_vrf end @vpc_domain.peer_keepalive_set(pka_dest, pka_src, pka_udp_port, pka_vrf, pka_interval, pka_timeout, pka_prec, pka_hold_timeout) end # rubocop:enable Metrics/MethodLength def flush if @property_flush[:ensure] == :absent @vpc_domain.destroy @vpc_domain = nil else # Create/Update if @vpc_domain.nil? new_vpc_domain = true @vpc_domain = Cisco::Vpc.new(@resource[:domain]) end properties_set(new_vpc_domain) end puts_config end def puts_config if @vpc_domain.nil? info "Vpc_domain=#{@resource[:domain]} is absent." return end # Dump all current properties for this vpc_domain current = sprintf("\n%30s: %s", 'vpc_domain', instance_name) VPC_PROPS.each do |prop| current.concat(sprintf("\n%30s: %s", prop, @vpc_domain.send(prop))) end debug current end # puts_config end # Puppet::Type
{ "content_hash": "da07500e1c6cab653593c572c8dc09fc", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 79, "avg_line_length": 30.293577981651374, "alnum_prop": 0.6399152029073288, "repo_name": "cisco/cisco-network-puppet-module", "id": "cbfd70ac62687d99a8b4f703fc57058045f82059", "size": "7225", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "lib/puppet/provider/cisco_vpc_domain/cisco.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "31" }, { "name": "Puppet", "bytes": "2912" }, { "name": "Python", "bytes": "7567" }, { "name": "Ruby", "bytes": "1809617" }, { "name": "Shell", "bytes": "10685" } ], "symlink_target": "" }
package com.example.post_dispose; import arez.ActionFlags; import arez.Arez; import arez.ArezContext; import arez.Component; import arez.Disposable; import arez.component.Identifiable; import arez.component.internal.ComponentKernel; import javax.annotation.Generated; import javax.annotation.Nonnull; import org.realityforge.braincheck.Guards; @Generated("arez.processor.ArezProcessor") final class Arez_PostDisposeWithDisabledDisposeNotifierModel extends PostDisposeWithDisabledDisposeNotifierModel implements Disposable, Identifiable<Integer> { private static volatile int $$arezi$$_nextId; private final ComponentKernel $$arezi$$_kernel; Arez_PostDisposeWithDisabledDisposeNotifierModel() { super(); final ArezContext $$arezv$$_context = Arez.context(); final int $$arezv$$_id = ++$$arezi$$_nextId; final String $$arezv$$_name = Arez.areNamesEnabled() ? "com_example_post_dispose_PostDisposeWithDisabledDisposeNotifierModel." + $$arezv$$_id : null; final Component $$arezv$$_component = Arez.areNativeComponentsEnabled() ? $$arezv$$_context.component( "com_example_post_dispose_PostDisposeWithDisabledDisposeNotifierModel", $$arezv$$_id, $$arezv$$_name, null, () -> super.postDispose() ) : null; this.$$arezi$$_kernel = new ComponentKernel( Arez.areZonesEnabled() ? $$arezv$$_context : null, Arez.areNamesEnabled() ? $$arezv$$_name : null, $$arezv$$_id, Arez.areNativeComponentsEnabled() ? $$arezv$$_component : null, null, null, Arez.areNativeComponentsEnabled() ? null : () -> super.postDispose(), false, false, false ); this.$$arezi$$_kernel.componentConstructed(); this.$$arezi$$_kernel.componentReady(); } private int $$arezi$$_id() { return this.$$arezi$$_kernel.getId(); } @Override @Nonnull public Integer getArezId() { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'getArezId' invoked on uninitialized component of type 'com_example_post_dispose_PostDisposeWithDisabledDisposeNotifierModel'" ); } if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'getArezId' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" ); } return $$arezi$$_id(); } @Override public boolean isDisposed() { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'isDisposed' invoked on uninitialized component of type 'com_example_post_dispose_PostDisposeWithDisabledDisposeNotifierModel'" ); } if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'isDisposed' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" ); } return this.$$arezi$$_kernel.isDisposed(); } @Override public void dispose() { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'dispose' invoked on uninitialized component of type 'com_example_post_dispose_PostDisposeWithDisabledDisposeNotifierModel'" ); } if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'dispose' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" ); } this.$$arezi$$_kernel.dispose(); } @Override public int someValue() { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.isActive(), () -> "Method named 'someValue' invoked on " + this.$$arezi$$_kernel.describeState() + " component named '" + this.$$arezi$$_kernel.getName() + "'" ); } return this.$$arezi$$_kernel.getContext().safeAction( Arez.areNamesEnabled() ? this.$$arezi$$_kernel.getName() + ".someValue" : null, () -> super.someValue(), ActionFlags.READ_WRITE | ActionFlags.VERIFY_ACTION_REQUIRED, null ); } @Override public String toString() { if ( Arez.areNamesEnabled() ) { return "ArezComponent[" + this.$$arezi$$_kernel.getName() + "]"; } else { return super.toString(); } } }
{ "content_hash": "28c5c3ebe5f6d387d4333d49b4c5460c", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 330, "avg_line_length": 55.082352941176474, "alnum_prop": 0.6815463477146518, "repo_name": "realityforge/arez", "id": "e3478df5289c15ad77271bad260a591d4954c9b3", "size": "4682", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "processor/src/test/fixtures/expected/com/example/post_dispose/Arez_PostDisposeWithDisabledDisposeNotifierModel.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "3464" }, { "name": "Java", "bytes": "1657719" }, { "name": "Ruby", "bytes": "49661" } ], "symlink_target": "" }
<?php namespace Chamilo\Core\Repository\ContentObject\Assignment\Display\Component; use Chamilo\Core\Repository\Common\Rendition\ContentObjectRendition; use Chamilo\Core\Repository\Common\Rendition\ContentObjectRenditionImplementation; use Chamilo\Core\Repository\ContentObject\Assignment\Display\Form\DetailsForm; use Chamilo\Core\Repository\ContentObject\Assignment\Display\Manager; use Chamilo\Core\Repository\ContentObject\Assignment\Display\Service\DetailsProcessor; use Chamilo\Libraries\Architecture\Application\ApplicationConfiguration; use Chamilo\Libraries\Architecture\Application\ApplicationFactory; use Chamilo\Libraries\Architecture\Exceptions\NoObjectSelectedException; use Chamilo\Libraries\Format\Structure\ActionBar\Button; use Chamilo\Libraries\Format\Structure\ActionBar\ButtonGroup; use Chamilo\Libraries\Format\Structure\ActionBar\ButtonToolBar; use Chamilo\Libraries\Format\Structure\ActionBar\Renderer\ButtonToolBarRenderer; use Chamilo\Libraries\Format\Tabs\DynamicContentTab; use Chamilo\Libraries\Format\Tabs\DynamicTabsRenderer; use Chamilo\Libraries\Format\Theme; use Chamilo\Libraries\Platform\Translation; use Chamilo\Libraries\Utilities\DatetimeUtilities; use Chamilo\Libraries\Utilities\Utilities; /** * * @package Chamilo\Core\Repository\ContentObject\Assignment\Display\Component * @author Hans De Bisschop <hans.de.bisschop@ehb.be> * @author Magali Gillard <magali.gillard@ehb.be> * @author Eduard Vossen <eduard.vossen@ehb.be> */ class EntryComponent extends Manager implements \Chamilo\Core\Repository\Feedback\FeedbackSupport { /** * * @var \Chamilo\Core\Repository\ContentObject\Assignment\Display\Storage\DataClass\Entry */ private $entry; /** * * @var \Chamilo\Core\Repository\ContentObject\Assignment\Display\Storage\DataClass\Score */ private $score; /** * * @var \Chamilo\Core\Repository\ContentObject\Assignment\Display\Storage\DataClass\Note */ private $note; /** * * @var \Chamilo\Core\Repository\ContentObject\Assignment\Display\Form\detailsForm */ private $detailsForm; /** * * @var ButtonToolBarRenderer */ private $buttonToolbarRenderer; public function run() { $entryIdentifier = $this->getRequest()->query->get(self::PARAM_ENTRY_ID); $this->buttonToolbarRenderer = $this->getButtonToolbarRenderer(); if (! $entryIdentifier) { throw new NoObjectSelectedException(Translation::get('Entry')); } else { $this->set_parameter(self::PARAM_ENTRY_ID, $entryIdentifier); } $this->entry = $this->getDataProvider()->findEntryByIdentifier($entryIdentifier); $this->processSubmittedData(); $html = array(); $html[] = $this->render_header(); $html[] = $this->ButtonToolbarRenderer->render(); $html[] = $this->renderTabs(); $html[] = $this->render_footer(); return implode(PHP_EOL, $html); } protected function processSubmittedData() { $detailsForm = $this->getDetailsForm(); if ($detailsForm->validate()) { $detailsProcessor = new DetailsProcessor( $this->getDataProvider(), $this->getUser(), $this->getEntry(), $this->getScore(), $this->getNote(), $detailsForm->exportValues()); if (! $detailsProcessor->run()) { return false; } } return true; } /** * * @return \Chamilo\Core\Repository\ContentObject\Assignment\Display\Storage\DataClass\Score */ protected function getScore() { if (! isset($this->score)) { $this->score = $this->getDataProvider()->findScoreByEntry($this->getEntry()); } return $this->score; } /** * * @return \Chamilo\Core\Repository\ContentObject\Assignment\Display\Storage\DataClass\Note */ protected function getNote() { if (! isset($this->note)) { $this->note = $this->getDataProvider()->findNoteByEntry($this->getEntry()); } return $this->note; } /** * * @return string */ protected function renderTabs() { $tabsRenderer = new DynamicTabsRenderer('entry'); $tabsRenderer->add_tab( new DynamicContentTab( 'details', Translation::get('Details'), Theme::getInstance()->getImagePath(self::package(), 'Tab/Details'), $this->renderDetails())); $tabsRenderer->add_tab( new DynamicContentTab( 'entry', Translation::get('Entry'), Theme::getInstance()->getImagePath(self::package(), 'Tab/Entry'), $this->renderContentObject())); return $tabsRenderer->render(); } /** * * @return \Chamilo\Core\Repository\ContentObject\Assignment\Display\Storage\DataClass\Entry */ protected function getEntry() { return $this->entry; } /** * * @return string */ protected function renderContentObject() { $contentObject = $this->getEntry()->getContentObject(); $display = ContentObjectRenditionImplementation::factory( $contentObject, ContentObjectRendition::FORMAT_HTML, ContentObjectRendition::VIEW_FULL, $this); return $display->render(); } /** * * @return string */ protected function renderDetails() { $dateFormat = Translation::get('DateTimeFormatLong', null, Utilities::COMMON_LIBRARIES); $submittedDate = DatetimeUtilities::format_locale_date($dateFormat, $this->getEntry()->getSubmitted()); $html = array(); $properties = array(); $properties[Translation::get('Submitted')] = $submittedDate; $entityRenderer = $this->getDataProvider()->getEntityRendererForEntityTypeAndId( $this->getEntry()->getEntityType(), $this->getEntry()->getEntityId()); $properties = array_merge($properties, $entityRenderer->getProperties()); $html[] = $this->renderPropertiesRows($properties); $html[] = $this->getDetailsForm()->toHtml(); $factory = new ApplicationFactory( \Chamilo\Core\Repository\Feedback\Manager::context(), new ApplicationConfiguration($this->getRequest(), $this->getUser(), $this)); $html[] = $factory->run(); return implode(PHP_EOL, $html); } /** * * @param string[] $properties * @return string */ protected function renderPropertiesRows($properties) { $html = array(); foreach ($properties as $label => $value) { $html[] = $this->renderRow($label, $value); } return implode(PHP_EOL, $html); } /** * * @param string $label * @param string $value * @return string */ protected function renderRow($label, $value) { $html = array(); $html[] = '<div class="form-row">'; $html[] = '<div class="form-label">' . $label . '</div>'; $html[] = '<div class="formw">' . $value . '</div>'; $html[] = '</div>'; return implode(PHP_EOL, $html); } /** * * @return \Chamilo\Core\Repository\ContentObject\Assignment\Display\Form\DetailsForm */ protected function getDetailsForm() { if (! isset($this->detailsForm)) { $this->detailsForm = new DetailsForm( $this->getScore(), $this->getNote(), $this->getDataProvider(), $this->get_url(array(self::PARAM_ENTRY_ID => $this->getEntry()->getId()))); } return $this->detailsForm; } /** * * @see \Chamilo\Core\Repository\Feedback\FeedbackSupport::retrieve_feedbacks() */ public function retrieve_feedbacks($count, $offset) { return $this->getDataProvider()->findFeedbackByEntry($this->getEntry()); } /** * * @see \Chamilo\Core\Repository\Feedback\FeedbackSupport::count_feedbacks() */ public function count_feedbacks() { return $this->getDataProvider()->countFeedbackByEntry($this->getEntry()); } /** * * @see \Chamilo\Core\Repository\Feedback\FeedbackSupport::retrieve_feedback() */ public function retrieve_feedback($feedbackIdentifier) { return $this->getDataProvider()->findFeedbackByIdentifier($feedbackIdentifier); } /** * * @see \Chamilo\Core\Repository\Feedback\FeedbackSupport::get_feedback() */ public function get_feedback() { $feedback = $this->getDataProvider()->initializeFeedback(); $feedback->setEntryId($this->getEntry()->getId()); return $feedback; } /** * * @see \Chamilo\Core\Repository\Feedback\FeedbackSupport::is_allowed_to_view_feedback() */ public function is_allowed_to_view_feedback() { // TODO: Only course managers / teachers should be able to do this return true; } /** * * @see \Chamilo\Core\Repository\Feedback\FeedbackSupport::is_allowed_to_create_feedback() */ public function is_allowed_to_create_feedback() { // TODO: Only course managers / teachers should be able to do this return true; } /** * * @see \Chamilo\Core\Repository\Feedback\FeedbackSupport::is_allowed_to_update_feedback() */ public function is_allowed_to_update_feedback($feedback) { // TODO: Only course managers / teachers should be able to do this return true; } /** * * @see \Chamilo\Core\Repository\Feedback\FeedbackSupport::is_allowed_to_delete_feedback() */ public function is_allowed_to_delete_feedback($feedback) { // TODO: Only course managers / teachers should be able to do this return true; } protected function getButtonToolbarRenderer() { if (! isset($this->actionBar)) { $buttonToolBar = new ButtonToolBar(); $buttonToolBar->addButtonGroup( new ButtonGroup( array( new Button( Translation::get('Download'), Theme::getInstance()->getCommonImagePath('Action/Download')), new Button( Translation::get('SubmissionSubmit'), Theme::getInstance()->getCommonImagePath('Action/Add'))))); $buttonToolBar->addButtonGroup( new ButtonGroup( array( new Button( Translation::get('ScoreOverview'), Theme::getInstance()->getCommonImagePath('Action/Statistics')), new Button( Translation::get('ScoreOverview'), Theme::getInstance()->getCommonImagePath('Action/Statistics'))))); $this->actionBar = new ButtonToolBarRenderer($buttonToolBar); } return $this->actionBar; } }
{ "content_hash": "04a4365f5aeed68d00c766a1feea719b", "timestamp": "", "source": "github", "line_count": 385, "max_line_length": 111, "avg_line_length": 30.441558441558442, "alnum_prop": 0.5785836177474403, "repo_name": "cosnicsTHLU/cosnics", "id": "ca79c0ceb3d04be0a83bf1799d8588f36820fd64", "size": "11720", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Chamilo/Core/Repository/ContentObject/Assignment/Display/Component/EntryComponent.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "86189" }, { "name": "C#", "bytes": "23363" }, { "name": "CSS", "bytes": "1135928" }, { "name": "CoffeeScript", "bytes": "17503" }, { "name": "Gherkin", "bytes": "24033" }, { "name": "HTML", "bytes": "542339" }, { "name": "JavaScript", "bytes": "5296016" }, { "name": "Makefile", "bytes": "3221" }, { "name": "PHP", "bytes": "21903304" }, { "name": "Ruby", "bytes": "618" }, { "name": "Shell", "bytes": "6385" }, { "name": "Smarty", "bytes": "15750" }, { "name": "XSLT", "bytes": "44115" } ], "symlink_target": "" }
/* 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.camunda.connect.httpclient.soap; import org.camunda.connect.Connectors; import org.camunda.connect.spi.Connector; public interface SoapHttpConnector extends Connector<SoapHttpRequest> { static final String ID = Connectors.SOAP_HTTP_CONNECTOR_ID; }
{ "content_hash": "bd4297b5e7b0956eda68da01c179e6b2", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 75, "avg_line_length": 37.54545454545455, "alnum_prop": 0.7663438256658596, "repo_name": "nagyistoce/camunda-connect", "id": "b2c5ac77ff9ab1ed216549a8d3783737d57bfe73", "size": "826", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "soap-http-client/src/main/java/org/camunda/connect/httpclient/soap/SoapHttpConnector.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "105456" } ], "symlink_target": "" }
features["DOM.Range.isPointInRange"] = !!(document.createRange().isPointInRange);
{ "content_hash": "e23f8da0c3a2f1beaf334f8d3e4cf550", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 81, "avg_line_length": 81, "alnum_prop": 0.7777777777777778, "repo_name": "Raynos/feature", "id": "7c59e6a16a9267bf27b604b7e279bba70f696b9d", "size": "81", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/features/DOM/Range/isPointInRange.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1488" }, { "name": "JavaScript", "bytes": "107799" } ], "symlink_target": "" }
package socialite.tables; import socialite.util.HashCode; import java.io.Externalizable; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.IOException; import socialite.util.SociaLiteException; public class Tuple_int_int_long extends Tuple implements Externalizable { private static final long serialVersionUID = 1; public int _0; public int _1; public long _2; public Tuple_int_int_long() {} public Tuple_int_int_long(int __0, int __1, long __2) { _0 = __0; _1 = __1; _2 = __2; } public Tuple_int_int_long clone() { return new Tuple_int_int_long(_0, _1, _2); } public int size() { return 3; } public void update(Tuple _t) { if (!(_t instanceof Tuple_int_int_long)) throw new SociaLiteException("Not supported operation"); Tuple_int_int_long t = (Tuple_int_int_long)_t; _0 = t._0; _1 = t._1; _2 = t._2; } public int hashCode() { return HashCode.get(_0)^HashCode.get(_1)^HashCode.get(_2); } public boolean equals(Object o) { if (!(o instanceof Tuple)) return false; Tuple _t = (Tuple)o; if (_t.getClass().equals(Tuple_int_int_long.class)) { Tuple_int_int_long t=(Tuple_int_int_long)_t; return (_0==(t._0))&& (_1==(t._1))&& (_2==(t._2)); } return false; } public Object get(int column) { if (column==0) return _0; if (column==1) return _1; if (column==2) return _2; return null; } public int getInt(int column) { if (column==0) return _0; if (column==1) return _1; throw new UnsupportedOperationException(); } public long getLong(int column) { if (column==2) return _2; throw new UnsupportedOperationException(); } public float getFloat(int column) { throw new UnsupportedOperationException(); } public double getDouble(int column) { throw new UnsupportedOperationException(); } public Object getObject(int column) { throw new UnsupportedOperationException(); } public void setInt(int column, int v) { if (column==0) { _0=v; return; } if (column==1) { _1=v; return; } throw new UnsupportedOperationException(); } public void setLong(int column, long v) { if (column==2) { _2=v; return; } throw new UnsupportedOperationException(); } public void setFloat(int column, float v) { throw new UnsupportedOperationException(); } public void setDouble(int column, double v) { throw new UnsupportedOperationException(); } public void setObject(int column, Object v) { throw new UnsupportedOperationException(); } public String toString() { return ""+_0+", "+_1+", "+_2; } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { _0=in.readInt(); _1=in.readInt(); _2=in.readLong(); } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(_0); out.writeInt(_1); out.writeLong(_2); } }
{ "content_hash": "d8463c3ed2fbd162ee1c098ca1a3dd53", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 86, "avg_line_length": 22.752, "alnum_prop": 0.6684247538677919, "repo_name": "ofermend/medicare-demo", "id": "e2b0e1f6df83533b19c0c45c9b1baf2970aa2f60", "size": "2844", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "socialite/src/socialite/tables/Tuple_int_int_long.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GAP", "bytes": "35489" }, { "name": "Groff", "bytes": "21" }, { "name": "HTML", "bytes": "111577" }, { "name": "Java", "bytes": "2267927" }, { "name": "PigLatin", "bytes": "5097" }, { "name": "Python", "bytes": "10846103" }, { "name": "R", "bytes": "752" }, { "name": "Shell", "bytes": "30621" }, { "name": "Visual Basic", "bytes": "481" } ], "symlink_target": "" }
<!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_75) on Wed Mar 18 19:43:01 PDT 2015 --> <title>PollServiceProto (grpc-examples 0.1.0-SNAPSHOT API)</title> <meta name="date" content="2015-03-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="PollServiceProto (grpc-examples 0.1.0-SNAPSHOT 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="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="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceStub.html" title="class in edu.sjsu.cmpe273.lab2"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceServer.html" title="class in edu.sjsu.cmpe273.lab2"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?edu/sjsu/cmpe273/lab2/PollServiceProto.html" target="_top">Frames</a></li> <li><a href="PollServiceProto.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>Field&nbsp;|&nbsp;</li> <li>Constr&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>Constr&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">edu.sjsu.cmpe273.lab2</div> <h2 title="Class PollServiceProto" class="title">Class PollServiceProto</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>edu.sjsu.cmpe273.lab2.PollServiceProto</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public final class <span class="strong">PollServiceProto</span> extends java.lang.Object</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== 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>static com.google.protobuf.Descriptors.FileDescriptor</code></td> <td class="colLast"><code><strong><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceProto.html#getDescriptor()">getDescriptor</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><code><strong><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceProto.html#registerAllExtensions(com.google.protobuf.ExtensionRegistry)">registerAllExtensions</a></strong>(com.google.protobuf.ExtensionRegistry&nbsp;registry)</code>&nbsp;</td> </tr> </table> <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, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="registerAllExtensions(com.google.protobuf.ExtensionRegistry)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>registerAllExtensions</h4> <pre>public static&nbsp;void&nbsp;registerAllExtensions(com.google.protobuf.ExtensionRegistry&nbsp;registry)</pre> </li> </ul> <a name="getDescriptor()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getDescriptor</h4> <pre>public static&nbsp;com.google.protobuf.Descriptors.FileDescriptor&nbsp;getDescriptor()</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="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="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceStub.html" title="class in edu.sjsu.cmpe273.lab2"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceServer.html" title="class in edu.sjsu.cmpe273.lab2"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?edu/sjsu/cmpe273/lab2/PollServiceProto.html" target="_top">Frames</a></li> <li><a href="PollServiceProto.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>Field&nbsp;|&nbsp;</li> <li>Constr&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>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "382b7c3700ea8ffe2c9b2e60b7f51eb3", "timestamp": "", "source": "github", "line_count": 233, "max_line_length": 266, "avg_line_length": 33.54935622317596, "alnum_prop": 0.6392477932710758, "repo_name": "nivedhithaVenkatachalam/grpc-java", "id": "5e90bfb3a686ae4bd792ea5ab0efda4e6d8dde75", "size": "7817", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/build/docs/javadoc/edu/sjsu/cmpe273/lab2/PollServiceProto.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "27373" }, { "name": "Java", "bytes": "951496" }, { "name": "Protocol Buffer", "bytes": "21910" }, { "name": "Shell", "bytes": "1396" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "5bd6852010e2dae6d8a3e11e492ab4b0", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "da08e1ce4e47c7d432b361d3badf5f62b6c16374", "size": "235", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Aspleniaceae/Asplenium/Asplenium obovatum/Asplenium obovatum ibericum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using Documenter, ODBC makedocs( modules = [ODBC], sitename = "ODBC.jl", pages = ["Home" => "index.md"] ) deploydocs( repo = "github.com/JuliaDatabases/ODBC.jl.git", target = "build" )
{ "content_hash": "42ee15226b652f11188ee0d048053b90", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 51, "avg_line_length": 17.25, "alnum_prop": 0.6038647342995169, "repo_name": "JuliaDB/ODBC.jl", "id": "a0b1a6e1be1344348023211224c8f69cc730c679", "size": "207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/make.jl", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "141652" }, { "name": "Julia", "bytes": "116985" } ], "symlink_target": "" }
""" Url patterns """ from django.conf.urls import url from worker import views, api_views # Template urlpatterns = [ url(r'^$', views.WorkerManagement.as_view()), ] # For APIs urlpatterns += [ url(r'^api-worker/$', api_views.WorkerAPI.as_view()), url(r'^api-worker/barcode/$', api_views.WorkerBarcodeAPI.as_view()), ]
{ "content_hash": "06f13f17df0d97329715822ba3a1d0d3", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 72, "avg_line_length": 18.555555555555557, "alnum_prop": 0.6616766467065869, "repo_name": "grtfou/data-analytics-web", "id": "87492c28b6391be9f3654c56fdb0f21828849d70", "size": "401", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "website/worker/urls.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "59401" }, { "name": "HTML", "bytes": "94552" }, { "name": "JavaScript", "bytes": "95287" }, { "name": "Python", "bytes": "149887" } ], "symlink_target": "" }
@interface BankCardAddDefaultCell : BankCardAddBaseTableCell @property (nonatomic,copy) void (^valueChangedBlock)(id sender); @end
{ "content_hash": "ecffdfeb59ce1fe235fed1b0948c1b68", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 64, "avg_line_length": 22.333333333333332, "alnum_prop": 0.8059701492537313, "repo_name": "BaoSeed/TianFuYun", "id": "71699012154a84b3f14138ba45caa70e5a32fae5", "size": "322", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ios/TianJiCloud/Sections/Mine/Bankcard/BankCardAdd/View/BankCardAddDefaultCell.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3694" }, { "name": "CSS", "bytes": "75311" }, { "name": "HTML", "bytes": "310734" }, { "name": "JavaScript", "bytes": "7725" }, { "name": "Objective-C", "bytes": "4846839" }, { "name": "Ruby", "bytes": "1408" }, { "name": "Shell", "bytes": "24921" } ], "symlink_target": "" }
/* This file is generated automatically by generatejs.con. Do not edit. */ 'use strict'; if (!con.C) con.C = { }; con.C.fopen = this.__cjs_fopen; con.C.fclose = this.__cjs_fclose; con.C.fread = this.__cjs_fread; con.C.fseek = this.__cjs_fseek; con.C.ftell = this.__cjs_ftell; con.C.fsize = this.__cjs_fsize; con.C.fgetstring = this.__cjs_fgetstring; con.C.feof = this.__cjs_feof; con.C.fflush = this.__cjs_fflush; con.C.fgetc = this.__cjs_fgetc; con.C.fputc = this.__cjs_fputc; con.C.fgets = this.__cjs_fgets; con.C.fputs = this.__cjs_fputs; con.C._fileno = this.__cjs__fileno; con.C.freopen = this.__cjs_freopen; con.C.remove = this.__cjs_remove; con.C._unlink = this.__cjs__unlink; con.C._chdir = this.__cjs__chdir; con.C._mkdir = this.__cjs__mkdir; con.C._rmdir = this.__cjs__rmdir; con.C.opendir = this.__cjs_opendir; con.C.readdir = this.__cjs_readdir; con.C.telldir = this.__cjs_telldir; con.C.seekdir = this.__cjs_seekdir; con.C.rewinddir = this.__cjs_rewinddir; con.C.closedir = this.__cjs_closedir; con.C.dirname = this.__cjs_dirname; con.C._stat = this.__cjs__stat; con.C.filetype = this.__cjs_filetype; con.C.filesize = this.__cjs_filesize; con.C.filelast_acc = this.__cjs_filelast_acc; con.C.filelast_mod = this.__cjs_filelast_mod; con.C.filelast_ch = this.__cjs_filelast_ch; con.C.fileuid = this.__cjs_fileuid; con.C.filegid = this.__cjs_filegid; con.C.ReadFile = this.__cjs_ReadFile; con.C.WriteFile = this.__cjs_WriteFile; con.C.FileExists = this.__cjs_FileExists; con.C.DirectoryExists = this.__cjs_DirectoryExists; con.C._errno = this.__cjs__errno; con.C.strerror = this.__cjs_strerror; con.C.rename = this.__cjs_rename; con.C.IniGet = this.__cjs_IniGet; con.C.IniSet = this.__cjs_IniSet; con.C.popen = this.__cjs_popen; con.C.pclose = this.__cjs_pclose; con.C._WEXITSTATUS = this.__cjs__WEXITSTATUS; con.C._MSWINDOWS = this.__cjs__MSWINDOWS; con.C._BITS = this.__cjs__BITS; con.C.IsSymlink = this.__cjs_IsSymlink; con.C.utime = this.__cjs_utime; con.C.dup = this.__cjs_dup; con.C.dup2 = this.__cjs_dup2; con.C.fdopen = this.__cjs_fdopen; con.C.pipe = this.__cjs_pipe; con.C.socketpair = this.__cjs_socketpair; con.C.close = this.__cjs_close; con.C.write = this.__cjs_write; con.C.read = this.__cjs_read; con.C.seek = this.__cjs_seek; con.C.mkfifo = this.__cjs_mkfifo; con.C.remap_pipe_stdin_stdout = this.__cjs_remap_pipe_stdin_stdout; con.C.umask = this.__cjs_umask; con.C.chmod = this.__cjs_chmod; con.C.panicexit = this.__cjs_panicexit; con.C.getcwd = this.__cjs_getcwd; con.C.getpid = this.__cjs_getpid; con.C.getpgrp = this.__cjs_getpgrp; con.C.kill = this.__cjs_kill; con.C.ExecuteJoin = this.__cjs_ExecuteJoin; con.C.ExecuteProcess = this.__cjs_ExecuteProcess; con.C.ExecuteIsRunning = this.__cjs_ExecuteIsRunning; con.C.Duplicate = this.__cjs_Duplicate; con.C.setuid = this.__cjs_setuid; con.C.setgid = this.__cjs_setgid; con.C.getpwnam = this.__cjs_getpwnam; con.C.getpwuid = this.__cjs_getpwuid; con.C.setrlimit = this.__cjs_setrlimit; con.C.getrlimit = this.__cjs_getrlimit; con.C.SetCurrentUser = this.__cjs_SetCurrentUser; con.C.SetNonBlocking = this.__cjs_SetNonBlocking; con.C.DescriptorWrite = this.__cjs_DescriptorWrite; con.C.DescriptorRead = this.__cjs_DescriptorRead; con.C.getrusage = this.__cjs_getrusage; con.C.sysconf = this.__cjs_sysconf; con.C.__PID = this.__cjs___PID; con.C.__cpuid = this.__cjs___cpuid; con.C.ftruncate = this.__cjs_ftruncate; con.C.LockFileBytes = this.__cjs_LockFileBytes; con.C.__ProcessTitle = this.__cjs___ProcessTitle; con.C.mmap = this.__cjs_mmap; con.C.munmap = this.__cjs_munmap; con.C.mprotect = this.__cjs_mprotect; con.C.msync = this.__cjs_msync; con.C.mlock = this.__cjs_mlock; con.C.munlock = this.__cjs_munlock; con.C.mread = this.__cjs_mread; con.C.mwrite = this.__cjs_mwrite; con.C.fsync2 = this.__cjs_fsync2; con.C.fsync = this.__cjs_fsync; con.C.fdatasync2 = this.__cjs_fdatasync2; con.C.fdatasync = this.__cjs_fdatasync; con.C.availablespace = this.__cjs_availablespace; con.C.signal = this.__cjs_signal; con.C.alarm = this.__cjs_alarm; con.C.getchar = this.__cjs_getchar; con.C.gets = this.__cjs_gets; con.C.getpassword = this.__cjs_getpassword; con.C.chroot = this.__cjs_chroot; con.C.Impersonate = this.__cjs_Impersonate; con.C.setvbuf = this.__cjs_setvbuf;
{ "content_hash": "fa198875cb830b677f409a76243bf45c", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 74, "avg_line_length": 36.2991452991453, "alnum_prop": 0.6922533553096303, "repo_name": "Devronium/ConceptApplicationServer", "id": "e9981b6ec66a39f0d748731a1d13e40d59f0408e", "size": "4247", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/_js/standard.C.io.js", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "156546" }, { "name": "Batchfile", "bytes": "5629" }, { "name": "C", "bytes": "23814868" }, { "name": "C++", "bytes": "9045245" }, { "name": "CSS", "bytes": "689616" }, { "name": "HTML", "bytes": "27027035" }, { "name": "JavaScript", "bytes": "3907862" }, { "name": "M4", "bytes": "126426" }, { "name": "Makefile", "bytes": "6102928" }, { "name": "PHP", "bytes": "11766" }, { "name": "Roff", "bytes": "10803" }, { "name": "SCSS", "bytes": "2187" }, { "name": "Shell", "bytes": "7230107" }, { "name": "Smarty", "bytes": "83738" }, { "name": "XSLT", "bytes": "16139" } ], "symlink_target": "" }
<lint> <issue id="UnknownNullness" severity="error"/> </lint>
{ "content_hash": "a97e1f6629022c6931710c69ca712c3b", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 48, "avg_line_length": 21.333333333333332, "alnum_prop": 0.671875, "repo_name": "square/duktape-android", "id": "bd596ee7a4bd6be06d8dd7ef18e101e8e03d0778", "size": "64", "binary": false, "copies": "1", "ref": "refs/heads/adrw.2022-08-23.loadAttempt", "path": "lint.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "5840418" }, { "name": "C++", "bytes": "142542" }, { "name": "CMake", "bytes": "321" }, { "name": "Java", "bytes": "147532" }, { "name": "JavaScript", "bytes": "6306082" }, { "name": "Shell", "bytes": "4606" } ], "symlink_target": "" }
import { createLocalVue, mount, Wrapper } from '@vue/test-utils'; import Vue, { VueConstructor } from 'vue'; import { addMessages } from '../../../tests/helpers/lang'; import { renderComponent } from '../../../tests/helpers/render'; import { ICON_NAME } from '../component-names'; import { MIcon } from '../icon/icon'; import MessagePlugin, { MMessage, MMessageSkin, MMessageState } from './message'; describe('MMessage', () => { let localVue: VueConstructor<Vue>; beforeEach(() => { localVue = createLocalVue(); localVue.use(MessagePlugin); addMessages(localVue, ['components/message/message.lang.en.json']); }); it('should render correctly', () => { const msg: Wrapper<MMessage> = mount(MMessage, { localVue: localVue }); return expect(renderComponent(msg.vm)).resolves.toMatchSnapshot(); }); it('should render correctly content', () => { const msg: Wrapper<MMessage> = mount(MMessage, { localVue: localVue, slots: { default: 'message' } }); return expect(renderComponent(msg.vm)).resolves.toMatchSnapshot(); }); it('should render nothing if not visible', () => { const msg: Wrapper<MMessage> = mount(MMessage, { localVue: localVue, propsData: { visible: false } }); return expect(renderComponent(msg.vm)).resolves.toEqual(''); }); it('should render correctly light skin', () => { const msg: Wrapper<MMessage> = mount(MMessage, { localVue: localVue, propsData: { skin: MMessageSkin.Light } }); return expect(renderComponent(msg.vm)).resolves.toMatchSnapshot(); }); it('should render correctly all possible states', async () => { const btn: Wrapper<MMessage> = mount(MMessage, { localVue: localVue }); for (const state in MMessageState) { btn.setProps({ state: MMessageState[state] }); expect(await renderComponent(btn.vm)).toMatchSnapshot(state); } }); it('should render correctly when there is no icon', () => { const msg: Wrapper<MMessage> = mount(MMessage, { localVue: localVue, propsData: { icon: false } }); return expect(renderComponent(msg.vm)).resolves.toMatchSnapshot(); }); it('should render correctly close button when prop is set', () => { // For vue-test-utils bug, else m-icon is not rendered in m-button-icon Vue.component(ICON_NAME, MIcon); const msg: Wrapper<MMessage> = mount(MMessage, { localVue: localVue, propsData: { closeButton: true } }); return expect(renderComponent(msg.vm)).resolves.toMatchSnapshot(); }); it('should render nothing after close button is clicked', async () => { const msg: Wrapper<MMessage> = mount(MMessage, { localVue: localVue, propsData: { closeButton: true } }); msg.find('button').trigger('click'); return expect(renderComponent(msg.vm)).resolves.toEqual(''); }); it('should emit close event when close button is clicked', () => { const msg: Wrapper<MMessage> = mount(MMessage, { localVue: localVue, propsData: { closeButton: true } }); msg.find('button').trigger('click'); expect(msg.emitted('close')).toBeTruthy(); }); });
{ "content_hash": "03666028f4c2d0b316fec3fbc2cc6f8f", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 81, "avg_line_length": 30.633333333333333, "alnum_prop": 0.5563112078346029, "repo_name": "ulaval/modul-components", "id": "09b09f648e70bccfdd615129e25d29e771f2335a", "size": "3676", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/components/message/message.spec.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3055" }, { "name": "CSS", "bytes": "273104" }, { "name": "Groovy", "bytes": "2030" }, { "name": "HTML", "bytes": "460968" }, { "name": "JavaScript", "bytes": "21149" }, { "name": "TypeScript", "bytes": "2028431" } ], "symlink_target": "" }
package vo.goods; public class GoodsComponentVo { private String itemId; private String itemTitle; private boolean blockFlag; public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId; } public String getItemTitle() { return itemTitle; } public void setItemTitle(String itemTitle) { this.itemTitle = itemTitle; } public boolean isBlockFlag() { return blockFlag; } public void setBlockFlag(boolean blockFlag) { this.blockFlag = blockFlag; } }
{ "content_hash": "5fc4aa222a2832db00df1d2cc1010df2", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 46, "avg_line_length": 15.909090909090908, "alnum_prop": 0.7276190476190476, "repo_name": "gitminingOrg/AirDevice", "id": "0c74d06144c0d0c43b9b4adad32d50f5a9e80fa8", "size": "525", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/src/main/java/vo/goods/GoodsComponentVo.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1868830" }, { "name": "HTML", "bytes": "1341685" }, { "name": "Java", "bytes": "792078" }, { "name": "JavaScript", "bytes": "12130539" }, { "name": "SQLPL", "bytes": "1147" } ], "symlink_target": "" }
package org.mycontroller.standalone.api.jaxrs.mapper; import org.mycontroller.standalone.MycUtils; import lombok.ToString; import lombok.Getter; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import lombok.Builder; /** * @author Jeeva Kandasamy (jkandasa) * @since 0.0.3 */ @Builder @NoArgsConstructor @AllArgsConstructor @Getter @ToString(includeFieldNames = true) public class BackupFile implements Comparable<BackupFile> { private String name; private String absolutePath; private Long timestamp; private Long size; @Override public int compareTo(BackupFile file) { return this.timestamp.compareTo(file.getTimestamp()); } public String getFriendlyTime() { return MycUtils.getDifferenceFriendlyTime(timestamp); } }
{ "content_hash": "3bf1cd9e4b161d112ca88eaeaa41f921", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 61, "avg_line_length": 22.194444444444443, "alnum_prop": 0.7521902377972466, "repo_name": "Dietmar-Franken/mycontroller", "id": "413feca794b5e3642588e57812199ac965392e79", "size": "1432", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/mycontroller/standalone/api/jaxrs/mapper/BackupFile.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1062" }, { "name": "CSS", "bytes": "177768" }, { "name": "HTML", "bytes": "168573" }, { "name": "Java", "bytes": "697633" }, { "name": "JavaScript", "bytes": "272580" }, { "name": "Shell", "bytes": "2909" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Novon 12:323. 2002 #### Original name Vesicaria nuttallii Torr. & A. Gray ### Remarks null
{ "content_hash": "b058fb693869f6e560225ce1480bc66f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 13.76923076923077, "alnum_prop": 0.7039106145251397, "repo_name": "mdoering/backbone", "id": "f0f6e6017e522cc4b07895944db882a8cc5b84a0", "size": "278", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Physaria/Physaria gracilis/Physaria gracilis nuttallii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
HTTP or HTTPS requests take place through the core/net module. To request the class from within a module: `http = self.server.rget('http.url')` ## Creating a request `response = http.request(url, code="GET", params={}, body=None, headers={}, timeout=None)` | Parameter | Description | | ---- | ---- | | `url` | Resource to request from. | | `code` | Can be "POST" or "GET", if "POST" then send `params` through the POST body (assuming `body` is `None`), otherwise send `params` through the URL. | | `params` | CGI Parameters. | | `body` | POST body, will send POST if `body` is set. | | `headers` | HTTP Headers. | | `timeout` | Timeout in seconds. | ## Reading from a request | Attribute | Description | | ---- | ---- | | `Response.headers` | The headers in a dictionary. | | `Response.raw()` | Get the raw response from the server. | | `Response.read()` | The response, decoded into a string. | | `Response.json()` | The response, decoded into a string and loaded as JSON. | ## Handling Errors | Exception | Description | | ---- | ---- | | `http.Error` | Base exception. | | `http.TimeoutError` | Timeout happened. | | `http.ResolveError` | Unable to resolve hostname. | | `http.HTTPError` | HTTP Error, same as urllib.errors.HTTPError. The `code` attribute contains the error.|
{ "content_hash": "278d4de89d2b8a7e41a1ffbe825e6ae1", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 157, "avg_line_length": 34.891891891891895, "alnum_prop": 0.6615027110766848, "repo_name": "shacknetisp/vepybot", "id": "c55941234aa307354ece91bd79b721dcbf9cd61f", "size": "1299", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/requests.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "186378" } ], "symlink_target": "" }
import pjson from '../../package.json'; import updateFile from './updateFile'; export default function appVeyorResults() { return updateFile( pjson.version, 'Updating appveyor.yml version', './appveyor.yml', data => data.replace(/version: (.*)\./, `version: ${pjson.version}.`) ); }
{ "content_hash": "daad900c2d325eaeac9df44d702c05ec", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 73, "avg_line_length": 27.636363636363637, "alnum_prop": 0.6513157894736842, "repo_name": "alexmcmillan/graphql-dotnet", "id": "7cc43aa788b96a905c77160f4310f9acb5c47ee1", "size": "304", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tools/tasks/appVeyorVersion.js", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "110" }, { "name": "C#", "bytes": "766792" }, { "name": "CSS", "bytes": "29078" }, { "name": "JavaScript", "bytes": "1167" }, { "name": "PowerShell", "bytes": "836" } ], "symlink_target": "" }
package com.orientechnologies.orient.core.index; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import com.orientechnologies.orient.core.db.record.OIdentifiable; /** * Iterator that allow to iterate against multiple collection of elements. * * @author Luca Garulli (l.garulli--at--orientechnologies.com) * * @param <T> */ public class OFlattenIterator<T> implements Iterator<OIdentifiable> { private Iterator<? extends Collection<OIdentifiable>> subIterator; private Iterator<OIdentifiable> partialIterator; public OFlattenIterator(final Iterator<? extends Collection<OIdentifiable>> iterator) { subIterator = iterator; getNextPartial(); } @Override public boolean hasNext() { if (partialIterator == null) return false; if (partialIterator.hasNext()) return true; else if (subIterator.hasNext()) return getNextPartial(); return false; } @Override public OIdentifiable next() { if (!hasNext()) throw new NoSuchElementException(); return partialIterator.next(); } @Override public void remove() { throw new UnsupportedOperationException("OFlattenIterator.remove()"); } protected boolean getNextPartial() { if (subIterator != null) while (subIterator.hasNext()) { final Collection<OIdentifiable> next = subIterator.next(); if (next != null && !next.isEmpty()) { partialIterator = next.iterator(); return true; } } return false; } }
{ "content_hash": "2011b0d78c66113918aecb61be596233", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 89, "avg_line_length": 25.26153846153846, "alnum_prop": 0.6528623629719854, "repo_name": "nengxu/OrientDB", "id": "b6fde897a2cc94dc7c5ed46ac0f8ee409d11c7b4", "size": "2295", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/com/orientechnologies/orient/core/index/OFlattenIterator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "7130105" }, { "name": "JavaScript", "bytes": "464766" }, { "name": "PHP", "bytes": "9168" }, { "name": "Shell", "bytes": "16948" } ], "symlink_target": "" }
{% load uqam %} <div id="search-panel"> <form method="get" action="/search/" id="main-search"> <!-- Changed this from bottom to top --> <div class="search-conditions-statement"> By using the UQ Anthropology Museum Online Catalogue you agree to the conditions of the <a href="#copyright">Copyright Statement</a> below. </div> <fieldset> <input size="15" type="text" value="{% if form.q.value %}{{form.q.value}}{% else %}Search the collection...{%endif%}" name="q" class="s{% if form.q.value %} active{% endif %}" onfocus="if (this.value == 'Search the collection...' || this.value == ' ') {this.value = ''; $(this).addClass('active');}" onblur="if (this.value == '') {this.value = 'Search the collection...'; $(this).removeClass('active')}" tabindex="1" id="main-search-q" /> <button class="submit btn" title="Search" type="submit" id="top-search-submit">Search</button> </fieldset> <!-- #### CHANGED THIS FOR DROPDOWN BUTTONS #####--> <div class="browse-by-link"> <p class="search-options-divider">or</p> <div class="btn-group" id="browseMenu"> <button class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"></span>Browse by </button> <ul class="dropdown-menu"> <li><a href="{% url categories_list %}">Categories</a></li> <li><a href="{% url parties_browse %}">People</a></li> <li><a href="{% url view_places %}">Places</a></li> </ul> </div> </div> {% advanced_search_fields form expanded=expanded %} {# uses /snippets/advanced_search_fields #} </form> </div>
{ "content_hash": "0824c3e3cb158bbc5eec61055a35afa5", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 446, "avg_line_length": 48.11764705882353, "alnum_prop": 0.5971882640586798, "repo_name": "uq-eresearch/uqam", "id": "a92dc3434de05201f210bf1dda61a67dcde11153", "size": "1636", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "templates/snippets/top_search_panel.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "117676" }, { "name": "HTML", "bytes": "108660" }, { "name": "JavaScript", "bytes": "977528" }, { "name": "Python", "bytes": "1297328" }, { "name": "Shell", "bytes": "24566" } ], "symlink_target": "" }
import weakref class CachedSpamManager: def __init__(self): self._cache = weakref.WeakValueDictionary() def get_spam(self, name): if name not in self._cache: s = Spam(name) self._cache[name] = s else: s = self._cache[name] return s class Spam: def __init__(self, name): self.name = name Spam.manager = CachedSpamManager() def get_spam(name): return Spam.manager.get_spam(name) if __name__ == '__main__': a = get_spam('foo') b = get_spam('bar') print('a is b:', a is b) c = get_spam('foo') print('a is c:', a is c)
{ "content_hash": "33ffe9767993f5040bf694179f7a622b", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 51, "avg_line_length": 22.75, "alnum_prop": 0.5368916797488226, "repo_name": "tuanavu/python-cookbook-3rd", "id": "8401dcce29416909b50d04c4437c4a147542b71d", "size": "637", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/8/creating_cached_instances/example2.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "20265" }, { "name": "CSS", "bytes": "184" }, { "name": "Jupyter Notebook", "bytes": "219413" }, { "name": "Makefile", "bytes": "231" }, { "name": "Python", "bytes": "250592" }, { "name": "Shell", "bytes": "179" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "8b7ef2487d5f42dd144496c0e39d4a1d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "867ff66882765e53f75108e7d69e2a964975252a", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Eriocaulaceae/Eriocaulon/Eriocaulon atratum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package de.uop.code.cubemerging.domain; import java.util.LinkedList; import java.util.List; public class MergedDSD { private String g1; private String g2; private List<MatchingComponent> matchingDimensions = new LinkedList<MatchingComponent>(); private List<Component> dimensions1 = new LinkedList<Component>(); private List<Component> dimensions2 = new LinkedList<Component>(); private List<MatchingComponent> matchingMeasures = new LinkedList<MatchingComponent>(); private List<Component> measures1 = new LinkedList<Component>(); private List<Component> measures2 = new LinkedList<Component>(); public String getG1() { return g1; } public void setG1(String g1) { this.g1 = g1; } public String getG2() { return g2; } public void setG2(String g2) { this.g2 = g2; } public List<MatchingComponent> getMatchingDimensions() { return matchingDimensions; } public void setMatchingDimensions(List<MatchingComponent> matchingDimensions) { this.matchingDimensions = matchingDimensions; } public List<Component> getDimensions1() { return dimensions1; } public void setDimensions1(List<Component> dimensions1) { this.dimensions1 = dimensions1; } public List<Component> getDimensions2() { return dimensions2; } public void setDimensions2(List<Component> dimensions2) { this.dimensions2 = dimensions2; } public List<MatchingComponent> getMatchingMeasures() { return matchingMeasures; } public void setMatchingMeasures(List<MatchingComponent> matchingMeasures) { this.matchingMeasures = matchingMeasures; } public List<Component> getMeasures1() { return measures1; } public void setMeasures1(List<Component> measures1) { this.measures1 = measures1; } public List<Component> getMeasures2() { return measures2; } public void setMeasures2(List<Component> measures2) { this.measures2 = measures2; } }
{ "content_hash": "0a5b885232441736525a322bbfd453a4", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 93, "avg_line_length": 25.51219512195122, "alnum_prop": 0.6782982791586998, "repo_name": "bayerls/bacon", "id": "f0f6c669d6019fa107e7d46f9883a35b81a1959f", "size": "2092", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/de/uop/code/cubemerging/domain/MergedDSD.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1101" }, { "name": "Java", "bytes": "107560" }, { "name": "JavaScript", "bytes": "4959" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Ukr. bot. Zh. 60(1): 68 (2003) #### Original name Caloplaca vorukhica S.Y. Kondr. & Kudratov ### Remarks null
{ "content_hash": "89f6eddbb040ff0875a8223fc7007d48", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 42, "avg_line_length": 13.307692307692308, "alnum_prop": 0.6705202312138728, "repo_name": "mdoering/backbone", "id": "e1a18aa97afbf2bb6ec2a6a737ed46a56afa8450", "size": "239", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Teloschistales/Teloschistaceae/Caloplaca/Caloplaca vorukhica/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.apache.cloudstack.engine.cloud.entity.api.db.dao; import java.util.List; import org.apache.cloudstack.engine.cloud.entity.api.db.VolumeReservationVO; import com.cloud.utils.db.GenericDao; public interface VolumeReservationDao extends GenericDao<VolumeReservationVO, Long>{ VolumeReservationVO findByVmId(long vmId); List<VolumeReservationVO> listVolumeReservation(long vmReservationId); }
{ "content_hash": "ceeb2fe675797bd72929fc4d90a6fbdc", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 84, "avg_line_length": 27.6, "alnum_prop": 0.8236714975845411, "repo_name": "mufaddalq/cloudstack-datera-driver", "id": "fd709b0db0a29cd78e4c69c8d20fee507718d448", "size": "1215", "binary": false, "copies": "1", "ref": "refs/heads/4.2", "path": "engine/schema/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VolumeReservationDao.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "250" }, { "name": "Batchfile", "bytes": "6317" }, { "name": "CSS", "bytes": "302008" }, { "name": "FreeMarker", "bytes": "4917" }, { "name": "HTML", "bytes": "38671" }, { "name": "Java", "bytes": "79758943" }, { "name": "JavaScript", "bytes": "4237188" }, { "name": "Perl", "bytes": "1879" }, { "name": "Python", "bytes": "5187499" }, { "name": "Shell", "bytes": "803262" } ], "symlink_target": "" }
package com.alsash.reciper.mvp.model.entity; /** * A Measure model (Food-measure) */ public interface Measure extends BaseEntity { String getUnitOne(); String getUnitOther(); double getWeight(); String getWeightUnit(); }
{ "content_hash": "e4b79f24b77cd62c9c06bce48e6975a5", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 45, "avg_line_length": 16.266666666666666, "alnum_prop": 0.6885245901639344, "repo_name": "alsash/reciper", "id": "8f29b8b38d07b7ccccda1cf0c4cbf63573331e39", "size": "244", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/alsash/reciper/mvp/model/entity/Measure.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "614844" } ], "symlink_target": "" }
{-# LANGUAGE OverloadedStrings #-} module Examples.Example1(example1) where import Development.NSIS -- Based on example1.nsi from NSIS -- -- This script is perhaps one of the simplest NSIs you can make. All of the -- optional settings are left to their default settings. The installer simply -- prompts the user asking them where to install, and drops a copy of example1.hs -- there. example1 = do -- The name of the installer name "Example1" -- The file to write outFile "example1.exe" -- The default installation directory installDir "$DESKTOP/Example1" -- Request application privileges for Windows Vista requestExecutionLevel User --------------------------------- -- Pages page Directory page InstFiles --------------------------------- -- The stuff to install section "" [] $ do -- No components page, name is not important -- Set output path to the installation directory. setOutPath "$INSTDIR" -- Put file there file [] "test/Examples/Example1.hs"
{ "content_hash": "eabe80aa47328707fed611add9515e08", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 81, "avg_line_length": 24.15909090909091, "alnum_prop": 0.638758231420508, "repo_name": "ndmitchell/nsis", "id": "d820911d5f17c426dd064b18c89048afa364d698", "size": "1063", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/Examples/Example1.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Haskell", "bytes": "109271" } ], "symlink_target": "" }
Describe "Environment-Variables" -Tags "CI" { It "Should have environment variables" { Get-Item ENV: | Should -Not -BeNullOrEmpty } It "Should have a nonempty PATH" { $ENV:PATH | Should -Not -BeNullOrEmpty } It "Should contain /bin in the PATH" { if ($IsWindows) { $ENV:PATH | Should -Match "C:" } else { $ENV:PATH | Should -Match "/bin" } } It "Should have the correct HOME" { if ($IsWindows) { # \Windows\System32 is found as $env:HOMEPATH for temporary profiles $expected = "\Users", "\Windows" Split-Path $ENV:HOMEPATH -Parent | Should -BeIn $expected } else { $expected = /bin/bash -c "cd ~ && pwd" $ENV:HOME | Should -Be $expected } } It "Should be able to set the environment variables" { $expected = "this is a test environment variable" { $ENV:TESTENVIRONMENTVARIABLE = $expected } | Should -Not -Throw $ENV:TESTENVIRONMENTVARIABLE | Should -Not -BeNullOrEmpty $ENV:TESTENVIRONMENTVARIABLE | Should -Be $expected } Context "~ in PATH" { AfterEach { $env:PATH = $oldPath } BeforeAll { $oldPath = $env:PATH $pwsh = (Get-Command pwsh | Select-Object -First 1).Source if ($IsWindows) { $pwsh2 = "pwsh2.exe" } else { $pwsh2 = "pwsh2" } Copy-Item -Path $pwsh -Destination "~/$pwsh2" $testPath = Join-Path -Path "~" -ChildPath (New-Guid) New-Item -Path $testPath -ItemType Directory > $null Copy-Item -Path $pwsh -Destination "$testPath/$pwsh2" } AfterAll { Remove-Item -Path "~/pwsh2" -Force Remove-Item -Path $testPath -Recurse -Force } It "Should be able to resolve ~ in PATH" { $env:PATH = "~" + [System.IO.Path]::PathSeparator + $env:PATH $out = Get-Command pwsh2 $out.Source | Should -BeExactly (Join-Path -Path ([System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::UserProfile)) -ChildPath $pwsh2) } It "Should be able to resolve ~/folder in PATH" { $env:PATH = $testPath + [System.IO.Path]::PathSeparator + $env:PATH $out = Get-Command pwsh2 $out.Source | Should -BeExactly (Join-Path -Path (Resolve-Path $testPath) -ChildPath $pwsh2) } } }
{ "content_hash": "8a3f356643f1327ad0d7f27a49fea980", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 166, "avg_line_length": 33.4078947368421, "alnum_prop": 0.5454903505317054, "repo_name": "JamesWTruher/PowerShell-1", "id": "4c2b839259bdb6a12ecc0e2963fd53ba9751e28b", "size": "2612", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "test/powershell/Modules/Microsoft.PowerShell.Utility/Environment-Variables.Tests.ps1", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "24" }, { "name": "C#", "bytes": "30851582" }, { "name": "Dockerfile", "bytes": "6482" }, { "name": "HTML", "bytes": "18060" }, { "name": "JavaScript", "bytes": "8738" }, { "name": "PowerShell", "bytes": "5083167" }, { "name": "Rich Text Format", "bytes": "40664" }, { "name": "Roff", "bytes": "214984" }, { "name": "Shell", "bytes": "57893" }, { "name": "XSLT", "bytes": "14394" } ], "symlink_target": "" }
 #pragma once #include <aws/fsx/FSx_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/fsx/model/ReportFormat.h> #include <aws/fsx/model/ReportScope.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace FSx { namespace Model { /** * <p>Provides a report detailing the data repository task results of the files * processed that match the criteria specified in the report <code>Scope</code> * parameter. FSx delivers the report to the file system's linked data repository * in Amazon S3, using the path specified in the report <code>Path</code> * parameter. You can specify whether or not a report gets generated for a task * using the <code>Enabled</code> parameter.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/fsx-2018-03-01/CompletionReport">AWS * API Reference</a></p> */ class AWS_FSX_API CompletionReport { public: CompletionReport(); CompletionReport(Aws::Utils::Json::JsonView jsonValue); CompletionReport& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>Set <code>Enabled</code> to <code>True</code> to generate a * <code>CompletionReport</code> when the task completes. If set to * <code>true</code>, then you need to provide a report <code>Scope</code>, * <code>Path</code>, and <code>Format</code>. Set <code>Enabled</code> to * <code>False</code> if you do not want a <code>CompletionReport</code> generated * when the task completes.</p> */ inline bool GetEnabled() const{ return m_enabled; } /** * <p>Set <code>Enabled</code> to <code>True</code> to generate a * <code>CompletionReport</code> when the task completes. If set to * <code>true</code>, then you need to provide a report <code>Scope</code>, * <code>Path</code>, and <code>Format</code>. Set <code>Enabled</code> to * <code>False</code> if you do not want a <code>CompletionReport</code> generated * when the task completes.</p> */ inline bool EnabledHasBeenSet() const { return m_enabledHasBeenSet; } /** * <p>Set <code>Enabled</code> to <code>True</code> to generate a * <code>CompletionReport</code> when the task completes. If set to * <code>true</code>, then you need to provide a report <code>Scope</code>, * <code>Path</code>, and <code>Format</code>. Set <code>Enabled</code> to * <code>False</code> if you do not want a <code>CompletionReport</code> generated * when the task completes.</p> */ inline void SetEnabled(bool value) { m_enabledHasBeenSet = true; m_enabled = value; } /** * <p>Set <code>Enabled</code> to <code>True</code> to generate a * <code>CompletionReport</code> when the task completes. If set to * <code>true</code>, then you need to provide a report <code>Scope</code>, * <code>Path</code>, and <code>Format</code>. Set <code>Enabled</code> to * <code>False</code> if you do not want a <code>CompletionReport</code> generated * when the task completes.</p> */ inline CompletionReport& WithEnabled(bool value) { SetEnabled(value); return *this;} /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * location of the report on the file system's linked S3 data repository. An * absolute path that defines where the completion report will be stored in the * destination location. The <code>Path</code> you provide must be located within * the file system’s ExportPath. An example <code>Path</code> value is * "s3://myBucket/myExportPath/optionalPrefix". The report provides the following * information for each file in the report: FilePath, FileStatus, and ErrorCode. To * learn more about a file system's <code>ExportPath</code>, see . </p> */ inline const Aws::String& GetPath() const{ return m_path; } /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * location of the report on the file system's linked S3 data repository. An * absolute path that defines where the completion report will be stored in the * destination location. The <code>Path</code> you provide must be located within * the file system’s ExportPath. An example <code>Path</code> value is * "s3://myBucket/myExportPath/optionalPrefix". The report provides the following * information for each file in the report: FilePath, FileStatus, and ErrorCode. To * learn more about a file system's <code>ExportPath</code>, see . </p> */ inline bool PathHasBeenSet() const { return m_pathHasBeenSet; } /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * location of the report on the file system's linked S3 data repository. An * absolute path that defines where the completion report will be stored in the * destination location. The <code>Path</code> you provide must be located within * the file system’s ExportPath. An example <code>Path</code> value is * "s3://myBucket/myExportPath/optionalPrefix". The report provides the following * information for each file in the report: FilePath, FileStatus, and ErrorCode. To * learn more about a file system's <code>ExportPath</code>, see . </p> */ inline void SetPath(const Aws::String& value) { m_pathHasBeenSet = true; m_path = value; } /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * location of the report on the file system's linked S3 data repository. An * absolute path that defines where the completion report will be stored in the * destination location. The <code>Path</code> you provide must be located within * the file system’s ExportPath. An example <code>Path</code> value is * "s3://myBucket/myExportPath/optionalPrefix". The report provides the following * information for each file in the report: FilePath, FileStatus, and ErrorCode. To * learn more about a file system's <code>ExportPath</code>, see . </p> */ inline void SetPath(Aws::String&& value) { m_pathHasBeenSet = true; m_path = std::move(value); } /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * location of the report on the file system's linked S3 data repository. An * absolute path that defines where the completion report will be stored in the * destination location. The <code>Path</code> you provide must be located within * the file system’s ExportPath. An example <code>Path</code> value is * "s3://myBucket/myExportPath/optionalPrefix". The report provides the following * information for each file in the report: FilePath, FileStatus, and ErrorCode. To * learn more about a file system's <code>ExportPath</code>, see . </p> */ inline void SetPath(const char* value) { m_pathHasBeenSet = true; m_path.assign(value); } /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * location of the report on the file system's linked S3 data repository. An * absolute path that defines where the completion report will be stored in the * destination location. The <code>Path</code> you provide must be located within * the file system’s ExportPath. An example <code>Path</code> value is * "s3://myBucket/myExportPath/optionalPrefix". The report provides the following * information for each file in the report: FilePath, FileStatus, and ErrorCode. To * learn more about a file system's <code>ExportPath</code>, see . </p> */ inline CompletionReport& WithPath(const Aws::String& value) { SetPath(value); return *this;} /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * location of the report on the file system's linked S3 data repository. An * absolute path that defines where the completion report will be stored in the * destination location. The <code>Path</code> you provide must be located within * the file system’s ExportPath. An example <code>Path</code> value is * "s3://myBucket/myExportPath/optionalPrefix". The report provides the following * information for each file in the report: FilePath, FileStatus, and ErrorCode. To * learn more about a file system's <code>ExportPath</code>, see . </p> */ inline CompletionReport& WithPath(Aws::String&& value) { SetPath(std::move(value)); return *this;} /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * location of the report on the file system's linked S3 data repository. An * absolute path that defines where the completion report will be stored in the * destination location. The <code>Path</code> you provide must be located within * the file system’s ExportPath. An example <code>Path</code> value is * "s3://myBucket/myExportPath/optionalPrefix". The report provides the following * information for each file in the report: FilePath, FileStatus, and ErrorCode. To * learn more about a file system's <code>ExportPath</code>, see . </p> */ inline CompletionReport& WithPath(const char* value) { SetPath(value); return *this;} /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * format of the <code>CompletionReport</code>. <code>REPORT_CSV_20191124</code> is * the only format currently supported. When <code>Format</code> is set to * <code>REPORT_CSV_20191124</code>, the <code>CompletionReport</code> is provided * in CSV format, and is delivered to <code>{path}/task-{id}/failures.csv</code>. * </p> */ inline const ReportFormat& GetFormat() const{ return m_format; } /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * format of the <code>CompletionReport</code>. <code>REPORT_CSV_20191124</code> is * the only format currently supported. When <code>Format</code> is set to * <code>REPORT_CSV_20191124</code>, the <code>CompletionReport</code> is provided * in CSV format, and is delivered to <code>{path}/task-{id}/failures.csv</code>. * </p> */ inline bool FormatHasBeenSet() const { return m_formatHasBeenSet; } /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * format of the <code>CompletionReport</code>. <code>REPORT_CSV_20191124</code> is * the only format currently supported. When <code>Format</code> is set to * <code>REPORT_CSV_20191124</code>, the <code>CompletionReport</code> is provided * in CSV format, and is delivered to <code>{path}/task-{id}/failures.csv</code>. * </p> */ inline void SetFormat(const ReportFormat& value) { m_formatHasBeenSet = true; m_format = value; } /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * format of the <code>CompletionReport</code>. <code>REPORT_CSV_20191124</code> is * the only format currently supported. When <code>Format</code> is set to * <code>REPORT_CSV_20191124</code>, the <code>CompletionReport</code> is provided * in CSV format, and is delivered to <code>{path}/task-{id}/failures.csv</code>. * </p> */ inline void SetFormat(ReportFormat&& value) { m_formatHasBeenSet = true; m_format = std::move(value); } /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * format of the <code>CompletionReport</code>. <code>REPORT_CSV_20191124</code> is * the only format currently supported. When <code>Format</code> is set to * <code>REPORT_CSV_20191124</code>, the <code>CompletionReport</code> is provided * in CSV format, and is delivered to <code>{path}/task-{id}/failures.csv</code>. * </p> */ inline CompletionReport& WithFormat(const ReportFormat& value) { SetFormat(value); return *this;} /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * format of the <code>CompletionReport</code>. <code>REPORT_CSV_20191124</code> is * the only format currently supported. When <code>Format</code> is set to * <code>REPORT_CSV_20191124</code>, the <code>CompletionReport</code> is provided * in CSV format, and is delivered to <code>{path}/task-{id}/failures.csv</code>. * </p> */ inline CompletionReport& WithFormat(ReportFormat&& value) { SetFormat(std::move(value)); return *this;} /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * scope of the <code>CompletionReport</code>; <code>FAILED_FILES_ONLY</code> is * the only scope currently supported. When <code>Scope</code> is set to * <code>FAILED_FILES_ONLY</code>, the <code>CompletionReport</code> only contains * information about files that the data repository task failed to process.</p> */ inline const ReportScope& GetScope() const{ return m_scope; } /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * scope of the <code>CompletionReport</code>; <code>FAILED_FILES_ONLY</code> is * the only scope currently supported. When <code>Scope</code> is set to * <code>FAILED_FILES_ONLY</code>, the <code>CompletionReport</code> only contains * information about files that the data repository task failed to process.</p> */ inline bool ScopeHasBeenSet() const { return m_scopeHasBeenSet; } /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * scope of the <code>CompletionReport</code>; <code>FAILED_FILES_ONLY</code> is * the only scope currently supported. When <code>Scope</code> is set to * <code>FAILED_FILES_ONLY</code>, the <code>CompletionReport</code> only contains * information about files that the data repository task failed to process.</p> */ inline void SetScope(const ReportScope& value) { m_scopeHasBeenSet = true; m_scope = value; } /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * scope of the <code>CompletionReport</code>; <code>FAILED_FILES_ONLY</code> is * the only scope currently supported. When <code>Scope</code> is set to * <code>FAILED_FILES_ONLY</code>, the <code>CompletionReport</code> only contains * information about files that the data repository task failed to process.</p> */ inline void SetScope(ReportScope&& value) { m_scopeHasBeenSet = true; m_scope = std::move(value); } /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * scope of the <code>CompletionReport</code>; <code>FAILED_FILES_ONLY</code> is * the only scope currently supported. When <code>Scope</code> is set to * <code>FAILED_FILES_ONLY</code>, the <code>CompletionReport</code> only contains * information about files that the data repository task failed to process.</p> */ inline CompletionReport& WithScope(const ReportScope& value) { SetScope(value); return *this;} /** * <p>Required if <code>Enabled</code> is set to <code>true</code>. Specifies the * scope of the <code>CompletionReport</code>; <code>FAILED_FILES_ONLY</code> is * the only scope currently supported. When <code>Scope</code> is set to * <code>FAILED_FILES_ONLY</code>, the <code>CompletionReport</code> only contains * information about files that the data repository task failed to process.</p> */ inline CompletionReport& WithScope(ReportScope&& value) { SetScope(std::move(value)); return *this;} private: bool m_enabled; bool m_enabledHasBeenSet; Aws::String m_path; bool m_pathHasBeenSet; ReportFormat m_format; bool m_formatHasBeenSet; ReportScope m_scope; bool m_scopeHasBeenSet; }; } // namespace Model } // namespace FSx } // namespace Aws
{ "content_hash": "c470fe44ed776f1d42873c69a5a2b69c", "timestamp": "", "source": "github", "line_count": 314, "max_line_length": 107, "avg_line_length": 51.547770700636946, "alnum_prop": 0.6810824169034968, "repo_name": "jt70471/aws-sdk-cpp", "id": "3e776e6a2c250244637b5fa7ed0770a4a19899e3", "size": "16321", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "aws-cpp-sdk-fsx/include/aws/fsx/model/CompletionReport.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "13452" }, { "name": "C++", "bytes": "278594037" }, { "name": "CMake", "bytes": "653931" }, { "name": "Dockerfile", "bytes": "5555" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "302182" }, { "name": "Python", "bytes": "110380" }, { "name": "Shell", "bytes": "4674" } ], "symlink_target": "" }
cask 'font-monoid-loose-0-1-nocalt' do version :latest sha256 :no_check # github.com/larsenwork/monoid was verified as official when first introduced to the cask url 'https://github.com/larsenwork/monoid/blob/release/Monoid-Loose-0-1-NoCalt.zip?raw=true' name 'Monoid-Loose-0-1-NoCalt' homepage 'http://larsenwork.com/monoid/' font 'Monoid-Bold-Loose-0-1-NoCalt.ttf' font 'Monoid-Italic-Loose-0-1-NoCalt.ttf' font 'Monoid-Regular-Loose-0-1-NoCalt.ttf' font 'Monoid-Retina-Loose-0-1-NoCalt.ttf' caveats <<~EOS #{token} is dual licensed with MIT and OFL licenses. https://github.com/larsenwork/monoid/tree/master#license EOS end
{ "content_hash": "2366233ee76c1e7b7a78f50c5ba6a714", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 94, "avg_line_length": 34.8421052631579, "alnum_prop": 0.7341389728096677, "repo_name": "sscotth/homebrew-monoid", "id": "5553a0b6594a0bf4cda4e46f5a01591764b56242", "size": "662", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Casks/font-monoid-loose-0-1-nocalt.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2611" }, { "name": "Ruby", "bytes": "461065" } ], "symlink_target": "" }
var cooking = require('cooking'); var path = require('path'); var config = require('../../build/config'); cooking.set({ entry: { index: path.join(__dirname, 'index.js') }, dist: path.join(__dirname, 'lib'), template: false, format: 'umd', moduleName: 'MintBoxGroup', extractCSS: 'style.css', extends: config.extends, alias: config.alias, externals: config.externals }); module.exports = cooking.resolve();
{ "content_hash": "3cc2adc3ee369ef8a246eb49feed0248", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 43, "avg_line_length": 22.736842105263158, "alnum_prop": 0.6527777777777778, "repo_name": "wisedu/bh-mint-ui2", "id": "e9728a6eeb95e72950a6ee4ac85f1c407da99c03", "size": "432", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/box-group/cooking.conf.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "26251" }, { "name": "JavaScript", "bytes": "140923" }, { "name": "Less", "bytes": "12145" }, { "name": "Makefile", "bytes": "763" }, { "name": "Shell", "bytes": "483" }, { "name": "Smarty", "bytes": "998" }, { "name": "Vue", "bytes": "562002" } ], "symlink_target": "" }
@interface PodsDummy_Pods_SwiftyDictionary_Tests : NSObject @end @implementation PodsDummy_Pods_SwiftyDictionary_Tests @end
{ "content_hash": "c88fb78e6270404a7dd56153338cea26", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 59, "avg_line_length": 31, "alnum_prop": 0.8467741935483871, "repo_name": "justinvyu/SwiftyDictionary", "id": "90b935a14b47067d6b017c0a3bbf60e86369403a", "size": "158", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Example/Pods/Target Support Files/Pods-SwiftyDictionary_Tests/Pods-SwiftyDictionary_Tests-dummy.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "1474" }, { "name": "Ruby", "bytes": "1234" }, { "name": "Shell", "bytes": "16960" }, { "name": "Swift", "bytes": "207488" } ], "symlink_target": "" }
FROM amazonlinux:2017.03 ARG uid=1000 RUN \ yum clean all \ && yum upgrade -y \ && yum groupinstall -y "Development Tools" \ && yum install -y epel-release \ && yum-config-manager --enable epel \ && yum install -y \ wget \ cmake \ pkgconfig \ openssl-devel \ sqlite-devel \ libsodium-devel \ spectool # install nodejs and npm RUN curl --silent --location https://rpm.nodesource.com/setup_8.x | bash - RUN yum -y install nodejs RUN cd /tmp && \ curl https://download.libsodium.org/libsodium/releases/old/libsodium-1.0.14.tar.gz | tar -xz && \ cd /tmp/libsodium-1.0.14 && \ ./configure && \ make && \ make install && \ rm -rf /tmp/libsodium-1.0.14 ENV PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig ENV LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib RUN yum install -y java-1.8.0-openjdk-devel ENV JAVA_HOME /usr/lib/jvm/java-1.8.0-openjdk RUN wget https://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo RUN sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo RUN yum install -y apache-maven ENV RUST_ARCHIVE=rust-1.32.0-x86_64-unknown-linux-gnu.tar.gz ENV RUST_DOWNLOAD_URL=https://static.rust-lang.org/dist/$RUST_ARCHIVE RUN mkdir -p /rust WORKDIR /rust RUN curl -fsOSL $RUST_DOWNLOAD_URL \ && curl -s $RUST_DOWNLOAD_URL.sha256 | sha256sum -c - \ && tar -C /rust -xzf $RUST_ARCHIVE --strip-components=1 \ && rm $RUST_ARCHIVE \ && ./install.sh ENV PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/.cargo/bin" RUN cd /usr/src && \ wget https://www.python.org/ftp/python/3.5.2/Python-3.5.2.tgz && \ tar xzf Python-3.5.2.tgz && \ cd Python-3.5.2 && \ ./configure && \ make altinstall RUN yum install -y ncurses-devel RUN cd /tmp && \ wget https://github.com/zeromq/libzmq/releases/download/v4.2.2/zeromq-4.2.2.tar.gz && \ tar xfz zeromq-4.2.2.tar.gz && rm zeromq-4.2.2.tar.gz && \ cd /tmp/zeromq-4.2.2 && \ ./configure && \ make && \ make install && \ rm -rf /tmp/zeromq-4.2.2 RUN useradd -ms /bin/bash -u $uid indy USER indy WORKDIR /home/indy
{ "content_hash": "083047b261beeaf41048b5651997e62e", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 130, "avg_line_length": 29.376623376623378, "alnum_prop": 0.6352785145888594, "repo_name": "anastasia-tarasova/indy-sdk", "id": "72c64645741151ab9252a304f102ca6932ec3607", "size": "2262", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "libindy/ci/amazon.dockerfile", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "207870" }, { "name": "C#", "bytes": "842011" }, { "name": "C++", "bytes": "229233" }, { "name": "CSS", "bytes": "137079" }, { "name": "Dockerfile", "bytes": "23945" }, { "name": "Groovy", "bytes": "102863" }, { "name": "HTML", "bytes": "897750" }, { "name": "Java", "bytes": "882162" }, { "name": "JavaScript", "bytes": "185247" }, { "name": "Makefile", "bytes": "328" }, { "name": "Objective-C", "bytes": "584121" }, { "name": "Objective-C++", "bytes": "706749" }, { "name": "Perl", "bytes": "8271" }, { "name": "Python", "bytes": "750776" }, { "name": "Ruby", "bytes": "80525" }, { "name": "Rust", "bytes": "5872898" }, { "name": "Shell", "bytes": "251160" }, { "name": "Swift", "bytes": "1114" }, { "name": "TypeScript", "bytes": "197439" } ], "symlink_target": "" }
using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; namespace Ammy.VisualStudio.Service.Intellisense { public class MixinParameter : IParameter { public MixinParameter(string documentation, Span locus, string name, ISignature signature) { Documentation = documentation; Locus = locus; Name = name; Signature = signature; } public ISignature Signature { get; } public string Name { get; } public string Documentation { get; } public Span Locus { get; } public Span PrettyPrintedLocus { get; } } }
{ "content_hash": "a77cd1e34df8a8dac24fde75899f90ce", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 98, "avg_line_length": 30.818181818181817, "alnum_prop": 0.616519174041298, "repo_name": "AmmyUI/AmmyUI", "id": "28b86e1909756b02fcef4f8663c4efa82c45eafb", "size": "680", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/IDE/Ammy.VisualStudio.Service/Intellisense/MixinParameter.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "15503" }, { "name": "C#", "bytes": "615941" }, { "name": "CSS", "bytes": "1997" }, { "name": "HTML", "bytes": "649678" }, { "name": "Nemerle", "bytes": "304128" }, { "name": "PowerShell", "bytes": "5904" }, { "name": "Smalltalk", "bytes": "10" } ], "symlink_target": "" }
using System.Threading.Tasks; using Firestorm.Client; using Xunit; namespace Firestorm.Client.Tests { public class RestClientScalarTests { private const string BASE_PATH = "scalar/here/siiiick/"; private const string FULL_BASE_URL = MockHttpClientCreator.BaseUrl + BASE_PATH; private readonly MockHttpClientCreator _clientCreator; private readonly RestClientScalar _scalar; public RestClientScalarTests() { _clientCreator = new MockHttpClientCreator(); _scalar = new RestClientScalar(_clientCreator, BASE_PATH); } [Fact] public async Task GetScalar_HasSameUri() { await _scalar.GetAsync(); Assert.Equal(_clientCreator.LastRequest.RequestUri.ToString(), FULL_BASE_URL); } [Fact] public async Task GetScalar_HasSameValue() { string str = "this is a string"; _clientCreator.ResponseBody = @"""" + str + @""""; object value = await _scalar.GetAsync(); Assert.Equal(str, value); } [Fact] public async Task EditScalar_HasSameValue() { string str = "new string"; await _scalar.EditAsync(str); Assert.Equal(@"""" + str + @"""", _clientCreator.LastRequestBody); } } }
{ "content_hash": "e38c26744e2cb80a4c58a9e9e1ab2957", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 90, "avg_line_length": 28.285714285714285, "alnum_prop": 0.5800865800865801, "repo_name": "connellw/Firestorm", "id": "b94ac03713968a3b5515490e6c4171600aabda35", "size": "1388", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Firestorm.Client.Tests/RestClientScalarTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "994432" }, { "name": "PowerShell", "bytes": "3080" } ], "symlink_target": "" }
/* 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.camunda.bpm.engine.rest.impl; import javax.ws.rs.core.Response.Status; import org.camunda.bpm.engine.ProcessEngine; import org.camunda.bpm.engine.rest.exception.InvalidRequestException; import org.camunda.bpm.engine.rest.spi.impl.AbstractProcessEngineAware; public abstract class AbstractRestProcessEngineAware extends AbstractProcessEngineAware { protected String relativeRootResourcePath = "/"; public AbstractRestProcessEngineAware() { super(); } public AbstractRestProcessEngineAware(String engineName) { super(engineName); } protected ProcessEngine getProcessEngine() { if (processEngine == null) { throw new InvalidRequestException(Status.BAD_REQUEST, "No process engine available"); } return processEngine; } /** * Override the root resource path, if this resource is a sub-resource. * The relative root resource path is used for generation of links to resources in results. * * @param relativeRootResourcePath */ public void setRelativeRootResourceUri(String relativeRootResourcePath) { this.relativeRootResourcePath = relativeRootResourcePath; } }
{ "content_hash": "e82f69a91062e28cf6833b23db0e0103", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 93, "avg_line_length": 34.734693877551024, "alnum_prop": 0.7608695652173914, "repo_name": "tkaefer/camunda-bpm-platform", "id": "c2b10bb51d7eabac15a79261f4174f523e4b1e66", "size": "1702", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/AbstractRestProcessEngineAware.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
describe VisitedQueue do before(:all) do @queue=VisitedQueue.new end it "push link" do @queue.push("http://www.baidu.com") expect(@queue.has_key?("http://www.baidu.com")).to be true end it "test if include link?" do expect(@queue.include?("http://www.baidu.com")).to be true expect(@queue.include?("http://g.com")).to be false end end #test uri filter describe Filter do before(:all) do @filter=Filter.new @filter.add("http://www.baidu.com",["/s","/ulize","a/b/c"]) @filter.add("http://www.ivy.com",["ivy","ui/iu"]) end it "test host format and path format" do expect{@filter.add("www.baidu.com")}.to raise_error(HostFormatError) end it "test if allow nil" do expect(@filter.allow?(nil)).to be false end it "test if allow other host" do expect(@filter.allow?("http://www.google.com")).to be false expect(@filter.allow?("http://www.baidu.com")).to be true end it "test path allow" do expect(@filter.allow?("http://www.baidu.com/")).to be true expect(@filter.allow?("http://www.baidu.com/s")).to be true expect(@filter.allow?("http://www.baidu.com/s/uy")).to be true expect(@filter.allow?("http://www.baidu.com/sjk")).to be false expect(@filter.allow?("http://www.baidu.com/ulize")).to be true expect(@filter.allow?("http://www.baidu.com/a")).to be false expect(@filter.allow?("http://www.baidu.com/a/b/c")).to be true end it "test multi allow" do expect(@filter.allow?("http://www.ivy.com")).to be true expect(@filter.allow?("http://www.ivy.com/ivy")).to be true expect(@filter.allow?("http://www.ivy.com/ivyd")).to be false expect(@filter.allow?("http://www.ivy.com/ui/iu")).to be true end end
{ "content_hash": "b64a73d188b5b0789138b86e9892faef", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 70, "avg_line_length": 30.87037037037037, "alnum_prop": 0.6658668266346731, "repo_name": "carney520/crawler", "id": "5bf2cfd42af47560c5eb36e263143b7384c63f9f", "size": "1703", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/crawler_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "53286" }, { "name": "Shell", "bytes": "115" } ], "symlink_target": "" }
require_relative '../test_helper' require_relative '../../lib/cheer' class TestCheer < Minitest::Test def test_happy_path_name actual = Cheer.for_person("Ed") expected = "Give me an... E!\n" + "Give me a... D!\n" + "Ed's just GRAND!" assert_equal expected, actual end def test_name_thats_blank assert_raises(ArgumentError) do Cheer.for_person("") end end def test_name_thats_all_whitespace assert_raises(ArgumentError) do Cheer.for_person(" ") end end def test_name_that_has_no_word_characters assert_raises(ArgumentError) do Cheer.for_person("*!?") end end def test_birthday_instead_of_name assert_raises(ArgumentError) do Cheer.for_person("08/25") end end def test_name_with_spaces actual = Cheer.for_person("Mary Jane") expected = "Give me an... M!\n" + "Give me an... A!\n" + "Give me an... R!\n" + "Give me a... Y!\n" + "Give me a... J!\n" + "Give me an... A!\n" + "Give me an... N!\n" + "Give me an... E!\n" + "Mary Jane's just GRAND!" assert_equal expected, actual end def test_name_with_hyphens actual = Cheer.for_person("Mary-Jane") expected = "Give me an... M!\n" + "Give me an... A!\n" + "Give me an... R!\n" + "Give me a... Y!\n" + "Give me a... J!\n" + "Give me an... A!\n" + "Give me an... N!\n" + "Give me an... E!\n" + "Mary-Jane's just GRAND!" assert_equal expected, actual end def test_all_an_letters actual = Cheer.for_person("AEFHILMNORSX") expected = "Give me an... A!\n" + "Give me an... E!\n" + "Give me an... F!\n" + "Give me an... H!\n" + "Give me an... I!\n" + "Give me an... L!\n" + "Give me an... M!\n" + "Give me an... N!\n" + "Give me an... O!\n" + "Give me an... R!\n" + "Give me an... S!\n" + "Give me an... X!\n" + "AEFHILMNORSX's just GRAND!" assert_equal expected, actual end def test_birthday_today actual = Cheer.for_birthday("05/05") expected = "Awesome! Your birthday is today! Happy Birthday!" assert_equal actual, expected end def test_birthday_tomorrow actual = Cheer.for_birthday("05/06") expected = "Awesome! Your birthday is in 1 day! Happy Birthday in advance!" assert_equal actual, expected end def test_birthday_yesterday actual = Cheer.for_birthday("05/04") expected = "Awesome! Your birthday is in 364 days! Happy Birthday in advance!" assert_equal actual, expected end def test_birthday_in_near_future actual = Cheer.for_birthday("06/02") expected = "Awesome! Your birthday is in 28 days! Happy Birthday in advance!" assert_equal actual, expected end def test_backwards_day assert_raises(ArgumentError) do Cheer.for_birthday("25/05") end end end
{ "content_hash": "8d8d85b69556163dbea628b0252946cf", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 82, "avg_line_length": 28.383928571428573, "alnum_prop": 0.530670022019503, "repo_name": "mollytaryn/cheers_take3", "id": "45d0393bc4b92fdbd0d8fc40ea8affd0d1d3cb3c", "size": "3179", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/units/test_cheer.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "9601" } ], "symlink_target": "" }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-example77-production</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script> </head> <body ng-app=""> <p>Typing in the input box below updates the key count</p> <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}} <p>Typing in the input box below updates the keycode</p> <input ng-keyup="event=$event"> <p>event keyCode: {{ event.keyCode }}</p> <p>event altKey: {{ event.altKey }}</p> </body> </html>
{ "content_hash": "2ad45ab7bf4d10982386d07274da6b92", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 88, "avg_line_length": 26.045454545454547, "alnum_prop": 0.6579406631762653, "repo_name": "dolymood/angular-packages", "id": "648e01b369eb0e971285cb56b56c249e0e5f845c", "size": "573", "binary": false, "copies": "4", "ref": "refs/heads/gh-pages", "path": "angular-1.4.5/docs/examples/example-example77/index-production.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1454701" }, { "name": "HTML", "bytes": "82151465" }, { "name": "JavaScript", "bytes": "15628922" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "8b0b3e964026b5b545546cdf358d7ea5", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "5904adafb222425278a899d2d31e55de4a4adeca", "size": "186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Thelypteridaceae/Pseudocyclosorus/Pseudocyclosorus esquirolii/ Syn. Dryopteris eberhardtii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
'use strict'; var _extends3 = _interopRequireDefault(require('babel-runtime/helpers/extends')); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _require = require('./GraphQLCompilerPublic'), CompilerContext = _require.CompilerContext, IRTransformer = _require.IRTransformer, getLiteralArgumentValues = _require.getLiteralArgumentValues; var RELAY = 'relay'; var PLURAL = 'plural'; var SCHEMA_EXTENSION = 'directive @relay(\n # Marks a connection field as containing nodes without \'id\' fields.\n # This is used to silence the warning when diffing connections.\n isConnectionWithoutNodeID: Boolean,\n\n # Marks a fragment as intended for pattern matching (as opposed to fetching).\n # Used in Classic only.\n pattern: Boolean,\n\n # Marks a fragment as being backed by a GraphQLList.\n plural: Boolean,\n\n # Marks a fragment spread which should be unmasked if provided false\n mask: Boolean = true,\n\n # Selectively pass variables down into a fragment. Only used in Classic.\n variables: [String!],\n) on FRAGMENT_DEFINITION | FRAGMENT_SPREAD | INLINE_FRAGMENT | FIELD'; /** * A transform that extracts `@relay(plural: Boolean)` directives and converts * them to metadata that can be accessed at runtime. */ function transform(context) { return IRTransformer.transform(context, { Fragment: visitFragment }, function () { return {}; } // empty state ); } function visitFragment(fragment) { var relayDirective = fragment.directives.find(function (_ref) { var name = _ref.name; return name === RELAY; }); if (!relayDirective) { return fragment; } var _getLiteralArgumentVa = getLiteralArgumentValues(relayDirective.args), plural = _getLiteralArgumentVa.plural; require('fbjs/lib/invariant')(plural === undefined || typeof plural === 'boolean', 'RelayRelayDirectiveTransform: Expected the %s argument to @%s to be ' + 'a boolean literal or not specified.', PLURAL, RELAY); return (0, _extends3['default'])({}, fragment, { directives: fragment.directives.filter(function (directive) { return directive !== relayDirective; }), metadata: (0, _extends3['default'])({}, fragment.metadata || {}, { plural: plural }) }); } module.exports = { RELAY: RELAY, SCHEMA_EXTENSION: SCHEMA_EXTENSION, transform: transform };
{ "content_hash": "800f5f8abb5e2f1b13fa693d61b07235", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 703, "avg_line_length": 41.06896551724138, "alnum_prop": 0.7065491183879093, "repo_name": "amiechen/amiechen.github.io", "id": "0711e98b6ec3ce4c98f12ae07fd01665ba2f389b", "size": "2630", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/relay-compiler/lib/RelayRelayDirectiveTransform.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13627" }, { "name": "HTML", "bytes": "7824" }, { "name": "JavaScript", "bytes": "368" } ], "symlink_target": "" }
'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('login-panel');
{ "content_hash": "a54e2a962f96edfa7fdba5af0374d264", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 64, "avg_line_length": 34, "alnum_prop": 0.8088235294117647, "repo_name": "Tarjei400/AngularAAC", "id": "5d93d6d948b4a0f956c3eb4d134bdb87713b8983", "size": "136", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/modules/login-panel/login-panel.client.module.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1122" }, { "name": "HTML", "bytes": "8763" }, { "name": "JavaScript", "bytes": "85126" }, { "name": "Perl", "bytes": "48" }, { "name": "Shell", "bytes": "414" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /> <title>Jetty Server Project 6.1.22 Reference Package org.mortbay.jetty.plus.jaas.ldap</title> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="style" /> </head> <body> <h3> <a href="package-summary.html" target="classFrame">org.mortbay.jetty.plus.jaas.ldap</a> </h3> <h3>Classes</h3> <ul> <li> <a href="LdapLoginModule.html" target="classFrame">LdapLoginModule</a> </li> </ul> </body> </html>
{ "content_hash": "dd9fc840dfa3f99a2d04ef1e992e1966", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 97, "avg_line_length": 31.958333333333332, "alnum_prop": 0.5697522816166884, "repo_name": "cscotta/miso-java", "id": "038a39b54f269eb418e413436e3622eb6d4db059", "size": "767", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jetty/jxr/org/mortbay/jetty/plus/jaas/ldap/package-frame.html", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "16295" }, { "name": "Groovy", "bytes": "7099" }, { "name": "Java", "bytes": "5396831" }, { "name": "JavaScript", "bytes": "34952" }, { "name": "Ruby", "bytes": "7594" }, { "name": "Shell", "bytes": "67795" } ], "symlink_target": "" }
using Microsoft.CodeAnalysis.Editor.Shared.Tagging; namespace Microsoft.CodeAnalysis.Editor.ReferenceHighlighting { internal class ReferenceHighlightTag : NavigableHighlightTag { internal const string TagId = "MarkerFormatDefinition/HighlightedReference"; public static readonly ReferenceHighlightTag Instance = new ReferenceHighlightTag(); private ReferenceHighlightTag() : base(TagId) { } } }
{ "content_hash": "9af5c8ad505c7b6073f4c418e4f6e466", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 92, "avg_line_length": 28.875, "alnum_prop": 0.7207792207792207, "repo_name": "amcasey/roslyn", "id": "299c701a9878037af0dba4aa08362fd4e318b3e6", "size": "624", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/EditorFeatures/Core/ReferenceHighlighting/Tags/ReferenceHighlightTag.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "1C Enterprise", "bytes": "289100" }, { "name": "Batchfile", "bytes": "10296" }, { "name": "C#", "bytes": "95201040" }, { "name": "C++", "bytes": "5392" }, { "name": "F#", "bytes": "3632" }, { "name": "Groovy", "bytes": "10878" }, { "name": "Makefile", "bytes": "2482" }, { "name": "PowerShell", "bytes": "106831" }, { "name": "Shell", "bytes": "7412" }, { "name": "Visual Basic", "bytes": "73109780" } ], "symlink_target": "" }
 #pragma once #include <aws/securityhub/SecurityHub_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/securityhub/model/ActionRemoteIpDetails.h> #include <aws/securityhub/model/ActionRemotePortDetails.h> #include <aws/securityhub/model/ActionLocalPortDetails.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace SecurityHub { namespace Model { /** * <p>Provided if <code>ActionType</code> is <code>NETWORK_CONNECTION</code>. It * provides details about the attempted network connection that was * detected.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/securityhub-2018-10-26/NetworkConnectionAction">AWS * API Reference</a></p> */ class AWS_SECURITYHUB_API NetworkConnectionAction { public: NetworkConnectionAction(); NetworkConnectionAction(Aws::Utils::Json::JsonView jsonValue); NetworkConnectionAction& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The direction of the network connection request (<code>IN</code> or * <code>OUT</code>).</p> */ inline const Aws::String& GetConnectionDirection() const{ return m_connectionDirection; } /** * <p>The direction of the network connection request (<code>IN</code> or * <code>OUT</code>).</p> */ inline bool ConnectionDirectionHasBeenSet() const { return m_connectionDirectionHasBeenSet; } /** * <p>The direction of the network connection request (<code>IN</code> or * <code>OUT</code>).</p> */ inline void SetConnectionDirection(const Aws::String& value) { m_connectionDirectionHasBeenSet = true; m_connectionDirection = value; } /** * <p>The direction of the network connection request (<code>IN</code> or * <code>OUT</code>).</p> */ inline void SetConnectionDirection(Aws::String&& value) { m_connectionDirectionHasBeenSet = true; m_connectionDirection = std::move(value); } /** * <p>The direction of the network connection request (<code>IN</code> or * <code>OUT</code>).</p> */ inline void SetConnectionDirection(const char* value) { m_connectionDirectionHasBeenSet = true; m_connectionDirection.assign(value); } /** * <p>The direction of the network connection request (<code>IN</code> or * <code>OUT</code>).</p> */ inline NetworkConnectionAction& WithConnectionDirection(const Aws::String& value) { SetConnectionDirection(value); return *this;} /** * <p>The direction of the network connection request (<code>IN</code> or * <code>OUT</code>).</p> */ inline NetworkConnectionAction& WithConnectionDirection(Aws::String&& value) { SetConnectionDirection(std::move(value)); return *this;} /** * <p>The direction of the network connection request (<code>IN</code> or * <code>OUT</code>).</p> */ inline NetworkConnectionAction& WithConnectionDirection(const char* value) { SetConnectionDirection(value); return *this;} /** * <p>Information about the remote IP address that issued the network connection * request.</p> */ inline const ActionRemoteIpDetails& GetRemoteIpDetails() const{ return m_remoteIpDetails; } /** * <p>Information about the remote IP address that issued the network connection * request.</p> */ inline bool RemoteIpDetailsHasBeenSet() const { return m_remoteIpDetailsHasBeenSet; } /** * <p>Information about the remote IP address that issued the network connection * request.</p> */ inline void SetRemoteIpDetails(const ActionRemoteIpDetails& value) { m_remoteIpDetailsHasBeenSet = true; m_remoteIpDetails = value; } /** * <p>Information about the remote IP address that issued the network connection * request.</p> */ inline void SetRemoteIpDetails(ActionRemoteIpDetails&& value) { m_remoteIpDetailsHasBeenSet = true; m_remoteIpDetails = std::move(value); } /** * <p>Information about the remote IP address that issued the network connection * request.</p> */ inline NetworkConnectionAction& WithRemoteIpDetails(const ActionRemoteIpDetails& value) { SetRemoteIpDetails(value); return *this;} /** * <p>Information about the remote IP address that issued the network connection * request.</p> */ inline NetworkConnectionAction& WithRemoteIpDetails(ActionRemoteIpDetails&& value) { SetRemoteIpDetails(std::move(value)); return *this;} /** * <p>Information about the port on the remote IP address.</p> */ inline const ActionRemotePortDetails& GetRemotePortDetails() const{ return m_remotePortDetails; } /** * <p>Information about the port on the remote IP address.</p> */ inline bool RemotePortDetailsHasBeenSet() const { return m_remotePortDetailsHasBeenSet; } /** * <p>Information about the port on the remote IP address.</p> */ inline void SetRemotePortDetails(const ActionRemotePortDetails& value) { m_remotePortDetailsHasBeenSet = true; m_remotePortDetails = value; } /** * <p>Information about the port on the remote IP address.</p> */ inline void SetRemotePortDetails(ActionRemotePortDetails&& value) { m_remotePortDetailsHasBeenSet = true; m_remotePortDetails = std::move(value); } /** * <p>Information about the port on the remote IP address.</p> */ inline NetworkConnectionAction& WithRemotePortDetails(const ActionRemotePortDetails& value) { SetRemotePortDetails(value); return *this;} /** * <p>Information about the port on the remote IP address.</p> */ inline NetworkConnectionAction& WithRemotePortDetails(ActionRemotePortDetails&& value) { SetRemotePortDetails(std::move(value)); return *this;} /** * <p>Information about the port on the EC2 instance.</p> */ inline const ActionLocalPortDetails& GetLocalPortDetails() const{ return m_localPortDetails; } /** * <p>Information about the port on the EC2 instance.</p> */ inline bool LocalPortDetailsHasBeenSet() const { return m_localPortDetailsHasBeenSet; } /** * <p>Information about the port on the EC2 instance.</p> */ inline void SetLocalPortDetails(const ActionLocalPortDetails& value) { m_localPortDetailsHasBeenSet = true; m_localPortDetails = value; } /** * <p>Information about the port on the EC2 instance.</p> */ inline void SetLocalPortDetails(ActionLocalPortDetails&& value) { m_localPortDetailsHasBeenSet = true; m_localPortDetails = std::move(value); } /** * <p>Information about the port on the EC2 instance.</p> */ inline NetworkConnectionAction& WithLocalPortDetails(const ActionLocalPortDetails& value) { SetLocalPortDetails(value); return *this;} /** * <p>Information about the port on the EC2 instance.</p> */ inline NetworkConnectionAction& WithLocalPortDetails(ActionLocalPortDetails&& value) { SetLocalPortDetails(std::move(value)); return *this;} /** * <p>The protocol used to make the network connection request.</p> */ inline const Aws::String& GetProtocol() const{ return m_protocol; } /** * <p>The protocol used to make the network connection request.</p> */ inline bool ProtocolHasBeenSet() const { return m_protocolHasBeenSet; } /** * <p>The protocol used to make the network connection request.</p> */ inline void SetProtocol(const Aws::String& value) { m_protocolHasBeenSet = true; m_protocol = value; } /** * <p>The protocol used to make the network connection request.</p> */ inline void SetProtocol(Aws::String&& value) { m_protocolHasBeenSet = true; m_protocol = std::move(value); } /** * <p>The protocol used to make the network connection request.</p> */ inline void SetProtocol(const char* value) { m_protocolHasBeenSet = true; m_protocol.assign(value); } /** * <p>The protocol used to make the network connection request.</p> */ inline NetworkConnectionAction& WithProtocol(const Aws::String& value) { SetProtocol(value); return *this;} /** * <p>The protocol used to make the network connection request.</p> */ inline NetworkConnectionAction& WithProtocol(Aws::String&& value) { SetProtocol(std::move(value)); return *this;} /** * <p>The protocol used to make the network connection request.</p> */ inline NetworkConnectionAction& WithProtocol(const char* value) { SetProtocol(value); return *this;} /** * <p>Indicates whether the network connection attempt was blocked.</p> */ inline bool GetBlocked() const{ return m_blocked; } /** * <p>Indicates whether the network connection attempt was blocked.</p> */ inline bool BlockedHasBeenSet() const { return m_blockedHasBeenSet; } /** * <p>Indicates whether the network connection attempt was blocked.</p> */ inline void SetBlocked(bool value) { m_blockedHasBeenSet = true; m_blocked = value; } /** * <p>Indicates whether the network connection attempt was blocked.</p> */ inline NetworkConnectionAction& WithBlocked(bool value) { SetBlocked(value); return *this;} private: Aws::String m_connectionDirection; bool m_connectionDirectionHasBeenSet; ActionRemoteIpDetails m_remoteIpDetails; bool m_remoteIpDetailsHasBeenSet; ActionRemotePortDetails m_remotePortDetails; bool m_remotePortDetailsHasBeenSet; ActionLocalPortDetails m_localPortDetails; bool m_localPortDetailsHasBeenSet; Aws::String m_protocol; bool m_protocolHasBeenSet; bool m_blocked; bool m_blockedHasBeenSet; }; } // namespace Model } // namespace SecurityHub } // namespace Aws
{ "content_hash": "89b8a52d01a2b624eca676a2fb713cda", "timestamp": "", "source": "github", "line_count": 274, "max_line_length": 151, "avg_line_length": 36.083941605839414, "alnum_prop": 0.6890866794781025, "repo_name": "cedral/aws-sdk-cpp", "id": "6bbe3b22150e65360c38202e57ec0483e5daeb80", "size": "10006", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "aws-cpp-sdk-securityhub/include/aws/securityhub/model/NetworkConnectionAction.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "294220" }, { "name": "C++", "bytes": "428637022" }, { "name": "CMake", "bytes": "862025" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "7904" }, { "name": "Java", "bytes": "352201" }, { "name": "Python", "bytes": "106761" }, { "name": "Shell", "bytes": "10891" } ], "symlink_target": "" }
<?php namespace Redmine\Api; use Redmine\Exception\MissingParameterException; use Redmine\Serializer\XmlSerializer; /** * Listing time entries, creating, editing. * * @see http://www.redmine.org/projects/redmine/wiki/Rest_TimeEntries * * @author Kevin Saliou <kevin at saliou dot name> */ class TimeEntry extends AbstractApi { private $timeEntries = []; /** * List time entries. * * @see http://www.redmine.org/projects/redmine/wiki/Rest_TimeEntries * * @param array $params optional parameters to be passed to the api (offset, limit, ...) * * @return array list of time entries found */ public function all(array $params = []) { $this->timeEntries = $this->retrieveData('/time_entries.json', $params); return $this->timeEntries; } /** * Get extended information about a time entry (including memberships + groups). * * @see http://www.redmine.org/projects/redmine/wiki/Rest_TimeEntries * * @param string $id the time entry id * * @return array information about the time entry */ public function show($id) { return $this->get('/time_entries/'.urlencode($id).'.json'); } /** * Create a new time entry given an array of $params. * * @see http://www.redmine.org/projects/redmine/wiki/Rest_TimeEntries * * @param array $params the new time entry data * * @throws MissingParameterException Missing mandatory parameters * * @return string|false */ public function create(array $params = []) { $defaults = [ 'issue_id' => null, 'project_id' => null, 'spent_on' => null, 'hours' => null, 'activity_id' => null, 'comments' => null, ]; $params = $this->sanitizeParams($defaults, $params); if ( (!isset($params['issue_id']) && !isset($params['project_id'])) || !isset($params['hours']) ) { throw new MissingParameterException('Theses parameters are mandatory: `issue_id` or `project_id`, `hours`'); } return $this->post( '/time_entries.xml', XmlSerializer::createFromArray(['time_entry' => $params])->getEncoded() ); } /** * Update time entry's information. * * @see http://www.redmine.org/projects/redmine/wiki/Rest_TimeEntries * * @param int $id * * @return string|false */ public function update($id, array $params) { $defaults = [ 'id' => $id, 'issue_id' => null, 'project_id' => null, 'spent_on' => null, 'hours' => null, 'activity_id' => null, 'comments' => null, ]; $params = $this->sanitizeParams($defaults, $params); return $this->put( '/time_entries/'.$id.'.xml', XmlSerializer::createFromArray(['time_entry' => $params])->getEncoded() ); } /** * Delete a time entry. * * @see http://www.redmine.org/projects/redmine/wiki/Rest_TimeEntries * * @param int $id id of the time entry * * @return false|\SimpleXMLElement|string */ public function remove($id) { return $this->delete('/time_entries/'.$id.'.xml'); } }
{ "content_hash": "ff36fd6c615983c038753e8c20d53a5e", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 120, "avg_line_length": 26.96031746031746, "alnum_prop": 0.5525463644392111, "repo_name": "kbsali/php-redmine-api", "id": "343633ebb624beec49c650651185bbd57b789ae6", "size": "3397", "binary": false, "copies": "1", "ref": "refs/heads/v2.x", "path": "src/Redmine/Api/TimeEntry.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "426944" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="ko-kr"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="generator" content="Hugo 0.15" /> <title>#Ludens</title> <meta property="og:site_name" content="#Ludens" /> <meta property="og:locale" content="ko-kr" /> <meta property="og:url" content="http://ludens.kr/tags/weddington-way/" /> <meta property="fb:pages" content="1707155736233413"/> <meta property="fb:admins" content="100001662925065"/> <meta property="fb:app_id" content="326482430777833"/> <meta property="fb:article_style" content="default" /> <meta name="twitter:site" content="@ludensk" /> <meta name="twitter:creator" content="@ludensk" /> <meta name="google-site-verification" content="RPY_1Z0am0hoduGzENYtuwF3BBoE0x5l3UxhUplLWPU" /> <meta name="naver-site-verification" content="f84c50bc744edf7a543994325914265117555d53" /> <meta name="p:domain_verify" content="381496f2247c95edc614061bacd92e08" /> <meta name="msvalidate.01" content="9137E6F3A8C1C4AE6DC4809DEDB06FD9" /> <meta property="og:title" content="Weddington Way" /> <meta property="og:type" content="website" /> <meta name="description" content="페이스북부터 심리학 그리고 워드프레스까지 온갖 잡지식을 가끔씩 끄적이고 있습니다." /> <meta name="twitter:card" content="summary" /> <link rel="author" href="humans.txt" /> <link rel="me" href="https://twitter.com/ludensk" /> <link rel="me" href="https://google.com/+ludensk" /> <link rel="me" href="https://github.com/ludens" /> <link rel="pingback" href="https://webmention.io/ludens.kr/xmlrpc" /> <link rel="webmention" href="https://webmention.io/ludens.kr/webmention" /> <link href="https://plus.google.com/+ludensk" rel="publisher"> <link rel="canonical" href="http://ludens.kr/tags/weddington-way/" /> <link rel="alternate" type="application/rss+xml" title="#Ludens" href="http://ludens.kr/rss/" /> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content="#Ludens"> <meta name="mobile-web-app-capable" content="yes"> <meta name="theme-color" content="#111111"> <meta name="msapplication-navbutton-color" content="#111111"> <meta name="msapplication-TileColor" content="#111111"> <meta name="application-name" content="#Ludens"> <meta name="msapplication-tooltip" content="페이스북부터 심리학 그리고 워드프레스까지 온갖 잡지식을 가끔씩 끄적이고 있습니다."> <meta name="msapplication-starturl" content="/"> <meta http-equiv="cleartype" content="on"> <meta name="msapplication-tap-highlight" content="no"> <link rel="apple-touch-icon" sizes="57x57" href="http://ludens.kr/favicon/apple-touch-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="http://ludens.kr/favicon/apple-touch-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="http://ludens.kr/favicon/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="http://ludens.kr/favicon/apple-touch-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="http://ludens.kr/favicon/apple-touch-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="http://ludens.kr/favicon/apple-touch-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="http://ludens.kr/favicon/apple-touch-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="http://ludens.kr/favicon/apple-touch-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="http://ludens.kr/favicon/apple-touch-icon-180x180.png"> <link rel="icon" type="image/png" href="http://ludens.kr/favicon/favicon-32x32.png" sizes="32x32"> <link rel="icon" type="image/png" href="http://ludens.kr/favicon/favicon-194x194.png" sizes="194x194"> <link rel="icon" type="image/png" href="http://ludens.kr/favicon/favicon-96x96.png" sizes="96x96"> <link rel="icon" type="image/png" href="http://ludens.kr/favicon/android-chrome-192x192.png" sizes="192x192"> <link rel="icon" type="image/png" href="http://ludens.kr/favicon/favicon-16x16.png" sizes="16x16"> <link rel="manifest" href="http://ludens.kr/favicon/manifest.json"> <link rel="mask-icon" href="http://ludens.kr/favicon/safari-pinned-tab.svg" color="#5bbad5"> <meta name="msapplication-TileImage" content="/mstile-144x144.png"> <link rel="stylesheet" href="http://ludens.kr/css/pure/pure-min.css" /> <link rel="stylesheet" href="http://ludens.kr/css/pure/grids-responsive-min.css" /> <link rel='stylesheet' href='http://ludens.kr/font/fonts.css'> <link rel="stylesheet" href="http://ludens.kr/font/font-awesome.min.css"> <link rel="stylesheet" href="http://ludens.kr/css/style.css"/> <script src="http://ludens.kr/js/jquery-2.2.1.min.js"></script> </head> <body> <script> window.fbAsyncInit = function() { FB.init({ appId : '326482430777833', xfbml : true, version : 'v2.6' }); }; (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/ko_KR/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <header class="pure-g"> <div class="pure-u-1 pure-u-sm-1-3 center"> <h1><a href="http://ludens.kr">#LUDENS</a></h1> </div> <nav class="pure-u-1 pure-u-sm-2-3 center"> <a href="http://ludens.kr/" class="home" title="Home">HOME</a> <a href="http://ludens.kr/categories/" class="category" title="Category">CATEGORY</a> <a href="http://ludens.kr/post/" class="archive" title="Archive">ARCHIVE</a> <a href="http://ludens.kr/tags/" class="tag" title="Tag">TAG</a> <a href="http://ludens.kr/guestbook/" class="guestbook" title="Guestbook">GUESTBOOK</a> </nav> </header> <main class="list mainWrap"> <h2 class="ellipsis"><small>Posts about </small>Weddington Way</h2> <h3 id="2013">2013</h3> <div class="pure-g"> <div class="pure-u-1 pure-u-sm-1-2"> <a href="http://ludens.kr/post/valentines-day-infographics/" class="cover" style="background-image: url('/images/old/cfile25.uf.1152B842511C6CFE2DD07E.jpg');"></a> <div class="category ubuntu300 grey"> <a class="grey" href="http://ludens.kr/categories/infographic" title="Infographic">Infographic</a> at <time datetime="14 Feb 2013 27:00">2013/2/14</time> </div> <h3 class="ellipsis margintop0"><a href="http://ludens.kr/post/valentines-day-infographics/" title="2013년 발렌타인데이 인포그래픽 40여개 모음">2013년 발렌타인데이 인포그래픽 40여개 모음</a></h3> </div> </div> </main> <footer> <div class="footerWrap pure-g"> <div class="pure-u-1 pure-u-md-2-5 copyright center"> ⓒ 2016 Ludens | Published with <a class="black dotline" href="http://gohugo.io" target="_blank" rel="nofollow">Hugo</a> </div> <nav class="pure-u-1 pure-u-md-3-5 center"> <a href="https://twitter.com/ludensk" class="twitter" title="Twitter"><i class='fa fa-twitter-square'></i></a> <a href="https://fb.com/ludensk" class="facebook" title="Facebook"><i class='fa fa-facebook-square'></i></a> <a href="https://instagr.am/ludensk" class="instagram" title="Instagram"><i class='fa fa-instagram'></i></a> <a href="https://pinterest.com/ludensk" class="pinterest" title="Pinterest"><i class='fa fa-pinterest-square'></i></a> <a href="https://www.youtube.com/user/ludensk" class="youtube" title="YouTube"><i class='fa fa-youtube-square'></i></a> <a href="https://ludensk.tumblr.com" class="tumblr" title="Tumblr"><i class='fa fa-tumblr-square'></i></a> <a href="https://linkedin.com/in/ludensk" class="linkedin" title="LinkedIn"><i class='fa fa-linkedin-square'></i></a> <a href="https://github.com/ludens" class="github" title="GitHub"><i class='fa fa-github-square'></i></a> <a href="http://ludens.kr/rss/" class="rss" title="RSS"><i class='fa fa-rss-square'></i></a> </nav> </div> </footer> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-29269230-1', 'auto'); ga('send', 'pageview'); </script> <script type="text/javascript" src="//wcs.naver.net/wcslog.js"></script> <script type="text/javascript"> if(!wcs_add) var wcs_add = {}; wcs_add["wa"] = "123cefa73667c5c"; wcs_do(); </script> <script> !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','//connect.facebook.net/en_US/fbevents.js'); fbq('init','1143503702345044'); fbq('track',"PageView"); </script> <noscript><img height="1" width="1" style="display:none" src="//www.facebook.com/tr?id=1143503702345044&ev=PageView&noscript=1" /></noscript> <script src="//twemoji.maxcdn.com/twemoji.min.js"></script> <script>var emoji=document.getElementsByClassName("emoji");twemoji.parse(emoji[0],{size:16});</script> <script src="http://ludens.kr/js/jquery.keep-ratio.min.js"></script> <script type="text/javascript"> $(function() { $('.kofic-poster').keepRatio({ ratio: 27/40, calculate: 'height' }); $('.articleWrap .cover, .post_latest .cover,.articleWrap header figure').keepRatio({ ratio: 12/5, calculate: 'height' }); if ($(window).width() >= 568) { $('.futher .cover,.error .cover,.post_two .cover,.list .cover').keepRatio({ ratio: 4/3, calculate: 'height' }); $('.categories .cover').keepRatio({ ratio: 1/1, calculate: 'height' }); } else { $('.futher .cover,.error .cover,.post_two .cover,.list .cover,.categories .cover').keepRatio({ ratio: 12/5, calculate: 'height' }); } }); </script> </body> </html>
{ "content_hash": "9cd72f8c9c01c3b1ae83894431b3a8eb", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 370, "avg_line_length": 45.53711790393013, "alnum_prop": 0.6573647871116226, "repo_name": "ludens/ludens.kr", "id": "27e07e71094660e735318aeeb63dbb98e614d5f4", "size": "10638", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "tags/weddington-way/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18631" }, { "name": "HTML", "bytes": "24946646" }, { "name": "JavaScript", "bytes": "8525" } ], "symlink_target": "" }
// FileUtils.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using System.IO; using System.Drawing; using System.Windows.Forms; using System.Xml.Serialization; using System.Reflection; using System.Collections.Generic; namespace CoreUtilities { public static class FileUtils { /// <summary> /// Serialize any serializable C# object into an xml file. /// </summary> /// <param name="oObject">The object to serialize</param> /// <param name="backup">backup directory</param> /// <param name="sName">Path and name of the output file, i.e. myobject.xml</param> public static void Serialize(object oObject, string sName, string backup) { bool bDidBackup = false; if (oObject == null || sName == null) { throw new Exception("Serialize null passed in for oObject or sName"); } // copy backup to safe place if (null != backup && "" != backup && File.Exists(sName)) { try { FileInfo f = new FileInfo(sName); backup = Path.Combine(backup,"backup"); File.Copy(sName, backup , true); f = null; bDidBackup = true; } catch (Exception) { } } try { System.Type t = oObject.GetType(); if (t != null) { XmlSerializer s = new XmlSerializer(t); TextWriter w = new StreamWriter(@sName); s.Serialize(w, oObject); w.Close(); t = null; w = null; s = null; } } catch (Exception ex) { if (true == bDidBackup) { // copy the backed up file if (File.Exists(backup) == true) { File.Copy(backup, sName, true); } } // February 2010 // I lost part of Zombieworld and I figured maybe it might make sense to copy a backup // of the filee being saved AND RESTORE it if there is an exception CoreUtilities.NewMessage.Show(sName + " did not save correctly. You should copy your data (copy/paste) shut down and retry. Your last saved version will still be valid." + ex.ToString()); } } /// <summary> /// Deserialize any object from xml. /// </summary> /// <param name="sName">File name</param> /// <param name="t">Object type (i.e. GetType(o))</param> /// <returns>Deserialized object. Cast back to type before using</returns> public static object DeSerialize(string sName, System.Type t) { FileInfo f = new FileInfo(sName); /*February 2009 * I had originally prevent any non xml files from entering here * but that was just a bandaid. * * I needed to pass bst (brainstorm) files into this and to do that I needed this to be open */ // if (f.Extension.ToLower() == ".xml") { TextReader r = null; try { XmlSerializer s = new XmlSerializer(t); object oRet; r = new StreamReader(@sName); oRet = s.Deserialize(r); r.Close(); return oRet; } catch (Exception ex) { if (r != null) r.Close(); // MessgeBox.Show(sName + " " + ex.ToString()); throw (new Exception(sName.ToUpper() + " " + ex.ToString())); } } /* else { MessgeBox.Show(String.Format("For some reason an invalid file ({0}) was passed into the xml deserializer. Skipping.", sName)); return null; }*/ // return null; } /// <summary> /// Doeses the this file have errors. /// /// If the file is blank will return true. /// </summary> /// <returns> /// <c>true</c>, if this file hae errors was doesed, <c>false</c> otherwise. /// </returns> /// <param name='file'> /// File. /// </param> public static bool DoesThisFileHaveErrors (string file) { bool foundRealText = false; //System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("^[a-zA-Z0-9]*$"); using (StreamReader sr = new StreamReader(file)) { String line = sr.ReadToEnd(); //Console.WriteLine (line); //if (string.IsNullOrWhiteSpace(line) == false) // if (r.IsMatch(line)) if (line.IndexOfAny(new char[5]{'a','i','o','u','e'}) > -1) { //Console.WriteLine ("found text"); foundRealText = true; } } return !foundRealText; } /// <summary> /// Finds the file, starting at rootDirectory. /// /// Returns the full path to the found file or BLANK, if not found /// </summary> /// <returns> /// The file. /// </returns> /// <param name='fileName'> /// File name. /// </param> /// <param name='rootDirectory'> /// Root directory. /// </param> public static string FindFile (string fileName, string rootDirectory) { string[] results = Directory.GetFiles (rootDirectory, fileName, SearchOption.AllDirectories); lg.Instance.Line("FileUtils->FindFile", ProblemType.MESSAGE, String.Format ("Searching for file {0} in Directory {1}", fileName, rootDirectory)); string returnresult = Constants.BLANK; if (results.Length > 0) { returnresult = results[0]; } return returnresult; } /// <summary> /// Checks for file error. /// /// Several times I have encounterd a harddrive failure (maybe) that all files that are saved after the point /// in which the invisible error happens. /// /// This affected the previous version of YOM (.NET 2.0) as well as PDF files that were open in Adobe. All the files /// would have the same filelength as previous but every character was replaced with a blank. /// /// Very bizarre. This is my attempt to create a test that is intended to be ran when an Application is closing. /// <returns>If it encounters the problem it returns TRUE meaning a file error has occurred. At this point /// it is advised to terminate the application without trying to save the files. /// </returns> /// /// /// </summary> public static bool CheckForFileError () { string oldfile = Path.GetTempFileName(); using (StreamWriter sw = new StreamWriter(oldfile)) { sw.Write ("This is a test file from coreutilities in YOM to make sure harddrive failure is not happening."); } return DoesThisFileHaveErrors(oldfile); } public static Icon GetIcon (string identifier) { return new Icon (System.Reflection.Assembly.GetCallingAssembly ().GetManifestResourceStream (identifier)); } public static Bitmap GetImage_ForDLL (string identifier) { return new Bitmap (System.Reflection.Assembly.GetCallingAssembly ().GetManifestResourceStream (identifier)); } public static Bitmap GetImage_ForEXE (string identifier) { return new Bitmap (System.Reflection.Assembly.GetExecutingAssembly ().GetManifestResourceStream (identifier)); } /// <summary> /// Makes the valid filename. Strips invalid characters from it NOTE: This is only for a FILENAME, not a path. It strips the : character out /// </summary> /// <returns> /// The valid filename. /// </returns> /// <param name='OriginalFileName'> /// Original file name. /// </param> public static string MakeValidFilename (string OriginalFileName) { foreach (char c in System.IO.Path.GetInvalidFileNameChars()) { OriginalFileName = OriginalFileName.Replace(c, '_'); } return OriginalFileName; } /// <summary> /// Defaults to 7 characters /// </summary> /// <param name="sDirectory"></param> /// <param name="sPrefix"></param> /// <param name="sExtension"></param> /// <returns></returns> public static string MakeUniqueFileNameForDirectory(string sDirectory, string sPrefix, string sExtension) { return MakeUniqueFileNameForDirectory(sDirectory, sPrefix, sExtension, 7, 0); } /// <summary> /// Creates a unique filename. Used for adding pages and submission files /// </summary> /// <param name="sDirectory"></param> /// <param name="sPrefix"></param> /// <param name="sExtension"></param> /// <param name="nCharacters">how many characters in the name. Throws exception if 0</param> /// <param name="nCount2">minimum number, for examplke Keeper can't create pages under 100. Throws exception if 0</param> /// <returns>null if unable to build the filename</returns> public static string MakeUniqueFileNameForDirectory(string sDirectory, string sPrefix, string sExtension, int nCharacters, int nCount2) { if (sDirectory == null || sPrefix == null || sExtension == null) { return null; } if (nCount2 < 0 || nCharacters == 0) { throw new ArgumentException("MakeUniqueFilenameForDirectory Count < 0 or nCharacters == 0"); } string sFileName = ""; int nCount = nCount2; // will loop to guarantee the uniqueness of the file do { // count number of files and add a Number string[] sFiles = Directory.GetFiles(sDirectory); sFileName = (sFiles.Length + 1 + nCount).ToString(); // add zeroes while (sFileName.Length < nCharacters) { sFileName = "0" + sFileName; } sFileName = sPrefix + sFileName + "." + sExtension; nCount++; } while (File.Exists(sDirectory + "\\" + sFileName) == true); return sFileName; } /// <summary> /// pulls resource of resourceid /// /// (Copies said file from embedded resources into the diretory said /// called by PrepareDictionary /// </summary> /// <param name="sResourceID"></param> public static void PreparePullResource(Assembly _assembly, string sResourceID, string sFile) { if (sResourceID == null || sFile == null) { throw new Exception("PreparePullResource - no file or resource specified"); } StreamReader _imageStream; _imageStream = new StreamReader(_assembly.GetManifestResourceStream(sResourceID)); if (_imageStream != null) { StreamWriter sw = new StreamWriter(sFile); string s = _imageStream.ReadLine(); while (s != null) { sw.WriteLine(s); s = _imageStream.ReadLine(); } _imageStream.Close(); sw.Close(); sw = null; _imageStream = null; } } /// <summary> // SOURCE: did up where this cam efrom /// xDirectory.Copy() - Copy a Source Directory /// and it's SubDirectories/Files /// </summary> /// <param name="diSource">The Source Directory</param> /// <param name="diDestination">The Destination Directory</param> /// <param name="FileFilter">The File Filter /// (Standard Windows Filter Parameter, Wildcards: "*" and "?")</param> /// <param name="DirectoryFilter">The Directory Filter /// (Standard Windows Filter Parameter, Wildcards: "*" and "?")</param> /// <param name="Overwrite">Whether or not to Overwrite /// a Destination File if it Exists.</param> /// <param name="FolderLimit">Iteration Limit - Total Number /// of Folders/SubFolders to Copy</param> public static void Copy(DirectoryInfo diSource, DirectoryInfo diDestination, string FileFilter, string DirectoryFilter, bool Overwrite, int FolderLimit, ProgressBar bar) { int iterator = 0; List<DirectoryInfo> diSourceList = new List<DirectoryInfo>(); List<FileInfo> fiSourceList = new List<FileInfo>(); try { ///// Error Checking ///// if (diSource == null) throw new ArgumentException("Source Directory: NULL"); if (diDestination == null) throw new ArgumentException("Destination Directory: NULL"); if (!diSource.Exists) throw new IOException("Source Directory: Does Not Exist"); if (!(FolderLimit > 0)) throw new ArgumentException("Folder Limit: Less Than 1"); if (DirectoryFilter == null || DirectoryFilter == string.Empty) DirectoryFilter = "*"; if (FileFilter == null || FileFilter == string.Empty) FileFilter = "*"; if (bar == null) throw new ArgumentException("Copy - Progress Bar: NULL"); ///// Add Source Directory to List ///// diSourceList.Add(diSource); ///// First Section: Get Folder/File Listing ///// while (iterator < diSourceList.Count && iterator < FolderLimit) { foreach (DirectoryInfo di in diSourceList[iterator].GetDirectories(DirectoryFilter)) diSourceList.Add(di); foreach (FileInfo fi in diSourceList[iterator].GetFiles(FileFilter)) fiSourceList.Add(fi); iterator++; } if (bar != null) { bar.Maximum = fiSourceList.Count; bar.Minimum = 0; bar.Step = 1; bar.Value = 0; } ///// Second Section: Create Folders from Listing ///// foreach (DirectoryInfo di in diSourceList) { if (di.Exists) { string sFolderPath = diDestination.FullName + @"\" + di.FullName.Remove(0, diSource.FullName.Length); ///// Prevent Silly IOException ///// if (!Directory.Exists(sFolderPath)) Directory.CreateDirectory(sFolderPath); } } ///// Third Section: Copy Files from Listing ///// foreach (FileInfo fi in fiSourceList) { if (fi.Exists) { string sFilePath = diDestination.FullName + @"\" + fi.FullName.Remove(0, diSource.FullName.Length); //// Better Overwrite Test W/O IOException from CopyTo() //// if (Overwrite) fi.CopyTo(sFilePath, true); else { ///// Prevent Silly IOException ///// if (!File.Exists(sFilePath)) fi.CopyTo(sFilePath, true); } if (bar != null) { bar.Increment(1); } } } } catch { throw; } } } }
{ "content_hash": "930c67fbeee7c0e3593a055942940ae5", "timestamp": "", "source": "github", "line_count": 474, "max_line_length": 191, "avg_line_length": 31.5210970464135, "alnum_prop": 0.6412556053811659, "repo_name": "BrentKnowles/YourOtherMind", "id": "7486dda24e3bc1a7b097249c120bb153d0dd78cd", "size": "14941", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "coreutilities/FileUtils.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1686701" } ], "symlink_target": "" }
<?php /** * @var $this PostController * @var $target Blog */ $this->title = Yii::t('BlogModule.blog', 'Posts of "{blog}" blog', ['{blog}' => CHtml::encode($target->name)]); $this->description = Yii::t('BlogModule.blog', 'Posts of "{blog}" blog', ['{blog}' => CHtml::encode($target->name)]); $this->keywords = $target->name; ?> <?php $this->breadcrumbs = [ Yii::t('BlogModule.blog', 'Blogs') => ['/blog/blog/index/'], CHtml::encode($target->name) => ['/blog/blog/view/', 'slug' => CHtml::encode($target->slug)], Yii::t('BlogModule.blog', 'Records'), ]; ?>
{ "content_hash": "97ab25ed84c67d5c0cdafef222053f6c", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 117, "avg_line_length": 34.94117647058823, "alnum_prop": 0.5656565656565656, "repo_name": "u4aew/MyHotelG", "id": "947efeaf24aac01221c47e5812f4ff8a5a425927", "size": "594", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "themes/shop/views/blog/post/blog-post.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "732" }, { "name": "Batchfile", "bytes": "393" }, { "name": "CSS", "bytes": "321119" }, { "name": "HTML", "bytes": "18575" }, { "name": "JavaScript", "bytes": "444481" }, { "name": "Nginx", "bytes": "2412" }, { "name": "PHP", "bytes": "5417018" }, { "name": "Shell", "bytes": "911" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Marssonia quercina var. major Overh. ### Remarks null
{ "content_hash": "178ceef336d68184f2649ce360d68f7f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 36, "avg_line_length": 10.846153846153847, "alnum_prop": 0.7092198581560284, "repo_name": "mdoering/backbone", "id": "bc1088a80d0330551bd0a140ef08a1f4e0515a66", "size": "201", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Dermateaceae/Marssonia/Marssonia quercina/Marssonia quercina major/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
 CKEDITOR.plugins.setLang( 'toolbar', 'da', { toolbarCollapse: 'Sammenklap værktøjslinje', toolbarExpand: 'Udvid værktøjslinje', toolbarGroups: { document: 'Dokument', clipboard: 'Udklipsholder/Fortryd', editing: 'Redigering', forms: 'Formularer', basicstyles: 'Basis styles', paragraph: 'Paragraf', links: 'Links', insert: 'Indsæt', styles: 'Typografier', colors: 'Farver', tools: 'Værktøjer' }, toolbars: 'Editors værktøjslinjer' });
{ "content_hash": "9b24dc1ed5f9eac9b805ecbae1148508", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 45, "avg_line_length": 24.42105263157895, "alnum_prop": 0.6961206896551724, "repo_name": "EZWebvietnam/vieclam24h", "id": "272c189e65e3b2e7adfbeb3437e20b3899ac4c35", "size": "619", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "plugin/ckeditor/plugins/toolbar/lang/da.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2283" }, { "name": "CSS", "bytes": "1342698" }, { "name": "JavaScript", "bytes": "5313655" }, { "name": "PHP", "bytes": "3216121" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Graphyllium chloës var. junci Peck ### Remarks null
{ "content_hash": "936e384a78228e11527197ace9b647c5", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 34, "avg_line_length": 10.692307692307692, "alnum_prop": 0.7122302158273381, "repo_name": "mdoering/backbone", "id": "3a943197f05cf96dd25fe237327dba3fe2603585", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Hysteriales/Hysteriaceae/Graphyllium/Graphyllium chloës/Graphyllium chloës junci/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php /** * [BEGIN_COT_EXT] * Hooks=projects.offers.loop * [END_COT_EXT] */ /** * mavatarslance for Cotonti CMF * * @version 1.2.1 * @author CMSWorks Team * @copyright Copyright (c) CMSWorks.ru, littledev.ru */ defined('COT_CODE') or die('Wrong URL'); global $cfg; if (cot_plugin_active('mavatars') && $cfg['plugin']['mavatarslance']['projects']) { require_once cot_incfile('mavatars', 'plug'); $mavatar = new mavatar('projectoffers', $id, $offers['item_id']); $mavatars_tags = $mavatar->generate_mavatars_tags(); $t_o->assign(array( 'OFFER_ROW_MAVATAR' => $mavatars_tags, 'OFFER_ROW_MAVATARCOUNT' => count($mavatars_tags) )); }
{ "content_hash": "f26e5fbffdc6dfbd1964b8ab26829415", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 81, "avg_line_length": 23.321428571428573, "alnum_prop": 0.6493108728943339, "repo_name": "Velm14/dribascorp", "id": "bb3c4300cc847453e440d6949d563c5b2e0d974b", "size": "653", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins/mavatarslance/mavatarslance.projects.offers.loop.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "125" }, { "name": "CSS", "bytes": "104664" }, { "name": "HTML", "bytes": "7932" }, { "name": "JavaScript", "bytes": "93545" }, { "name": "PHP", "bytes": "3379214" }, { "name": "Smarty", "bytes": "544125" } ], "symlink_target": "" }
package com.main.plistview; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; import android.widget.ListAdapter; import android.widget.ListView; public class PinnedHeaderListView extends ListView { public interface PinnedHeaderAdapter { public static final int PINNED_HEADER_GONE = 0; public static final int PINNED_HEADER_VISIBLE = 1; public static final int PINNED_HEADER_PUSHED_UP = 2; int getPinnedHeaderState(int position); void configurePinnedHeader(View header, int position, int alpha); } private static final int MAX_ALPHA = 255; private PinnedHeaderAdapter mAdapter; private View mHeaderView; private boolean mHeaderViewVisible; private int mHeaderViewWidth; private int mHeaderViewHeight; public PinnedHeaderListView(Context context) { super(context); } public PinnedHeaderListView(Context context, AttributeSet attrs) { super(context, attrs); } public PinnedHeaderListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (mHeaderView != null) { mHeaderView.layout(0, 0, mHeaderViewWidth, mHeaderViewHeight); configureHeaderView(getFirstVisiblePosition()); } } protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (mHeaderView != null) { measureChild(mHeaderView, widthMeasureSpec, heightMeasureSpec); mHeaderViewWidth = mHeaderView.getMeasuredWidth(); mHeaderViewHeight = mHeaderView.getMeasuredHeight(); } } public void setPinnedHeaderView(View view) { mHeaderView = view; if (mHeaderView != null) { setFadingEdgeLength(0); } requestLayout(); } public void setAdapter(ListAdapter adapter) { super.setAdapter(adapter); mAdapter = (PinnedHeaderAdapter) adapter; } public void configureHeaderView(int position) { if (mHeaderView == null) { return; } int state = mAdapter.getPinnedHeaderState(position); switch (state) { case PinnedHeaderAdapter.PINNED_HEADER_GONE: { mHeaderViewVisible = false; break; } case PinnedHeaderAdapter.PINNED_HEADER_VISIBLE: { mAdapter.configurePinnedHeader(mHeaderView, position, MAX_ALPHA); if (mHeaderView.getTop() != 0) { mHeaderView.layout(0, 0, mHeaderViewWidth, mHeaderViewHeight); } mHeaderViewVisible = true; break; } case PinnedHeaderAdapter.PINNED_HEADER_PUSHED_UP: { View firstView = getChildAt(0); int bottom = firstView.getBottom(); int headerHeight = mHeaderView.getHeight(); int y; int alpha; if (bottom < headerHeight) { y = (bottom - headerHeight); alpha = MAX_ALPHA * (headerHeight + y) / headerHeight; } else { y = 0; alpha = MAX_ALPHA; } mAdapter.configurePinnedHeader(mHeaderView, position, alpha); if (mHeaderView.getTop() != y) { mHeaderView.layout(0, y, mHeaderViewWidth, mHeaderViewHeight + y); } mHeaderViewVisible = true; break; } } } protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); if (mHeaderViewVisible) { drawChild(canvas, mHeaderView, getDrawingTime()); } } }
{ "content_hash": "29421928b814acd60d454b1bda3c2b36", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 72, "avg_line_length": 26.733870967741936, "alnum_prop": 0.7339366515837104, "repo_name": "PeoceWang/WeatherAPP", "id": "a497e930cdfd04994727040688d44f92aa693d20", "size": "3315", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/main/plistview/PinnedHeaderListView.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1173356" } ], "symlink_target": "" }
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.google.android.ads.nativetemplates"> <application android:supportsRtl="true"> </application> </manifest>
{ "content_hash": "069ca25b25779c1a7dff390fe7d8a30e", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 68, "avg_line_length": 24.5, "alnum_prop": 0.75, "repo_name": "googleads/googleads-mobile-android-native-templates", "id": "4169af54d15d97167d03aaa624c655b918f35439", "size": "196", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "nativetemplates/src/main/AndroidManifest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "17842" } ], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_MAIN_H #define BITCOIN_MAIN_H #include "bignum.h" #include "sync.h" #include "net.h" #include "script.h" #include "hashblock.h" #include <list> class CWallet; class CBlock; class CBlockIndex; class CKeyItem; class CReserveKey; class CAddress; class CInv; class CNode; struct CBlockIndexWorkComparator; /** The maximum allowed size for a serialized block, in bytes (network rule) */ static const unsigned int MAX_BLOCK_SIZE = 1000000; // 1000KB block hard limit /** Obsolete: maximum size for mined blocks */ static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/4; // 250KB block soft limit /** Default for -blockmaxsize, maximum size for mined blocks **/ static const unsigned int DEFAULT_BLOCK_MAX_SIZE = 250000; /** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/ static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 17000; /** The maximum size for transactions we're willing to relay/mine */ static const unsigned int MAX_STANDARD_TX_SIZE = 100000; /** The maximum allowed number of signature check operations in a block (network rule) */ static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50; /** The maximum number of orphan transactions kept in memory */ static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100; /** The maximum number of entries in an 'inv' protocol message */ static const unsigned int MAX_INV_SZ = 50000; /** The maximum size of a blk?????.dat file (since 0.8) */ static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */ static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */ static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB /** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */ static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF; /** Dust Soft Limit, allowed with additional fee per output */ static const int64 DUST_SOFT_LIMIT = 100000; // 0.001 FIT /** Dust Hard Limit, ignored as wallet inputs (mininput default) */ static const int64 DUST_HARD_LIMIT = 1000; // 0.00001 FIT mininput /** No amount larger than this (in satoshi) is valid */ static const int64 MAX_MONEY = 90000000 * COIN; inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); } /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */ static const int COINBASE_MATURITY = 100; /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */ static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC /** Maximum number of script-checking threads allowed */ static const int MAX_SCRIPTCHECK_THREADS = 16; #ifdef USE_UPNP static const int fHaveUPnP = true; #else static const int fHaveUPnP = false; #endif extern CScript COINBASE_FLAGS; extern CCriticalSection cs_main; extern std::map<uint256, CBlockIndex*> mapBlockIndex; extern std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; extern uint256 hashGenesisBlock; extern CBlockIndex* pindexGenesisBlock; extern int nBestHeight; extern uint256 nBestChainWork; extern uint256 nBestInvalidWork; extern uint256 hashBestChain; extern CBlockIndex* pindexBest; extern unsigned int nTransactionsUpdated; extern uint64 nLastBlockTx; extern uint64 nLastBlockSize; extern const std::string strMessageMagic; extern double dHashesPerSec; extern int64 nHPSTimerStart; extern int64 nTimeBestReceived; extern CCriticalSection cs_setpwalletRegistered; extern std::set<CWallet*> setpwalletRegistered; extern bool fImporting; extern bool fReindex; extern bool fBenchmark; extern int nScriptCheckThreads; extern bool fTxIndex; extern unsigned int nCoinCacheSize; // Settings extern int64 nTransactionFee; extern int64 nMinimumInputValue; // Minimum disk space required - used in CheckDiskSpace() static const uint64 nMinDiskSpace = 52428800; class CReserveKey; class CCoinsDB; class CBlockTreeDB; struct CDiskBlockPos; class CCoins; class CTxUndo; class CCoinsView; class CCoinsViewCache; class CScriptCheck; class CValidationState; struct CBlockTemplate; /** Register a wallet to receive updates from core */ void RegisterWallet(CWallet* pwalletIn); /** Unregister a wallet from core */ void UnregisterWallet(CWallet* pwalletIn); /** Push an updated transaction to all registered wallets */ void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false); /** Process an incoming block */ bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL); /** Check whether enough disk space is available for an incoming block */ bool CheckDiskSpace(uint64 nAdditionalBytes = 0); /** Open a block file (blk?????.dat) */ FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false); /** Open an undo file (rev?????.dat) */ FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false); /** Import blocks from an external file */ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL); /** Initialize a new block tree database + block data on disk */ bool InitBlockIndex(); /** Load the block tree and coins database from disk */ bool LoadBlockIndex(); /** Unload database information */ void UnloadBlockIndex(); /** Verify consistency of the block and coin databases */ bool VerifyDB(int nCheckLevel, int nCheckDepth); /** Print the loaded block tree */ void PrintBlockTree(); /** Find a block by height in the currently-connected chain */ CBlockIndex* FindBlockByHeight(int nHeight); /** Process protocol messages received from a given node */ bool ProcessMessages(CNode* pfrom); /** Send queued protocol messages to be sent to a give node */ bool SendMessages(CNode* pto, bool fSendTrickle); /** Run an instance of the script checking thread */ void ThreadScriptCheck(); /** Run the miner threads */ void GenerateBitcoins(bool fGenerate, CWallet* pwallet); /** Generate a new block, without valid proof-of-work */ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn); CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey); /** Modify the extranonce in a block */ void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce); /** Do mining precalculation */ void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1); /** Check mined block */ bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey); /** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */ bool CheckProofOfWork(uint256 hash, unsigned int nBits); /** Calculate the minimum amount of work a received block needs, without knowing its direct parent */ unsigned int ComputeMinWork(unsigned int nBase, int64 nTime); /** Get the number of active peers */ int GetNumBlocksOfPeers(); /** Check whether we are doing an initial block download (synchronizing from disk or network) */ bool IsInitialBlockDownload(); /** Format a string that describes several potential problems detected by the core */ std::string GetWarnings(std::string strFor); /** Retrieve a transaction (from memory pool, or from disk, if possible) */ bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false); /** Connect/disconnect blocks until pindexNew is the new tip of the active block chain */ bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew); /** Find the best known block, and make it the tip of the block chain */ bool ConnectBestBlock(CValidationState &state); /** Create a new block index entry for a given block hash */ CBlockIndex * InsertBlockIndex(uint256 hash); /** Verify a signature */ bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType); /** Abort with a message */ bool AbortNode(const std::string &msg); bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut); struct CDiskBlockPos { int nFile; unsigned int nPos; IMPLEMENT_SERIALIZE( READWRITE(VARINT(nFile)); READWRITE(VARINT(nPos)); ) CDiskBlockPos() { SetNull(); } CDiskBlockPos(int nFileIn, unsigned int nPosIn) { nFile = nFileIn; nPos = nPosIn; } friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) { return (a.nFile == b.nFile && a.nPos == b.nPos); } friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) { return !(a == b); } void SetNull() { nFile = -1; nPos = 0; } bool IsNull() const { return (nFile == -1); } }; struct CDiskTxPos : public CDiskBlockPos { unsigned int nTxOffset; // after header IMPLEMENT_SERIALIZE( READWRITE(*(CDiskBlockPos*)this); READWRITE(VARINT(nTxOffset)); ) CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) { } CDiskTxPos() { SetNull(); } void SetNull() { CDiskBlockPos::SetNull(); nTxOffset = 0; } }; /** An inpoint - a combination of a transaction and an index n into its vin */ class CInPoint { public: CTransaction* ptx; unsigned int n; CInPoint() { SetNull(); } CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; } void SetNull() { ptx = NULL; n = (unsigned int) -1; } bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); } }; /** An outpoint - a combination of a transaction hash and an index n into its vout */ class COutPoint { public: uint256 hash; unsigned int n; COutPoint() { SetNull(); } COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; } IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); ) void SetNull() { hash = 0; n = (unsigned int) -1; } bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); } friend bool operator<(const COutPoint& a, const COutPoint& b) { return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n)); } friend bool operator==(const COutPoint& a, const COutPoint& b) { return (a.hash == b.hash && a.n == b.n); } friend bool operator!=(const COutPoint& a, const COutPoint& b) { return !(a == b); } std::string ToString() const { return strprintf("COutPoint(%s, %u)", hash.ToString().c_str(), n); } void print() const { printf("%s\n", ToString().c_str()); } }; /** An input of a transaction. It contains the location of the previous * transaction's output that it claims and a signature that matches the * output's public key. */ class CTxIn { public: COutPoint prevout; CScript scriptSig; unsigned int nSequence; CTxIn() { nSequence = std::numeric_limits<unsigned int>::max(); } explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max()) { prevout = prevoutIn; scriptSig = scriptSigIn; nSequence = nSequenceIn; } CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max()) { prevout = COutPoint(hashPrevTx, nOut); scriptSig = scriptSigIn; nSequence = nSequenceIn; } IMPLEMENT_SERIALIZE ( READWRITE(prevout); READWRITE(scriptSig); READWRITE(nSequence); ) bool IsFinal() const { return (nSequence == std::numeric_limits<unsigned int>::max()); } friend bool operator==(const CTxIn& a, const CTxIn& b) { return (a.prevout == b.prevout && a.scriptSig == b.scriptSig && a.nSequence == b.nSequence); } friend bool operator!=(const CTxIn& a, const CTxIn& b) { return !(a == b); } std::string ToString() const { std::string str; str += "CTxIn("; str += prevout.ToString(); if (prevout.IsNull()) str += strprintf(", coinbase %s", HexStr(scriptSig).c_str()); else str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str()); if (nSequence != std::numeric_limits<unsigned int>::max()) str += strprintf(", nSequence=%u", nSequence); str += ")"; return str; } void print() const { printf("%s\n", ToString().c_str()); } }; /** An output of a transaction. It contains the public key that the next input * must be able to sign with to claim it. */ class CTxOut { public: int64 nValue; CScript scriptPubKey; CTxOut() { SetNull(); } CTxOut(int64 nValueIn, CScript scriptPubKeyIn) { nValue = nValueIn; scriptPubKey = scriptPubKeyIn; } IMPLEMENT_SERIALIZE ( READWRITE(nValue); READWRITE(scriptPubKey); ) void SetNull() { nValue = -1; scriptPubKey.clear(); } bool IsNull() const { return (nValue == -1); } uint256 GetHash() const { return SerializeHash(*this); } friend bool operator==(const CTxOut& a, const CTxOut& b) { return (a.nValue == b.nValue && a.scriptPubKey == b.scriptPubKey); } friend bool operator!=(const CTxOut& a, const CTxOut& b) { return !(a == b); } bool IsDust() const; std::string ToString() const { if (scriptPubKey.size() < 6) return "CTxOut(error)"; return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str()); } void print() const { printf("%s\n", ToString().c_str()); } }; enum GetMinFee_mode { GMF_BLOCK, GMF_RELAY, GMF_SEND, }; /** The basic transaction that is broadcasted on the network and contained in * blocks. A transaction can contain multiple inputs and outputs. */ class CTransaction { public: static int64 nMinTxFee; static int64 nMinRelayTxFee; static const int CURRENT_VERSION=1; int nVersion; std::vector<CTxIn> vin; std::vector<CTxOut> vout; unsigned int nLockTime; CTransaction() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(vin); READWRITE(vout); READWRITE(nLockTime); ) void SetNull() { nVersion = CTransaction::CURRENT_VERSION; vin.clear(); vout.clear(); nLockTime = 0; } bool IsNull() const { return (vin.empty() && vout.empty()); } uint256 GetHash() const { return SerializeHash(*this); } bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const { // Time based nLockTime implemented in 0.1.6 if (nLockTime == 0) return true; if (nBlockHeight == 0) nBlockHeight = nBestHeight; if (nBlockTime == 0) nBlockTime = GetAdjustedTime(); if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime)) return true; BOOST_FOREACH(const CTxIn& txin, vin) if (!txin.IsFinal()) return false; return true; } bool IsNewerThan(const CTransaction& old) const { if (vin.size() != old.vin.size()) return false; for (unsigned int i = 0; i < vin.size(); i++) if (vin[i].prevout != old.vin[i].prevout) return false; bool fNewer = false; unsigned int nLowest = std::numeric_limits<unsigned int>::max(); for (unsigned int i = 0; i < vin.size(); i++) { if (vin[i].nSequence != old.vin[i].nSequence) { if (vin[i].nSequence <= nLowest) { fNewer = false; nLowest = vin[i].nSequence; } if (old.vin[i].nSequence < nLowest) { fNewer = true; nLowest = old.vin[i].nSequence; } } } return fNewer; } bool IsCoinBase() const { return (vin.size() == 1 && vin[0].prevout.IsNull()); } /** Check for standard transaction types @return True if all outputs (scriptPubKeys) use only standard transaction forms */ bool IsStandard(std::string& strReason) const; bool IsStandard() const { std::string strReason; return IsStandard(strReason); } /** Check for standard transaction types @param[in] mapInputs Map of previous transactions that have outputs we're spending @return True if all inputs (scriptSigs) use only standard transaction forms */ bool AreInputsStandard(CCoinsViewCache& mapInputs) const; /** Count ECDSA signature operations the old-fashioned (pre-0.6) way @return number of sigops this transaction's outputs will produce when spent */ unsigned int GetLegacySigOpCount() const; /** Count ECDSA signature operations in pay-to-script-hash inputs. @param[in] mapInputs Map of previous transactions that have outputs we're spending @return maximum number of sigops required to validate this transaction's inputs */ unsigned int GetP2SHSigOpCount(CCoinsViewCache& mapInputs) const; /** Amount of bitcoins spent by this transaction. @return sum of all outputs (note: does not include fees) */ int64 GetValueOut() const { int64 nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { nValueOut += txout.nValue; if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut)) throw std::runtime_error("CTransaction::GetValueOut() : value out of range"); } return nValueOut; } /** Amount of bitcoins coming in to this transaction Note that lightweight clients may not know anything besides the hash of previous transactions, so may not be able to calculate this. @param[in] mapInputs Map of previous transactions that have outputs we're spending @return Sum of value of all inputs (scriptSigs) */ int64 GetValueIn(CCoinsViewCache& mapInputs) const; static bool AllowFree(double dPriority) { // Large (in bytes) low-priority (new, small-coin) transactions // need a fee. return dPriority > COIN * 1440 / 250; } // Apply the effects of this transaction on the UTXO set represented by view void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash); int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const; friend bool operator==(const CTransaction& a, const CTransaction& b) { return (a.nVersion == b.nVersion && a.vin == b.vin && a.vout == b.vout && a.nLockTime == b.nLockTime); } friend bool operator!=(const CTransaction& a, const CTransaction& b) { return !(a == b); } std::string ToString() const { std::string str; str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%u)\n", GetHash().ToString().c_str(), nVersion, vin.size(), vout.size(), nLockTime); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].ToString() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) str += " " + vout[i].ToString() + "\n"; return str; } void print() const { printf("%s", ToString().c_str()); } // Check whether all prevouts of this transaction are present in the UTXO set represented by view bool HaveInputs(CCoinsViewCache &view) const; // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts) // This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it // instead of being performed inline. bool CheckInputs(CValidationState &state, CCoinsViewCache &view, bool fScriptChecks = true, unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, std::vector<CScriptCheck> *pvChecks = NULL) const; // Apply the effects of this transaction on the UTXO set represented by view void UpdateCoins(CValidationState &state, CCoinsViewCache &view, CTxUndo &txundo, int nHeight, const uint256 &txhash) const; // Context-independent validity checks bool CheckTransaction(CValidationState &state) const; // Try to accept this transaction into the memory pool bool AcceptToMemoryPool(CValidationState &state, bool fCheckInputs=true, bool fLimitFree = true, bool* pfMissingInputs=NULL); protected: static const CTxOut &GetOutputFor(const CTxIn& input, CCoinsViewCache& mapInputs); }; /** wrapper for CTxOut that provides a more compact serialization */ class CTxOutCompressor { private: CTxOut &txout; public: static uint64 CompressAmount(uint64 nAmount); static uint64 DecompressAmount(uint64 nAmount); CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { } IMPLEMENT_SERIALIZE(({ if (!fRead) { uint64 nVal = CompressAmount(txout.nValue); READWRITE(VARINT(nVal)); } else { uint64 nVal = 0; READWRITE(VARINT(nVal)); txout.nValue = DecompressAmount(nVal); } CScriptCompressor cscript(REF(txout.scriptPubKey)); READWRITE(cscript); });) }; /** Undo information for a CTxIn * * Contains the prevout's CTxOut being spent, and if this was the * last output of the affected transaction, its metadata as well * (coinbase or not, height, transaction version) */ class CTxInUndo { public: CTxOut txout; // the txout data before being spent bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase unsigned int nHeight; // if the outpoint was the last unspent: its height int nVersion; // if the outpoint was the last unspent: its version CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {} CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { } unsigned int GetSerializeSize(int nType, int nVersion) const { return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) + (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) + ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion); } template<typename Stream> void Serialize(Stream &s, int nType, int nVersion) const { ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion); if (nHeight > 0) ::Serialize(s, VARINT(this->nVersion), nType, nVersion); ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion); } template<typename Stream> void Unserialize(Stream &s, int nType, int nVersion) { unsigned int nCode = 0; ::Unserialize(s, VARINT(nCode), nType, nVersion); nHeight = nCode / 2; fCoinBase = nCode & 1; if (nHeight > 0) ::Unserialize(s, VARINT(this->nVersion), nType, nVersion); ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion); } }; /** Undo information for a CTransaction */ class CTxUndo { public: // undo information for all txins std::vector<CTxInUndo> vprevout; IMPLEMENT_SERIALIZE( READWRITE(vprevout); ) }; /** Undo information for a CBlock */ class CBlockUndo { public: std::vector<CTxUndo> vtxundo; // for all but the coinbase IMPLEMENT_SERIALIZE( READWRITE(vtxundo); ) bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock) { // Open history file to append CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION); if (!fileout) return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed"); // Write index header unsigned char pchMessageStart[4]; GetMessageStart(pchMessageStart, true); unsigned int nSize = fileout.GetSerializeSize(*this); fileout << FLATDATA(pchMessageStart) << nSize; // Write undo data long fileOutPos = ftell(fileout); if (fileOutPos < 0) return error("CBlockUndo::WriteToDisk() : ftell failed"); pos.nPos = (unsigned int)fileOutPos; fileout << *this; // calculate & write checksum CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); hasher << hashBlock; hasher << *this; fileout << hasher.GetHash(); // Flush stdio buffers and commit to disk before returning fflush(fileout); if (!IsInitialBlockDownload()) FileCommit(fileout); return true; } bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock) { // Open history file to read CAutoFile filein = CAutoFile(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION); if (!filein) return error("CBlockUndo::ReadFromDisk() : OpenBlockFile failed"); // Read block uint256 hashChecksum; try { filein >> *this; filein >> hashChecksum; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Verify checksum CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); hasher << hashBlock; hasher << *this; if (hashChecksum != hasher.GetHash()) return error("CBlockUndo::ReadFromDisk() : checksum mismatch"); return true; } }; /** pruned version of CTransaction: only retains metadata and unspent transaction outputs * * Serialized format: * - VARINT(nVersion) * - VARINT(nCode) * - unspentness bitvector, for vout[2] and further; least significant byte first * - the non-spent CTxOuts (via CTxOutCompressor) * - VARINT(nHeight) * * The nCode value consists of: * - bit 1: IsCoinBase() * - bit 2: vout[0] is not spent * - bit 4: vout[1] is not spent * - The higher bits encode N, the number of non-zero bytes in the following bitvector. * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at * least one non-spent output). * * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e * <><><--------------------------------------------><----> * | \ | / * version code vout[1] height * * - version = 1 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow) * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35 * * 8358: compact amount representation for 60000000000 (600 BTC) * * 00: special txout type pay-to-pubkey-hash * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160 * - height = 203998 * * * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b * <><><--><--------------------------------------------------><----------------------------------------------><----> * / \ \ | | / * version code unspentness vout[4] vout[16] height * * - version = 1 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent, * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow) * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC) * * 00: special txout type pay-to-pubkey-hash * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4 * * bbd123: compact amount representation for 110397 (0.001 BTC) * * 00: special txout type pay-to-pubkey-hash * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160 * - height = 120891 */ class CCoins { public: // whether transaction is a coinbase bool fCoinBase; // unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped std::vector<CTxOut> vout; // at which height this transaction was included in the active block chain int nHeight; // version of the CTransaction; accesses to this value should probably check for nHeight as well, // as new tx version will probably only be introduced at certain heights int nVersion; // construct a CCoins from a CTransaction, at a given height CCoins(const CTransaction &tx, int nHeightIn) : fCoinBase(tx.IsCoinBase()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion) { } // empty constructor CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { } // remove spent outputs at the end of vout void Cleanup() { while (vout.size() > 0 && vout.back().IsNull()) vout.pop_back(); if (vout.empty()) std::vector<CTxOut>().swap(vout); } void swap(CCoins &to) { std::swap(to.fCoinBase, fCoinBase); to.vout.swap(vout); std::swap(to.nHeight, nHeight); std::swap(to.nVersion, nVersion); } // equality test friend bool operator==(const CCoins &a, const CCoins &b) { return a.fCoinBase == b.fCoinBase && a.nHeight == b.nHeight && a.nVersion == b.nVersion && a.vout == b.vout; } friend bool operator!=(const CCoins &a, const CCoins &b) { return !(a == b); } // calculate number of bytes for the bitmask, and its number of non-zero bytes // each bit in the bitmask represents the availability of one output, but the // availabilities of the first two outputs are encoded separately void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const { unsigned int nLastUsedByte = 0; for (unsigned int b = 0; 2+b*8 < vout.size(); b++) { bool fZero = true; for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) { if (!vout[2+b*8+i].IsNull()) { fZero = false; continue; } } if (!fZero) { nLastUsedByte = b + 1; nNonzeroBytes++; } } nBytes += nLastUsedByte; } bool IsCoinBase() const { return fCoinBase; } unsigned int GetSerializeSize(int nType, int nVersion) const { unsigned int nSize = 0; unsigned int nMaskSize = 0, nMaskCode = 0; CalcMaskSize(nMaskSize, nMaskCode); bool fFirst = vout.size() > 0 && !vout[0].IsNull(); bool fSecond = vout.size() > 1 && !vout[1].IsNull(); assert(fFirst || fSecond || nMaskCode); unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0); // version nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion); // size of header code nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion); // spentness bitmask nSize += nMaskSize; // txouts themself for (unsigned int i = 0; i < vout.size(); i++) if (!vout[i].IsNull()) nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion); // height nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion); return nSize; } template<typename Stream> void Serialize(Stream &s, int nType, int nVersion) const { unsigned int nMaskSize = 0, nMaskCode = 0; CalcMaskSize(nMaskSize, nMaskCode); bool fFirst = vout.size() > 0 && !vout[0].IsNull(); bool fSecond = vout.size() > 1 && !vout[1].IsNull(); assert(fFirst || fSecond || nMaskCode); unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0); // version ::Serialize(s, VARINT(this->nVersion), nType, nVersion); // header code ::Serialize(s, VARINT(nCode), nType, nVersion); // spentness bitmask for (unsigned int b = 0; b<nMaskSize; b++) { unsigned char chAvail = 0; for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) if (!vout[2+b*8+i].IsNull()) chAvail |= (1 << i); ::Serialize(s, chAvail, nType, nVersion); } // txouts themself for (unsigned int i = 0; i < vout.size(); i++) { if (!vout[i].IsNull()) ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion); } // coinbase height ::Serialize(s, VARINT(nHeight), nType, nVersion); } template<typename Stream> void Unserialize(Stream &s, int nType, int nVersion) { unsigned int nCode = 0; // version ::Unserialize(s, VARINT(this->nVersion), nType, nVersion); // header code ::Unserialize(s, VARINT(nCode), nType, nVersion); fCoinBase = nCode & 1; std::vector<bool> vAvail(2, false); vAvail[0] = nCode & 2; vAvail[1] = nCode & 4; unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1); // spentness bitmask while (nMaskCode > 0) { unsigned char chAvail = 0; ::Unserialize(s, chAvail, nType, nVersion); for (unsigned int p = 0; p < 8; p++) { bool f = (chAvail & (1 << p)) != 0; vAvail.push_back(f); } if (chAvail != 0) nMaskCode--; } // txouts themself vout.assign(vAvail.size(), CTxOut()); for (unsigned int i = 0; i < vAvail.size(); i++) { if (vAvail[i]) ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion); } // coinbase height ::Unserialize(s, VARINT(nHeight), nType, nVersion); Cleanup(); } // mark an outpoint spent, and construct undo information bool Spend(const COutPoint &out, CTxInUndo &undo) { if (out.n >= vout.size()) return false; if (vout[out.n].IsNull()) return false; undo = CTxInUndo(vout[out.n]); vout[out.n].SetNull(); Cleanup(); if (vout.size() == 0) { undo.nHeight = nHeight; undo.fCoinBase = fCoinBase; undo.nVersion = this->nVersion; } return true; } // mark a vout spent bool Spend(int nPos) { CTxInUndo undo; COutPoint out(0, nPos); return Spend(out, undo); } // check whether a particular output is still available bool IsAvailable(unsigned int nPos) const { return (nPos < vout.size() && !vout[nPos].IsNull()); } // check whether the entire CCoins is spent // note that only !IsPruned() CCoins can be serialized bool IsPruned() const { BOOST_FOREACH(const CTxOut &out, vout) if (!out.IsNull()) return false; return true; } }; /** Closure representing one script verification * Note that this stores references to the spending transaction */ class CScriptCheck { private: CScript scriptPubKey; const CTransaction *ptxTo; unsigned int nIn; unsigned int nFlags; int nHashType; public: CScriptCheck() {} CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) : scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { } bool operator()() const; void swap(CScriptCheck &check) { scriptPubKey.swap(check.scriptPubKey); std::swap(ptxTo, check.ptxTo); std::swap(nIn, check.nIn); std::swap(nFlags, check.nFlags); std::swap(nHashType, check.nHashType); } }; /** A transaction with a merkle branch linking it to the block chain. */ class CMerkleTx : public CTransaction { public: uint256 hashBlock; std::vector<uint256> vMerkleBranch; int nIndex; // memory only mutable bool fMerkleVerified; CMerkleTx() { Init(); } CMerkleTx(const CTransaction& txIn) : CTransaction(txIn) { Init(); } void Init() { hashBlock = 0; nIndex = -1; fMerkleVerified = false; } IMPLEMENT_SERIALIZE ( nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action); nVersion = this->nVersion; READWRITE(hashBlock); READWRITE(vMerkleBranch); READWRITE(nIndex); ) int SetMerkleBranch(const CBlock* pblock=NULL); int GetDepthInMainChain(CBlockIndex* &pindexRet) const; int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); } bool IsInMainChain() const { return GetDepthInMainChain() > 0; } int GetBlocksToMaturity() const; bool AcceptToMemoryPool(bool fCheckInputs=true, bool fLimitFree=true); }; /** Data structure that represents a partial merkle tree. * * It respresents a subset of the txid's of a known block, in a way that * allows recovery of the list of txid's and the merkle root, in an * authenticated way. * * The encoding works as follows: we traverse the tree in depth-first order, * storing a bit for each traversed node, signifying whether the node is the * parent of at least one matched leaf txid (or a matched txid itself). In * case we are at the leaf level, or this bit is 0, its merkle node hash is * stored, and its children are not explorer further. Otherwise, no hash is * stored, but we recurse into both (or the only) child branch. During * decoding, the same depth-first traversal is performed, consuming bits and * hashes as they written during encoding. * * The serialization is fixed and provides a hard guarantee about the * encoded size: * * SIZE <= 10 + ceil(32.25*N) * * Where N represents the number of leaf nodes of the partial tree. N itself * is bounded by: * * N <= total_transactions * N <= 1 + matched_transactions*tree_height * * The serialization format: * - uint32 total_transactions (4 bytes) * - varint number of hashes (1-3 bytes) * - uint256[] hashes in depth-first order (<= 32*N bytes) * - varint number of bytes of flag bits (1-3 bytes) * - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits) * The size constraints follow from this. */ class CPartialMerkleTree { protected: // the total number of transactions in the block unsigned int nTransactions; // node-is-parent-of-matched-txid bits std::vector<bool> vBits; // txids and internal hashes std::vector<uint256> vHash; // flag set when encountering invalid data bool fBad; // helper function to efficiently calculate the number of nodes at given height in the merkle tree unsigned int CalcTreeWidth(int height) { return (nTransactions+(1 << height)-1) >> height; } // calculate the hash of a node in the merkle tree (at leaf level: the txid's themself) uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid); // recursive function that traverses tree nodes, storing the data as bits and hashes void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch); // recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild. // it returns the hash of the respective node. uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch); public: // serialization implementation IMPLEMENT_SERIALIZE( READWRITE(nTransactions); READWRITE(vHash); std::vector<unsigned char> vBytes; if (fRead) { READWRITE(vBytes); CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this)); us.vBits.resize(vBytes.size() * 8); for (unsigned int p = 0; p < us.vBits.size(); p++) us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0; us.fBad = false; } else { vBytes.resize((vBits.size()+7)/8); for (unsigned int p = 0; p < vBits.size(); p++) vBytes[p / 8] |= vBits[p] << (p % 8); READWRITE(vBytes); } ) // Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch); CPartialMerkleTree(); // extract the matching txid's represented by this partial merkle tree. // returns the merkle root, or 0 in case of failure uint256 ExtractMatches(std::vector<uint256> &vMatch); }; /** Nodes collect new transactions into a block, hash them into a hash tree, * and scan through nonce values to make the block's hash satisfy proof-of-work * requirements. When they solve the proof-of-work, they broadcast the block * to everyone and the block is added to the block chain. The first transaction * in the block is a special one that creates a new coin owned by the creator * of the block. */ class CBlockHeader { public: // header static const int CURRENT_VERSION=2; int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; CBlockHeader() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(hashPrevBlock); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); ) void SetNull() { nVersion = CBlockHeader::CURRENT_VERSION; hashPrevBlock = 0; hashMerkleRoot = 0; nTime = 0; nBits = 0; nNonce = 0; } bool IsNull() const { return (nBits == 0); } uint256 GetHash() const { return Hash9(BEGIN(nVersion), END(nNonce)); } int64 GetBlockTime() const { return (int64)nTime; } void UpdateTime(const CBlockIndex* pindexPrev); }; class CBlock : public CBlockHeader { public: // network and disk std::vector<CTransaction> vtx; // memory only mutable std::vector<uint256> vMerkleTree; CBlock() { SetNull(); } CBlock(const CBlockHeader &header) { SetNull(); *((CBlockHeader*)this) = header; } IMPLEMENT_SERIALIZE ( READWRITE(*(CBlockHeader*)this); READWRITE(vtx); ) void SetNull() { CBlockHeader::SetNull(); vtx.clear(); vMerkleTree.clear(); } uint256 GetPoWHash() const { return GetHash(); } CBlockHeader GetBlockHeader() const { CBlockHeader block; block.nVersion = nVersion; block.hashPrevBlock = hashPrevBlock; block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } uint256 BuildMerkleTree() const { vMerkleTree.clear(); BOOST_FOREACH(const CTransaction& tx, vtx) vMerkleTree.push_back(tx.GetHash()); int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { for (int i = 0; i < nSize; i += 2) { int i2 = std::min(i+1, nSize-1); vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]), BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2]))); } j += nSize; } return (vMerkleTree.empty() ? 0 : vMerkleTree.back()); } const uint256 &GetTxHash(unsigned int nIndex) const { assert(vMerkleTree.size() > 0); // BuildMerkleTree must have been called first assert(nIndex < vtx.size()); return vMerkleTree[nIndex]; } std::vector<uint256> GetMerkleBranch(int nIndex) const { if (vMerkleTree.empty()) BuildMerkleTree(); std::vector<uint256> vMerkleBranch; int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { int i = std::min(nIndex^1, nSize-1); vMerkleBranch.push_back(vMerkleTree[j+i]); nIndex >>= 1; j += nSize; } return vMerkleBranch; } static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) { if (nIndex == -1) return 0; BOOST_FOREACH(const uint256& otherside, vMerkleBranch) { if (nIndex & 1) hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash)); else hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside)); nIndex >>= 1; } return hash; } bool WriteToDisk(CDiskBlockPos &pos) { // Open history file to append CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION); if (!fileout) return error("CBlock::WriteToDisk() : OpenBlockFile failed"); // Write index header unsigned char pchMessageStart[4]; GetMessageStart(pchMessageStart); unsigned int nSize = fileout.GetSerializeSize(*this); fileout << FLATDATA(pchMessageStart) << nSize; // Write block long fileOutPos = ftell(fileout); if (fileOutPos < 0) return error("CBlock::WriteToDisk() : ftell failed"); pos.nPos = (unsigned int)fileOutPos; fileout << *this; // Flush stdio buffers and commit to disk before returning fflush(fileout); if (!IsInitialBlockDownload()) FileCommit(fileout); return true; } bool ReadFromDisk(const CDiskBlockPos &pos) { SetNull(); // Open history file to read CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION); if (!filein) return error("CBlock::ReadFromDisk() : OpenBlockFile failed"); // Read block try { filein >> *this; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Check the header if (!CheckProofOfWork(GetPoWHash(), nBits)) return error("CBlock::ReadFromDisk() : errors in block header"); return true; } void print() const { printf("CBlock(hash=%s, input=%s, PoW=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu")\n", GetHash().ToString().c_str(), HexStr(BEGIN(nVersion),BEGIN(nVersion)+80,false).c_str(), GetPoWHash().ToString().c_str(), nVersion, hashPrevBlock.ToString().c_str(), hashMerkleRoot.ToString().c_str(), nTime, nBits, nNonce, vtx.size()); for (unsigned int i = 0; i < vtx.size(); i++) { printf(" "); vtx[i].print(); } printf(" vMerkleTree: "); for (unsigned int i = 0; i < vMerkleTree.size(); i++) printf("%s ", vMerkleTree[i].ToString().c_str()); printf("\n"); } /** Undo the effects of this block (with given index) on the UTXO set represented by coins. * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean * will be true if no problems were found. Otherwise, the return value will be false in case * of problems. Note that in any case, coins may be modified. */ bool DisconnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool *pfClean = NULL); // Apply the effects of this block (with given index) on the UTXO set represented by coins bool ConnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false); // Read a block from disk bool ReadFromDisk(const CBlockIndex* pindex); // Add this block to the block index, and if necessary, switch the active block chain to this bool AddToBlockIndex(CValidationState &state, const CDiskBlockPos &pos); // Context-independent validity checks bool CheckBlock(CValidationState &state, bool fCheckPOW=true, bool fCheckMerkleRoot=true) const; // Store block on disk // if dbp is provided, the file is known to already reside on disk bool AcceptBlock(CValidationState &state, CDiskBlockPos *dbp = NULL); }; class CBlockFileInfo { public: unsigned int nBlocks; // number of blocks stored in file unsigned int nSize; // number of used bytes of block file unsigned int nUndoSize; // number of used bytes in the undo file unsigned int nHeightFirst; // lowest height of block in file unsigned int nHeightLast; // highest height of block in file uint64 nTimeFirst; // earliest time of block in file uint64 nTimeLast; // latest time of block in file IMPLEMENT_SERIALIZE( READWRITE(VARINT(nBlocks)); READWRITE(VARINT(nSize)); READWRITE(VARINT(nUndoSize)); READWRITE(VARINT(nHeightFirst)); READWRITE(VARINT(nHeightLast)); READWRITE(VARINT(nTimeFirst)); READWRITE(VARINT(nTimeLast)); ) void SetNull() { nBlocks = 0; nSize = 0; nUndoSize = 0; nHeightFirst = 0; nHeightLast = 0; nTimeFirst = 0; nTimeLast = 0; } CBlockFileInfo() { SetNull(); } std::string ToString() const { return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst).c_str(), DateTimeStrFormat("%Y-%m-%d", nTimeLast).c_str()); } // update statistics (does not update nSize) void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) { if (nBlocks==0 || nHeightFirst > nHeightIn) nHeightFirst = nHeightIn; if (nBlocks==0 || nTimeFirst > nTimeIn) nTimeFirst = nTimeIn; nBlocks++; if (nHeightIn > nHeightFirst) nHeightLast = nHeightIn; if (nTimeIn > nTimeLast) nTimeLast = nTimeIn; } }; extern CCriticalSection cs_LastBlockFile; extern CBlockFileInfo infoLastBlockFile; extern int nLastBlockFile; enum BlockStatus { BLOCK_VALID_UNKNOWN = 0, BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30 BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok BLOCK_VALID_MASK = 7, BLOCK_HAVE_DATA = 8, // full block available in blk*.dat BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat BLOCK_HAVE_MASK = 24, BLOCK_FAILED_VALID = 32, // stage after last reached validness failed BLOCK_FAILED_CHILD = 64, // descends from failed block BLOCK_FAILED_MASK = 96 }; /** The block chain is a tree shaped structure starting with the * genesis block at the root, with each block potentially having multiple * candidates to be the next block. pprev and pnext link a path through the * main/longest chain. A blockindex may have multiple pprev pointing back * to it, but pnext will only point forward to the longest branch, or will * be null if the block is not part of the longest chain. */ class CBlockIndex { public: // pointer to the hash of the block, if any. memory is owned by this CBlockIndex const uint256* phashBlock; // pointer to the index of the predecessor of this block CBlockIndex* pprev; // (memory only) pointer to the index of the *active* successor of this block CBlockIndex* pnext; // height of the entry in the chain. The genesis block has height 0 int nHeight; // Which # file this block is stored in (blk?????.dat) int nFile; // Byte offset within blk?????.dat where this block's data is stored unsigned int nDataPos; // Byte offset within rev?????.dat where this block's undo data is stored unsigned int nUndoPos; // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block uint256 nChainWork; // Number of transactions in this block. // Note: in a potential headers-first mode, this number cannot be relied upon unsigned int nTx; // (memory only) Number of transactions in the chain up to and including this block unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030 // Verification status of this block. See enum BlockStatus unsigned int nStatus; // block header int nVersion; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; CBlockIndex() { phashBlock = NULL; pprev = NULL; pnext = NULL; nHeight = 0; nFile = 0; nDataPos = 0; nUndoPos = 0; nChainWork = 0; nTx = 0; nChainTx = 0; nStatus = 0; nVersion = 0; hashMerkleRoot = 0; nTime = 0; nBits = 0; nNonce = 0; } CBlockIndex(CBlockHeader& block) { phashBlock = NULL; pprev = NULL; pnext = NULL; nHeight = 0; nFile = 0; nDataPos = 0; nUndoPos = 0; nChainWork = 0; nTx = 0; nChainTx = 0; nStatus = 0; nVersion = block.nVersion; hashMerkleRoot = block.hashMerkleRoot; nTime = block.nTime; nBits = block.nBits; nNonce = block.nNonce; } CDiskBlockPos GetBlockPos() const { CDiskBlockPos ret; if (nStatus & BLOCK_HAVE_DATA) { ret.nFile = nFile; ret.nPos = nDataPos; } return ret; } CDiskBlockPos GetUndoPos() const { CDiskBlockPos ret; if (nStatus & BLOCK_HAVE_UNDO) { ret.nFile = nFile; ret.nPos = nUndoPos; } return ret; } CBlockHeader GetBlockHeader() const { CBlockHeader block; block.nVersion = nVersion; if (pprev) block.hashPrevBlock = pprev->GetBlockHash(); block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } uint256 GetBlockHash() const { return *phashBlock; } int64 GetBlockTime() const { return (int64)nTime; } CBigNum GetBlockWork() const { CBigNum bnTarget; bnTarget.SetCompact(nBits); if (bnTarget <= 0) return 0; return (CBigNum(1)<<256) / (bnTarget+1); } bool IsInMainChain() const { return (pnext || this == pindexBest); } bool CheckIndex() const { /** Scrypt is used for block proof-of-work, but for purposes of performance the index internally uses sha256. * This check was considered unneccessary given the other safeguards like the genesis and checkpoints. */ return true; // return CheckProofOfWork(GetBlockHash(), nBits); } enum { nMedianTimeSpan=11 }; int64 GetMedianTimePast() const { int64 pmedian[nMedianTimeSpan]; int64* pbegin = &pmedian[nMedianTimeSpan]; int64* pend = &pmedian[nMedianTimeSpan]; const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev) *(--pbegin) = pindex->GetBlockTime(); std::sort(pbegin, pend); return pbegin[(pend - pbegin)/2]; } int64 GetMedianTime() const { const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan/2; i++) { if (!pindex->pnext) return GetBlockTime(); pindex = pindex->pnext; } return pindex->GetMedianTimePast(); } /** * Returns true if there are nRequired or more blocks of minVersion or above * in the last nToCheck blocks, starting at pstart and going backwards. */ static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck); std::string ToString() const { return strprintf("CBlockIndex(pprev=%p, pnext=%p, nHeight=%d, merkle=%s, hashBlock=%s)", pprev, pnext, nHeight, hashMerkleRoot.ToString().c_str(), GetBlockHash().ToString().c_str()); } void print() const { printf("%s\n", ToString().c_str()); } }; struct CBlockIndexWorkComparator { bool operator()(CBlockIndex *pa, CBlockIndex *pb) { if (pa->nChainWork > pb->nChainWork) return false; if (pa->nChainWork < pb->nChainWork) return true; if (pa->GetBlockHash() < pb->GetBlockHash()) return false; if (pa->GetBlockHash() > pb->GetBlockHash()) return true; return false; // identical blocks } }; /** Used to marshal pointers into hashes for db storage. */ class CDiskBlockIndex : public CBlockIndex { public: uint256 hashPrev; CDiskBlockIndex() { hashPrev = 0; } explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) { hashPrev = (pprev ? pprev->GetBlockHash() : 0); } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(VARINT(nVersion)); READWRITE(VARINT(nHeight)); READWRITE(VARINT(nStatus)); READWRITE(VARINT(nTx)); if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO)) READWRITE(VARINT(nFile)); if (nStatus & BLOCK_HAVE_DATA) READWRITE(VARINT(nDataPos)); if (nStatus & BLOCK_HAVE_UNDO) READWRITE(VARINT(nUndoPos)); // block header READWRITE(this->nVersion); READWRITE(hashPrev); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); ) uint256 GetBlockHash() const { CBlockHeader block; block.nVersion = nVersion; block.hashPrevBlock = hashPrev; block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block.GetHash(); } std::string ToString() const { std::string str = "CDiskBlockIndex("; str += CBlockIndex::ToString(); str += strprintf("\n hashBlock=%s, hashPrev=%s)", GetBlockHash().ToString().c_str(), hashPrev.ToString().c_str()); return str; } void print() const { printf("%s\n", ToString().c_str()); } }; /** Capture information about block/transaction validation */ class CValidationState { private: enum mode_state { MODE_VALID, // everything ok MODE_INVALID, // network rule violation (DoS value may be set) MODE_ERROR, // run-time error } mode; int nDoS; bool corruptionPossible; public: CValidationState() : mode(MODE_VALID), nDoS(0), corruptionPossible(false) {} bool DoS(int level, bool ret = false, bool corruptionIn = false) { if (mode == MODE_ERROR) return ret; nDoS += level; mode = MODE_INVALID; corruptionPossible = corruptionIn; return ret; } bool Invalid(bool ret = false) { return DoS(0, ret); } bool Error() { mode = MODE_ERROR; return false; } bool Abort(const std::string &msg) { AbortNode(msg); return Error(); } bool IsValid() { return mode == MODE_VALID; } bool IsInvalid() { return mode == MODE_INVALID; } bool IsError() { return mode == MODE_ERROR; } bool IsInvalid(int &nDoSOut) { if (IsInvalid()) { nDoSOut = nDoS; return true; } return false; } bool CorruptionPossible() { return corruptionPossible; } }; /** Describes a place in the block chain to another node such that if the * other node doesn't have the same branch, it can find a recent common trunk. * The further back it is, the further before the fork it may be. */ class CBlockLocator { protected: std::vector<uint256> vHave; public: CBlockLocator() { } explicit CBlockLocator(const CBlockIndex* pindex) { Set(pindex); } explicit CBlockLocator(uint256 hashBlock) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end()) Set((*mi).second); } CBlockLocator(const std::vector<uint256>& vHaveIn) { vHave = vHaveIn; } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(vHave); ) void SetNull() { vHave.clear(); } bool IsNull() { return vHave.empty(); } void Set(const CBlockIndex* pindex) { vHave.clear(); int nStep = 1; while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Exponentially larger steps back for (int i = 0; pindex && i < nStep; i++) pindex = pindex->pprev; if (vHave.size() > 10) nStep *= 2; } vHave.push_back(hashGenesisBlock); } int GetDistanceBack() { // Retrace how far back it was in the sender's branch int nDistance = 0; int nStep = 1; BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return nDistance; } nDistance += nStep; if (nDistance > 10) nStep *= 2; } return nDistance; } CBlockIndex* GetBlockIndex() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return pindex; } } return pindexGenesisBlock; } uint256 GetBlockHash() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return hash; } } return hashGenesisBlock; } int GetHeight() { CBlockIndex* pindex = GetBlockIndex(); if (!pindex) return 0; return pindex->nHeight; } }; class CTxMemPool { public: mutable CCriticalSection cs; std::map<uint256, CTransaction> mapTx; std::map<COutPoint, CInPoint> mapNextTx; bool accept(CValidationState &state, CTransaction &tx, bool fCheckInputs, bool fLimitFree, bool* pfMissingInputs); bool addUnchecked(const uint256& hash, const CTransaction &tx); bool remove(const CTransaction &tx, bool fRecursive = false); bool removeConflicts(const CTransaction &tx); void clear(); void queryHashes(std::vector<uint256>& vtxid); void pruneSpent(const uint256& hash, CCoins &coins); unsigned long size() { LOCK(cs); return mapTx.size(); } bool exists(uint256 hash) { return (mapTx.count(hash) != 0); } CTransaction& lookup(uint256 hash) { return mapTx[hash]; } }; extern CTxMemPool mempool; struct CCoinsStats { int nHeight; uint256 hashBlock; uint64 nTransactions; uint64 nTransactionOutputs; uint64 nSerializedSize; uint256 hashSerialized; int64 nTotalAmount; CCoinsStats() : nHeight(0), hashBlock(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), hashSerialized(0), nTotalAmount(0) {} }; /** Abstract view on the open txout dataset. */ class CCoinsView { public: // Retrieve the CCoins (unspent transaction outputs) for a given txid virtual bool GetCoins(const uint256 &txid, CCoins &coins); // Modify the CCoins for a given txid virtual bool SetCoins(const uint256 &txid, const CCoins &coins); // Just check whether we have data for a given txid. // This may (but cannot always) return true for fully spent transactions virtual bool HaveCoins(const uint256 &txid); // Retrieve the block index whose state this CCoinsView currently represents virtual CBlockIndex *GetBestBlock(); // Modify the currently active block index virtual bool SetBestBlock(CBlockIndex *pindex); // Do a bulk modification (multiple SetCoins + one SetBestBlock) virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex); // Calculate statistics about the unspent transaction output set virtual bool GetStats(CCoinsStats &stats); // As we use CCoinsViews polymorphically, have a virtual destructor virtual ~CCoinsView() {} }; /** CCoinsView backed by another CCoinsView */ class CCoinsViewBacked : public CCoinsView { protected: CCoinsView *base; public: CCoinsViewBacked(CCoinsView &viewIn); bool GetCoins(const uint256 &txid, CCoins &coins); bool SetCoins(const uint256 &txid, const CCoins &coins); bool HaveCoins(const uint256 &txid); CBlockIndex *GetBestBlock(); bool SetBestBlock(CBlockIndex *pindex); void SetBackend(CCoinsView &viewIn); bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex); bool GetStats(CCoinsStats &stats); }; /** CCoinsView that adds a memory cache for transactions to another CCoinsView */ class CCoinsViewCache : public CCoinsViewBacked { protected: CBlockIndex *pindexTip; std::map<uint256,CCoins> cacheCoins; public: CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false); // Standard CCoinsView methods bool GetCoins(const uint256 &txid, CCoins &coins); bool SetCoins(const uint256 &txid, const CCoins &coins); bool HaveCoins(const uint256 &txid); CBlockIndex *GetBestBlock(); bool SetBestBlock(CBlockIndex *pindex); bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex); // Return a modifiable reference to a CCoins. Check HaveCoins first. // Many methods explicitly require a CCoinsViewCache because of this method, to reduce // copying. CCoins &GetCoins(const uint256 &txid); // Push the modifications applied to this cache to its base. // Failure to call this method before destruction will cause the changes to be forgotten. bool Flush(); // Calculate the size of the cache (in number of transactions) unsigned int GetCacheSize(); private: std::map<uint256,CCoins>::iterator FetchCoins(const uint256 &txid); }; /** CCoinsView that brings transactions from a memorypool into view. It does not check for spendings by memory pool transactions. */ class CCoinsViewMemPool : public CCoinsViewBacked { protected: CTxMemPool &mempool; public: CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn); bool GetCoins(const uint256 &txid, CCoins &coins); bool HaveCoins(const uint256 &txid); }; /** Global variable that points to the active CCoinsView (protected by cs_main) */ extern CCoinsViewCache *pcoinsTip; /** Global variable that points to the active block tree (protected by cs_main) */ extern CBlockTreeDB *pblocktree; struct CBlockTemplate { CBlock block; std::vector<int64_t> vTxFees; std::vector<int64_t> vTxSigOps; }; #if defined(_M_IX86) || defined(__i386__) || defined(__i386) || defined(_M_X64) || defined(__x86_64__) || defined(_M_AMD64) extern unsigned int cpuid_edx; #endif /** Used to relay blocks as header + vector<merkle branch> * to filtered nodes. */ class CMerkleBlock { public: // Public only for unit testing CBlockHeader header; CPartialMerkleTree txn; public: // Public only for unit testing and relay testing // (not relayed) std::vector<std::pair<unsigned int, uint256> > vMatchedTxn; // Create from a CBlock, filtering transactions according to filter // Note that this will call IsRelevantAndUpdate on the filter for each transaction, // thus the filter will likely be modified. CMerkleBlock(const CBlock& block, CBloomFilter& filter); IMPLEMENT_SERIALIZE ( READWRITE(header); READWRITE(txn); ) }; #endif
{ "content_hash": "34959f15a0b6e36f682335e19ae60adb", "timestamp": "", "source": "github", "line_count": 2289, "max_line_length": 239, "avg_line_length": 31.499781564001747, "alnum_prop": 0.6182405725143197, "repo_name": "fitcoins/fitcoin", "id": "0906f63ba99bbe20140e5ced8a3d3735c8f50a6d", "size": "72103", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "765626" }, { "name": "C++", "bytes": "2530741" }, { "name": "CSS", "bytes": "1127" }, { "name": "IDL", "bytes": "14828" }, { "name": "Objective-C++", "bytes": "5864" }, { "name": "Python", "bytes": "37260" }, { "name": "Shell", "bytes": "9701" }, { "name": "TypeScript", "bytes": "5232065" } ], "symlink_target": "" }
class Rbdl < Formula desc "RBDL - Rigid Body Dynamics Library" homepage "https://bitbucket.org/rbdl/rbdl" url "https://bitbucket.org/rbdl/rbdl", :using => :hg, :tag => "v2.5.0" head "https://bitbucket.org/rbdl/rbdl", :using => :hg, :branch => "default" version "2.5.0" depends_on "cmake" => :build depends_on "eigen" depends_on "unittest-cpp" => :recommended def install cmake_args = std_cmake_args + %W[ ] mkdir "build" do system "cmake", "-G", "Unix Makefiles", "..", *cmake_args system "make" system "make", "install" end end test do system "false" end end
{ "content_hash": "f4aa30bdb48cdfff05f27deafd8936c9", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 77, "avg_line_length": 24.26923076923077, "alnum_prop": 0.6022187004754358, "repo_name": "ahundt/homebrew-robotics", "id": "5ebc176f2190c16e9afaebab7db889d727458bbe", "size": "631", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rbdl.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ruby", "bytes": "30751" }, { "name": "Shell", "bytes": "10885" } ], "symlink_target": "" }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.FormControlLabelRoot = void 0; var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose")); var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var React = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _clsx = _interopRequireDefault(require("clsx")); var _utils = require("@material-ui/utils"); var _unstyled = require("@material-ui/unstyled"); var _FormControl = require("../FormControl"); var _Typography = _interopRequireDefault(require("../Typography")); var _capitalize = _interopRequireDefault(require("../utils/capitalize")); var _styled = _interopRequireDefault(require("../styles/styled")); var _useThemeProps = _interopRequireDefault(require("../styles/useThemeProps")); var _formControlLabelClasses = _interopRequireWildcard(require("./formControlLabelClasses")); var _jsxRuntime = require("react/jsx-runtime"); const _excluded = ["checked", "className", "componentProps", "control", "disabled", "disableTypography", "inputRef", "label", "labelPlacement", "name", "onChange", "value"]; function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } const useUtilityClasses = styleProps => { const { classes, disabled, labelPlacement } = styleProps; const slots = { root: ['root', disabled && 'disabled', `labelPlacement${(0, _capitalize.default)(labelPlacement)}`], label: ['label', disabled && 'disabled'] }; return (0, _unstyled.unstable_composeClasses)(slots, _formControlLabelClasses.getFormControlLabelUtilityClasses, classes); }; const FormControlLabelRoot = (0, _styled.default)('label', { name: 'MuiFormControlLabel', slot: 'Root', overridesResolver: (props, styles) => { const { styleProps } = props; return (0, _extends2.default)({ [`& .${_formControlLabelClasses.default.label}`]: styles.label }, styles.root, styles[`labelPlacement${(0, _capitalize.default)(styleProps.labelPlacement)}`]); } })(({ theme, styleProps }) => (0, _extends2.default)({ display: 'inline-flex', alignItems: 'center', cursor: 'pointer', // For correct alignment with the text. verticalAlign: 'middle', WebkitTapHighlightColor: 'transparent', marginLeft: -11, marginRight: 16, // used for row presentation of radio/checkbox [`&.${_formControlLabelClasses.default.disabled}`]: { cursor: 'default' } }, styleProps.labelPlacement === 'start' && { flexDirection: 'row-reverse', marginLeft: 16, // used for row presentation of radio/checkbox marginRight: -11 }, styleProps.labelPlacement === 'top' && { flexDirection: 'column-reverse', marginLeft: 16 }, styleProps.labelPlacement === 'bottom' && { flexDirection: 'column', marginLeft: 16 }, { [`& .${_formControlLabelClasses.default.label}`]: { [`&.${_formControlLabelClasses.default.disabled}`]: { color: theme.palette.text.disabled } } })); /** * Drop-in replacement of the `Radio`, `Switch` and `Checkbox` component. * Use this component if you want to display an extra label. */ exports.FormControlLabelRoot = FormControlLabelRoot; const FormControlLabel = /*#__PURE__*/React.forwardRef(function FormControlLabel(inProps, ref) { const props = (0, _useThemeProps.default)({ props: inProps, name: 'MuiFormControlLabel' }); const { className, componentProps = {}, control, disabled: disabledProp, disableTypography, label, labelPlacement = 'end' } = props, other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded); const muiFormControl = (0, _FormControl.useFormControl)(); let disabled = disabledProp; if (typeof disabled === 'undefined' && typeof control.props.disabled !== 'undefined') { disabled = control.props.disabled; } if (typeof disabled === 'undefined' && muiFormControl) { disabled = muiFormControl.disabled; } const controlProps = { disabled }; ['checked', 'name', 'onChange', 'value', 'inputRef'].forEach(key => { if (typeof control.props[key] === 'undefined' && typeof props[key] !== 'undefined') { controlProps[key] = props[key]; } }); const styleProps = (0, _extends2.default)({}, props, { disabled, label, labelPlacement }); const classes = useUtilityClasses(styleProps); return /*#__PURE__*/(0, _jsxRuntime.jsxs)(FormControlLabelRoot, (0, _extends2.default)({ className: (0, _clsx.default)(classes.root, className), styleProps: styleProps, ref: ref }, other, { children: [/*#__PURE__*/React.cloneElement(control, controlProps), label.type === _Typography.default || disableTypography ? label : /*#__PURE__*/(0, _jsxRuntime.jsx)(_Typography.default, (0, _extends2.default)({ component: "span", className: classes.label }, componentProps.typography, { children: label }))] })); }); process.env.NODE_ENV !== "production" ? FormControlLabel.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * If `true`, the component appears selected. */ checked: _propTypes.default.bool, /** * Override or extend the styles applied to the component. */ classes: _propTypes.default.object, /** * @ignore */ className: _propTypes.default.string, /** * The props used for each slot inside. * @default {} */ componentProps: _propTypes.default.object, /** * A control element. For instance, it can be a `Radio`, a `Switch` or a `Checkbox`. */ control: _propTypes.default.element.isRequired, /** * If `true`, the control is disabled. */ disabled: _propTypes.default.bool, /** * If `true`, the label is rendered as it is passed without an additional typography node. */ disableTypography: _propTypes.default.bool, /** * Pass a ref to the `input` element. */ inputRef: _utils.refType, /** * The text to be used in an enclosing label element. */ label: _propTypes.default.node, /** * The position of the label. * @default 'end' */ labelPlacement: _propTypes.default.oneOf(['bottom', 'end', 'start', 'top']), /** * @ignore */ name: _propTypes.default.string, /** * Callback fired when the state is changed. * * @param {object} event The event source of the callback. * You can pull out the new checked state by accessing `event.target.checked` (boolean). */ onChange: _propTypes.default.func, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: _propTypes.default.object, /** * The value of the component. */ value: _propTypes.default.any } : void 0; var _default = FormControlLabel; exports.default = _default;
{ "content_hash": "6cd05df9db02388000eff0a962772e1e", "timestamp": "", "source": "github", "line_count": 245, "max_line_length": 804, "avg_line_length": 33.86530612244898, "alnum_prop": 0.6648186091358322, "repo_name": "cdnjs/cdnjs", "id": "f2ad098f414a670c2cefed35bb493280fddbeb7d", "size": "8297", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ajax/libs/material-ui/5.0.0-alpha.38/node/FormControlLabel/FormControlLabel.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.8 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ using System; using System.Runtime.InteropServices; public class aiTextureVector : IDisposable, System.Collections.IEnumerable #if !SWIG_DOTNET_1 , System.Collections.Generic.IList<aiTexture> #endif { private HandleRef swigCPtr; protected bool swigCMemOwn; internal aiTextureVector(IntPtr cPtr, bool cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = new HandleRef(this, cPtr); } internal static HandleRef getCPtr(aiTextureVector obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } ~aiTextureVector() { Dispose(); } public virtual void Dispose() { lock(this) { if (swigCPtr.Handle != IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; AssimpPINVOKE.delete_aiTextureVector(swigCPtr); } swigCPtr = new HandleRef(null, IntPtr.Zero); } GC.SuppressFinalize(this); } } public aiTextureVector(System.Collections.ICollection c) : this() { if (c == null) throw new ArgumentNullException("c"); foreach (aiTexture element in c) { this.Add(element); } } public bool IsFixedSize { get { return false; } } public bool IsReadOnly { get { return false; } } public aiTexture this[int index] { get { return getitem(index); } set { setitem(index, value); } } public int Capacity { get { return (int)capacity(); } set { if (value < size()) throw new ArgumentOutOfRangeException("Capacity"); reserve((uint)value); } } public int Count { get { return (int)size(); } } public bool IsSynchronized { get { return false; } } #if SWIG_DOTNET_1 public void CopyTo(System.Array array) #else public void CopyTo(aiTexture[] array) #endif { CopyTo(0, array, 0, this.Count); } #if SWIG_DOTNET_1 public void CopyTo(System.Array array, int arrayIndex) #else public void CopyTo(aiTexture[] array, int arrayIndex) #endif { CopyTo(0, array, arrayIndex, this.Count); } #if SWIG_DOTNET_1 public void CopyTo(int index, System.Array array, int arrayIndex, int count) #else public void CopyTo(int index, aiTexture[] array, int arrayIndex, int count) #endif { if (array == null) throw new ArgumentNullException("array"); if (index < 0) throw new ArgumentOutOfRangeException("index", "Value is less than zero"); if (arrayIndex < 0) throw new ArgumentOutOfRangeException("arrayIndex", "Value is less than zero"); if (count < 0) throw new ArgumentOutOfRangeException("count", "Value is less than zero"); if (array.Rank > 1) throw new ArgumentException("Multi dimensional array.", "array"); if (index+count > this.Count || arrayIndex+count > array.Length) throw new ArgumentException("Number of elements to copy is too large."); for (int i=0; i<count; i++) array.SetValue(getitemcopy(index+i), arrayIndex+i); } #if !SWIG_DOTNET_1 System.Collections.Generic.IEnumerator<aiTexture> System.Collections.Generic.IEnumerable<aiTexture>.GetEnumerator() { return new aiTextureVectorEnumerator(this); } #endif System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new aiTextureVectorEnumerator(this); } public aiTextureVectorEnumerator GetEnumerator() { return new aiTextureVectorEnumerator(this); } // Type-safe enumerator /// Note that the IEnumerator documentation requires an InvalidOperationException to be thrown /// whenever the collection is modified. This has been done for changes in the size of the /// collection but not when one of the elements of the collection is modified as it is a bit /// tricky to detect unmanaged code that modifies the collection under our feet. public sealed class aiTextureVectorEnumerator : System.Collections.IEnumerator #if !SWIG_DOTNET_1 , System.Collections.Generic.IEnumerator<aiTexture> #endif { private aiTextureVector collectionRef; private int currentIndex; private object currentObject; private int currentSize; public aiTextureVectorEnumerator(aiTextureVector collection) { collectionRef = collection; currentIndex = -1; currentObject = null; currentSize = collectionRef.Count; } // Type-safe iterator Current public aiTexture Current { get { if (currentIndex == -1) throw new InvalidOperationException("Enumeration not started."); if (currentIndex > currentSize - 1) throw new InvalidOperationException("Enumeration finished."); if (currentObject == null) throw new InvalidOperationException("Collection modified."); return (aiTexture)currentObject; } } // Type-unsafe IEnumerator.Current object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { int size = collectionRef.Count; bool moveOkay = (currentIndex+1 < size) && (size == currentSize); if (moveOkay) { currentIndex++; currentObject = collectionRef[currentIndex]; } else { currentObject = null; } return moveOkay; } public void Reset() { currentIndex = -1; currentObject = null; if (collectionRef.Count != currentSize) { throw new InvalidOperationException("Collection modified."); } } #if !SWIG_DOTNET_1 public void Dispose() { currentIndex = -1; currentObject = null; } #endif } public void Clear() { AssimpPINVOKE.aiTextureVector_Clear(swigCPtr); } public void Add(aiTexture x) { AssimpPINVOKE.aiTextureVector_Add(swigCPtr, aiTexture.getCPtr(x)); } private uint size() { uint ret = AssimpPINVOKE.aiTextureVector_size(swigCPtr); return ret; } private uint capacity() { uint ret = AssimpPINVOKE.aiTextureVector_capacity(swigCPtr); return ret; } private void reserve(uint n) { AssimpPINVOKE.aiTextureVector_reserve(swigCPtr, n); } public aiTextureVector() : this(AssimpPINVOKE.new_aiTextureVector__SWIG_0(), true) { } public aiTextureVector(aiTextureVector other) : this(AssimpPINVOKE.new_aiTextureVector__SWIG_1(aiTextureVector.getCPtr(other)), true) { if (AssimpPINVOKE.SWIGPendingException.Pending) throw AssimpPINVOKE.SWIGPendingException.Retrieve(); } public aiTextureVector(int capacity) : this(AssimpPINVOKE.new_aiTextureVector__SWIG_2(capacity), true) { if (AssimpPINVOKE.SWIGPendingException.Pending) throw AssimpPINVOKE.SWIGPendingException.Retrieve(); } private aiTexture getitemcopy(int index) { IntPtr cPtr = AssimpPINVOKE.aiTextureVector_getitemcopy(swigCPtr, index); aiTexture ret = (cPtr == IntPtr.Zero) ? null : new aiTexture(cPtr, false); if (AssimpPINVOKE.SWIGPendingException.Pending) throw AssimpPINVOKE.SWIGPendingException.Retrieve(); return ret; } private aiTexture getitem(int index) { IntPtr cPtr = AssimpPINVOKE.aiTextureVector_getitem(swigCPtr, index); aiTexture ret = (cPtr == IntPtr.Zero) ? null : new aiTexture(cPtr, false); if (AssimpPINVOKE.SWIGPendingException.Pending) throw AssimpPINVOKE.SWIGPendingException.Retrieve(); return ret; } private void setitem(int index, aiTexture val) { AssimpPINVOKE.aiTextureVector_setitem(swigCPtr, index, aiTexture.getCPtr(val)); if (AssimpPINVOKE.SWIGPendingException.Pending) throw AssimpPINVOKE.SWIGPendingException.Retrieve(); } public void AddRange(aiTextureVector values) { AssimpPINVOKE.aiTextureVector_AddRange(swigCPtr, aiTextureVector.getCPtr(values)); if (AssimpPINVOKE.SWIGPendingException.Pending) throw AssimpPINVOKE.SWIGPendingException.Retrieve(); } public aiTextureVector GetRange(int index, int count) { IntPtr cPtr = AssimpPINVOKE.aiTextureVector_GetRange(swigCPtr, index, count); aiTextureVector ret = (cPtr == IntPtr.Zero) ? null : new aiTextureVector(cPtr, true); if (AssimpPINVOKE.SWIGPendingException.Pending) throw AssimpPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void Insert(int index, aiTexture x) { AssimpPINVOKE.aiTextureVector_Insert(swigCPtr, index, aiTexture.getCPtr(x)); if (AssimpPINVOKE.SWIGPendingException.Pending) throw AssimpPINVOKE.SWIGPendingException.Retrieve(); } public void InsertRange(int index, aiTextureVector values) { AssimpPINVOKE.aiTextureVector_InsertRange(swigCPtr, index, aiTextureVector.getCPtr(values)); if (AssimpPINVOKE.SWIGPendingException.Pending) throw AssimpPINVOKE.SWIGPendingException.Retrieve(); } public void RemoveAt(int index) { AssimpPINVOKE.aiTextureVector_RemoveAt(swigCPtr, index); if (AssimpPINVOKE.SWIGPendingException.Pending) throw AssimpPINVOKE.SWIGPendingException.Retrieve(); } public void RemoveRange(int index, int count) { AssimpPINVOKE.aiTextureVector_RemoveRange(swigCPtr, index, count); if (AssimpPINVOKE.SWIGPendingException.Pending) throw AssimpPINVOKE.SWIGPendingException.Retrieve(); } public static aiTextureVector Repeat(aiTexture value, int count) { IntPtr cPtr = AssimpPINVOKE.aiTextureVector_Repeat(aiTexture.getCPtr(value), count); aiTextureVector ret = (cPtr == IntPtr.Zero) ? null : new aiTextureVector(cPtr, true); if (AssimpPINVOKE.SWIGPendingException.Pending) throw AssimpPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void Reverse() { AssimpPINVOKE.aiTextureVector_Reverse__SWIG_0(swigCPtr); } public void Reverse(int index, int count) { AssimpPINVOKE.aiTextureVector_Reverse__SWIG_1(swigCPtr, index, count); if (AssimpPINVOKE.SWIGPendingException.Pending) throw AssimpPINVOKE.SWIGPendingException.Retrieve(); } public void SetRange(int index, aiTextureVector values) { AssimpPINVOKE.aiTextureVector_SetRange(swigCPtr, index, aiTextureVector.getCPtr(values)); if (AssimpPINVOKE.SWIGPendingException.Pending) throw AssimpPINVOKE.SWIGPendingException.Retrieve(); } public bool Contains(aiTexture value) { bool ret = AssimpPINVOKE.aiTextureVector_Contains(swigCPtr, aiTexture.getCPtr(value)); return ret; } public int IndexOf(aiTexture value) { int ret = AssimpPINVOKE.aiTextureVector_IndexOf(swigCPtr, aiTexture.getCPtr(value)); return ret; } public int LastIndexOf(aiTexture value) { int ret = AssimpPINVOKE.aiTextureVector_LastIndexOf(swigCPtr, aiTexture.getCPtr(value)); return ret; } public bool Remove(aiTexture value) { bool ret = AssimpPINVOKE.aiTextureVector_Remove(swigCPtr, aiTexture.getCPtr(value)); return ret; } }
{ "content_hash": "7bdf81f54edfab58a0856fbf6ec52df5", "timestamp": "", "source": "github", "line_count": 348, "max_line_length": 137, "avg_line_length": 32.75574712643678, "alnum_prop": 0.6773401175541715, "repo_name": "jansedivy/pathtracer", "id": "745a44ec81a8d44fd3ea545eccde57c6d31696fa", "size": "11399", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "libs/windows/assimp/port/Assimp.NET/Assimp.NET_CS/aiTextureVector.cs", "mode": "33261", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "6821" }, { "name": "C", "bytes": "1572595" }, { "name": "C++", "bytes": "6906796" }, { "name": "CMake", "bytes": "63940" }, { "name": "Inno Setup", "bytes": "8592" }, { "name": "Makefile", "bytes": "166356" }, { "name": "Objective-C", "bytes": "10733" }, { "name": "Shell", "bytes": "947" } ], "symlink_target": "" }
package io.gravitee.rest.api.portal.rest.mapper; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; import io.gravitee.rest.api.model.ApplicationEntity; import io.gravitee.rest.api.model.GroupEntity; import io.gravitee.rest.api.model.PrimaryOwnerEntity; import io.gravitee.rest.api.model.UserEntity; import io.gravitee.rest.api.model.application.ApplicationListItem; import io.gravitee.rest.api.model.application.ApplicationSettings; import io.gravitee.rest.api.model.application.OAuthClientSettings; import io.gravitee.rest.api.model.application.SimpleApplicationSettings; import io.gravitee.rest.api.portal.rest.model.Application; import io.gravitee.rest.api.portal.rest.model.ApplicationLinks; import io.gravitee.rest.api.portal.rest.model.Group; import io.gravitee.rest.api.portal.rest.model.User; import io.gravitee.rest.api.service.GroupService; import io.gravitee.rest.api.service.UserService; import java.time.Instant; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.List; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; /** * @author Florent CHAMFROY (florent.chamfroy at graviteesource.com) * @author GraviteeSource Team */ @RunWith(MockitoJUnitRunner.class) public class ApplicationMapperTest { private static final String APPLICATION = "my-application"; private static final String APPLICATION_ID = "my-application-id"; private static final String APPLICATION_DESCRIPTION = "my-application-description"; private static final String APPLICATION_NAME = "my-application-name"; private static final String APPLICATION_GROUP_ID = "my-application-group-id"; private static final String APPLICATION_GROUP_NAME = "my-application-group-name"; private static final String APPLICATION_STATUS = "my-application-status"; private static final String APPLICATION_TYPE = "my-application-type"; private static final String APPLICATION_USER_ID = "my-application-user-id"; private static final String APPLICATION_USER_DISPLAYNAME = "my-application-user-display-name"; private static final String APPLICATION_USER_EMAIL = "my-application-user-email"; private static final String APPLICATION_SIMPLE_CLIENT_ID = "my-application-simple-client-id"; private static final String APPLICATION_SIMPLE_TYPE = "my-application-simple-type"; private static final String APPLICATION_OAUTH_APPLICATION_TYPE = "my-application-oauth-application-type"; private static final String APPLICATION_OAUTH_CLIENT_ID = "my-application-oauth-client-id"; private static final String APPLICATION_OAUTH_CLIENT_SECRET = "my-application-oauth-client-secret"; private static final String APPLICATION_OAUTH_CLIENT_URI = "my-application-oauth--client-uri"; private static final String APPLICATION_OAUTH_GRANT_TYPE = "my-application-oauth-grant-type"; private static final String APPLICATION_OAUTH_LOGO_URI = "my-application-oauth-logo-uri"; private static final String APPLICATION_OAUTH_REDIRECT_URI = "my-application-oauth-redirect-uri"; private static final String APPLICATION_OAUTH_RESPONSE_TYPE = "my-application-oauth-response-type"; @InjectMocks private ApplicationMapper applicationMapper; @Mock private UriInfo uriInfo; @Mock private UserService userService; @Mock private GroupService groupService; @Spy private UserMapper userMapper = new UserMapper(); ApplicationEntity applicationEntity; ApplicationListItem applicationListItem; Instant now; private enum AppSettingsEnum { NO_SETTINGS, SIMPLE_SETTINGS, OAUTH_SETTINGS, } @Before public void init() { now = Instant.now(); Date nowDate = Date.from(now); applicationEntity = new ApplicationEntity(); applicationListItem = new ApplicationListItem(); //init reset(groupService); reset(userService); reset(userMapper); GroupEntity grpEntity = new GroupEntity(); grpEntity.setId(APPLICATION_GROUP_ID); grpEntity.setName(APPLICATION_GROUP_NAME); when(groupService.findById(APPLICATION_GROUP_ID)).thenReturn(grpEntity); UserEntity userEntity = Mockito.mock(UserEntity.class); when(userEntity.getDisplayName()).thenReturn(APPLICATION_USER_DISPLAYNAME); when(userEntity.getEmail()).thenReturn(APPLICATION_USER_EMAIL); when(userEntity.getId()).thenReturn(APPLICATION_USER_ID); when(userService.findById(APPLICATION_USER_ID)).thenReturn(userEntity); when(userMapper.convert(userEntity)).thenCallRealMethod(); when(userMapper.computeUserLinks(anyString(), any())).thenCallRealMethod(); PrimaryOwnerEntity primaryOwner = new PrimaryOwnerEntity(userEntity); when(uriInfo.getBaseUriBuilder()).thenReturn(UriBuilder.fromPath("")); applicationEntity.setCreatedAt(nowDate); applicationEntity.setDescription(APPLICATION_DESCRIPTION); applicationEntity.setGroups(new HashSet<String>(Arrays.asList(APPLICATION_GROUP_ID))); applicationEntity.setId(APPLICATION_ID); applicationEntity.setName(APPLICATION_NAME); applicationEntity.setPrimaryOwner(primaryOwner); applicationEntity.setStatus(APPLICATION_STATUS); applicationEntity.setType(APPLICATION_TYPE); applicationEntity.setUpdatedAt(nowDate); applicationListItem.setCreatedAt(nowDate); applicationListItem.setDescription(APPLICATION_DESCRIPTION); applicationListItem.setGroups(new HashSet<String>(Arrays.asList(APPLICATION_GROUP_ID))); applicationListItem.setId(APPLICATION_ID); applicationListItem.setName(APPLICATION_NAME); applicationListItem.setPrimaryOwner(primaryOwner); applicationListItem.setStatus(APPLICATION_STATUS); applicationListItem.setType(APPLICATION_TYPE); applicationListItem.setUpdatedAt(nowDate); } @Test public void testConvertFromAppListItem() { Application responseApplication = applicationMapper.convert(applicationListItem, uriInfo); checkApplication(now, responseApplication, AppSettingsEnum.NO_SETTINGS); } @Test public void testConvertFromAppEntityNoSettings() { Application responseApplication = applicationMapper.convert(applicationEntity, uriInfo); checkApplication(now, responseApplication, AppSettingsEnum.NO_SETTINGS); } @Test public void testConvertFromAppEntitySimpleApp() { ApplicationSettings settings = new ApplicationSettings(); SimpleApplicationSettings simpleAppEntitySetings = new SimpleApplicationSettings(); simpleAppEntitySetings.setClientId(APPLICATION_SIMPLE_CLIENT_ID); simpleAppEntitySetings.setType(APPLICATION_SIMPLE_TYPE); settings.setApp(simpleAppEntitySetings); applicationEntity.setSettings(settings); Application responseApplication = applicationMapper.convert(applicationEntity, uriInfo); checkApplication(now, responseApplication, AppSettingsEnum.SIMPLE_SETTINGS); } @Test public void testConvertFromAppEntityOAuthClient() { ApplicationSettings settings = new ApplicationSettings(); OAuthClientSettings oAuthClientEntitySettings = new OAuthClientSettings(); oAuthClientEntitySettings.setApplicationType(APPLICATION_OAUTH_APPLICATION_TYPE); oAuthClientEntitySettings.setClientId(APPLICATION_OAUTH_CLIENT_ID); oAuthClientEntitySettings.setClientSecret(APPLICATION_OAUTH_CLIENT_SECRET); oAuthClientEntitySettings.setClientUri(APPLICATION_OAUTH_CLIENT_URI); oAuthClientEntitySettings.setGrantTypes(Arrays.asList(APPLICATION_OAUTH_GRANT_TYPE)); oAuthClientEntitySettings.setLogoUri(APPLICATION_OAUTH_LOGO_URI); oAuthClientEntitySettings.setRedirectUris(Arrays.asList(APPLICATION_OAUTH_REDIRECT_URI)); oAuthClientEntitySettings.setRenewClientSecretSupported(true); oAuthClientEntitySettings.setResponseTypes(Arrays.asList(APPLICATION_OAUTH_RESPONSE_TYPE)); settings.setoAuthClient(oAuthClientEntitySettings); applicationEntity.setSettings(settings); Application responseApplication = applicationMapper.convert(applicationEntity, uriInfo); checkApplication(now, responseApplication, AppSettingsEnum.OAUTH_SETTINGS); } private void checkApplication(Instant now, Application responseApplication, AppSettingsEnum appSettingsType) { assertNotNull(responseApplication); assertNull(responseApplication.getLinks()); assertEquals(APPLICATION_TYPE, responseApplication.getApplicationType()); assertEquals(now.toEpochMilli(), responseApplication.getCreatedAt().toInstant().toEpochMilli()); assertEquals(APPLICATION_DESCRIPTION, responseApplication.getDescription()); assertEquals(APPLICATION_ID, responseApplication.getId()); assertEquals(APPLICATION_NAME, responseApplication.getName()); assertEquals(now.toEpochMilli(), responseApplication.getUpdatedAt().toInstant().toEpochMilli()); List<Group> groups = responseApplication.getGroups(); assertNotNull(groups); assertEquals(1, groups.size()); assertEquals(APPLICATION_GROUP_ID, groups.get(0).getId()); assertEquals(APPLICATION_GROUP_NAME, groups.get(0).getName()); User owner = responseApplication.getOwner(); assertNotNull(owner); assertEquals(APPLICATION_USER_DISPLAYNAME, owner.getDisplayName()); assertEquals(APPLICATION_USER_EMAIL, owner.getEmail()); assertEquals(APPLICATION_USER_ID, owner.getId()); assertEquals("environments/DEFAULT/users/" + APPLICATION_USER_ID + "/avatar?", owner.getLinks().getAvatar()); io.gravitee.rest.api.portal.rest.model.ApplicationSettings applicationSettings = responseApplication.getSettings(); if (AppSettingsEnum.NO_SETTINGS == appSettingsType) { assertNull(applicationSettings); } else { io.gravitee.rest.api.portal.rest.model.SimpleApplicationSettings sas = applicationSettings.getApp(); io.gravitee.rest.api.portal.rest.model.OAuthClientSettings oacs = applicationSettings.getOauth(); if (AppSettingsEnum.OAUTH_SETTINGS == appSettingsType) { assertNull(sas); assertNotNull(oacs); assertEquals(APPLICATION_OAUTH_APPLICATION_TYPE, oacs.getApplicationType()); assertEquals(APPLICATION_OAUTH_CLIENT_ID, oacs.getClientId()); assertEquals(APPLICATION_OAUTH_CLIENT_SECRET, oacs.getClientSecret()); assertEquals(APPLICATION_OAUTH_CLIENT_URI, oacs.getClientUri()); assertEquals(APPLICATION_OAUTH_LOGO_URI, oacs.getLogoUri()); assertEquals(Boolean.TRUE, oacs.getRenewClientSecretSupported()); final List<String> grantTypes = oacs.getGrantTypes(); assertNotNull(grantTypes); assertFalse(grantTypes.isEmpty()); assertEquals(APPLICATION_OAUTH_GRANT_TYPE, grantTypes.get(0)); final List<String> redirectUris = oacs.getRedirectUris(); assertNotNull(redirectUris); assertFalse(redirectUris.isEmpty()); assertEquals(APPLICATION_OAUTH_REDIRECT_URI, redirectUris.get(0)); final List<String> responseTypes = oacs.getResponseTypes(); assertNotNull(responseTypes); assertFalse(responseTypes.isEmpty()); assertEquals(APPLICATION_OAUTH_RESPONSE_TYPE, responseTypes.get(0)); assertEquals(responseApplication.getHasClientId(), true); } else if (AppSettingsEnum.SIMPLE_SETTINGS == appSettingsType) { assertNotNull(sas); assertNull(oacs); assertEquals(APPLICATION_SIMPLE_CLIENT_ID, sas.getClientId()); assertEquals(APPLICATION_SIMPLE_TYPE, sas.getType()); assertEquals(responseApplication.getHasClientId(), true); } } } @Test public void testApplicationLinks() { String basePath = "/" + APPLICATION; ApplicationLinks links = applicationMapper.computeApplicationLinks(basePath, null); assertNotNull(links); assertEquals(basePath, links.getSelf()); assertEquals(basePath + "/members", links.getMembers()); assertEquals(basePath + "/notifications", links.getNotifications()); assertEquals(basePath + "/picture", links.getPicture()); } }
{ "content_hash": "8027aea109c9a62660775659710e8b96", "timestamp": "", "source": "github", "line_count": 271, "max_line_length": 123, "avg_line_length": 47.981549815498155, "alnum_prop": 0.7313696839190956, "repo_name": "gravitee-io/gravitee-management-rest-api", "id": "497d9bedad4515d0744b971788e314383160088a", "size": "13633", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gravitee-rest-api-portal/gravitee-rest-api-portal-rest/src/test/java/io/gravitee/rest/api/portal/rest/mapper/ApplicationMapperTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5018" }, { "name": "HTML", "bytes": "22559" }, { "name": "Java", "bytes": "5346629" }, { "name": "Shell", "bytes": "8486" } ], "symlink_target": "" }
class SamlController < ApplicationController before_action :saml_enabled? skip_before_action :require_user, only: :init def init respond_to do |format| format.html { redirect_to sso_saml_index_url } format.json { render json: { url: init_saml_index_url } } end end def sso settings = saml_settings if settings.nil? render action: :no_settings return end request = OneLogin::RubySaml::Authrequest.new redirect_to(request.create(settings)) end def acs response = OneLogin::RubySaml::Response.new(params[:SAMLResponse]) response.settings = saml_settings if response.is_valid? staff = Staff.find_by email: response.name_id if staff.nil? staff = Staff.new staff.email = response.name_id staff.password = Devise.friendly_token.first(8) staff.save! end sign_in_and_redirect(:staff, staff) else saml_failure end end # Trigger SP and IdP initiated Logout requests def logout # If we're given a logout request, handle it in the IdP logout initiated method if params[:SAMLRequest] return idp_logout_request # We've been given a response back from the IdP elsif params[:SAMLResponse] return process_logout_response elsif params[:slo] return sp_logout_request else reset_session end end # Create an SP initiated SLO def sp_logout_request # LogoutRequest accepts plain browser requests w/o paramters settings = saml_settings if settings.idp_slo_target_url.nil? reset_session else # Since we created a new SAML request, save the transaction_id # to compare it with the response we get back logout_request = OneLogin::RubySaml::Logoutrequest.new session[:transaction_id] = logout_request.uuid if settings.name_identifier_value.nil? settings.name_identifier_value = session[:user_id] end relay_state = url_for controller: 'saml', action: 'index' redirect_to(logout_request.create(settings, RelayState: relay_state)) end end # After sending an SP initiated LogoutRequest to the IdP, we need to accept # the LogoutResponse, verify it, then actually delete our session. def process_logout_response settings = saml_settings if session.key? :transation_id logout_response = OneLogin::RubySaml::Logoutresponse.new(params[:SAMLResponse], settings, matches_request_id: session[:transation_id]) else logout_response = OneLogin::RubySaml::Logoutresponse.new(params[:SAMLResponse], settings) end # Validate the SAML Logout Response # Actually log out this session reset_session if logout_response.success? end # Method to handle IdP initiated logouts def idp_logout_request settings = saml_settings logout_request = OneLogin::RubySaml::SloLogoutrequest.new(params[:SAMLRequest]) render inline: logger.error unless logout_request.is_valid? # Actually log out this session reset_session logout_response = OneLogin::RubySaml::SloLogoutresponse.new.create(settings, logout_request_id, nil, RelayState: params[:RelayState]) redirect_to logout_response end def saml_settings idp_metadata_parser = OneLogin::RubySaml::IdpMetadataParser.new # Returns OneLogin::RubySaml::Settings prepopulated with idp metadata settings = idp_metadata_parser.parse_remote(ENV['SAML_REMOTE_XML_URL']) settings.assertion_consumer_service_url = acs_saml_index_url settings.assertion_consumer_logout_service_url = logout_saml_index_url settings.issuer = "#{metadata_saml_index_url}.xml" settings.name_identifier_format = ENV['SAML_IDENTIFIER'] settings.authn_context = 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport' settings.certificate = ENV['SAML_CERTIFICATE'] settings end def metadata settings = saml_settings meta = OneLogin::RubySaml::Metadata.new render xml: meta.generate(settings), content_type: 'application/samlmetadata+xml' end private def saml_enabled? return saml_failure if ENV['SAML_ENABLED'].nil? true end def saml_failure respond_to do |format| format.html { render file: "#{Rails.root}/public/404", layout: false, status: :not_found } format.json { render json: { error: MissingRecordDetection::Messages.not_found }, status: :not_found } end false end end
{ "content_hash": "3c6097bd37d4af582e7b9ae2043578d3", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 140, "avg_line_length": 30.06756756756757, "alnum_prop": 0.7, "repo_name": "AllenBW/api", "id": "70981198eafb0aa311f74f1d66e8529d307808c3", "size": "4450", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "app/controllers/saml_controller.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "80914" }, { "name": "HTML", "bytes": "158433" }, { "name": "JavaScript", "bytes": "327573" }, { "name": "Ruby", "bytes": "410941" } ], "symlink_target": "" }
<?php include("assets/core/config/part_set_timezone.php"); include("connectDatabase.inc"); include("part_session.php"); include("requestVariableSanitizer.inc"); include("class_category_user_group_validator.php"); include("class_config_reader.php"); $parentId = sanitize_string($_REQUEST['parentId']); $id = sanitize_string($_REQUEST['id']); $type = sanitize_string($_REQUEST['type']); $body = sanitize_string($_REQUEST['body']); if (trim($parentId) == "" || trim($type) == "" || trim($_SESSION['username']) == "") { exit; } switch ($type) { case "documentComment": $outputTo = "#message_box"; break; case "documentImageComment": $outputTo = "#message_box"; break; case "userProfileComment": $outputTo = "#comment_message_box"; break; case "userImageComment": $outputTo = "#message_box"; break; case "blogComment": $outputTo = "#message_box"; break; case "eventComment": $outputTo = "#message_box"; break; case "groupImageComment": $outputTo = "#message_box"; break; } if (trim($body) == "") {$error = 1; $errorMessage .= "- Please enter a comment.<br>";} if ($error != 1) { //get the current date and time $time = time(); switch ($type) { case "documentComment": //gather document information to display in notifications $result = mysql_query("SELECT documents.shortcut, documents.title FROM documents WHERE documents.id = '{$parentId}'"); $row = mysql_fetch_object($result); $messageURL = "http://" . $_SERVER['HTTP_HOST'] . "/documents/open/$row->shortcut"; include("assets/core/config/notifications/add_comment/document/notification.php"); //add comment to database $result = mysql_query("INSERT INTO commentsDocuments (parentId, type, username, dateCreated, body) VALUES ('{$parentId}', '{$type}', '{$_SESSION['username']}', {$time}, '{$body}')"); //grab the id for this comment $commentId = mysql_result(mysql_query("SELECT LAST_INSERT_ID() AS id"), 0, "id"); break; case "documentImageComment": $messageURL = "http://" . $_SERVER['HTTP_HOST'] . "/galleries/id/$parentId"; include("assets/core/config/notifications/add_comment/document_image/notification.php"); //add comment to database $result = mysql_query("INSERT INTO commentsImages (parentId, imageId, type, username, dateCreated, body) VALUES ('{$parentId}', '{$id}', '{$type}', '{$_SESSION['username']}', {$time}, '{$body}')"); //grab the id for this comment $commentId = mysql_result(mysql_query("SELECT LAST_INSERT_ID() AS id"), 0, "id"); break; case "userProfileComment": //check if commentsFromFriendsOnly is enabled for the user being commented on $result = mysql_query("SELECT commentsFromFriendsOnly FROM users WHERE username = '{$parentId}'"); $row = mysql_fetch_object($result); //if commentsFromFriendsOnly is enabled and commentor is not a friend, exit if ($row->commentsFromFriendsOnly == '1') { $result = mysql_query("SELECT owner FROM friends WHERE owner = '{$parentId}' AND friend = '{$_SESSION['username']}' AND status = 'approved'"); if(mysql_num_rows($result) == 0) { exit; } } //gather document information to display in notifications $messageURL = "http://" . $_SERVER['HTTP_HOST'] . "/showProfile.php?username=" . urlencode(unsanitize_string($parentId)); include("assets/core/config/notifications/add_comment/profile/notification.php"); //add comment to database $result = mysql_query("INSERT INTO commentsUserProfiles (parentId, username, dateCreated, body) VALUES ('{$parentId}', '{$_SESSION['username']}', {$time}, '{$body}')"); //grab the id for this comment $commentId = mysql_result(mysql_query("SELECT LAST_INSERT_ID() AS id"), 0, "id"); break; case "userImageComment": //gather document information to display in notifications $messageURL = "http://" . $_SERVER['HTTP_HOST'] . "/usergalleries/username/$parentId"; include("assets/core/config/notifications/add_comment/profile_image/notification.php"); //add comment to database $result = mysql_query("INSERT INTO commentsImages (parentId, imageId, type, username, dateCreated, body) VALUES ('{$parentId}', '{$id}', '{$type}', '{$_SESSION['username']}', {$time}, '{$body}')"); //grab the id for this comment $commentId = mysql_result(mysql_query("SELECT LAST_INSERT_ID() AS id"), 0, "id"); break; case "blogComment": //gather document information to display in notifications $result = mysql_query("SELECT title, usernameCreated FROM blogs where id = '{$parentId}'"); $row = mysql_fetch_object($result); $messageURL = "http://" . $_SERVER['HTTP_HOST'] . "/blogs/id/$parentId"; include("assets/core/config/notifications/add_comment/blog/notification.php"); //add comment to database $result = mysql_query("INSERT INTO commentsDocuments (parentId, type, username, dateCreated, body) VALUES ('{$parentId}', '{$type}', '{$_SESSION['username']}', {$time}, '{$body}')"); //grab the id for this comment $commentId = mysql_result(mysql_query("SELECT LAST_INSERT_ID() AS id"), 0, "id"); break; case "eventComment": //gather document information to display in notifications $result = mysql_query("SELECT events.category, events.title FROM events WHERE events.id = '{$parentId}'"); $row = mysql_fetch_object($result); $messageURL = "http://" . $_SERVER['HTTP_HOST'] . "/events/id/$parentId"; include("assets/core/config/notifications/add_comment/event/notification.php"); if(accessPrivateGroupEvent($parentId)) { //add comment to database $result = mysql_query("INSERT INTO commentsDocuments (parentId, type, username, dateCreated, body) VALUES ('{$parentId}', '{$type}', '{$_SESSION['username']}', {$time}, '{$body}')"); //grab the id for this comment $commentId = mysql_result(mysql_query("SELECT LAST_INSERT_ID() AS id"), 0, "id"); } else { exit; } break; case "groupImageComment": //gather document information to display in notifications $result = mysql_query("SELECT name FROM groups WHERE id = '{$parentId}' LIMIT 1"); $row = mysql_fetch_object($result); $messageURL = "http://" . $_SERVER['HTTP_HOST'] . "/groupgalleries/id/$parentId"; include("assets/core/config/notifications/add_comment/group_image/notification.php"); //add comment to database $result = mysql_query("INSERT INTO commentsImages (parentId, imageId, type, username, dateCreated, body) VALUES ('{$parentId}', '{$id}', '{$type}', '{$_SESSION['username']}', {$time}, '{$body}')"); //grab the id for this comment $commentId = mysql_result(mysql_query("SELECT LAST_INSERT_ID() AS id"), 0, "id"); break; } if ($result) { //read config file $config = new ConfigReader(); $config->loadConfigFile('assets/core/config/config.properties'); $result = mysql_query("SELECT users.username, users.name, users.email, users.allowEmailNotifications FROM friends INNER JOIN users ON friends.owner = '{$_SESSION['username']}' AND friends.friend = users.username AND friends.status = 'approved'"); $time = time(); while ($row = mysql_fetch_object($result)) { $subject = $_SESSION['username'] . " has posted a new comment on " . preg_replace("/^www\.{1}/i", "", $_SERVER['HTTP_HOST']) . "!"; $notificationMessage = "Hello " . htmlentities($row->name) . ",<br><br>Your friend " . $_SESSION['username'] . $notificationText; mysql_query("INSERT INTO messages (dateSent, toUser, fromUser, subject, body, status, system) VALUES ($time, '{$row->username}', '{$_SESSION['username']}', '" . sanitize_string($subject) . "', '" . sanitize_string($notificationMessage) . "', 'unread', 1)"); if ($row->allowEmailNotifications == 1) { $to = $row->email; $notificationEmail = "<html>"; $notificationEmail .= "<body>"; $notificationEmail .= $notificationMessage; $notificationEmail .= "</body>"; $notificationEmail .= "</html>"; $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $headers .= "From: " . $config->readValue('siteEmailAddress') . "\r\n"; $headers .= "Reply-To: " . $config->readValue('siteEmailAddress') . "\r\n"; mail($to, $subject, $notificationEmail, $headers); } } header('Content-type: application/javascript'); print "$('$outputTo').html('Your comment has been added.');"; print "$('$outputTo').show();"; exit; } else { header('Content-type: application/javascript'); print "$('$outputTo').html('Unknown error! Please try your request again.');"; print "$('$outputTo').show();"; exit; } } else { $showMessage = "<b>There was an error processing your request, please check the following:</b><br>$errorMessage"; header('Content-type: application/javascript'); print "$('$outputTo').html('$showMessage');"; print "$('$outputTo').show();"; exit; } function accessPrivateGroupEvent($parentId) { $result = mysql_query("SELECT groupId, private FROM events WHERE id = '{$parentId}'"); $row = mysql_fetch_object($result); $groupId = $row->groupId; $private = $row->private; if (trim($groupId) != "" && $private == 1) { if ($_SESSION['userLevel'] != 1 && $_SESSION['userLevel'] != 2) { //if the user is not an admin, validate that the user is allowed to delete the requested group $result = mysql_query("SELECT parentId FROM groupsMembers WHERE parentId = '{$groupId}' AND username = '{$_SESSION['username']}' AND status = 'approved'"); if (mysql_num_rows($result) == 0) { return false; } } } return true; } ?>
{ "content_hash": "73cefb20032f64d39eb18c42d339608e", "timestamp": "", "source": "github", "line_count": 292, "max_line_length": 260, "avg_line_length": 33.58561643835616, "alnum_prop": 0.6407667992250433, "repo_name": "omeganetresearch/SoNetCMS", "id": "3f8bc13e6430a0ac0eb66b31ae1873b96ae7110e", "size": "9807", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajaxAddComment.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "5668" }, { "name": "CSS", "bytes": "275870" }, { "name": "HTML", "bytes": "1618869" }, { "name": "JavaScript", "bytes": "667781" }, { "name": "PHP", "bytes": "1407595" } ], "symlink_target": "" }
knockout-contrib ================ Custom Bindings for [knockout.js](http://knockoutjs.com) Custom Bindings --------------- **tvalue** tvalue binding is exactly like the default value binding, but trims the values before accepting them. Example: `<input data-bind='tvalue:firstName' />`
{ "content_hash": "a932bc40da6343611e6218e0569e7d18", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 101, "avg_line_length": 20.857142857142858, "alnum_prop": 0.678082191780822, "repo_name": "ssayala/knockout-contrib", "id": "2b2261d849ff3ec79f566c90390fdb47ed999370", "size": "292", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "235423" } ], "symlink_target": "" }
import * as React from 'react'; import { ShengnianShorthandCollection } from '../..'; import { default as FeedContent } from './FeedContent'; import { default as FeedDate } from './FeedDate'; import { default as FeedEvent, FeedEventProps } from './FeedEvent'; import { default as FeedExtra } from './FeedExtra'; import { default as FeedLabel } from './FeedLabel'; import { default as FeedMeta } from './FeedMeta'; import { default as FeedLike } from './FeedLike'; import { default as FeedSummary } from './FeedSummary'; import { default as FeedUser } from './FeedUser'; export interface FeedProps { [key: string]: any; /** An element type to render as (string or function). */ as?: any; /** Primary content. */ children?: React.ReactNode; /** Additional classes. */ className?: string; /** Shorthand array of props for FeedEvent. */ events?: ShengnianShorthandCollection<FeedEventProps>; /** A feed can have different sizes. */ size?: 'small' | 'large'; } interface FeedComponent extends React.StatelessComponent<FeedProps> { Content: typeof FeedContent; Date: typeof FeedDate; Event: typeof FeedEvent; Extra: typeof FeedExtra; Label: typeof FeedLabel; Meta: typeof FeedMeta; Like: typeof FeedLike; Summary: typeof FeedSummary; User: typeof FeedUser; } declare const Feed: FeedComponent; export default Feed;
{ "content_hash": "2724709d66573a979ccac17eabc69b75", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 69, "avg_line_length": 28.914893617021278, "alnum_prop": 0.7086092715231788, "repo_name": "shengnian/shengnian-ui-react", "id": "a404069efeac15b66ed7453e73f3fab39ccd1541", "size": "1359", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/views/Feed/Feed.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1233" }, { "name": "JavaScript", "bytes": "1168671" }, { "name": "TypeScript", "bytes": "116" } ], "symlink_target": "" }
{% extends "base.html" %} {% load i18n %} {% load thumbnail %} {% load staticfiles %} {% load crispy_forms_tags %} {% block title %}{{ block.super }}Home{% endblock %} {% block navbar-left %} {% include "_navbar.html" with active_link="product" %} {% endblock %} {% block floating-sidebar %} {% include "_sidebar.html" with active_link="product" %} {% endblock %} {% block navbar-right %} {% if not user.is_authenticated %} {# {% crispy signin_form %} #} {% else %} {{ block.super }} {% endif %} {% endblock %} {% block page-id %} home {% endblock %} {% block page-class %} wow-animate-wrapper {% endblock %} {% block jumbo-tron %} <div class="jumbotron jumbotron-carousel corporate-jumbo" style="background-image:url(/static/site/img/product-banner.jpg); no-repeat center center;"> <div class="container"> <div class="row"> <div class="col-md-8 col-sm-8 wow fadeInUp" data-wow-duration="2s"> <h1>{% include "_brandname.html" %}</h1> <p>Best Quality Christmas Trees & Greens in NYC</p> <p>Greenpoint Trees LLC Home Delivery Christmas Trees</p> <p>866 535 3878</p> </div> <!-- <div class="col-md-4 col-sm-4"> {# {% if not user.is_authenticated %} #} <div class="span3 well"> <legend>Create an Account</legend> {# {% crispy signup_form %} #} </div> {# {% endif %} #} </div>--> </div> </div> </div> {% endblock %} {% block container %} <div class="container"> <div class="row"> <div class="col-md-8"> <div class="heading box wow fadeInLeft" data-wow-duration="2s"> <p> <strong>Call to Place Your Order 866 535 3878 </strong></p> </div> </div> <div class="col-md-4 wow bounceInLeft" data-wow-duration="2s"> <img src="/static/site/img/service.png" alt="service"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-md-12 wow fadeInRight" data-wow-duration="2.5s"> <div class="heading box"> <p><strong>Greenpoint Trees LLC Home Delivery Christmas Trees</strong></p> </div> </div> </div> <div class="row package"> <div class="col-md-10 col-md-offset-1"> <div class="product-body text-center wow bounceIn" data-wow-duration="2s"> <h3>FRASER FIR</h3> <p>The Fraser fir branches turn slightly upward. They have good form and needle-retention. They are dark blue-green in color. They have a pleasant scent, and excellent shipping characteristics as well.</p> <hr> <h3>Fresh Cut Premium Fraser Fir </h3> <h4>4' to 15' foot </h4> <hr> </div> </div> </div> {% for row in product_rows %} <div class="row package"> {% for product in row %} <div class="col-md-6"> <div class="product-box bg-product-white wow bounceIn{% cycle 'Left' 'Right' %}" data-wow-duration="2s"> {% with image=product.primary_image %} {% thumbnail image.original "200x200" format="PNG" upscale=False as thumb %} <div class="img-section" style="background-image:url({{ thumb.url }})" alt="tree"> </div> {% endthumbnail %} {% endwith %} <div class="product-body bg-product-white"> <h3>{{product.title}} {% if product.price.excl_tax %} {{product.price.excl_tax}}{{product.price.currency}} {% endif %} </h3> <div> {{product.description|safe}} </div> <div class="product-btn text-center"> <form id="add_to_basket_form" action="{% url 'basket:add' pk=product.pk %}" method="post" class="add-to-basket"> {% csrf_token %} {# {% include "partials/form_fields.html" with form=basket_form %} #} <input id="id_quantity" name="quantity" type="hidden" value="1"> <a href="tel:866 535 3878"> {# <button type="button" class="btn btn-primary btn-lg " data-loading-text="Adding...">Call to place order <i class="fa fa-phone"></i></button> #} </a> <button type="submit" class="btn btn-primary btn-lg btn-add-to-basket" data-loading-text="Adding...">Ready for sell now <i class="fa fa-shopping-cart"></i></button> </form> </div> </div> </div> </div> {% endfor %} </div> {% endfor %} </div> </div> {% endblock container %}
{ "content_hash": "6fb68de96c9e1b0423b118439135ed1b", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 212, "avg_line_length": 31.22695035460993, "alnum_prop": 0.5723370429252782, "repo_name": "canhhs91/greenpointtrees", "id": "988c29da9c599f692163b93ad45e2c52ca04f502", "size": "4403", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/templates/product-oscar.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1742692" }, { "name": "CoffeeScript", "bytes": "39030" }, { "name": "HTML", "bytes": "607982" }, { "name": "JavaScript", "bytes": "1561649" }, { "name": "Python", "bytes": "1689463" }, { "name": "Shell", "bytes": "3789" } ], "symlink_target": "" }
package cfvbaibai.cardfantasy.engine; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class CardStatus { private List<CardStatusItem> items; public CardStatus() { this.items = new LinkedList<CardStatusItem>(); } public void add(CardStatusItem item) { this.items.add(item); } public boolean remove(CardStatusType type) { Iterator<CardStatusItem> iterator = items.iterator(); while (iterator.hasNext()) { CardStatusItem next = iterator.next(); if (next.getType() == type) { iterator.remove(); return true; } } return false; } public boolean containsStatus(CardStatusType type) { for (CardStatusItem item : items) { if (item.getType() == type) { return true; } } return false; } public List<CardStatusItem> getStatusOf(CardStatusType type) { List<CardStatusItem> result = new LinkedList<CardStatusItem>(); for (CardStatusItem item : items) { if (item.getType() == type) { result.add(item); } } return result; } public String getShortDesc() { if (items.size() == 0) { return "-"; } StringBuffer sb = new StringBuffer(); sb.append("【"); for (CardStatusItem item : items) { sb.append(item.getShortDesc()); sb.append(", "); } sb.deleteCharAt(sb.length() - 1); sb.deleteCharAt(sb.length() - 1); sb.append("】"); return sb.toString(); } public boolean containsStatusCausedBy(FeatureInfo feature, CardStatusType type) { List<CardStatusItem> items = this.getStatusOf(type); for (CardStatusItem item : items) { if (item.getCause().equals(feature)) { return true; } } return false; } }
{ "content_hash": "00ab49b4e901619162a2ab11c53e6eab", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 85, "avg_line_length": 27.283783783783782, "alnum_prop": 0.5468053491827637, "repo_name": "catree1988/CardFantasy-master", "id": "4077d1e73517d583583137eef199d5730edc1aa5", "size": "2023", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "workspace/CardFantasyCore/src/cfvbaibai/cardfantasy/engine/CardStatus.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "4840" }, { "name": "Java", "bytes": "522118" }, { "name": "JavaScript", "bytes": "134304" }, { "name": "Shell", "bytes": "1846" } ], "symlink_target": "" }
"""The tests for the discovery component.""" from unittest.mock import MagicMock, patch import pytest from homeassistant import config_entries from homeassistant.bootstrap import async_setup_component from homeassistant.components import discovery from homeassistant.util.dt import utcnow from tests.common import async_fire_time_changed, mock_coro # One might consider to "mock" services, but it's easy enough to just use # what is already available. SERVICE = "yamaha" SERVICE_COMPONENT = "media_player" SERVICE_NO_PLATFORM = "hass_ios" SERVICE_NO_PLATFORM_COMPONENT = "ios" SERVICE_INFO = {"key": "value"} # Can be anything UNKNOWN_SERVICE = "this_service_will_never_be_supported" BASE_CONFIG = {discovery.DOMAIN: {"ignore": [], "enable": []}} IGNORE_CONFIG = {discovery.DOMAIN: {"ignore": [SERVICE_NO_PLATFORM]}} @pytest.fixture(autouse=True) def netdisco_mock(): """Mock netdisco.""" with patch.dict("sys.modules", {"netdisco.discovery": MagicMock()}): yield async def mock_discovery(hass, discoveries, config=BASE_CONFIG): """Mock discoveries.""" result = await async_setup_component(hass, "discovery", config) assert result await hass.async_start() with patch.object(discovery, "_discover", discoveries), patch( "homeassistant.components.discovery.async_discover", return_value=mock_coro() ) as mock_discover, patch( "homeassistant.components.discovery.async_load_platform", return_value=mock_coro(), ) as mock_platform: async_fire_time_changed(hass, utcnow()) # Work around an issue where our loop.call_soon not get caught await hass.async_block_till_done() await hass.async_block_till_done() return mock_discover, mock_platform async def test_unknown_service(hass): """Test that unknown service is ignored.""" def discover(netdisco): """Fake discovery.""" return [("this_service_will_never_be_supported", {"info": "some"})] mock_discover, mock_platform = await mock_discovery(hass, discover) assert not mock_discover.called assert not mock_platform.called async def test_load_platform(hass): """Test load a platform.""" def discover(netdisco): """Fake discovery.""" return [(SERVICE, SERVICE_INFO)] mock_discover, mock_platform = await mock_discovery(hass, discover) assert not mock_discover.called assert mock_platform.called mock_platform.assert_called_with( hass, SERVICE_COMPONENT, SERVICE, SERVICE_INFO, BASE_CONFIG ) async def test_load_component(hass): """Test load a component.""" def discover(netdisco): """Fake discovery.""" return [(SERVICE_NO_PLATFORM, SERVICE_INFO)] mock_discover, mock_platform = await mock_discovery(hass, discover) assert mock_discover.called assert not mock_platform.called mock_discover.assert_called_with( hass, SERVICE_NO_PLATFORM, SERVICE_INFO, SERVICE_NO_PLATFORM_COMPONENT, BASE_CONFIG, ) async def test_ignore_service(hass): """Test ignore service.""" def discover(netdisco): """Fake discovery.""" return [(SERVICE_NO_PLATFORM, SERVICE_INFO)] mock_discover, mock_platform = await mock_discovery(hass, discover, IGNORE_CONFIG) assert not mock_discover.called assert not mock_platform.called async def test_discover_duplicates(hass): """Test load a component.""" def discover(netdisco): """Fake discovery.""" return [ (SERVICE_NO_PLATFORM, SERVICE_INFO), (SERVICE_NO_PLATFORM, SERVICE_INFO), ] mock_discover, mock_platform = await mock_discovery(hass, discover) assert mock_discover.called assert mock_discover.call_count == 1 assert not mock_platform.called mock_discover.assert_called_with( hass, SERVICE_NO_PLATFORM, SERVICE_INFO, SERVICE_NO_PLATFORM_COMPONENT, BASE_CONFIG, ) async def test_discover_config_flow(hass): """Test discovery triggering a config flow.""" discovery_info = {"hello": "world"} def discover(netdisco): """Fake discovery.""" return [("mock-service", discovery_info)] with patch.dict( discovery.CONFIG_ENTRY_HANDLERS, {"mock-service": "mock-component"} ), patch("homeassistant.data_entry_flow.FlowManager.async_init") as m_init: await mock_discovery(hass, discover) assert len(m_init.mock_calls) == 1 args, kwargs = m_init.mock_calls[0][1:] assert args == ("mock-component",) assert kwargs["context"]["source"] == config_entries.SOURCE_DISCOVERY assert kwargs["data"] == discovery_info
{ "content_hash": "ab9136b0f8c535af1f25d7fc63151169", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 86, "avg_line_length": 29.4375, "alnum_prop": 0.6719745222929936, "repo_name": "Teagan42/home-assistant", "id": "1d11bba9e16e8cd962f8daed7fcc92d6129a6de7", "size": "4710", "binary": false, "copies": "2", "ref": "refs/heads/dev", "path": "tests/components/discovery/test_init.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "19774313" }, { "name": "Shell", "bytes": "6846" } ], "symlink_target": "" }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace StringsOperations.ConsoleClient.StringsService { [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.ServiceContractAttribute(ConfigurationName="StringsService.IStringsService")] public interface IStringsService { [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IStringsService/NumberOfContains", ReplyAction="http://tempuri.org/IStringsService/NumberOfContainsResponse")] int NumberOfContains(string subString, string text); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IStringsService/NumberOfContains", ReplyAction="http://tempuri.org/IStringsService/NumberOfContainsResponse")] System.Threading.Tasks.Task<int> NumberOfContainsAsync(string subString, string text); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public interface IStringsServiceChannel : StringsOperations.ConsoleClient.StringsService.IStringsService, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public partial class StringsServiceClient : System.ServiceModel.ClientBase<StringsOperations.ConsoleClient.StringsService.IStringsService>, StringsOperations.ConsoleClient.StringsService.IStringsService { public StringsServiceClient() { } public StringsServiceClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public StringsServiceClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public StringsServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public StringsServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public int NumberOfContains(string subString, string text) { return base.Channel.NumberOfContains(subString, text); } public System.Threading.Tasks.Task<int> NumberOfContainsAsync(string subString, string text) { return base.Channel.NumberOfContainsAsync(subString, text); } } }
{ "content_hash": "239176d75b17ba3dc36f606ff3f61e3a", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 208, "avg_line_length": 50.21666666666667, "alnum_prop": 0.6807168934616661, "repo_name": "ni4ka7a/TelerikAcademyHomeworks", "id": "63e54daa3df7648a652caa2f467338bdc4093d95", "size": "3015", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WebServicesAndCloud/06.WindowsCommunicationFoundation/StringsOperations.ConsoleClient/Service References/StringsService/Reference.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "68371" }, { "name": "C#", "bytes": "686464" }, { "name": "CSS", "bytes": "9330" }, { "name": "CoffeeScript", "bytes": "208" }, { "name": "HTML", "bytes": "88037" }, { "name": "JavaScript", "bytes": "2065339" }, { "name": "XSLT", "bytes": "4422" } ], "symlink_target": "" }
<!DOCTYPE html> <!--[if IE]><![endif]--> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Class TermsEnumAggregator | Picturepark.SDK.V1 API </title> <meta name="viewport" content="width=device-width"> <meta name="title" content="Class TermsEnumAggregator | Picturepark.SDK.V1 API "> <meta name="generator" content="docfx 2.59.4.0"> <link rel="shortcut icon" href="../favicon.ico"> <link rel="stylesheet" href="../styles/docfx.vendor.css"> <link rel="stylesheet" href="../styles/docfx.css"> <link rel="stylesheet" href="../styles/main.css"> <meta property="docfx:navrel" content="../toc.html"> <meta property="docfx:tocrel" content="toc.html"> <meta property="docfx:rel" content="../"> </head> <body data-spy="scroll" data-target="#affix" data-offset="120"> <div id="wrapper"> <header> <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../index.html"> <img id="logo" class="svg" src="../logo.svg" alt=""> </a> </div> <div class="collapse navbar-collapse" id="navbar"> <form class="navbar-form navbar-right" role="search" id="search"> <div class="form-group"> <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off"> </div> </form> </div> </div> </nav> <div class="subnav navbar navbar-default"> <div class="container hide-when-search" id="breadcrumb"> <ul class="breadcrumb"> <li></li> </ul> </div> </div> </header> <div class="container body-content"> <div id="search-results"> <div class="search-list">Search Results for <span></span></div> <div class="sr-items"> <p><i class="glyphicon glyphicon-refresh index-loading"></i></p> </div> <ul id="pagination" data-first="First" data-prev="Previous" data-next="Next" data-last="Last"></ul> </div> </div> <div role="main" class="container body-content hide-when-search"> <div class="sidenav hide-when-search"> <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a> <div class="sidetoggle collapse" id="sidetoggle"> <div id="sidetoc"></div> </div> </div> <div class="article row grid-right"> <div class="col-md-10"> <article class="content wrap" id="_content" data-uid="Picturepark.SDK.V1.Contract.TermsEnumAggregator"> <h1 id="Picturepark_SDK_V1_Contract_TermsEnumAggregator" data-uid="Picturepark.SDK.V1.Contract.TermsEnumAggregator">Class TermsEnumAggregator </h1> <div class="markdown level0 summary"><p>A multi-bucket value aggregator used for aggregations on indexed enum values.</p> </div> <div class="markdown level0 conceptual"></div> <div class="inheritance"> <h5>Inheritance</h5> <div class="level0"><span class="xref">System.Object</span></div> <div class="level1"><a class="xref" href="Picturepark.SDK.V1.Contract.AggregatorBase.html">AggregatorBase</a></div> <div class="level2"><a class="xref" href="Picturepark.SDK.V1.Contract.TermsAggregator.html">TermsAggregator</a></div> <div class="level3"><span class="xref">TermsEnumAggregator</span></div> </div> <div class="inheritedMembers"> <h5>Inherited Members</h5> <div> <a class="xref" href="Picturepark.SDK.V1.Contract.TermsAggregator.html#Picturepark_SDK_V1_Contract_TermsAggregator_Field">TermsAggregator.Field</a> </div> <div> <a class="xref" href="Picturepark.SDK.V1.Contract.TermsAggregator.html#Picturepark_SDK_V1_Contract_TermsAggregator_Size">TermsAggregator.Size</a> </div> <div> <a class="xref" href="Picturepark.SDK.V1.Contract.TermsAggregator.html#Picturepark_SDK_V1_Contract_TermsAggregator_Includes">TermsAggregator.Includes</a> </div> <div> <a class="xref" href="Picturepark.SDK.V1.Contract.TermsAggregator.html#Picturepark_SDK_V1_Contract_TermsAggregator_Excludes">TermsAggregator.Excludes</a> </div> <div> <a class="xref" href="Picturepark.SDK.V1.Contract.TermsAggregator.html#Picturepark_SDK_V1_Contract_TermsAggregator_SearchString">TermsAggregator.SearchString</a> </div> <div> <a class="xref" href="Picturepark.SDK.V1.Contract.TermsAggregator.html#Picturepark_SDK_V1_Contract_TermsAggregator_SearchFields">TermsAggregator.SearchFields</a> </div> <div> <a class="xref" href="Picturepark.SDK.V1.Contract.TermsAggregator.html#Picturepark_SDK_V1_Contract_TermsAggregator_Sort">TermsAggregator.Sort</a> </div> <div> <a class="xref" href="Picturepark.SDK.V1.Contract.AggregatorBase.html#Picturepark_SDK_V1_Contract_AggregatorBase_Name">AggregatorBase.Name</a> </div> <div> <a class="xref" href="Picturepark.SDK.V1.Contract.AggregatorBase.html#Picturepark_SDK_V1_Contract_AggregatorBase_Names">AggregatorBase.Names</a> </div> <div> <a class="xref" href="Picturepark.SDK.V1.Contract.AggregatorBase.html#Picturepark_SDK_V1_Contract_AggregatorBase_Aggregators">AggregatorBase.Aggregators</a> </div> <div> <a class="xref" href="Picturepark.SDK.V1.Contract.AggregatorBase.html#Picturepark_SDK_V1_Contract_AggregatorBase_Filter">AggregatorBase.Filter</a> </div> <div> <a class="xref" href="Picturepark.SDK.V1.Contract.AggregatorBase.html#Picturepark_SDK_V1_Contract_AggregatorBase_UiBehavior">AggregatorBase.UiBehavior</a> </div> <div> <span class="xref">System.Object.ToString()</span> </div> <div> <span class="xref">System.Object.Equals(System.Object)</span> </div> <div> <span class="xref">System.Object.Equals(System.Object, System.Object)</span> </div> <div> <span class="xref">System.Object.ReferenceEquals(System.Object, System.Object)</span> </div> <div> <span class="xref">System.Object.GetHashCode()</span> </div> <div> <span class="xref">System.Object.GetType()</span> </div> <div> <span class="xref">System.Object.MemberwiseClone()</span> </div> </div> <h6><strong>Namespace</strong>: System.Dynamic.ExpandoObject</h6> <h5 id="Picturepark_SDK_V1_Contract_TermsEnumAggregator_syntax">Syntax</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public class TermsEnumAggregator : TermsAggregator</code></pre> </div> <h3 id="properties">Properties </h3> <a id="Picturepark_SDK_V1_Contract_TermsEnumAggregator_EnumType_" data-uid="Picturepark.SDK.V1.Contract.TermsEnumAggregator.EnumType*"></a> <h4 id="Picturepark_SDK_V1_Contract_TermsEnumAggregator_EnumType" data-uid="Picturepark.SDK.V1.Contract.TermsEnumAggregator.EnumType"><a href="#collapsible-Picturepark_SDK_V1_Contract_TermsEnumAggregator_EnumType" class="expander" data-toggle="collapse">EnumType</a></h4> <div id="collapsible-Picturepark_SDK_V1_Contract_TermsEnumAggregator_EnumType" class="collapse in"> <div class="markdown level1 summary"><p>Type of the enum target of the relation. It is used to resolve the enum translation.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public string EnumType { get; set; }</code></pre> </div> <h5 class="propertyValue">Property Value</h5> <table> <tr> <td> <span class="xref">System.String</span> <p> </td> </tr> </table> </div> <h3 id="methods">Methods </h3> <a id="Picturepark_SDK_V1_Contract_TermsEnumAggregator_FromJson_" data-uid="Picturepark.SDK.V1.Contract.TermsEnumAggregator.FromJson*"></a> <h4 id="Picturepark_SDK_V1_Contract_TermsEnumAggregator_FromJson_System_String_" data-uid="Picturepark.SDK.V1.Contract.TermsEnumAggregator.FromJson(System.String)"><a href="#collapsible-Picturepark_SDK_V1_Contract_TermsEnumAggregator_FromJson_System_String_" class="expander" data-toggle="collapse">FromJson(String)</a></h4> <div id="collapsible-Picturepark_SDK_V1_Contract_TermsEnumAggregator_FromJson_System_String_" class="collapse in"> <div class="markdown level1 summary"></div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public static TermsEnumAggregator FromJson(string data)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table> <tr> <td> <span class="pull-right"><span class="xref">System.String</span></span> <span class="parametername">data</span> <p> </td> </tr> </table> <h5 class="returns">Returns</h5> <table> <tr> <td> <a class="xref" href="Picturepark.SDK.V1.Contract.TermsEnumAggregator.html">TermsEnumAggregator</a> <p> </td> </tr> </table> </div> <a id="Picturepark_SDK_V1_Contract_TermsEnumAggregator_ToJson_" data-uid="Picturepark.SDK.V1.Contract.TermsEnumAggregator.ToJson*"></a> <h4 id="Picturepark_SDK_V1_Contract_TermsEnumAggregator_ToJson" data-uid="Picturepark.SDK.V1.Contract.TermsEnumAggregator.ToJson"><a href="#collapsible-Picturepark_SDK_V1_Contract_TermsEnumAggregator_ToJson" class="expander" data-toggle="collapse">ToJson()</a></h4> <div id="collapsible-Picturepark_SDK_V1_Contract_TermsEnumAggregator_ToJson" class="collapse in"> <div class="markdown level1 summary"></div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public string ToJson()</code></pre> </div> <h5 class="returns">Returns</h5> <table> <tr> <td> <span class="xref">System.String</span> <p> </td> </tr> </table> </div> </article> </div> <div class="contribution-panel mobile-hide"> </div> <div class="hidden-sm col-md-2" role="complementary"> <div class="sideaffix"> <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix"> </nav> </div> </div> </div> </div> <footer> <div class="grad-bottom"></div> <div class="footer"> <div class="container"> <span class="pull-right"> <a href="#top">Back to top</a> </span> <span>Generated by <strong>DocFX</strong></span> </div> </div> </footer> </div> <script type="text/javascript" src="../styles/docfx.vendor.js"></script> <script type="text/javascript" src="../styles/docfx.js"></script> <script type="text/javascript" src="../styles/main.js"></script> </body> </html>
{ "content_hash": "aed9699e5cc291804e6a35862e7d1f3a", "timestamp": "", "source": "github", "line_count": 326, "max_line_length": 326, "avg_line_length": 36.22699386503067, "alnum_prop": 0.6329381879762913, "repo_name": "Picturepark/Picturepark.SDK.DotNet", "id": "b5a5948ca4eb7523c15c3f5ad07acf22ce25196e", "size": "11812", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/sdk/site/api/Picturepark.SDK.V1.Contract.TermsEnumAggregator.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1481" }, { "name": "C#", "bytes": "8219178" }, { "name": "PostScript", "bytes": "2927" }, { "name": "PowerShell", "bytes": "2869" } ], "symlink_target": "" }
package R.helper; import android.support.annotation.NonNull; /** * Created by duynk on 1/25/16. */ public class CallbackResult<T> { protected CallbackResult() { } public static <T> CallbackResult<T> error() { CallbackResult<T> obj = new CallbackResult<>(); obj.data = null; obj.error = new ICallbackError() { @Override public int getCode() { return -1; } @Override public String getMessage() { return ""; } @Override public boolean is(ICallbackError error ) {return getCode() == error.getCode();} @Override public boolean is(int error ) {return getCode() == error;} }; return obj; } public static <T> CallbackResult<T> error(ICallbackError error) { CallbackResult<T> obj = new CallbackResult<>(); obj.data = null; obj.error = error; return obj; } public static <T> CallbackResult<T> error(final int error) { CallbackResult<T> obj = new CallbackResult<>(); obj.data = null; obj.error = new ICallbackError() { @Override public int getCode() { return error; } @Override public String getMessage() { return ""; } @Override public boolean is(ICallbackError error ) {return getCode() == error.getCode();} @Override public boolean is(int error ) {return getCode() == error;} }; return obj; } public static <T> CallbackResult<T> error(final int error,@NonNull final String message) { CallbackResult<T> obj = new CallbackResult<>(); obj.data = null; obj.error = new ICallbackError() { @Override public int getCode() { return error; } @Override public String getMessage() { return message; } @Override public boolean is(ICallbackError error ) {return getCode() == error.getCode();} @Override public boolean is(int error ) {return getCode() == error;} }; return obj; } public static <T> CallbackResult<T> error(@NonNull final String message) { CallbackResult<T> obj = new CallbackResult<>(); obj.data = null; obj.error = new ICallbackError() { @Override public int getCode() { return -1; } @Override public String getMessage() { return message; } @Override public boolean is(ICallbackError error ) {return getCode() == error.getCode();} @Override public boolean is(int error ) {return getCode() == error;} }; return obj; } public static <T> CallbackResult<T> success(@NonNull T data) { CallbackResult<T> obj = new CallbackResult<>(); obj.data = data; obj.error = null; return obj; } public static <T> CallbackResult<T> success() { CallbackResult<T> obj = new CallbackResult<>(); obj.data = null; obj.error = null; return obj; } public interface ICallbackError { int getCode(); String getMessage(); boolean is(ICallbackError error); boolean is(int error); } protected T data; protected ICallbackError error; public boolean hasError() { return error != null; } public T getData() { return data; } public T getData(Class<T> clz) { return data; } public ICallbackError getError() { return error; } }
{ "content_hash": "41c34d3fd3686e8a9ffa5b947731bec5", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 94, "avg_line_length": 25.209150326797385, "alnum_prop": 0.5219082188229194, "repo_name": "rickyngk/android-helper", "id": "56d5a970d553942e88b66be81b17446b4111a588", "size": "3857", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/R/helper/CallbackResult.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "60335" } ], "symlink_target": "" }
package com.speedment.common.injector.exception; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; final class ConstructorResolutionExceptionTest { @Test void construct() { assertDoesNotThrow(() -> new ConstructorResolutionException("A")); } }
{ "content_hash": "0e213378c37ef7685effe387dabbf8ee", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 74, "avg_line_length": 20.266666666666666, "alnum_prop": 0.7335526315789473, "repo_name": "speedment/speedment", "id": "0369268c97ef3866e8c44509f7b824c865531aae", "size": "933", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common-parent/injector/src/test/java/com/speedment/common/injector/exception/ConstructorResolutionExceptionTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "17142" }, { "name": "Java", "bytes": "13137551" }, { "name": "Shell", "bytes": "7494" } ], "symlink_target": "" }
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model common\modules\auth\AuthItem */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="auth-item-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'type')->textInput() ?> <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?> <?= $form->field($model, 'rule_name')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'data')->textarea(['rows' => 6]) ?> <?= $form->field($model, 'created_at')->textInput() ?> <?= $form->field($model, 'updated_at')->textInput() ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
{ "content_hash": "449c4d01552a1c45805737cd17543e96", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 150, "avg_line_length": 27.2, "alnum_prop": 0.5630252100840336, "repo_name": "sebfrab/restobar", "id": "62187050b43399259be2364bada51c52a8ca4784", "size": "952", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "backend/views/rbac/_form.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "758" }, { "name": "Batchfile", "bytes": "1571" }, { "name": "CSS", "bytes": "29724" }, { "name": "JavaScript", "bytes": "40495" }, { "name": "PHP", "bytes": "288889" } ], "symlink_target": "" }
In the Java world, `.hashCode` doesn't get mentioned much. I've rarely seen it implemented in otherwise standard POJOs and, now that I've learned a trick or two, I can't fathom why. ## Why use it? `Collection.contains`. That's why. How often do you find yourself searching through an array, checking to see if it contains an element that matches one you have? Not never, most likely. And as long as the element you're checking for is the same instance as the one in the `Collection`, you're fine; no need for hashcode, necessarily. But consider this: ```java MyClass item1 = new MyClass("hello", "world"); MyClass item2 = new MyClass("hello", "world"); List<MyClass> list = Collections.singletonList(item1); Assert.true(list.contains(item2)); // CRASH! ``` The result may or may not surprise you, depending on what you're used to. The `assert` will fail, because `.contains` internally uses `.equals`, which, by default, basically does a *reference check*. That is to say, it checks if `item1` is a reference to the exact same object as `item2`, rather than if it contains the same values. If we changed the `item2` declaration to `MyClass item2 = item1` and ran `list.contains(item2)`, it would return true. In that case, we'd have two variables, but only a single object in memory, which is what `.contains`/`.equals` checks for. ## What if we want to change that? Firstly, the default behavior may well be exactly what you want. You don't need to blindly implement `.hashCode`. But I've found that when I'm checking for equality, what I really want to know is whether there's an item with the same values, regardless of whether it's the same instance. To change this, we should implement two methods; `equals` and `hashCode`. Technically, `.equals` would be enough on its own, but the two go together. If one returns true, then the other should return true, and vice versa. Implementing only `.equals` would violate that and lead to unexpected behavior (aka bugs) down the line. Ok, now for the fun part. There's a not-very-secret-but-I-didn't-know-about-it-and-nobody-else-I-know-did-either way to implement `.hashCode`. Here goes: ```java @Override public int hashCode() { return java.util.Objects.hash(property1, property2); } ``` You were expecting something fancier, weren't you? Nope. This is so easy, a Java programmer could do it. The `.equals` is just as easy: ```java @Override public boolean equals(Object o) { return o instanceof MyClass && o.hashCode() == this.hashCode(); } ``` And there you have it. Throw those into `MyClass` and our `Assert` up there will finally return true. ## Special case: Arrays If your class has an array, you can't just throw it into `Objects.hash`; different lists with elements that equal each other will have different hashcodes. For arrays, add `Arrays.hashCode(yourList)`, like so: ```java Objects.hash(Arrays.hashCode(yourList), prop1, prop2, prop3); ``` ## Special case: Kotlin If you are using Kotlin, there's an easier way to do it than in java, as you've probably come to expect by now. [`data class`es](https://kotlinlang.org/docs/reference/data-classes.html) automatically generate `toString`, `copy`, `hashCode`, and `equals` for you; as long as your class is a `data class`, you're good to go. I have created a snippet of runnable Kotlin code with different ways of using hashcode, along with whether they are equal or not. <http://try.kotlinlang.org/#/UserProjects/9mgchmsmbb427n7osbp3s4dmet/tt4l4cmelbl7u96u8pdq8rapsj>
{ "content_hash": "654b532c4ee6f20095f2025734255299", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 332, "avg_line_length": 54.984375, "alnum_prop": 0.7465188974140381, "repo_name": "davidwhitman/davidwhitman.github.io", "id": "7563739fee715076a73a2a2182a8d6e83c8dd1ba", "size": "3554", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2017-04-30-don't-forget-hashcode!.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7986" }, { "name": "HTML", "bytes": "12193" }, { "name": "JavaScript", "bytes": "980" } ], "symlink_target": "" }
/* * linked_list.h * * \date Jul 16, 2010 * \author <a href="mailto:dev@celix.apache.org">Apache Celix Project Team</a> * \copyright Apache License, Version 2.0 */ #ifndef LINKED_LIST_H_ #define LINKED_LIST_H_ #include "celixbool.h" #include "celix_errno.h" #include "exports.h" typedef struct linked_list_entry * linked_list_entry_pt; typedef struct linked_list * linked_list_pt; UTILS_EXPORT celix_status_t linkedList_create(linked_list_pt *list); UTILS_EXPORT celix_status_t linkedList_destroy(linked_list_pt list); UTILS_EXPORT celix_status_t linkedList_clone(linked_list_pt list, linked_list_pt *clone); UTILS_EXPORT void * linkedList_getFirst(linked_list_pt list); UTILS_EXPORT void * linkedList_getLast(linked_list_pt list); UTILS_EXPORT void * linkedList_removeFirst(linked_list_pt list); UTILS_EXPORT void * linkedList_removeLast(linked_list_pt list); UTILS_EXPORT void linkedList_addFirst(linked_list_pt list, void * element); UTILS_EXPORT void linkedList_addLast(linked_list_pt list, void * element); UTILS_EXPORT bool linkedList_contains(linked_list_pt list, void * element); UTILS_EXPORT int linkedList_size(linked_list_pt list); UTILS_EXPORT bool linkedList_isEmpty(linked_list_pt list); UTILS_EXPORT bool linkedList_addElement(linked_list_pt list, void * element); UTILS_EXPORT bool linkedList_removeElement(linked_list_pt list, void * element); UTILS_EXPORT void linkedList_clear(linked_list_pt list); UTILS_EXPORT void * linkedList_get(linked_list_pt list, int index); UTILS_EXPORT void * linkedList_set(linked_list_pt list, int index, void * element); UTILS_EXPORT void linkedList_addIndex(linked_list_pt list, int index, void * element); UTILS_EXPORT void * linkedList_removeIndex(linked_list_pt list, int index); UTILS_EXPORT linked_list_entry_pt linkedList_entry(linked_list_pt list, int index); UTILS_EXPORT int linkedList_indexOf(linked_list_pt list, void * element); UTILS_EXPORT linked_list_entry_pt linkedList_addBefore(linked_list_pt list, void * element, linked_list_entry_pt entry); UTILS_EXPORT void * linkedList_removeEntry(linked_list_pt list, linked_list_entry_pt entry); #endif /* LINKED_LIST_H_ */
{ "content_hash": "e5528829acb07809424a8df387b16318", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 120, "avg_line_length": 46.95652173913044, "alnum_prop": 0.7666666666666667, "repo_name": "marcojansen/android-inaetics", "id": "6321c5a2f1d40e0dead734f2f5ebf915c3327bc3", "size": "2955", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "celix/utils/public/include/linked_list.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2788290" }, { "name": "C++", "bytes": "510127" }, { "name": "CMake", "bytes": "286255" }, { "name": "HTML", "bytes": "1010" }, { "name": "Java", "bytes": "9898" }, { "name": "Makefile", "bytes": "16066" }, { "name": "Objective-C", "bytes": "19137" }, { "name": "Shell", "bytes": "10474" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>charge-core: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- 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.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.12.1 / charge-core - 1.0.1</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> charge-core <small> 1.0.1 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-10 20:00:39 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-10 20:00:39 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.12.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.11.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.11.2 Official release 4.11.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;gmalecha@gmail.com&quot; homepage: &quot;https://github.com/jesper-bengtson/ChargeCore&quot; dev-repo: &quot;git+https://github.com/jesper-bengtson/ChargeCore.git&quot; bug-reports: &quot;https://github.com/jesper-bengtson/ChargeCore/issues&quot; authors: [&quot;Jesper Bengtson&quot; &quot;Gregory Malecha&quot;] license: &quot;APACHE 2.0&quot; build: [ [make &quot;-j%{jobs}%&quot; &quot;-C&quot; &quot;ChargeCore&quot;] ] install: [ [make &quot;-C&quot; &quot;ChargeCore&quot; &quot;install&quot;] ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.5.1&quot; &amp; &lt; &quot;8.7~&quot;} &quot;coq-ext-lib&quot; {&gt;= &quot;0.9.3&quot;} ] synopsis: &quot;A framework for embedded logics&quot; url { src: &quot;https://github.com/jesper-bengtson/ChargeCore/archive/v1.0.1.tar.gz&quot; checksum: &quot;md5=e2a68b53aafb0d44865160e848353836&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-charge-core.1.0.1 coq.8.12.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.12.1). The following dependencies couldn&#39;t be met: - coq-charge-core -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-charge-core.1.0.1</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "008844ccaffabebe9eef53a20e3078db", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 159, "avg_line_length": 40.18633540372671, "alnum_prop": 0.5276661514683153, "repo_name": "coq-bench/coq-bench.github.io", "id": "c818c2ab5027d35771035359990a0473be00b1f3", "size": "6495", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.11.2-2.0.7/released/8.12.1/charge-core/1.0.1.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
#ifndef USE_TCL_STUBS # define USE_TCL_STUBS #endif #include "tclInt.h" #ifdef TCL_THREADS /* * Each thread has an single instance of the following structure. There is one * instance of this structure per thread even if that thread contains multiple * interpreters. The interpreter identified by this structure is the main * interpreter for the thread. * * The main interpreter is the one that will process any messages received by * a thread. Any thread can send messages but only the main interpreter can * receive them. */ typedef struct ThreadSpecificData { Tcl_ThreadId threadId; /* Tcl ID for this thread */ Tcl_Interp *interp; /* Main interpreter for this thread */ int flags; /* See the TP_ defines below... */ struct ThreadSpecificData *nextPtr; /* List for "thread names" */ struct ThreadSpecificData *prevPtr; /* List for "thread names" */ } ThreadSpecificData; static Tcl_ThreadDataKey dataKey; /* * This list is used to list all threads that have interpreters. This is * protected by threadMutex. */ static ThreadSpecificData *threadList = NULL; /* * The following bit-values are legal for the "flags" field of the * ThreadSpecificData structure. */ #define TP_Dying 0x001 /* This thread is being canceled */ /* * An instance of the following structure contains all information that is * passed into a new thread when the thread is created using either the * "thread create" Tcl command or the ThreadCreate() C function. */ typedef struct ThreadCtrl { const char *script; /* The Tcl command this thread should * execute */ int flags; /* Initial value of the "flags" field in the * ThreadSpecificData structure for the new * thread. Might contain TP_Detached or * TP_TclThread. */ Tcl_Condition condWait; /* This condition variable is used to * synchronize the parent and child threads. * The child won't run until it acquires * threadMutex, and the parent function won't * complete until signaled on this condition * variable. */ } ThreadCtrl; /* * This is the event used to send scripts to other threads. */ typedef struct ThreadEvent { Tcl_Event event; /* Must be first */ char *script; /* The script to execute. */ struct ThreadEventResult *resultPtr; /* To communicate the result. This is NULL if * we don't care about it. */ } ThreadEvent; typedef struct ThreadEventResult { Tcl_Condition done; /* Signaled when the script completes */ int code; /* Return value of Tcl_Eval */ char *result; /* Result from the script */ char *errorInfo; /* Copy of errorInfo variable */ char *errorCode; /* Copy of errorCode variable */ Tcl_ThreadId srcThreadId; /* Id of sending thread, in case it dies */ Tcl_ThreadId dstThreadId; /* Id of target thread, in case it dies */ struct ThreadEvent *eventPtr; /* Back pointer */ struct ThreadEventResult *nextPtr; /* List for cleanup */ struct ThreadEventResult *prevPtr; } ThreadEventResult; static ThreadEventResult *resultList; /* * This is for simple error handling when a thread script exits badly. */ static Tcl_ThreadId mainThreadId; static Tcl_ThreadId errorThreadId; static char *errorProcString; /* * Access to the list of threads and to the thread send results is guarded by * this mutex. */ TCL_DECLARE_MUTEX(threadMutex) static int ThreadObjCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]); static int ThreadCreate(Tcl_Interp *interp, const char *script, int joinable); static int ThreadList(Tcl_Interp *interp); static int ThreadSend(Tcl_Interp *interp, Tcl_ThreadId id, const char *script, int wait); static int ThreadCancel(Tcl_Interp *interp, Tcl_ThreadId id, const char *result, int flags); static Tcl_ThreadCreateType NewTestThread(ClientData clientData); static void ListRemove(ThreadSpecificData *tsdPtr); static void ListUpdateInner(ThreadSpecificData *tsdPtr); static int ThreadEventProc(Tcl_Event *evPtr, int mask); static void ThreadErrorProc(Tcl_Interp *interp); static void ThreadFreeProc(ClientData clientData); static int ThreadDeleteEvent(Tcl_Event *eventPtr, ClientData clientData); static void ThreadExitProc(ClientData clientData); extern int Tcltest_Init(Tcl_Interp *interp); /* *---------------------------------------------------------------------- * * TclThread_Init -- * * Initialize the test thread command. * * Results: * TCL_OK if the package was properly initialized. * * Side effects: * Add the "testthread" command to the interp. * *---------------------------------------------------------------------- */ int TclThread_Init( Tcl_Interp *interp) /* The current Tcl interpreter */ { /* * If the main thread Id has not been set, do it now. */ Tcl_MutexLock(&threadMutex); if (mainThreadId == 0) { mainThreadId = Tcl_GetCurrentThread(); } Tcl_MutexUnlock(&threadMutex); Tcl_CreateObjCommand(interp, "testthread", ThreadObjCmd, NULL, NULL); return TCL_OK; } /* *---------------------------------------------------------------------- * * ThreadObjCmd -- * * This procedure is invoked to process the "testthread" Tcl command. See * the user documentation for details on what it does. * * thread cancel ?-unwind? id ?result? * thread create ?-joinable? ?script? * thread send ?-async? id script * thread event * thread exit * thread id ?-main? * thread names * thread wait * thread errorproc proc * thread join id * * Results: * A standard Tcl result. * * Side effects: * See the user documentation. * *---------------------------------------------------------------------- */ /* ARGSUSED */ static int ThreadObjCmd( ClientData dummy, /* Not used. */ Tcl_Interp *interp, /* Current interpreter. */ int objc, /* Number of arguments. */ Tcl_Obj *const objv[]) /* Argument objects. */ { ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); int option; static const char *const threadOptions[] = { "cancel", "create", "event", "exit", "id", "join", "names", "send", "wait", "errorproc", NULL }; enum options { THREAD_CANCEL, THREAD_CREATE, THREAD_EVENT, THREAD_EXIT, THREAD_ID, THREAD_JOIN, THREAD_NAMES, THREAD_SEND, THREAD_WAIT, THREAD_ERRORPROC }; if (objc < 2) { Tcl_WrongNumArgs(interp, 1, objv, "option ?arg ...?"); return TCL_ERROR; } if (Tcl_GetIndexFromObj(interp, objv[1], threadOptions, "option", 0, &option) != TCL_OK) { return TCL_ERROR; } /* * Make sure the initial thread is on the list before doing anything. */ if (tsdPtr->interp == NULL) { Tcl_MutexLock(&threadMutex); tsdPtr->interp = interp; ListUpdateInner(tsdPtr); Tcl_CreateThreadExitHandler(ThreadExitProc, NULL); Tcl_MutexUnlock(&threadMutex); } switch ((enum options)option) { case THREAD_CANCEL: { Tcl_WideInt id; const char *result; int flags, arg; if ((objc < 3) || (objc > 5)) { Tcl_WrongNumArgs(interp, 2, objv, "?-unwind? id ?result?"); return TCL_ERROR; } flags = 0; arg = 2; if ((objc == 4) || (objc == 5)) { if (strcmp("-unwind", Tcl_GetString(objv[arg])) == 0) { flags = TCL_CANCEL_UNWIND; arg++; } } if (Tcl_GetWideIntFromObj(interp, objv[arg], &id) != TCL_OK) { return TCL_ERROR; } arg++; if (arg < objc) { result = Tcl_GetString(objv[arg]); } else { result = NULL; } return ThreadCancel(interp, (Tcl_ThreadId) (size_t) id, result, flags); } case THREAD_CREATE: { const char *script; int joinable, len; if (objc == 2) { /* * Neither joinable nor special script */ joinable = 0; script = "testthread wait"; /* Just enter event loop */ } else if (objc == 3) { /* * Possibly -joinable, then no special script, no joinable, then * its a script. */ script = Tcl_GetStringFromObj(objv[2], &len); if ((len > 1) && (script[0] == '-') && (script[1] == 'j') && (0 == strncmp(script, "-joinable", len))) { joinable = 1; script = "testthread wait"; /* Just enter event loop */ } else { /* * Remember the script */ joinable = 0; } } else if (objc == 4) { /* * Definitely a script available, but is the flag -joinable? */ script = Tcl_GetStringFromObj(objv[2], &len); joinable = ((len > 1) && (script[0] == '-') && (script[1] == 'j') && (0 == strncmp(script, "-joinable", len))); script = Tcl_GetString(objv[3]); } else { Tcl_WrongNumArgs(interp, 2, objv, "?-joinable? ?script?"); return TCL_ERROR; } return ThreadCreate(interp, script, joinable); } case THREAD_EXIT: if (objc > 2) { Tcl_WrongNumArgs(interp, 2, objv, NULL); return TCL_ERROR; } ListRemove(NULL); Tcl_ExitThread(0); return TCL_OK; case THREAD_ID: if (objc == 2 || objc == 3) { Tcl_Obj *idObj; /* * Check if they want the main thread id or the current thread id. */ if (objc == 2) { idObj = Tcl_NewWideIntObj((Tcl_WideInt)(size_t)Tcl_GetCurrentThread()); } else if (objc == 3 && strcmp("-main", Tcl_GetString(objv[2])) == 0) { Tcl_MutexLock(&threadMutex); idObj = Tcl_NewWideIntObj((Tcl_WideInt)(size_t)mainThreadId); Tcl_MutexUnlock(&threadMutex); } else { Tcl_WrongNumArgs(interp, 2, objv, NULL); return TCL_ERROR; } Tcl_SetObjResult(interp, idObj); return TCL_OK; } else { Tcl_WrongNumArgs(interp, 2, objv, NULL); return TCL_ERROR; } case THREAD_JOIN: { Tcl_WideInt id; int result, status; if (objc != 3) { Tcl_WrongNumArgs(interp, 2, objv, "id"); return TCL_ERROR; } if (Tcl_GetWideIntFromObj(interp, objv[2], &id) != TCL_OK) { return TCL_ERROR; } result = Tcl_JoinThread((Tcl_ThreadId)(size_t)id, &status); if (result == TCL_OK) { Tcl_SetIntObj(Tcl_GetObjResult(interp), status); } else { char buf[20]; sprintf(buf, "%" TCL_LL_MODIFIER "d", id); Tcl_AppendResult(interp, "cannot join thread ", buf, NULL); } return result; } case THREAD_NAMES: if (objc > 2) { Tcl_WrongNumArgs(interp, 2, objv, NULL); return TCL_ERROR; } return ThreadList(interp); case THREAD_SEND: { Tcl_WideInt id; const char *script; int wait, arg; if ((objc != 4) && (objc != 5)) { Tcl_WrongNumArgs(interp, 2, objv, "?-async? id script"); return TCL_ERROR; } if (objc == 5) { if (strcmp("-async", Tcl_GetString(objv[2])) != 0) { Tcl_WrongNumArgs(interp, 2, objv, "?-async? id script"); return TCL_ERROR; } wait = 0; arg = 3; } else { wait = 1; arg = 2; } if (Tcl_GetWideIntFromObj(interp, objv[arg], &id) != TCL_OK) { return TCL_ERROR; } arg++; script = Tcl_GetString(objv[arg]); return ThreadSend(interp, (Tcl_ThreadId)(size_t)id, script, wait); } case THREAD_EVENT: { if (objc > 2) { Tcl_WrongNumArgs(interp, 2, objv, NULL); return TCL_ERROR; } Tcl_SetObjResult(interp, Tcl_NewIntObj( Tcl_DoOneEvent(TCL_ALL_EVENTS | TCL_DONT_WAIT))); return TCL_OK; } case THREAD_ERRORPROC: { /* * Arrange for this proc to handle thread death errors. */ const char *proc; if (objc != 3) { Tcl_WrongNumArgs(interp, 2, objv, "proc"); return TCL_ERROR; } Tcl_MutexLock(&threadMutex); errorThreadId = Tcl_GetCurrentThread(); if (errorProcString) { ckfree(errorProcString); } proc = Tcl_GetString(objv[2]); errorProcString = ckalloc(strlen(proc) + 1); strcpy(errorProcString, proc); Tcl_MutexUnlock(&threadMutex); return TCL_OK; } case THREAD_WAIT: if (objc > 2) { Tcl_WrongNumArgs(interp, 2, objv, ""); return TCL_ERROR; } while (1) { /* * If the script has been unwound, bail out immediately. This does * not follow the recommended guidelines for how extensions should * handle the script cancellation functionality because this is * not a "normal" extension. Most extensions do not have a command * that simply enters an infinite Tcl event loop. Normal * extensions should not specify the TCL_CANCEL_UNWIND when * calling Tcl_Canceled to check if the command has been canceled. */ if (Tcl_Canceled(interp, TCL_LEAVE_ERR_MSG | TCL_CANCEL_UNWIND) == TCL_ERROR) { break; } (void) Tcl_DoOneEvent(TCL_ALL_EVENTS); } /* * If we get to this point, we have been canceled by another thread, * which is considered to be an "error". */ ThreadErrorProc(interp); return TCL_OK; } return TCL_OK; } /* *---------------------------------------------------------------------- * * ThreadCreate -- * * This procedure is invoked to create a thread containing an interp to * run a script. This returns after the thread has started executing. * * Results: * A standard Tcl result, which is the thread ID. * * Side effects: * Create a thread. * *---------------------------------------------------------------------- */ /* ARGSUSED */ static int ThreadCreate( Tcl_Interp *interp, /* Current interpreter. */ const char *script, /* Script to execute */ int joinable) /* Flag, joinable thread or not */ { ThreadCtrl ctrl; Tcl_ThreadId id; ctrl.script = script; ctrl.condWait = NULL; ctrl.flags = 0; joinable = joinable ? TCL_THREAD_JOINABLE : TCL_THREAD_NOFLAGS; Tcl_MutexLock(&threadMutex); if (Tcl_CreateThread(&id, NewTestThread, (ClientData) &ctrl, TCL_THREAD_STACK_DEFAULT, joinable) != TCL_OK) { Tcl_MutexUnlock(&threadMutex); Tcl_AppendResult(interp, "can't create a new thread", NULL); return TCL_ERROR; } /* * Wait for the thread to start because it is using something on our stack! */ Tcl_ConditionWait(&ctrl.condWait, &threadMutex, NULL); Tcl_MutexUnlock(&threadMutex); Tcl_ConditionFinalize(&ctrl.condWait); Tcl_SetObjResult(interp, Tcl_NewWideIntObj((Tcl_WideInt)(size_t)id)); return TCL_OK; } /* *------------------------------------------------------------------------ * * NewTestThread -- * * This routine is the "main()" for a new thread whose task is to execute * a single Tcl script. The argument to this function is a pointer to a * structure that contains the text of the TCL script to be executed. * * Space to hold the script field of the ThreadControl structure passed * in as the only argument was obtained from malloc() and must be freed * by this function before it exits. Space to hold the ThreadControl * structure itself is released by the calling function, and the two * condition variables in the ThreadControl structure are destroyed by * the calling function. The calling function will destroy the * ThreadControl structure and the condition variable as soon as * ctrlPtr->condWait is signaled, so this routine must make copies of any * data it might need after that point. * * Results: * None * * Side effects: * A Tcl script is executed in a new thread. * *------------------------------------------------------------------------ */ Tcl_ThreadCreateType NewTestThread( ClientData clientData) { ThreadCtrl *ctrlPtr = clientData; ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); int result; char *threadEvalScript; /* * Initialize the interpreter. This should be more general. */ tsdPtr->interp = Tcl_CreateInterp(); result = Tcl_Init(tsdPtr->interp); if (result != TCL_OK) { ThreadErrorProc(tsdPtr->interp); } /* * This is part of the test facility. Initialize _ALL_ test commands for * use by the new thread. */ result = Tcltest_Init(tsdPtr->interp); if (result != TCL_OK) { ThreadErrorProc(tsdPtr->interp); } /* * Update the list of threads. */ Tcl_MutexLock(&threadMutex); ListUpdateInner(tsdPtr); /* * We need to keep a pointer to the alloc'ed mem of the script we are * eval'ing, for the case that we exit during evaluation */ threadEvalScript = ckalloc(strlen(ctrlPtr->script) + 1); strcpy(threadEvalScript, ctrlPtr->script); Tcl_CreateThreadExitHandler(ThreadExitProc, threadEvalScript); /* * Notify the parent we are alive. */ Tcl_ConditionNotify(&ctrlPtr->condWait); Tcl_MutexUnlock(&threadMutex); /* * Run the script. */ Tcl_Preserve(tsdPtr->interp); result = Tcl_EvalEx(tsdPtr->interp, threadEvalScript, -1, 0); if (result != TCL_OK) { ThreadErrorProc(tsdPtr->interp); } /* * Clean up. */ Tcl_DeleteInterp(tsdPtr->interp); Tcl_Release(tsdPtr->interp); ListRemove(tsdPtr); Tcl_ExitThread(result); TCL_THREAD_CREATE_RETURN; } /* *------------------------------------------------------------------------ * * ThreadErrorProc -- * * Send a message to the thread willing to hear about errors. * * Results: * None * * Side effects: * Send an event. * *------------------------------------------------------------------------ */ static void ThreadErrorProc( Tcl_Interp *interp) /* Interp that failed */ { Tcl_Channel errChannel; const char *errorInfo, *argv[3]; char *script; char buf[TCL_DOUBLE_SPACE+1]; sprintf(buf, "%" TCL_LL_MODIFIER "d", (Tcl_WideInt)(size_t)Tcl_GetCurrentThread()); errorInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY); if (errorProcString == NULL) { errChannel = Tcl_GetStdChannel(TCL_STDERR); Tcl_WriteChars(errChannel, "Error from thread ", -1); Tcl_WriteChars(errChannel, buf, -1); Tcl_WriteChars(errChannel, "\n", 1); Tcl_WriteChars(errChannel, errorInfo, -1); Tcl_WriteChars(errChannel, "\n", 1); } else { argv[0] = errorProcString; argv[1] = buf; argv[2] = errorInfo; script = Tcl_Merge(3, argv); ThreadSend(interp, errorThreadId, script, 0); ckfree(script); } } /* *------------------------------------------------------------------------ * * ListUpdateInner -- * * Add the thread local storage to the list. This assumes the caller has * obtained the mutex. * * Results: * None * * Side effects: * Add the thread local storage to its list. * *------------------------------------------------------------------------ */ static void ListUpdateInner( ThreadSpecificData *tsdPtr) { if (tsdPtr == NULL) { tsdPtr = TCL_TSD_INIT(&dataKey); } tsdPtr->threadId = Tcl_GetCurrentThread(); tsdPtr->nextPtr = threadList; if (threadList) { threadList->prevPtr = tsdPtr; } tsdPtr->prevPtr = NULL; threadList = tsdPtr; } /* *------------------------------------------------------------------------ * * ListRemove -- * * Remove the thread local storage from its list. This grabs the mutex to * protect the list. * * Results: * None * * Side effects: * Remove the thread local storage from its list. * *------------------------------------------------------------------------ */ static void ListRemove( ThreadSpecificData *tsdPtr) { if (tsdPtr == NULL) { tsdPtr = TCL_TSD_INIT(&dataKey); } Tcl_MutexLock(&threadMutex); if (tsdPtr->prevPtr) { tsdPtr->prevPtr->nextPtr = tsdPtr->nextPtr; } else { threadList = tsdPtr->nextPtr; } if (tsdPtr->nextPtr) { tsdPtr->nextPtr->prevPtr = tsdPtr->prevPtr; } tsdPtr->nextPtr = tsdPtr->prevPtr = 0; tsdPtr->interp = NULL; Tcl_MutexUnlock(&threadMutex); } /* *------------------------------------------------------------------------ * * ThreadList -- * * Return a list of threads running Tcl interpreters. * * Results: * A standard Tcl result. * * Side effects: * None. * *------------------------------------------------------------------------ */ static int ThreadList( Tcl_Interp *interp) { ThreadSpecificData *tsdPtr; Tcl_Obj *listPtr; listPtr = Tcl_NewListObj(0, NULL); Tcl_MutexLock(&threadMutex); for (tsdPtr = threadList ; tsdPtr ; tsdPtr = tsdPtr->nextPtr) { Tcl_ListObjAppendElement(interp, listPtr, Tcl_NewWideIntObj((Tcl_WideInt)(size_t)tsdPtr->threadId)); } Tcl_MutexUnlock(&threadMutex); Tcl_SetObjResult(interp, listPtr); return TCL_OK; } /* *------------------------------------------------------------------------ * * ThreadSend -- * * Send a script to another thread. * * Results: * A standard Tcl result. * * Side effects: * None. * *------------------------------------------------------------------------ */ static int ThreadSend( Tcl_Interp *interp, /* The current interpreter. */ Tcl_ThreadId id, /* Thread Id of other interpreter. */ const char *script, /* The script to evaluate. */ int wait) /* If 1, we block for the result. */ { ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); ThreadEvent *threadEventPtr; ThreadEventResult *resultPtr; int found, code; Tcl_ThreadId threadId = (Tcl_ThreadId) id; /* * Verify the thread exists. */ Tcl_MutexLock(&threadMutex); found = 0; for (tsdPtr = threadList ; tsdPtr ; tsdPtr = tsdPtr->nextPtr) { if (tsdPtr->threadId == threadId) { found = 1; break; } } if (!found) { Tcl_MutexUnlock(&threadMutex); Tcl_AppendResult(interp, "invalid thread id", NULL); return TCL_ERROR; } /* * Short circut sends to ourself. Ought to do something with -async, like * run in an idle handler. */ if (threadId == Tcl_GetCurrentThread()) { Tcl_MutexUnlock(&threadMutex); return Tcl_EvalEx(interp, script,-1,TCL_EVAL_GLOBAL); } /* * Create the event for its event queue. */ threadEventPtr = ckalloc(sizeof(ThreadEvent)); threadEventPtr->script = ckalloc(strlen(script) + 1); strcpy(threadEventPtr->script, script); if (!wait) { resultPtr = threadEventPtr->resultPtr = NULL; } else { resultPtr = ckalloc(sizeof(ThreadEventResult)); threadEventPtr->resultPtr = resultPtr; /* * Initialize the result fields. */ resultPtr->done = NULL; resultPtr->code = 0; resultPtr->result = NULL; resultPtr->errorInfo = NULL; resultPtr->errorCode = NULL; /* * Maintain the cleanup list. */ resultPtr->srcThreadId = Tcl_GetCurrentThread(); resultPtr->dstThreadId = threadId; resultPtr->eventPtr = threadEventPtr; resultPtr->nextPtr = resultList; if (resultList) { resultList->prevPtr = resultPtr; } resultPtr->prevPtr = NULL; resultList = resultPtr; } /* * Queue the event and poke the other thread's notifier. */ threadEventPtr->event.proc = ThreadEventProc; Tcl_ThreadQueueEvent(threadId, (Tcl_Event *) threadEventPtr, TCL_QUEUE_TAIL); Tcl_ThreadAlert(threadId); if (!wait) { Tcl_MutexUnlock(&threadMutex); return TCL_OK; } /* * Block on the results and then get them. */ Tcl_ResetResult(interp); while (resultPtr->result == NULL) { Tcl_ConditionWait(&resultPtr->done, &threadMutex, NULL); } /* * Unlink result from the result list. */ if (resultPtr->prevPtr) { resultPtr->prevPtr->nextPtr = resultPtr->nextPtr; } else { resultList = resultPtr->nextPtr; } if (resultPtr->nextPtr) { resultPtr->nextPtr->prevPtr = resultPtr->prevPtr; } resultPtr->eventPtr = NULL; resultPtr->nextPtr = NULL; resultPtr->prevPtr = NULL; Tcl_MutexUnlock(&threadMutex); if (resultPtr->code != TCL_OK) { if (resultPtr->errorCode) { Tcl_SetErrorCode(interp, resultPtr->errorCode, NULL); ckfree(resultPtr->errorCode); } if (resultPtr->errorInfo) { Tcl_AddErrorInfo(interp, resultPtr->errorInfo); ckfree(resultPtr->errorInfo); } } Tcl_AppendResult(interp, resultPtr->result, NULL); Tcl_ConditionFinalize(&resultPtr->done); code = resultPtr->code; ckfree(resultPtr->result); ckfree(resultPtr); return code; } /* *------------------------------------------------------------------------ * * ThreadCancel -- * * Cancels a script in another thread. * * Results: * A standard Tcl result. * * Side effects: * None. * *------------------------------------------------------------------------ */ static int ThreadCancel( Tcl_Interp *interp, /* The current interpreter. */ Tcl_ThreadId id, /* Thread Id of other interpreter. */ const char *result, /* The result or NULL for default. */ int flags) /* Flags for Tcl_CancelEval. */ { ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); int found; Tcl_ThreadId threadId = (Tcl_ThreadId) id; /* * Verify the thread exists. */ Tcl_MutexLock(&threadMutex); found = 0; for (tsdPtr = threadList ; tsdPtr ; tsdPtr = tsdPtr->nextPtr) { if (tsdPtr->threadId == threadId) { found = 1; break; } } if (!found) { Tcl_MutexUnlock(&threadMutex); Tcl_AppendResult(interp, "invalid thread id", NULL); return TCL_ERROR; } /* * Since Tcl_CancelEval can be safely called from any thread, * we do it now. */ Tcl_MutexUnlock(&threadMutex); Tcl_ResetResult(interp); return Tcl_CancelEval(tsdPtr->interp, (result != NULL) ? Tcl_NewStringObj(result, -1) : NULL, 0, flags); } /* *------------------------------------------------------------------------ * * ThreadEventProc -- * * Handle the event in the target thread. * * Results: * Returns 1 to indicate that the event was processed. * * Side effects: * Fills out the ThreadEventResult struct. * *------------------------------------------------------------------------ */ static int ThreadEventProc( Tcl_Event *evPtr, /* Really ThreadEvent */ int mask) { ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); ThreadEvent *threadEventPtr = (ThreadEvent *) evPtr; ThreadEventResult *resultPtr = threadEventPtr->resultPtr; Tcl_Interp *interp = tsdPtr->interp; int code; const char *result, *errorCode, *errorInfo; if (interp == NULL) { code = TCL_ERROR; result = "no target interp!"; errorCode = "THREAD"; errorInfo = ""; } else { Tcl_Preserve(interp); Tcl_ResetResult(interp); Tcl_CreateThreadExitHandler(ThreadFreeProc, threadEventPtr->script); code = Tcl_EvalEx(interp, threadEventPtr->script,-1,TCL_EVAL_GLOBAL); Tcl_DeleteThreadExitHandler(ThreadFreeProc, threadEventPtr->script); if (code != TCL_OK) { errorCode = Tcl_GetVar(interp, "errorCode", TCL_GLOBAL_ONLY); errorInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY); } else { errorCode = errorInfo = NULL; } result = Tcl_GetStringResult(interp); } ckfree(threadEventPtr->script); if (resultPtr) { Tcl_MutexLock(&threadMutex); resultPtr->code = code; resultPtr->result = ckalloc(strlen(result) + 1); strcpy(resultPtr->result, result); if (errorCode != NULL) { resultPtr->errorCode = ckalloc(strlen(errorCode) + 1); strcpy(resultPtr->errorCode, errorCode); } if (errorInfo != NULL) { resultPtr->errorInfo = ckalloc(strlen(errorInfo) + 1); strcpy(resultPtr->errorInfo, errorInfo); } Tcl_ConditionNotify(&resultPtr->done); Tcl_MutexUnlock(&threadMutex); } if (interp != NULL) { Tcl_Release(interp); } return 1; } /* *------------------------------------------------------------------------ * * ThreadFreeProc -- * * This is called from when we are exiting and memory needs * to be freed. * * Results: * None. * * Side effects: * Clears up mem specified in ClientData * *------------------------------------------------------------------------ */ /* ARGSUSED */ static void ThreadFreeProc( ClientData clientData) { if (clientData) { ckfree(clientData); } } /* *------------------------------------------------------------------------ * * ThreadDeleteEvent -- * * This is called from the ThreadExitProc to delete memory related * to events that we put on the queue. * * Results: * 1 it was our event and we want it removed, 0 otherwise. * * Side effects: * It cleans up our events in the event queue for this thread. * *------------------------------------------------------------------------ */ /* ARGSUSED */ static int ThreadDeleteEvent( Tcl_Event *eventPtr, /* Really ThreadEvent */ ClientData clientData) /* dummy */ { if (eventPtr->proc == ThreadEventProc) { ckfree(((ThreadEvent *) eventPtr)->script); return 1; } /* * If it was NULL, we were in the middle of servicing the event and it * should be removed */ return (eventPtr->proc == NULL); } /* *------------------------------------------------------------------------ * * ThreadExitProc -- * * This is called when the thread exits. * * Results: * None. * * Side effects: * It unblocks anyone that is waiting on a send to this thread. It cleans * up any events in the event queue for this thread. * *------------------------------------------------------------------------ */ /* ARGSUSED */ static void ThreadExitProc( ClientData clientData) { char *threadEvalScript = clientData; ThreadEventResult *resultPtr, *nextPtr; Tcl_ThreadId self = Tcl_GetCurrentThread(); ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); if (tsdPtr->interp != NULL) { ListRemove(tsdPtr); } Tcl_MutexLock(&threadMutex); if (self == errorThreadId) { if (errorProcString) { /* Extra safety */ ckfree(errorProcString); errorProcString = NULL; } errorThreadId = 0; } if (threadEvalScript) { ckfree(threadEvalScript); threadEvalScript = NULL; } Tcl_DeleteEvents((Tcl_EventDeleteProc *) ThreadDeleteEvent, NULL); for (resultPtr = resultList ; resultPtr ; resultPtr = nextPtr) { nextPtr = resultPtr->nextPtr; if (resultPtr->srcThreadId == self) { /* * We are going away. By freeing up the result we signal to the * other thread we don't care about the result. */ if (resultPtr->prevPtr) { resultPtr->prevPtr->nextPtr = resultPtr->nextPtr; } else { resultList = resultPtr->nextPtr; } if (resultPtr->nextPtr) { resultPtr->nextPtr->prevPtr = resultPtr->prevPtr; } resultPtr->nextPtr = resultPtr->prevPtr = 0; resultPtr->eventPtr->resultPtr = NULL; ckfree(resultPtr); } else if (resultPtr->dstThreadId == self) { /* * Dang. The target is going away. Unblock the caller. The result * string must be dynamically allocated because the main thread is * going to call free on it. */ const char *msg = "target thread died"; resultPtr->result = ckalloc(strlen(msg) + 1); strcpy(resultPtr->result, msg); resultPtr->code = TCL_ERROR; Tcl_ConditionNotify(&resultPtr->done); } } Tcl_MutexUnlock(&threadMutex); } #endif /* TCL_THREADS */ /* * Local Variables: * mode: c * c-basic-offset: 4 * fill-column: 78 * End: */
{ "content_hash": "74f8506337517e31bc54cabd91a67afb", "timestamp": "", "source": "github", "line_count": 1220, "max_line_length": 87, "avg_line_length": 25.34262295081967, "alnum_prop": 0.6044375444724756, "repo_name": "macports/macports-base", "id": "ff180779607e305a6c51b785e6434c2f36ca471d", "size": "31436", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/tcl8.6.12/generic/tclThreadTest.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1023346" }, { "name": "M4", "bytes": "92177" }, { "name": "Makefile", "bytes": "27509" }, { "name": "Rich Text Format", "bytes": "6834" }, { "name": "Shell", "bytes": "39512" }, { "name": "Tcl", "bytes": "1531263" } ], "symlink_target": "" }
require 'spec_helper' describe 'neutron::quota' do let :params do {} end let :default_params do { :quota_firewall_rule => -1, :quota_network_gateway => 5, :quota_packet_filter => 100 } end let :facts do { :operatingsystem => 'default', :operatingsystemrelease => 'default' } end shared_examples_for 'neutron quota' do let :params_hash do default_params.merge(params) end it 'configures quota in neutron.conf' do params_hash.each_pair do |config,value| is_expected.to contain_neutron_config("quotas/#{config}").with_value( value ) end end end context 'with default parameters' do it_configures 'neutron quota' end context 'with provided parameters' do before do params.merge!({ :quota_network => 20, :quota_subnet => 20, :quota_port => 100, :quota_router => 20, :quota_floatingip => 100, :quota_security_group => 20, :quota_security_group_rule => 200, :quota_firewall => 1, :quota_firewall_policy => 1, :quota_firewall_rule => -1, :quota_health_monitor => -1, :quota_items => 'network,subnet,port', :quota_member => -1, :quota_network_gateway => 5, :quota_packet_filter => 100, :quota_pool => 10, :quota_vip => 10 }) end it_configures 'neutron quota' end end
{ "content_hash": "623b79e58458dc8f7d9341c8a1df7817", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 85, "avg_line_length": 26.14516129032258, "alnum_prop": 0.5089450956199877, "repo_name": "rdo-puppet-modules/puppet-neutron", "id": "c056444792296466a8fd51c6d03bb2bf179ce1b8", "size": "1621", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/classes/neutron_quota_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "5423" }, { "name": "Puppet", "bytes": "219551" }, { "name": "Ruby", "bytes": "388092" } ], "symlink_target": "" }
// $Id: Unbounded_Set.cpp 79134 2007-07-31 18:23:50Z johnnyw $ #ifndef ACE_UNBOUNDED_SET_CPP #define ACE_UNBOUNDED_SET_CPP #include "ace/Unbounded_Set.h" #include "ace/Malloc_Base.h" #include "ace/Log_Msg.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #if !defined (__ACE_INLINE__) #include "ace/Unbounded_Set.inl" #endif /* __ACE_INLINE__ */ ACE_BEGIN_VERSIONED_NAMESPACE_DECL ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Set) template <class T> size_t ACE_Unbounded_Set<T>::size (void) const { // ACE_TRACE ("ACE_Unbounded_Set<T>::size"); return this->cur_size_; } template <class T> int ACE_Unbounded_Set<T>::insert_tail (const T &item) { // ACE_TRACE ("ACE_Unbounded_Set<T>::insert_tail"); ACE_Node<T> *temp = 0; // Insert <item> into the old dummy node location. this->head_->item_ = item; // Create a new dummy node. ACE_NEW_MALLOC_RETURN (temp, static_cast<ACE_Node<T>*> (this->allocator_->malloc (sizeof (ACE_Node<T>))), ACE_Node<T> (this->head_->next_), -1); // Link this pointer into the list. this->head_->next_ = temp; // Point the head to the new dummy node. this->head_ = temp; ++this->cur_size_; return 0; } template <class T> void ACE_Unbounded_Set<T>::reset (void) { ACE_TRACE ("reset"); this->delete_nodes (); } template <class T> void ACE_Unbounded_Set<T>::dump (void) const { #if defined (ACE_HAS_DUMP) ACE_TRACE ("ACE_Unbounded_Set<T>::dump"); ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_ = %u"), this->head_)); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_->next_ = %u"), this->head_->next_)); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncur_size_ = %d\n"), this->cur_size_)); T *item = 0; #if !defined (ACE_NLOGGING) size_t count = 1; #endif /* ! ACE_NLOGGING */ const_iterator const the_end = this->end (); for (const_iterator i (this->begin ()); i != end; ++i) ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("count = %u\n"), count++)); ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); #endif /* ACE_HAS_DUMP */ } template <class T> void ACE_Unbounded_Set<T>::copy_nodes (const ACE_Unbounded_Set<T> &us) { for (ACE_Node<T> *curr = us.head_->next_; curr != us.head_; curr = curr->next_) this->insert_tail (curr->item_); } template <class T> void ACE_Unbounded_Set<T>::delete_nodes (void) { ACE_Node<T> *curr = this->head_->next_; // Keep looking until we've hit the dummy node. while (curr != this->head_) { ACE_Node<T> *temp = curr; curr = curr->next_; ACE_DES_FREE_TEMPLATE (temp, this->allocator_->free, ACE_Node, <T>); --this->cur_size_; } // Reset the list to be a circular list with just a dummy node. this->head_->next_ = this->head_; } template <class T> ACE_Unbounded_Set<T>::~ACE_Unbounded_Set (void) { // ACE_TRACE ("ACE_Unbounded_Set<T>::~ACE_Unbounded_Set"); this->delete_nodes (); // Delete the dummy node. ACE_DES_FREE_TEMPLATE (head_, this->allocator_->free, ACE_Node, <T>); this->head_ = 0; } template <class T> ACE_Unbounded_Set<T>::ACE_Unbounded_Set (ACE_Allocator *alloc) : head_ (0), cur_size_ (0), allocator_ (alloc) { // ACE_TRACE ("ACE_Unbounded_Set<T>::ACE_Unbounded_Set"); if (this->allocator_ == 0) this->allocator_ = ACE_Allocator::instance (); ACE_NEW_MALLOC (this->head_, (ACE_Node<T>*) this->allocator_->malloc (sizeof (ACE_Node<T>)), ACE_Node<T>); // Make the list circular by pointing it back to itself. this->head_->next_ = this->head_; } template <class T> ACE_Unbounded_Set<T>::ACE_Unbounded_Set (const ACE_Unbounded_Set<T> &us) : head_ (0), cur_size_ (0), allocator_ (us.allocator_) { ACE_TRACE ("ACE_Unbounded_Set<T>::ACE_Unbounded_Set"); if (this->allocator_ == 0) this->allocator_ = ACE_Allocator::instance (); ACE_NEW_MALLOC (this->head_, (ACE_Node<T>*) this->allocator_->malloc (sizeof (ACE_Node<T>)), ACE_Node<T>); this->head_->next_ = this->head_; this->copy_nodes (us); } template <class T> ACE_Unbounded_Set<T> & ACE_Unbounded_Set<T>::operator= (const ACE_Unbounded_Set<T> &us) { ACE_TRACE ("ACE_Unbounded_Set<T>::operator="); if (this != &us) { this->delete_nodes (); this->copy_nodes (us); } return *this; } template <class T> int ACE_Unbounded_Set<T>::find (const T &item) const { // ACE_TRACE ("ACE_Unbounded_Set<T>::find"); const_iterator const the_end = this->end (); for (const_iterator i = this->begin (); i != the_end; ++i) if ((*i) == item) return 0; return -1; } template <class T> int ACE_Unbounded_Set<T>::insert (const T &item) { // ACE_TRACE ("ACE_Unbounded_Set<T>::insert"); if (this->find (item) == 0) return 1; else return this->insert_tail (item); } template <class T> int ACE_Unbounded_Set<T>::remove (const T &item) { // ACE_TRACE ("ACE_Unbounded_Set<T>::remove"); // Insert the item to be founded into the dummy node. this->head_->item_ = item; ACE_Node<T> *curr = this->head_; while (!(curr->next_->item_ == item)) curr = curr->next_; if (curr->next_ == this->head_) return -1; // Item was not found. else { ACE_Node<T> *temp = curr->next_; // Skip over the node that we're deleting. curr->next_ = temp->next_; --this->cur_size_; ACE_DES_FREE_TEMPLATE (temp, this->allocator_->free, ACE_Node, <T>); return 0; } } template <class T> typename ACE_Unbounded_Set<T>::iterator ACE_Unbounded_Set<T>::begin (void) { // ACE_TRACE ("ACE_Unbounded_Set<T>::begin"); return iterator (*this); } template <class T> typename ACE_Unbounded_Set<T>::iterator ACE_Unbounded_Set<T>::end (void) { // ACE_TRACE ("ACE_Unbounded_Set<T>::end"); return iterator (*this, 1); } template <class T> typename ACE_Unbounded_Set<T>::const_iterator ACE_Unbounded_Set<T>::begin (void) const { // ACE_TRACE ("ACE_Unbounded_Set<T>::begin"); return const_iterator (*this); } template <class T> typename ACE_Unbounded_Set<T>::const_iterator ACE_Unbounded_Set<T>::end (void) const { // ACE_TRACE ("ACE_Unbounded_Set<T>::end"); return const_iterator (*this, 1); } ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Set_Iterator) template <class T> void ACE_Unbounded_Set_Iterator<T>::dump (void) const { #if defined (ACE_HAS_DUMP) // ACE_TRACE ("ACE_Unbounded_Set_Iterator<T>::dump"); #endif /* ACE_HAS_DUMP */ } template <class T> ACE_Unbounded_Set_Iterator<T>::ACE_Unbounded_Set_Iterator ( ACE_Unbounded_Set<T> &s, bool end) : current_ (!end ? s.head_->next_ : s.head_ ), set_ (&s) { // ACE_TRACE ("ACE_Unbounded_Set_Iterator<T>::ACE_Unbounded_Set_Iterator"); } template <class T> int ACE_Unbounded_Set_Iterator<T>::advance (void) { // ACE_TRACE ("ACE_Unbounded_Set_Iterator<T>::advance"); this->current_ = this->current_->next_; return this->current_ != this->set_->head_; } template <class T> int ACE_Unbounded_Set_Iterator<T>::first (void) { // ACE_TRACE ("ACE_Unbounded_Set_Iterator<T>::first"); this->current_ = this->set_->head_->next_; return this->current_ != this->set_->head_; } template <class T> int ACE_Unbounded_Set_Iterator<T>::done (void) const { ACE_TRACE ("ACE_Unbounded_Set_Iterator<T>::done"); return this->current_ == this->set_->head_; } template <class T> int ACE_Unbounded_Set_Iterator<T>::next (T *&item) { // ACE_TRACE ("ACE_Unbounded_Set_Iterator<T>::next"); if (this->current_ == this->set_->head_) return 0; else { item = &this->current_->item_; return 1; } } template <class T> ACE_Unbounded_Set_Iterator<T> ACE_Unbounded_Set_Iterator<T>::operator++ (int) { //ACE_TRACE ("ACE_Unbounded_Set_Iterator<T>::operator++ (int)"); ACE_Unbounded_Set_Iterator<T> retv (*this); // postfix operator this->advance (); return retv; } template <class T> ACE_Unbounded_Set_Iterator<T>& ACE_Unbounded_Set_Iterator<T>::operator++ (void) { // ACE_TRACE ("ACE_Unbounded_Set_Iterator<T>::operator++ (void)"); // prefix operator this->advance (); return *this; } template <class T> T& ACE_Unbounded_Set_Iterator<T>::operator* (void) { //ACE_TRACE ("ACE_Unbounded_Set_Iterator<T>::operator*"); T *retv = 0; int result = this->next (retv); ACE_ASSERT (result != 0); ACE_UNUSED_ARG (result); return *retv; } template <class T> bool ACE_Unbounded_Set_Iterator<T>::operator== (const ACE_Unbounded_Set_Iterator<T> &rhs) const { //ACE_TRACE ("ACE_Unbounded_Set_Iterator<T>::operator=="); return (this->set_ == rhs.set_ && this->current_ == rhs.current_); } template <class T> bool ACE_Unbounded_Set_Iterator<T>::operator!= (const ACE_Unbounded_Set_Iterator<T> &rhs) const { //ACE_TRACE ("ACE_Unbounded_Set_Iterator<T>::operator!="); return (this->set_ != rhs.set_ || this->current_ != rhs.current_); } ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Set_Const_Iterator) template <class T> void ACE_Unbounded_Set_Const_Iterator<T>::dump (void) const { #if defined (ACE_HAS_DUMP) // ACE_TRACE ("ACE_Unbounded_Set_Const_Iterator<T>::dump"); #endif /* ACE_HAS_DUMP */ } template <class T> ACE_Unbounded_Set_Const_Iterator<T>::ACE_Unbounded_Set_Const_Iterator ( const ACE_Unbounded_Set<T> &s, bool end) : current_ (!end ? s.head_->next_ : s.head_ ), set_ (&s) { // ACE_TRACE ("ACE_Unbounded_Set_Const_Iterator<T>::ACE_Unbounded_Set_Const_Iterator"); } template <class T> int ACE_Unbounded_Set_Const_Iterator<T>::advance (void) { // ACE_TRACE ("ACE_Unbounded_Set_Const_Iterator<T>::advance"); this->current_ = this->current_->next_; return this->current_ != this->set_->head_; } template <class T> int ACE_Unbounded_Set_Const_Iterator<T>::first (void) { // ACE_TRACE ("ACE_Unbounded_Set_Const_Iterator<T>::first"); this->current_ = this->set_->head_->next_; return this->current_ != this->set_->head_; } template <class T> int ACE_Unbounded_Set_Const_Iterator<T>::done (void) const { ACE_TRACE ("ACE_Unbounded_Set_Const_Iterator<T>::done"); return this->current_ == this->set_->head_; } template <class T> int ACE_Unbounded_Set_Const_Iterator<T>::next (T *&item) { // ACE_TRACE ("ACE_Unbounded_Set_Const_Iterator<T>::next"); if (this->current_ == this->set_->head_) return 0; else { item = &this->current_->item_; return 1; } } template <class T> ACE_Unbounded_Set_Const_Iterator<T> ACE_Unbounded_Set_Const_Iterator<T>::operator++ (int) { //ACE_TRACE ("ACE_Unbounded_Set_Const_Iterator<T>::operator++ (int)"); ACE_Unbounded_Set_Const_Iterator<T> retv (*this); // postfix operator this->advance (); return retv; } template <class T> ACE_Unbounded_Set_Const_Iterator<T>& ACE_Unbounded_Set_Const_Iterator<T>::operator++ (void) { // ACE_TRACE ("ACE_Unbounded_Set_Const_Iterator<T>::operator++ (void)"); // prefix operator this->advance (); return *this; } template <class T> T& ACE_Unbounded_Set_Const_Iterator<T>::operator* (void) { //ACE_TRACE ("ACE_Unbounded_Set_Const_Iterator<T>::operator*"); T *retv = 0; int const result = this->next (retv); ACE_ASSERT (result != 0); ACE_UNUSED_ARG (result); return *retv; } template <class T> bool ACE_Unbounded_Set_Const_Iterator<T>::operator== (const ACE_Unbounded_Set_Const_Iterator<T> &rhs) const { //ACE_TRACE ("ACE_Unbounded_Set_Const_Iterator<T>::operator=="); return (this->set_ == rhs.set_ && this->current_ == rhs.current_); } template <class T> bool ACE_Unbounded_Set_Const_Iterator<T>::operator!= (const ACE_Unbounded_Set_Const_Iterator<T> &rhs) const { //ACE_TRACE ("ACE_Unbounded_Set_Const_Iterator<T>::operator!="); return (this->set_ != rhs.set_ || this->current_ != rhs.current_); } ACE_END_VERSIONED_NAMESPACE_DECL #endif /* ACE_UNBOUNDED_SET_CPP */
{ "content_hash": "2a4121f5e1df7efeb03f3fec87f28744", "timestamp": "", "source": "github", "line_count": 478, "max_line_length": 102, "avg_line_length": 26.271966527196653, "alnum_prop": 0.5934065934065934, "repo_name": "yuanxu/liveshow_r2", "id": "7c2cd381007ea4436d50f4b38c7e5a57538a5e72", "size": "12558", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "P2pNet/ace/Unbounded_Set.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1037" }, { "name": "C", "bytes": "51778" }, { "name": "C#", "bytes": "166129" }, { "name": "C++", "bytes": "10074836" }, { "name": "HTML", "bytes": "20728" }, { "name": "Makefile", "bytes": "38717" }, { "name": "NSIS", "bytes": "10048" }, { "name": "Pascal", "bytes": "1921" }, { "name": "Yacc", "bytes": "10810" } ], "symlink_target": "" }
from aisikl.app import check_connection from .commonui import WebuiCommonUIMixin from .hodnotenia import WebuiHodnoteniaMixin from .obdobia import WebuiObdobiaMixin from .osoby import WebuiOsobyMixin from .predmety import WebuiPredmetyMixin from .studium import WebuiStudiumMixin from .terminy import WebuiTerminyMixin from .zapis import WebuiZapisMixin class WebuiClient(WebuiCommonUIMixin, WebuiHodnoteniaMixin, WebuiObdobiaMixin, WebuiOsobyMixin, WebuiPredmetyMixin, WebuiStudiumMixin, WebuiTerminyMixin, WebuiZapisMixin): def __init__(self, context): self.context = context def check_connection(self): check_connection(self.context) def logout(self): self.context.request_html(self.context.ais_logout_path)
{ "content_hash": "94ad9fdbda93a4d98047cf4bd9dfaeb0", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 78, "avg_line_length": 35.77272727272727, "alnum_prop": 0.7674714104193139, "repo_name": "fmfi-svt/votr", "id": "61a1a4558224634a6505a32e63ddbb004a2fad4c", "size": "788", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fladgejt/webui/__init__.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "131300" }, { "name": "Python", "bytes": "264927" }, { "name": "SCSS", "bytes": "9269" } ], "symlink_target": "" }
from .resource import Resource class NetworkWatcher(Resource): """Network watcher in a resource group. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :ivar provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :vartype provisioning_state: str or ~azure.mgmt.network.v2016_12_01.models.ProvisioningState """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'etag': {'key': 'etag', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } def __init__(self, *, id: str=None, location: str=None, tags=None, etag: str=None, **kwargs) -> None: super(NetworkWatcher, self).__init__(id=id, location=location, tags=tags, **kwargs) self.etag = etag self.provisioning_state = None
{ "content_hash": "119e913a55c55839772f99505ee9abda", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 105, "avg_line_length": 35.020833333333336, "alnum_prop": 0.5978584176085663, "repo_name": "lmazuel/azure-sdk-for-python", "id": "0c844b80b3df80e6aeb37a2d5e724b288dbf6e8b", "size": "2155", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "azure-mgmt-network/azure/mgmt/network/v2016_12_01/models/network_watcher_py3.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "42572767" } ], "symlink_target": "" }
<!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"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v0.1.16 - v0.1.18: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v0.1.16 - v0.1.18 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;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><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.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)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></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)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1_primitive.html">Primitive</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">v8::Primitive Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classv8_1_1_primitive.html">v8::Primitive</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>BooleanValue</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#adc2a7a92a120675bbd4c992163a20869">Equals</a>(Handle&lt; Value &gt; that) const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>Int32Value</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>IntegerValue</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#aaee0b144087d20eae02314c9393ff80f">IsArray</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#a0aceb7645e71b096df5cd73d1252b1b0">IsBoolean</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a8bc11fab0aded4a805722ab6df173cae">IsDate</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#a7ac61a325c18af8dcb6d7d5bf47d2503">IsExternal</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a68c0296071d01ca899825d7643cf495a">IsFalse</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#a05532a34cdd215f273163830ed8b77e7">IsFunction</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a01e1db51c65b2feace248b7acbf71a2c">IsInt32</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#aa2c6ed8ef832223a7e2cd81e6ac61c78">IsNull</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a1bd51e3e55f67c65b9a8f587fbffb7c7">IsNumber</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#a355b7991c5c978c0341f6f961b63c5a2">IsObject</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#ab23a34b7df62806808e01b0908bf5f00">IsString</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#a8f27462322186b295195eecb3e81d6d7">IsTrue</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#aea287b745656baa8a12a2ae1d69744b6">IsUndefined</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>NumberValue</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>StrictEquals</b>(Handle&lt; Value &gt; that) const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#ae810be0ae81a87f677592d0176daac48">ToArrayIndex</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ToBoolean</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>ToDetailString</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ToInt32</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>ToInteger</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ToNumber</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>ToObject</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ToString</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>ToUint32</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>Uint32Value</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Aug 11 2015 23:44:20 for V8 API Reference Guide for node.js v0.1.16 - v0.1.18 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "43298279212b75505adc4ae7d565511d", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 293, "avg_line_length": 87.81481481481481, "alnum_prop": 0.6534795444959932, "repo_name": "v8-dox/v8-dox.github.io", "id": "ebc61ba18bd9a7516c4bf61a2fd90e60af014738", "size": "11855", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "6959a1d/html/classv8_1_1_primitive-members.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.broadinstitute.hellbender.utils.runtime; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.broadinstitute.hellbender.exceptions.GATKException; import org.broadinstitute.hellbender.exceptions.UserException; import org.broadinstitute.hellbender.utils.Utils; import java.io.File; /** * Base class for executors that find and run scripts in an external script engine process (R, Python, etc). * * Subclasses must implement: * * {@link #getApproximateCommandLine} * {@link #getScriptException} */ public abstract class ScriptExecutor { private static final Logger logger = LogManager.getLogger(org.broadinstitute.hellbender.utils.runtime.ScriptExecutor.class); protected final String externalScriptExecutableName; // external program to run; e.g. "RScript" or "python" protected boolean ignoreExceptions = false; private final File externalScriptExecutablePath; // File for path to externalScriptExecutable private String[] commandLineArgs; /** * @param externalScriptExecutableName Name of the script engine to run (i.e. "RScript" or "python") */ public ScriptExecutor(final String externalScriptExecutableName) { Utils.nonNull(externalScriptExecutableName); this.externalScriptExecutableName = externalScriptExecutableName; this.externalScriptExecutablePath = RuntimeUtils.which(externalScriptExecutableName); } /** * @return true if the executable exists and can be found on the path */ public boolean externalExecutableExists() { return externalScriptExecutablePath != null; } /** * Set to true to have the ScriptExecutor catch and ignore GATK exceptions. * * @param ignoreExceptions */ public void setIgnoreExceptions(final boolean ignoreExceptions) { this.ignoreExceptions = ignoreExceptions; } /** * Return a (not necessarily executable) string representing the command line for this executor for error * reporting purposes. * @return Command line string. */ public abstract String getApproximateCommandLine(); protected void executableMissing() { throw new UserException.CannotExecuteScript( externalScriptExecutableName, String.format("Please add the %s directory to your environment ${PATH}", externalScriptExecutableName)); } /** * Called by the script executor when error is encountered. Subclasses should override and return an exception * that is a subclass of ScriptExecutorException. * * @param message String with the cause of the exception. * @return a {#ScriptExecutorException}-derived exception object */ public abstract ScriptExecutorException getScriptException(final String message); /** * Inspect process output exit code and construct a corresponding exception message. * * @param po script process output * @return script exception message */ public String getExceptionMessageFromScriptError(final ProcessOutput po) { Utils.nonNull(po, "process output cannot be null"); final int exitValue = po.getExitValue(); final String commandLineMessage = String.format("\n%s exited with %d\nCommand Line: %s", externalScriptExecutableName, exitValue, String.join(" ", Utils.nonNull(commandLineArgs, "command line args have not been set yet"))); //if debug was enabled the stdout/error were already output somewhere final boolean outputStdout = !logger.isDebugEnabled(); return commandLineMessage.concat(po.getStatusSummary(outputStdout)); } /** * Execute the script represented by the arguments in {@code commandLineArguments} and handle process output. * * @param commandLineArguments command line arguments * @return true if the command executed successfully, otherwise false */ protected boolean executeCuratedArgs(final String[] commandLineArguments) { try { final ProcessOutput po = executeCuratedArgsAndGetOutput(commandLineArguments); if (po == null) { return false; } final int exitValue = po.getExitValue(); logger.debug("Result: " + exitValue); if (exitValue != 0) { throw getScriptException(getExceptionMessageFromScriptError(po)); } return true; } catch (final GATKException e) { if (!ignoreExceptions) { throw e; } else { logger.warn(e.getMessage()); return false; } } } /** * Execute the script represented by the arguments in {@code commandLineArguments} and return process output. * Note that this method does not do any examination or handling of the process output. * * @param commandLineArguments command line arguments * @return process output */ protected ProcessOutput executeCuratedArgsAndGetOutput(final String[] commandLineArguments) { Utils.nonNull(commandLineArguments, "Command line arguments cannot be null"); commandLineArgs = commandLineArguments; if (!externalExecutableExists()) { if (!ignoreExceptions) { executableMissing(); } else { logger.warn("Skipping: " + getApproximateCommandLine()); return null; } } final ProcessSettings processSettings = new ProcessSettings(commandLineArgs); //if debug is enabled, output the stdout and stderr, otherwise capture it to a buffer if (logger.isDebugEnabled()) { processSettings.getStdoutSettings().printStandard(true); processSettings.getStderrSettings().printStandard(true); } else { processSettings.getStdoutSettings().setBufferSize(8192); processSettings.getStderrSettings().setBufferSize(8192); } final ProcessController controller = ProcessController.getThreadLocal(); if (logger.isDebugEnabled()) { logger.debug("Executing:"); for (final String arg: commandLineArgs) { logger.debug(" " + arg); } } return controller.exec(processSettings); } }
{ "content_hash": "5b6b267dba978497092bdd422df6ce95", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 128, "avg_line_length": 38.704819277108435, "alnum_prop": 0.6706614785992218, "repo_name": "broadinstitute/hellbender", "id": "b0c40cd24fc0a107e7b5dd01de0d424d40ce54d9", "size": "6425", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/main/java/org/broadinstitute/hellbender/utils/runtime/ScriptExecutor.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1878" }, { "name": "C++", "bytes": "60687" }, { "name": "Java", "bytes": "7458782" }, { "name": "Python", "bytes": "10963" }, { "name": "R", "bytes": "27481" }, { "name": "Shell", "bytes": "11688" } ], "symlink_target": "" }
'use strict'; export function menuRunBlock(gui, nwwindow, cwd, $rootScope, menuService) { 'ngInject'; var menu = new gui.Menu({ type: 'menubar' }); var menuItems = new gui.Menu(); menuItems.append(new gui.MenuItem({ label: 'Open', click: function() { menuService.open(); } })); menuItems.append(new gui.MenuItem({ label: 'Close', click: function() { nwwindow.close(); } })); if(menu.createMacBuiltin){ menu.createMacBuiltin('tree-view', { hideEdit: true, hideWindow: true }); } menu.append( new gui.MenuItem({ label: 'File', submenu: menuItems }) ); nwwindow.menu = menu; }
{ "content_hash": "5ed3311ead124c1e15608912a5de7b5d", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 75, "avg_line_length": 16.404761904761905, "alnum_prop": 0.579100145137881, "repo_name": "konstantindenerz/labs-tree-view", "id": "2254a6ea7a8a51871a73a56faf3afe8295e1fc84", "size": "689", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/app/components/menu/menu.run.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2252" }, { "name": "HTML", "bytes": "2482" }, { "name": "JavaScript", "bytes": "33682" } ], "symlink_target": "" }
package com.hkm.longmenux; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.hkm.longmenu.Bind; import com.hkm.longmenu.LongMenuComponent; import com.hkm.longmenu.menuitem; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LongMenuComponent fragment_byID = (LongMenuComponent) getFragmentManager().findFragmentById(R.id.menu); Bind b = new Bind(80, this); b.setItemHeight(90); b.setPattern(Bind.Pattern.GREEN); b.setIconPadding(0f); b.setWithSeparator(false); b.setResIdCompanyLogo(R.drawable.icoshlogo); b.setAddListMenu(new menuitem(R.drawable.home128, "Home")); b.setAddListMenu(new menuitem(R.drawable.helpquestionmark128, "Help")); b.setAddListMenu(new menuitem(R.drawable.paperplane128, "Paper")); b.setAddListMenu(new menuitem(R.drawable.settings128, "Settings")); b.setAddListMenu(new menuitem(R.drawable.gift128, "Settings")); b.setAddListMenu(new menuitem(R.drawable.roundbubbleheart128, "Settings")); b.setAddListMenu(new menuitem(R.drawable.wifi128, "Settings")); b.setAddListMenu(new menuitem(R.drawable.user128, "Settings")); b.setAddListMenu(new menuitem(R.drawable.diamond28, "Settings", MenuDishes.class)); b.setAddListMenu(new menuitem(R.drawable.controllerconsole128, "Settings")); b.setAddListMenu(new menuitem(R.drawable.paperplane128, "Paper")); b.setAddListMenu(new menuitem(R.drawable.settings128, "Settings")); b.setAddListMenu(new menuitem(R.drawable.gift128, "Settings")); b.setAddListMenu(new menuitem(R.drawable.roundbubbleheart128, "Settings")); b.setAddListMenu(new menuitem(R.drawable.wifi128, "Settings")); fragment_byID.init(b); //Fragment currentFragment = fragmentManager.findFragmentByTag("fragmentTag"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
{ "content_hash": "00d25b1272136943358b2d0f0e4fa297", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 111, "avg_line_length": 41.130434782608695, "alnum_prop": 0.697322057787174, "repo_name": "msoftware/LongMenu", "id": "4edb2f61fac54e52bfa29bc2d12dff73e7a9c312", "size": "2838", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example/src/main/java/com/hkm/longmenux/MainActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "16269" } ], "symlink_target": "" }
<?php namespace Very\Tests\Config; use PHPUnit\Framework\TestCase; use Very\Config; class RepositoryTest extends TestCase { /** * @var \Very\Config */ protected $repository; public function setUp() { $this->repository = new Config(__DIR__.'/config'); parent::setUp(); } public function testConstruct() { $this->assertInstanceOf(Config::class, $this->repository); } public function testHasIsTrue() { $this->assertTrue($this->repository->has('test.foo')); } public function testHasIsFalse() { $this->assertFalse($this->repository->has('test.not-exist')); } public function testGet() { $this->assertSame('bar', $this->repository->get('test.foo')); } public function testGetWithDefault() { $this->assertSame('default', $this->repository->get('test.not-exist', 'default')); } public function testSet() { $this->repository->set('test.key', 'value'); $this->assertSame('value', $this->repository->get('test.key')); } public function testSetArray() { $this->repository->set([ 'test.key1' => 'value1', 'test.key2' => 'value2', ]); $this->assertSame('value1', $this->repository->get('test.key1')); $this->assertSame('value2', $this->repository->get('test.key2')); } public function testPrepend() { $this->repository->prepend('test.array', 'xxx'); $this->assertSame('xxx', $this->repository->get('test.array.0')); } public function testPush() { $this->repository->push('test.array', 'xxx'); $this->assertSame('xxx', $this->repository->get('test.array.3')); } }
{ "content_hash": "4f56b67701abc0d21b3bdd79531b7fa0", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 90, "avg_line_length": 24.123287671232877, "alnum_prop": 0.5718341851220897, "repo_name": "verystar/framework", "id": "17abfad2eeb01d9b5ea987dd4b171ead46c8b3cb", "size": "1761", "binary": false, "copies": "1", "ref": "refs/heads/3.0", "path": "tests/Config/ConfigTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "487971" } ], "symlink_target": "" }
import stat import py_utils from devil.android import device_utils from systrace import tracing_agents from systrace import trace_result # identify this as trace of cgroup state TRACE_HEADER = 'CGROUP DUMP\n' def add_options(parser): # pylint: disable=unused-argument return None def try_create_agent(config): if config.target != 'android': return None if not config.atrace_categories: return None # 'sched' contains cgroup events if 'sched' not in config.atrace_categories: return None if config.from_file is not None: return None return AndroidCgroupAgent() def get_config(options): return options def parse_proc_cgroups(cgroups, subsys): for line in cgroups.split('\n'): if line.startswith(subsys): return line.split()[1] return '-1' class AndroidCgroupAgent(tracing_agents.TracingAgent): def __init__(self): super(AndroidCgroupAgent, self).__init__() self._config = None self._device_utils = None self._trace_data = "" def __repr__(self): return 'cgroup_data' @py_utils.Timeout(tracing_agents.START_STOP_TIMEOUT) def StartAgentTracing(self, config, timeout=None): self._config = config self._device_utils = device_utils.DeviceUtils( self._config.device_serial_number) if not self._device_utils.HasRoot(): return False self._trace_data += self._get_cgroup_info() return True @py_utils.Timeout(tracing_agents.START_STOP_TIMEOUT) def StopAgentTracing(self, timeout=None): return True @py_utils.Timeout(tracing_agents.GET_RESULTS_TIMEOUT) def GetResults(self, timeout=None): result = TRACE_HEADER + self._trace_data return trace_result.TraceResult('cgroupDump', result) def SupportsExplicitClockSync(self): return False def RecordClockSyncMarker(self, sync_id, did_record_sync_marker_callback): pass def _get_cgroup_info(self): data = [] CGROUP_SUBSYS = 'cpuset' CGROUP_ROOT = '/dev/cpuset/' cgroups = self._device_utils.ReadFile('/proc/cgroups') header = '# cgroup task attachment\n' root_id = parse_proc_cgroups(cgroups, CGROUP_SUBSYS) for cgrp in self._device_utils.StatDirectory(CGROUP_ROOT): if not stat.S_ISDIR(cgrp['st_mode']): continue tasks_file = CGROUP_ROOT + cgrp['filename'] + '/tasks' tasks = self._device_utils.ReadFile(tasks_file).split('\n') cgrp_info = '/%s (root=%s) : ' % (cgrp['filename'], root_id) data.append(cgrp_info + ' '.join(tasks)) return cgroups + header + '\n'.join(data) + '\n'
{ "content_hash": "6273d4b26e07a325b0e98f8f73a020dd", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 76, "avg_line_length": 28.56179775280899, "alnum_prop": 0.6845003933910306, "repo_name": "endlessm/chromium-browser", "id": "75e0872d67ddde8aefd4f6dcdb9bd185bade9814", "size": "2796", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/catapult/systrace/systrace/tracing_agents/android_cgroup_agent.py", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
# if !defined TS_ERRATA_HEADER # define TS_ERRATA_HEADER # include <memory> # include <string> # include <iosfwd> # include <sstream> # include <deque> # include "NumericType.h" # include "IntrusivePtr.h" namespace ts { /** Class to hold a stack of error messages (the "errata"). This is a smart handle class, which wraps the actual data and can therefore be treated a value type with cheap copy semantics. Default construction is very cheap. */ class Errata { protected: /// Implementation class. struct Data; /// Handle for implementation class instance. typedef IntrusivePtr<Data> ImpPtr; public: typedef Errata self; /// Self reference type. /// Message ID. typedef NumericType<unsigned int, struct MsgIdTag> Id; /* Tag / level / code severity. This is intended for clients to use to provide additional classification of a message. A severity code, as for syslog, is a common use. */ typedef NumericType<unsigned int, struct CodeTag> Code; struct Message; typedef std::deque<Message> Container; ///< Storage type for messages. // We iterate backwards to look like a stack. // typedef Container::reverse_iterator iterator; ///< Message iteration. /// Message const iteration. // typedef Container::const_reverse_iterator const_iterator; /// Reverse message iteration. // typedef Container::iterator reverse_iterator; /// Reverse constant message iteration. // typedef Container::const_iterator const_reverse_iterator; /// Default constructor - empty errata, very fast. Errata(); /// Copy constructor, very fast. Errata ( self const& that ///< Object to copy ); /// Construct from string. /// Message Id and Code are default. explicit Errata( std::string const& text ///< Finalized message text. ); /// Construct with @a id and @a text. /// Code is default. Errata( Id id, ///< Message id. std::string const& text ///< Message text. ); /// Construct with @a id, @a code, and @a text. Errata( Id id, ///< Message text. Code code, ///< Message code. std::string const& text ///< Message text. ); /** Construct from a message instance. This is equivalent to default constructing an @c errata and then invoking @c push with an argument of @a msg. */ Errata( Message const& msg ///< Message to push ); /// Move constructor. Errata(self && that); /// Move constructor from @c Message. Errata(Message && msg); /// destructor ~Errata(); /// Self assignment. /// @return A reference to this object. self& operator = ( const self& that ///< Source instance. ); /// Move assignment. self& operator = (self && that); /** Assign message. All other messages are discarded. @return A reference to this object. */ self& operator = ( Message const& msg ///< Source message. ); /** Push @a text as a message. The message is constructed from just the @a text. It becomes the top message. @return A reference to this object. */ self& push(std::string const& text); /** Push @a text as a message with message @a id. The message is constructed from @a text and @a id. It becomes the top message. @return A reference to this object. */ self& push(Id id, std::string const& text); /** Push @a text as a message with message @a id and @a code. The message is constructed from @a text and @a id. It becomes the top message. @return A reference to this object. */ self& push(Id id, Code code, std::string const& text); /** Push a message. @a msg becomes the top message. @return A reference to this object. */ self& push(Message const& msg); self& push(Message && msg); /** Push a constructed @c Message. The @c Message is set to have the @a id and @a code. The other arguments are converted to strings and concatenated to form the messsage text. @return A reference to this object. */ template < typename ... Args > self& push(Id id, Code code, Args const& ... args); /** Push a nested status. @a err becomes the top item. @return A reference to this object. */ self& push(self const& err); /** Access top message. @return If the errata is empty, a default constructed message otherwise the most recent message. */ Message const& top() const; /** Move messages from @a that to @c this errata. Messages from @a that are put on the top of the stack in @c this and removed from @a that. */ self& pull(self& that); /// Remove last message. void pop(); /// Remove all messages. void clear(); /** Inhibit logging. @note This only affects @c this as a top level @c errata. It has no effect on this @c this being logged as a nested @c errata. */ self& doNotLog(); friend std::ostream& operator<< (std::ostream&, self const&); /// Default glue value (a newline) for text rendering. static std::string const DEFAULT_GLUE; /** Test status. Equivalent to @c success but more convenient for use in control statements. @return @c true if no messages or last message has a zero message ID, @c false otherwise. */ operator bool() const; /** Test errata for no failure condition. Equivalent to @c operator @c bool but easier to invoke. @return @c true if no messages or last message has a zero message ID, @c false otherwise. */ bool isOK() const; /// Number of messages in the errata. size_t size() const; /* Forward declares. We have to make our own iterators as the least bad option. The problem is that we have recursive structures so declaration order is difficult. We can't use the container iterators here because the element type is not yet defined. If we define the element type here, it can't contain an Errata and we have to do funky things to get around that. So we have our own iterators, which are just shadowing sublclasses of the container iterators. */ class iterator; class const_iterator; /// Reference to top item on the stack. iterator begin(); /// Reference to top item on the stack. const_iterator begin() const; //! Reference one past bottom item on the stack. iterator end(); //! Reference one past bottom item on the stack. const_iterator end() const; // Logging support. /** Base class for erratum sink. When an errata is abandoned, this will be called on it to perform any client specific logging. It is passed around by handle so that it doesn't have to support copy semantics (and is not destructed until application shutdown). Clients can subclass this class in order to preserve arbitrary data for the sink or retain a handle to the sink for runtime modifications. */ class Sink : public IntrusivePtrCounter { public: typedef Sink self; ///< Self reference type. typedef IntrusivePtr<self> Handle; ///< Handle type. /// Handle an abandoned errata. virtual void operator() (Errata const&) const = 0; /// Force virtual destructor. virtual ~Sink() {} }; //! Register a sink for discarded erratum. static void registerSink(Sink::Handle const& s); /// Register a function as a sink. typedef void (*SinkHandlerFunction)(Errata const&); // Wrapper class to support registering functions as sinks. struct SinkFunctionWrapper : public Sink { /// Constructor. SinkFunctionWrapper(SinkHandlerFunction f) : m_f(f) { } /// Operator to invoke the function. void operator() (Errata const& e) const override { m_f(e); } SinkHandlerFunction m_f; ///< Client supplied handler. }; /// Register a sink function for abandonded erratum. static void registerSink(SinkHandlerFunction f) { registerSink(Sink::Handle(new SinkFunctionWrapper(f))); } /** Simple formatted output. Each message is written to a line. All lines are indented with whitespace @a offset characters. Lines are indented an additional @a indent. This value is increased by @a shift for each level of nesting of an @c Errata. if @a lead is not @c NULL the indentation is overwritten by @a lead if @a indent is non-zero. It acts as a "continuation" marker for nested @c Errata. */ std::ostream& write( std::ostream& out, ///< Output stream. int offset, ///< Lead white space for every line. int indent, ///< Additional indention per line for messages. int shift, ///< Additional @a indent for nested @c Errata. char const* lead ///< Leading text for nested @c Errata. ) const; /// Simple formatted output to fixed sized buffer. /// @return Number of characters written to @a buffer. size_t write( char* buffer, ///< Output buffer. size_t n, ///< Buffer size. int offset, ///< Lead white space for every line. int indent, ///< Additional indention per line for messages. int shift, ///< Additional @a indent for nested @c Errata. char const* lead ///< Leading text for nested @c Errata. ) const; protected: /// Construct from implementation pointer. /// Used internally by nested classes. Errata(ImpPtr const& ptr); /// Implementation instance. ImpPtr m_data; /// Return the implementation instance, allocating and unsharing as needed. Data* pre_write(); /// Force and return an implementation instance. /// Does not follow copy on write. Data const* instance(); /// Used for returns when no data is present. static Message const NIL_MESSAGE; friend struct Data; friend class Item; }; extern std::ostream& operator<< (std::ostream& os, Errata const& stat); /// Storage for a single message. struct Errata::Message { typedef Message self; ///< Self reference type. /// Default constructor. /// The message has Id = 0, default code, and empty text. Message(); /// Construct from text. /// Id is zero and Code is default. Message( std::string const& text ///< Finalized message text. ); /// Construct with @a id and @a text. /// Code is default. Message( Id id, ///< ID of message in table. std::string const& text ///< Final text for message. ); /// Construct with @a id, @a code, and @a text. Message( Id id, ///< Message Id. Code code, ///< Message Code. std::string const& text ///< Final text for message. ); /// Construct with an @a id, @a code, and a @a message. /// The message contents are created by converting the variable arguments /// to strings using the stream operator and concatenated in order. template < typename ... Args> Message( Id id, ///< Message Id. Code code, ///< Message Code. Args const& ... text ); /// Reset to the message to default state. self& clear(); /// Set the message Id. self& set( Id id ///< New message Id. ); /// Set the code. self& set( Code code ///< New code for message. ); /// Set the text. self& set( std::string const& text ///< New message text. ); /// Set the text. self& set( char const* text ///< New message text. ); /// Set the errata. self& set( Errata const& err ///< Errata to store. ); /// Get the text of the message. std::string const& text() const; /// Get the code. Code getCode() const; /// Get the nested status. /// @return A status object, which is not @c NULL if there is a /// nested status stored in this item. Errata getErrata() const; /** The default message code. This value is used as the Code value for constructing and clearing messages. It can be changed to control the value used for empty messages. */ static Code Default_Code; /// Type for overriding success message test. typedef bool (*SuccessTest)(Message const& m); /** Success message test. When a message is tested for being "successful", this function is called. It may be overridden by a client. The initial value is @c DEFAULT_SUCCESS_TEST. @note This is only called when there are Messages in the Errata. An empty Errata (@c NULL or empty stack) is always a success. Only the @c top Message is checked. @return @c true if the message indicates success, @c false otherwise. */ static SuccessTest Success_Test; /// Indicate success if the message code is zero. /// @note Used as the default success test. static bool isCodeZero(Message const& m); static SuccessTest const DEFAULT_SUCCESS_TEST; template < typename ... Args> static std::string stringify(Args const& ... items); Id m_id; ///< Message ID. Code m_code; ///< Message code. std::string m_text; ///< Final text. Errata m_errata; ///< Nested errata. }; /** This is the implementation class for Errata. It holds the actual messages and is treated as a passive data object with nice constructors. We implement reference counting semantics by hand for two reasons. One is that we need to do some specialized things, but mainly because the client can't see this class so we can't */ struct Errata::Data : public IntrusivePtrCounter { typedef Data self; ///< Self reference type. //! Default constructor. Data(); /// Destructor, to do logging. ~Data(); //! Number of messages. size_t size() const; /// Get the top message on the stack. Message const& top() const; /// Put a message on top of the stack. void push(Message const& msg); void push(Message && msg); /// Log this when it is deleted. mutable bool m_log_on_delete = true; //! The message stack. Container m_items; }; /// Forward iterator for @c Messages in an @c Errata. class Errata::iterator : public Errata::Container::reverse_iterator { public: typedef iterator self; ///< Self reference type. typedef Errata::Container::reverse_iterator super; ///< Parent type. iterator(); ///< Default constructor. /// Copy constructor. iterator( self const& that ///< Source instance. ); /// Construct from super class. iterator( super const& that ///< Source instance. ); /// Assignment. self& operator = (self const& that); /// Assignment from super class. self& operator = (super const& that); /// Prefix increment. self& operator ++ (); /// Prefix decrement. self& operator -- (); }; /// Forward constant iterator for @c Messages in an @c Errata. class Errata::const_iterator : public Errata::Container::const_reverse_iterator { public: typedef const_iterator self; ///< Self reference type. typedef Errata::Container::const_reverse_iterator super; ///< Parent type. const_iterator(); ///< Default constructor. /// Copy constructor. const_iterator( self const& that ///< Source instance. ); const_iterator( super const& that ///< Source instance. ); /// Assignment. self& operator = (self const& that); /// Assignment from super class. self& operator = (super const& that); /// Prefix increment. self& operator ++ (); /// Prefix decrement. self& operator -- (); }; /** Helper class for @c Rv. This class enables us to move the implementation of non-templated methods and members out of the header file for a cleaner API. */ struct RvBase { Errata _errata; ///< The status from the function. /** Default constructor. */ RvBase(); /** Construct with specific status. */ RvBase ( Errata const& s ///< Status to copy ); //! Test the return value for success. bool isOK() const; /** Clear any stacked errors. This is useful during shutdown, to silence irrelevant errors caused by the shutdown process. */ void clear(); /// Inhibit logging of the errata. void doNotLog(); }; /** Return type for returning a value and status (errata). In general, a method wants to return both a result and a status so that errors are logged properly. This structure is used to do that in way that is more usable than just @c std::pair. - Simpler and shorter typography - Force use of @c errata rather than having to remember it (and the order) each time - Enable assignment directly to @a R for ease of use and compatibility so clients can upgrade asynchronously. */ template < typename R > struct Rv : public RvBase { typedef Rv self; ///< Standard self reference type. typedef RvBase super; ///< Standard super class reference type. typedef R Result; ///< Type of result value. Result _result; ///< The actual result of the function. /** Default constructor. The default constructor for @a R is used. The status is initialized to SUCCESS. */ Rv(); /** Standard (success) constructor. This copies the result and sets the status to SUCCESS. @note Not @c explicit so that clients can return just a result and have it be marked as SUCCESS. */ Rv( Result const& r ///< The function result ); /** Construct from a result and a pre-existing status object. @internal No constructor from just an Errata to avoid potential ambiguity with constructing from result type. */ Rv( Result const& r, ///< The function result Errata const& s ///< A pre-existing status object ); /** User conversion to the result type. This makes it easy to use the function normally or to pass the result only to other functions without having to extract it by hand. */ operator Result const& () const; /** Assignment from result type. This allows the result to be assigned to a pre-declared return value structure. The return value is a reference to the internal result so that this operator can be chained in other assignments to instances of result type. This is most commonly used when the result is computed in to a local variable to be both returned and stored in a member. @code Rv<int> zret; int value; // ... complex computations, result in value this->m_value = zret = value; // ... return zret; @endcode @return A reference to the copy of @a r stored in this object. */ Result& operator = ( Result const& r ///< Result to assign ) { _result = r; return _result; } /** Add the status from another instance to this one. @return A reference to @c this object. */ template < typename U > self& push( Rv<U> const& that ///< Source of status messages ); /** Set the result. This differs from assignment of the function result in that the return value is a reference to the @c Rv, not the internal result. This makes it useful for assigning a result local variable and then returning. @code Rv<int> zret; int value; // ... complex computation, result in value return zret.set(value); @endcode */ self& set( Result const& r ///< Result to store ); /** Return the result. @return A reference to the result value in this object. */ Result& result(); /** Return the result. @return A reference to the result value in this object. */ Result const& result() const; /** Return the status. @return A reference to the @c errata in this object. */ Errata& errata(); /** Return the status. @return A reference to the @c errata in this object. */ Errata const& errata() const; /// Directly set the errata self& operator = ( Errata const& status ///< Errata to assign. ); /// Push a message on to the status. self& push( Errata::Message const& msg ); }; /** Combine a function result and status in to an @c Rv. This is useful for clients that want to declare the status object and result independently. */ template < typename R > Rv<R> MakeRv( R const& r, ///< The function result Errata const& s ///< The pre-existing status object ) { return Rv<R>(r, s); } /* ----------------------------------------------------------------------- */ /* ----------------------------------------------------------------------- */ // Inline methods. inline Errata::Message::Message() : m_id(0), m_code(Default_Code) { } inline Errata::Message::Message(std::string const& text) : m_id(0), m_code(Default_Code), m_text(text) { } inline Errata::Message::Message(Id id, std::string const& text) : m_id(id), m_code(Default_Code), m_text(text) { } inline Errata::Message::Message(Id id, Code code, std::string const& text) : m_id(id), m_code(code), m_text(text) { } template < typename ... Args> Errata::Message::Message(Id id, Code code, Args const& ... text) : m_id(id), m_code(code), m_text(stringify(text ...)) { } inline Errata::Message& Errata::Message::clear() { m_id = 0; m_code = Default_Code; m_text.erase(); m_errata.clear(); return *this; } inline std::string const& Errata::Message::text() const { return m_text; } inline Errata::Code Errata::Message::getCode() const { return m_code; } inline Errata Errata::Message::getErrata() const { return m_errata; } inline Errata::Message& Errata::Message::set(Id id) { m_id = id; return *this; } inline Errata::Message& Errata::Message::set(Code code) { m_code = code; return *this; } inline Errata::Message& Errata::Message::set(std::string const& text) { m_text = text; return *this; } inline Errata::Message& Errata::Message::set(char const* text) { m_text = text; return *this; } inline Errata::Message& Errata::Message::set(Errata const& err) { m_errata = err; m_errata.doNotLog(); return *this; } template < typename ... Args> std::string Errata::Message::stringify(Args const& ... items) { std::ostringstream s; (void)(int[]){0, ( (s << items) , 0 ) ... }; return s.str(); } inline Errata::Errata() {} inline Errata::Errata(Id id, Code code, std::string const& text) { this->push(Message(id, code, text)); } inline Errata::Errata(Message const& msg) { this->push(msg); } inline Errata::Errata(Message && msg) { this->push(std::move(msg)); } inline Errata::operator bool() const { return this->isOK(); } inline size_t Errata::size() const { return m_data ? m_data->m_items.size() : 0; } inline bool Errata::isOK() const { return nullptr == m_data || 0 == m_data->size() || Message::Success_Test(this->top()) ; } inline Errata& Errata::push(std::string const& text) { this->push(Message(text)); return *this; } inline Errata& Errata::push(Id id, std::string const& text) { this->push(Message(id, text)); return *this; } inline Errata& Errata::push(Id id, Code code, std::string const& text) { this->push(Message(id, code, text)); return *this; } template < typename ... Args > auto Errata::push(Id id, Code code, Args const& ... args) -> self& { this->push(Message(id, code, args ...)); return *this; } inline Errata::Message const& Errata::top() const { return m_data ? m_data->top() : NIL_MESSAGE; } inline Errata& Errata::doNotLog() { this->instance()->m_log_on_delete = false; return *this; } inline Errata::Data::Data() {} inline size_t Errata::Data::size() const { return m_items.size(); } inline Errata::iterator::iterator() { } inline Errata::iterator::iterator(self const& that) : super(that) { } inline Errata::iterator::iterator(super const& that) : super(that) { } inline Errata::iterator& Errata::iterator::operator = (self const& that) { this->super::operator = (that); return *this; } inline Errata::iterator& Errata::iterator::operator = (super const& that) { this->super::operator = (that); return *this; } inline Errata::iterator& Errata::iterator::operator ++ () { this->super::operator ++ (); return *this; } inline Errata::iterator& Errata::iterator::operator -- () { this->super::operator -- (); return *this; } inline Errata::const_iterator::const_iterator() { } inline Errata::const_iterator::const_iterator(self const& that) : super(that) { } inline Errata::const_iterator::const_iterator(super const& that) : super(that) { } inline Errata::const_iterator& Errata::const_iterator::operator = (self const& that) { super::operator = (that); return *this; } inline Errata::const_iterator& Errata::const_iterator::operator = (super const& that) { super::operator = (that); return *this; } inline Errata::const_iterator& Errata::const_iterator::operator ++ () { this->super::operator ++ (); return *this; } inline Errata::const_iterator& Errata::const_iterator::operator -- () { this->super::operator -- (); return *this; } inline RvBase::RvBase() { } inline RvBase::RvBase(Errata const& errata) : _errata(errata) { } inline bool RvBase::isOK() const { return _errata; } inline void RvBase::clear() { _errata.clear(); } inline void RvBase::doNotLog() { _errata.doNotLog(); } template < typename T > Rv<T>::Rv() : _result() { } template < typename T > Rv<T>::Rv(Result const& r) : _result(r) { } template < typename T > Rv<T>::Rv(Result const& r, Errata const& errata) : super(errata) , _result(r) { } template < typename T > Rv<T>::operator Result const&() const { return _result; } template < typename T > T const& Rv<T>::result() const { return _result; } template < typename T > T& Rv<T>::result() { return _result; } template < typename T > Errata const& Rv<T>::errata() const { return _errata; } template < typename T > Errata& Rv<T>::errata() { return _errata; } template < typename T > Rv<T>& Rv<T>::set(Result const& r) { _result = r; return *this; } template < typename T > Rv<T>& Rv<T>::operator = (Errata const& errata) { _errata = errata; return *this; } template < typename T > Rv<T>& Rv<T>::push(Errata::Message const& msg) { _errata.push(msg); return *this; } template < typename T > template < typename U > Rv<T>& Rv<T>::push(Rv<U> const& that) { _errata.push(that.errata()); return *this; } /* ----------------------------------------------------------------------- */ /* ----------------------------------------------------------------------- */ } // namespace ts # endif // TS_ERRATA_HEADER
{ "content_hash": "3f6147deaff59686a8352acf7cd7d76d", "timestamp": "", "source": "github", "line_count": 870, "max_line_length": 129, "avg_line_length": 30.597701149425287, "alnum_prop": 0.6358377160030052, "repo_name": "chitianhao/trafficserver", "id": "eba5bacf4ac2d1f147a4a1f2daeb467f4505e25a", "size": "29634", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/tsconfig/Errata.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1481933" }, { "name": "C++", "bytes": "12818807" }, { "name": "CMake", "bytes": "18505" }, { "name": "Dockerfile", "bytes": "3283" }, { "name": "Java", "bytes": "9881" }, { "name": "JavaScript", "bytes": "1609" }, { "name": "Lex", "bytes": "4029" }, { "name": "Lua", "bytes": "39258" }, { "name": "M4", "bytes": "187086" }, { "name": "Makefile", "bytes": "195501" }, { "name": "Objective-C", "bytes": "15182" }, { "name": "Perl", "bytes": "110166" }, { "name": "Python", "bytes": "705967" }, { "name": "Shell", "bytes": "119499" }, { "name": "Vim script", "bytes": "192" }, { "name": "Yacc", "bytes": "3255" }, { "name": "sed", "bytes": "131" } ], "symlink_target": "" }
package squants.electro import squants.QuantityParseException import squants.space.{CubicMeters, Meters, SquareMeters} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers /** * * @author Nicolas Vinuesa * @since 1.4 * */ class ElectricChargeDensitySpec extends AnyFlatSpec with Matchers { behavior of "ElectricChargeDensity and its Units of Measure" it should "create values using UOM factories" in { CoulombsPerCubicMeter(1).toCoulombsCubicMeters should be(1) } it should "create values from properly formatted Strings" in { ElectricChargeDensity("10.22 C/m³").get should be(CoulombsPerCubicMeter(10.22)) ElectricChargeDensity("10.22 zz").failed.get should be(QuantityParseException("Unable to parse ElectricChargeDensity", "10.22 zz")) ElectricChargeDensity("zz C/m³").failed.get should be(QuantityParseException("Unable to parse ElectricChargeDensity", "zz C/m³")) } it should "properly convert to all supported Units of Measure" in { val x = CoulombsPerCubicMeter(10) x.toCoulombsCubicMeters should be(10.0) } it should "return properly formatted strings for all supported Units of Measure" in { CoulombsPerCubicMeter(1).toString(CoulombsPerCubicMeter) should be("1.0 C/m³") } it should "return ElectricCharge when multiplied by Volume" in { CoulombsPerCubicMeter(1) * CubicMeters(1) should be(Coulombs(1)) } it should "return LinearElectricChargeDensity when multiplied by Area" in { CoulombsPerCubicMeter(1) * SquareMeters(1) should be(CoulombsPerMeter(1)) } it should "return AreaElectricChargeDensity when multiplied by Length" in { CoulombsPerCubicMeter(1) * Meters(1) should be(CoulombsPerSquareMeter(1)) } behavior of "ElectricChargeDensityConversions" it should "provide aliases for single unit values" in { import ElectricChargeDensityConversions._ coulombPerCubicMeter should be(CoulombsPerCubicMeter(1)) } it should "provide implicit conversion from Double" in { import ElectricChargeDensityConversions._ val d = 10.22 d.coulombsPerCubicMeter should be(CoulombsPerCubicMeter(d)) } it should "provide Numeric support" in { import ElectricChargeDensityConversions.ElectricChargeDensityNumeric val rs = List(CoulombsPerCubicMeter(100), CoulombsPerCubicMeter(10)) rs.sum should be(CoulombsPerCubicMeter(110)) } }
{ "content_hash": "1673e6b06542338b23102cecc9d26e66", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 135, "avg_line_length": 34.32857142857143, "alnum_prop": 0.7632126508531003, "repo_name": "typelevel/squants", "id": "af881faa1c0be58181fbe03c0fefe02aeb330524", "size": "2407", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "shared/src/test/scala/squants/electro/ElectricChargeDensitySpec.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "855870" } ], "symlink_target": "" }
package com.example.android.BluetoothChat; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; /** * This class does all the work for setting up and managing Bluetooth * connections with other devices. It has a thread that listens for * incoming connections, a thread for connecting with a device, and a * thread for performing data transmissions when connected. */ public class BluetoothChatService { // Debugging private static final String TAG = "BluetoothChatService"; private static final boolean D = true; // Name for the SDP record when creating server socket private static final String NAME = "BluetoothChat"; // Unique UUID for this application private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Member fields private final BluetoothAdapter mAdapter; private final Handler mHandler; private AcceptThread mAcceptThread; private ConnectThread mConnectThread; private ConnectedThread mConnectedThread; private int mState; // Constants that indicate the current connection state public static final int STATE_NONE = 0; // we're doing nothing public static final int STATE_LISTEN = 1; // now listening for incoming connections public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection public static final int STATE_CONNECTED = 3; // now connected to a remote device /** * Constructor. Prepares a new BluetoothChat session. * @param context The UI Activity Context * @param handler A Handler to send messages back to the UI Activity */ public BluetoothChatService(Context context, Handler handler) { mAdapter = BluetoothAdapter.getDefaultAdapter(); mState = STATE_NONE; mHandler = handler; } /** * Set the current state of the chat connection * @param state An integer defining the current connection state */ private synchronized void setState(int state) { if (D) Log.d(TAG, "setState() " + mState + " -> " + state); mState = state; // Give the new state to the Handler so the UI Activity can update mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1).sendToTarget(); } /** * Return the current connection state. */ public synchronized int getState() { return mState; } /** * Start the chat service. Specifically start AcceptThread to begin a * session in listening (server) mode. Called by the Activity onResume() */ public synchronized void start() { if (D) Log.d(TAG, "start"); // Cancel any thread attempting to make a connection if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;} // Cancel any thread currently running a connection if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} // Start the thread to listen on a BluetoothServerSocket if (mAcceptThread == null) { mAcceptThread = new AcceptThread(); mAcceptThread.start(); } setState(STATE_LISTEN); } /** * Start the ConnectThread to initiate a connection to a remote device. * @param device The BluetoothDevice to connect */ public synchronized void connect(BluetoothDevice device) { if (D) Log.d(TAG, "connect to: " + device); // Cancel any thread attempting to make a connection if (mState == STATE_CONNECTING) { if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;} } // Cancel any thread currently running a connection if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} // Start the thread to connect with the given device mConnectThread = new ConnectThread(device); mConnectThread.start(); setState(STATE_CONNECTING); } /** * Start the ConnectedThread to begin managing a Bluetooth connection * @param socket The BluetoothSocket on which the connection was made * @param device The BluetoothDevice that has been connected */ public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) { if (D) Log.d(TAG, "connected"); // Cancel the thread that completed the connection if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;} // Cancel any thread currently running a connection if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} // Cancel the accept thread because we only want to connect to one device if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;} // Start the thread to manage the connection and perform transmissions mConnectedThread = new ConnectedThread(socket); mConnectedThread.start(); // Send the name of the connected device back to the UI Activity Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME); Bundle bundle = new Bundle(); bundle.putString(BluetoothChat.DEVICE_NAME, device.getName()); msg.setData(bundle); mHandler.sendMessage(msg); setState(STATE_CONNECTED); } /** * Stop all threads */ public synchronized void stop() { if (D) Log.d(TAG, "stop"); if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;} if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;} setState(STATE_NONE); } /** * Write to the ConnectedThread in an unsynchronized manner * @param out The bytes to write * @see ConnectedThread#write(byte[]) */ public void write(byte[] out) { // Create temporary object ConnectedThread r; // Synchronize a copy of the ConnectedThread synchronized (this) { if (mState != STATE_CONNECTED) return; r = mConnectedThread; } // Perform the write unsynchronized r.write(out); } /** * Indicate that the connection attempt failed and notify the UI Activity. */ private void connectionFailed() { setState(STATE_LISTEN); // Send a failure message back to the Activity Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST); Bundle bundle = new Bundle(); bundle.putString(BluetoothChat.TOAST, "Unable to connect device"); msg.setData(bundle); mHandler.sendMessage(msg); } /** * Indicate that the connection was lost and notify the UI Activity. */ private void connectionLost() { setState(STATE_LISTEN); // Send a failure message back to the Activity Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST); Bundle bundle = new Bundle(); bundle.putString(BluetoothChat.TOAST, "Device connection was lost"); msg.setData(bundle); mHandler.sendMessage(msg); } /** * This thread runs while listening for incoming connections. It behaves * like a server-side client. It runs until a connection is accepted * (or until cancelled). */ private class AcceptThread extends Thread { // The local server socket private final BluetoothServerSocket mmServerSocket; public AcceptThread() { BluetoothServerSocket tmp = null; // Create a new listening server socket try { tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID); } catch (IOException e) { Log.e(TAG, "listen() failed", e); } mmServerSocket = tmp; } public void run() { if (D) Log.d(TAG, "BEGIN mAcceptThread" + this); setName("AcceptThread"); BluetoothSocket socket = null; // Listen to the server socket if we're not connected while (mState != STATE_CONNECTED) { try { // This is a blocking call and will only return on a // successful connection or an exception socket = mmServerSocket.accept(); } catch (IOException e) { Log.e(TAG, "accept() failed", e); break; } // If a connection was accepted if (socket != null) { synchronized (BluetoothChatService.this) { switch (mState) { case STATE_LISTEN: case STATE_CONNECTING: // Situation normal. Start the connected thread. connected(socket, socket.getRemoteDevice()); break; case STATE_NONE: case STATE_CONNECTED: // Either not ready or already connected. Terminate new socket. try { socket.close(); } catch (IOException e) { Log.e(TAG, "Could not close unwanted socket", e); } break; } } } } if (D) Log.i(TAG, "END mAcceptThread"); } public void cancel() { if (D) Log.d(TAG, "cancel " + this); try { mmServerSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of server failed", e); } } } /** * This thread runs while attempting to make an outgoing connection * with a device. It runs straight through; the connection either * succeeds or fails. */ private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) { mmDevice = device; BluetoothSocket tmp = null; // Get a BluetoothSocket for a connection with the // given BluetoothDevice try { tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { Log.e(TAG, "create() failed", e); } mmSocket = tmp; } public void run() { Log.i(TAG, "BEGIN mConnectThread"); setName("ConnectThread"); // Always cancel discovery because it will slow down a connection mAdapter.cancelDiscovery(); // Make a connection to the BluetoothSocket try { // This is a blocking call and will only return on a // successful connection or an exception mmSocket.connect(); } catch (IOException e) { connectionFailed(); // Close the socket try { mmSocket.close(); } catch (IOException e2) { Log.e(TAG, "unable to close() socket during connection failure", e2); } // Start the service over to restart listening mode BluetoothChatService.this.start(); return; } // Reset the ConnectThread because we're done synchronized (BluetoothChatService.this) { mConnectThread = null; } // Start the connected thread connected(mmSocket, mmDevice); } public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect socket failed", e); } } } /** * This thread runs during a connection with a remote device. * It handles all incoming and outgoing transmissions. */ private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { Log.d(TAG, "create ConnectedThread"); mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the BluetoothSocket input and output streams try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { Log.e(TAG, "temp sockets not created", e); } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { Log.i(TAG, "BEGIN mConnectedThread"); byte[] buffer = new byte[1024]; int bytes; // Keep listening to the InputStream while connected while (true) { try { // Read from the InputStream bytes = mmInStream.read(buffer); // Send the obtained bytes to the UI Activity mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { Log.e(TAG, "disconnected", e); connectionLost(); break; } } } /** * Write to the connected OutStream. * @param buffer The bytes to write */ public void write(byte[] buffer) { try { mmOutStream.write(buffer); // Share the sent message back to the UI Activity mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer) .sendToTarget(); } catch (IOException e) { Log.e(TAG, "Exception during write", e); } } public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect socket failed", e); } } } }
{ "content_hash": "89c54c065719e4bb8b8eed665ef89cc2", "timestamp": "", "source": "github", "line_count": 420, "max_line_length": 96, "avg_line_length": 35.59761904761905, "alnum_prop": 0.5789579292355026, "repo_name": "wahihi/SIVA", "id": "49fc313bb447090b77659acf667ed56bb65cee66", "size": "15570", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SIVA/arduino-HC-06-master/Android/BluetoothChat/src/com/example/android/BluetoothChat/BluetoothChatService.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Arduino", "bytes": "38236" }, { "name": "C++", "bytes": "54819" }, { "name": "Java", "bytes": "42458" }, { "name": "Python", "bytes": "910" } ], "symlink_target": "" }
package ru.lanwen.diff.uri.core.filters; import java.net.URI; /** * User: lanwen */ public interface UriDiffFilter { URI apply(URI uri); }
{ "content_hash": "169687db067e906fbd04b37b55624a1a", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 40, "avg_line_length": 14.7, "alnum_prop": 0.6870748299319728, "repo_name": "yandex-qatools/uri-differ", "id": "6e648825f970e7fadfe4345a5aff7065023de07f", "size": "147", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/ru/lanwen/diff/uri/core/filters/UriDiffFilter.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "43235" } ], "symlink_target": "" }
package com.rhcloud.igorbotian.rsskit.rest.facebook; /** * @author Igor Botian */ public class FacebookException extends Exception { public FacebookException() { super(); } public FacebookException(String message) { super(message); } public FacebookException(String message, Throwable cause) { super(message, cause); } public FacebookException(Throwable cause) { super(cause); } protected FacebookException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
{ "content_hash": "0e9e273be52aae2b99d728ffc8d5c45d", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 121, "avg_line_length": 24.11111111111111, "alnum_prop": 0.6897081413210445, "repo_name": "igorbotian/rsskit", "id": "16ca1bc4ef9fb1a9b21c723136f816c0c0b8f28c", "size": "651", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/rhcloud/igorbotian/rsskit/rest/facebook/FacebookException.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Java", "bytes": "1022" } ], "symlink_target": "" }