code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
package org.openbase.jul.pattern.controller;
/*
* #%L
* JUL Pattern Controller
* %%
* Copyright (C) 2015 - 2021 openbase.org
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
import org.openbase.jul.iface.Configurable;
import org.openbase.jul.iface.Manageable;
/**
*
* @author <a href="mailto:divine@openbase.org">Divine Threepwood</a>
* @param <ID> the identifier type
* @param <M> the data type
* @param <CONFIG> the configuration type
*/
public interface ConfigurableController<ID, M, CONFIG> extends IdentifiableController<ID, M>, Manageable<CONFIG>, Configurable<ID, CONFIG> {
}
| DivineCooperation/jul | pattern/controller/src/main/java/org/openbase/jul/pattern/controller/ConfigurableController.java | Java | lgpl-3.0 | 1,249 |
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
namespace Logging.Impl
{
/// <summary>
/// An implementation of <see cref="ILoggerFactory"/> that caches loggers created by the factory.
/// </summary>
/// <remarks>
/// For a concrete implementation, override <see cref="CreateLogger"/>.
/// </remarks>
public abstract class AbstractCachingLoggerFactory : ILoggerFactory
{
private readonly Hashtable _loggers;
/// <summary>
/// Creates a new instance of the caching logger factory.
/// </summary>
/// <param name="caseSensitiveCache">
/// If <c>true</c> loggers will be stored in the cache with case sensitivity.
/// </param>
protected AbstractCachingLoggerFactory(bool caseSensitiveCache)
{
_loggers = (caseSensitiveCache) ? new Hashtable() : CollectionsUtil.CreateCaseInsensitiveHashtable();
}
/// <summary>
/// Flushes the logger cache.
/// </summary>
protected void ClearCache()
{
lock (_loggers)
{
_loggers.Clear();
}
}
/// <summary>
/// Creates an instance of a logger with a specific name.
/// </summary>
/// <param name="name">The name of the logger.</param>
/// <remarks>
/// Derived factories need to implement this method to create the actual logger instance.
/// </remarks>
protected abstract ILogger CreateLogger(string name);
#region ILoggerFactory Members
/// <summary>
/// GetField an <see cref="ILogger"/> instance by type.
/// </summary>
/// <param name="type">The <see cref="Type">type</see> to use for the logger</param>
/// <returns>An <see cref="ILogger"/> instance.</returns>
public ILogger GetLogger(Type type)
{
if (type == null) throw new ArgumentNullException("type");
return GetLoggerInternal(type.FullName);
}
/// <summary>
/// GetField an <see cref="ILogger"/> instance by name.
/// </summary>
/// <param name="name">The name of the logger</param>
/// <returns>An <see cref="ILogger"/> instance.</returns>
public ILogger GetLogger(string name)
{
if (name == null) throw new ArgumentNullException("name");
return GetLoggerInternal(name);
}
/// <summary>
/// Gets a logger using the type of the calling class.
/// </summary>
/// <remarks>
/// This method needs to inspect the <see cref="StackTrace"/> in order to determine the calling
/// class. This of course comes with a performance penalty, thus you shouldn't call it too
/// often in your application.
/// </remarks>
/// <seealso cref="ILoggerFactory.GetLogger(System.Type)"/>
[MethodImpl(MethodImplOptions.NoInlining)]
public ILogger GetCurrentClassLogger()
{
var frame = new StackFrame(1, false);
return GetLogger(frame.GetMethod().DeclaringType);
}
#endregion
#region GetLoggerInternal
/// <summary>
/// GetField or create a <see cref="ILogger" /> instance by name.
/// </summary>
/// <param name="name">Usually a <see cref="Type" />'s Name or FullName property.</param>
/// <returns>
/// An <see cref="ILogger" /> instance either obtained from the internal cache or created by a call to <see cref="CreateLogger"/>.
/// </returns>
private ILogger GetLoggerInternal(string name)
{
var logger = _loggers[name] as ILogger;
if (logger == null)
{
lock (_loggers)
{
logger = _loggers[name] as ILogger;
if (logger == null)
{
logger = CreateLogger(name);
if (logger == null)
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} returned null on creating logger instance for name {1}", GetType().FullName, name));
}
}
}
}
return logger;
}
#endregion
}
}
| mishrsud/EnterpriseApplicationSamples | LoggingApplicationBlock/Source/Logging.Impl/AbstractCachingLoggerFactory.cs | C# | lgpl-3.0 | 3,872 |
package be.kwakeroni.workshop.java9.solution;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
new Main().handleFiles(args);
}
private final StudentParser parser = new StudentParser();
private void handleFiles(String[] args) throws Exception {
if (args.length == 0) {
handleGroups(
parser.parseStudents(Paths.get("group1.csv")),
parser.parseStudents(Paths.get("group2.csv")));
} else {
handleGroups(parse(args));
}
}
@SuppressWarnings("unchecked")
private List<Student>[] parse(String[] paths) {
return Arrays.stream(paths)
.map(Paths::get)
.map(this::parse)
.toArray(List[]::new);
}
private List<Student> parse(Path path) {
try {
return parser.parseStudents(path);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@java.lang.SafeVarargs
private void handleGroups(List<Student>... groups) {
for (int i = 0; i < groups.length; i++) {
System.out.println("- Group #%s".formatted(i));
groups[i].forEach(student -> System.out.println("-- %s %s (aged %s)".formatted(student.lastName(), student.firstName(), student.age())));
}
}
}
| kwakeroni/workshops | java9/solution/src/main/java/be/kwakeroni/workshop/java9/solution/Main.java | Java | lgpl-3.0 | 1,540 |
"""
Property reference docs:
- https://docs.microsoft.com/en-us/office/client-developer/outlook/mapi/mapping-canonical-property-names-to-mapi-names#tagged-properties
- https://interoperability.blob.core.windows.net/files/MS-OXPROPS/[MS-OXPROPS].pdf
- https://fossies.org/linux/libpst/xml/MAPI_definitions.pdf
- https://docs.microsoft.com/en-us/office/client-developer/outlook/mapi/mapi-constants
+----------------+----------------+-------------------------------------------------------------------------------+
| Range minimum | Range maximum | Description |
+----------------+----------------+-------------------------------------------------------------------------------+
| 0x0001 | 0x0BFF | Message object envelope property; reserved |
| 0x0C00 | 0x0DFF | Recipient property; reserved |
| 0x0E00 | 0x0FFF | Non-transmittable Message property; reserved |
| 0x1000 | 0x2FFF | Message content property; reserved |
| 0x3000 | 0x33FF | Multi-purpose property that can appear on all or most objects; reserved |
| 0x3400 | 0x35FF | Message store property; reserved |
| 0x3600 | 0x36FF | Folder and address book container property; reserved |
| 0x3700 | 0x38FF | Attachment property; reserved |
| 0x3900 | 0x39FF | Address Book object property; reserved |
| 0x3A00 | 0x3BFF | Mail user object property; reserved |
| 0x3C00 | 0x3CFF | Distribution list property; reserved |
| 0x3D00 | 0x3DFF | Profile section property; reserved |
| 0x3E00 | 0x3EFF | Status object property; reserved |
| 0x4000 | 0x57FF | Transport-defined envelope property |
| 0x5800 | 0x5FFF | Transport-defined recipient property |
| 0x6000 | 0x65FF | User-defined non-transmittable property |
| 0x6600 | 0x67FF | Provider-defined internal non-transmittable property |
| 0x6800 | 0x7BFF | Message class-defined content property |
| 0x7C00 | 0x7FFF | Message class-defined non-transmittable property |
| 0x8000 | 0xFFFF | Reserved for mapping to named properties. The exceptions to this rule are |
| | | some of the address book tagged properties (those with names beginning with |
| | | PIDTagAddressBook). Many are static property IDs but are in this range. |
+----------------+----------------+-------------------------------------------------------------------------------+
""" # noqa: E501
MAPI_ACKNOWLEDGEMENT_MODE = 0x0001
MAPI_ALTERNATE_RECIPIENT_ALLOWED = 0x0002
MAPI_AUTHORIZING_USERS = 0x0003
MAPI_AUTO_FORWARD_COMMENT = 0x0004
MAPI_AUTO_FORWARDED = 0x0005
MAPI_CONTENT_CONFIDENTIALITY_ALGORITHM_ID = 0x0006
MAPI_CONTENT_CORRELATOR = 0x0007
MAPI_CONTENT_IDENTIFIER = 0x0008
MAPI_CONTENT_LENGTH = 0x0009
MAPI_CONTENT_RETURN_REQUESTED = 0x000A
MAPI_CONVERSATION_KEY = 0x000B
MAPI_CONVERSION_EITS = 0x000C
MAPI_CONVERSION_WITH_LOSS_PROHIBITED = 0x000D
MAPI_CONVERTED_EITS = 0x000E
MAPI_DEFERRED_DELIVERY_TIME = 0x000F
MAPI_DELIVER_TIME = 0x0010
MAPI_DISCARD_REASON = 0x0011
MAPI_DISCLOSURE_OF_RECIPIENTS = 0x0012
MAPI_DL_EXPANSION_HISTORY = 0x0013
MAPI_DL_EXPANSION_PROHIBITED = 0x0014
MAPI_EXPIRY_TIME = 0x0015
MAPI_IMPLICIT_CONVERSION_PROHIBITED = 0x0016
MAPI_IMPORTANCE = 0x0017
MAPI_IPM_ID = 0x0018
MAPI_LATEST_DELIVERY_TIME = 0x0019
MAPI_MESSAGE_CLASS = 0x001A
MAPI_MESSAGE_DELIVERY_ID = 0x001B
MAPI_MESSAGE_SECURITY_LABEL = 0x001E
MAPI_OBSOLETED_IPMS = 0x001F
MAPI_ORIGINALLY_INTENDED_RECIPIENT_NAME = 0x0020
MAPI_ORIGINAL_EITS = 0x0021
MAPI_ORIGINATOR_CERTIFICATE = 0x0022
MAPI_ORIGINATOR_DELIVERY_REPORT_REQUESTED = 0x0023
MAPI_ORIGINATOR_RETURN_ADDRESS = 0x0024
MAPI_PARENT_KEY = 0x0025
MAPI_PRIORITY = 0x0026
MAPI_ORIGIN_CHECK = 0x0027
MAPI_PROOF_OF_SUBMISSION_REQUESTED = 0x0028
MAPI_READ_RECEIPT_REQUESTED = 0x0029
MAPI_RECEIPT_TIME = 0x002A
MAPI_RECIPIENT_REASSIGNMENT_PROHIBITED = 0x002B
MAPI_REDIRECTION_HISTORY = 0x002C
MAPI_RELATED_IPMS = 0x002D
MAPI_ORIGINAL_SENSITIVITY = 0x002E
MAPI_LANGUAGES = 0x002F
MAPI_REPLY_TIME = 0x0030
MAPI_REPORT_TAG = 0x0031
MAPI_REPORT_TIME = 0x0032
MAPI_RETURNED_IPM = 0x0033
MAPI_SECURITY = 0x0034
MAPI_INCOMPLETE_COPY = 0x0035
MAPI_SENSITIVITY = 0x0036
MAPI_SUBJECT = 0x0037
MAPI_SUBJECT_IPM = 0x0038
MAPI_CLIENT_SUBMIT_TIME = 0x0039
MAPI_REPORT_NAME = 0x003A
MAPI_SENT_REPRESENTING_SEARCH_KEY = 0x003B
MAPI_X400_CONTENT_TYPE = 0x003C
MAPI_SUBJECT_PREFIX = 0x003D
MAPI_NON_RECEIPT_REASON = 0x003E
MAPI_RECEIVED_BY_ENTRYID = 0x003F
MAPI_RECEIVED_BY_NAME = 0x0040
MAPI_SENT_REPRESENTING_ENTRYID = 0x0041
MAPI_SENT_REPRESENTING_NAME = 0x0042
MAPI_RCVD_REPRESENTING_ENTRYID = 0x0043
MAPI_RCVD_REPRESENTING_NAME = 0x0044
MAPI_REPORT_ENTRYID = 0x0045
MAPI_READ_RECEIPT_ENTRYID = 0x0046
MAPI_MESSAGE_SUBMISSION_ID = 0x0047
MAPI_PROVIDER_SUBMIT_TIME = 0x0048
MAPI_ORIGINAL_SUBJECT = 0x0049
MAPI_DISC_VAL = 0x004A
MAPI_ORIG_MESSAGE_CLASS = 0x004B
MAPI_ORIGINAL_AUTHOR_ENTRYID = 0x004C
MAPI_ORIGINAL_AUTHOR_NAME = 0x004D
MAPI_ORIGINAL_SUBMIT_TIME = 0x004E
MAPI_REPLY_RECIPIENT_ENTRIES = 0x004F
MAPI_REPLY_RECIPIENT_NAMES = 0x0050
MAPI_RECEIVED_BY_SEARCH_KEY = 0x0051
MAPI_RCVD_REPRESENTING_SEARCH_KEY = 0x0052
MAPI_READ_RECEIPT_SEARCH_KEY = 0x0053
MAPI_REPORT_SEARCH_KEY = 0x0054
MAPI_ORIGINAL_DELIVERY_TIME = 0x0055
MAPI_ORIGINAL_AUTHOR_SEARCH_KEY = 0x0056
MAPI_MESSAGE_TO_ME = 0x0057
MAPI_MESSAGE_CC_ME = 0x0058
MAPI_MESSAGE_RECIP_ME = 0x0059
MAPI_ORIGINAL_SENDER_NAME = 0x005A
MAPI_ORIGINAL_SENDER_ENTRYID = 0x005B
MAPI_ORIGINAL_SENDER_SEARCH_KEY = 0x005C
MAPI_ORIGINAL_SENT_REPRESENTING_NAME = 0x005D
MAPI_ORIGINAL_SENT_REPRESENTING_ENTRYID = 0x005E
MAPI_ORIGINAL_SENT_REPRESENTING_SEARCH_KEY = 0x005F
MAPI_START_DATE = 0x0060
MAPI_END_DATE = 0x0061
MAPI_OWNER_APPT_ID = 0x0062
MAPI_RESPONSE_REQUESTED = 0x0063
MAPI_SENT_REPRESENTING_ADDRTYPE = 0x0064
MAPI_SENT_REPRESENTING_EMAIL_ADDRESS = 0x0065
MAPI_ORIGINAL_SENDER_ADDRTYPE = 0x0066
MAPI_ORIGINAL_SENDER_EMAIL_ADDRESS = 0x0067
MAPI_ORIGINAL_SENT_REPRESENTING_ADDRTYPE = 0x0068
MAPI_ORIGINAL_SENT_REPRESENTING_EMAIL_ADDRESS = 0x0069
MAPI_CONVERSATION_TOPIC = 0x0070
MAPI_CONVERSATION_INDEX = 0x0071
MAPI_ORIGINAL_DISPLAY_BCC = 0x0072
MAPI_ORIGINAL_DISPLAY_CC = 0x0073
MAPI_ORIGINAL_DISPLAY_TO = 0x0074
MAPI_RECEIVED_BY_ADDRTYPE = 0x0075
MAPI_RECEIVED_BY_EMAIL_ADDRESS = 0x0076
MAPI_RCVD_REPRESENTING_ADDRTYPE = 0x0077
MAPI_RCVD_REPRESENTING_EMAIL_ADDRESS = 0x0078
MAPI_ORIGINAL_AUTHOR_ADDRTYPE = 0x0079
MAPI_ORIGINAL_AUTHOR_EMAIL_ADDRESS = 0x007A
MAPI_ORIGINALLY_INTENDED_RECIP_ADDRTYPE = 0x007B
MAPI_ORIGINALLY_INTENDED_RECIP_EMAIL_ADDRESS = 0x007C
MAPI_TRANSPORT_MESSAGE_HEADERS = 0x007D
MAPI_DELEGATION = 0x007E
MAPI_TNEF_CORRELATION_KEY = 0x007F
MAPI_CONTENT_INTEGRITY_CHECK = 0x0C00
MAPI_EXPLICIT_CONVERSION = 0x0C01
MAPI_IPM_RETURN_REQUESTED = 0x0C02
MAPI_MESSAGE_TOKEN = 0x0C03
MAPI_NDR_REASON_CODE = 0x0C04
MAPI_NDR_DIAG_CODE = 0x0C05
MAPI_NON_RECEIPT_NOTIFICATION_REQUESTED = 0x0C06
MAPI_DELIVERY_POINT = 0x0C07
MAPI_ORIGINATOR_NON_DELIVERY_REPORT_REQUESTED = 0x0C08
MAPI_ORIGINATOR_REQUESTED_ALTERNATE_RECIPIENT = 0x0C09
MAPI_PHYSICAL_DELIVERY_BUREAU_FAX_DELIVERY = 0x0C0A
MAPI_PHYSICAL_DELIVERY_MODE = 0x0C0B
MAPI_PHYSICAL_DELIVERY_REPORT_REQUEST = 0x0C0C
MAPI_PHYSICAL_FORWARDING_ADDRESS = 0x0C0D
MAPI_PHYSICAL_FORWARDING_ADDRESS_REQUESTED = 0x0C0E
MAPI_PHYSICAL_FORWARDING_PROHIBITED = 0x0C0F
MAPI_PHYSICAL_RENDITION_ATTRIBUTES = 0x0C10
MAPI_PROOF_OF_DELIVERY = 0x0C11
MAPI_PROOF_OF_DELIVERY_REQUESTED = 0x0C12
MAPI_RECIPIENT_CERTIFICATE = 0x0C13
MAPI_RECIPIENT_NUMBER_FOR_ADVICE = 0x0C14
MAPI_RECIPIENT_TYPE = 0x0C15
MAPI_REGISTERED_MAIL_TYPE = 0x0C16
MAPI_REPLY_REQUESTED = 0x0C17
MAPI_REQUESTED_DELIVERY_METHOD = 0x0C18
MAPI_SENDER_ENTRYID = 0x0C19
MAPI_SENDER_NAME = 0x0C1A
MAPI_SUPPLEMENTARY_INFO = 0x0C1B
MAPI_TYPE_OF_MTS_USER = 0x0C1C
MAPI_SENDER_SEARCH_KEY = 0x0C1D
MAPI_SENDER_ADDRTYPE = 0x0C1E
MAPI_SENDER_EMAIL_ADDRESS = 0x0C1F
MAPI_CURRENT_VERSION = 0x0E00
MAPI_DELETE_AFTER_SUBMIT = 0x0E01
MAPI_DISPLAY_BCC = 0x0E02
MAPI_DISPLAY_CC = 0x0E03
MAPI_DISPLAY_TO = 0x0E04
MAPI_PARENT_DISPLAY = 0x0E05
MAPI_MESSAGE_DELIVERY_TIME = 0x0E06
MAPI_MESSAGE_FLAGS = 0x0E07
MAPI_MESSAGE_SIZE = 0x0E08
MAPI_PARENT_ENTRYID = 0x0E09
MAPI_SENTMAIL_ENTRYID = 0x0E0A
MAPI_CORRELATE = 0x0E0C
MAPI_CORRELATE_MTSID = 0x0E0D
MAPI_DISCRETE_VALUES = 0x0E0E
MAPI_RESPONSIBILITY = 0x0E0F
MAPI_SPOOLER_STATUS = 0x0E10
MAPI_TRANSPORT_STATUS = 0x0E11
MAPI_MESSAGE_RECIPIENTS = 0x0E12
MAPI_MESSAGE_ATTACHMENTS = 0x0E13
MAPI_SUBMIT_FLAGS = 0x0E14
MAPI_RECIPIENT_STATUS = 0x0E15
MAPI_TRANSPORT_KEY = 0x0E16
MAPI_MSG_STATUS = 0x0E17
MAPI_MESSAGE_DOWNLOAD_TIME = 0x0E18
MAPI_CREATION_VERSION = 0x0E19
MAPI_MODIFY_VERSION = 0x0E1A
MAPI_HASATTACH = 0x0E1B
MAPI_BODY_CRC = 0x0E1C
MAPI_NORMALIZED_SUBJECT = 0x0E1D
MAPI_RTF_IN_SYNC = 0x0E1F
MAPI_ATTACH_SIZE = 0x0E20
MAPI_ATTACH_NUM = 0x0E21
MAPI_PREPROCESS = 0x0E22
MAPI_ORIGINATING_MTA_CERTIFICATE = 0x0E25
MAPI_PROOF_OF_SUBMISSION = 0x0E26
MAPI_PRIMARY_SEND_ACCOUNT = 0x0E28
MAPI_NEXT_SEND_ACCT = 0x0E29
MAPI_ACCESS = 0x0FF4
MAPI_ROW_TYPE = 0x0FF5
MAPI_INSTANCE_KEY = 0x0FF6
MAPI_ACCESS_LEVEL = 0x0FF7
MAPI_MAPPING_SIGNATURE = 0x0FF8
MAPI_RECORD_KEY = 0x0FF9
MAPI_STORE_RECORD_KEY = 0x0FFA
MAPI_STORE_ENTRYID = 0x0FFB
MAPI_MINI_ICON = 0x0FFC
MAPI_ICON = 0x0FFD
MAPI_OBJECT_TYPE = 0x0FFE
MAPI_ENTRYID = 0x0FFF
MAPI_BODY = 0x1000
MAPI_REPORT_TEXT = 0x1001
MAPI_ORIGINATOR_AND_DL_EXPANSION_HISTORY = 0x1002
MAPI_REPORTING_DL_NAME = 0x1003
MAPI_REPORTING_MTA_CERTIFICATE = 0x1004
MAPI_RTF_SYNC_BODY_CRC = 0x1006
MAPI_RTF_SYNC_BODY_COUNT = 0x1007
MAPI_RTF_SYNC_BODY_TAG = 0x1008
MAPI_RTF_COMPRESSED = 0x1009
MAPI_RTF_SYNC_PREFIX_COUNT = 0x1010
MAPI_RTF_SYNC_TRAILING_COUNT = 0x1011
MAPI_ORIGINALLY_INTENDED_RECIP_ENTRYID = 0x1012
MAPI_BODY_HTML = 0x1013
MAPI_NATIVE_BODY = 0x1016
MAPI_SMTP_MESSAGE_ID = 0x1035
MAPI_INTERNET_REFERENCES = 0x1039
MAPI_IN_REPLY_TO_ID = 0x1042
MAPI_INTERNET_RETURN_PATH = 0x1046
MAPI_ICON_INDEX = 0x1080
MAPI_LAST_VERB_EXECUTED = 0x1081
MAPI_LAST_VERB_EXECUTION_TIME = 0x1082
MAPI_URL_COMP_NAME = 0x10F3
MAPI_ATTRIBUTE_HIDDEN = 0x10F4
MAPI_ATTRIBUTE_SYSTEM = 0x10F5
MAPI_ATTRIBUTE_READ_ONLY = 0x10F6
MAPI_ROWID = 0x3000
MAPI_DISPLAY_NAME = 0x3001
MAPI_ADDRTYPE = 0x3002
MAPI_EMAIL_ADDRESS = 0x3003
MAPI_COMMENT = 0x3004
MAPI_DEPTH = 0x3005
MAPI_PROVIDER_DISPLAY = 0x3006
MAPI_CREATION_TIME = 0x3007
MAPI_LAST_MODIFICATION_TIME = 0x3008
MAPI_RESOURCE_FLAGS = 0x3009
MAPI_PROVIDER_DLL_NAME = 0x300A
MAPI_SEARCH_KEY = 0x300B
MAPI_PROVIDER_UID = 0x300C
MAPI_PROVIDER_ORDINAL = 0x300D
MAPI_TARGET_ENTRY_ID = 0x3010
MAPI_CONVERSATION_ID = 0x3013
MAPI_CONVERSATION_INDEX_TRACKING = 0x3016
MAPI_FORM_VERSION = 0x3301
MAPI_FORM_CLSID = 0x3302
MAPI_FORM_CONTACT_NAME = 0x3303
MAPI_FORM_CATEGORY = 0x3304
MAPI_FORM_CATEGORY_SUB = 0x3305
MAPI_FORM_HOST_MAP = 0x3306
MAPI_FORM_HIDDEN = 0x3307
MAPI_FORM_DESIGNER_NAME = 0x3308
MAPI_FORM_DESIGNER_GUID = 0x3309
MAPI_FORM_MESSAGE_BEHAVIOR = 0x330A
MAPI_DEFAULT_STORE = 0x3400
MAPI_STORE_SUPPORT_MASK = 0x340D
MAPI_STORE_STATE = 0x340E
MAPI_STORE_UNICODE_MASK = 0x340F
MAPI_IPM_SUBTREE_SEARCH_KEY = 0x3410
MAPI_IPM_OUTBOX_SEARCH_KEY = 0x3411
MAPI_IPM_WASTEBASKET_SEARCH_KEY = 0x3412
MAPI_IPM_SENTMAIL_SEARCH_KEY = 0x3413
MAPI_MDB_PROVIDER = 0x3414
MAPI_RECEIVE_FOLDER_SETTINGS = 0x3415
MAPI_VALID_FOLDER_MASK = 0x35DF
MAPI_IPM_SUBTREE_ENTRYID = 0x35E0
MAPI_IPM_OUTBOX_ENTRYID = 0x35E2
MAPI_IPM_WASTEBASKET_ENTRYID = 0x35E3
MAPI_IPM_SENTMAIL_ENTRYID = 0x35E4
MAPI_VIEWS_ENTRYID = 0x35E5
MAPI_COMMON_VIEWS_ENTRYID = 0x35E6
MAPI_FINDER_ENTRYID = 0x35E7
MAPI_CONTAINER_FLAGS = 0x3600
MAPI_FOLDER_TYPE = 0x3601
MAPI_CONTENT_COUNT = 0x3602
MAPI_CONTENT_UNREAD = 0x3603
MAPI_CREATE_TEMPLATES = 0x3604
MAPI_DETAILS_TABLE = 0x3605
MAPI_SEARCH = 0x3607
MAPI_SELECTABLE = 0x3609
MAPI_SUBFOLDERS = 0x360A
MAPI_STATUS = 0x360B
MAPI_ANR = 0x360C
MAPI_CONTENTS_SORT_ORDER = 0x360D
MAPI_CONTAINER_HIERARCHY = 0x360E
MAPI_CONTAINER_CONTENTS = 0x360F
MAPI_FOLDER_ASSOCIATED_CONTENTS = 0x3610
MAPI_DEF_CREATE_DL = 0x3611
MAPI_DEF_CREATE_MAILUSER = 0x3612
MAPI_CONTAINER_CLASS = 0x3613
MAPI_CONTAINER_MODIFY_VERSION = 0x3614
MAPI_AB_PROVIDER_ID = 0x3615
MAPI_DEFAULT_VIEW_ENTRYID = 0x3616
MAPI_ASSOC_CONTENT_COUNT = 0x3617
MAPI_ATTACHMENT_X400_PARAMETERS = 0x3700
MAPI_ATTACH_DATA_OBJ = 0x3701
MAPI_ATTACH_ENCODING = 0x3702
MAPI_ATTACH_EXTENSION = 0x3703
MAPI_ATTACH_FILENAME = 0x3704
MAPI_ATTACH_METHOD = 0x3705
MAPI_ATTACH_LONG_FILENAME = 0x3707
MAPI_ATTACH_PATHNAME = 0x3708
MAPI_ATTACH_RENDERING = 0x3709
MAPI_ATTACH_TAG = 0x370A
MAPI_RENDERING_POSITION = 0x370B
MAPI_ATTACH_TRANSPORT_NAME = 0x370C
MAPI_ATTACH_LONG_PATHNAME = 0x370D
MAPI_ATTACH_MIME_TAG = 0x370E
MAPI_ATTACH_ADDITIONAL_INFO = 0x370F
MAPI_ATTACH_MIME_SEQUENCE = 0x3710
MAPI_ATTACH_CONTENT_ID = 0x3712
MAPI_ATTACH_CONTENT_LOCATION = 0x3713
MAPI_ATTACH_FLAGS = 0x3714
MAPI_DISPLAY_TYPE = 0x3900
MAPI_TEMPLATEID = 0x3902
MAPI_PRIMARY_CAPABILITY = 0x3904
MAPI_SMTP_ADDRESS = 0x39FE
MAPI_7BIT_DISPLAY_NAME = 0x39FF
MAPI_ACCOUNT = 0x3A00
MAPI_ALTERNATE_RECIPIENT = 0x3A01
MAPI_CALLBACK_TELEPHONE_NUMBER = 0x3A02
MAPI_CONVERSION_PROHIBITED = 0x3A03
MAPI_DISCLOSE_RECIPIENTS = 0x3A04
MAPI_GENERATION = 0x3A05
MAPI_GIVEN_NAME = 0x3A06
MAPI_GOVERNMENT_ID_NUMBER = 0x3A07
MAPI_BUSINESS_TELEPHONE_NUMBER = 0x3A08
MAPI_HOME_TELEPHONE_NUMBER = 0x3A09
MAPI_INITIALS = 0x3A0A
MAPI_KEYWORD = 0x3A0B
MAPI_LANGUAGE = 0x3A0C
MAPI_LOCATION = 0x3A0D
MAPI_MAIL_PERMISSION = 0x3A0E
MAPI_MHS_COMMON_NAME = 0x3A0F
MAPI_ORGANIZATIONAL_ID_NUMBER = 0x3A10
MAPI_SURNAME = 0x3A11
MAPI_ORIGINAL_ENTRYID = 0x3A12
MAPI_ORIGINAL_DISPLAY_NAME = 0x3A13
MAPI_ORIGINAL_SEARCH_KEY = 0x3A14
MAPI_POSTAL_ADDRESS = 0x3A15
MAPI_COMPANY_NAME = 0x3A16
MAPI_TITLE = 0x3A17
MAPI_DEPARTMENT_NAME = 0x3A18
MAPI_OFFICE_LOCATION = 0x3A19
MAPI_PRIMARY_TELEPHONE_NUMBER = 0x3A1A
MAPI_BUSINESS2_TELEPHONE_NUMBER = 0x3A1B
MAPI_MOBILE_TELEPHONE_NUMBER = 0x3A1C
MAPI_RADIO_TELEPHONE_NUMBER = 0x3A1D
MAPI_CAR_TELEPHONE_NUMBER = 0x3A1E
MAPI_OTHER_TELEPHONE_NUMBER = 0x3A1F
MAPI_TRANSMITABLE_DISPLAY_NAME = 0x3A20
MAPI_PAGER_TELEPHONE_NUMBER = 0x3A21
MAPI_USER_CERTIFICATE = 0x3A22
MAPI_PRIMARY_FAX_NUMBER = 0x3A23
MAPI_BUSINESS_FAX_NUMBER = 0x3A24
MAPI_HOME_FAX_NUMBER = 0x3A25
MAPI_COUNTRY = 0x3A26
MAPI_LOCALITY = 0x3A27
MAPI_STATE_OR_PROVINCE = 0x3A28
MAPI_STREET_ADDRESS = 0x3A29
MAPI_POSTAL_CODE = 0x3A2A
MAPI_POST_OFFICE_BOX = 0x3A2B
MAPI_TELEX_NUMBER = 0x3A2C
MAPI_ISDN_NUMBER = 0x3A2D
MAPI_ASSISTANT_TELEPHONE_NUMBER = 0x3A2E
MAPI_HOME2_TELEPHONE_NUMBER = 0x3A2F
MAPI_ASSISTANT = 0x3A30
MAPI_SEND_RICH_INFO = 0x3A40
MAPI_WEDDING_ANNIVERSARY = 0x3A41
MAPI_BIRTHDAY = 0x3A42
MAPI_HOBBIES = 0x3A43
MAPI_MIDDLE_NAME = 0x3A44
MAPI_DISPLAY_NAME_PREFIX = 0x3A45
MAPI_PROFESSION = 0x3A46
MAPI_PREFERRED_BY_NAME = 0x3A47
MAPI_SPOUSE_NAME = 0x3A48
MAPI_COMPUTER_NETWORK_NAME = 0x3A49
MAPI_CUSTOMER_ID = 0x3A4A
MAPI_TTYTDD_PHONE_NUMBER = 0x3A4B
MAPI_FTP_SITE = 0x3A4C
MAPI_GENDER = 0x3A4D
MAPI_MANAGER_NAME = 0x3A4E
MAPI_NICKNAME = 0x3A4F
MAPI_PERSONAL_HOME_PAGE = 0x3A50
MAPI_BUSINESS_HOME_PAGE = 0x3A51
MAPI_CONTACT_VERSION = 0x3A52
MAPI_CONTACT_ENTRYIDS = 0x3A53
MAPI_CONTACT_ADDRTYPES = 0x3A54
MAPI_CONTACT_DEFAULT_ADDRESS_INDEX = 0x3A55
MAPI_CONTACT_EMAIL_ADDRESSES = 0x3A56
MAPI_COMPANY_MAIN_PHONE_NUMBER = 0x3A57
MAPI_CHILDRENS_NAMES = 0x3A58
MAPI_HOME_ADDRESS_CITY = 0x3A59
MAPI_HOME_ADDRESS_COUNTRY = 0x3A5A
MAPI_HOME_ADDRESS_POSTAL_CODE = 0x3A5B
MAPI_HOME_ADDRESS_STATE_OR_PROVINCE = 0x3A5C
MAPI_HOME_ADDRESS_STREET = 0x3A5D
MAPI_HOME_ADDRESS_POST_OFFICE_BOX = 0x3A5E
MAPI_OTHER_ADDRESS_CITY = 0x3A5F
MAPI_OTHER_ADDRESS_COUNTRY = 0x3A60
MAPI_OTHER_ADDRESS_POSTAL_CODE = 0x3A61
MAPI_OTHER_ADDRESS_STATE_OR_PROVINCE = 0x3A62
MAPI_OTHER_ADDRESS_STREET = 0x3A63
MAPI_OTHER_ADDRESS_POST_OFFICE_BOX = 0x3A64
MAPI_SEND_INTERNET_ENCODING = 0x3A71
MAPI_STORE_PROVIDERS = 0x3D00
MAPI_AB_PROVIDERS = 0x3D01
MAPI_TRANSPORT_PROVIDERS = 0x3D02
MAPI_DEFAULT_PROFILE = 0x3D04
MAPI_AB_SEARCH_PATH = 0x3D05
MAPI_AB_DEFAULT_DIR = 0x3D06
MAPI_AB_DEFAULT_PAB = 0x3D07
MAPI_FILTERING_HOOKS = 0x3D08
MAPI_SERVICE_NAME = 0x3D09
MAPI_SERVICE_DLL_NAME = 0x3D0A
MAPI_SERVICE_ENTRY_NAME = 0x3D0B
MAPI_SERVICE_UID = 0x3D0C
MAPI_SERVICE_EXTRA_UIDS = 0x3D0D
MAPI_SERVICES = 0x3D0E
MAPI_SERVICE_SUPPORT_FILES = 0x3D0F
MAPI_SERVICE_DELETE_FILES = 0x3D10
MAPI_AB_SEARCH_PATH_UPDATE = 0x3D11
MAPI_PROFILE_NAME = 0x3D12
MAPI_IDENTITY_DISPLAY = 0x3E00
MAPI_IDENTITY_ENTRYID = 0x3E01
MAPI_RESOURCE_METHODS = 0x3E02
MAPI_RESOURCE_TYPE = 0x3E03
MAPI_STATUS_CODE = 0x3E04
MAPI_IDENTITY_SEARCH_KEY = 0x3E05
MAPI_OWN_STORE_ENTRYID = 0x3E06
MAPI_RESOURCE_PATH = 0x3E07
MAPI_STATUS_STRING = 0x3E08
MAPI_X400_DEFERRED_DELIVERY_CANCEL = 0x3E09
MAPI_HEADER_FOLDER_ENTRYID = 0x3E0A
MAPI_REMOTE_PROGRESS = 0x3E0B
MAPI_REMOTE_PROGRESS_TEXT = 0x3E0C
MAPI_REMOTE_VALIDATE_OK = 0x3E0D
MAPI_CONTROL_FLAGS = 0x3F00
MAPI_CONTROL_STRUCTURE = 0x3F01
MAPI_CONTROL_TYPE = 0x3F02
MAPI_DELTAX = 0x3F03
MAPI_DELTAY = 0x3F04
MAPI_XPOS = 0x3F05
MAPI_YPOS = 0x3F06
MAPI_CONTROL_ID = 0x3F07
MAPI_INITIAL_DETAILS_PANE = 0x3F08
MAPI_UNCOMPRESSED_BODY = 0x3FD9
MAPI_INTERNET_CODEPAGE = 0x3FDE
MAPI_AUTO_RESPONSE_SUPPRESS = 0x3FDF
MAPI_MESSAGE_LOCALE_ID = 0x3FF1
MAPI_RULE_TRIGGER_HISTORY = 0x3FF2
MAPI_MOVE_TO_STORE_ENTRYID = 0x3FF3
MAPI_MOVE_TO_FOLDER_ENTRYID = 0x3FF4
MAPI_STORAGE_QUOTA_LIMIT = 0x3FF5
MAPI_EXCESS_STORAGE_USED = 0x3FF6
MAPI_SVR_GENERATING_QUOTA_MSG = 0x3FF7
MAPI_CREATOR_NAME = 0x3FF8
MAPI_CREATOR_ENTRY_ID = 0x3FF9
MAPI_LAST_MODIFIER_NAME = 0x3FFA
MAPI_LAST_MODIFIER_ENTRY_ID = 0x3FFB
MAPI_REPLY_RECIPIENT_SMTP_PROXIES = 0x3FFC
MAPI_MESSAGE_CODEPAGE = 0x3FFD
MAPI_EXTENDED_ACL_DATA = 0x3FFE
MAPI_SENDER_FLAGS = 0x4019
MAPI_SENT_REPRESENTING_FLAGS = 0x401A
MAPI_RECEIVED_BY_FLAGS = 0x401B
MAPI_RECEIVED_REPRESENTING_FLAGS = 0x401C
MAPI_CREATOR_ADDRESS_TYPE = 0x4022
MAPI_CREATOR_EMAIL_ADDRESS = 0x4023
MAPI_SENDER_SIMPLE_DISPLAY_NAME = 0x4030
MAPI_SENT_REPRESENTING_SIMPLE_DISPLAY_NAME = 0x4031
MAPI_RECEIVED_REPRESENTING_SIMPLE_DISPLAY_NAME = 0x4035
MAPI_CREATOR_SIMPLE_DISP_NAME = 0x4038
MAPI_LAST_MODIFIER_SIMPLE_DISPLAY_NAME = 0x4039
MAPI_CONTENT_FILTER_SPAM_CONFIDENCE_LEVEL = 0x4076
MAPI_INTERNET_MAIL_OVERRIDE_FORMAT = 0x5902
MAPI_MESSAGE_EDITOR_FORMAT = 0x5909
MAPI_SENDER_SMTP_ADDRESS = 0x5D01
MAPI_SENT_REPRESENTING_SMTP_ADDRESS = 0x5D02
MAPI_READ_RECEIPT_SMTP_ADDRESS = 0x5D05
MAPI_RECEIVED_BY_SMTP_ADDRESS = 0x5D07
MAPI_RECEIVED_REPRESENTING_SMTP_ADDRESS = 0x5D08
MAPI_SENDING_SMTP_ADDRESS = 0x5D09
MAPI_SIP_ADDRESS = 0x5FE5
MAPI_RECIPIENT_DISPLAY_NAME = 0x5FF6
MAPI_RECIPIENT_ENTRYID = 0x5FF7
MAPI_RECIPIENT_FLAGS = 0x5FFD
MAPI_RECIPIENT_TRACKSTATUS = 0x5FFF
MAPI_CHANGE_KEY = 0x65E2
MAPI_PREDECESSOR_CHANGE_LIST = 0x65E3
MAPI_ID_SECURE_MIN = 0x67F0
MAPI_ID_SECURE_MAX = 0x67FF
MAPI_VOICE_MESSAGE_DURATION = 0x6801
MAPI_SENDER_TELEPHONE_NUMBER = 0x6802
MAPI_VOICE_MESSAGE_SENDER_NAME = 0x6803
MAPI_FAX_NUMBER_OF_PAGES = 0x6804
MAPI_VOICE_MESSAGE_ATTACHMENT_ORDER = 0x6805
MAPI_CALL_ID = 0x6806
MAPI_ATTACHMENT_LINK_ID = 0x7FFA
MAPI_EXCEPTION_START_TIME = 0x7FFB
MAPI_EXCEPTION_END_TIME = 0x7FFC
MAPI_ATTACHMENT_FLAGS = 0x7FFD
MAPI_ATTACHMENT_HIDDEN = 0x7FFE
MAPI_ATTACHMENT_CONTACT_PHOTO = 0x7FFF
MAPI_FILE_UNDER = 0x8005
MAPI_FILE_UNDER_ID = 0x8006
MAPI_CONTACT_ITEM_DATA = 0x8007
MAPI_REFERRED_BY = 0x800E
MAPI_DEPARTMENT = 0x8010
MAPI_HAS_PICTURE = 0x8015
MAPI_HOME_ADDRESS = 0x801A
MAPI_WORK_ADDRESS = 0x801B
MAPI_OTHER_ADDRESS = 0x801C
MAPI_POSTAL_ADDRESS_ID = 0x8022
MAPI_CONTACT_CHARACTER_SET = 0x8023
MAPI_AUTO_LOG = 0x8025
MAPI_FILE_UNDER_LIST = 0x8026
MAPI_EMAIL_LIST = 0x8027
MAPI_ADDRESS_BOOK_PROVIDER_EMAIL_LIST = 0x8028
MAPI_ADDRESS_BOOK_PROVIDER_ARRAY_TYPE = 0x8029
MAPI_HTML = 0x802B
MAPI_YOMI_FIRST_NAME = 0x802C
MAPI_YOMI_LAST_NAME = 0x802D
MAPI_YOMI_COMPANY_NAME = 0x802E
MAPI_BUSINESS_CARD_DISPLAY_DEFINITION = 0x8040
MAPI_BUSINESS_CARD_CARD_PICTURE = 0x8041
MAPI_WORK_ADDRESS_STREET = 0x8045
MAPI_WORK_ADDRESS_CITY = 0x8046
MAPI_WORK_ADDRESS_STATE = 0x8047
MAPI_WORK_ADDRESS_POSTAL_CODE = 0x8048
MAPI_WORK_ADDRESS_COUNTRY = 0x8049
MAPI_WORK_ADDRESS_POST_OFFICE_BOX = 0x804A
MAPI_DISTRIBUTION_LIST_CHECKSUM = 0x804C
MAPI_BIRTHDAY_EVENT_ENTRY_ID = 0x804D
MAPI_ANNIVERSARY_EVENT_ENTRY_ID = 0x804E
MAPI_CONTACT_USER_FIELD1 = 0x804F
MAPI_CONTACT_USER_FIELD2 = 0x8050
MAPI_CONTACT_USER_FIELD3 = 0x8051
MAPI_CONTACT_USER_FIELD4 = 0x8052
MAPI_DISTRIBUTION_LIST_NAME = 0x8053
MAPI_DISTRIBUTION_LIST_ONE_OFF_MEMBERS = 0x8054
MAPI_DISTRIBUTION_LIST_MEMBERS = 0x8055
MAPI_INSTANT_MESSAGING_ADDRESS = 0x8062
MAPI_DISTRIBUTION_LIST_STREAM = 0x8064
MAPI_EMAIL_DISPLAY_NAME = 0x8080
MAPI_EMAIL_ADDR_TYPE = 0x8082
MAPI_EMAIL_EMAIL_ADDRESS = 0x8083
MAPI_EMAIL_ORIGINAL_DISPLAY_NAME = 0x8084
MAPI_EMAIL1ORIGINAL_ENTRY_ID = 0x8085
MAPI_EMAIL1RICH_TEXT_FORMAT = 0x8086
MAPI_EMAIL1EMAIL_TYPE = 0x8087
MAPI_EMAIL2DISPLAY_NAME = 0x8090
MAPI_EMAIL2ENTRY_ID = 0x8091
MAPI_EMAIL2ADDR_TYPE = 0x8092
MAPI_EMAIL2EMAIL_ADDRESS = 0x8093
MAPI_EMAIL2ORIGINAL_DISPLAY_NAME = 0x8094
MAPI_EMAIL2ORIGINAL_ENTRY_ID = 0x8095
MAPI_EMAIL2RICH_TEXT_FORMAT = 0x8096
MAPI_EMAIL3DISPLAY_NAME = 0x80A0
MAPI_EMAIL3ENTRY_ID = 0x80A1
MAPI_EMAIL3ADDR_TYPE = 0x80A2
MAPI_EMAIL3EMAIL_ADDRESS = 0x80A3
MAPI_EMAIL3ORIGINAL_DISPLAY_NAME = 0x80A4
MAPI_EMAIL3ORIGINAL_ENTRY_ID = 0x80A5
MAPI_EMAIL3RICH_TEXT_FORMAT = 0x80A6
MAPI_FAX1ADDRESS_TYPE = 0x80B2
MAPI_FAX1EMAIL_ADDRESS = 0x80B3
MAPI_FAX1ORIGINAL_DISPLAY_NAME = 0x80B4
MAPI_FAX1ORIGINAL_ENTRY_ID = 0x80B5
MAPI_FAX2ADDRESS_TYPE = 0x80C2
MAPI_FAX2EMAIL_ADDRESS = 0x80C3
MAPI_FAX2ORIGINAL_DISPLAY_NAME = 0x80C4
MAPI_FAX2ORIGINAL_ENTRY_ID = 0x80C5
MAPI_FAX3ADDRESS_TYPE = 0x80D2
MAPI_FAX3EMAIL_ADDRESS = 0x80D3
MAPI_FAX3ORIGINAL_DISPLAY_NAME = 0x80D4
MAPI_FAX3ORIGINAL_ENTRY_ID = 0x80D5
MAPI_FREE_BUSY_LOCATION = 0x80D8
MAPI_HOME_ADDRESS_COUNTRY_CODE = 0x80DA
MAPI_WORK_ADDRESS_COUNTRY_CODE = 0x80DB
MAPI_OTHER_ADDRESS_COUNTRY_CODE = 0x80DC
MAPI_ADDRESS_COUNTRY_CODE = 0x80DD
MAPI_BIRTHDAY_LOCAL = 0x80DE
MAPI_WEDDING_ANNIVERSARY_LOCAL = 0x80DF
MAPI_TASK_STATUS = 0x8101
MAPI_TASK_START_DATE = 0x8104
MAPI_TASK_DUE_DATE = 0x8105
MAPI_TASK_ACTUAL_EFFORT = 0x8110
MAPI_TASK_ESTIMATED_EFFORT = 0x8111
MAPI_TASK_FRECUR = 0x8126
MAPI_SEND_MEETING_AS_ICAL = 0x8200
MAPI_APPOINTMENT_SEQUENCE = 0x8201
MAPI_APPOINTMENT_SEQUENCE_TIME = 0x8202
MAPI_APPOINTMENT_LAST_SEQUENCE = 0x8203
MAPI_CHANGE_HIGHLIGHT = 0x8204
MAPI_BUSY_STATUS = 0x8205
MAPI_FEXCEPTIONAL_BODY = 0x8206
MAPI_APPOINTMENT_AUXILIARY_FLAGS = 0x8207
MAPI_OUTLOOK_LOCATION = 0x8208
MAPI_MEETING_WORKSPACE_URL = 0x8209
MAPI_FORWARD_INSTANCE = 0x820A
MAPI_LINKED_TASK_ITEMS = 0x820C
MAPI_APPT_START_WHOLE = 0x820D
MAPI_APPT_END_WHOLE = 0x820E
MAPI_APPOINTMENT_START_TIME = 0x820F
MAPI_APPOINTMENT_END_TIME = 0x8210
MAPI_APPOINTMENT_END_DATE = 0x8211
MAPI_APPOINTMENT_START_DATE = 0x8212
MAPI_APPT_DURATION = 0x8213
MAPI_APPOINTMENT_COLOR = 0x8214
MAPI_APPOINTMENT_SUB_TYPE = 0x8215
MAPI_APPOINTMENT_RECUR = 0x8216
MAPI_APPOINTMENT_STATE_FLAGS = 0x8217
MAPI_RESPONSE_STATUS = 0x8218
MAPI_APPOINTMENT_REPLY_TIME = 0x8220
MAPI_RECURRING = 0x8223
MAPI_INTENDED_BUSY_STATUS = 0x8224
MAPI_APPOINTMENT_UPDATE_TIME = 0x8226
MAPI_EXCEPTION_REPLACE_TIME = 0x8228
MAPI_OWNER_NAME = 0x822E
MAPI_APPOINTMENT_REPLY_NAME = 0x8230
MAPI_RECURRENCE_TYPE = 0x8231
MAPI_RECURRENCE_PATTERN = 0x8232
MAPI_TIME_ZONE_STRUCT = 0x8233
MAPI_TIME_ZONE_DESCRIPTION = 0x8234
MAPI_CLIP_START = 0x8235
MAPI_CLIP_END = 0x8236
MAPI_ORIGINAL_STORE_ENTRY_ID = 0x8237
MAPI_ALL_ATTENDEES_STRING = 0x8238
MAPI_AUTO_FILL_LOCATION = 0x823A
MAPI_TO_ATTENDEES_STRING = 0x823B
MAPI_CCATTENDEES_STRING = 0x823C
MAPI_CONF_CHECK = 0x8240
MAPI_CONFERENCING_TYPE = 0x8241
MAPI_DIRECTORY = 0x8242
MAPI_ORGANIZER_ALIAS = 0x8243
MAPI_AUTO_START_CHECK = 0x8244
MAPI_AUTO_START_WHEN = 0x8245
MAPI_ALLOW_EXTERNAL_CHECK = 0x8246
MAPI_COLLABORATE_DOC = 0x8247
MAPI_NET_SHOW_URL = 0x8248
MAPI_ONLINE_PASSWORD = 0x8249
MAPI_APPOINTMENT_PROPOSED_DURATION = 0x8256
MAPI_APPT_COUNTER_PROPOSAL = 0x8257
MAPI_APPOINTMENT_PROPOSAL_NUMBER = 0x8259
MAPI_APPOINTMENT_NOT_ALLOW_PROPOSE = 0x825A
MAPI_APPT_TZDEF_START_DISPLAY = 0x825E
MAPI_APPT_TZDEF_END_DISPLAY = 0x825F
MAPI_APPT_TZDEF_RECUR = 0x8260
MAPI_REMINDER_MINUTES_BEFORE_START = 0x8501
MAPI_REMINDER_TIME = 0x8502
MAPI_REMINDER_SET = 0x8503
MAPI_PRIVATE = 0x8506
MAPI_AGING_DONT_AGE_ME = 0x850E
MAPI_FORM_STORAGE = 0x850F
MAPI_SIDE_EFFECTS = 0x8510
MAPI_REMOTE_STATUS = 0x8511
MAPI_PAGE_DIR_STREAM = 0x8513
MAPI_SMART_NO_ATTACH = 0x8514
MAPI_COMMON_START = 0x8516
MAPI_COMMON_END = 0x8517
MAPI_TASK_MODE = 0x8518
MAPI_FORM_PROP_STREAM = 0x851B
MAPI_REQUEST = 0x8530
MAPI_NON_SENDABLE_TO = 0x8536
MAPI_NON_SENDABLE_CC = 0x8537
MAPI_NON_SENDABLE_BCC = 0x8538
MAPI_COMPANIES = 0x8539
MAPI_CONTACTS = 0x853A
MAPI_PROP_DEF_STREAM = 0x8540
MAPI_SCRIPT_STREAM = 0x8541
MAPI_CUSTOM_FLAG = 0x8542
MAPI_OUTLOOK_CURRENT_VERSION = 0x8552
MAPI_CURRENT_VERSION_NAME = 0x8554
MAPI_REMINDER_NEXT_TIME = 0x8560
MAPI_HEADER_ITEM = 0x8578
MAPI_USE_TNEF = 0x8582
MAPI_TO_DO_TITLE = 0x85A4
MAPI_VALID_FLAG_STRING_PROOF = 0x85BF
MAPI_LOG_TYPE = 0x8700
MAPI_LOG_START = 0x8706
MAPI_LOG_DURATION = 0x8707
MAPI_LOG_END = 0x8708
CODE_TO_NAME = {
MAPI_ACKNOWLEDGEMENT_MODE: "MAPI_ACKNOWLEDGEMENT_MODE",
MAPI_ALTERNATE_RECIPIENT_ALLOWED: "MAPI_ALTERNATE_RECIPIENT_ALLOWED",
MAPI_AUTHORIZING_USERS: "MAPI_AUTHORIZING_USERS",
MAPI_AUTO_FORWARD_COMMENT: "MAPI_AUTO_FORWARD_COMMENT",
MAPI_AUTO_FORWARDED: "MAPI_AUTO_FORWARDED",
MAPI_CONTENT_CONFIDENTIALITY_ALGORITHM_ID: "MAPI_CONTENT_CONFIDENTIALITY_ALGORITHM_ID",
MAPI_CONTENT_CORRELATOR: "MAPI_CONTENT_CORRELATOR",
MAPI_CONTENT_IDENTIFIER: "MAPI_CONTENT_IDENTIFIER",
MAPI_CONTENT_LENGTH: "MAPI_CONTENT_LENGTH",
MAPI_CONTENT_RETURN_REQUESTED: "MAPI_CONTENT_RETURN_REQUESTED",
MAPI_CONVERSATION_KEY: "MAPI_CONVERSATION_KEY",
MAPI_CONVERSION_EITS: "MAPI_CONVERSION_EITS",
MAPI_CONVERSION_WITH_LOSS_PROHIBITED: "MAPI_CONVERSION_WITH_LOSS_PROHIBITED",
MAPI_CONVERTED_EITS: "MAPI_CONVERTED_EITS",
MAPI_DEFERRED_DELIVERY_TIME: "MAPI_DEFERRED_DELIVERY_TIME",
MAPI_DELIVER_TIME: "MAPI_DELIVER_TIME",
MAPI_DISCARD_REASON: "MAPI_DISCARD_REASON",
MAPI_DISCLOSURE_OF_RECIPIENTS: "MAPI_DISCLOSURE_OF_RECIPIENTS",
MAPI_DL_EXPANSION_HISTORY: "MAPI_DL_EXPANSION_HISTORY",
MAPI_DL_EXPANSION_PROHIBITED: "MAPI_DL_EXPANSION_PROHIBITED",
MAPI_EXPIRY_TIME: "MAPI_EXPIRY_TIME",
MAPI_IMPLICIT_CONVERSION_PROHIBITED: "MAPI_IMPLICIT_CONVERSION_PROHIBITED",
MAPI_IMPORTANCE: "MAPI_IMPORTANCE",
MAPI_IPM_ID: "MAPI_IPM_ID",
MAPI_LATEST_DELIVERY_TIME: "MAPI_LATEST_DELIVERY_TIME",
MAPI_MESSAGE_CLASS: "MAPI_MESSAGE_CLASS",
MAPI_MESSAGE_DELIVERY_ID: "MAPI_MESSAGE_DELIVERY_ID",
MAPI_MESSAGE_SECURITY_LABEL: "MAPI_MESSAGE_SECURITY_LABEL",
MAPI_OBSOLETED_IPMS: "MAPI_OBSOLETED_IPMS",
MAPI_ORIGINALLY_INTENDED_RECIPIENT_NAME: "MAPI_ORIGINALLY_INTENDED_RECIPIENT_NAME",
MAPI_ORIGINAL_EITS: "MAPI_ORIGINAL_EITS",
MAPI_ORIGINATOR_CERTIFICATE: "MAPI_ORIGINATOR_CERTIFICATE",
MAPI_ORIGINATOR_DELIVERY_REPORT_REQUESTED: "MAPI_ORIGINATOR_DELIVERY_REPORT_REQUESTED",
MAPI_ORIGINATOR_RETURN_ADDRESS: "MAPI_ORIGINATOR_RETURN_ADDRESS",
MAPI_PARENT_KEY: "MAPI_PARENT_KEY",
MAPI_PRIORITY: "MAPI_PRIORITY",
MAPI_ORIGIN_CHECK: "MAPI_ORIGIN_CHECK",
MAPI_PROOF_OF_SUBMISSION_REQUESTED: "MAPI_PROOF_OF_SUBMISSION_REQUESTED",
MAPI_READ_RECEIPT_REQUESTED: "MAPI_READ_RECEIPT_REQUESTED",
MAPI_RECEIPT_TIME: "MAPI_RECEIPT_TIME",
MAPI_RECIPIENT_REASSIGNMENT_PROHIBITED: "MAPI_RECIPIENT_REASSIGNMENT_PROHIBITED",
MAPI_REDIRECTION_HISTORY: "MAPI_REDIRECTION_HISTORY",
MAPI_RELATED_IPMS: "MAPI_RELATED_IPMS",
MAPI_ORIGINAL_SENSITIVITY: "MAPI_ORIGINAL_SENSITIVITY",
MAPI_LANGUAGES: "MAPI_LANGUAGES",
MAPI_REPLY_TIME: "MAPI_REPLY_TIME",
MAPI_REPORT_TAG: "MAPI_REPORT_TAG",
MAPI_REPORT_TIME: "MAPI_REPORT_TIME",
MAPI_RETURNED_IPM: "MAPI_RETURNED_IPM",
MAPI_SECURITY: "MAPI_SECURITY",
MAPI_INCOMPLETE_COPY: "MAPI_INCOMPLETE_COPY",
MAPI_SENSITIVITY: "MAPI_SENSITIVITY",
MAPI_SUBJECT: "MAPI_SUBJECT",
MAPI_SUBJECT_IPM: "MAPI_SUBJECT_IPM",
MAPI_CLIENT_SUBMIT_TIME: "MAPI_CLIENT_SUBMIT_TIME",
MAPI_REPORT_NAME: "MAPI_REPORT_NAME",
MAPI_SENT_REPRESENTING_SEARCH_KEY: "MAPI_SENT_REPRESENTING_SEARCH_KEY",
MAPI_X400_CONTENT_TYPE: "MAPI_X400_CONTENT_TYPE",
MAPI_SUBJECT_PREFIX: "MAPI_SUBJECT_PREFIX",
MAPI_NON_RECEIPT_REASON: "MAPI_NON_RECEIPT_REASON",
MAPI_RECEIVED_BY_ENTRYID: "MAPI_RECEIVED_BY_ENTRYID",
MAPI_RECEIVED_BY_NAME: "MAPI_RECEIVED_BY_NAME",
MAPI_SENT_REPRESENTING_ENTRYID: "MAPI_SENT_REPRESENTING_ENTRYID",
MAPI_SENT_REPRESENTING_NAME: "MAPI_SENT_REPRESENTING_NAME",
MAPI_RCVD_REPRESENTING_ENTRYID: "MAPI_RCVD_REPRESENTING_ENTRYID",
MAPI_RCVD_REPRESENTING_NAME: "MAPI_RCVD_REPRESENTING_NAME",
MAPI_REPORT_ENTRYID: "MAPI_REPORT_ENTRYID",
MAPI_READ_RECEIPT_ENTRYID: "MAPI_READ_RECEIPT_ENTRYID",
MAPI_MESSAGE_SUBMISSION_ID: "MAPI_MESSAGE_SUBMISSION_ID",
MAPI_PROVIDER_SUBMIT_TIME: "MAPI_PROVIDER_SUBMIT_TIME",
MAPI_ORIGINAL_SUBJECT: "MAPI_ORIGINAL_SUBJECT",
MAPI_DISC_VAL: "MAPI_DISC_VAL",
MAPI_ORIG_MESSAGE_CLASS: "MAPI_ORIG_MESSAGE_CLASS",
MAPI_ORIGINAL_AUTHOR_ENTRYID: "MAPI_ORIGINAL_AUTHOR_ENTRYID",
MAPI_ORIGINAL_AUTHOR_NAME: "MAPI_ORIGINAL_AUTHOR_NAME",
MAPI_ORIGINAL_SUBMIT_TIME: "MAPI_ORIGINAL_SUBMIT_TIME",
MAPI_REPLY_RECIPIENT_ENTRIES: "MAPI_REPLY_RECIPIENT_ENTRIES",
MAPI_REPLY_RECIPIENT_NAMES: "MAPI_REPLY_RECIPIENT_NAMES",
MAPI_RECEIVED_BY_SEARCH_KEY: "MAPI_RECEIVED_BY_SEARCH_KEY",
MAPI_RCVD_REPRESENTING_SEARCH_KEY: "MAPI_RCVD_REPRESENTING_SEARCH_KEY",
MAPI_READ_RECEIPT_SEARCH_KEY: "MAPI_READ_RECEIPT_SEARCH_KEY",
MAPI_REPORT_SEARCH_KEY: "MAPI_REPORT_SEARCH_KEY",
MAPI_ORIGINAL_DELIVERY_TIME: "MAPI_ORIGINAL_DELIVERY_TIME",
MAPI_ORIGINAL_AUTHOR_SEARCH_KEY: "MAPI_ORIGINAL_AUTHOR_SEARCH_KEY",
MAPI_MESSAGE_TO_ME: "MAPI_MESSAGE_TO_ME",
MAPI_MESSAGE_CC_ME: "MAPI_MESSAGE_CC_ME",
MAPI_MESSAGE_RECIP_ME: "MAPI_MESSAGE_RECIP_ME",
MAPI_ORIGINAL_SENDER_NAME: "MAPI_ORIGINAL_SENDER_NAME",
MAPI_ORIGINAL_SENDER_ENTRYID: "MAPI_ORIGINAL_SENDER_ENTRYID",
MAPI_ORIGINAL_SENDER_SEARCH_KEY: "MAPI_ORIGINAL_SENDER_SEARCH_KEY",
MAPI_ORIGINAL_SENT_REPRESENTING_NAME: "MAPI_ORIGINAL_SENT_REPRESENTING_NAME",
MAPI_ORIGINAL_SENT_REPRESENTING_ENTRYID: "MAPI_ORIGINAL_SENT_REPRESENTING_ENTRYID",
MAPI_ORIGINAL_SENT_REPRESENTING_SEARCH_KEY: "MAPI_ORIGINAL_SENT_REPRESENTING_SEARCH_KEY",
MAPI_START_DATE: "MAPI_START_DATE",
MAPI_END_DATE: "MAPI_END_DATE",
MAPI_OWNER_APPT_ID: "MAPI_OWNER_APPT_ID",
MAPI_RESPONSE_REQUESTED: "MAPI_RESPONSE_REQUESTED",
MAPI_SENT_REPRESENTING_ADDRTYPE: "MAPI_SENT_REPRESENTING_ADDRTYPE",
MAPI_SENT_REPRESENTING_EMAIL_ADDRESS: "MAPI_SENT_REPRESENTING_EMAIL_ADDRESS",
MAPI_ORIGINAL_SENDER_ADDRTYPE: "MAPI_ORIGINAL_SENDER_ADDRTYPE",
MAPI_ORIGINAL_SENDER_EMAIL_ADDRESS: "MAPI_ORIGINAL_SENDER_EMAIL_ADDRESS",
MAPI_ORIGINAL_SENT_REPRESENTING_ADDRTYPE: "MAPI_ORIGINAL_SENT_REPRESENTING_ADDRTYPE",
MAPI_ORIGINAL_SENT_REPRESENTING_EMAIL_ADDRESS: "MAPI_ORIGINAL_SENT_REPRESENTING_EMAIL_ADDRESS",
MAPI_CONVERSATION_TOPIC: "MAPI_CONVERSATION_TOPIC",
MAPI_CONVERSATION_INDEX: "MAPI_CONVERSATION_INDEX",
MAPI_ORIGINAL_DISPLAY_BCC: "MAPI_ORIGINAL_DISPLAY_BCC",
MAPI_ORIGINAL_DISPLAY_CC: "MAPI_ORIGINAL_DISPLAY_CC",
MAPI_ORIGINAL_DISPLAY_TO: "MAPI_ORIGINAL_DISPLAY_TO",
MAPI_RECEIVED_BY_ADDRTYPE: "MAPI_RECEIVED_BY_ADDRTYPE",
MAPI_RECEIVED_BY_EMAIL_ADDRESS: "MAPI_RECEIVED_BY_EMAIL_ADDRESS",
MAPI_RCVD_REPRESENTING_ADDRTYPE: "MAPI_RCVD_REPRESENTING_ADDRTYPE",
MAPI_RCVD_REPRESENTING_EMAIL_ADDRESS: "MAPI_RCVD_REPRESENTING_EMAIL_ADDRESS",
MAPI_ORIGINAL_AUTHOR_ADDRTYPE: "MAPI_ORIGINAL_AUTHOR_ADDRTYPE",
MAPI_ORIGINAL_AUTHOR_EMAIL_ADDRESS: "MAPI_ORIGINAL_AUTHOR_EMAIL_ADDRESS",
MAPI_ORIGINALLY_INTENDED_RECIP_ADDRTYPE: "MAPI_ORIGINALLY_INTENDED_RECIP_ADDRTYPE",
MAPI_ORIGINALLY_INTENDED_RECIP_EMAIL_ADDRESS: "MAPI_ORIGINALLY_INTENDED_RECIP_EMAIL_ADDRESS",
MAPI_TRANSPORT_MESSAGE_HEADERS: "MAPI_TRANSPORT_MESSAGE_HEADERS",
MAPI_DELEGATION: "MAPI_DELEGATION",
MAPI_TNEF_CORRELATION_KEY: "MAPI_TNEF_CORRELATION_KEY",
MAPI_CONTENT_INTEGRITY_CHECK: "MAPI_CONTENT_INTEGRITY_CHECK",
MAPI_EXPLICIT_CONVERSION: "MAPI_EXPLICIT_CONVERSION",
MAPI_IPM_RETURN_REQUESTED: "MAPI_IPM_RETURN_REQUESTED",
MAPI_MESSAGE_TOKEN: "MAPI_MESSAGE_TOKEN",
MAPI_NDR_REASON_CODE: "MAPI_NDR_REASON_CODE",
MAPI_NDR_DIAG_CODE: "MAPI_NDR_DIAG_CODE",
MAPI_NON_RECEIPT_NOTIFICATION_REQUESTED: "MAPI_NON_RECEIPT_NOTIFICATION_REQUESTED",
MAPI_DELIVERY_POINT: "MAPI_DELIVERY_POINT",
MAPI_ORIGINATOR_NON_DELIVERY_REPORT_REQUESTED: "MAPI_ORIGINATOR_NON_DELIVERY_REPORT_REQUESTED",
MAPI_ORIGINATOR_REQUESTED_ALTERNATE_RECIPIENT: "MAPI_ORIGINATOR_REQUESTED_ALTERNATE_RECIPIENT",
MAPI_PHYSICAL_DELIVERY_BUREAU_FAX_DELIVERY: "MAPI_PHYSICAL_DELIVERY_BUREAU_FAX_DELIVERY",
MAPI_PHYSICAL_DELIVERY_MODE: "MAPI_PHYSICAL_DELIVERY_MODE",
MAPI_PHYSICAL_DELIVERY_REPORT_REQUEST: "MAPI_PHYSICAL_DELIVERY_REPORT_REQUEST",
MAPI_PHYSICAL_FORWARDING_ADDRESS: "MAPI_PHYSICAL_FORWARDING_ADDRESS",
MAPI_PHYSICAL_FORWARDING_ADDRESS_REQUESTED: "MAPI_PHYSICAL_FORWARDING_ADDRESS_REQUESTED",
MAPI_PHYSICAL_FORWARDING_PROHIBITED: "MAPI_PHYSICAL_FORWARDING_PROHIBITED",
MAPI_PHYSICAL_RENDITION_ATTRIBUTES: "MAPI_PHYSICAL_RENDITION_ATTRIBUTES",
MAPI_PROOF_OF_DELIVERY: "MAPI_PROOF_OF_DELIVERY",
MAPI_PROOF_OF_DELIVERY_REQUESTED: "MAPI_PROOF_OF_DELIVERY_REQUESTED",
MAPI_RECIPIENT_CERTIFICATE: "MAPI_RECIPIENT_CERTIFICATE",
MAPI_RECIPIENT_NUMBER_FOR_ADVICE: "MAPI_RECIPIENT_NUMBER_FOR_ADVICE",
MAPI_RECIPIENT_TYPE: "MAPI_RECIPIENT_TYPE",
MAPI_REGISTERED_MAIL_TYPE: "MAPI_REGISTERED_MAIL_TYPE",
MAPI_REPLY_REQUESTED: "MAPI_REPLY_REQUESTED",
MAPI_REQUESTED_DELIVERY_METHOD: "MAPI_REQUESTED_DELIVERY_METHOD",
MAPI_SENDER_ENTRYID: "MAPI_SENDER_ENTRYID",
MAPI_SENDER_NAME: "MAPI_SENDER_NAME",
MAPI_SUPPLEMENTARY_INFO: "MAPI_SUPPLEMENTARY_INFO",
MAPI_TYPE_OF_MTS_USER: "MAPI_TYPE_OF_MTS_USER",
MAPI_SENDER_SEARCH_KEY: "MAPI_SENDER_SEARCH_KEY",
MAPI_SENDER_ADDRTYPE: "MAPI_SENDER_ADDRTYPE",
MAPI_SENDER_EMAIL_ADDRESS: "MAPI_SENDER_EMAIL_ADDRESS",
MAPI_CURRENT_VERSION: "MAPI_CURRENT_VERSION",
MAPI_DELETE_AFTER_SUBMIT: "MAPI_DELETE_AFTER_SUBMIT",
MAPI_DISPLAY_BCC: "MAPI_DISPLAY_BCC",
MAPI_DISPLAY_CC: "MAPI_DISPLAY_CC",
MAPI_DISPLAY_TO: "MAPI_DISPLAY_TO",
MAPI_PARENT_DISPLAY: "MAPI_PARENT_DISPLAY",
MAPI_MESSAGE_DELIVERY_TIME: "MAPI_MESSAGE_DELIVERY_TIME",
MAPI_MESSAGE_FLAGS: "MAPI_MESSAGE_FLAGS",
MAPI_MESSAGE_SIZE: "MAPI_MESSAGE_SIZE",
MAPI_PARENT_ENTRYID: "MAPI_PARENT_ENTRYID",
MAPI_SENTMAIL_ENTRYID: "MAPI_SENTMAIL_ENTRYID",
MAPI_CORRELATE: "MAPI_CORRELATE",
MAPI_CORRELATE_MTSID: "MAPI_CORRELATE_MTSID",
MAPI_DISCRETE_VALUES: "MAPI_DISCRETE_VALUES",
MAPI_RESPONSIBILITY: "MAPI_RESPONSIBILITY",
MAPI_SPOOLER_STATUS: "MAPI_SPOOLER_STATUS",
MAPI_TRANSPORT_STATUS: "MAPI_TRANSPORT_STATUS",
MAPI_MESSAGE_RECIPIENTS: "MAPI_MESSAGE_RECIPIENTS",
MAPI_MESSAGE_ATTACHMENTS: "MAPI_MESSAGE_ATTACHMENTS",
MAPI_SUBMIT_FLAGS: "MAPI_SUBMIT_FLAGS",
MAPI_RECIPIENT_STATUS: "MAPI_RECIPIENT_STATUS",
MAPI_TRANSPORT_KEY: "MAPI_TRANSPORT_KEY",
MAPI_MSG_STATUS: "MAPI_MSG_STATUS",
MAPI_MESSAGE_DOWNLOAD_TIME: "MAPI_MESSAGE_DOWNLOAD_TIME",
MAPI_CREATION_VERSION: "MAPI_CREATION_VERSION",
MAPI_MODIFY_VERSION: "MAPI_MODIFY_VERSION",
MAPI_HASATTACH: "MAPI_HASATTACH",
MAPI_BODY_CRC: "MAPI_BODY_CRC",
MAPI_NORMALIZED_SUBJECT: "MAPI_NORMALIZED_SUBJECT",
MAPI_RTF_IN_SYNC: "MAPI_RTF_IN_SYNC",
MAPI_ATTACH_SIZE: "MAPI_ATTACH_SIZE",
MAPI_ATTACH_NUM: "MAPI_ATTACH_NUM",
MAPI_PREPROCESS: "MAPI_PREPROCESS",
MAPI_ORIGINATING_MTA_CERTIFICATE: "MAPI_ORIGINATING_MTA_CERTIFICATE",
MAPI_PROOF_OF_SUBMISSION: "MAPI_PROOF_OF_SUBMISSION",
MAPI_PRIMARY_SEND_ACCOUNT: "MAPI_PRIMARY_SEND_ACCOUNT",
MAPI_NEXT_SEND_ACCT: "MAPI_NEXT_SEND_ACCT",
MAPI_ACCESS: "MAPI_ACCESS",
MAPI_ROW_TYPE: "MAPI_ROW_TYPE",
MAPI_INSTANCE_KEY: "MAPI_INSTANCE_KEY",
MAPI_ACCESS_LEVEL: "MAPI_ACCESS_LEVEL",
MAPI_MAPPING_SIGNATURE: "MAPI_MAPPING_SIGNATURE",
MAPI_RECORD_KEY: "MAPI_RECORD_KEY",
MAPI_STORE_RECORD_KEY: "MAPI_STORE_RECORD_KEY",
MAPI_STORE_ENTRYID: "MAPI_STORE_ENTRYID",
MAPI_MINI_ICON: "MAPI_MINI_ICON",
MAPI_ICON: "MAPI_ICON",
MAPI_OBJECT_TYPE: "MAPI_OBJECT_TYPE",
MAPI_ENTRYID: "MAPI_ENTRYID",
MAPI_BODY: "MAPI_BODY",
MAPI_REPORT_TEXT: "MAPI_REPORT_TEXT",
MAPI_ORIGINATOR_AND_DL_EXPANSION_HISTORY: "MAPI_ORIGINATOR_AND_DL_EXPANSION_HISTORY",
MAPI_REPORTING_DL_NAME: "MAPI_REPORTING_DL_NAME",
MAPI_REPORTING_MTA_CERTIFICATE: "MAPI_REPORTING_MTA_CERTIFICATE",
MAPI_RTF_SYNC_BODY_CRC: "MAPI_RTF_SYNC_BODY_CRC",
MAPI_RTF_SYNC_BODY_COUNT: "MAPI_RTF_SYNC_BODY_COUNT",
MAPI_RTF_SYNC_BODY_TAG: "MAPI_RTF_SYNC_BODY_TAG",
MAPI_RTF_COMPRESSED: "MAPI_RTF_COMPRESSED",
MAPI_RTF_SYNC_PREFIX_COUNT: "MAPI_RTF_SYNC_PREFIX_COUNT",
MAPI_RTF_SYNC_TRAILING_COUNT: "MAPI_RTF_SYNC_TRAILING_COUNT",
MAPI_ORIGINALLY_INTENDED_RECIP_ENTRYID: "MAPI_ORIGINALLY_INTENDED_RECIP_ENTRYID",
MAPI_BODY_HTML: "MAPI_BODY_HTML",
MAPI_NATIVE_BODY: "MAPI_NATIVE_BODY",
MAPI_SMTP_MESSAGE_ID: "MAPI_SMTP_MESSAGE_ID",
MAPI_INTERNET_REFERENCES: "MAPI_INTERNET_REFERENCES",
MAPI_IN_REPLY_TO_ID: "MAPI_IN_REPLY_TO_ID",
MAPI_INTERNET_RETURN_PATH: "MAPI_INTERNET_RETURN_PATH",
MAPI_ICON_INDEX: "MAPI_ICON_INDEX",
MAPI_LAST_VERB_EXECUTED: "MAPI_LAST_VERB_EXECUTED",
MAPI_LAST_VERB_EXECUTION_TIME: "MAPI_LAST_VERB_EXECUTION_TIME",
MAPI_URL_COMP_NAME: "MAPI_URL_COMP_NAME",
MAPI_ATTRIBUTE_HIDDEN: "MAPI_ATTRIBUTE_HIDDEN",
MAPI_ATTRIBUTE_SYSTEM: "MAPI_ATTRIBUTE_SYSTEM",
MAPI_ATTRIBUTE_READ_ONLY: "MAPI_ATTRIBUTE_READ_ONLY",
MAPI_ROWID: "MAPI_ROWID",
MAPI_DISPLAY_NAME: "MAPI_DISPLAY_NAME",
MAPI_ADDRTYPE: "MAPI_ADDRTYPE",
MAPI_EMAIL_ADDRESS: "MAPI_EMAIL_ADDRESS",
MAPI_COMMENT: "MAPI_COMMENT",
MAPI_DEPTH: "MAPI_DEPTH",
MAPI_PROVIDER_DISPLAY: "MAPI_PROVIDER_DISPLAY",
MAPI_CREATION_TIME: "MAPI_CREATION_TIME",
MAPI_LAST_MODIFICATION_TIME: "MAPI_LAST_MODIFICATION_TIME",
MAPI_RESOURCE_FLAGS: "MAPI_RESOURCE_FLAGS",
MAPI_PROVIDER_DLL_NAME: "MAPI_PROVIDER_DLL_NAME",
MAPI_SEARCH_KEY: "MAPI_SEARCH_KEY",
MAPI_PROVIDER_UID: "MAPI_PROVIDER_UID",
MAPI_PROVIDER_ORDINAL: "MAPI_PROVIDER_ORDINAL",
MAPI_TARGET_ENTRY_ID: "MAPI_TARGET_ENTRY_ID",
MAPI_CONVERSATION_ID: "MAPI_CONVERSATION_ID",
MAPI_CONVERSATION_INDEX_TRACKING: "MAPI_CONVERSATION_INDEX_TRACKING",
MAPI_FORM_VERSION: "MAPI_FORM_VERSION",
MAPI_FORM_CLSID: "MAPI_FORM_CLSID",
MAPI_FORM_CONTACT_NAME: "MAPI_FORM_CONTACT_NAME",
MAPI_FORM_CATEGORY: "MAPI_FORM_CATEGORY",
MAPI_FORM_CATEGORY_SUB: "MAPI_FORM_CATEGORY_SUB",
MAPI_FORM_HOST_MAP: "MAPI_FORM_HOST_MAP",
MAPI_FORM_HIDDEN: "MAPI_FORM_HIDDEN",
MAPI_FORM_DESIGNER_NAME: "MAPI_FORM_DESIGNER_NAME",
MAPI_FORM_DESIGNER_GUID: "MAPI_FORM_DESIGNER_GUID",
MAPI_FORM_MESSAGE_BEHAVIOR: "MAPI_FORM_MESSAGE_BEHAVIOR",
MAPI_DEFAULT_STORE: "MAPI_DEFAULT_STORE",
MAPI_STORE_SUPPORT_MASK: "MAPI_STORE_SUPPORT_MASK",
MAPI_STORE_STATE: "MAPI_STORE_STATE",
MAPI_STORE_UNICODE_MASK: "MAPI_STORE_UNICODE_MASK",
MAPI_IPM_SUBTREE_SEARCH_KEY: "MAPI_IPM_SUBTREE_SEARCH_KEY",
MAPI_IPM_OUTBOX_SEARCH_KEY: "MAPI_IPM_OUTBOX_SEARCH_KEY",
MAPI_IPM_WASTEBASKET_SEARCH_KEY: "MAPI_IPM_WASTEBASKET_SEARCH_KEY",
MAPI_IPM_SENTMAIL_SEARCH_KEY: "MAPI_IPM_SENTMAIL_SEARCH_KEY",
MAPI_MDB_PROVIDER: "MAPI_MDB_PROVIDER",
MAPI_RECEIVE_FOLDER_SETTINGS: "MAPI_RECEIVE_FOLDER_SETTINGS",
MAPI_VALID_FOLDER_MASK: "MAPI_VALID_FOLDER_MASK",
MAPI_IPM_SUBTREE_ENTRYID: "MAPI_IPM_SUBTREE_ENTRYID",
MAPI_IPM_OUTBOX_ENTRYID: "MAPI_IPM_OUTBOX_ENTRYID",
MAPI_IPM_WASTEBASKET_ENTRYID: "MAPI_IPM_WASTEBASKET_ENTRYID",
MAPI_IPM_SENTMAIL_ENTRYID: "MAPI_IPM_SENTMAIL_ENTRYID",
MAPI_VIEWS_ENTRYID: "MAPI_VIEWS_ENTRYID",
MAPI_COMMON_VIEWS_ENTRYID: "MAPI_COMMON_VIEWS_ENTRYID",
MAPI_FINDER_ENTRYID: "MAPI_FINDER_ENTRYID",
MAPI_CONTAINER_FLAGS: "MAPI_CONTAINER_FLAGS",
MAPI_FOLDER_TYPE: "MAPI_FOLDER_TYPE",
MAPI_CONTENT_COUNT: "MAPI_CONTENT_COUNT",
MAPI_CONTENT_UNREAD: "MAPI_CONTENT_UNREAD",
MAPI_CREATE_TEMPLATES: "MAPI_CREATE_TEMPLATES",
MAPI_DETAILS_TABLE: "MAPI_DETAILS_TABLE",
MAPI_SEARCH: "MAPI_SEARCH",
MAPI_SELECTABLE: "MAPI_SELECTABLE",
MAPI_SUBFOLDERS: "MAPI_SUBFOLDERS",
MAPI_STATUS: "MAPI_STATUS",
MAPI_ANR: "MAPI_ANR",
MAPI_CONTENTS_SORT_ORDER: "MAPI_CONTENTS_SORT_ORDER",
MAPI_CONTAINER_HIERARCHY: "MAPI_CONTAINER_HIERARCHY",
MAPI_CONTAINER_CONTENTS: "MAPI_CONTAINER_CONTENTS",
MAPI_FOLDER_ASSOCIATED_CONTENTS: "MAPI_FOLDER_ASSOCIATED_CONTENTS",
MAPI_DEF_CREATE_DL: "MAPI_DEF_CREATE_DL",
MAPI_DEF_CREATE_MAILUSER: "MAPI_DEF_CREATE_MAILUSER",
MAPI_CONTAINER_CLASS: "MAPI_CONTAINER_CLASS",
MAPI_CONTAINER_MODIFY_VERSION: "MAPI_CONTAINER_MODIFY_VERSION",
MAPI_AB_PROVIDER_ID: "MAPI_AB_PROVIDER_ID",
MAPI_DEFAULT_VIEW_ENTRYID: "MAPI_DEFAULT_VIEW_ENTRYID",
MAPI_ASSOC_CONTENT_COUNT: "MAPI_ASSOC_CONTENT_COUNT",
MAPI_ATTACHMENT_X400_PARAMETERS: "MAPI_ATTACHMENT_X400_PARAMETERS",
MAPI_ATTACH_DATA_OBJ: "MAPI_ATTACH_DATA_OBJ",
MAPI_ATTACH_ENCODING: "MAPI_ATTACH_ENCODING",
MAPI_ATTACH_EXTENSION: "MAPI_ATTACH_EXTENSION",
MAPI_ATTACH_FILENAME: "MAPI_ATTACH_FILENAME",
MAPI_ATTACH_METHOD: "MAPI_ATTACH_METHOD",
MAPI_ATTACH_LONG_FILENAME: "MAPI_ATTACH_LONG_FILENAME",
MAPI_ATTACH_PATHNAME: "MAPI_ATTACH_PATHNAME",
MAPI_ATTACH_RENDERING: "MAPI_ATTACH_RENDERING",
MAPI_ATTACH_TAG: "MAPI_ATTACH_TAG",
MAPI_RENDERING_POSITION: "MAPI_RENDERING_POSITION",
MAPI_ATTACH_TRANSPORT_NAME: "MAPI_ATTACH_TRANSPORT_NAME",
MAPI_ATTACH_LONG_PATHNAME: "MAPI_ATTACH_LONG_PATHNAME",
MAPI_ATTACH_MIME_TAG: "MAPI_ATTACH_MIME_TAG",
MAPI_ATTACH_ADDITIONAL_INFO: "MAPI_ATTACH_ADDITIONAL_INFO",
MAPI_ATTACH_MIME_SEQUENCE: "MAPI_ATTACH_MIME_SEQUENCE",
MAPI_ATTACH_CONTENT_ID: "MAPI_ATTACH_CONTENT_ID",
MAPI_ATTACH_CONTENT_LOCATION: "MAPI_ATTACH_CONTENT_LOCATION",
MAPI_ATTACH_FLAGS: "MAPI_ATTACH_FLAGS",
MAPI_DISPLAY_TYPE: "MAPI_DISPLAY_TYPE",
MAPI_TEMPLATEID: "MAPI_TEMPLATEID",
MAPI_PRIMARY_CAPABILITY: "MAPI_PRIMARY_CAPABILITY",
MAPI_SMTP_ADDRESS: "MAPI_SMTP_ADDRESS",
MAPI_7BIT_DISPLAY_NAME: "MAPI_7BIT_DISPLAY_NAME",
MAPI_ACCOUNT: "MAPI_ACCOUNT",
MAPI_ALTERNATE_RECIPIENT: "MAPI_ALTERNATE_RECIPIENT",
MAPI_CALLBACK_TELEPHONE_NUMBER: "MAPI_CALLBACK_TELEPHONE_NUMBER",
MAPI_CONVERSION_PROHIBITED: "MAPI_CONVERSION_PROHIBITED",
MAPI_DISCLOSE_RECIPIENTS: "MAPI_DISCLOSE_RECIPIENTS",
MAPI_GENERATION: "MAPI_GENERATION",
MAPI_GIVEN_NAME: "MAPI_GIVEN_NAME",
MAPI_GOVERNMENT_ID_NUMBER: "MAPI_GOVERNMENT_ID_NUMBER",
MAPI_BUSINESS_TELEPHONE_NUMBER: "MAPI_BUSINESS_TELEPHONE_NUMBER",
MAPI_HOME_TELEPHONE_NUMBER: "MAPI_HOME_TELEPHONE_NUMBER",
MAPI_INITIALS: "MAPI_INITIALS",
MAPI_KEYWORD: "MAPI_KEYWORD",
MAPI_LANGUAGE: "MAPI_LANGUAGE",
MAPI_LOCATION: "MAPI_LOCATION",
MAPI_MAIL_PERMISSION: "MAPI_MAIL_PERMISSION",
MAPI_MHS_COMMON_NAME: "MAPI_MHS_COMMON_NAME",
MAPI_ORGANIZATIONAL_ID_NUMBER: "MAPI_ORGANIZATIONAL_ID_NUMBER",
MAPI_SURNAME: "MAPI_SURNAME",
MAPI_ORIGINAL_ENTRYID: "MAPI_ORIGINAL_ENTRYID",
MAPI_ORIGINAL_DISPLAY_NAME: "MAPI_ORIGINAL_DISPLAY_NAME",
MAPI_ORIGINAL_SEARCH_KEY: "MAPI_ORIGINAL_SEARCH_KEY",
MAPI_POSTAL_ADDRESS: "MAPI_POSTAL_ADDRESS",
MAPI_COMPANY_NAME: "MAPI_COMPANY_NAME",
MAPI_TITLE: "MAPI_TITLE",
MAPI_DEPARTMENT_NAME: "MAPI_DEPARTMENT_NAME",
MAPI_OFFICE_LOCATION: "MAPI_OFFICE_LOCATION",
MAPI_PRIMARY_TELEPHONE_NUMBER: "MAPI_PRIMARY_TELEPHONE_NUMBER",
MAPI_BUSINESS2_TELEPHONE_NUMBER: "MAPI_BUSINESS2_TELEPHONE_NUMBER",
MAPI_MOBILE_TELEPHONE_NUMBER: "MAPI_MOBILE_TELEPHONE_NUMBER",
MAPI_RADIO_TELEPHONE_NUMBER: "MAPI_RADIO_TELEPHONE_NUMBER",
MAPI_CAR_TELEPHONE_NUMBER: "MAPI_CAR_TELEPHONE_NUMBER",
MAPI_OTHER_TELEPHONE_NUMBER: "MAPI_OTHER_TELEPHONE_NUMBER",
MAPI_TRANSMITABLE_DISPLAY_NAME: "MAPI_TRANSMITABLE_DISPLAY_NAME",
MAPI_PAGER_TELEPHONE_NUMBER: "MAPI_PAGER_TELEPHONE_NUMBER",
MAPI_USER_CERTIFICATE: "MAPI_USER_CERTIFICATE",
MAPI_PRIMARY_FAX_NUMBER: "MAPI_PRIMARY_FAX_NUMBER",
MAPI_BUSINESS_FAX_NUMBER: "MAPI_BUSINESS_FAX_NUMBER",
MAPI_HOME_FAX_NUMBER: "MAPI_HOME_FAX_NUMBER",
MAPI_COUNTRY: "MAPI_COUNTRY",
MAPI_LOCALITY: "MAPI_LOCALITY",
MAPI_STATE_OR_PROVINCE: "MAPI_STATE_OR_PROVINCE",
MAPI_STREET_ADDRESS: "MAPI_STREET_ADDRESS",
MAPI_POSTAL_CODE: "MAPI_POSTAL_CODE",
MAPI_POST_OFFICE_BOX: "MAPI_POST_OFFICE_BOX",
MAPI_TELEX_NUMBER: "MAPI_TELEX_NUMBER",
MAPI_ISDN_NUMBER: "MAPI_ISDN_NUMBER",
MAPI_ASSISTANT_TELEPHONE_NUMBER: "MAPI_ASSISTANT_TELEPHONE_NUMBER",
MAPI_HOME2_TELEPHONE_NUMBER: "MAPI_HOME2_TELEPHONE_NUMBER",
MAPI_ASSISTANT: "MAPI_ASSISTANT",
MAPI_SEND_RICH_INFO: "MAPI_SEND_RICH_INFO",
MAPI_WEDDING_ANNIVERSARY: "MAPI_WEDDING_ANNIVERSARY",
MAPI_BIRTHDAY: "MAPI_BIRTHDAY",
MAPI_HOBBIES: "MAPI_HOBBIES",
MAPI_MIDDLE_NAME: "MAPI_MIDDLE_NAME",
MAPI_DISPLAY_NAME_PREFIX: "MAPI_DISPLAY_NAME_PREFIX",
MAPI_PROFESSION: "MAPI_PROFESSION",
MAPI_PREFERRED_BY_NAME: "MAPI_PREFERRED_BY_NAME",
MAPI_SPOUSE_NAME: "MAPI_SPOUSE_NAME",
MAPI_COMPUTER_NETWORK_NAME: "MAPI_COMPUTER_NETWORK_NAME",
MAPI_CUSTOMER_ID: "MAPI_CUSTOMER_ID",
MAPI_TTYTDD_PHONE_NUMBER: "MAPI_TTYTDD_PHONE_NUMBER",
MAPI_FTP_SITE: "MAPI_FTP_SITE",
MAPI_GENDER: "MAPI_GENDER",
MAPI_MANAGER_NAME: "MAPI_MANAGER_NAME",
MAPI_NICKNAME: "MAPI_NICKNAME",
MAPI_PERSONAL_HOME_PAGE: "MAPI_PERSONAL_HOME_PAGE",
MAPI_BUSINESS_HOME_PAGE: "MAPI_BUSINESS_HOME_PAGE",
MAPI_CONTACT_VERSION: "MAPI_CONTACT_VERSION",
MAPI_CONTACT_ENTRYIDS: "MAPI_CONTACT_ENTRYIDS",
MAPI_CONTACT_ADDRTYPES: "MAPI_CONTACT_ADDRTYPES",
MAPI_CONTACT_DEFAULT_ADDRESS_INDEX: "MAPI_CONTACT_DEFAULT_ADDRESS_INDEX",
MAPI_CONTACT_EMAIL_ADDRESSES: "MAPI_CONTACT_EMAIL_ADDRESSES",
MAPI_COMPANY_MAIN_PHONE_NUMBER: "MAPI_COMPANY_MAIN_PHONE_NUMBER",
MAPI_CHILDRENS_NAMES: "MAPI_CHILDRENS_NAMES",
MAPI_HOME_ADDRESS_CITY: "MAPI_HOME_ADDRESS_CITY",
MAPI_HOME_ADDRESS_COUNTRY: "MAPI_HOME_ADDRESS_COUNTRY",
MAPI_HOME_ADDRESS_POSTAL_CODE: "MAPI_HOME_ADDRESS_POSTAL_CODE",
MAPI_HOME_ADDRESS_STATE_OR_PROVINCE: "MAPI_HOME_ADDRESS_STATE_OR_PROVINCE",
MAPI_HOME_ADDRESS_STREET: "MAPI_HOME_ADDRESS_STREET",
MAPI_HOME_ADDRESS_POST_OFFICE_BOX: "MAPI_HOME_ADDRESS_POST_OFFICE_BOX",
MAPI_OTHER_ADDRESS_CITY: "MAPI_OTHER_ADDRESS_CITY",
MAPI_OTHER_ADDRESS_COUNTRY: "MAPI_OTHER_ADDRESS_COUNTRY",
MAPI_OTHER_ADDRESS_POSTAL_CODE: "MAPI_OTHER_ADDRESS_POSTAL_CODE",
MAPI_OTHER_ADDRESS_STATE_OR_PROVINCE: "MAPI_OTHER_ADDRESS_STATE_OR_PROVINCE",
MAPI_OTHER_ADDRESS_STREET: "MAPI_OTHER_ADDRESS_STREET",
MAPI_OTHER_ADDRESS_POST_OFFICE_BOX: "MAPI_OTHER_ADDRESS_POST_OFFICE_BOX",
MAPI_SEND_INTERNET_ENCODING: "MAPI_SEND_INTERNET_ENCODING",
MAPI_STORE_PROVIDERS: "MAPI_STORE_PROVIDERS",
MAPI_AB_PROVIDERS: "MAPI_AB_PROVIDERS",
MAPI_TRANSPORT_PROVIDERS: "MAPI_TRANSPORT_PROVIDERS",
MAPI_DEFAULT_PROFILE: "MAPI_DEFAULT_PROFILE",
MAPI_AB_SEARCH_PATH: "MAPI_AB_SEARCH_PATH",
MAPI_AB_DEFAULT_DIR: "MAPI_AB_DEFAULT_DIR",
MAPI_AB_DEFAULT_PAB: "MAPI_AB_DEFAULT_PAB",
MAPI_FILTERING_HOOKS: "MAPI_FILTERING_HOOKS",
MAPI_SERVICE_NAME: "MAPI_SERVICE_NAME",
MAPI_SERVICE_DLL_NAME: "MAPI_SERVICE_DLL_NAME",
MAPI_SERVICE_ENTRY_NAME: "MAPI_SERVICE_ENTRY_NAME",
MAPI_SERVICE_UID: "MAPI_SERVICE_UID",
MAPI_SERVICE_EXTRA_UIDS: "MAPI_SERVICE_EXTRA_UIDS",
MAPI_SERVICES: "MAPI_SERVICES",
MAPI_SERVICE_SUPPORT_FILES: "MAPI_SERVICE_SUPPORT_FILES",
MAPI_SERVICE_DELETE_FILES: "MAPI_SERVICE_DELETE_FILES",
MAPI_AB_SEARCH_PATH_UPDATE: "MAPI_AB_SEARCH_PATH_UPDATE",
MAPI_PROFILE_NAME: "MAPI_PROFILE_NAME",
MAPI_IDENTITY_DISPLAY: "MAPI_IDENTITY_DISPLAY",
MAPI_IDENTITY_ENTRYID: "MAPI_IDENTITY_ENTRYID",
MAPI_RESOURCE_METHODS: "MAPI_RESOURCE_METHODS",
MAPI_RESOURCE_TYPE: "MAPI_RESOURCE_TYPE",
MAPI_STATUS_CODE: "MAPI_STATUS_CODE",
MAPI_IDENTITY_SEARCH_KEY: "MAPI_IDENTITY_SEARCH_KEY",
MAPI_OWN_STORE_ENTRYID: "MAPI_OWN_STORE_ENTRYID",
MAPI_RESOURCE_PATH: "MAPI_RESOURCE_PATH",
MAPI_STATUS_STRING: "MAPI_STATUS_STRING",
MAPI_X400_DEFERRED_DELIVERY_CANCEL: "MAPI_X400_DEFERRED_DELIVERY_CANCEL",
MAPI_HEADER_FOLDER_ENTRYID: "MAPI_HEADER_FOLDER_ENTRYID",
MAPI_REMOTE_PROGRESS: "MAPI_REMOTE_PROGRESS",
MAPI_REMOTE_PROGRESS_TEXT: "MAPI_REMOTE_PROGRESS_TEXT",
MAPI_REMOTE_VALIDATE_OK: "MAPI_REMOTE_VALIDATE_OK",
MAPI_CONTROL_FLAGS: "MAPI_CONTROL_FLAGS",
MAPI_CONTROL_STRUCTURE: "MAPI_CONTROL_STRUCTURE",
MAPI_CONTROL_TYPE: "MAPI_CONTROL_TYPE",
MAPI_DELTAX: "MAPI_DELTAX",
MAPI_DELTAY: "MAPI_DELTAY",
MAPI_XPOS: "MAPI_XPOS",
MAPI_YPOS: "MAPI_YPOS",
MAPI_CONTROL_ID: "MAPI_CONTROL_ID",
MAPI_INITIAL_DETAILS_PANE: "MAPI_INITIAL_DETAILS_PANE",
MAPI_UNCOMPRESSED_BODY: "MAPI_UNCOMPRESSED_BODY",
MAPI_INTERNET_CODEPAGE: "MAPI_INTERNET_CODEPAGE",
MAPI_AUTO_RESPONSE_SUPPRESS: "MAPI_AUTO_RESPONSE_SUPPRESS",
MAPI_MESSAGE_LOCALE_ID: "MAPI_MESSAGE_LOCALE_ID",
MAPI_RULE_TRIGGER_HISTORY: "MAPI_RULE_TRIGGER_HISTORY",
MAPI_MOVE_TO_STORE_ENTRYID: "MAPI_MOVE_TO_STORE_ENTRYID",
MAPI_MOVE_TO_FOLDER_ENTRYID: "MAPI_MOVE_TO_FOLDER_ENTRYID",
MAPI_STORAGE_QUOTA_LIMIT: "MAPI_STORAGE_QUOTA_LIMIT",
MAPI_EXCESS_STORAGE_USED: "MAPI_EXCESS_STORAGE_USED",
MAPI_SVR_GENERATING_QUOTA_MSG: "MAPI_SVR_GENERATING_QUOTA_MSG",
MAPI_CREATOR_NAME: "MAPI_CREATOR_NAME",
MAPI_CREATOR_ENTRY_ID: "MAPI_CREATOR_ENTRY_ID",
MAPI_LAST_MODIFIER_NAME: "MAPI_LAST_MODIFIER_NAME",
MAPI_LAST_MODIFIER_ENTRY_ID: "MAPI_LAST_MODIFIER_ENTRY_ID",
MAPI_REPLY_RECIPIENT_SMTP_PROXIES: "MAPI_REPLY_RECIPIENT_SMTP_PROXIES",
MAPI_MESSAGE_CODEPAGE: "MAPI_MESSAGE_CODEPAGE",
MAPI_EXTENDED_ACL_DATA: "MAPI_EXTENDED_ACL_DATA",
MAPI_SENDER_FLAGS: "MAPI_SENDER_FLAGS",
MAPI_SENT_REPRESENTING_FLAGS: "MAPI_SENT_REPRESENTING_FLAGS",
MAPI_RECEIVED_BY_FLAGS: "MAPI_RECEIVED_BY_FLAGS",
MAPI_RECEIVED_REPRESENTING_FLAGS: "MAPI_RECEIVED_REPRESENTING_FLAGS",
MAPI_CREATOR_ADDRESS_TYPE: "MAPI_CREATOR_ADDRESS_TYPE",
MAPI_CREATOR_EMAIL_ADDRESS: "MAPI_CREATOR_EMAIL_ADDRESS",
MAPI_SENDER_SIMPLE_DISPLAY_NAME: "MAPI_SENDER_SIMPLE_DISPLAY_NAME",
MAPI_SENT_REPRESENTING_SIMPLE_DISPLAY_NAME: "MAPI_SENT_REPRESENTING_SIMPLE_DISPLAY_NAME",
MAPI_RECEIVED_REPRESENTING_SIMPLE_DISPLAY_NAME: "MAPI_RECEIVED_REPRESENTING_SIMPLE_DISPLAY_NAME",
MAPI_CREATOR_SIMPLE_DISP_NAME: "MAPI_CREATOR_SIMPLE_DISP_NAME",
MAPI_LAST_MODIFIER_SIMPLE_DISPLAY_NAME: "MAPI_LAST_MODIFIER_SIMPLE_DISPLAY_NAME",
MAPI_CONTENT_FILTER_SPAM_CONFIDENCE_LEVEL: "MAPI_CONTENT_FILTER_SPAM_CONFIDENCE_LEVEL",
MAPI_INTERNET_MAIL_OVERRIDE_FORMAT: "MAPI_INTERNET_MAIL_OVERRIDE_FORMAT",
MAPI_MESSAGE_EDITOR_FORMAT: "MAPI_MESSAGE_EDITOR_FORMAT",
MAPI_SENDER_SMTP_ADDRESS: "MAPI_SENDER_SMTP_ADDRESS",
MAPI_SENT_REPRESENTING_SMTP_ADDRESS: "MAPI_SENT_REPRESENTING_SMTP_ADDRESS",
MAPI_READ_RECEIPT_SMTP_ADDRESS: "MAPI_READ_RECEIPT_SMTP_ADDRESS",
MAPI_RECEIVED_BY_SMTP_ADDRESS: "MAPI_RECEIVED_BY_SMTP_ADDRESS",
MAPI_RECEIVED_REPRESENTING_SMTP_ADDRESS: "MAPI_RECEIVED_REPRESENTING_SMTP_ADDRESS",
MAPI_SENDING_SMTP_ADDRESS: "MAPI_SENDING_SMTP_ADDRESS",
MAPI_SIP_ADDRESS: "MAPI_SIP_ADDRESS",
MAPI_RECIPIENT_DISPLAY_NAME: "MAPI_RECIPIENT_DISPLAY_NAME",
MAPI_RECIPIENT_ENTRYID: "MAPI_RECIPIENT_ENTRYID",
MAPI_RECIPIENT_FLAGS: "MAPI_RECIPIENT_FLAGS",
MAPI_RECIPIENT_TRACKSTATUS: "MAPI_RECIPIENT_TRACKSTATUS",
MAPI_CHANGE_KEY: "MAPI_CHANGE_KEY",
MAPI_PREDECESSOR_CHANGE_LIST: "MAPI_PREDECESSOR_CHANGE_LIST",
MAPI_ID_SECURE_MIN: "MAPI_ID_SECURE_MIN",
MAPI_ID_SECURE_MAX: "MAPI_ID_SECURE_MAX",
MAPI_VOICE_MESSAGE_DURATION: "MAPI_VOICE_MESSAGE_DURATION",
MAPI_SENDER_TELEPHONE_NUMBER: "MAPI_SENDER_TELEPHONE_NUMBER",
MAPI_VOICE_MESSAGE_SENDER_NAME: "MAPI_VOICE_MESSAGE_SENDER_NAME",
MAPI_FAX_NUMBER_OF_PAGES: "MAPI_FAX_NUMBER_OF_PAGES",
MAPI_VOICE_MESSAGE_ATTACHMENT_ORDER: "MAPI_VOICE_MESSAGE_ATTACHMENT_ORDER",
MAPI_CALL_ID: "MAPI_CALL_ID",
MAPI_ATTACHMENT_LINK_ID: "MAPI_ATTACHMENT_LINK_ID",
MAPI_EXCEPTION_START_TIME: "MAPI_EXCEPTION_START_TIME",
MAPI_EXCEPTION_END_TIME: "MAPI_EXCEPTION_END_TIME",
MAPI_ATTACHMENT_FLAGS: "MAPI_ATTACHMENT_FLAGS",
MAPI_ATTACHMENT_HIDDEN: "MAPI_ATTACHMENT_HIDDEN",
MAPI_ATTACHMENT_CONTACT_PHOTO: "MAPI_ATTACHMENT_CONTACT_PHOTO",
MAPI_FILE_UNDER: "MAPI_FILE_UNDER",
MAPI_FILE_UNDER_ID: "MAPI_FILE_UNDER_ID",
MAPI_CONTACT_ITEM_DATA: "MAPI_CONTACT_ITEM_DATA",
MAPI_REFERRED_BY: "MAPI_REFERRED_BY",
MAPI_DEPARTMENT: "MAPI_DEPARTMENT",
MAPI_HAS_PICTURE: "MAPI_HAS_PICTURE",
MAPI_HOME_ADDRESS: "MAPI_HOME_ADDRESS",
MAPI_WORK_ADDRESS: "MAPI_WORK_ADDRESS",
MAPI_OTHER_ADDRESS: "MAPI_OTHER_ADDRESS",
MAPI_POSTAL_ADDRESS_ID: "MAPI_POSTAL_ADDRESS_ID",
MAPI_CONTACT_CHARACTER_SET: "MAPI_CONTACT_CHARACTER_SET",
MAPI_AUTO_LOG: "MAPI_AUTO_LOG",
MAPI_FILE_UNDER_LIST: "MAPI_FILE_UNDER_LIST",
MAPI_EMAIL_LIST: "MAPI_EMAIL_LIST",
MAPI_ADDRESS_BOOK_PROVIDER_EMAIL_LIST: "MAPI_ADDRESS_BOOK_PROVIDER_EMAIL_LIST",
MAPI_ADDRESS_BOOK_PROVIDER_ARRAY_TYPE: "MAPI_ADDRESS_BOOK_PROVIDER_ARRAY_TYPE",
MAPI_HTML: "MAPI_HTML",
MAPI_YOMI_FIRST_NAME: "MAPI_YOMI_FIRST_NAME",
MAPI_YOMI_LAST_NAME: "MAPI_YOMI_LAST_NAME",
MAPI_YOMI_COMPANY_NAME: "MAPI_YOMI_COMPANY_NAME",
MAPI_BUSINESS_CARD_DISPLAY_DEFINITION: "MAPI_BUSINESS_CARD_DISPLAY_DEFINITION",
MAPI_BUSINESS_CARD_CARD_PICTURE: "MAPI_BUSINESS_CARD_CARD_PICTURE",
MAPI_WORK_ADDRESS_STREET: "MAPI_WORK_ADDRESS_STREET",
MAPI_WORK_ADDRESS_CITY: "MAPI_WORK_ADDRESS_CITY",
MAPI_WORK_ADDRESS_STATE: "MAPI_WORK_ADDRESS_STATE",
MAPI_WORK_ADDRESS_POSTAL_CODE: "MAPI_WORK_ADDRESS_POSTAL_CODE",
MAPI_WORK_ADDRESS_COUNTRY: "MAPI_WORK_ADDRESS_COUNTRY",
MAPI_WORK_ADDRESS_POST_OFFICE_BOX: "MAPI_WORK_ADDRESS_POST_OFFICE_BOX",
MAPI_DISTRIBUTION_LIST_CHECKSUM: "MAPI_DISTRIBUTION_LIST_CHECKSUM",
MAPI_BIRTHDAY_EVENT_ENTRY_ID: "MAPI_BIRTHDAY_EVENT_ENTRY_ID",
MAPI_ANNIVERSARY_EVENT_ENTRY_ID: "MAPI_ANNIVERSARY_EVENT_ENTRY_ID",
MAPI_CONTACT_USER_FIELD1: "MAPI_CONTACT_USER_FIELD1",
MAPI_CONTACT_USER_FIELD2: "MAPI_CONTACT_USER_FIELD2",
MAPI_CONTACT_USER_FIELD3: "MAPI_CONTACT_USER_FIELD3",
MAPI_CONTACT_USER_FIELD4: "MAPI_CONTACT_USER_FIELD4",
MAPI_DISTRIBUTION_LIST_NAME: "MAPI_DISTRIBUTION_LIST_NAME",
MAPI_DISTRIBUTION_LIST_ONE_OFF_MEMBERS: "MAPI_DISTRIBUTION_LIST_ONE_OFF_MEMBERS",
MAPI_DISTRIBUTION_LIST_MEMBERS: "MAPI_DISTRIBUTION_LIST_MEMBERS",
MAPI_INSTANT_MESSAGING_ADDRESS: "MAPI_INSTANT_MESSAGING_ADDRESS",
MAPI_DISTRIBUTION_LIST_STREAM: "MAPI_DISTRIBUTION_LIST_STREAM",
MAPI_EMAIL_DISPLAY_NAME: "MAPI_EMAIL_DISPLAY_NAME",
MAPI_EMAIL_ADDR_TYPE: "MAPI_EMAIL_ADDR_TYPE",
MAPI_EMAIL_EMAIL_ADDRESS: "MAPI_EMAIL_EMAIL_ADDRESS",
MAPI_EMAIL_ORIGINAL_DISPLAY_NAME: "MAPI_EMAIL_ORIGINAL_DISPLAY_NAME",
MAPI_EMAIL1ORIGINAL_ENTRY_ID: "MAPI_EMAIL1ORIGINAL_ENTRY_ID",
MAPI_EMAIL1RICH_TEXT_FORMAT: "MAPI_EMAIL1RICH_TEXT_FORMAT",
MAPI_EMAIL1EMAIL_TYPE: "MAPI_EMAIL1EMAIL_TYPE",
MAPI_EMAIL2DISPLAY_NAME: "MAPI_EMAIL2DISPLAY_NAME",
MAPI_EMAIL2ENTRY_ID: "MAPI_EMAIL2ENTRY_ID",
MAPI_EMAIL2ADDR_TYPE: "MAPI_EMAIL2ADDR_TYPE",
MAPI_EMAIL2EMAIL_ADDRESS: "MAPI_EMAIL2EMAIL_ADDRESS",
MAPI_EMAIL2ORIGINAL_DISPLAY_NAME: "MAPI_EMAIL2ORIGINAL_DISPLAY_NAME",
MAPI_EMAIL2ORIGINAL_ENTRY_ID: "MAPI_EMAIL2ORIGINAL_ENTRY_ID",
MAPI_EMAIL2RICH_TEXT_FORMAT: "MAPI_EMAIL2RICH_TEXT_FORMAT",
MAPI_EMAIL3DISPLAY_NAME: "MAPI_EMAIL3DISPLAY_NAME",
MAPI_EMAIL3ENTRY_ID: "MAPI_EMAIL3ENTRY_ID",
MAPI_EMAIL3ADDR_TYPE: "MAPI_EMAIL3ADDR_TYPE",
MAPI_EMAIL3EMAIL_ADDRESS: "MAPI_EMAIL3EMAIL_ADDRESS",
MAPI_EMAIL3ORIGINAL_DISPLAY_NAME: "MAPI_EMAIL3ORIGINAL_DISPLAY_NAME",
MAPI_EMAIL3ORIGINAL_ENTRY_ID: "MAPI_EMAIL3ORIGINAL_ENTRY_ID",
MAPI_EMAIL3RICH_TEXT_FORMAT: "MAPI_EMAIL3RICH_TEXT_FORMAT",
MAPI_FAX1ADDRESS_TYPE: "MAPI_FAX1ADDRESS_TYPE",
MAPI_FAX1EMAIL_ADDRESS: "MAPI_FAX1EMAIL_ADDRESS",
MAPI_FAX1ORIGINAL_DISPLAY_NAME: "MAPI_FAX1ORIGINAL_DISPLAY_NAME",
MAPI_FAX1ORIGINAL_ENTRY_ID: "MAPI_FAX1ORIGINAL_ENTRY_ID",
MAPI_FAX2ADDRESS_TYPE: "MAPI_FAX2ADDRESS_TYPE",
MAPI_FAX2EMAIL_ADDRESS: "MAPI_FAX2EMAIL_ADDRESS",
MAPI_FAX2ORIGINAL_DISPLAY_NAME: "MAPI_FAX2ORIGINAL_DISPLAY_NAME",
MAPI_FAX2ORIGINAL_ENTRY_ID: "MAPI_FAX2ORIGINAL_ENTRY_ID",
MAPI_FAX3ADDRESS_TYPE: "MAPI_FAX3ADDRESS_TYPE",
MAPI_FAX3EMAIL_ADDRESS: "MAPI_FAX3EMAIL_ADDRESS",
MAPI_FAX3ORIGINAL_DISPLAY_NAME: "MAPI_FAX3ORIGINAL_DISPLAY_NAME",
MAPI_FAX3ORIGINAL_ENTRY_ID: "MAPI_FAX3ORIGINAL_ENTRY_ID",
MAPI_FREE_BUSY_LOCATION: "MAPI_FREE_BUSY_LOCATION",
MAPI_HOME_ADDRESS_COUNTRY_CODE: "MAPI_HOME_ADDRESS_COUNTRY_CODE",
MAPI_WORK_ADDRESS_COUNTRY_CODE: "MAPI_WORK_ADDRESS_COUNTRY_CODE",
MAPI_OTHER_ADDRESS_COUNTRY_CODE: "MAPI_OTHER_ADDRESS_COUNTRY_CODE",
MAPI_ADDRESS_COUNTRY_CODE: "MAPI_ADDRESS_COUNTRY_CODE",
MAPI_BIRTHDAY_LOCAL: "MAPI_BIRTHDAY_LOCAL",
MAPI_WEDDING_ANNIVERSARY_LOCAL: "MAPI_WEDDING_ANNIVERSARY_LOCAL",
MAPI_TASK_STATUS: "MAPI_TASK_STATUS",
MAPI_TASK_START_DATE: "MAPI_TASK_START_DATE",
MAPI_TASK_DUE_DATE: "MAPI_TASK_DUE_DATE",
MAPI_TASK_ACTUAL_EFFORT: "MAPI_TASK_ACTUAL_EFFORT",
MAPI_TASK_ESTIMATED_EFFORT: "MAPI_TASK_ESTIMATED_EFFORT",
MAPI_TASK_FRECUR: "MAPI_TASK_FRECUR",
MAPI_SEND_MEETING_AS_ICAL: "MAPI_SEND_MEETING_AS_ICAL",
MAPI_APPOINTMENT_SEQUENCE: "MAPI_APPOINTMENT_SEQUENCE",
MAPI_APPOINTMENT_SEQUENCE_TIME: "MAPI_APPOINTMENT_SEQUENCE_TIME",
MAPI_APPOINTMENT_LAST_SEQUENCE: "MAPI_APPOINTMENT_LAST_SEQUENCE",
MAPI_CHANGE_HIGHLIGHT: "MAPI_CHANGE_HIGHLIGHT",
MAPI_BUSY_STATUS: "MAPI_BUSY_STATUS",
MAPI_FEXCEPTIONAL_BODY: "MAPI_FEXCEPTIONAL_BODY",
MAPI_APPOINTMENT_AUXILIARY_FLAGS: "MAPI_APPOINTMENT_AUXILIARY_FLAGS",
MAPI_OUTLOOK_LOCATION: "MAPI_OUTLOOK_LOCATION",
MAPI_MEETING_WORKSPACE_URL: "MAPI_MEETING_WORKSPACE_URL",
MAPI_FORWARD_INSTANCE: "MAPI_FORWARD_INSTANCE",
MAPI_LINKED_TASK_ITEMS: "MAPI_LINKED_TASK_ITEMS",
MAPI_APPT_START_WHOLE: "MAPI_APPT_START_WHOLE",
MAPI_APPT_END_WHOLE: "MAPI_APPT_END_WHOLE",
MAPI_APPOINTMENT_START_TIME: "MAPI_APPOINTMENT_START_TIME",
MAPI_APPOINTMENT_END_TIME: "MAPI_APPOINTMENT_END_TIME",
MAPI_APPOINTMENT_END_DATE: "MAPI_APPOINTMENT_END_DATE",
MAPI_APPOINTMENT_START_DATE: "MAPI_APPOINTMENT_START_DATE",
MAPI_APPT_DURATION: "MAPI_APPT_DURATION",
MAPI_APPOINTMENT_COLOR: "MAPI_APPOINTMENT_COLOR",
MAPI_APPOINTMENT_SUB_TYPE: "MAPI_APPOINTMENT_SUB_TYPE",
MAPI_APPOINTMENT_RECUR: "MAPI_APPOINTMENT_RECUR",
MAPI_APPOINTMENT_STATE_FLAGS: "MAPI_APPOINTMENT_STATE_FLAGS",
MAPI_RESPONSE_STATUS: "MAPI_RESPONSE_STATUS",
MAPI_APPOINTMENT_REPLY_TIME: "MAPI_APPOINTMENT_REPLY_TIME",
MAPI_RECURRING: "MAPI_RECURRING",
MAPI_INTENDED_BUSY_STATUS: "MAPI_INTENDED_BUSY_STATUS",
MAPI_APPOINTMENT_UPDATE_TIME: "MAPI_APPOINTMENT_UPDATE_TIME",
MAPI_EXCEPTION_REPLACE_TIME: "MAPI_EXCEPTION_REPLACE_TIME",
MAPI_OWNER_NAME: "MAPI_OWNER_NAME",
MAPI_APPOINTMENT_REPLY_NAME: "MAPI_APPOINTMENT_REPLY_NAME",
MAPI_RECURRENCE_TYPE: "MAPI_RECURRENCE_TYPE",
MAPI_RECURRENCE_PATTERN: "MAPI_RECURRENCE_PATTERN",
MAPI_TIME_ZONE_STRUCT: "MAPI_TIME_ZONE_STRUCT",
MAPI_TIME_ZONE_DESCRIPTION: "MAPI_TIME_ZONE_DESCRIPTION",
MAPI_CLIP_START: "MAPI_CLIP_START",
MAPI_CLIP_END: "MAPI_CLIP_END",
MAPI_ORIGINAL_STORE_ENTRY_ID: "MAPI_ORIGINAL_STORE_ENTRY_ID",
MAPI_ALL_ATTENDEES_STRING: "MAPI_ALL_ATTENDEES_STRING",
MAPI_AUTO_FILL_LOCATION: "MAPI_AUTO_FILL_LOCATION",
MAPI_TO_ATTENDEES_STRING: "MAPI_TO_ATTENDEES_STRING",
MAPI_CCATTENDEES_STRING: "MAPI_CCATTENDEES_STRING",
MAPI_CONF_CHECK: "MAPI_CONF_CHECK",
MAPI_CONFERENCING_TYPE: "MAPI_CONFERENCING_TYPE",
MAPI_DIRECTORY: "MAPI_DIRECTORY",
MAPI_ORGANIZER_ALIAS: "MAPI_ORGANIZER_ALIAS",
MAPI_AUTO_START_CHECK: "MAPI_AUTO_START_CHECK",
MAPI_AUTO_START_WHEN: "MAPI_AUTO_START_WHEN",
MAPI_ALLOW_EXTERNAL_CHECK: "MAPI_ALLOW_EXTERNAL_CHECK",
MAPI_COLLABORATE_DOC: "MAPI_COLLABORATE_DOC",
MAPI_NET_SHOW_URL: "MAPI_NET_SHOW_URL",
MAPI_ONLINE_PASSWORD: "MAPI_ONLINE_PASSWORD",
MAPI_APPOINTMENT_PROPOSED_DURATION: "MAPI_APPOINTMENT_PROPOSED_DURATION",
MAPI_APPT_COUNTER_PROPOSAL: "MAPI_APPT_COUNTER_PROPOSAL",
MAPI_APPOINTMENT_PROPOSAL_NUMBER: "MAPI_APPOINTMENT_PROPOSAL_NUMBER",
MAPI_APPOINTMENT_NOT_ALLOW_PROPOSE: "MAPI_APPOINTMENT_NOT_ALLOW_PROPOSE",
MAPI_APPT_TZDEF_START_DISPLAY: "MAPI_APPT_TZDEF_START_DISPLAY",
MAPI_APPT_TZDEF_END_DISPLAY: "MAPI_APPT_TZDEF_END_DISPLAY",
MAPI_APPT_TZDEF_RECUR: "MAPI_APPT_TZDEF_RECUR",
MAPI_REMINDER_MINUTES_BEFORE_START: "MAPI_REMINDER_MINUTES_BEFORE_START",
MAPI_REMINDER_TIME: "MAPI_REMINDER_TIME",
MAPI_REMINDER_SET: "MAPI_REMINDER_SET",
MAPI_PRIVATE: "MAPI_PRIVATE",
MAPI_AGING_DONT_AGE_ME: "MAPI_AGING_DONT_AGE_ME",
MAPI_FORM_STORAGE: "MAPI_FORM_STORAGE",
MAPI_SIDE_EFFECTS: "MAPI_SIDE_EFFECTS",
MAPI_REMOTE_STATUS: "MAPI_REMOTE_STATUS",
MAPI_PAGE_DIR_STREAM: "MAPI_PAGE_DIR_STREAM",
MAPI_SMART_NO_ATTACH: "MAPI_SMART_NO_ATTACH",
MAPI_COMMON_START: "MAPI_COMMON_START",
MAPI_COMMON_END: "MAPI_COMMON_END",
MAPI_TASK_MODE: "MAPI_TASK_MODE",
MAPI_FORM_PROP_STREAM: "MAPI_FORM_PROP_STREAM",
MAPI_REQUEST: "MAPI_REQUEST",
MAPI_NON_SENDABLE_TO: "MAPI_NON_SENDABLE_TO",
MAPI_NON_SENDABLE_CC: "MAPI_NON_SENDABLE_CC",
MAPI_NON_SENDABLE_BCC: "MAPI_NON_SENDABLE_BCC",
MAPI_COMPANIES: "MAPI_COMPANIES",
MAPI_CONTACTS: "MAPI_CONTACTS",
MAPI_PROP_DEF_STREAM: "MAPI_PROP_DEF_STREAM",
MAPI_SCRIPT_STREAM: "MAPI_SCRIPT_STREAM",
MAPI_CUSTOM_FLAG: "MAPI_CUSTOM_FLAG",
MAPI_OUTLOOK_CURRENT_VERSION: "MAPI_OUTLOOK_CURRENT_VERSION",
MAPI_CURRENT_VERSION_NAME: "MAPI_CURRENT_VERSION_NAME",
MAPI_REMINDER_NEXT_TIME: "MAPI_REMINDER_NEXT_TIME",
MAPI_HEADER_ITEM: "MAPI_HEADER_ITEM",
MAPI_USE_TNEF: "MAPI_USE_TNEF",
MAPI_TO_DO_TITLE: "MAPI_TO_DO_TITLE",
MAPI_VALID_FLAG_STRING_PROOF: "MAPI_VALID_FLAG_STRING_PROOF",
MAPI_LOG_TYPE: "MAPI_LOG_TYPE",
MAPI_LOG_START: "MAPI_LOG_START",
MAPI_LOG_DURATION: "MAPI_LOG_DURATION",
MAPI_LOG_END: "MAPI_LOG_END",
}
| koodaamo/tnefparse | tnefparse/properties.py | Python | lgpl-3.0 | 63,627 |
/*-------------------------------------------------------------------------------------------------
_______ __ _ _______ _______ ______ ______
|_____| | \ | | |______ | \ |_____]
| | | \_| | ______| |_____/ |_____]
Copyright (c) 2016, antsdb.com and/or its affiliates. All rights reserved. *-xguo0<@
This program is free software: you can redistribute it and/or modify it under the terms of the
GNU GNU Lesser General Public License, version 3, as published by the Free Software Foundation.
You should have received a copy of the GNU Affero General Public License along with this program.
If not, see <https://www.gnu.org/licenses/lgpl-3.0.en.html>
-------------------------------------------------------------------------------------------------*/
package com.antsdb.saltedfish.sql.vdm;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import com.antsdb.saltedfish.cpp.FishObject;
import com.antsdb.saltedfish.cpp.Heap;
import com.antsdb.saltedfish.sql.DataType;
public class StringLiteral extends Operator {
String value;
public StringLiteral(String value) {
super();
this.value = value;
}
@Override
public long eval(VdmContext ctx, Heap heap, Parameters params, long pRecord) {
long addr = FishObject.allocSet(heap, this.value);
return addr;
}
@Override
public DataType getReturnType() {
return DataType.varchar();
}
@Override
public List<Operator> getChildren() {
return Collections.emptyList();
}
@Override
public void visit(Consumer<Operator> visitor) {
visitor.accept(this);
}
@Override
public String toString() {
return "'" + this.value + "'";
}
public String getValue() {
return this.value;
}
}
| waterguo/antsdb | fish-server/src/main/java/com/antsdb/saltedfish/sql/vdm/StringLiteral.java | Java | lgpl-3.0 | 1,832 |
# BlenderBIM Add-on - OpenBIM Blender Add-on
# Copyright (C) 2020, 2021 Maxim Vasilyev <qwiglydee@gmail.com>
#
# This file is part of BlenderBIM Add-on.
#
# BlenderBIM Add-on is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# BlenderBIM Add-on is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with BlenderBIM Add-on. If not, see <http://www.gnu.org/licenses/>.
import bpy
import blf
import math
import gpu, bgl
from bpy import types
from mathutils import Vector, Matrix
from mathutils import geometry
from bpy_extras import view3d_utils
from blenderbim.bim.module.drawing.shaders import DotsGizmoShader, ExtrusionGuidesShader, BaseLinesShader
from ifcopenshell.util.unit import si_conversions
"""Gizmos under the hood
## Transforms:
source/blender/windowmanager/gizmo/WM_gizmo_types.h
matrix_basis -- "Transformation of this gizmo." = placement in scene
matrix_offset -- "Custom offset from origin." = local transforms according to state/value
matrix_space -- "The space this gizmo is being modified in." used by some gizmos for undefined purposes
matrix_world -- final matrix, scaled according to viewport zoom and custom scale_basis
source/blender/windowmanager/gizmo/intern/wm_gizmo.c:WM_gizmo_calc_matrix_final_params
final = space @ (autoscale * (basis @ offset))
final = space @ (basis @ offset) -- if gizmo.use_draw_scale == False
final = space @ ((autoscale * basis) @ offset) -- if gizmo.use_draw_offset_scale
source/blender/windowmanager/gizmo/intern/wm_gizmo.c:wm_gizmo_calculate_scale
autoscale = gizmo.scale_basis * magic(preferences, matrix_space, matrix_basis, context.region_data)
magic -- making 1.0 to match preferences.view.gizmo_size pixels (75 by default)
## Selection
select_id -- apparently, id of a selectable part
test_select -- expected to return id of selection, doesn't seem to work
draw_select -- fake-draw of selection geometry for gpu-side cursor tracking
"""
# some geometries for Gizmo.custom_shape shaders
CUBE = (
(+1, +1, +1),
(-1, +1, +1),
(+1, -1, +1), # top
(+1, -1, +1),
(-1, +1, +1),
(-1, -1, +1),
(+1, +1, +1),
(+1, -1, +1),
(+1, +1, -1), # right
(+1, +1, -1),
(+1, -1, +1),
(+1, -1, -1),
(+1, +1, +1),
(+1, +1, -1),
(-1, +1, +1), # back
(-1, +1, +1),
(+1, +1, -1),
(-1, +1, -1),
(-1, -1, -1),
(-1, +1, -1),
(+1, -1, -1), # bot
(+1, -1, -1),
(-1, +1, -1),
(+1, +1, -1),
(-1, -1, -1),
(-1, -1, +1),
(-1, +1, -1), # left
(-1, +1, -1),
(-1, -1, +1),
(-1, +1, +1),
(-1, -1, -1),
(+1, -1, -1),
(-1, -1, +1), # front
(-1, -1, +1),
(+1, -1, -1),
(+1, -1, +1),
)
DISC = (
(0.0, 0.0, 0.0),
(1.0, 0.0, 0),
(0.8660254037844387, 0.49999999999999994, 0),
(0.0, 0.0, 0.0),
(0.8660254037844387, 0.49999999999999994, 0),
(0.5000000000000001, 0.8660254037844386, 0),
(0.0, 0.0, 0.0),
(0.5000000000000001, 0.8660254037844386, 0),
(6.123233995736766e-17, 1.0, 0),
(0.0, 0.0, 0.0),
(6.123233995736766e-17, 1.0, 0),
(-0.4999999999999998, 0.8660254037844387, 0),
(0.0, 0.0, 0.0),
(-0.4999999999999998, 0.8660254037844387, 0),
(-0.8660254037844385, 0.5000000000000003, 0),
(0.0, 0.0, 0.0),
(-0.8660254037844385, 0.5000000000000003, 0),
(-1.0, 1.2246467991473532e-16, 0),
(0.0, 0.0, 0.0),
(-1.0, 1.2246467991473532e-16, 0),
(-0.8660254037844388, -0.4999999999999997, 0),
(0.0, 0.0, 0.0),
(-0.8660254037844388, -0.4999999999999997, 0),
(-0.5000000000000004, -0.8660254037844384, 0),
(0.0, 0.0, 0.0),
(-0.5000000000000004, -0.8660254037844384, 0),
(-1.8369701987210297e-16, -1.0, 0),
(0.0, 0.0, 0.0),
(-1.8369701987210297e-16, -1.0, 0),
(0.49999999999999933, -0.866025403784439, 0),
(0.0, 0.0, 0.0),
(0.49999999999999933, -0.866025403784439, 0),
(0.8660254037844384, -0.5000000000000004, 0),
(0.0, 0.0, 0.0),
(0.8660254037844384, -0.5000000000000004, 0),
(1.0, 0.0, 0),
)
X3DISC = (
(0.0, 0.0, 0.0),
(1.0, 0.0, 0),
(0.8660254037844387, 0.49999999999999994, 0),
(0.0, 0.0, 0.0),
(0.8660254037844387, 0.49999999999999994, 0),
(0.5000000000000001, 0.8660254037844386, 0),
(0.0, 0.0, 0.0),
(0.5000000000000001, 0.8660254037844386, 0),
(6.123233995736766e-17, 1.0, 0),
(0.0, 0.0, 0.0),
(6.123233995736766e-17, 1.0, 0),
(-0.4999999999999998, 0.8660254037844387, 0),
(0.0, 0.0, 0.0),
(-0.4999999999999998, 0.8660254037844387, 0),
(-0.8660254037844385, 0.5000000000000003, 0),
(0.0, 0.0, 0.0),
(-0.8660254037844385, 0.5000000000000003, 0),
(-1.0, 1.2246467991473532e-16, 0),
(0.0, 0.0, 0.0),
(-1.0, 1.2246467991473532e-16, 0),
(-0.8660254037844388, -0.4999999999999997, 0),
(0.0, 0.0, 0.0),
(-0.8660254037844388, -0.4999999999999997, 0),
(-0.5000000000000004, -0.8660254037844384, 0),
(0.0, 0.0, 0.0),
(-0.5000000000000004, -0.8660254037844384, 0),
(-1.8369701987210297e-16, -1.0, 0),
(0.0, 0.0, 0.0),
(-1.8369701987210297e-16, -1.0, 0),
(0.49999999999999933, -0.866025403784439, 0),
(0.0, 0.0, 0.0),
(0.49999999999999933, -0.866025403784439, 0),
(0.8660254037844384, -0.5000000000000004, 0),
(0.0, 0.0, 0.0),
(0.8660254037844384, -0.5000000000000004, 0),
(1.0, 0.0, 0),
(0.0, 0.0, 0.0),
(0, 1.0, 0.0),
(0, 0.8660254037844387, 0.49999999999999994),
(0.0, 0.0, 0.0),
(0, 0.8660254037844387, 0.49999999999999994),
(0, 0.5000000000000001, 0.8660254037844386),
(0.0, 0.0, 0.0),
(0, 0.5000000000000001, 0.8660254037844386),
(0, 6.123233995736766e-17, 1.0),
(0.0, 0.0, 0.0),
(0, 6.123233995736766e-17, 1.0),
(0, -0.4999999999999998, 0.8660254037844387),
(0.0, 0.0, 0.0),
(0, -0.4999999999999998, 0.8660254037844387),
(0, -0.8660254037844385, 0.5000000000000003),
(0.0, 0.0, 0.0),
(0, -0.8660254037844385, 0.5000000000000003),
(0, -1.0, 1.2246467991473532e-16),
(0.0, 0.0, 0.0),
(0, -1.0, 1.2246467991473532e-16),
(0, -0.8660254037844388, -0.4999999999999997),
(0.0, 0.0, 0.0),
(0, -0.8660254037844388, -0.4999999999999997),
(0, -0.5000000000000004, -0.8660254037844384),
(0.0, 0.0, 0.0),
(0, -0.5000000000000004, -0.8660254037844384),
(0, -1.8369701987210297e-16, -1.0),
(0.0, 0.0, 0.0),
(0, -1.8369701987210297e-16, -1.0),
(0, 0.49999999999999933, -0.866025403784439),
(0.0, 0.0, 0.0),
(0, 0.49999999999999933, -0.866025403784439),
(0, 0.8660254037844384, -0.5000000000000004),
(0.0, 0.0, 0.0),
(0, 0.8660254037844384, -0.5000000000000004),
(0, 1.0, 0.0),
(0.0, 0.0, 0.0),
(0.0, 0, 1.0),
(0.49999999999999994, 0, 0.8660254037844387),
(0.0, 0.0, 0.0),
(0.49999999999999994, 0, 0.8660254037844387),
(0.8660254037844386, 0, 0.5000000000000001),
(0.0, 0.0, 0.0),
(0.8660254037844386, 0, 0.5000000000000001),
(1.0, 0, 6.123233995736766e-17),
(0.0, 0.0, 0.0),
(1.0, 0, 6.123233995736766e-17),
(0.8660254037844387, 0, -0.4999999999999998),
(0.0, 0.0, 0.0),
(0.8660254037844387, 0, -0.4999999999999998),
(0.5000000000000003, 0, -0.8660254037844385),
(0.0, 0.0, 0.0),
(0.5000000000000003, 0, -0.8660254037844385),
(1.2246467991473532e-16, 0, -1.0),
(0.0, 0.0, 0.0),
(1.2246467991473532e-16, 0, -1.0),
(-0.4999999999999997, 0, -0.8660254037844388),
(0.0, 0.0, 0.0),
(-0.4999999999999997, 0, -0.8660254037844388),
(-0.8660254037844384, 0, -0.5000000000000004),
(0.0, 0.0, 0.0),
(-0.8660254037844384, 0, -0.5000000000000004),
(-1.0, 0, -1.8369701987210297e-16),
(0.0, 0.0, 0.0),
(-1.0, 0, -1.8369701987210297e-16),
(-0.866025403784439, 0, 0.49999999999999933),
(0.0, 0.0, 0.0),
(-0.866025403784439, 0, 0.49999999999999933),
(-0.5000000000000004, 0, 0.8660254037844384),
(0.0, 0.0, 0.0),
(-0.5000000000000004, 0, 0.8660254037844384),
(0.0, 0, 1.0),
)
class CustomGizmo:
# FIXME: highliting/selection doesnt work
def draw_very_custom_shape(self, ctx, custom_shape, select_id=None):
# similar to draw_custom_shape
shape, batch, shader = custom_shape
shader.bind()
if select_id is not None:
gpu.select.load_id(select_id)
else:
if self.is_highlight:
color = (*self.color_highlight, self.alpha_highlight)
else:
color = (*self.color, self.alpha)
shader.uniform_float("color", color)
shape.glenable()
shape.uniform_region(ctx)
# shader.uniform_float('modelMatrix', self.matrix_world)
with gpu.matrix.push_pop():
gpu.matrix.multiply_matrix(self.matrix_world)
batch.draw()
bgl.glDisable(bgl.GL_BLEND)
class OffsetHandle:
"""Handling mouse to offset gizmo from base along Z axis"""
# FIXME: works a bit weird for rotated objects
def invoke(self, ctx, event):
self.init_value = self.target_get_value("offset") / self.scale_value
coordz = self.project_mouse(ctx, event)
if coordz is None:
return {"CANCELLED"}
self.init_coordz = coordz
return {"RUNNING_MODAL"}
def modal(self, ctx, event, tweak):
coordz = self.project_mouse(ctx, event)
if coordz is None:
return {"CANCELLED"}
delta = coordz - self.init_coordz
if "PRECISE" in tweak:
delta /= 10.0
value = max(0, self.init_value + delta)
value *= self.scale_value
# ctx.area.header_text_set(f"coords: {self.init_coordz} - {coordz}, delta: {delta}, value: {value}")
ctx.area.header_text_set(f"Depth: {value}")
self.target_set_value("offset", value)
return {"RUNNING_MODAL"}
def project_mouse(self, ctx, event):
"""Projecting mouse coords to local axis Z"""
# logic from source/blender/editors/gizmo_library/gizmo_types/arrow3d_gizmo.c:gizmo_arrow_modal
mouse = Vector((event.mouse_region_x, event.mouse_region_y))
region = ctx.region
region3d = ctx.region_data
ray_orig = view3d_utils.region_2d_to_origin_3d(region, region3d, mouse)
ray_norm = view3d_utils.region_2d_to_vector_3d(region, region3d, mouse)
# 'arrow' origin and direction
base = Vector((0, 0, 0))
axis = Vector((0, 0, 1))
# projecttion of the arrow to a plane, perpendicular to view ray
axis_proj = axis - ray_norm * axis.dot(ray_norm)
# intersection of the axis with the plane through view origin perpendicular to the arrow projection
coords = geometry.intersect_line_plane(base, axis, ray_orig, axis_proj)
return coords.z
def exit(self, ctx, cancel):
if cancel:
self.target_set_value("offset", self.init_value)
else:
self.group.update(ctx)
class UglyDotGizmo(OffsetHandle, types.Gizmo):
"""three orthogonal circles"""
bl_idname = "BIM_GT_uglydot_3d"
bl_target_properties = ({"id": "offset", "type": "FLOAT", "array_length": 1},)
__slots__ = (
"scale_value",
"custom_shape",
"init_value",
"init_coordz",
)
def setup(self):
self.custom_shape = self.new_custom_shape(type="TRIS", verts=X3DISC)
def refresh(self):
offset = self.target_get_value("offset") / self.scale_value
self.matrix_offset.col[3][2] = offset # z-shift
def draw(self, ctx):
self.refresh()
self.draw_custom_shape(self.custom_shape)
def draw_select(self, ctx, select_id):
self.refresh()
self.draw_custom_shape(self.custom_shape, select_id=select_id)
class DotGizmo(CustomGizmo, OffsetHandle, types.Gizmo):
"""Single dot viewport-aligned"""
# FIXME: make it selectable
bl_idname = "BIM_GT_dot_2d"
bl_target_properties = ({"id": "offset", "type": "FLOAT", "array_length": 1},)
__slots__ = (
"scale_value",
"custom_shape",
)
def setup(self):
shader = DotsGizmoShader()
self.custom_shape = shader, shader.batch(pos=((0, 0, 0),)), shader.prog
self.use_draw_scale = False
def refresh(self):
offset = self.target_get_value("offset") / self.scale_value
self.matrix_offset.col[3][2] = offset # z-shifted
def draw(self, ctx):
self.refresh()
self.draw_very_custom_shape(ctx, self.custom_shape)
def draw_select(self, ctx, select_id):
self.refresh()
self.draw_very_custom_shape(ctx, self.custom_shape, select_id=select_id)
# doesn't get called
# def test_select(self, ctx, location):
# pass
class ExtrusionGuidesGizmo(CustomGizmo, types.Gizmo):
"""Extrusion guides
Noninteractive gizmo to indicate extrusion depth and planes.
Draws main segment and orthogonal cross at endpoints.
"""
bl_idname = "BIM_GT_extrusion_guides"
bl_target_properties = ({"id": "depth", "type": "FLOAT", "array_length": 1},)
__slots__ = ("scale_value", "custom_shape")
def setup(self):
shader = ExtrusionGuidesShader()
self.custom_shape = shader, shader.batch(pos=((0, 0, 0), (0, 0, 1))), shader.prog
self.use_draw_scale = False
def refresh(self):
depth = self.target_get_value("depth") / self.scale_value
self.matrix_offset.col[2][2] = depth # z-scaled
def draw(self, ctx):
self.refresh()
self.draw_very_custom_shape(ctx, self.custom_shape)
class DimensionLabelGizmo(types.Gizmo):
"""Text label for a dimension"""
# does not work properly, fonts are totally screwed up
bl_idname = "BIM_GT_dimension_label"
bl_target_properties = ({"id": "value", "type": "FLOAT", "array_length": 1},)
__slots__ = "text_label"
def setup(self):
pass
def refresh(self, ctx):
value = self.target_get_value("value")
self.matrix_offset.col[3][2] = value * 0.5
unit_system = ctx.scene.unit_settings.system
self.text_label = bpy.utils.units.to_string(unit_system, "LENGTH", value, 3, split_unit=False)
def draw(self, ctx):
self.refresh(ctx)
self.draw_text(ctx)
def draw_text(self, ctx):
font_id = 0
font_size = 16
dpi = ctx.preferences.system.dpi
# pos = self.matrix_world @ Vector((0, 0, 0, 1))
# pos = Vector((0, 0, 0.5))
# region = ctx.region
# region3d = ctx.region_data
# pos = view3d_utils.location_3d_to_region_2d(region, region3d, pos)
# text = self.text_label
blf.size(font_id, font_size, dpi)
blf.position(font_id, 0, 0, 0)
blf.color(font_id, *self.color, self.alpha)
blf.draw(font_id, "ABC")
class ExtrusionWidget(types.GizmoGroup):
bl_idname = "bim.extrusion_widget"
bl_label = "Extrusion Gizmos"
bl_space_type = "VIEW_3D"
bl_region_type = "WINDOW"
bl_options = {"3D", "PERSISTENT", "SHOW_MODAL_ALL"}
@classmethod
def poll(cls, ctx):
obj = ctx.object
return (
obj
and obj.type == "MESH"
and obj.data.BIMMeshProperties.ifc_parameters.get("IfcExtrudedAreaSolid/Depth") is not None
)
def setup(self, ctx):
target = ctx.object
prop = target.data.BIMMeshProperties.ifc_parameters.get("IfcExtrudedAreaSolid/Depth")
basis = target.matrix_world.normalized()
theme = ctx.preferences.themes[0].user_interface
scale_value = self.get_scale_value(ctx.scene.unit_settings.system, ctx.scene.unit_settings.length_unit)
gz = self.handle = self.gizmos.new("BIM_GT_uglydot_3d")
gz.matrix_basis = basis
gz.scale_basis = 0.1
gz.color = gz.color_highlight = tuple(theme.gizmo_primary)
gz.alpha = 0.5
gz.alpha_highlight = 1.0
gz.use_draw_modal = True
gz.target_set_prop("offset", prop, "value")
gz.scale_value = scale_value
gz = self.guides = self.gizmos.new("BIM_GT_extrusion_guides")
gz.matrix_basis = basis
gz.color = gz.color_highlight = tuple(theme.gizmo_secondary)
gz.alpha = gz.alpha_highlight = 0.5
gz.use_draw_modal = True
gz.target_set_prop("depth", prop, "value")
gz.scale_value = scale_value
# gz = self.label = self.gizmos.new('GIZMO_GT_dimension_label')
# gz.matrix_basis = basis
# gz.color = tuple(theme.gizmo_secondary)
# gz.alpha = 0.5
# gz.use_draw_modal = True
# gz.target_set_prop('value', target.demo, 'depth')
def refresh(self, ctx):
"""updating gizmos"""
target = ctx.object
basis = target.matrix_world.normalized()
self.handle.matrix_basis = basis
self.guides.matrix_basis = basis
def update(self, ctx):
"""updating object"""
bpy.ops.bim.update_parametric_representation()
target = ctx.object
prop = target.data.BIMMeshProperties.ifc_parameters.get("IfcExtrudedAreaSolid/Depth")
self.handle.target_set_prop("offset", prop, "value")
self.guides.target_set_prop("depth", prop, "value")
@staticmethod
def get_scale_value(system, length_unit):
scale_value = 1
if system == "METRIC":
if length_unit == "KILOMETERS":
scale_value /= 1000
elif length_unit == "CENTIMETERS":
scale_value *= 100
elif length_unit == "MILLIMETERS":
scale_value *= 1000
elif length_unit == "MICROMETERS":
scale_value *= 1000000
elif system == "IMPERIAL":
if length_unit == "MILES":
scale_value /= si_conversions["mile"]
elif length_unit == "FEET":
scale_value /= si_conversions["foot"]
elif length_unit == "INCHES":
scale_value /= si_conversions["inch"]
elif length_unit == "THOU":
scale_value /= si_conversions["thou"]
return scale_value
| IfcOpenShell/IfcOpenShell | src/blenderbim/blenderbim/bim/module/drawing/gizmos.py | Python | lgpl-3.0 | 18,534 |
package ch.loway.oss.ari4java.generated.ari_1_5_0.models;
// ----------------------------------------------------
// THIS CLASS WAS GENERATED AUTOMATICALLY
// PLEASE DO NOT EDIT
// Generated on: Sat Sep 19 08:50:54 CEST 2015
// ----------------------------------------------------
import ch.loway.oss.ari4java.generated.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**********************************************************
* Identifies the format and language of a sound file
*
* Defined in file: sounds.json
* Generated by: Model
*********************************************************/
public class FormatLangPair_impl_ari_1_5_0 implements FormatLangPair, java.io.Serializable {
private static final long serialVersionUID = 1L;
/** */
private String format;
public String getFormat() {
return format;
}
@JsonDeserialize( as=String.class )
public void setFormat(String val ) {
format = val;
}
/** */
private String language;
public String getLanguage() {
return language;
}
@JsonDeserialize( as=String.class )
public void setLanguage(String val ) {
language = val;
}
/** No missing signatures from interface */
}
| korvus81/ari4java | classes/ch/loway/oss/ari4java/generated/ari_1_5_0/models/FormatLangPair_impl_ari_1_5_0.java | Java | lgpl-3.0 | 1,312 |
<?php
namespace BlackBoxCode\Pando\ProductSaleBundle\Model;
use BlackBoxCode\Pando\BaseBundle\Model\IdInterface;
interface ProductVariantInventoryInterface extends IdInterface
{
/**
* @return integer
*/
public function getAmount();
/**
* @param integer $amount
* @return $this
*/
public function setAmount($amount);
/**
* @return ProductVariantInterface
*/
public function getProductVariant();
/**
* @param ProductVariantInterface $productVariant
* @return $this
*/
public function setProductVariant(ProductVariantInterface $productVariant);
}
| BlackBoxRepo/PandoProductSaleBundle | Model/ProductVariantInventoryInterface.php | PHP | lgpl-3.0 | 631 |
#region CodeMaid is Copyright 2007-2015 Steve Cadwallader.
// CodeMaid is free software: you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License version 3 as published by the Free Software Foundation.
//
// CodeMaid is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
// even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details <http://www.gnu.org/licenses/>.
#endregion CodeMaid is Copyright 2007-2015 Steve Cadwallader.
using EnvDTE;
using SteveCadwallader.CodeMaid.Helpers;
using SteveCadwallader.CodeMaid.Logic.Formatting;
using SteveCadwallader.CodeMaid.Logic.Reorganizing;
using SteveCadwallader.CodeMaid.Model;
using SteveCadwallader.CodeMaid.Model.CodeItems;
using SteveCadwallader.CodeMaid.Properties;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SteveCadwallader.CodeMaid.Logic.Cleaning
{
/// <summary>
/// A manager class for cleaning up code.
/// </summary>
/// <remarks>
///
/// Note: All POSIXRegEx text replacements search against '\n' but insert/replace with
/// Environment.NewLine. This handles line endings correctly.
/// </remarks>
internal class CodeCleanupManager
{
#region Fields
private readonly CodeMaidPackage _package;
private readonly CodeModelManager _codeModelManager;
private readonly CodeReorganizationManager _codeReorganizationManager;
private readonly CommandHelper _commandHelper;
private readonly UndoTransactionHelper _undoTransactionHelper;
private readonly CodeCleanupAvailabilityLogic _codeCleanupAvailabilityLogic;
private readonly CommentFormatLogic _commentFormatLogic;
private readonly InsertBlankLinePaddingLogic _insertBlankLinePaddingLogic;
private readonly InsertExplicitAccessModifierLogic _insertExplicitAccessModifierLogic;
private readonly InsertWhitespaceLogic _insertWhitespaceLogic;
private readonly RemoveRegionLogic _removeRegionLogic;
private readonly RemoveWhitespaceLogic _removeWhitespaceLogic;
private readonly UpdateLogic _updateLogic;
private readonly UsingStatementCleanupLogic _usingStatementCleanupLogic;
private readonly CachedSettingSet<string> _otherCleaningCommands =
new CachedSettingSet<string>(() => Settings.Default.ThirdParty_OtherCleaningCommandsExpression,
expression =>
expression.Split(new[] { "||" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim())
.Where(y => !string.IsNullOrEmpty(y))
.ToList());
#endregion Fields
#region Constructors
/// <summary>
/// The singleton instance of the <see cref="CodeCleanupManager" /> class.
/// </summary>
private static CodeCleanupManager _instance;
/// <summary>
/// Gets an instance of the <see cref="CodeCleanupManager" /> class.
/// </summary>
/// <param name="package">The hosting package.</param>
/// <returns>An instance of the <see cref="CodeCleanupManager" /> class.</returns>
internal static CodeCleanupManager GetInstance(CodeMaidPackage package)
{
return _instance ?? (_instance = new CodeCleanupManager(package));
}
/// <summary>
/// Initializes a new instance of the <see cref="CodeCleanupManager" /> class.
/// </summary>
/// <param name="package">The hosting package.</param>
private CodeCleanupManager(CodeMaidPackage package)
{
_package = package;
_codeModelManager = CodeModelManager.GetInstance(_package);
_codeReorganizationManager = CodeReorganizationManager.GetInstance(_package);
_commandHelper = CommandHelper.GetInstance(_package);
_undoTransactionHelper = new UndoTransactionHelper(_package, "CodeMaid Cleanup");
_codeCleanupAvailabilityLogic = CodeCleanupAvailabilityLogic.GetInstance(_package);
_commentFormatLogic = CommentFormatLogic.GetInstance(_package);
_insertBlankLinePaddingLogic = InsertBlankLinePaddingLogic.GetInstance(_package);
_insertExplicitAccessModifierLogic = InsertExplicitAccessModifierLogic.GetInstance();
_insertWhitespaceLogic = InsertWhitespaceLogic.GetInstance(_package);
_removeRegionLogic = RemoveRegionLogic.GetInstance(_package);
_removeWhitespaceLogic = RemoveWhitespaceLogic.GetInstance(_package);
_updateLogic = UpdateLogic.GetInstance(_package);
_usingStatementCleanupLogic = UsingStatementCleanupLogic.GetInstance(_package);
}
#endregion Constructors
#region Internal Methods
/// <summary>
/// Attempts to run code cleanup on the specified project item.
/// </summary>
/// <param name="projectItem">The project item for cleanup.</param>
internal void Cleanup(ProjectItem projectItem)
{
if (!_codeCleanupAvailabilityLogic.CanCleanup(projectItem)) return;
// Attempt to open the document if not already opened.
bool wasOpen = projectItem.IsOpen[Constants.vsViewKindTextView];
if (!wasOpen)
{
try
{
projectItem.Open(Constants.vsViewKindTextView);
}
catch (Exception)
{
// OK if file cannot be opened (ex: deleted from disk, non-text based type.)
}
}
if (projectItem.Document != null)
{
Cleanup(projectItem.Document);
// Close the document if it was opened for cleanup.
if (Settings.Default.Cleaning_AutoSaveAndCloseIfOpenedByCleanup && !wasOpen)
{
projectItem.Document.Close(vsSaveChanges.vsSaveChangesYes);
}
}
}
/// <summary>
/// Attempts to run code cleanup on the specified document.
/// </summary>
/// <param name="document">The document for cleanup.</param>
/// <param name="isAutoSave">A flag indicating if occurring due to auto-save.</param>
internal void Cleanup(Document document, bool isAutoSave = false)
{
if (!_codeCleanupAvailabilityLogic.CanCleanup(document, true)) return;
// Make sure the document to be cleaned up is active, required for some commands like
// format document.
document.Activate();
if (_package.ActiveDocument != document)
{
OutputWindowHelper.WarningWriteLine(
string.Format("Activation was not completed before cleaning began for '{0}'", document.Name));
}
// Conditionally start cleanup with reorganization.
if (Settings.Default.Reorganizing_RunAtStartOfCleanup)
{
_codeReorganizationManager.Reorganize(document, isAutoSave);
}
_undoTransactionHelper.Run(
() => !(isAutoSave && Settings.Default.General_SkipUndoTransactionsDuringAutoCleanupOnSave),
delegate
{
var cleanupMethod = FindCodeCleanupMethod(document);
if (cleanupMethod != null)
{
OutputWindowHelper.DiagnosticWriteLine(
string.Format("CodeCleanupManager.Cleanup started for '{0}'", document.FullName));
_package.IDE.StatusBar.Text = string.Format("CodeMaid is cleaning '{0}'...", document.Name);
// Perform the set of configured cleanups based on the language.
cleanupMethod(document, isAutoSave);
_package.IDE.StatusBar.Text = string.Format("CodeMaid cleaned '{0}'.", document.Name);
OutputWindowHelper.DiagnosticWriteLine(
string.Format("CodeCleanupManager.Cleanup completed for '{0}'", document.FullName));
}
},
delegate(Exception ex)
{
OutputWindowHelper.ExceptionWriteLine(
string.Format("Stopped cleaning '{0}'", document.Name), ex);
_package.IDE.StatusBar.Text = string.Format("CodeMaid stopped cleaning '{0}'. See output window for more details.", document.Name);
});
}
#endregion Internal Methods
#region Private Language Methods
/// <summary>
/// Finds a code cleanup method appropriate for the specified document, otherwise null.
/// </summary>
/// <param name="document">The document.</param>
/// <returns>The code cleanup method, otherwise null.</returns>
private Action<Document, bool> FindCodeCleanupMethod(Document document)
{
switch (document.Language)
{
case "CSharp":
return RunCodeCleanupCSharp;
case "C/C++":
case "CSS":
case "JavaScript":
case "JScript":
case "JSON":
case "LESS":
case "PHP":
case "SCSS":
case "TypeScript":
return RunCodeCleanupC;
case "HTML":
case "HTMLX":
case "XAML":
case "XML":
return RunCodeCleanupMarkup;
case "Basic":
case "F#":
return RunCodeCleanupGeneric;
default:
OutputWindowHelper.WarningWriteLine(
string.Format("FindCodeCleanupMethod does not recognize document language '{0}'", document.Language));
return null;
}
}
/// <summary>
/// Attempts to run code cleanup on the specified CSharp document.
/// </summary>
/// <param name="document">The document for cleanup.</param>
/// <param name="isAutoSave">A flag indicating if occurring due to auto-save.</param>
private void RunCodeCleanupCSharp(Document document, bool isAutoSave)
{
var textDocument = document.GetTextDocument();
// Perform any actions that can modify the file code model first.
RunExternalFormatting(textDocument);
if (!document.IsExternal())
{
_usingStatementCleanupLogic.RemoveUnusedUsingStatements(textDocument, isAutoSave);
_usingStatementCleanupLogic.SortUsingStatements(isAutoSave);
}
// Interpret the document into a collection of elements.
var codeItems = _codeModelManager.RetrieveAllCodeItems(document);
var regions = codeItems.OfType<CodeItemRegion>().ToList();
var usingStatements = codeItems.OfType<CodeItemUsingStatement>().ToList();
var namespaces = codeItems.OfType<CodeItemNamespace>().ToList();
var classes = codeItems.OfType<CodeItemClass>().ToList();
var delegates = codeItems.OfType<CodeItemDelegate>().ToList();
var enumerations = codeItems.OfType<CodeItemEnum>().ToList();
var events = codeItems.OfType<CodeItemEvent>().ToList();
var fields = codeItems.OfType<CodeItemField>().ToList();
var interfaces = codeItems.OfType<CodeItemInterface>().ToList();
var methods = codeItems.OfType<CodeItemMethod>().ToList();
var properties = codeItems.OfType<CodeItemProperty>().ToList();
var structs = codeItems.OfType<CodeItemStruct>().ToList();
// Build up more complicated collections.
var usingStatementBlocks = CodeModelHelper.GetCodeItemBlocks(usingStatements).ToList();
var usingStatementsThatStartBlocks = (from IEnumerable<CodeItemUsingStatement> block in usingStatementBlocks select block.First()).ToList();
var usingStatementsThatEndBlocks = (from IEnumerable<CodeItemUsingStatement> block in usingStatementBlocks select block.Last()).ToList();
var fieldsWithComments = fields.Where(x => x.StartPoint.Line < x.EndPoint.Line).ToList();
// Perform removal cleanup.
_removeRegionLogic.RemoveRegionsPerSettings(regions);
_removeWhitespaceLogic.RemoveEOLWhitespace(textDocument);
_removeWhitespaceLogic.RemoveBlankLinesAtTop(textDocument);
_removeWhitespaceLogic.RemoveBlankLinesAtBottom(textDocument);
_removeWhitespaceLogic.RemoveEOFTrailingNewLine(textDocument);
_removeWhitespaceLogic.RemoveBlankLinesAfterAttributes(textDocument);
_removeWhitespaceLogic.RemoveBlankLinesAfterOpeningBrace(textDocument);
_removeWhitespaceLogic.RemoveBlankLinesBeforeClosingBrace(textDocument);
_removeWhitespaceLogic.RemoveBlankLinesBetweenChainedStatements(textDocument);
_removeWhitespaceLogic.RemoveMultipleConsecutiveBlankLines(textDocument);
// Perform insertion of blank line padding cleanup.
_insertBlankLinePaddingLogic.InsertPaddingBeforeRegionTags(regions);
_insertBlankLinePaddingLogic.InsertPaddingAfterRegionTags(regions);
_insertBlankLinePaddingLogic.InsertPaddingBeforeEndRegionTags(regions);
_insertBlankLinePaddingLogic.InsertPaddingAfterEndRegionTags(regions);
_insertBlankLinePaddingLogic.InsertPaddingBeforeCodeElements(usingStatementsThatStartBlocks);
_insertBlankLinePaddingLogic.InsertPaddingAfterCodeElements(usingStatementsThatEndBlocks);
_insertBlankLinePaddingLogic.InsertPaddingBeforeCodeElements(namespaces);
_insertBlankLinePaddingLogic.InsertPaddingAfterCodeElements(namespaces);
_insertBlankLinePaddingLogic.InsertPaddingBeforeCodeElements(classes);
_insertBlankLinePaddingLogic.InsertPaddingAfterCodeElements(classes);
_insertBlankLinePaddingLogic.InsertPaddingBeforeCodeElements(delegates);
_insertBlankLinePaddingLogic.InsertPaddingAfterCodeElements(delegates);
_insertBlankLinePaddingLogic.InsertPaddingBeforeCodeElements(enumerations);
_insertBlankLinePaddingLogic.InsertPaddingAfterCodeElements(enumerations);
_insertBlankLinePaddingLogic.InsertPaddingBeforeCodeElements(events);
_insertBlankLinePaddingLogic.InsertPaddingAfterCodeElements(events);
_insertBlankLinePaddingLogic.InsertPaddingBeforeCodeElements(fieldsWithComments);
_insertBlankLinePaddingLogic.InsertPaddingAfterCodeElements(fieldsWithComments);
_insertBlankLinePaddingLogic.InsertPaddingBeforeCodeElements(interfaces);
_insertBlankLinePaddingLogic.InsertPaddingAfterCodeElements(interfaces);
_insertBlankLinePaddingLogic.InsertPaddingBeforeCodeElements(methods);
_insertBlankLinePaddingLogic.InsertPaddingAfterCodeElements(methods);
_insertBlankLinePaddingLogic.InsertPaddingBeforeCodeElements(properties);
_insertBlankLinePaddingLogic.InsertPaddingBetweenMultiLinePropertyAccessors(properties);
_insertBlankLinePaddingLogic.InsertPaddingAfterCodeElements(properties);
_insertBlankLinePaddingLogic.InsertPaddingBeforeCodeElements(structs);
_insertBlankLinePaddingLogic.InsertPaddingAfterCodeElements(structs);
_insertBlankLinePaddingLogic.InsertPaddingBeforeCaseStatements(textDocument);
_insertBlankLinePaddingLogic.InsertPaddingBeforeSingleLineComments(textDocument);
// Perform insertion of explicit access modifier cleanup.
_insertExplicitAccessModifierLogic.InsertExplicitAccessModifiersOnClasses(classes);
_insertExplicitAccessModifierLogic.InsertExplicitAccessModifiersOnDelegates(delegates);
_insertExplicitAccessModifierLogic.InsertExplicitAccessModifiersOnEnumerations(enumerations);
_insertExplicitAccessModifierLogic.InsertExplicitAccessModifiersOnEvents(events);
_insertExplicitAccessModifierLogic.InsertExplicitAccessModifiersOnFields(fields);
_insertExplicitAccessModifierLogic.InsertExplicitAccessModifiersOnInterfaces(interfaces);
_insertExplicitAccessModifierLogic.InsertExplicitAccessModifiersOnMethods(methods);
_insertExplicitAccessModifierLogic.InsertExplicitAccessModifiersOnProperties(properties);
_insertExplicitAccessModifierLogic.InsertExplicitAccessModifiersOnStructs(structs);
// Perform insertion of whitespace cleanup.
_insertWhitespaceLogic.InsertEOFTrailingNewLine(textDocument);
// Perform update cleanup.
_updateLogic.UpdateEndRegionDirectives(textDocument);
_updateLogic.UpdateEventAccessorsToBothBeSingleLineOrMultiLine(events);
_updateLogic.UpdatePropertyAccessorsToBothBeSingleLineOrMultiLine(properties);
_updateLogic.UpdateSingleLineMethods(methods);
// Perform comment cleaning.
_commentFormatLogic.FormatComments(textDocument);
}
/// <summary>
/// Attempts to run code cleanup on the specified C/C++ document.
/// </summary>
/// <param name="document">The document for cleanup.</param>
/// <param name="isAutoSave">A flag indicating if occurring due to auto-save.</param>
private void RunCodeCleanupC(Document document, bool isAutoSave)
{
var textDocument = document.GetTextDocument();
RunExternalFormatting(textDocument);
// Perform removal cleanup.
_removeWhitespaceLogic.RemoveEOLWhitespace(textDocument);
_removeWhitespaceLogic.RemoveBlankLinesAtTop(textDocument);
_removeWhitespaceLogic.RemoveBlankLinesAtBottom(textDocument);
_removeWhitespaceLogic.RemoveEOFTrailingNewLine(textDocument);
_removeWhitespaceLogic.RemoveBlankLinesAfterOpeningBrace(textDocument);
_removeWhitespaceLogic.RemoveBlankLinesBeforeClosingBrace(textDocument);
_removeWhitespaceLogic.RemoveMultipleConsecutiveBlankLines(textDocument);
// Perform insertion cleanup.
_insertWhitespaceLogic.InsertEOFTrailingNewLine(textDocument);
}
/// <summary>
/// Attempts to run code cleanup on the specified markup document.
/// </summary>
/// <param name="document">The document for cleanup.</param>
/// <param name="isAutoSave">A flag indicating if occurring due to auto-save.</param>
private void RunCodeCleanupMarkup(Document document, bool isAutoSave)
{
var textDocument = document.GetTextDocument();
RunExternalFormatting(textDocument);
// Perform removal cleanup.
_removeWhitespaceLogic.RemoveEOLWhitespace(textDocument);
_removeWhitespaceLogic.RemoveBlankLinesAtTop(textDocument);
_removeWhitespaceLogic.RemoveBlankLinesAtBottom(textDocument);
_removeWhitespaceLogic.RemoveEOFTrailingNewLine(textDocument);
_removeWhitespaceLogic.RemoveBlankLinesBeforeClosingTag(textDocument);
_removeWhitespaceLogic.RemoveBlankSpacesBeforeClosingAngleBracket(textDocument);
_removeWhitespaceLogic.RemoveMultipleConsecutiveBlankLines(textDocument);
// Perform insertion cleanup.
_insertWhitespaceLogic.InsertBlankSpaceBeforeSelfClosingAngleBracket(textDocument);
_insertWhitespaceLogic.InsertEOFTrailingNewLine(textDocument);
}
/// <summary>
/// Attempts to run code cleanup on the specified generic document.
/// </summary>
/// <param name="document">The document for cleanup.</param>
/// <param name="isAutoSave">A flag indicating if occurring due to auto-save.</param>
private void RunCodeCleanupGeneric(Document document, bool isAutoSave)
{
var textDocument = document.GetTextDocument();
RunExternalFormatting(textDocument);
// Perform removal cleanup.
_removeWhitespaceLogic.RemoveEOLWhitespace(textDocument);
_removeWhitespaceLogic.RemoveBlankLinesAtTop(textDocument);
_removeWhitespaceLogic.RemoveBlankLinesAtBottom(textDocument);
_removeWhitespaceLogic.RemoveEOFTrailingNewLine(textDocument);
_removeWhitespaceLogic.RemoveMultipleConsecutiveBlankLines(textDocument);
// Perform insertion cleanup.
_insertWhitespaceLogic.InsertEOFTrailingNewLine(textDocument);
}
#endregion Private Language Methods
#region Private Cleanup Methods
/// <summary>
/// Runs external formatting tools (e.g. Visual Studio, JetBrains ReSharper, Telerik JustCode).
/// </summary>
/// <param name="textDocument">The text document to cleanup.</param>
private void RunExternalFormatting(TextDocument textDocument)
{
RunVisualStudioFormatDocument(textDocument);
RunJetBrainsReSharperCleanup(textDocument);
RunTelerikJustCodeCleanup(textDocument);
RunXAMLStylerCleanup(textDocument);
RunOtherCleanupCommands(textDocument);
}
/// <summary>
/// Runs the Visual Studio built-in format document command.
/// </summary>
/// <param name="textDocument">The text document to cleanup.</param>
private void RunVisualStudioFormatDocument(TextDocument textDocument)
{
if (!Settings.Default.Cleaning_RunVisualStudioFormatDocumentCommand) return;
ExecuteCommand(textDocument, "Edit.FormatDocument");
}
/// <summary>
/// Runs the JetBrains ReSharper cleanup command.
/// </summary>
/// <param name="textDocument">The text document to cleanup.</param>
private void RunJetBrainsReSharperCleanup(TextDocument textDocument)
{
if (!Settings.Default.ThirdParty_UseJetBrainsReSharperCleanup) return;
ExecuteCommand(textDocument, "ReSharper_SilentCleanupCode");
}
/// <summary>
/// Runs the Telerik JustCode cleanup command.
/// </summary>
/// <param name="textDocument">The text document to cleanup.</param>
private void RunTelerikJustCodeCleanup(TextDocument textDocument)
{
if (!Settings.Default.ThirdParty_UseTelerikJustCodeCleanup) return;
ExecuteCommand(textDocument, "JustCode.JustCode_CleanCodeWithDefaultProfile");
}
/// <summary>
/// Runs the XAML Styler cleanup command.
/// </summary>
/// <param name="textDocument">The text document to cleanup.</param>
private void RunXAMLStylerCleanup(TextDocument textDocument)
{
if (!Settings.Default.ThirdParty_UseXAMLStylerCleanup) return;
ExecuteCommand(textDocument, "EditorContextMenus.XAMLEditor.BeautifyXaml", "EditorContextMenus.XAMLEditor.FormatXAML");
}
/// <summary>
/// Runs the other cleanup commands.
/// </summary>
/// <param name="textDocument">The text document to cleanup.</param>
private void RunOtherCleanupCommands(TextDocument textDocument)
{
if (!_otherCleaningCommands.Value.Any()) return;
foreach (var commandName in _otherCleaningCommands.Value)
{
ExecuteCommand(textDocument, commandName);
}
}
/// <summary>
/// Executes the specified cleanup command when available against the specified text document.
/// </summary>
/// <param name="textDocument">The text document to cleanup.</param>
/// <param name="commandNames">The cleanup command name(s).</param>
private void ExecuteCommand(TextDocument textDocument, params string[] commandNames)
{
try
{
var command = _commandHelper.FindCommand(commandNames);
if (command != null && command.IsAvailable)
{
using (new CursorPositionRestorer(textDocument))
{
_package.IDE.ExecuteCommand(command.Name, String.Empty);
}
}
}
catch
{
// OK if fails, not available for some file types.
}
}
#endregion Private Cleanup Methods
}
} | AlkindiX/codemaid | CodeMaid/Logic/Cleaning/CodeCleanupManager.cs | C# | lgpl-3.0 | 25,682 |
/*----------------------------------------------------------------------------*
* This file is part of Pitaya. *
* Copyright (C) 2012-2016 Osman KOCAK <kocakosm@gmail.com> *
* *
* This program is free software: you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or (at your *
* option) any later version. *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public *
* License for more details. *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*----------------------------------------------------------------------------*/
package org.kocakosm.pitaya.io;
import org.kocakosm.pitaya.charset.Charsets;
import org.kocakosm.pitaya.util.Parameters;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* Text files utilities.
*
* @see XFiles
*
* @author Osman KOCAK
*/
public final class TextFiles
{
/**
* Returns the first (up to 10) lines of the given {@code File} using
* the system's default charset. Named after the Unix command of the
* same name.
*
* @param f the {@code File} to read.
*
* @return the first lines of the given {@code File}.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> head(File f) throws IOException
{
return head(f, Charsets.DEFAULT);
}
/**
* Returns the first (up to 10) lines of the given {@code File} using
* the specified charset. Named after the Unix command of the same name.
*
* @param f the {@code File} to read.
* @param charset the charset to use.
*
* @return the first lines of the given {@code File}.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> head(File f, Charset charset) throws IOException
{
return head(f, 10, charset);
}
/**
* Returns the first (up to {@code n}) lines of the given {@code File}
* using the system's default charset. Named after the Unix command of
* the same name.
*
* @param f the {@code File} to read.
* @param n the maximum number of lines to read.
*
* @return the first lines of the given {@code File}.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws IllegalArgumentException if {@code n} is negative.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> head(File f, int n) throws IOException
{
return head(f, n, Charsets.DEFAULT);
}
/**
* Returns the first (up to {@code n}) lines of the given {@code File}
* using the specified charset. Named after the Unix command of the same
* name.
*
* @param f the {@code File} to read.
* @param n the maximum number of lines to read.
* @param charset the charset to use.
*
* @return the first lines of the given {@code File}.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws IllegalArgumentException if {@code n} is negative.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> head(File f, int n, Charset charset)
throws IOException
{
Parameters.checkCondition(n >= 0);
List<String> lines = new ArrayList<String>();
BufferedReader reader = newReader(f, charset);
try {
String line = reader.readLine();
while (line != null && lines.size() < n) {
lines.add(line);
line = reader.readLine();
}
} finally {
IO.close(reader);
}
return Collections.unmodifiableList(lines);
}
/**
* Returns the last (up to 10) lines of the given {@code File} using the
* system's default charset. Named after the Unix command of the same
* name.
*
* @param f the {@code File} to read.
*
* @return the last lines of the given {@code File}.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> tail(File f) throws IOException
{
return tail(f, Charsets.DEFAULT);
}
/**
* Returns the last (up to 10) lines of the given {@code File} using the
* specified charset. Named after the Unix command of the same name.
*
* @param f the {@code File} to read.
* @param charset the charset to use.
*
* @return the last lines of the given {@code File}.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> tail(File f, Charset charset) throws IOException
{
return tail(f, 10, charset);
}
/**
* Returns the last (up to n) lines of the given {@code File} using the
* system's default charset. Named after the Unix command of the same
* name.
*
* @param f the {@code File} to read.
* @param n the maximum number of lines to read.
*
* @return the last lines of the given {@code File}.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws IllegalArgumentException if {@code n} is negative.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> tail(File f, int n) throws IOException
{
return tail(f, n, Charsets.DEFAULT);
}
/**
* Returns the last (up to n) lines of the given {@code File} using the
* specified charset. Named after the Unix command of the same name.
*
* @param f the {@code File} to read.
* @param n the maximum number of lines to read.
* @param charset the charset to use.
*
* @return the last lines of the given {@code File}.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws IllegalArgumentException if {@code n} is negative.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> tail(File f, int n, Charset charset)
throws IOException
{
Parameters.checkCondition(n >= 0);
if (n == 0) {
return Collections.emptyList();
}
List<String> lines = new LinkedList<String>();
BufferedReader reader = newReader(f, charset);
try {
String line = reader.readLine();
while (line != null) {
lines.add(line);
if (lines.size() > n) {
lines.remove(0);
}
line = reader.readLine();
}
} finally {
IO.close(reader);
}
return Collections.unmodifiableList(lines);
}
/**
* Returns a new {@code BufferedReader} to read the given {@code File}
* using the system's default charset.
*
* @param f the file to read from.
*
* @return a {@code BufferedReader} to read the given {@code File}.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws FileNotFoundException if {@code f} doesn't exist, or if it is
* a directory rather than a regular file, or if it can't be opened
* for reading.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static BufferedReader newReader(File f) throws FileNotFoundException
{
return newReader(f, Charsets.DEFAULT);
}
/**
* Returns a new {@code BufferedReader} to read the given {@code File}
* using the specified charset.
*
* @param f the file to read from.
* @param charset the charset to use.
*
* @return a {@code BufferedReader} to read the given {@code File}.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws FileNotFoundException if {@code f} doesn't exist, or if it is
* a directory rather than a regular file, or if it can't be opened
* for reading.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static BufferedReader newReader(File f, Charset charset)
throws FileNotFoundException
{
InputStream in = new FileInputStream(f);
return new BufferedReader(new InputStreamReader(in, charset));
}
/**
* Returns a new {@code BufferedWriter} to write to the given
* {@code File} using the system's default charset.
*
* @param f the file to write to.
* @param options the write options.
*
* @return a {@code BufferedWriter} to write to the given {@code File}.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws IllegalArgumentException if incompatible options are given.
* @throws FileNotFoundException if {@code f} exists but is a directory
* rather than a regular file, or if it does not exist but cannot
* be created, or if it cannot be opened for any other reason.
* @throws IOException if the {@link WriteOption#CREATE} option is given
* and the specified file already exists.
* @throws SecurityException if a security manager exists and denies
* write access to {@code f}.
*/
public static BufferedWriter newWriter(File f, WriteOption... options)
throws IOException
{
return newWriter(f, Charsets.DEFAULT, options);
}
/**
* Returns a new {@code BufferedWriter} to write to the given
* {@code File} using the specified charset.
*
* @param f the file to write to.
* @param charset the charset to use.
* @param options the write options.
*
* @return a {@code BufferedWriter} to write to the given {@code File}.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws IllegalArgumentException if incompatible options are given.
* @throws FileNotFoundException if {@code f} exists but is a directory
* rather than a regular file, or if it does not exist but cannot
* be created, or if it cannot be opened for any other reason.
* @throws IOException if the {@link WriteOption#CREATE} option is given
* and the specified file already exists.
* @throws SecurityException if a security manager exists and denies
* write access to {@code f}.
*/
public static BufferedWriter newWriter(File f, Charset charset,
WriteOption... options) throws IOException
{
OutputStream out = XFiles.newOutputStream(f, options);
return new BufferedWriter(new OutputStreamWriter(out, charset));
}
/**
* Reads the whole content of the given {@code File} as a {@code String}
* using the system's default charset.
*
* @param f the file to read.
*
* @return the file's content as a {@code String}.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static String read(File f) throws IOException
{
return read(f, Charsets.DEFAULT);
}
/**
* Reads the whole content of the given {@code File} as a {@code String}
* using the specified charset.
*
* @param f the file to read.
* @param charset the charset to use.
*
* @return the file's content as a {@code String}.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static String read(File f, Charset charset) throws IOException
{
BufferedReader in = newReader(f, charset);
try {
return CharStreams.read(in);
} finally {
IO.close(in);
}
}
/**
* Reads all the lines from the given {@code File} using the system's
* default charset. Note that the returned {@code List} is immutable.
*
* @param f the file to read.
*
* @return the file's lines.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> readLines(File f) throws IOException
{
return readLines(f, Charsets.DEFAULT);
}
/**
* Reads all the lines from the given {@code File} using the specified
* charset. Note that the returned {@code List} is immutable.
*
* @param f the file to read.
* @param charset the charset to use.
*
* @return the file's lines.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> readLines(File f, Charset charset)
throws IOException
{
BufferedReader in = newReader(f, charset);
try {
return CharStreams.readLines(in);
} finally {
IO.close(in);
}
}
private TextFiles()
{
/* ... */
}
}
| kocakosm/pitaya | src/org/kocakosm/pitaya/io/TextFiles.java | Java | lgpl-3.0 | 15,156 |
#include <list>
#include <QGLFunctions>
#include <QGLBuffer>
#include <QPaintDevice>
#include <QSharedPointer>
#include <QColor>
#include <QMap>
#include "Scene/transformation.h"
#include "Scene/camera.h"
#include "Scene/scene.h"
#include "Scene/mesh.h"
#include "Scene/meshinstance.h"
#include "Scene/helpers.h"
#include "Math/matrix4.h"
#include "glrenderer.h"
#include "glutils.h"
#include "shader.h"
namespace GLDemo
{
namespace
{
/**
* \internal Class representing GL buffer data for a particular element type.
* Used to cache the buffer data associated with a particular mesh.
*/
class IndexBufferData
{
public:
IndexBufferData(ElementList::ElementType type, const QGLBuffer& buffer, int numIndices) :
m_type(type),
m_indexData(buffer),
m_numIndices(numIndices)
{
}
// Make these public so they can be cheaply accessed from the cache item.
ElementList::ElementType m_type;
QGLBuffer m_indexData;
int m_numIndices;
};
typedef std::list<IndexBufferData> IndexDataList;
/**
* \internal Class for caching GL mesh data once it's been created.
*/
class CachedMesh
{
public:
CachedMesh(const QString& meshId) : m_meshId(meshId) {}
// Make these public so they can be cheaply accessed from the cache item.
QString m_meshId;
QGLBuffer m_vertexData;
IndexDataList m_indexData;
};
}
/**
* \internal
* We extend QGLFunctions so we get access to OpenGL functions here. We extend
* it publicly so that shaders can access the class without having to create their
* own instance of the QGLFunctions class.
*/
class GLRendererImpl : public QGLFunctions
{
public:
typedef QMap<QString, CachedMesh> MeshDataCache;
GLRendererImpl(const GLRendererImpl&);
GLRendererImpl& operator=(const GLRendererImpl&);
GLRenderer& m_renderer;
QPaintDevice& m_paintDevice;
MeshDataCache m_meshCache;
int m_width;
int m_height;
bool m_initialized;
Matrix4f m_matProj;
Matrix4f m_matView;
Matrix4f m_matViewInv;
Camera* m_camera;
GLRendererImpl(GLRenderer& renderer, QPaintDevice& device);
~GLRendererImpl();
void setCamera(Camera* camera);
bool process(const MeshInstance& instance);
void setupViewport(int x, int y, int width, int height);
bool setupMatrices(Scene& scene);
bool preRender(Scene& scene);
bool renderScene(Scene& scene);
bool postRender(Scene& scene);
bool initialize();
bool resize(int width, int height);
};
/**
*
*/
GLRendererImpl::GLRendererImpl(GLRenderer& renderer, QPaintDevice& device) :
m_renderer(renderer),
m_paintDevice(device),
m_width(device.width()),
m_height(device.height()),
m_initialized(false),
m_camera(0)
{
}
/**
*
*/
GLRendererImpl::~GLRendererImpl()
{
// We don't need to worry about cleaning up our allocated QGLBuffers,
// as the destructor of the QGLBuffer object does this for us, according
// to the Qt documentation.
}
/**
*
*/
bool GLRendererImpl::setupMatrices(Scene& scene)
{
// Set up our perspective matrix
const float aspectRatio = static_cast<float>(m_width) / m_height;
const float fov = m_camera->getFieldOfView();
const float zNear = m_camera->getNearPlaneDistance();
const float zFar = m_camera->getFarPlaneDistance();
m_matProj.makePerspectiveProjectionFOV(fov, aspectRatio, zNear, zFar);
m_camera->toViewMatrix(m_matView);
m_matViewInv = m_matView.inverse();
return true;
}
/**
* \param width Width of the viewport.
* \param height Height of the viewport.
*/
void GLRendererImpl::setupViewport(int x, int y, int width, int height)
{
glViewport(x, y, width, height);
}
/**
*
*/
void GLRendererImpl::setCamera(Camera* camera)
{
m_camera = camera;
}
/**
* \param instance The mesh instance to process
*
* Processes a mesh instance, generating the appropriate OpenGL data structures
* if the mesh hasn't before been rendered.
*/
bool GLRendererImpl::process(const MeshInstance& instance)
{
PtrMesh ptrMesh = instance.getMesh();
if (ptrMesh.isNull())
{
std::cout << "ERROR: Mesh " << instance.instanceName() << " contents are invalid." << std::endl;
return false;
}
Mesh& mesh = *ptrMesh;
// For both our vertices and all our primitives, we check to see whether a buffer exists
// for our data, and if not, we create one.
MeshDataCache::iterator meshIter = m_meshCache.find(mesh.instanceName());
if (m_meshCache.end() == meshIter)
{
CachedMesh cachedMesh(mesh.instanceName());
// Qt does shallow copy, so we can copy buffers around in "shallow" manner.
// Start by creating our vertex data.
{
QGLBuffer vbo(QGLBuffer::VertexBuffer);
vbo.setUsagePattern(QGLBuffer::StreamDraw);
if ( !vbo.create() )
{
std::cout << "ERROR: Failed to create vertex buffer object." << std::endl;
return false;
}
vbo.bind();
std::vector<Vertex>& vertices = mesh.getVertices();
vbo.allocate(&vertices.front(), vertices.size() * sizeof(Vertex));
cachedMesh.m_vertexData = vbo;
}
// Now process the elements.
std::list<ElementList>& elementLists = mesh.getElementLists();
for (std::list<ElementList>::iterator elIter = elementLists.begin(); elIter != elementLists.end(); ++elIter)
{
QGLBuffer vbo(QGLBuffer::IndexBuffer);
vbo.setUsagePattern(QGLBuffer::StreamDraw);
if ( !vbo.create() )
{
std::cout << "ERROR: Failed to create index buffer object." << std::endl;
return false;
}
vbo.bind();
std::vector<unsigned>& indices = elIter->getIndices();
vbo.allocate(&indices.front(), indices.size() * sizeof(unsigned));
cachedMesh.m_indexData.push_front( IndexBufferData(elIter->getElementType(), vbo, indices.size()) );
}
meshIter = m_meshCache.insert(mesh.instanceName(), cachedMesh);
}
// Now that we've created the data, we can bind and render it.
CachedMesh& glMesh = *meshIter;
// Activate the shader
const PtrShader& ptrShader = instance.getShader();
if (ptrShader.isNull())
{
std::cout << "ERROR: Mesh instance must have a valid shader in order to be rendered." << std::endl;
return false;
}
// Compute our matrices, starting by obtaining the world matrix.
Matrix4f matWorld;
instance.getWorldTransformation().toMatrix(matWorld);
Matrix4f matWorldView(m_matView * matWorld);
Matrix4f matWorldViewInvTranspose(matWorldView.inverse().transpose());
Matrix4f matWorldViewProj(m_matProj * matWorldView);
if (!ptrShader->activate(m_matView, matWorldView, matWorldViewInvTranspose, matWorldViewProj))
{
std::cout << "ERROR: Failed to activate shader." << std::endl;
return false;
}
// Bind our vertex data to the appropriate attribute locations.
int stride = 8 * sizeof(GLfloat);
glMesh.m_vertexData.bind();
glVertexAttribPointer(GLRenderer::Position, 3, GL_FLOAT, false, stride, 0);
glVertexAttribPointer(GLRenderer::Normal, 3, GL_FLOAT, false, stride, (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(GLRenderer::Position);
glEnableVertexAttribArray(GLRenderer::Normal);
// Now render each set of elements.
IndexBufferData* indices = 0;
for (std::list<IndexBufferData>::iterator iIter = glMesh.m_indexData.begin(); iIter != glMesh.m_indexData.end(); ++iIter)
{
indices = &*iIter;
indices->m_indexData.bind();
switch (indices->m_type)
{
case ElementList::TRI_LIST:
glDrawElements(indices->m_type, 3 * indices->m_numIndices, GL_UNSIGNED_INT, 0);
break;
default:
std::cout << "ERROR: Unable to render element type " << indices->m_type << std::endl;
}
}
return GL_GOOD_STATE();
}
/**
*
*/
bool GLRendererImpl::preRender(Scene& scene)
{
// Make sure the relevant initialization has taken place prior to performing any rendering.
assert(m_initialized);
// Ensure we have a camera set
if (!m_camera)
{
return false;
}
// Need to setup the view and projection matrices in preparation for rendering.
if (!setupMatrices(scene))
return false;
#ifndef NDEBUG
#ifdef Q_OS_OSX
// On newer versions of OSX, it's possible (somehow) to create a widget before creating
// a main framebuffer. This causes OpenGL to return the GL_FRAMEBUFFER_UNDEFINED
// error, and god knows what problems this causes if we continue to render to a context
// with no current draw framebuffer.
GLenum framebufferStatus = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER);
assert(framebufferStatus != GL_FRAMEBUFFER_UNDEFINED);
#endif
#endif
// Clear the buffers in preparation for redrawing the scene.
const QColor& bc = QColor(255, 255, 255, 255);
glClearColor( bc.redF(), bc.greenF(), bc.blueF(), bc.alphaF() );
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
return GL_GOOD_STATE();
}
/**
*
*/
bool GLRendererImpl::renderScene(Scene &scene)
{
// Currently, we are rendering directly as we process each item in the scene. This is less than ideal,
// as what we'd really like to do is sort each item so that we can efficiently render them. The best way
// to do this is to generate a queue of items, sorted according to some pre-generated key.
if (!scene.getRootNode().draw(&m_renderer))
{
std::cout << "ERROR: Failed to draw scene." << std::endl;
return false;
}
return GL_GOOD_STATE();
}
/**
*
*/
bool GLRendererImpl::postRender(Scene& scene)
{
return GL_GOOD_STATE();
}
/**
* Initializes the OpenGL context - must be called only after the context has been created.
* Cannot be invoked from the constructor.
*
* The core activity involved in the initialisation are ensuring the required OpenGL version
* and OpenGL extensions are supported by and ready to use on the current platform.
*/
bool GLRendererImpl::initialize()
{
if (m_initialized)
return true;
initializeGLFunctions();
// Set up our 'permanently' enabled GL states.
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
m_initialized = true;
return GL_GOOD_STATE();
}
/**
*
*/
bool GLRendererImpl::resize(int width, int height)
{
m_width = width;
m_height = height;
setupViewport(0, 0, width, height);
return true;
}
//=============================//
/**
* Creates a new GLRenderer, used for drawing a Scene using OpenGL.
*
* \note While creating a GLRenderer does not require a current OpenGL context,
* deleting one does, as any dedicated resources used by the renderer will potentially be
* cleaned up at the time it is deleted.
*/
GLRenderer::GLRenderer(QPaintDevice& device) :
m_pImpl(static_cast<GLRendererImpl*>(0))
{
m_pImpl = new GLRendererImpl(*this, device);
}
/**
*
*/
GLRenderer::~GLRenderer()
{
delete m_pImpl;
}
/**
* \param camera The camera the renderer should use.
*/
void GLRenderer::setCamera(Camera* camera)
{
m_pImpl->setCamera(camera);
}
/**
* \return The current camera.
*/
Camera* GLRenderer::getCamera()
{
return m_pImpl->m_camera;
}
/**
* \return The current camera.
*/
const Camera* GLRenderer::getCamera() const
{
return m_pImpl->m_camera;
}
/**
* \pre The context must have been made current prior to invoking this function.
* \return True if the initialization of the renderer was successful.
*
* This function should be called once only after the creation of the renderer, as it requires that
* a GL context exists. It will generally be invoked by the initialize event triggered by the GLWidget
* parent of the renderer. If the parent of the renderer does not have such an
* initialization event, this function will need to be invoked manually.
*
* No renderering will occur if initialize has not yet been called on the
* renderer.
*/
bool GLRenderer::initialize()
{
return m_pImpl->initialize();
}
/**
* \pre The context must have been made current prior to invoking this function.
*/
bool GLRenderer::renderScene(Scene& scene)
{
if (!m_pImpl->preRender(scene))
return false;
// Make sure we always post-render if we get past a pre-render
bool success = true;
if (!m_pImpl->renderScene(scene))
success = false;
if (!m_pImpl->postRender(scene))
return false;
return success;
}
/**
* \pre The context must have been made current prior to invoking this function.
* \param width The desired width of the renderer.
* \param height The desired height of the renderer.
*
* \return true if the resize was successful. The resize may fail for a number of reasons,
* but usually only if an invalid size is specified, or it is unable to set up the required
* off-screen buffers.
*/
bool GLRenderer::resize(int width, int height)
{
return m_pImpl->resize(width, height);
}
/**
*
*/
int GLRenderer::getWidth() const
{
return m_pImpl->m_width;
}
/**
*
*/
int GLRenderer::getHeight() const
{
return m_pImpl->m_height;
}
/**
*
*/
bool GLRenderer::process(const MeshInstance& instance)
{
return m_pImpl->process(instance);
}
}
| lhethert/qgldemo | Renderer/glrenderer.cpp | C++ | lgpl-3.0 | 15,398 |
// Catalano Imaging Library
// The Catalano Framework
//
// Copyright © Diego Catalano, 2015
// diego.catalano at live.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
package Catalano.Imaging.Filters;
import Catalano.Imaging.FastBitmap;
import Catalano.Imaging.IBaseInPlace;
/**
* The filter does image binarization using specified threshold value. All pixels with intensities equal or higher than threshold value are converted to white pixels. All other pixels with intensities below threshold value are converted to black pixels.
*
* Supported types: Grayscale.
* Coordinate System: Independent.
*
* @author Diego Catalano
*/
public class Threshold implements IBaseInPlace{
private int value = 128;
private boolean invert = false;
/**
* Initialize a new instance of the Threshold class.
*/
public Threshold() {}
/**
* Initialize a new instance of the Threshold class.
* @param value Threshold value.
*/
public Threshold(int value){
this.value = value;
}
/**
* Initialize a new instance of the Threshold class.
* @param value Threshold value.
* @param invert All pixels with intensities equal or higher than threshold value are converted to black pixels. All other pixels with intensities below threshold value are converted to white pixels.
*/
public Threshold(int value, boolean invert){
this.value = value;
this.invert = invert;
}
/**
* Threshold value.
* @return Threshold value.
*/
public int getValue() {
return value;
}
/**
* Threshold value.
* @param value Threshold value.
*/
public void setValue(int value) {
this.value = value;
}
@Override
public void applyInPlace(FastBitmap fastBitmap){
if (!fastBitmap.isGrayscale())
throw new IllegalArgumentException("Binarization works only with RGB images.");
int[] pixels = fastBitmap.getData();
for (int i = 0; i < pixels.length; i++) {
int l = pixels[i] & 0xFF;
if(invert == false){
if(l >= value){
pixels[i] = 255 << 24 | 255 << 16 | 255 << 8 | 255;
}
else{
pixels[i] = 0;
}
}
else{
if(l < value){
pixels[i] = 0;
}
else{
pixels[i] = 255 << 24 | 255 << 16 | 255 << 8 | 255;
}
}
}
}
} | cswaroop/Catalano-Framework | Catalano.Android.Image/src/Catalano/Imaging/Filters/Threshold.java | Java | lgpl-3.0 | 3,408 |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
// <version>$Revision$</version>
// </file>
using System;
using System.Collections.Generic;
using System.IO;
using ICSharpCode.Core;
using ICSharpCode.SharpZipLib.Zip;
namespace ICSharpCode.AddInManager
{
public class InstallableAddIn
{
string fileName;
bool isPackage;
AddIn addIn;
public AddIn AddIn {
get {
return addIn;
}
}
public InstallableAddIn(string fileName, bool isPackage)
{
this.fileName = fileName;
this.isPackage = isPackage;
if (isPackage) {
ZipFile file = new ZipFile(fileName);
try {
LoadAddInFromZip(file);
} finally {
file.Close();
}
} else {
addIn = AddIn.Load(fileName);
}
if (addIn.Manifest.PrimaryIdentity == null)
throw new AddInLoadException("The AddIn must have an <Identity> for use with the AddIn-Manager.");
}
void LoadAddInFromZip(ZipFile file)
{
ZipEntry addInEntry = null;
foreach (ZipEntry entry in file) {
if (entry.Name.EndsWith(".addin")) {
if (addInEntry != null)
throw new AddInLoadException("The package may only contain one .addin file.");
addInEntry = entry;
}
}
if (addInEntry == null)
throw new AddInLoadException("The package must contain one .addin file.");
using (Stream s = file.GetInputStream(addInEntry)) {
using (StreamReader r = new StreamReader(s)) {
addIn = AddIn.Load(r);
}
}
}
public void Install(bool isUpdate)
{
foreach (string identity in addIn.Manifest.Identities.Keys) {
ICSharpCode.Core.AddInManager.AbortRemoveUserAddInOnNextStart(identity);
}
if (isPackage) {
string targetDir = Path.Combine(ICSharpCode.Core.AddInManager.AddInInstallTemp,
addIn.Manifest.PrimaryIdentity);
if (Directory.Exists(targetDir))
Directory.Delete(targetDir, true);
Directory.CreateDirectory(targetDir);
FastZip fastZip = new FastZip();
fastZip.CreateEmptyDirectories = true;
fastZip.ExtractZip(fileName, targetDir, null);
addIn.Action = AddInAction.Install;
if (!isUpdate) {
AddInTree.InsertAddIn(addIn);
}
} else {
ICSharpCode.Core.AddInManager.AddExternalAddIns(new AddIn[] { addIn });
}
}
public static void CancelUpdate(IList<AddIn> addIns)
{
foreach (AddIn addIn in addIns) {
foreach (string identity in addIn.Manifest.Identities.Keys) {
// delete from installation temp (if installation or update is pending)
string targetDir = Path.Combine(ICSharpCode.Core.AddInManager.AddInInstallTemp,
identity);
if (Directory.Exists(targetDir))
Directory.Delete(targetDir, true);
}
}
}
public static void Uninstall(IList<AddIn> addIns)
{
CancelUpdate(addIns);
foreach (AddIn addIn in addIns) {
foreach (string identity in addIn.Manifest.Identities.Keys) {
// remove the user AddIn
string targetDir = Path.Combine(ICSharpCode.Core.AddInManager.UserAddInPath, identity);
if (Directory.Exists(targetDir)) {
if (!addIn.Enabled) {
try {
Directory.Delete(targetDir, true);
continue;
} catch {
}
}
ICSharpCode.Core.AddInManager.RemoveUserAddInOnNextStart(identity);
}
}
}
}
}
}
| kingjiang/SharpDevelopLite | samples/ICSharpCode.Core.Demo/AddInManager/Src/InstallableAddIn.cs | C# | lgpl-3.0 | 3,447 |
/*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import * as React from 'react';
import { shallow, ShallowWrapper } from 'enzyme';
import ListStyleFacet, { Props } from '../ListStyleFacet';
import { waitAndUpdate } from '../../../helpers/testUtils';
it('should render', () => {
expect(shallowRender()).toMatchSnapshot();
});
it('should select items', () => {
const onChange = jest.fn();
const wrapper = shallowRender({ onChange });
const instance = wrapper.instance() as ListStyleFacet<string>;
// select one item
instance.handleItemClick('b', false);
expect(onChange).lastCalledWith({ foo: ['b'] });
wrapper.setProps({ values: ['b'] });
// select another item
instance.handleItemClick('a', false);
expect(onChange).lastCalledWith({ foo: ['a'] });
wrapper.setProps({ values: ['a'] });
// unselect item
instance.handleItemClick('a', false);
expect(onChange).lastCalledWith({ foo: [] });
wrapper.setProps({ values: [] });
// select multiple items
wrapper.setProps({ values: ['b'] });
instance.handleItemClick('c', true);
expect(onChange).lastCalledWith({ foo: ['b', 'c'] });
wrapper.setProps({ values: ['b', 'c'] });
// unselect item
instance.handleItemClick('c', true);
expect(onChange).lastCalledWith({ foo: ['b'] });
});
it('should toggle', () => {
const onToggle = jest.fn();
const wrapper = shallowRender({ onToggle });
wrapper.find('FacetHeader').prop<Function>('onClick')();
expect(onToggle).toBeCalled();
});
it('should clear', () => {
const onChange = jest.fn();
const wrapper = shallowRender({ onChange, values: ['a'] });
wrapper.find('FacetHeader').prop<Function>('onClear')();
expect(onChange).toBeCalledWith({ foo: [] });
});
it('should search', async () => {
const onSearch = jest.fn().mockResolvedValue({
results: ['d', 'e'],
paging: { pageIndex: 1, pageSize: 2, total: 3 }
});
const loadSearchResultCount = jest.fn().mockResolvedValue({ d: 7, e: 3 });
const wrapper = shallowRender({ loadSearchResultCount, onSearch });
// search
wrapper.find('SearchBox').prop<Function>('onChange')('query');
await waitAndUpdate(wrapper);
expect(wrapper).toMatchSnapshot();
expect(onSearch).lastCalledWith('query');
expect(loadSearchResultCount).lastCalledWith(['d', 'e']);
// load more results
onSearch.mockResolvedValue({
results: ['f'],
paging: { pageIndex: 2, pageSize: 2, total: 3 }
});
loadSearchResultCount.mockResolvedValue({ f: 5 });
wrapper.find('ListFooter').prop<Function>('loadMore')();
await waitAndUpdate(wrapper);
expect(wrapper).toMatchSnapshot();
expect(onSearch).lastCalledWith('query', 2);
// clear search
onSearch.mockClear();
loadSearchResultCount.mockClear();
wrapper.find('SearchBox').prop<Function>('onChange')('');
await waitAndUpdate(wrapper);
expect(wrapper).toMatchSnapshot();
expect(onSearch).not.toBeCalled();
expect(loadSearchResultCount).not.toBeCalled();
// search for no results
onSearch.mockResolvedValue({ results: [], paging: { pageIndex: 1, pageSize: 2, total: 0 } });
wrapper.find('SearchBox').prop<Function>('onChange')('blabla');
await waitAndUpdate(wrapper);
expect(wrapper).toMatchSnapshot();
expect(onSearch).lastCalledWith('blabla');
expect(loadSearchResultCount).not.toBeCalled();
// search fails
onSearch.mockRejectedValue(undefined);
wrapper.find('SearchBox').prop<Function>('onChange')('blabla');
await waitAndUpdate(wrapper);
expect(wrapper).toMatchSnapshot(); // should render previous results
expect(onSearch).lastCalledWith('blabla');
expect(loadSearchResultCount).not.toBeCalled();
});
it('should limit the number of items', () => {
const wrapper = shallowRender({ maxInitialItems: 2, maxItems: 5 });
expect(wrapper.find('FacetItem').length).toBe(2);
wrapper.find('ListStyleFacetFooter').prop<Function>('showMore')();
wrapper.update();
expect(wrapper.find('FacetItem').length).toBe(3);
wrapper.find('ListStyleFacetFooter').prop<Function>('showLess')();
wrapper.update();
expect(wrapper.find('FacetItem').length).toBe(2);
});
it('should show warning that there might be more results', () => {
const wrapper = shallowRender({ maxInitialItems: 2, maxItems: 3 });
wrapper.find('ListStyleFacetFooter').prop<Function>('showMore')();
wrapper.update();
expect(wrapper.find('Alert').exists()).toBe(true);
});
it('should reset state when closes', () => {
const wrapper = shallowRender();
wrapper.setState({
query: 'foobar',
searchResults: ['foo', 'bar'],
searching: true,
showFullList: true
});
wrapper.setProps({ open: false });
checkInitialState(wrapper);
});
it('should reset search when query changes', () => {
const wrapper = shallowRender({ query: { a: ['foo'] } });
wrapper.setState({ query: 'foo', searchResults: ['foo'], searchResultsCounts: { foo: 3 } });
wrapper.setProps({ query: { a: ['foo'], b: ['bar'] } });
checkInitialState(wrapper);
});
it('should collapse list when new stats have few results', () => {
const wrapper = shallowRender({ maxInitialItems: 2, maxItems: 3 });
wrapper.setState({ showFullList: true });
wrapper.setProps({ stats: { d: 1 } });
expect(wrapper.state('showFullList')).toBe(false);
});
it('should display all selected items', () => {
const wrapper = shallowRender({
maxInitialItems: 2,
stats: { a: 10, b: 5, c: 3 },
values: ['a', 'b', 'c']
});
expect(wrapper).toMatchSnapshot();
});
it('should be disabled', () => {
const wrapper = shallowRender({ disabled: true, disabledHelper: 'Disabled helper description' });
expect(wrapper).toMatchSnapshot();
});
function shallowRender(props: Partial<Props<string>> = {}) {
return shallow(
<ListStyleFacet
facetHeader="facet header"
fetching={false}
getFacetItemText={identity}
getSearchResultKey={identity}
getSearchResultText={identity}
onChange={jest.fn()}
onSearch={jest.fn()}
onToggle={jest.fn()}
open={true}
property="foo"
renderFacetItem={identity}
renderSearchResult={identity}
searchPlaceholder="search for foo..."
stats={{ a: 10, b: 8, c: 1 }}
values={[]}
{...props}
/>
);
}
function identity(str: string) {
return str;
}
function checkInitialState(wrapper: ShallowWrapper) {
expect(wrapper.state('query')).toBe('');
expect(wrapper.state('searchResults')).toBe(undefined);
expect(wrapper.state('searching')).toBe(false);
expect(wrapper.state('searchResultsCounts')).toEqual({});
expect(wrapper.state('showFullList')).toBe(false);
}
| Godin/sonar | server/sonar-web/src/main/js/components/facet/__tests__/ListStyleFacet-test.tsx | TypeScript | lgpl-3.0 | 7,356 |
require 'optparse'
require 'rack'
require_relative './handler'
module RackCocaine
class Server < Rack::Server
class Options
def parse!(args)
options = {}
opt_parser = OptionParser.new("", 24, ' ') do |opts|
opts.banner = "Usage: cocaine-rackup [ruby options] [rack options] [rackup config]"
opts.separator ""
opts.separator "Ruby options:"
lineno = 1
opts.on("-e", "--eval LINE", "evaluate a LINE of code") { |line|
eval line, TOPLEVEL_BINDING, "-e", lineno
lineno += 1
}
opts.on("-b", "--builder BUILDER_LINE", "evaluate a BUILDER_LINE of code as a builder script") { |line|
options[:builder] = line
}
opts.on("-d", "--debug", "set debugging flags (set $DEBUG to true)") {
options[:debug] = true
}
opts.on("-w", "--warn", "turn warnings on for your script") {
options[:warn] = true
}
opts.on("-q", "--quiet", "turn off logging") {
options[:quiet] = true
}
opts.on("-I", "--include PATH",
"specify $LOAD_PATH (may be used more than once)") { |path|
(options[:include] ||= []).concat(path.split(":"))
}
opts.on("-r", "--require LIBRARY",
"require the library, before executing your script") { |library|
options[:require] = library
}
opts.separator ""
opts.separator "Rack options:"
options[:server] = 'cocaine'
opts.on('--app NAME', 'Worker name') { |a| options[:app] = a }
opts.on('--locator ADDRESS', 'Locator address') { |a| options[:locator] = a }
opts.on('--uuid UUID', 'Worker uuid') { |a| options[:uuid] = a }
opts.on('--endpoint ENDPOINT', 'Worker endpoint') { |a| options[:endpoint] = a }
opts.on("-O", "--option NAME[=VALUE]", "pass VALUE to the server as option NAME. If no VALUE, sets it to true. Run '#{$0} -s SERVER -h' to get a list of options for SERVER") { |name|
name, value = name.split('=', 2)
value = true if value.nil?
options[name.to_sym] = value
}
opts.on("-E", "--env ENVIRONMENT", "use ENVIRONMENT for defaults (default: development)") { |e|
options[:environment] = e
}
options[:daemonize] = false
options[:pid] = false
opts.separator ""
opts.separator "Common options:"
opts.on_tail("-h", "-?", "--help", "Show this message") do
puts opts
exit
end
opts.on_tail("--version", "Show version") do
puts "Rack #{Rack.version} (Release: #{Rack.release})"
exit
end
end
begin
opt_parser.parse! args
rescue OptionParser::InvalidOption => e
warn e.message
abort opt_parser.to_s
end
options[:config] = args.last if args.last
options
end
end
def self.start(options = nil, &block)
new(options).start(&block)
end
def opt_parser
RackCocaine::Server::Options.new
end
end
end
| fuCtor/rack-cocaine | lib/rack_cocaine/server.rb | Ruby | lgpl-3.0 | 3,360 |
/*
* Copyright (C) 2014 The AppCan Open Source Project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.zywx.wbpalmstar.engine;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.inputmethod.InputMethodManager;
import android.webkit.DownloadListener;
import android.webkit.WebView;
import android.widget.FrameLayout;
import org.json.JSONObject;
import org.zywx.wbpalmstar.acedes.ACEDes;
import org.zywx.wbpalmstar.acedes.EXWebViewClient;
import org.zywx.wbpalmstar.base.BDebug;
import org.zywx.wbpalmstar.base.vo.KernelInfoVO;
import org.zywx.wbpalmstar.engine.EBrowserHistory.EHistoryEntry;
import org.zywx.wbpalmstar.engine.universalex.EUExCallback;
import org.zywx.wbpalmstar.engine.universalex.EUExManager;
import org.zywx.wbpalmstar.engine.universalex.EUExWindow;
import org.zywx.wbpalmstar.widgetone.dataservice.WWidgetData;
import java.lang.reflect.Method;
import java.util.Map;
public class EBrowserView extends WebView implements View.OnLongClickListener,
DownloadListener {
public static final String CONTENT_MIMETYPE_HTML = "text/html";
public static final String CONTENT_DEFAULT_CODE = "utf-8";
public static final int F_PRINT_TYPE_DOM_TREE = 0;
public static final int F_PRINT_TYPE_DISPLAY_TREE = 1;
public static final int F_PRINT_TYPE_RENDER_TREE = 2;
public static final int F_PRINT_TYPE_DRAW_PAGE = 3;
private int mType;
private String mName;
private String mQuery;
private String mRelativeUrl;
private Context mContext;
private EUExManager mUExMgr;
private EBrowserBaseSetting mBaSetting;
private EBrowserWindow mBroWind;
private boolean mShouldOpenInSystem;
private boolean mOpaque;
private boolean mOAuth;
private boolean mWebApp;
private boolean mSupportZoom;
private int mDateType;
private boolean mDestroyed;
private EBrwViewAnim mViewAnim;
private EXWebViewClient mEXWebViewClient;
private Method mDismissZoomControl;
private int mDownloadCallback = 0; // 0 下载不回调,使用引擎下载; 1 下载回调给主窗口,前端自己下载; 2 下载回调给当前窗口,前端自己下载;
// use for debug
private Method mDumpDisplayTree;
private Method mDumpDomTree;
private Method mDumpRenderTree;
private Method mDrawPage;
private int mMyCountId;
private int mScrollDistance = 10;
private EUExWindow callback;
private boolean mIsNeedScroll = false;
private boolean isMultilPopoverFlippingEnbaled = false;
private boolean isSupportSlideCallback = false;//is need callback,set by API interface.
private boolean disturbLongPressGesture = false;
private int mThreshold = 5;
private OnEBrowserViewChangeListener mBrowserViewChangeListener;
public static boolean sHardwareAccelerate = true;//配置全部WebView是否硬件加速,默认开启,config.xml 配置关闭
public EBrowserView(Context context, int inType, EBrowserWindow inParent) {
super(context);
mMyCountId = EBrowser.assignCountID();
mBroWind = inParent;
mContext = context;
mType = inType;
initPrivateVoid();
setOnLongClickListener(this);
setDownloadListener(this);
setACEHardwareAccelerate();
}
public EUExManager getEUExManager() {
return mUExMgr;
}
public void setScrollCallBackContex(EUExWindow callback) {
this.callback = callback;
}
public float getCustomScale(){
float nowScale = 1.0f;
if (Build.VERSION.SDK_INT <= 18) {
nowScale = getScale();
}
return nowScale;
}
public void init() {
setInitialScale(100);
setVerticalScrollbarOverlay(true);
setHorizontalScrollbarOverlay(true);
setLayoutAnimation(null);
setAnimation(null);
setNetworkAvailable(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (mBroWind!=null){
int debug = mBroWind.getWidget().m_appdebug;
setWebContentsDebuggingEnabled(debug == 1 ? true : false);
}
}
if (Build.VERSION.SDK_INT <= 7) {
if (mBaSetting == null) {
mBaSetting = new EBrowserSetting(this);
mBaSetting.initBaseSetting(mWebApp);
setWebViewClient(mEXWebViewClient = new CBrowserWindow());
setWebChromeClient(new CBrowserMainFrame(mContext));
}
} else {
if (mBaSetting == null) {
mBaSetting = new EBrowserSetting7(this);
mBaSetting.initBaseSetting(mWebApp);
setWebViewClient(mEXWebViewClient = new CBrowserWindow7());
setWebChromeClient(new CBrowserMainFrame7(mContext));
}
}
mUExMgr = new EUExManager(mContext);
mUExMgr.addJavascriptInterface(this);
}
private void setACEHardwareAccelerate() {
if (!sHardwareAccelerate) {
setLayerType(LAYER_TYPE_SOFTWARE, null);
} else {
closeHardwareForSpecificString();
}
}
@Override
protected void onAttachedToWindow() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (!isHardwareAccelerated()) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
BDebug.i("setLayerType","LAYER_TYPE_SOFTWARE");
} else {
closeHardwareForSpecificString();
}
}
super.onAttachedToWindow();
}
private void closeHardwareForSpecificString() {
WWidgetData widgetData = getCurrentWidget();
if (widgetData != null) {
for (String noHardware : widgetData.noHardwareList) {
String str = noHardware.trim();
// 手机型号、Android系统定制商、硬件制造商
if (Build.MODEL.trim().equals(str)
|| Build.BRAND.trim().equals(str)
|| Build.MANUFACTURER.trim().equals(str)) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
BDebug.i("setLayerType", "LAYER_TYPE_SOFTWARE");
break;
}
}
}
}
@Override
public boolean isHardwareAccelerated() {
//confirm view is attached to a window
boolean isHardwareAccelerated = super.isHardwareAccelerated();
BDebug.v("isHardwareAccelerated", isHardwareAccelerated);
return isHardwareAccelerated;
}
@Override
public void loadUrl(String url) {
if (mDestroyed) {
return;
}
BDebug.i("loadUrl url " + url);
try {
if (url.startsWith("javascript:") && Build.VERSION.SDK_INT >= 19) {
evaluateJavascript(url.substring("javascript:".length()), null);
} else {
super.loadUrl(url);
}
} catch (Exception e) {
;
}
}
@SuppressLint("NewApi")
@Override
public void loadUrl(String url, Map<String, String> extraHeaders) {
if (mDestroyed) {
return;
}
try {
super.loadUrl(url, extraHeaders);
} catch (Exception e) {
;
}
}
@Override
public void loadData(String data, String mimeType, String encoding) {
if (mDestroyed) {
return;
}
try {
super.loadData(data, mimeType, encoding);
} catch (Exception e) {
;
}
}
@Override
public void loadDataWithBaseURL(String baseUrl, String data,
String mimeType, String encoding, String historyUrl) {
if (mDestroyed) {
return;
}
try {
super.loadDataWithBaseURL(baseUrl, data, mimeType, encoding,
historyUrl);
} catch (Exception e) {
;
}
}
public boolean checkType(int inType) {
return inType == mType;
}
public int getMyId() {
return mMyCountId;
}
public void setDefaultFontSize(int size) {
if (mDestroyed) {
return;
}
mBaSetting.setDefaultFontSize(size);
}
public void setSupportZoom() {
mSupportZoom = true;
mBaSetting.setSupportZoom();
}
public boolean supportZoom() {
return mSupportZoom;
}
@SuppressLint("NewApi")
private void initPrivateVoid() {
Class[] nullParm = {};
try {
mDismissZoomControl = WebView.class.getDeclaredMethod(
"dismissZoomControl", nullParm);
mDismissZoomControl.setAccessible(true);
} catch (Exception e) {
;
}
try {
mDumpDisplayTree = WebView.class.getDeclaredMethod(
"dumpDisplayTree", nullParm);
mDumpDisplayTree.setAccessible(true);
} catch (Exception e) {
;
}
Class[] booleanParam = {boolean.class};
try {
mDumpDomTree = WebView.class.getDeclaredMethod("dumpDomTree",
booleanParam);
mDumpDomTree.setAccessible(true);
} catch (Exception e) {
;
}
try {
mDumpRenderTree = WebView.class.getDeclaredMethod("dumpRenderTree",
booleanParam);
mDumpRenderTree.setAccessible(true);
} catch (Exception e) {
;
}
try {
Class[] canvasParam = {Canvas.class};
mDrawPage = WebView.class
.getDeclaredMethod("drawPage", canvasParam);
mDrawPage.setAccessible(true);
} catch (Exception e) {
;
}
if (Build.VERSION.SDK_INT >= 9) {
setOverScrollMode(2);
return;
}
try {
Class[] intParam = {int.class};
Method setOverScrollMode = WebView.class.getDeclaredMethod(
"setOverScrollMode", intParam);
setOverScrollMode.invoke(this, 2);
} catch (Exception e) {
;
}
}
public void dumpPageInfo(int type) {
switch (type) {
case F_PRINT_TYPE_DOM_TREE:
myDumpDomTree();
break;
case F_PRINT_TYPE_DISPLAY_TREE:
myDumpDisplayTree();
break;
case F_PRINT_TYPE_RENDER_TREE:
myDumpRenderTree();
break;
case F_PRINT_TYPE_DRAW_PAGE:
break;
}
}
// protected void setLayerTypeForHeighVersion() {
// // if(Build.VERSION.SDK_INT < 11){
// // return;
// // }
// // String MODEL = Build.MODEL;
// // String MANUFACTURER = Build.MANUFACTURER;
// // if(null != MODEL && null != MANUFACTURER){
// // MODEL = MODEL.toLowerCase();
// // MANUFACTURER = MANUFACTURER.toLowerCase();
// // if((MODEL.contains("9508") || MODEL.contains("9500")) &&
// // MANUFACTURER.contains("samsung")){
// // return;
// // }
// // }
// // Paint paint = new Paint();
// // paint.setColor(0x00000000);
// // if(isHardwareAccelerated()){
// // setLayerType(View.LAYER_TYPE_SOFTWARE, null);
// // }
// }
// @SuppressLint("NewApi")
// @Override
// protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// if (Build.VERSION.SDK_INT >= 11) {
// String MODEL = Build.MODEL;
// String MANUFACTURER = Build.MANUFACTURER;
// if (null != MODEL && null != MANUFACTURER) {
// MODEL = MODEL.toLowerCase();
// MANUFACTURER = MANUFACTURER.toLowerCase();
// if ((MODEL.contains("9508") || MODEL.contains("9500"))
// && MANUFACTURER.contains("samsung")) {
// if (isHardwareAccelerated()) {
// setLayerType(View.LAYER_TYPE_SOFTWARE, null);
// }
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// return;
// }
// }
// setLayerType(View.LAYER_TYPE_SOFTWARE, null);
// invalidate();
// }
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// }
@SuppressLint("NewApi")
public void destroyControl() {
if (null != mDismissZoomControl) {
try {
mDismissZoomControl.invoke(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@SuppressLint("NewApi")
private void pauseCore() {
if (Build.VERSION.SDK_INT >= 11) {
super.onPause();
} else {
try {
Class[] nullParm = {};
Method pause = WebView.class.getDeclaredMethod("onPause",
nullParm);
pause.setAccessible(true);
pause.invoke(this);
} catch (Exception e) {
;
}
}
}
@SuppressLint("NewApi")
private void resumeCore() {
if (Build.VERSION.SDK_INT >= 11) {
super.onResume();
} else {
try {
Class[] nullParm = {};
Method resume = WebView.class.getDeclaredMethod("onResume",
nullParm);
resume.setAccessible(true);
resume.invoke(this);
} catch (Exception e) {
;
}
}
}
public void myDumpDisplayTree() {
if (null != mDumpDisplayTree) {
try {
mDumpDisplayTree.invoke(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void myDumpDomTree() {
if (null != mDumpDomTree) {
try {
mDumpDomTree.invoke(this, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void myDumpRenderTree() {
if (null != mDumpRenderTree) {
try {
mDumpRenderTree.invoke(this, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void myDrawPage(Canvas canvas) {
if (null != mDrawPage) {
try {
mDrawPage.invoke(this, canvas);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mDestroyed) {
return false;
}
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
if (!isFocused()) {
strugglefoucs();
}
onScrollChanged(getScrollX(), getScrollY(), getScrollX(), getScrollY());
if (mIsNeedScroll) {
//modify no-response-for-onclick-event
int temp_ScrollY = this.getScrollY();
this.scrollTo(this.getScrollX(), this.getScrollY() + 1);
this.scrollTo(this.getScrollX(), temp_ScrollY);
}
setMultilPopoverFlippingEnbaled();
break;
case MotionEvent.ACTION_MOVE:
setMultilPopoverFlippingEnbaled();
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
break;
}
return super.onTouchEvent(ev);
}
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
return super.onGenericMotionEvent(event); //To change body of overridden methods use File | Settings | File Templates.
}
public void setIsMultilPopoverFlippingEnbaled(boolean isEnabled) {
isMultilPopoverFlippingEnbaled = isEnabled;
setMultilPopoverFlippingEnbaled();
}
private void setMultilPopoverFlippingEnbaled() {
View parentBounceView = (View) this.getParent();
if (parentBounceView != null && parentBounceView instanceof EBounceView) {
ViewParent parentViewPager = parentBounceView.getParent();
if (parentViewPager != null && parentViewPager instanceof ViewPager) {
parentViewPager.requestDisallowInterceptTouchEvent(isMultilPopoverFlippingEnbaled);
}
}
}
private void strugglefoucs() {
requestFocus();
/**
* InputManager.get().hideSoftInput(getWindowToken(), 0, null);
* Log.d("ldx", "-------------- view in: " + mName);
*
* Log.d("ldx", "hasFocus: " + hasFocus()); Log.d("ldx", "isFocused: " +
* isFocused());
*
* try{ Class[] nullParam = {}; Method clearHelpers =
* WebView.class.getDeclaredMethod("clearHelpers", nullParam);
* clearHelpers.setAccessible(true); clearHelpers.invoke(this); }catch
* (Exception e) { e.printStackTrace(); } Log.d("ldx",
* "-------------- --------------");
*
* boolean Ac1 = InputManager.get().isActive(); boolean Ac2 =
* InputManager.get().isActive(this); if(Ac1){
* InputManager.get().hideSoftInput(this.getWindowToken(), 0, null); }
* Log.d("ldx", "imm Ac1: " + Ac1); Log.d("ldx", "imm Ac2: " + Ac2); int
* childCount = getChildCount(); Log.d("ldx", "childCount: " +
* childCount); for(int i = 0; i < childCount; ++i){ View child =
* getChildAt(i); boolean Ac3 = InputManager.get().isActive(child);
* Log.d("ldx", "imm Ac3: " + Ac3); if(Ac3){
* InputManager.get().hideSoftInput(child.getWindowToken(), 0, null); }
* child.clearFocus(); } boolean requestFocusOk = requestFocus();
* removeAllViews();
*
* Log.d("ldx", "requestFocusOk: " + requestFocusOk);
**/
// int childCount1 = getChildCount();
// Log.d("ldx", "childCount1: " + childCount1);
Log.d("ldx", "hasFocus: " + hasFocus());
Log.d("ldx", "isFocused: " + isFocused());
Log.d("ldx", "-------------- view out: " + mName);
}
@Override
public boolean onLongClick(View v) {
return disturbLongPressGesture;
}
public void setDisturbLongPressGesture(boolean disturbLongPress) {
disturbLongPressGesture = disturbLongPress;
}
@SuppressLint("NewApi")
@Override
protected void onVisibilityChanged(View v, int visibility) {
super.onVisibilityChanged(v, visibility);
if ((v == this || v == mBroWind)
&& (visibility == INVISIBLE || visibility == GONE)) {
hideSoftKeyboard();
}
}
private void hideSoftKeyboard() {
try {
InputMethodManager imm = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onPageStarted(EBrowserView view, String url) {
if (mDestroyed) {
return;
}
mUExMgr.notifyDocChange();
if (checkType(EBrwViewEntry.VIEW_TYPE_POP) && mOAuth) {
mBroWind.onUrlChange(mName, url);
return;
}
if (!checkType(EBrwViewEntry.VIEW_TYPE_MAIN)) {
return;
}
if (mBroWind!=null) {
mBroWind.onPageStarted(view, url);
}
}
protected void onPageFinished(EBrowserView view, String url) {
if (mDestroyed) {
return;
}
if (mBroWind!=null){
mBroWind.onPageFinished(view, url);
}
if (mBrowserViewChangeListener != null) {
mBrowserViewChangeListener.onPageFinish();
}
}
public boolean isObfuscation() {
if (mDestroyed) {
return false;
}
return mBroWind.isObfuscation();
}
public boolean isOAth() {
if (mDestroyed) {
return false;
}
return mBroWind.isOAuth();
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
@Override
public void goBack() {
if (mDestroyed) {
return;
}
if (isObfuscation()) {
EHistoryEntry enty = mBroWind.getHistory(-1);
if (null != enty) {
String url = enty.mUrl;
if (Build.VERSION.SDK_INT >= 11) {
if (url.startsWith("file")) {
int index = url.indexOf("?");
if (index > 0) {
mQuery = url.substring(index + 1);
url = url.substring(0, index);
}
}
}
if (enty.mIsObfuscation) {
needToEncrypt(this, url, EBrowserHistory.UPDATE_STEP_BACK);
} else {
loadUrl(url);
updateObfuscationHistroy(url,
EBrowserHistory.UPDATE_STEP_BACK, false);
}
}
} else {
super.goBack();
}
}
@Override
public void goForward() {
if (mDestroyed) {
return;
}
if (isObfuscation()) {
EHistoryEntry enty = mBroWind.getHistory(1);
if (null != enty) {
if (enty.mIsObfuscation) {
needToEncrypt(this, enty.mUrl,
EBrowserHistory.UPDATE_STEP_FORWARD);
} else {
loadUrl(enty.mUrl);
updateObfuscationHistroy(enty.mUrl,
EBrowserHistory.UPDATE_STEP_FORWARD, false);
}
}
} else {
super.goForward();
}
}
protected void updateObfuscationHistroy(String inUrl, int step,
boolean isObfuscation) {
if (mDestroyed) {
return;
}
if (!checkType(EBrwViewEntry.VIEW_TYPE_MAIN)) {
return;
}
mBroWind.updateObfuscationHistroy(inUrl, step, isObfuscation);
}
protected void clearObfuscationHistroy() {
if (mDestroyed) {
return;
}
mBroWind.clearObfuscationHistroy();
}
public void addViewToCurrentWindow(View child,
FrameLayout.LayoutParams parms) {
if (mDestroyed) {
return;
}
if (parms != null) {
child.setLayoutParams(parms);
}
mBroWind.addViewToCurrentWindow(child);
}
public void removeViewFromCurrentWindow(View child) {
if (mDestroyed) {
return;
}
mBroWind.removeViewFromCurrentWindow(child);
}
public final void startWidget(WWidgetData inData, EWgtResultInfo inResult) {
if (mDestroyed) {
return;
}
mBroWind.startWidget(inData, inResult);
}
protected void start1(String url) {
if (mDestroyed) {
return;
}
if (null == url || 0 == url.length()) {
return;
}
if (Build.VERSION.SDK_INT >= 11) {
if (url != null) {
int index = url.indexOf("?");
if (index > 0) {
setQuery(url.substring(index + 1));
if (!url.startsWith("http")) {
url = url.substring(0, index);
}
}
}
}
addUriTask(url);
}
private void eClearHistory() {
if (mDestroyed) {
return;
}
if (isObfuscation()) {
clearObfuscationHistroy();
} else {
clearHistory();
}
}
protected void start(String url) {
if (mDestroyed) {
return;
}
if (null == url || 0 == url.length()) {
return;
}
if (isObfuscation()) {
clearObfuscationHistroy();
if (url.startsWith("http")) {
addUriTask(url);
updateObfuscationHistroy(url, EBrowserHistory.UPDATE_STEP_INIT,
false);
} else {
needToEncrypt(this, url, EBrowserHistory.UPDATE_STEP_INIT); // may
// be
// crash
}
} else {
if (Build.VERSION.SDK_INT >= 11) {
if (url != null) {
int index = url.indexOf("?");
if (index > 0) {
setQuery(url.substring(index + 1));
if (!url.startsWith("http")) {
url = url.substring(0, index);
}
}
}
}
addUriTask(url);
clearHistory();
}
}
public void newLoadUrl(String url) {
if (mDestroyed) {
return;
}
if (null == url || 0 == url.length()) {
return;
}
addUriTask(url);
}
public void newLoadData(String inData) {
if (mDestroyed) {
return;
}
loadData(inData, CONTENT_MIMETYPE_HTML, CONTENT_DEFAULT_CODE);
}
protected void receivedError(int errorCode, String description,
String failingUrl) {
if (mDestroyed) {
return;
}
if (checkType(EBrwViewEntry.VIEW_TYPE_ADD)) {
loadUrl("about:bank");
mBroWind.closeAd();
return;
}
String errorPath="file:///android_asset/error/error.html";
if (mBroWind!=null&&!TextUtils.isEmpty(getRootWidget().mErrorPath)){
errorPath="file:///android_asset/widget/"+getRootWidget().mErrorPath;
loadUrl(errorPath);
}else{
loadUrl(errorPath);
}
}
public int getType() {
return mType;
}
public void addUriTask(String uri) {
if (null != mBroWind && !mDestroyed) {
mBroWind.addUriTask(this, uri);
}
}
public void addUriTaskAsyn(String uri) {
if (null != mBroWind && !mDestroyed) {
mBroWind.addUriTaskAsyn(this, uri);
}
}
/**
* 设置是否开启硬件加速
*
* @param flag -1不处理,0关闭,1开启
*/
public void setHWEnable(int flag) {
if (flag == -1) {
return;
}
if (flag == 1) {
setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
protected void needToEncrypt(WebView view, String url, int inFlag) {
if (mDestroyed) {
return;
}
int index = url.indexOf("?");
String turl = url;
if (index > 0) {
setQuery(url.substring(index + 1));
turl = turl.substring(0, index);
}
String data = ACEDes.decrypt(turl, mContext, false, null);
;
if (ACEDes.isSpecifiedEncrypt()) {
// data = SpecifiedEncrypt.parseSpecifiedEncryptHtml(data);
}
// if (SpecifiedEncrypt.isSpecifiedEncrypt()) {
//
// data = SpecifiedEncrypt.parseSpecifiedEncrypt(turl);
//
// } else {
// data = BHtmlDecrypt.decrypt(turl, mContext, false, null);
// }
view.loadDataWithBaseURL(url, data, CONTENT_MIMETYPE_HTML,
CONTENT_DEFAULT_CODE, url);
if (mType == EBrwViewEntry.VIEW_TYPE_MAIN) {
updateObfuscationHistroy(url, inFlag, true);
}
}
public EBrowserWindow getBrowserWindow() {
return mBroWind;
}
public int getWidgetType() {
int type = mBroWind.getWidgetType();
return type;
}
public String getWindowName() {
if (mDestroyed) {
return null;
}
return mBroWind.getName();
}
public void setQuery(String query) {
if (mDestroyed) {
return;
}
mQuery = query;
}
public String getQuery() {
if (mDestroyed) {
return null;
}
return mQuery;
}
public String getRelativeUrl() {
if (mDestroyed) {
return null;
}
return mRelativeUrl;
}
public void setRelativeUrl(String url) {
if (mDestroyed) {
return;
}
mRelativeUrl = url;
}
public String getCurrentUrl() {
if (mDestroyed) {
return "";
}
//修改浮动窗口中不能打开窗口问题
//if (!checkType(EBrwViewEntry.VIEW_TYPE_MAIN)) {
// return mBroWind.location();
//} else {
String url = getUrl();
int index = url.indexOf("?");
if (-1 != index) {
url = url.substring(0, index);
}
int indexS = url.indexOf("#");
if (-1 != indexS) {
url = url.substring(0, indexS);
}
return url;
//}
}
public String getCurrentUrl(String baseUrl) {
if (mDestroyed) {
return "";
}
//修改浮动窗口中不能打开窗口问题
//if (!checkType(EBrwViewEntry.VIEW_TYPE_MAIN)) {
// return mBroWind.location();
//} else {
String url = getUrl();
if (TextUtils.isEmpty(url)) {
url = baseUrl;
}
int index = url.indexOf("?");
if (-1 != index) {
url = url.substring(0, index);
}
int indexS = url.indexOf("#");
if (-1 != indexS) {
url = url.substring(0, indexS);
}
return url;
//}
}
public String getWidgetPath() {
if (mDestroyed) {
return "";
}
String ret = getCurrentWidget().m_widgetPath;
return ret;
}
public WWidgetData getCurrentWidget() {
if (mDestroyed) {
return new WWidgetData();
}
return mBroWind.getWidget();
}
public WWidgetData getRootWidget() {
if (mDestroyed) {
return new WWidgetData();
}
return mBroWind.getRootWidget();
}
public boolean isOAuth() {
return mOAuth;
}
public void setOAuth(boolean flag) {
mOAuth = flag;
}
public boolean shouldOpenInSystem() {
return mShouldOpenInSystem;
}
public void setShouldOpenInSystem(boolean flag) {
mShouldOpenInSystem = flag;
}
public void setOpaque(boolean flag) {
mOpaque = flag;
if (mOpaque) {
setBackgroundColor(0xFFFFFFFF);
} else {
setBackgroundColor(Color.TRANSPARENT);
}
}
/**wanglei del 20151124*/
// public void setBrwViewBackground(boolean flag, String bgColor, String baseUrl) {
// if (flag) {
// if(bgColor.startsWith("#") || bgColor.startsWith("rgb")){
// int color = BUtility.parseColor(bgColor);
// setBackgroundColor(color);
// }else{
// String path = BUtility.makeRealPath(BUtility.makeUrl(getCurrentUrl(baseUrl),bgColor),
// getCurrentWidget().m_widgetPath, getCurrentWidget().m_wgtType);
// Bitmap bitmap = BUtility.getLocalImg(mContext, path);
// Drawable d = null;
// if(bitmap != null){
// d = new BitmapDrawable(mContext.getResources(), bitmap);
// }
// int version = Build.VERSION.SDK_INT;
// if(version < 16){
// setBackgroundDrawable(d);
// setBackgroundColor(Color.argb(0, 0, 0, 0));
// }else{
// setBackground(d);
// setBackgroundColor(Color.argb(0, 0, 0, 0));
// }
// }
// } else {
// setBackgroundColor(Color.TRANSPARENT);
// }
// }
public void setWebApp(boolean flag) {
mWebApp = flag;
}
public boolean isWebApp() {
return mWebApp;
}
public int getDateType() {
return mDateType;
}
public void setDateType(int dateType) {
mDateType = dateType;
}
public void beginAnimition() {
if (mDestroyed) {
return;
}
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null == mViewAnim) {
mViewAnim = new EBrwViewAnim();
}
mViewAnim.beginAnimition(v);
}
});
}
public void setAnimitionDelay(final long del) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.setAnimitionDelay(v, del);
}
}
});
}
public void setAnimitionDuration(final long dur) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.setAnimitionDuration(v, dur);
}
}
});
}
public void setAnimitionCurve(final int cur) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.setAnimitionCurve(v, cur);
}
}
});
}
public void setAnimitionRepeatCount(final int count) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.setAnimitionRepeatCount(v, count);
}
}
});
}
public void setAnimitionAutoReverse(final boolean flag) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.setAnimitionAutoReverse(v, flag);
}
}
});
}
public void makeTranslation(final float tx, final float ty, final float tz) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.makeTranslation(v, tx, ty, tz);
}
}
});
}
public void makeScale(final float tx, final float ty, final float tz) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.makeScale(v, tx, ty, tz);
}
}
});
}
public void makeRotate(final float fd, final float px, final float py,
final float pz) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.makeRotate(v, fd, px, py, pz);
}
}
});
}
public void makeAlpha(final float fc) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.makeAlpha(v, fc);
}
}
});
}
public void commitAnimition() {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.commitAnimition(v);
mBroWind.invalidate();
}
}
});
}
public void cbBounceState(int inData) {
String js = "javascript:if(" + EUExWindow.function_cbBounceState + "){"
+ EUExWindow.function_cbBounceState + "(" + 0 + "," + 2 + ","
+ inData + ")}";
addUriTask(js);
}
public void getBounce() {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.obj = getParent();
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_GET_BOUNCE_VIEW);
}
public void setBounce(int flag) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.obj = getParent();
bounceEntry.flag = flag;
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_SET_BOUNCE_VIEW);
}
public void notifyBounceEvent(int inType, int inStatus) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.type = inType;
bounceEntry.obj = getParent();
bounceEntry.flag = inStatus;
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_NOTIFY_BOUNCE_VIEW);
}
public void showBounceView(int inType, String inColor, int inFlag) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.type = inType;
bounceEntry.obj = getParent();
bounceEntry.color = parseColor(inColor);
bounceEntry.flag = inFlag;
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_SHOW_BOUNCE_VIEW);
}
public void onBounceStateChange(int type, int state) {
String js = "javascript:if(uexWindow.onBounceStateChange){uexWindow.onBounceStateChange("
+ type + "," + state + ");}";
loadUrl(js);
}
public int parseColor(String inColor) {
int reColor = 0;
try {
if (inColor != null && inColor.length() != 0) {
inColor = inColor.replace(" ", "");
if (inColor.charAt(0) == 'r') { // rgba
int start = inColor.indexOf('(') + 1;
int off = inColor.indexOf(')');
inColor = inColor.substring(start, off);
String[] rgba = inColor.split(",");
int r = Integer.parseInt(rgba[0]);
int g = Integer.parseInt(rgba[1]);
int b = Integer.parseInt(rgba[2]);
int a = Integer.parseInt(rgba[3]);
reColor = (a << 24) | (r << 16) | (g << 8) | b;
} else { // #
inColor = inColor.substring(1);
if (3 == inColor.length()) {
char[] t = new char[6];
t[0] = inColor.charAt(0);
t[1] = inColor.charAt(0);
t[2] = inColor.charAt(1);
t[3] = inColor.charAt(1);
t[4] = inColor.charAt(2);
t[5] = inColor.charAt(2);
inColor = String.valueOf(t);
} else if (6 == inColor.length()) {
;
}
long color = Long.parseLong(inColor, 16);
reColor = (int) (color | 0x00000000ff000000);
}
}
} catch (Exception e) {
;
}
return reColor;
}
public void resetBounceView(int inType) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.type = inType;
bounceEntry.obj = getParent();
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_RESET_BOUNCE_VIEW);
}
public void hiddenBounceView(int inType) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.type = inType;
bounceEntry.obj = getParent();
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_HIDDEN_BOUNCE_VIEW);
}
public void setBounceParams(int inType, JSONObject json, String guestId) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.type = inType;
bounceEntry.obj = getParent();
bounceEntry.obj1 = json;
bounceEntry.arg1 = guestId;
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_SET_BOUNCE_PARMS);
}
public void topBounceViewRefresh() {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.obj = getParent();
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_TOP_BOUNCE_VIEW_REFRESH);
}
public boolean beDestroy() {
return mDestroyed;
}
protected void reset() {
mDestroyed = false;
View bv = (View) getParent();
if (bv != null && bv instanceof EBounceView) {
((EBounceView) bv).release();
}
clearView();
clearMatches();
mQuery = null;
mName = null;
mRelativeUrl = null;
mShouldOpenInSystem = false;
mOpaque = false;
mOAuth = false;
mWebApp = false;
mSupportZoom = false;
isSupportSlideCallback = false;
disturbLongPressGesture = false;
eClearHistory();
resumeCore();
mUExMgr.notifyReset();
}
@Override
public void stopLoading() {
super.stopLoading();
mUExMgr.notifyStop();
pauseCore();
}
@Override
public void destroy() {
if (mDestroyed) {
return;
}
mDestroyed = true;
mBroWind = null;
mBaSetting = null;
mContext = null;
clearView();
clearHistory();
ViewGroup parent = (ViewGroup) getParent();
if (null != parent) {
parent.removeView(this);
}
mUExMgr.notifyDestroy(this);
mUExMgr = null;
super.destroy();
}
protected void printThreadStackTrace() {
StackTraceElement[] stak = Thread.currentThread().getStackTrace();
String s = "";
int len = stak.length;
for (int i = 0; i < len; ++i) {
StackTraceElement one = stak[i];
String className = one.getClassName();
String methodName = one.getMethodName();
int line = one.getLineNumber();
String x = s + className + "." + methodName + " [" + line + "]";
x.charAt(0);
if (i == 0 || i == 1 || i == 2) {
s += " ";
}
}
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
//if (!EBrowserWindow.isShowDialog) {
int versionA = Build.VERSION.SDK_INT;
boolean isSlideCallback = false;
if (versionA >= 19) {
//system above 4.4, is support callback depend on isSupportSlideCallback which
// set by developer.
// 4.4以上手机系统,是否回调取决于前端接口设置。
isSlideCallback = isSupportSlideCallback;
} else {
//system below 4.4, is support callback depend on isSupportSlideCallback and
//isShowDialog, isShowDialog indicate is pop-up keyboard or whether to switch
// the screen.
// 4.4以下手机系统,是否回调即取决于前端接口设置,也取决于当前键盘是否弹出或者是否变换屏幕。因此在该
// 条件下屏幕旋转之后,上滑下滑的监听不生效。
isSlideCallback = isSupportSlideCallback && !EBrowserWindow.isShowDialog;
}
if (isSlideCallback) {
float contentHeight = getContentHeight() * getCustomScale();
boolean isSlipedDownEdge = t != oldt && t > 0
&& contentHeight <= t + getHeight() + mThreshold;
if (isSlipedDownEdge) {
callback.jsCallback(EUExWindow.function_cbslipedDownEdge, 0,
EUExCallback.F_C_INT, 0);
callback.jsCallback(EUExWindow.function_onSlipedDownEdge, 0,
EUExCallback.F_C_INT, 0);
} else if (getScrollY() == 0) {
callback.jsCallback(EUExWindow.function_cbslipedUpEdge, 0,
EUExCallback.F_C_INT, 0);
callback.jsCallback(EUExWindow.function_onSlipedUpEdge, 0,
EUExCallback.F_C_INT, 0);
} else if (oldt - t > mScrollDistance) {
callback.jsCallback(EUExWindow.function_cbslipedDownward, 0,
EUExCallback.F_C_INT, 0);
callback.jsCallback(EUExWindow.function_onSlipedDownward, 0,
EUExCallback.F_C_INT, 0);
} else if (oldt - t < -mScrollDistance) {
callback.jsCallback(EUExWindow.function_cbslipedUpward, 0,
EUExCallback.F_C_INT, 0);
callback.jsCallback(EUExWindow.function_onSlipedUpward, 0,
EUExCallback.F_C_INT, 0);
}
}
//}
super.onScrollChanged(l, t, oldl, oldt);
}
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength) {
if (mDownloadCallback == 0) {
mEXWebViewClient.onDownloadStart(mContext, url, userAgent,
contentDisposition, mimetype, contentLength);
} else {
mBroWind.executeCbDownloadCallbackJs(this, mDownloadCallback,
url, userAgent, contentDisposition, mimetype, contentLength);
}
}
public void setNeedScroll(boolean b) {
this.mIsNeedScroll = b;
}
public void setIsSupportSlideCallback(boolean isSupport) {
isSupportSlideCallback = isSupport;
}
public void setEBrowserViewChangeListener(OnEBrowserViewChangeListener browserViewChangeListener) {
mBrowserViewChangeListener = browserViewChangeListener;
}
public interface OnEBrowserViewChangeListener {
void onPageFinish();
}
public String getWebViewKernelInfo() {
KernelInfoVO infoVO = new KernelInfoVO();
if (Build.VERSION.SDK_INT > 18) {
infoVO.setKernelType("System(Blink)");
try {
PackageManager pm = this.getContext().getPackageManager();
PackageInfo pinfo = pm.getPackageInfo("com.google.android.webview",
PackageManager.GET_CONFIGURATIONS);
infoVO.setKernelVersion(pinfo.versionName);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
} else {
infoVO.setKernelType("System(Webkit)");
}
String info = DataHelper.gson.toJson(infoVO);
return info;
}
public void setUserAgent(String userAgent) {
mBaSetting.setUserAgent(userAgent);
}
public int getDownloadCallback() {
if (mDestroyed) {
return 0;
}
return mDownloadCallback;
}
public void setDownloadCallback(int downloadCallback) {
if (mDestroyed) {
return;
}
this.mDownloadCallback = downloadCallback;
}
}
| pingping-jiang6141/Engine-Master | Engine/src/org/zywx/wbpalmstar/engine/EBrowserView.java | Java | lgpl-3.0 | 49,210 |
package ecologylab.serialization.deserializers.parsers.bibtex.entrytypes;
import ecologylab.serialization.annotations.bibtex_tag;
import ecologylab.serialization.annotations.bibtex_type;
import ecologylab.serialization.annotations.simpl_inherit;
import ecologylab.serialization.annotations.simpl_scalar;
import ecologylab.serialization.annotations.simpl_tag;
@simpl_inherit
@simpl_tag("bibtex_techreport")
@bibtex_type("techreport")
public class BibTeXTechReport extends AbstractBibTeXEntry
{
// required fields
@simpl_scalar
@bibtex_tag("institution")
private String institution;
@simpl_scalar
@bibtex_tag("type")
private String type;
@simpl_scalar
@bibtex_tag("number")
private long number;
@simpl_scalar
@bibtex_tag("address")
private String address;
public String getInstitution()
{
return institution;
}
public void setInstitution(String institution)
{
this.institution = institution;
}
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
public long getNumber()
{
return number;
}
public void setNumber(long number)
{
this.number = number;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
}
| ecologylab/ecologylabFundamental | src/ecologylab/serialization/deserializers/parsers/bibtex/entrytypes/BibTeXTechReport.java | Java | lgpl-3.0 | 1,351 |
package org.orchestra.client;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.SignatureException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.orchestra.auth.Constants;
import org.orchestra.rest.ServerAuthHelper;
import org.orchestra.util.CipherUtil;
import org.orchestra.util.HttpUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
public class ClientAuthHelper {
private static Map<String, String> cache = new HashMap<String, String>();
private String username;
private String password;
private String filename;
private String apikeyPath;
public ClientAuthHelper(String username, String password) {
this.username = username;
this.password = password;
this.apikeyPath = Client.getProperty("apikey.dir");
this.filename = new Md5Hash(username) + ".apikey";
}
public String getApikey() {
String apikey = cache.get(username);
if(apikey != null) return apikey;
apikey = loadApikeyFromFile();
if(apikey != null) return apikey;
apikey = getApikeyFromServer();
return apikey;
}
private String getApikeyFromServer() {
HttpCommandBuilder builder = new HttpCommandBuilder(username, password);
HttpCommand command = builder.setScheme("https")
.setNeedAuthHeader(true)
.setHost(Client.getProperty("server"))
.setPort(Integer.valueOf(Client.getProperty("port")))
.setAction("update")
.setTarget("apikey")
.addPathParameter(username)
.addPathParameter(Client.getName())
.build();
HttpResponse response = command.execute();
if(200 != response.getStatusLine().getStatusCode()) {
throw new RuntimeException("Unable to get apikey from server.");
}
String apikey = saveApikeyToFile(response);
return apikey;
}
public void removeApikeyFile() {
File file = new File(apikeyPath + "/" + filename);
if(file.exists()) file.delete();
}
public String saveApikeyToFile(HttpResponse response) {
Reader in = null;
try {
in = new InputStreamReader(response.getEntity().getContent());
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
JSONObject json = (JSONObject) JSONValue.parse(in);
String apikey = null;
if(json != null) {
apikey = (String) json.get("apikey");
String secret = (String) json.get("secret");
cache.put(username, apikey);
cache.put(apikey, secret);
String jsonString = json.toJSONString();
System.out.println(jsonString);
OutputStream out = null;
try {
String apikey_filename = apikeyPath + "/" + filename;
File file = new File(apikey_filename);
if(file.exists()) {
file.delete();
}
out = new FileOutputStream(apikey_filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
CipherUtil.encrypt(jsonString , out , password);
}
return apikey;
}
private String loadApikeyFromFile() {
File file = new File(apikeyPath + "/" + filename);
InputStream in = null;
if(!file.exists()) return null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String jsonString = CipherUtil.decrypt(in, password);
JSONObject json = (JSONObject) JSONValue.parse(jsonString);
if(json == null) return null;
String apikey = (String) json.get("apikey");
String secret = (String) json.get("secret");
if(apikey == null || secret == null) return null;
cache.put(username, apikey);
cache.put(apikey, secret);
return apikey;
}
public String sign(HttpCommandBuilder request) throws SignatureException, UnsupportedEncodingException {
String secret = cache.get(getApikey());
String canonicalRequestHashHex = CipherUtil.toHex(CipherUtil.hash(getCanonicalRequest(request)));
String timestamp = (String) request.getParameter("timestamp");
String nonce = (String) request.getParameter("nonce");
String stringToSign =
Constants.SIGNATURE_ALGORITHM + Constants.NEW_LINE +
timestamp + Constants.NEW_LINE +
canonicalRequestHashHex;
DateTimeFormatter formatter = DateTimeFormat.forPattern(Constants.TIMESTAMP_FORMAT);
DateTime date = formatter.parseDateTime(timestamp);
String dateStamp = date .toString(Constants.DATE_FORMAT);
byte[] kDate = CipherUtil.sign(dateStamp, secret);
byte[] kSigning = CipherUtil.sign(nonce , kDate);
byte[] signature = CipherUtil.sign(stringToSign, kSigning);
String signatureHex = CipherUtil.toHex(signature);
return signatureHex;
}
public static String getCanonicalRequest(HttpCommandBuilder request) throws UnsupportedEncodingException, SignatureException {
String method = request.getMethod();
String canonicalURI = HttpUtil.canonicalURI(request.getPath());
String canonicalQueryString = canonicalizeQueryString(request);
String canonicalHeadersString = canonicalizeHeadersString(request);
String signedHeadersString = getSignedHeadersString(request);
String canonicalRequest =
method + Constants.NEW_LINE +
canonicalURI + Constants.NEW_LINE +
canonicalQueryString + Constants.NEW_LINE +
canonicalHeadersString + Constants.NEW_LINE +
signedHeadersString;
return canonicalRequest;
}
private static String canonicalizeHeadersString(HttpCommandBuilder request) {
Map<String, String> headers = request.getAllHeaders();
StringBuilder buffer = new StringBuilder();
for( Entry<String, String> header : headers.entrySet()) {
if(header.getKey().equalsIgnoreCase(Constants.SIGNED_HEADERS)) continue;
buffer.append(header.getKey().toLowerCase()).append(":");
String values = header.getValue();
buffer.append(values.trim());
buffer.append(Constants.NEW_LINE);
}
return buffer.toString();
}
private static String canonicalizeQueryString(HttpCommandBuilder request) {
String queryString = request.getQueryString();
return HttpUtil.canonicalizeQueryString(queryString);
}
public static String getSignedHeadersString(HttpCommandBuilder request) {
Map<String, String> headers = request.getAllHeaders();
StringBuilder buffer = new StringBuilder();
for(Entry<String, String> header : headers.entrySet()) {
if(header.getKey().equalsIgnoreCase(Constants.SIGNED_HEADERS)) continue;
if (buffer.length() > 0) buffer.append(";");
buffer.append(header.getKey().toLowerCase());
}
return buffer.toString();
}
private static class HeaderComparator implements Comparator<org.apache.http.Header> {
@Override
public int compare(org.apache.http.Header o1,
org.apache.http.Header o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
}
}
| bigorc/orchestra | src/main/java/org/orchestra/client/ClientAuthHelper.java | Java | lgpl-3.0 | 7,259 |
using System;
using System.Runtime.Serialization;
using Sandbox.Common.ObjectBuilders;
namespace SEModAPIInternal.API.Entity.Sector.SectorObject.CubeGrid.CubeBlock
{
[DataContract( Name = "ConveyorBlockEntityProxy" )]
public class ConveyorBlockEntity : CubeBlockEntity
{
#region "Attributes"
public static string ConveyorBlockNamespace = "";
public static string ConveyorBlockClass = "=TOO9vEcUQ4GPDzJaGQ7GgjTGAt=";
#endregion "Attributes"
#region "Constructors and Intializers"
public ConveyorBlockEntity( CubeGridEntity parent, MyObjectBuilder_Conveyor definition )
: base( parent, definition )
{
}
public ConveyorBlockEntity( CubeGridEntity parent, MyObjectBuilder_Conveyor definition, Object backingObject )
: base( parent, definition, backingObject )
{
}
#endregion "Constructors and Intializers"
}
} | Tyrsis/SE-Community-Mod-API | SEModAPIInternal/API/Entity/Sector/SectorObject/CubeGrid/CubeBlock/ConveyorBlockEntity.cs | C# | lgpl-3.0 | 846 |
/*
# (C) British Crown Copyright 2015 - 2020, Met Office
#
# This file is part of agg-regrid.
#
# agg-regrid is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# agg-regrid is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with agg-regrid. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include <agg_basics.h>
#include <agg_pixfmt_gray.h>
#include <agg_rasterizer_scanline_aa.h>
#include <agg_renderer_base.h>
#include <agg_renderer_scanline.h>
#include <agg_rendering_buffer.h>
//#include <agg_scanline_p.h>
#include <agg_scanline_u.h>
#include <_agg_raster.h>
void _raster(uint8_t *weights, const double *xi, const double *yi,
int nx, int ny)
{
typedef agg::renderer_base<agg::pixfmt_gray8> ren_base;
agg::rendering_buffer rbuf(weights, nx, ny, nx);
agg::pixfmt_gray8 pixf(rbuf);
ren_base ren(pixf);
//agg::scanline_p8 sl;
agg::scanline_u8 sl;
//ren.clear(agg::gray8(255));
agg::rasterizer_scanline_aa<> ras;
ras.reset();
ras.move_to_d(xi[0], yi[0]);
ras.line_to_d(xi[1], yi[1]);
ras.line_to_d(xi[3], yi[3]);
ras.line_to_d(xi[2], yi[2]);
agg::render_scanlines_aa_solid(ras, sl, ren, agg::gray8(255));
}
| SciTools-incubator/iris-agg-regrid | agg_regrid/_agg_raster.cpp | C++ | lgpl-3.0 | 1,666 |
#include "ros1initializer.h"
#include <ros/ros.h>
#include <common/logging.h>
using namespace roscommunication;
Ros1Initializer::Ros1Initializer(QString name)
: mInitialized(false)
{
ros::VP_string initString;
QString nodeName = name;
ros::init(initString, nodeName.toStdString());
if(!ros::isInitialized())
{
debug(LOG_ERROR, "RosInitializer", "Could not initialize ROS");
return;
}
mInitialized = true;
debug(LOG_WARNING, "RosInitializer", "Initialized");
ROS_INFO("ROS initialized");
}
bool Ros1Initializer::initialized() const
{
return mInitialized;
}
| piappl/ros2_benchmarking | comm/ros1node/ros1initializer.cpp | C++ | lgpl-3.0 | 620 |
using System;
using System.Linq;
using NUnit.Framework;
namespace StringCalcKata
{
[TestFixture]
public class StringCalcKataTests
{
public StringCalculator Calculator;
[TestFixtureSetUp]
public void CreateCalculator()
{
Calculator = new StringCalculator();
}
[TestCase("", 0)]
[TestCase("1,1", 2)]
[TestCase("2,2", 4)]
[TestCase("4,8", 12)]
[TestCase("172,28", 200)]
public void CalculateTwoNumberSum(string sum, int expected)
{
var result = Calculator.Add(sum);
Assert.AreEqual(expected, result);
}
[TestCase("2,2,2", 6)]
[TestCase("8,16,32", 56)]
[TestCase("8,16,32,64,128", 248)]
public void CalculateAnyNumberSum(string sum, int expected)
{
var result = Calculator.Add(sum);
Assert.AreEqual(expected, result);
}
[TestCase("2\n2,2", 6)]
[TestCase("8,16\n32", 56)]
[TestCase("8,16\n32,64\n128", 248)]
public void CalculateAnyNumberSumWithNewLine(string sum, int expected)
{
var result = Calculator.Add(sum);
Assert.AreEqual(expected, result);
}
[TestCase("//;\n2;2;2", 6)]
[TestCase("// \n8 16 32", 56)]
[TestCase("//+\n8+16+32+64+128", 248)]
[TestCase("//split\n2split2", 4)]
[TestCase("//[*][%]\n1*2%3", 6)]
public void CalculateAnyNumberSumWithDelimiterDefined(string sum, int expected)
{
var result = Calculator.Add(sum);
Assert.AreEqual(expected, result);
}
[Test]
public void CalculatingWithANegativeNumber_ReturnsException()
{
var exception = Assert.Throws<ArgumentOutOfRangeException>(() => Calculator.Add("1,-1"));
Assert.AreEqual("Negatives are not allowed.", exception.Message.Split('\r').First());
}
[Test]
public void CalculatingWithANumberOverAThousandIgnoresTheNumber()
{
var result = Calculator.Add("2,1001");
Assert.AreEqual(2, result);
}
}
} | StormPooper/CSharpKatas | StringCalcKata/StringCalcKataTests.cs | C# | unlicense | 2,173 |
angular.module('dnsControllers', ['dnsServices', 'dnsModels'])
.controller('dnsCtrl', function($scope, $location, socket, Hosts, Zone) {
$scope.dns = {
zone : Zone.get(),
hosts : Hosts.list()
};
socket.on('new:host', function (host) {
var found = false;
if ($scope.dns.hosts.records) {
for (var i = 0 ; i < $scope.dns.hosts.records.length ; ++i) {
if ($scope.dns.hosts.records[i].name === host.name) {
found = true;
$scope.dns.hosts.records[i].record = host.record;
break;
}
}
}
if (!found) {
if (!$scope.dns.hosts.records)
$scope.dns.hosts.records = [];
$scope.dns.hosts.records.push(host);
}
});
socket.on('delete:host', function (host) {
if ($scope.dns.hosts.records) {
for (var i = 0 ; i < $scope.dns.hosts.records.length ; ++i) {
if ($scope.dns.hosts.records[i].name === host.name) {
$scope.dns.hosts.records.splice(i, 1);
break;
}
}
}
});
})
;
| binRick/thc.digital | dnsServer/public/js/controllers/dns-controller.js | JavaScript | unlicense | 1,158 |
<?php
namespace Google\Service\Manager;
class FirewallModule extends \Google\Collection
{
protected $allowedType = 'Google\Service\Manager\AllowedRule';
protected $allowedDataType = 'array';
public $description;
public $network;
public $sourceRanges;
public $sourceTags;
public $targetTags;
public function setAllowed($allowed)
{
$this->allowed = $allowed;
}
public function getAllowed()
{
return $this->allowed;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setNetwork($network)
{
$this->network = $network;
}
public function getNetwork()
{
return $this->network;
}
public function setSourceRanges($sourceRanges)
{
$this->sourceRanges = $sourceRanges;
}
public function getSourceRanges()
{
return $this->sourceRanges;
}
public function setSourceTags($sourceTags)
{
$this->sourceTags = $sourceTags;
}
public function getSourceTags()
{
return $this->sourceTags;
}
public function setTargetTags($targetTags)
{
$this->targetTags = $targetTags;
}
public function getTargetTags()
{
return $this->targetTags;
}
}
| inri13666/google-api-php-client-v2 | libs/Google/Service/Manager/FirewallModule.php | PHP | unlicense | 1,274 |
package com.mocha.util.queue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* <strong>Title : ConcurrentLinkedQueueExtendsHandler </strong>. <br>
* <strong>Description : 队列管理.</strong> <br>
* <strong>Create on : 2014年8月14日 下午2:31:02 </strong>. <br>
* <p>
* <strong>Copyright (C) Mocha Software Co.,Ltd.</strong> <br>
* </p>
*
* @author 刘军 liujun1@mochasoft.com.cn <br>
* @version <strong>Mocha JavaOA v7.0.0</strong> <br>
* <br>
* <strong>修改历史: .</strong> <br>
* 修改人 修改日期 修改描述<br>
* -------------------------------------------<br>
* <br>
* <br>
*/
public class ConcurrentLinkedQueueExtendsHandler<E> implements QueueHandler<E> {
/**
* 单例对象实例
*/
private static ConcurrentLinkedQueueExtendsHandler instance = null;
// public static ConcurrentLinkedQueueExtendsHandler getInstance() {
// if (instance == null) {
// instance = new ConcurrentLinkedQueueExtendsHandler(); //
// }
// return instance;
// }
private static class ConcurrentLinkedQueueExtendsSingletonHolder {
/**
* 单例对象实例
*/
static final ConcurrentLinkedQueueExtendsHandler INSTANCE = new ConcurrentLinkedQueueExtendsHandler();
}
public static ConcurrentLinkedQueueExtendsHandler getInstance() {
return ConcurrentLinkedQueueExtendsSingletonHolder.INSTANCE;
}
/**
* private的构造函数用于避免外界直接使用new来实例化对象
*/
private ConcurrentLinkedQueueExtendsHandler() {
}
// 队列容器
List<ConcurrentLinkedQueueExtends<E>> queueList = new LinkedList<ConcurrentLinkedQueueExtends<E>>();
// 队列名字容器
List<String> queueNames = new ArrayList<String>();
// =========================对队列的操作
/**
* 根据名称参数动态创建不包含任何元素的空队列
*
* @param name
* 队列的名字
* @return
* @throws Exception
*/
@Override
public ConcurrentLinkedQueueExtends<E> createQueueByName(String name)
throws Exception {
if (null == name || "".equals(name)) {
throw new Exception("队列名称不能为空。");
}
if (queueNames.contains(name)) {
throw new Exception("此名称已被使用,请另起其他名字。");
}
ConcurrentLinkedQueueExtends<E> queue = new ConcurrentLinkedQueueExtends<E>(
name);
// 将队列加到容器中
queueList.add(queue);
// 将本队列名加入容器中
queueNames.add(name);
return queue;
}
/**
* 根据名称参数动态创建不包含任何元素的空队列
*
* @param name
* 队列的名字
* @return
* @throws Exception
*/
@Override
public void createQueueByNames(String[] names) throws Exception {
for (String name : names) {
if (null == name || "".equals(name)) {
throw new Exception("队列名称不能为空。");
}
if (queueNames.contains(name)) {
throw new Exception("此名称已被使用,请另起其他名字。");
}
ConcurrentLinkedQueueExtends<E> queue = new ConcurrentLinkedQueueExtends<E>(
name);
// 将队列加到容器中
queueList.add(queue);
// 将本队列名加入容器中
queueNames.add(name);
}
}
/**
* 根据名称参数动态创建不包含任何元素的空队列, 并设置队列的大小。
*
* @param name
* 队列的名字
* @param length
* 队列元素最大个数
* @return 新的队列对象
* @throws Exception
*/
@Override
public ConcurrentLinkedQueueExtends<E> createQueueByName(String name,
int maxSize) throws Exception {
if (null == name || "".equals(name)) {
throw new Exception("队列名称不能为空。");
}
if (queueNames.contains(name)) {
throw new Exception("此名称已被使用,请另起其他名字。");
}
if (maxSize <= 0) {
throw new Exception("队列大小必须大于零");
}
ConcurrentLinkedQueueExtends<E> queue = new ConcurrentLinkedQueueExtends<E>(
name, maxSize);
// 将队列加到容器中
queueList.add(queue);
// 将本队列名加入容器中
queueNames.add(name);
return queue;
}
public boolean checkqueueName(String name) {
boolean flag = false;
if (queueNames.contains(name)) {
flag = true;
}
return flag;
}
/**
* 根据名称参数动态获得队列。
*
* @param name
* 队列的名字
* @return
* @throws Exception
*/
@Override
public ConcurrentLinkedQueueExtends<E> getQueueByName(String name)
throws Exception {
if (queueNames.contains(name)) {
return queueList.get(queueNames.indexOf(name));
} else
throw new Exception("不存在名称为 " + name + "的队列");
}
/**
* 根据名称参数动态删除队列
*
* @param name
* 队列的名字
*/
@Override
public void removeQueueByName(String name) {
if (queueNames.contains(name)) {
queueList.remove(queueNames.indexOf(name));
queueNames.remove(name);
}
}
// =========================对队列中的元素的操作
// 1.添加
/**
* 根据队列名向队列中添加元素,若添加元素失败,则抛出异常
*
* @param queueName
* 队列名字
* @param e
* 向队列中添加的元素
* @return
* @throws Exception
*/
@Override
public boolean add(String queueName, E e) throws Exception {
ConcurrentLinkedQueueExtends<E> queue = this.getQueueByName(queueName);
if (queue.size() >= queue.getMaxSize()) {
throw new Exception("队列已满,不允许继续添加元素。");
}
return queue.add(e);
}
/**
* 根据队列名向队列中添加元素集合,若添加元素集合失败,则抛出异常
*
* @param queueName
* 队列名称
* @param c
* collection containing elements to be added to this queue
* @return <tt>true</tt> if this queue changed as a result of the call
* @throws Exception
*/
@Override
public boolean addAll(String queueName, Collection<? extends E> c)
throws Exception {
ConcurrentLinkedQueueExtends<E> queue = this.getQueueByName(queueName);
if (queue.size() >= queue.getMaxSize()) {
throw new Exception("队列已满,不允许继续添加元素。");
} else if (queue.size() + c.size() > queue.getMaxSize()) {
throw new Exception("新增的集合中的元素太多,以致超出队列容量上限");
}
return queue.addAll(c);
}
/**
* 根据队列名向队列中添加元素,若添加元素失败,则返回false
*
* @param queueName
* 队列名
* @param e
* 向队列中添加的元素
* @return
* @throws Exception
*/
@Override
public boolean offer(String queueName, E e) throws Exception {
ConcurrentLinkedQueueExtends<E> queue = this.getQueueByName(queueName);
if (queue.size() >= queue.getMaxSize()) {
throw new Exception("队列已满,不允许继续添加元素。");
}
return queue.offer(e);
}
// 2.得到但不删除
/**
* 获取但不移除此队列的头;如果此队列为空,则返回 null。
*
* @param queueName
* 队列名字
* @return 队列的头,如果此队列为空,则返回 null
* @throws Exception
*/
@Override
public E peek(String queueName) throws Exception {
return this.getQueueByName(queueName).peek();
}
/**
* 获取但不移除此队列的头;如果此队列为空,则抛出异常。
*
* @param queueName
* 队列名字
* @return 队列的头,如果此队列为空,则抛出异常
* @throws Exception
*/
@Override
public E element(String queueName) throws Exception {
return this.getQueueByName(queueName).element();
}
// 3.得到并删除
/**
* 获取并移除此队列的头,如果此队列为空,则返回 null。
*
* @param queueName
* 队列名字
* @return 此队列的头;如果此队列为空,则返回 null
* @throws Exception
*/
@Override
public E poll(String queueName) throws Exception {
return this.getQueueByName(queueName).poll();
}
/**
* 获取并移除此队列的头,如果此队列为空,则抛出异常。
*
* @param queueName
* 队列名字
* @return
* @throws Exception
*/
@Override
public E remove(String queueName) throws Exception {
return this.getQueueByName(queueName).remove();
}
/**
* 根据队列名删除某一元素
*
* @param queueName
* 队列名字
* @param o
* 删除的元素
* @return
* @throws Exception
*/
@Override
public boolean remove(String queueName, Object o) throws Exception {
return this.getQueueByName(queueName).remove(o);
}
/**
*
* @param queueName
* 队列名字
* @param c
* 删除的元素
* @return
* @throws Exception
*/
@Override
public boolean removeAll(String queueName, Collection<?> c)
throws Exception {
return this.getQueueByName(queueName).removeAll(c);
}
/**
* 清空队列
*
* @param queueName
* 队列名字
* @throws Exception
*/
@Override
public void clear(String queueName) throws Exception {
this.getQueueByName(queueName).clear();
}
/**
* 判断 名称与参数一致的 队列 中是否有元素
*
* @param queueName
* 队列名
* @return
* @throws Exception
*/
@Override
public boolean isEmpty(String queueName) throws Exception {
return this.getQueueByName(queueName).isEmpty();
}
/**
* 根据 队列名 判断队列中已有元素的歌声
*
* @param queueName
* 队列名
* @return
* @throws Exception
*/
@Override
public int size(String queueName) throws Exception {
return this.getQueueByName(queueName).size();
}
/**
* 根据队列名判断队列中是否包含某一元素
*
* @param queueName
* 队列名
* @param o
* 元素
* @return
* @throws Exception
*/
@Override
public boolean contains(String queueName, Object o) throws Exception {
return this.getQueueByName(queueName).contains(o);
}
/**
* 根据队列名判断队列中是否包含某些元素
*
* @param queueName
* 队列名
* @param c
* 元素集合
* @return
* @throws Exception
*/
@Override
public boolean containsAll(String queueName, Collection<?> c)
throws Exception {
return this.getQueueByName(queueName).containsAll(c);
}
/**
* 根据队列名将某一队列中的元素转换为Object数组形式
*
* @param queueName
* @return
* @throws Exception
*/
@Override
public Object[] toArray(String queueName) throws Exception {
return this.getQueueByName(queueName).toArray();
}
/**
* 根据队列名将某一队列中的元素转换为某一特定类型的数组形式
*
* @param queueName
* 队列名
* @param a
* @return
* @throws Exception
*/
@Override
public <T> T[] toArray(String queueName, T[] a) throws Exception {
return this.getQueueByName(queueName).toArray(a);
}
/**
* 根据队列名遍历队列中所有元素
*
* @param queueName
* 队列名
* @return
* @throws Exception
*/
@Override
public Iterator<E> iterator(String queueName) throws Exception {
return this.getQueueByName(queueName).iterator();
}
@Override
public Iterator<E> iterator(String[] queueName) throws Exception {
// TODO Auto-generated method stub
return null;
}
}
| lewjeen/framework | unitecore-parent/unitecore/unitecore-tools/src/main/java/com/mocha/util/queue/ConcurrentLinkedQueueExtendsHandler.java | Java | unlicense | 11,926 |
/*
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.util.xmlparser;
import org.hyperic.util.StringUtil;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.File;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.xml.sax.EntityResolver;
/**
* The main entry point && bulk of XmlParser. The parsing routine
* takes an entry-point tag, which provides information about subtags,
* attributes it takes, etc. Tags can implement various interfaces
* to tell the parser to call back when certain conditions are met.
* This class takes the role of both a minimal validator as well as
* a traversal mechanism for building data objects out of XML.
*/
public class XmlParser {
private XmlParser(){}
private static void checkAttributes(Element elem, XmlTagHandler tag,
XmlFilterHandler filter)
throws XmlAttrException
{
boolean handlesAttrs = tag instanceof XmlAttrHandler;
XmlAttr[] attrs;
if(handlesAttrs)
attrs = ((XmlAttrHandler)tag).getAttributes();
else
attrs = new XmlAttr[0];
// Ensure out all the required && optional attributes
for(int i=0; i<attrs.length; i++){
Attribute a = null;
boolean found = false;
for(Iterator j=elem.getAttributes().iterator(); j.hasNext(); ){
a = (Attribute)j.next();
if(a.getName().equalsIgnoreCase(attrs[i].getName())){
found = true;
break;
}
}
if(!found && attrs[i].getType() == XmlAttr.REQUIRED){
throw new XmlRequiredAttrException(elem,
attrs[i].getName());
}
if(found && handlesAttrs){
String val;
val = filter.filterAttrValue(tag, a.getName(), a.getValue());
((XmlAttrHandler)tag).handleAttribute(i, val);
}
}
// Second loop to handle unknown attributes
for(Iterator i=elem.getAttributes().iterator(); i.hasNext(); ){
Attribute a = (Attribute)i.next();
boolean found = false;
for(int j=0; j<attrs.length; j++){
if(a.getName().equalsIgnoreCase(attrs[j].getName())){
found = true;
break;
}
}
if(found)
continue;
if(tag instanceof XmlUnAttrHandler){
XmlUnAttrHandler handler;
String val;
val = filter.filterAttrValue(tag, a.getName(), a.getValue());
handler = (XmlUnAttrHandler)tag;
handler.handleUnknownAttribute(a.getName(), val);
} else {
throw new XmlUnknownAttrException(elem, a.getName());
}
}
if(tag instanceof XmlEndAttrHandler){
((XmlEndAttrHandler)tag).endAttributes();
}
}
private static void checkSubNodes(Element elem, XmlTagHandler tag,
XmlFilterHandler filter)
throws XmlAttrException, XmlTagException
{
XmlTagInfo[] subTags = tag.getSubTags();
Map hash;
hash = new HashMap();
// First, count how many times each sub-tag is referenced
for(Iterator i=elem.getChildren().iterator(); i.hasNext(); ){
Element e = (Element)i.next();
String name;
Integer val;
name = e.getName().toLowerCase();
if((val = (Integer)hash.get(name)) == null){
val = new Integer(0);
}
val = new Integer(val.intValue() + 1);
hash.put(name, val);
}
for(int i=0; i<subTags.length; i++){
String name = subTags[i].getTag().getName().toLowerCase();
Integer iVal = (Integer)hash.get(name);
int threshold = 0, val;
val = iVal == null ? 0 : iVal.intValue();
switch(subTags[i].getType()){
case XmlTagInfo.REQUIRED:
if(val == 0){
throw new XmlMissingTagException(elem, name);
} else if(val != 1){
throw new XmlTooManyTagException(elem, name);
}
break;
case XmlTagInfo.OPTIONAL:
if(val > 1){
throw new XmlTooManyTagException(elem, name);
}
break;
case XmlTagInfo.ONE_OR_MORE:
threshold++;
case XmlTagInfo.ZERO_OR_MORE:
if(val < threshold){
throw new XmlMissingTagException(elem, name);
}
break;
}
hash.remove(name);
}
// Now check for excess sub-tags
if(hash.size() != 0){
Set keys = hash.keySet();
throw new XmlTooManyTagException(elem,
(String)keys.iterator().next());
}
// Recurse to all sub-tags
for(Iterator i=elem.getChildren().iterator(); i.hasNext(); ){
Element child = (Element)i.next();
for(int j=0; j<subTags.length; j++){
XmlTagHandler subTag = subTags[j].getTag();
String subName = subTag.getName();
if(child.getName().equalsIgnoreCase(subName)){
XmlParser.processNode(child, subTag, filter);
break;
}
}
}
}
private static void processNode(Element elem, XmlTagHandler tag,
XmlFilterHandler filter)
throws XmlAttrException, XmlTagException
{
if(tag instanceof XmlTagEntryHandler){
((XmlTagEntryHandler)tag).enter();
}
if(tag instanceof XmlFilterHandler){
filter = (XmlFilterHandler)tag;
}
XmlParser.checkAttributes(elem, tag, filter);
if(tag instanceof XmlTextHandler) {
((XmlTextHandler)tag).handleText(elem.getText());
}
XmlParser.checkSubNodes(elem, tag, filter);
if(tag instanceof XmlTagExitHandler){
((XmlTagExitHandler)tag).exit();
}
}
private static class DummyFilter
implements XmlFilterHandler
{
public String filterAttrValue(XmlTagHandler tag, String attrName,
String attrValue)
{
return attrValue;
}
}
/**
* Parse an input stream, otherwise the same as parsing a file
*/
public static void parse(InputStream is, XmlTagHandler tag)
throws XmlParseException
{
parse(is, tag, null);
}
public static void parse(InputStream is, XmlTagHandler tag,
EntityResolver resolver)
throws XmlParseException
{
SAXBuilder builder;
Document doc;
builder = new SAXBuilder();
if (resolver != null) {
builder.setEntityResolver(resolver);
}
try {
if (resolver != null) {
//WTF? seems relative entity URIs are allowed
//by certain xerces impls. but fully qualified
//file://... URLs trigger a NullPointerException
//in others. setting base here worksaround
doc = builder.build(is, "");
}
else {
doc = builder.build(is);
}
} catch(JDOMException exc){
XmlParseException toThrow = new XmlParseException(exc.getMessage());
toThrow.initCause(exc);
throw toThrow;
} catch (IOException exc) {
XmlParseException toThrow = new XmlParseException(exc.getMessage());
toThrow.initCause(exc);
throw toThrow;
}
generalParse(tag, doc);
}
/**
* Parse a file, which should have a root which is the associated tag.
*
* @param in File to parse
* @param tag Root tag which the parsed file should contain
*/
public static void parse(File in, XmlTagHandler tag)
throws XmlParseException
{
SAXBuilder builder;
Document doc;
builder = new SAXBuilder();
InputStream is = null;
//open the file ourselves. the builder(File)
//method escapes " " -> "%20" and bombs
try {
is = new FileInputStream(in);
doc = builder.build(is);
} catch (IOException exc) {
throw new XmlParseException(exc.getMessage());
} catch (JDOMException exc) {
throw new XmlParseException(exc.getMessage());
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {}
}
}
generalParse(tag, doc);
}
/** General parsing used by both parse methods above */
private static void generalParse(XmlTagHandler tag, Document doc)
throws XmlParseException
{
Element root = doc.getRootElement();
if(!root.getName().equalsIgnoreCase(tag.getName())){
throw new XmlParseException("Incorrect root tag. Expected <"+
tag.getName() + "> but got <" +
root.getName() + ">");
}
XmlParser.processNode(root, tag, new DummyFilter());
}
private static void dumpAttrs(XmlAttr[] attrs, String typeName,
int type, PrintStream out, int indent)
{
String printMsg;
boolean printed = false;
int lineBase, lineLen;
if(attrs.length == 0)
return;
lineLen = 0;
printMsg = "- Has " + typeName + " attributes: ";
lineBase = indent + printMsg.length();
// Required attributes
for(int i=0; i<attrs.length; i++){
String toPrint;
if(attrs[i].getType() != type)
continue;
if(!printed){
toPrint = StringUtil.repeatChars(' ', indent) +
"- Has " + typeName + " attributes: ";
out.print(toPrint);
lineLen = toPrint.length();
printed = true;
}
toPrint = attrs[i].getName() + ", ";
lineLen += toPrint.length();
out.print(toPrint);
if(lineLen > 70){
out.println();
out.print(StringUtil.repeatChars(' ', lineBase));
lineLen = lineBase;
}
}
if(printed)
out.println();
}
private static void dumpNode(XmlTagHandler tag, PrintStream out,
int indent)
throws XmlTagException
{
XmlTagInfo[] subTags = tag.getSubTags();
out.println(StringUtil.repeatChars(' ', indent) +
"Tag <" + tag.getName() + ">:");
if(tag instanceof XmlAttrHandler){
XmlAttr[] attrs;
attrs = ((XmlAttrHandler)tag).getAttributes();
if(attrs.length == 0)
out.println(StringUtil.repeatChars(' ', indent) +
"- has no required or optional attributes");
XmlParser.dumpAttrs(attrs, "REQUIRED", XmlAttr.REQUIRED,
out, indent);
XmlParser.dumpAttrs(attrs, "OPTIONAL", XmlAttr.OPTIONAL,
out, indent);
} else {
out.println(StringUtil.repeatChars(' ', indent) +
"- has no required or optional attributes");
}
if(tag instanceof XmlUnAttrHandler)
out.println(StringUtil.repeatChars(' ', indent) +
"- handles arbitrary attributes");
subTags = tag.getSubTags();
if(subTags.length == 0){
out.println(StringUtil.repeatChars(' ', indent) +
"- has no subtags");
} else {
for(int i=0; i<subTags.length; i++){
String name = subTags[i].getTag().getName();
int type = subTags[i].getType();
out.print(StringUtil.repeatChars(' ', indent) +
"- has subtag <" + name + ">, which ");
switch(type){
case XmlTagInfo.REQUIRED:
out.println("is REQUIRED");
break;
case XmlTagInfo.OPTIONAL:
out.println("is OPTIONAL");
break;
case XmlTagInfo.ONE_OR_MORE:
out.println("is REQUIRED at least ONCE");
break;
case XmlTagInfo.ZERO_OR_MORE:
out.println("can be specified any # of times");
break;
}
XmlParser.dumpNode(subTags[i].getTag(), out, indent + 4);
}
}
}
public static void dump(XmlTagHandler root, PrintStream out){
try {
XmlParser.dumpNode(root, out, 0);
} catch(XmlTagException exc){
out.println("Error traversing tags: " + exc.getMessage());
}
}
private static String bold(String text) {
return "<emphasis role=\"bold\">" + text + "</emphasis>";
}
private static String tag(String name) {
return bold("<" + name + ">");
}
private static String listitem(String name, String desc) {
String item =
"<listitem><para>" + name + "</para>";
if (desc != null) {
item += "<para>" + desc + "</para>";
}
return item;
}
private static void dumpAttrsWiki(XmlAttr[] attrs, String typeName,
int type, PrintStream out, int indent)
{
boolean printed = false;
if (attrs.length == 0) {
return;
}
// Required attributes
for (int i=0; i<attrs.length; i++) {
if (attrs[i].getType() != type) {
continue;
}
if (!printed) {
out.println(StringUtil.repeatChars('*', indent) +
" " + typeName + " attributes: ");
printed = true;
}
out.println(StringUtil.repeatChars('*', indent) +
" " + attrs[i].getName());
}
}
private static void dumpNodeWiki(XmlTagHandler tag, PrintStream out,
int indent)
throws XmlTagException
{
XmlTagInfo[] subTags = tag.getSubTags();
if (indent == 1) {
out.println(StringUtil.repeatChars('*', indent) +
" Tag *<" + tag.getName() + ">*: ");
}
if (tag instanceof XmlAttrHandler) {
XmlAttr[] attrs;
attrs = ((XmlAttrHandler)tag).getAttributes();
dumpAttrsWiki(attrs, "*REQUIRED*", XmlAttr.REQUIRED,
out, indent+1);
dumpAttrsWiki(attrs, "*OPTIONAL*", XmlAttr.OPTIONAL,
out, indent+1);
}
subTags = tag.getSubTags();
if (subTags.length != 0) {
for (int i=0; i<subTags.length; i++) {
String name = subTags[i].getTag().getName();
int type = subTags[i].getType();
String desc = "";
switch(type){
case XmlTagInfo.REQUIRED:
desc = "REQUIRED";
break;
case XmlTagInfo.OPTIONAL:
desc = "OPTIONAL";
break;
case XmlTagInfo.ONE_OR_MORE:
desc = "REQUIRED at least ONCE";
break;
case XmlTagInfo.ZERO_OR_MORE:
desc = "can be specified any # of times";
break;
}
out.println(StringUtil.repeatChars('*', indent+1) +
" Sub Tag *<" + name + ">* " + desc);
dumpNodeWiki(subTags[i].getTag(), out, indent+1);
}
}
}
public static void dumpWiki(XmlTagHandler root, PrintStream out){
try {
dumpNodeWiki(root, out, 1);
} catch(XmlTagException exc){
out.println("Error traversing tags: " + exc.getMessage());
}
}
}
| cc14514/hq6 | hq-util/src/main/java/org/hyperic/util/xmlparser/XmlParser.java | Java | unlicense | 18,165 |
/// <reference path="../typings/tsd.d.ts" />
import * as _ from 'lodash';
function hello(s: string) {
console.log(`hello, ${s}`);
}
hello('typescript');
function foo() {
}
_.each([12, "123"], (e) => console.log(e)); | cbjs/fe-learn | angular2/01-typescriptflow/src/hello.ts | TypeScript | unlicense | 220 |
# https://en.wikipedia.org/wiki/Treap
import random
import time
class Treap:
def __init__(self, key):
self.key = key
self.prio = random.randint(0, 1000000000)
self.size = 1
self.left = None
self.right = None
def update(self):
self.size = 1 + size(self.left) + size(self.right)
def size(treap):
return 0 if treap is None else treap.size
def split(root, minRight):
if root is None:
return None, None
if root.key >= minRight:
left, right = split(root.left, minRight)
root.left = right
root.update()
return left, root
else:
left, right = split(root.right, minRight)
root.right = left
root.update()
return root, right
def merge(left, right):
if left is None:
return right
if right is None:
return left
if left.prio > right.prio:
left.right = merge(left.right, right)
left.update()
return left
else:
right.left = merge(left, right.left)
right.update()
return right
def insert(root, key):
left, right = split(root, key)
return merge(merge(left, Treap(key)), right)
def remove(root, key):
left, right = split(root, key)
return merge(left, split(right, key + 1)[1])
def kth(root, k):
if k < size(root.left):
return kth(root.left, k)
elif k > size(root.left):
return kth(root.right, k - size(root.left) - 1)
return root.key
def print_treap(root):
def dfs_print(root):
if root is None:
return
dfs_print(root.left)
print(str(root.key) + ' ', end='')
dfs_print(root.right)
dfs_print(root)
print()
def test():
start = time.time()
treap = None
s = set()
for i in range(100000):
key = random.randint(0, 10000)
if random.randint(0, 1) == 0:
if key in s:
treap = remove(treap, key)
s.remove(key)
elif key not in s:
treap = insert(treap, key)
s.add(key)
assert len(s) == size(treap)
for i in range(size(treap)):
assert kth(treap, i) in s
print(time.time() - start)
test()
| indy256/codelibrary | python/treap_bst.py | Python | unlicense | 2,234 |
package android.support.v7.app;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.support.v7.b.b;
import android.view.KeyEvent;
import android.view.View;
public abstract class a
{
public android.support.v7.b.a a(b paramb)
{
return null;
}
public abstract View a();
public abstract void a(int paramInt);
public void a(Configuration paramConfiguration)
{
}
public abstract void a(Drawable paramDrawable);
public abstract void a(View paramView);
public abstract void a(CharSequence paramCharSequence);
public abstract void a(boolean paramBoolean);
public boolean a(int paramInt, KeyEvent paramKeyEvent)
{
return false;
}
public abstract int b();
public void b(CharSequence paramCharSequence)
{
}
public abstract void b(boolean paramBoolean);
public Context c()
{
return null;
}
public abstract void c(boolean paramBoolean);
public abstract void d(boolean paramBoolean);
public boolean d()
{
return false;
}
public void e(boolean paramBoolean)
{
}
public boolean e()
{
return false;
}
public void f(boolean paramBoolean)
{
}
public void g(boolean paramBoolean)
{
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: android.support.v7.app.a
* JD-Core Version: 0.6.0
*/ | clilystudio/NetBook | allsrc/android/support/v7/app/a(1).java | Java | unlicense | 1,431 |
package com.ximalaya.ting.android.opensdk.datatrasfer;
import com.google.gson.reflect.TypeToken;
import com.ximalaya.ting.android.opensdk.model.album.HotAggregation;
import java.util.List;
class CommonRequest$29$1 extends TypeToken<List<HotAggregation>>
{
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ximalaya.ting.android.opensdk.datatrasfer.CommonRequest.29.1
* JD-Core Version: 0.6.0
*/ | clilystudio/NetBook | allsrc/com/ximalaya/ting/android/opensdk/datatrasfer/CommonRequest$29$1.java | Java | unlicense | 465 |
/**
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2009-2010], VMware, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
*/
package org.hyperic.hq.livedata.server.session;
import org.hyperic.hq.livedata.shared.LiveDataCommand;
class LiveDataCacheKey {
private LiveDataCommand[] _commands;
public LiveDataCacheKey(LiveDataCommand[] cmds) {
_commands = cmds;
}
public LiveDataCommand[] getCommands() {
return _commands;
}
public boolean equals(Object o) {
if (!(o instanceof LiveDataCacheKey)) {
return false;
}
LiveDataCommand[] cmds = ((LiveDataCacheKey)o).getCommands();
for (int i = 0; i < cmds.length; i++) {
if (!(cmds[i].equals(_commands[i]))) {
return false;
}
}
return true;
}
public int hashCode() {
int result = 17;
for (int i = 0; i < _commands.length; i++) {
result = result*37 + _commands[i].hashCode();
}
return result;
}
}
| cc14514/hq6 | hq-server/src/main/java/org/hyperic/hq/livedata/server/session/LiveDataCacheKey.java | Java | unlicense | 2,028 |
<?php
App::uses('File', 'Utility');
class MinifyController extends CakeBootstrapAppController {
public $components = array(
'CakeBootstrap.AssetMinify',
'RequestHandler'
);
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array(
'css',
'js'
));
/*
if ($this->request->is('ajax')) {
$this->layout = 'CakeBootstrap.ajax';
}
*/
}
private function fileContents($path) {
if (is_file($path)) {
$file = new File($path);
$contents = $file->read();
$file->close();
return $contents;
}
return false;
}
public function css () {
$type = 'css';
$absolutePath = $this->AssetMinify->assetPath(
implode('/', $this->request->pass),
$type
);
if ( $absolutePath && (strtolower(pathinfo($absolutePath, PATHINFO_EXTENSION)) === $type) ) {
$contents = $this->fileContents($absolutePath);
if ($contents) {
$contents = ( strtolower(pathinfo($absolutePath, PATHINFO_EXTENSION)) === $type ? $this->AssetMinify->compress_css($contents) : $contents );
$this->response->body( $contents );
$this->response->type( strtolower(pathinfo($absolutePath, PATHINFO_EXTENSION)) );
return $this->response;
}
} elseif ( $absolutePath ) {
$this->response->file( $absolutePath );
return $this->response;
}
exit();
}
public function js () {
$type = 'js';
$absolutePath = $this->AssetMinify->assetPath(
implode('/', $this->request->pass),
$type
);
if ( $absolutePath && (strtolower(pathinfo($absolutePath, PATHINFO_EXTENSION)) === $type) ) {
$contents = $this->fileContents($absolutePath);
if ($contents) {
$contents = ( strtolower(pathinfo($absolutePath, PATHINFO_EXTENSION)) === $type ? $this->AssetMinify->compress_js($contents) : $contents );
$this->response->body( $contents );
$this->response->type( strtolower(pathinfo($absolutePath, PATHINFO_EXTENSION)) );
return $this->response;
}
} elseif ( $absolutePath ) {
$this->response->file( $absolutePath );
return $this->response;
}
exit();
}
}
| brutesque/CakeBootstrap | Controller/MinifyController.php | PHP | unlicense | 2,070 |
namespace Logger.Interfaces
{
using Enums;
public interface IAppender
{
int Count { get; }
ILayout Layout { get; }
ReportLevel ReportLevel { get; set; }
void Append(string timeStamp, string reportLevel, string message);
}
} | GoldenR1618/SoftUni-Exercises-and-Exams | 07.C#_OOP_Advanced/07.SOLID/EXERCISE/Logger/Interfaces/IAppender.cs | C# | unlicense | 286 |
/*
* ImgHeaderCallback.java
*
* Copyright 2001-2007 Goldin-Rudahl Associates
*
* Created by Sally Goldin, 5/16/2001
*
* $Id: ImgHeaderCallback.java,v 1.20 2007/01/05 07:41:57 rudahl Exp $
* $Log: ImgHeaderCallback.java,v $
* Revision 1.20 2007/01/05 07:41:57 rudahl
* added Whatis info
*
* Revision 1.19 2006/12/17 11:35:56 goldin
* fix formatting of reals
*
* Revision 1.18 2006/12/10 12:09:58 goldin
* Adding new menus and panels for revised geometry/geography
*
* Revision 1.17 2006/02/11 07:15:31 goldin
* Enable classnames tab even if no classnames yet
*
* Revision 1.16 2005/08/13 08:41:23 goldin
* Migrate fix in 5.6 regarding display type setting based on header
*
* Revision 1.15 2004/12/06 03:41:56 goldin
* Don't change display type for MEA if =M
*
* Revision 1.14 2002/09/11 23:34:20 goldin
* Call new statusmanager method to translate =R etc into a filename
*
* Revision 1.13 2002/07/25 23:06:18 goldin
* Make Source show up in HEA
*
* Revision 1.12 2002/05/29 17:52:24 goldin
* Add processing for calibration fields
*
* Revision 1.11 2002/03/06 17:48:12 goldin
* Enhance and extend use of ImgHeaderCallback to control display type
*
* Revision 1.10 2001/11/30 18:01:21 goldin
* Moved most of the UI basic components to the com.grs.gui package
*
* Revision 1.9 2001/11/16 16:41:07 goldin
* Move some files to common .gui package and adjust imports in dragon.ui pkg
*
* Revision 1.8 2001/11/09 17:52:05 goldin
* Set display type to color for =C or classified file
*
* Revision 1.7 2001/11/05 13:59:15 goldin
* Put UI code in a package
*
* Revision 1.6 2001/10/17 10:29:37 goldin
* Modify to use ApplicationManager to get error display, etc.
*
* Revision 1.5 2001/10/12 11:41:05 goldin
* New callbacks for HEA panel
*
* Revision 1.4 2001/07/31 17:40:38 goldin
* display correct range as part of message for out-of-range errors
*
* Revision 1.3 2001/07/25 11:53:05 goldin
* support nlines/npix in SUB
*
* Revision 1.2 2001/05/29 10:35:28 goldin
* Add tab disabling capability
*
* Revision 1.1 2001/05/16 15:43:16 goldin
* Implemen header-based callback
*
*/
package com.grs.dragon.ui;
import com.grs.gui.*;
import java.util.*;
import javax.swing.*;
import java.text.NumberFormat;
/**
* This class implements the Callback interface. It is used to populate
* fields depending on a panel, based on data in the header of the
* image file specified in the field that invokes the callback.
* @author goldin*/
public class ImgHeaderCallback extends HeaderCallback
{
/** Primary method of a callback class.
* Process sigFile if necessary, and set values in the
* appropriate combo box.
* @param field Field whose value will determine the
* effects of the callback.
*/
public void executeCallback(DragonField field)
{
DImageHeader thisHeader = null;
DragonField dispTypeField = null;
DragonPanel parent = field.getTopLevelPanel();
if (parent == null)
{
return;
}
DragonUI mainApp = DragonUI.currentApplication;
String value = field.getFieldValue();
if ((value == null) || (value.length() == 0))
return;
// determine if there is a current header and if so,
// if that is what the user requested
DImageHeader header = mainApp.getMemoryHeader();
if ((header != null) && (header.isInitialized()) &&
(value.equals("=M")))
{
thisHeader = header;
}
else if (value.equals("=C"))
{
dispTypeField = parent.getField("^DSP");
if (dispTypeField != null)
dispTypeField.setFieldValue("C");
return;
}
else
{
if (value.startsWith("="))
value =
DragonUI.currentApplication.getStatusManager().getMemoryFileEquivalent(value);
thisHeader = new DImageHeader(value);
if (!thisHeader.isInitialized())
{
UiErrorDisplay errDisp = (UiErrorDisplay)
ApplicationManager.getErrorDisplay();
errDisp.sendError(thisHeader.getErrorMessage());
return;
}
}
String parentID = parent.getName();
if (parentID.compareTo("rHEA")== 0)
{
processHeaFields(parent, thisHeader);
}
else if ((parentID.compareTo("rMEA")== 0) ||
(parentID.compareTo("rBUF")== 0))
{
processMeaFields(value, parent, thisHeader);
}
else if (parentID.compareTo("rSUB")== 0)
{
processSubFields(parent, thisHeader);
}
else
{
processDisplayType(parent,thisHeader);
}
}
/**
* Set fields in MEA panel based on header values.
*/
protected void processMeaFields(String value,
DragonPanel parent,
DImageHeader header)
{
NumberFormat nformat = NumberFormat.getInstance();
nformat.setMaximumFractionDigits(2);
DragonField units = parent.getField("^U");
if (units != null)
units.setFieldValue(header.getUnitname());
DragonField xcell = parent.getField("^XF");
if (xcell != null)
xcell.setFieldValue(nformat.format(header.getXcell_size()));
DragonField ycell = parent.getField("^YF");
if (ycell != null)
ycell.setFieldValue(nformat.format(header.getYcell_size()));
// we have already dealt with the display type for memory files
if (!value.startsWith("="))
processDisplayType(parent,header);
}
/** Set fields in HEA panel based on header values. */
protected void processHeaFields(DragonPanel parent,
DImageHeader header)
{
DragonField fld = parent.getField("^FXI");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getImg_x()));
fld = parent.getField("^FYI");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getImg_y()));
fld = parent.getField("^RFX");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getRef_x()));
fld = parent.getField("^RFY");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getRef_y()));
fld = parent.getField("^MU");
if (fld != null)
fld.setFieldValue(header.getUnitname());
fld = parent.getField("^CLX");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getXcell_size()));
fld = parent.getField("^CLY");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getYcell_size()));
fld = parent.getField("^ECUTIL");
if (fld != null)
fld.setFieldValue(header.getComment());
fld = parent.getField("^ESID");
if (fld != null)
fld.setFieldValue(header.getScene());
fld = parent.getField("^ESS");
if (fld != null)
fld.setFieldValue(header.getSubscene());
fld = parent.getField("^ECF");
if (fld != null)
fld.setFieldValue(header.getClf());
fld = parent.getField("^ESRC");
if (fld != null)
fld.setFieldValue(header.getSource());
fld = parent.getField("^EB");
if (fld != null)
fld.setFieldValue(header.getBand());
fld = parent.getField("^ET");
if (fld != null)
fld.setFieldValue(header.getFileType());
fld = parent.getField("^CALUNIT");
if (fld != null)
fld.setFieldValue(header.getZUnit());
fld = parent.getField("^CALMULT");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getZScale()));
fld = parent.getField("^CALOFF");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getZOffset()));
if (header.getFileType().compareTo("I") == 0)
{
parent.enableTab(1,false);
clearClassNames(parent,header);
}
else
{
parent.enableTab(1,true);
processClassNames(parent,header);
}
}
/**
* Set fields in SUB panel based on header values.
*/
protected void processSubFields(DragonPanel parent,
DImageHeader header)
{
boolean bEnable = false;
DragonField nlines = parent.getField("^NLS");
if (nlines != null)
nlines.setFieldValue(String.valueOf(header.getNLines()));
DragonField npix = parent.getField("^NPS");
if (npix != null)
npix.setFieldValue(String.valueOf(header.getNPix()));
if (header.getBitsPerPix() == 8)
{
bEnable = false;
}
else
{
bEnable = true;
}
DragonField fld = parent.getField("^SM");
if (fld != null)
fld.setEnabled(bEnable);
processDisplayType(parent,header);
}
/**
* If the panel has a "display" type option, set it
* to 'C' if the file is classified.
*/
protected void processDisplayType(DragonPanel parent,
DImageHeader header)
{
DragonField dispType = parent.getField("^DSP");
if (dispType == null)
return;
if (header.getFileType().startsWith("I"))
dispType.setFieldValue("G");
else if (header.getFileType().startsWith("C"))
dispType.setFieldValue("C");
else if (header.getFileType().startsWith("L"))
dispType.setFieldValue("C");
}
protected static String cvsInfo = null;
protected static void setCvsInfo()
{
cvsInfo = "\n@(#) $Id: ImgHeaderCallback.java,v 1.20 2007/01/05 07:41:57 rudahl Exp $ \n";
}
}
| patinyanudklin/git_testing | cpe-2015-projects/DragonCommon/javasrc/com/grs/dragon/ui/ImgHeaderCallback.java | Java | unlicense | 9,258 |
namespace Creuna.Basis.Revisited.Web.Business.UserHandling
{
public interface IUserAuthenticationHandler
{
bool Login(string username, string password, bool persistLogin);
void Logout();
}
} | Creuna-Oslo/Episerver.Basis.Slim | src/Template/Creuna.Basis.Revisited.Web/Business/UserHandling/IUserAuthenticationHandler.cs | C# | unlicense | 228 |
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Palla.Labs.Vdt.App.Infraestrutura.Mongo;
namespace Palla.Labs.Vdt.Controllers
{
public class VerificaSaudeController : ApiController
{
private readonly RepositorioEquipamentos _repositorioEquipamentos;
public VerificaSaudeController(RepositorioEquipamentos repositorioEquipamentos)
{
_repositorioEquipamentos = repositorioEquipamentos;
}
public HttpResponseMessage Get()
{
_repositorioEquipamentos.BuscarPorId(Guid.NewGuid(), Guid.NewGuid()); //Verifica se consigo chegar no banco de dados
return Request.CreateResponse(HttpStatusCode.OK, "Aparentemente está tudo ok...");
}
}
} | mfpalladino/palla.labs.vdt | Server/src/Palla.Labs.Vdt.WebApi/Controllers/VerificaSaudeController.cs | C# | unlicense | 773 |
import { Injectable } from '@angular/core';
@Injectable()
export class JsonReferenceService {
constructor() { }
dereference<T>(obj: any, $ref: string): T {
if(!$ref.startsWith('#/')) {
console.warn('Invalid $ref. Only references to current document supported.', $ref);
return null;
}
let parts = $ref.substr(2).split('/');
for(let i = 0; i < parts.length; i++) {
obj = obj[parts[i]];
if(obj === undefined) return null;
}
return <T>obj;
}
}
| gislikonrad/swangular-components | src/app/swangular-components/services/json-reference.service.ts | TypeScript | unlicense | 498 |
#include "HashMap.h"
#include <benchmark/benchmark.h>
#include <string>
#include <tr1/unordered_map>
#include <map>
#include <utility>
using namespace snippet::algo;
static const std::string gs_str_value = "0123456789";
template<typename T>
struct GetValue;
template<>
struct GetValue<int>
{
static int Get()
{
return 123456;
}
};
template<>
struct GetValue<std::string>
{
static const std::string& Get()
{
return gs_str_value;
}
};
template<typename T>
static void BM_HashMapInsert(benchmark::State& state)
{
HashMap<int, T> hash_map;
T value = GetValue<T>::Get();
while (state.KeepRunning())
{
for (int i = 0; i < state.range_x(); ++i)
{
hash_map.Insert(i, value);
}
}
}
template<typename T>
static void BM_StdMapInsert(benchmark::State& state)
{
std::map<int, T> std_map;
T value = GetValue<T>::Get();
while (state.KeepRunning())
{
for (int i = 0; i < state.range_x(); ++i)
{
std_map.insert(std::make_pair(i, value));
}
}
}
template<typename T>
static void BM_StdUnorderedMapInsert(benchmark::State& state)
{
std::tr1::unordered_map<int, T> std_map;
T value = GetValue<T>::Get();
while (state.KeepRunning())
{
for (int i = 0; i < state.range_x(); ++i)
{
std_map.insert(std::make_pair(i, value));
}
}
}
// Register the function as a benchmark
// BM for <int, int>
BENCHMARK_TEMPLATE(BM_HashMapInsert, int)->Range(8, 8<<10);
BENCHMARK_TEMPLATE(BM_StdMapInsert, int)->Range(8, 8<<10);
BENCHMARK_TEMPLATE(BM_StdUnorderedMapInsert, int)->Range(8, 8<<10);
BENCHMARK_TEMPLATE(BM_HashMapInsert, std::string)->Range(8, 8<<10);
BENCHMARK_TEMPLATE(BM_StdMapInsert, std::string)->Range(8, 8<<10);
BENCHMARK_TEMPLATE(BM_StdUnorderedMapInsert, std::string)->Range(8, 8<<10);
BENCHMARK_MAIN();
| airekans/Snippet | cpp/algo/benchmark/HashMapInsertBenchmark.cpp | C++ | unlicense | 1,906 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Ics.NHibernate")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5d58c7da-37a3-4a4a-98fe-cf76498361c2")]
| Slesa/Poseidon | old/src/1st/Persistence/Ics.NHibernate/Properties/AssemblyInfo.cs | C# | unlicense | 848 |
import fechbase
class Records(fechbase.RecordsBase):
def __init__(self):
fechbase.RecordsBase.__init__(self)
self.fields = [
{'name': 'FORM TYPE', 'number': '1'},
{'name': 'FILER FEC CMTE ID', 'number': '2'},
{'name': 'ENTITY TYPE', 'number': '3'},
{'name': 'NAME (Payee)', 'number': '4'},
{'name': 'STREET 1', 'number': '5'},
{'name': 'STREET 2', 'number': '6'},
{'name': 'CITY', 'number': '7'},
{'name': 'STATE', 'number': '8'},
{'name': 'ZIP', 'number': '9'},
{'name': 'TRANSDESC', 'number': '10'},
{'name': 'Of Expenditure', 'number': '11-'},
{'name': 'AMOUNT', 'number': '12'},
{'name': 'SUPPORT/OPPOSE', 'number': '13'},
{'name': 'S/O FEC CAN ID NUMBER', 'number': '14'},
{'name': 'S/O CAN/NAME', 'number': '15'},
{'name': 'S/O CAN/OFFICE', 'number': '16'},
{'name': 'S/O CAN/STATE', 'number': '17'},
{'name': 'S/O CAN/DIST', 'number': '18'},
{'name': 'FEC COMMITTEE ID NUMBER', 'number': '19'},
{'name': 'Unused field', 'number': '20'},
{'name': 'Unused field', 'number': '21'},
{'name': 'Unused field', 'number': '22'},
{'name': 'Unused field', 'number': '23'},
{'name': 'Unused field', 'number': '24'},
{'name': 'CONDUIT NAME', 'number': '25'},
{'name': 'CONDUIT STREET 1', 'number': '26'},
{'name': 'CONDUIT STREET 2', 'number': '27'},
{'name': 'CONDUIT CITY', 'number': '28'},
{'name': 'CONDUIT STATE', 'number': '29'},
{'name': 'CONDUIT ZIP', 'number': '30'},
{'name': 'AMENDED CD', 'number': '31'},
{'name': 'TRAN ID', 'number': '32'},
]
self.fields_names = self.hash_names(self.fields)
| h4ck3rm1k3/FEC-Field-Documentation | fec/version/v3/F57.py | Python | unlicense | 1,916 |
#!/usr/bin/env python
"""
Largest product in a grid
Problem 11
Published on 22 February 2002 at 06:00 pm [Server Time]
In the 20x20 grid below, four numbers along a diagonal line have been marked in red.
The product of these numbers is 26 * 63 * 78 * 14 = 1788696.
What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20x20 grid?
"""
THE_GRID = [[int(column) for column in row.split(' ')] for row in
"""
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
""".strip().split('\n')]
"""
A few words about the declaration of THE_GRID:
This is not the easiest thing to digest on first look. I think it is "pythonic"
in its implementation and it allows to copy/paste the grid straight out of the problem
statement without a bunch of mucking around to manually turn it into a 2d array
( or nested lists, actually ). It is arranged as a list of rows. Each row is a
list of numbers for each column in that row. Looking at it, the multi-line string
definition actually converts to a list of strings from the split operation. One
string for each row. The top list comprehension converts each row into a list of
short strings ( the columns ) which are also converted to int.
"""
#------------------------------------------------------------------------------
import operator
#------------------------------------------------------------------------------
def product(iterable):
return reduce(operator.mul, iterable, 1)
def solve(run_length):
height = len(THE_GRID)
width = len(THE_GRID[0])
for row in range(height-run_length+1):
for column in range(width-run_length+1):
for y_dir in (0, 1):
for x_dir in (0,1):
for i in range(run_length):
print THE_GRID[row+(y_dir*i)][column+x_dir*i]
def solve(run_length):
height = len(THE_GRID)
width = len(THE_GRID[0])
for row in range(height-run_length+1):
for column in range(width-run_length+1):
for i in range(run_length):
for y_dir in (0, 1):
for x_dir in (0,1):
print THE_GRID[row+(y_dir*i)][column+x_dir*i]
def solve(run_length):
height = len(THE_GRID)
width = len(THE_GRID[0])
highest = 0
for row in range(height-run_length+1):
for column in range(width-run_length+1):
for x_dir, y_dir in [(1, 0), (0, 1), (1, 1)]:
for i in range(run_length):
print THE_GRID[row+(y_dir*i)][column+x_dir*i]
def solve(run_length):
height = len(THE_GRID)
width = len(THE_GRID[0])
highest = 0
for row in range(height-run_length+1):
for column in range(width-run_length+1):
for x_dir, y_dir in [(1, 0), (0, 1), (1, 1)]:
run =[THE_GRID[row+(y_dir*i)][column+x_dir*i] for i in range(run_length)]
result = product(run)
print run, result
#if result > highest:
# highest = result
#return(highest)
#------------------------------------------------------------------------------
def solve():
g = THE_GRID
maxp = 0
rows, cols, path_size = len(g), len(g[0]), 5
for i in range(rows):
for j in range(cols - path_size + 1):
phv = max(product([g[i][j+s] for s in range(path_size)]),
product([g[j+s][i] for s in range(path_size)]))
#phv = max(g[i][j] * g[i][j+1] * g[i][j+2] * g[i][j+3],
# g[j][i] * g[j+1][i] * g[j+2][i] * g[j+3][i])
if i < rows - path_size:
pdd = max(product([g[i+s][j+s] for s in range(path_size)]),
product([g[i+s][j+path_size-s-1] for s in range(path_size)]))
#pdd = max(g[i][j] * g[i+1][j+1] * g[i+2][j+2] * g[i+3][j+3],
# g[i][j+3] * g[i+1][j+2] * g[i+2][j+1] * g[i+3][j])
maxp = max(maxp, phv, pdd)
return maxp
#------------------------------------------------------------------------------
def main():
print "PROBLEM:\n"
for line in __doc__.strip().split('\n'):
print '\t', line
print "\nSOLUTION:"
print "\n\t", solve()
#------------------------------------------------------------------------------
if __name__ == "__main__":
main() | slowkid/EulerProject | solutions/problem11.py | Python | unlicense | 5,822 |
#include <iostream>
#include <vector>
//merges two arrays
std::vector<int> merge(std::vector<int>& ar1,std::vector<int>& ar2,unsigned int& inv_count) {
unsigned int n=ar1.size();
unsigned int m=ar2.size();
std::vector<int> merged(n+m);
unsigned int a,b;
a=0;b=0;
for(unsigned int i=0;i<(n+m);++i) {
if(a==n) {
merged[i]=ar2[b];
b++;
} else if(b==m) {
merged[i]=ar1[a];
a++;
} else if(ar1[a]<=ar2[b]) {
merged[i]=ar1[a];
a++;
} else {
merged[i]=ar2[b];
inv_count+=n-a;
b++;
}
}
return merged;
}
std::vector<int> mergesort(std::vector<int>& arr,unsigned int& inv_count) {
unsigned int n=arr.size();
unsigned int n1,n2;
if(n==1) return arr;
else {
n1=n/2;
n2=n-n1;
std::vector<int> ar1(n1),ar2(n2);
for(unsigned int i=0;i<n1;++i) {
ar1[i]=arr[i];
}
for(unsigned int i=0;i<n2;++i) {
ar2[i]=arr[i+n1];
}
ar1=mergesort(ar1,inv_count);
ar2=mergesort(ar2,inv_count);
arr=merge(ar1,ar2,inv_count);
return arr;
}
}
int main() {
unsigned int n;
unsigned int n1,n2;
unsigned int inv_count=0;
std::cin >> n;
std::vector<int> org(n);
for(unsigned int i=0;i<n;++i) {
std::cin >> org[i];
}
org=mergesort(org,inv_count);
// for(auto &it: org) {
// std::cout << it << " ";
// }
// std::cout << std::endl;
std::cout << inv_count << std::endl;
return 0;
}
| lbovard/rosalind | algos/inv.cpp | C++ | unlicense | 1,432 |
// This is free and unencumbered software released into the public
// domain. For more information, see <http://unlicense.org> or the
// accompanying UNLICENSE file.
package navigator
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"github.com/nelsam/gxui"
"github.com/nelsam/gxui/math"
"github.com/nelsam/gxui/mixins"
"github.com/nelsam/gxui/themes/basic"
"github.com/nelsam/vidar/command/focus"
"github.com/nelsam/vidar/commander/bind"
)
var (
genericColor = gxui.Color{
R: 0.6,
G: 0.8,
B: 1,
A: 1,
}
nameColor = gxui.Color{
R: 0.6,
G: 1,
B: 0.5,
A: 1,
}
nonGoColor = gxui.Color{
R: 0.9,
G: 0.9,
B: 0.9,
A: 1,
}
errColor = gxui.Color{
R: 0.9,
G: 0.2,
B: 0,
A: 1,
}
skippableColor = gxui.Color{
R: 0.9,
G: 0.6,
B: 0.8,
A: 1,
}
// Since the const values aren't exported by go/build, I've just copied them
// from https://github.com/golang/go/blob/master/src/go/build/syslist.go
gooses = []string{
"android", "darwin", "dragonfly", "freebsd", "linux", "nacl", "netbsd", "openbsd", "plan9", "solaris", "windows",
}
goarches = []string{
"386", "amd64", "amd64p32", "arm", "armbe", "arm64", "arm64be", "ppc64", "ppc64le", "mips", "mipsle", "mips64",
"mips64le", "mips64p32", "mips64p32le", "ppc", "s390", "s390x", "sparc", "sparc64",
}
)
type Commander interface {
Bindable(name string) bind.Bindable
Execute(bind.Bindable)
}
type Opener interface {
For(...focus.Opt) bind.Bindable
}
type genericNode struct {
mixins.LinearLayout
driver gxui.Driver
theme gxui.Theme
button *treeButton
children gxui.LinearLayout
}
func newGenericNode(driver gxui.Driver, theme gxui.Theme, name string, color gxui.Color) *genericNode {
g := &genericNode{}
g.Init(g, driver, theme, name, color)
return g
}
func (n *genericNode) Init(outer mixins.LinearLayoutOuter, driver gxui.Driver, theme gxui.Theme, name string, color gxui.Color) {
n.LinearLayout.Init(outer, theme)
n.driver = driver
n.theme = theme
n.SetDirection(gxui.TopToBottom)
n.button = newTreeButton(driver, theme.(*basic.Theme), name)
n.button.Label().SetColor(color)
n.LinearLayout.AddChild(n.button)
n.children = theme.CreateLinearLayout()
n.children.SetDirection(gxui.TopToBottom)
n.children.SetMargin(math.Spacing{L: 10})
}
func (n *genericNode) AddChild(c gxui.Control) *gxui.Child {
child := n.children.AddChild(c)
if len(n.children.Children()) > 1 {
return child
}
n.button.SetExpandable(true)
n.button.OnClick(func(gxui.MouseEvent) {
if n.children.Attached() {
n.LinearLayout.RemoveChild(n.children)
n.button.Collapse()
return
}
n.LinearLayout.AddChild(n.children)
n.button.Expand()
})
return child
}
func (n *genericNode) MissingChild() gxui.Control {
if n.children.Attached() {
return nil
}
return n.children
}
type packageNode struct {
genericNode
cmdr Commander
consts, vars, types, funcs *genericNode
typeMap map[string]*Name
}
func newPackageNode(cmdr Commander, driver gxui.Driver, theme gxui.Theme, name string) *packageNode {
node := &packageNode{
cmdr: cmdr,
consts: newGenericNode(driver, theme, "constants", genericColor),
vars: newGenericNode(driver, theme, "vars", genericColor),
types: newGenericNode(driver, theme, "types", genericColor),
funcs: newGenericNode(driver, theme, "funcs", genericColor),
typeMap: make(map[string]*Name),
}
node.Init(node, driver, theme, name, skippableColor)
node.AddChild(node.consts)
node.AddChild(node.vars)
node.AddChild(node.types)
node.AddChild(node.funcs)
return node
}
func (p *packageNode) expand() {
p.consts.button.Click(gxui.MouseEvent{})
p.vars.button.Click(gxui.MouseEvent{})
p.types.button.Click(gxui.MouseEvent{})
p.funcs.button.Click(gxui.MouseEvent{})
}
func (p *packageNode) addConsts(consts ...*Name) {
for _, c := range consts {
p.consts.AddChild(c)
}
}
func (p *packageNode) addVars(vars ...*Name) {
for _, v := range vars {
p.vars.AddChild(v)
}
}
func (p *packageNode) addTypes(types ...*Name) {
for _, typ := range types {
// Since we can't guarantee that we parsed the type declaration before
// any method declarations, we have to check to see if the type already
// exists.
existingType, ok := p.typeMap[typ.button.Text()]
if !ok {
p.typeMap[typ.button.Text()] = typ
p.types.AddChild(typ)
continue
}
existingType.button.Label().SetColor(typ.button.Label().Color())
existingType.filepath = typ.filepath
existingType.position = typ.position
}
}
func (p *packageNode) addFuncs(funcs ...*Name) {
for _, f := range funcs {
p.funcs.AddChild(f)
}
}
func (p *packageNode) addMethod(typeName string, method *Name) {
typ, ok := p.typeMap[typeName]
if !ok {
typ = newName(p.cmdr, p.driver, p.theme, typeName, nameColor)
p.typeMap[typeName] = typ
p.types.AddChild(typ)
}
typ.AddChild(method)
}
type Location struct {
filepath string
position token.Position
}
func (l Location) File() string {
return l.filepath
}
func (l Location) Position() token.Position {
return l.position
}
type Name struct {
genericNode
Location
cmdr Commander
}
func newName(cmdr Commander, driver gxui.Driver, theme gxui.Theme, name string, color gxui.Color) *Name {
node := &Name{cmdr: cmdr}
node.Init(node, driver, theme, name, color)
node.button.OnClick(func(gxui.MouseEvent) {
cmd := node.cmdr.Bindable("focus-location").(Opener)
node.cmdr.Execute(cmd.For(focus.Path(node.File()), focus.Offset(node.Position().Offset)))
})
return node
}
type TOC struct {
mixins.LinearLayout
cmdr Commander
driver gxui.Driver
theme gxui.Theme
dir string
fileSet *token.FileSet
packageMap map[string]*packageNode
lock sync.Mutex
}
func NewTOC(cmdr Commander, driver gxui.Driver, theme gxui.Theme, dir string) *TOC {
toc := &TOC{
cmdr: cmdr,
driver: driver,
theme: theme,
dir: dir,
}
toc.Init(toc, theme)
toc.Reload()
return toc
}
func (t *TOC) Reload() {
t.lock.Lock()
defer t.lock.Unlock()
defer t.expandPackages()
t.fileSet = token.NewFileSet()
t.RemoveAll()
t.packageMap = make(map[string]*packageNode)
allFiles, err := ioutil.ReadDir(t.dir)
if err != nil {
log.Printf("Received error reading directory %s: %s", t.dir, err)
return
}
t.parseFiles(t.dir, allFiles...)
}
func (t *TOC) expandPackages() {
for _, c := range t.Children() {
pkg, ok := c.Control.(*packageNode)
if !ok {
continue
}
pkg.button.Click(gxui.MouseEvent{})
pkg.expand()
}
}
func (t *TOC) parseFiles(dir string, files ...os.FileInfo) {
filesNode := newGenericNode(t.driver, t.theme, "files", skippableColor)
t.AddChild(filesNode)
defer filesNode.button.Click(gxui.MouseEvent{})
for _, file := range files {
if file.IsDir() {
continue
}
fileNode := t.parseFile(dir, file)
fileNode.filepath = filepath.Join(dir, file.Name())
filesNode.AddChild(fileNode)
}
}
func (t *TOC) parseFile(dir string, file os.FileInfo) *Name {
if !strings.HasSuffix(file.Name(), ".go") {
return newName(t.cmdr, t.driver, t.theme, file.Name(), nonGoColor)
}
path := filepath.Join(dir, file.Name())
f, err := parser.ParseFile(t.fileSet, path, nil, parser.ParseComments)
if err != nil {
return newName(t.cmdr, t.driver, t.theme, file.Name(), errColor)
}
t.parseAstFile(path, f)
return newName(t.cmdr, t.driver, t.theme, file.Name(), nameColor)
}
func (t *TOC) parseAstFile(filepath string, file *ast.File) *packageNode {
buildTags := findBuildTags(filepath, file)
buildTagLine := strings.Join(buildTags, " ")
packageName := file.Name.String()
pkgNode, ok := t.packageMap[packageName]
if !ok {
pkgNode = newPackageNode(t.cmdr, t.driver, t.theme, packageName)
t.packageMap[pkgNode.button.Text()] = pkgNode
t.AddChild(pkgNode)
}
for _, decl := range file.Decls {
switch src := decl.(type) {
case *ast.GenDecl:
t.parseGenDecl(pkgNode, src, filepath, buildTagLine)
case *ast.FuncDecl:
if src.Name.String() == "init" {
// There can be multiple inits in the package, so this
// doesn't really help us in the TOC.
continue
}
text := src.Name.String()
if buildTagLine != "" {
text = fmt.Sprintf("%s (%s)", text, buildTagLine)
}
name := newName(t.cmdr, t.driver, t.theme, text, nameColor)
name.filepath = filepath
name.position = t.fileSet.Position(src.Pos())
if src.Recv == nil {
pkgNode.addFuncs(name)
continue
}
recvTyp := src.Recv.List[0].Type
if starExpr, ok := recvTyp.(*ast.StarExpr); ok {
recvTyp = starExpr.X
}
recvTypeName := recvTyp.(*ast.Ident).String()
pkgNode.addMethod(recvTypeName, name)
}
}
return pkgNode
}
func (t *TOC) parseGenDecl(pkgNode *packageNode, decl *ast.GenDecl, filepath, buildTags string) {
switch decl.Tok.String() {
case "const":
pkgNode.addConsts(t.valueNamesFrom(filepath, buildTags, decl.Specs)...)
case "var":
pkgNode.addVars(t.valueNamesFrom(filepath, buildTags, decl.Specs)...)
case "type":
// I have yet to see a case where a type declaration has len(Specs) != 0.
typeSpec := decl.Specs[0].(*ast.TypeSpec)
name := typeSpec.Name.String()
if buildTags != "" {
name = fmt.Sprintf("%s (%s)", name, buildTags)
}
typ := newName(t.cmdr, t.driver, t.theme, name, nameColor)
typ.filepath = filepath
typ.position = t.fileSet.Position(typeSpec.Pos())
pkgNode.addTypes(typ)
}
}
func (t *TOC) valueNamesFrom(filepath, buildTags string, specs []ast.Spec) (names []*Name) {
for _, spec := range specs {
valSpec, ok := spec.(*ast.ValueSpec)
if !ok {
continue
}
for _, name := range valSpec.Names {
if name.String() == "_" {
// _ can be redeclared multiple times, so providing access to
// it in the TOC isn't that useful.
continue
}
n := name.String()
if buildTags != "" {
n = fmt.Sprintf("%s (%s)", n, buildTags)
}
node := newName(t.cmdr, t.driver, t.theme, n, nameColor)
node.filepath = filepath
node.position = t.fileSet.Position(name.Pos())
names = append(names, node)
}
}
return names
}
func findBuildTags(filename string, file *ast.File) (tags []string) {
fileTag := parseFileTag(filename)
if fileTag != "" {
tags = append(tags, fileTag)
}
for _, commentBlock := range file.Comments {
if commentBlock.End() >= file.Package-1 {
// A build tag comment *must* have an empty line between it
// and the `package` declaration.
continue
}
for _, comment := range commentBlock.List {
newTags := parseTag(comment)
tags = applyTags(newTags, tags)
}
}
return tags
}
func applyTags(newTags, prevTags []string) (combinedTags []string) {
if len(prevTags) == 0 {
return newTags
}
if len(newTags) == 0 {
return prevTags
}
for _, newTag := range newTags {
for _, prevTag := range prevTags {
combinedTags = append(combinedTags, prevTag+","+newTag)
}
}
return
}
func parseFileTag(filename string) (fileTag string) {
filename = strings.TrimSuffix(filename, ".go")
filename = strings.TrimSuffix(filename, "_test")
var goarch, goos string
for _, arch := range goarches {
archSuffix := "_" + arch
if strings.HasSuffix(filename, archSuffix) {
goarch = arch
filename = strings.TrimSuffix(filename, archSuffix)
break
}
}
for _, os := range gooses {
osSuffix := "_" + os
if strings.HasSuffix(filename, osSuffix) {
goos = os
filename = strings.TrimSuffix(filename, osSuffix)
break
}
}
if goos != "" {
fileTag += goos
}
if goarch != "" {
if fileTag != "" {
fileTag += ","
}
fileTag += goarch
}
return fileTag
}
func parseTag(commentLine *ast.Comment) []string {
comment := commentLine.Text
if !strings.HasPrefix(comment, "// +build ") {
return nil
}
tags := strings.TrimPrefix(comment, "// +build ")
return strings.Split(tags, " ")
}
| nelsam/gxui_playground | navigator/toc_tree.go | GO | unlicense | 11,823 |
"""
Your job is to write a function which increments a string, to create a new string. If the string already ends with a number, the number should be incremented by 1. If the string does not end with a number the number 1 should be appended to the new string.
Examples:
foo -> foo1
foobar23 -> foobar24
foo0042 -> foo0043
foo9 -> foo10
foo099 -> foo100
Attention: If the number has leading zeros the amount of digits should be considered.
"""
import re
def increment_string(strng):
match = re.match(r"(.*?)(\d*)$",strng)
string = match.group(1)
number = match.group(2)
if not number:
return string + '1'
else:
return string + str(int(number)+1).zfill(len(number))
| aadithpm/code-a-day | py/String Incrementer.py | Python | unlicense | 744 |
namespace Persistence.Csv
{
/// <summary>
/// Only properties decorated with this attribute will be exported to CSV file.
/// </summary>
public class FieldAttribute : CsvAttribute
{
#region Fields
/// <summary>
/// Gets the column order of the resulting CSV line exported.
/// </summary>
/// <value>
/// The order.
/// </value>
public ushort Order { get; private set; }
/// <summary>
/// Gets the (optional) description of the field.
/// </summary>
/// <value>
/// The description.
/// </value>
public string Description { get; private set; }
#endregion
#region Constructors
public FieldAttribute(ushort order, string description = null)
{
Order = order;
Description = description;
}
#endregion
}
} | jesuswasrasta/CsvRepository | Persistence.Csv/FieldAttribute.cs | C# | unlicense | 778 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import controller.GestorLocalidad;
import java.util.ArrayList;
import org.w3c.dom.Document;
/**
*
* @author soriagal
*/
public class ManejadorUbicar {
private WebUbicar webUbicar;
private GestorLocalidad gestorLocalidad = new GestorLocalidad();
private ArrayList idLocalidades;
private ArrayList documents; //object: document con el xml
private ArrayList localidades = new ArrayList(); //object: objeto localidad
public void pedirUbicacion () {
idLocalidades = gestorLocalidad.getLocalidades();
webUbicar = new WebUbicar();
documents = webUbicar.getDocuments(idLocalidades);
for (int i=0; i<documents.size(); i++) {
Localidad localidad;
LectorUbicacionXml lector = new LectorUbicacionXml((Document) documents.get(i));
localidad = lector.getLocalidad();
localidades.add(localidad);
}
}
public void guardarUbicacion () {
for (int i=0; i<localidades.size(); i++) {
Localidad localidad = (Localidad) localidades.get(i);
gestorLocalidad.guardarUbicacion(localidad);
}
}
}
| facundofarias/iBee | Source/WeatherService/src/model/ManejadorUbicar.java | Java | unlicense | 1,255 |
package com.stech.meetat.service;
public interface SchedulerService {
}
| vijayvelpula/MeetAt | src/main/java/com/stech/meetat/service/SchedulerService.java | Java | unlicense | 74 |
namespace SiteAccess.Model
{
// Bets for pinnacle
public enum OddsFormat
{
American,
Decimal,
Hongkong,
Indonesian,
Malay
}
public enum WinRiskType
{
Win,
Risk
}
public enum BetType
{
Moneyline,
TeamTotalPoints,
Spread,
TotalPoints,
Special
}
public enum TeamType
{
Draw,
Team1,
Team2
}
public enum SideType
{
Over,
Under
}
} | bbenetskyy/WinParse | WinParse/SiteAccess/Model/PinnacleEnums.cs | C# | unlicense | 573 |
import _ from 'lodash';
import React from 'react';
import Reflux from 'reflux';
import { Navigation } from 'react-router';
import recipeActions from 'actions/recipe';
import recipeStore from 'stores/recipe';
import SapCalculator from 'components/sapCalculator';
import FormSaveRecipe from 'components/formSaveRecipe';
import Imageable from 'components/imageable';
import ImageableEdit from 'components/imageableEdit';
export default React.createClass( {
statics: {
willTransitionTo: function ( transition, params ) {
recipeActions.getRecipeById( params.id );
}
},
mixins: [
Navigation,
Reflux.connect( recipeStore, 'recipe' )
],
render() {
document.title = 'Soapee - Edit';
return (
<div id="recipe-edit">
<SapCalculator
recipe={ this.state.recipe }
/>
{ _.get(this.state, 'recipe.recipe.images.length' ) > 0 &&
<div className="row">
<div className="col-md-12">
<legend>Delete Photos?</legend>
<ImageableEdit
images={ this.state.recipe.recipe.images }
/>
</div>
</div>
}
{ this.state.recipe.countWeights() > 0 &&
<div className="row">
<FormSaveRecipe
recipe={ this.state.recipe }
buttonCancel={ true }
buttonCaptionSave={ this.saveCaption() }
buttonDisabledSave={ this.state.saving }
onSave={ this.saveRecipe }
onSaveAs={ this.saveAsRecipe }
onCancel={ this.goBackToView }
/>
</div>
}
</div>
);
},
startImageUploadHookFn( fnToStartUploads ) {
this.startUploads = fnToStartUploads;
},
saveCaption() {
return this.state.saving ? 'Saving Recipe' : 'Save Recipe';
},
saveRecipe() {
return this.doSaveAction( recipeActions.updateRecipe );
},
saveAsRecipe() {
return this.doSaveAction( recipeActions.createRecipe );
},
doSaveAction( action ) {
this.setState( {
saving: true
} );
recipeStore.calculate();
return action( this.state.recipe )
.then( this.toRecipeView.bind( this ) )
.finally(() => this.setState({
saving: false
}));
function uploadImages() {
this.startUploads( this.state.recipe.getModelValue( 'id' ) );
}
},
printRecipe() {
this.replaceWith( 'printRecipe', { id: this.state.recipe.getModelValue( 'id' ) } );
},
goBackToView() {
this.toRecipeView( this.state.recipe.recipe );
},
toRecipeView(recipe) {
this.transitionTo( 'recipe', { id: recipe.id} );
}
} ); | nazar/soapee-ui | src/app/views/recipeEdit.js | JavaScript | unlicense | 3,163 |
from ..parsers.errors import ErrorResponse
from warnings import warn
def raise_for_error(f):
"""
Wrapper method to parse any error response and raise the ErrorResponse instance if an error is encountered.
:param f:
:return:
"""
def inner(*args, **kwargs):
warn('`raise_for_error` is deprecated and will not process any response content.')
return f(*args, **kwargs)
# e = ErrorResponse.load(content)
# e.raise_for_error()
# return content
return inner
def raise_response_for_error(f):
"""
Wrapper method to parse a response object and raise the ErrorResponse
instance if an error is encountered in the response body.
:param f:
:return:
"""
def inner(*args, **kwargs):
warn('`raise_response_for_error` is deprecated and will not process any response content.')
return f(*args, **kwargs)
return inner
| ziplokk1/python-amazon-mws-tools | mwstools/requesters/base.py | Python | unlicense | 920 |
/*
* SmartGWT Mobile
* Copyright 2008 and beyond, Isomorphic Software, Inc.
*
* SmartGWT Mobile is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3
* as published by the Free Software Foundation. SmartGWT Mobile is also
* available under typical commercial license terms - see
* http://smartclient.com/license
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package com.smartgwt.mobile.client.widgets.toolbar;
import com.smartgwt.mobile.client.widgets.BaseButton;
/**
* This class represents a button that is placed on the {@link ToolStrip}.
* It can either be a back / forward button, or an action button.
*
* @see com.smartgwt.mobile.client.widgets.toolbar.ToolStrip#addButton(ToolStripButton)
*/
public class ToolStripButton extends BaseButton {
private ButtonType buttonType = ButtonType.BORDERED;
private boolean inheritTint;
public ToolStripButton() {
internalSetButtonType(buttonType);
}
public ToolStripButton(String title) {
this();
setTitle(title);
}
public ToolStripButton(String title, ButtonType buttonType) {
this(title);
internalSetButtonType(buttonType);
}
public final ButtonType getButtonType() {
return buttonType;
}
private void internalSetButtonType(ButtonType buttonType) {
if (this.buttonType != null) {
getElement().removeClassName(this.buttonType._getClassNames());
}
this.buttonType = buttonType;
if (buttonType != null) {
getElement().addClassName(buttonType._getClassNames());
}
}
public void setButtonType(ButtonType buttonType) {
internalSetButtonType(buttonType);
}
public final boolean isInheritTint() {
return inheritTint;
}
public void setInheritTint(boolean inheritTint) {
this.inheritTint = inheritTint;
if(inheritTint) {
getElement().addClassName(_CSS.customTintedButtonClass());
} else {
getElement().removeClassName(_CSS.customTintedButtonClass());
}
}
}
| will-gilbert/SmartGWT-Mobile | mobile/src/main/java/com/smartgwt/mobile/client/widgets/toolbar/ToolStripButton.java | Java | unlicense | 2,366 |
package fr.mvanbesien.projecteuler.from001to020;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
public class Problem015 implements Callable<Long> {
public static void main(String[] args) throws Exception {
long nanotime = System.nanoTime();
System.out.println("Answer is " + new Problem015().call());
System.out.println(String.format("Executed in %d µs", (System.nanoTime() - nanotime) / 1000));
}
@Override
public Long call() throws Exception {
List<Long> list = new ArrayList<>();
list.add(1L);
list.add(1L);
for (int i = 1; i < 40; i++) {
List<Long> list2 = new ArrayList<>();
list2.add(1L);
for (int j = 0; j < list.size() - 1; j++) {
list2.add(list.get(j) + list.get(j + 1));
}
list2.add(1L);
list = list2;
}
return list.get(list.size() / 2);
}
}
| mvanbesien/projecteuler | fr.mvanbesien.projecteuler/src/main/java/fr/mvanbesien/projecteuler/from001to020/Problem015.java | Java | unlicense | 846 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package consolefps.views;
import consolefps.models.elements.Elements;
/**
*
* @author krilivye
*/
public interface IAffichage {
public String afficher(Elements element);
}
| BTS-SIO2-2013/ZombieKiller | src/consolefps/views/IAffichage.java | Java | unlicense | 280 |
package bronz.accounting.bunk.ui.model;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.table.AbstractTableModel;
import bronz.accounting.bunk.ui.panel.CalendarPanel;
import bronz.utilities.custom.CustomCalendar;
import bronz.utilities.general.DateUtil;
public class CalendarTableModel extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
private final CalendarPanel panel;
private final Calendar startDate;
private Object[][] data;
private String[] columnNames = { "", "", "", "", "", "", "" };
public CalendarTableModel( final CalendarPanel panel ,
final Calendar startDate )
{
this.panel = panel;
this.startDate = startDate;
this.data = new Object[ 7 ][ 7 ];
loadDates();
}
private void loadDates()
{
this.data[ 0 ][ 0 ] = "SUN";
this.data[ 0 ][ 1 ] = "MON";
this.data[ 0 ][ 2 ] = "TUE";
this.data[ 0 ][ 3 ] = "WED";
this.data[ 0 ][ 4 ] = "THU";
this.data[ 0 ][ 5 ] = "FRI";
this.data[ 0 ][ 6 ] = "SAT";
int a = DateUtil.getNoOfDayInMonth( (GregorianCalendar) startDate);
startDate.set( Calendar.DATE, 1 );
int day = startDate.get( Calendar.DAY_OF_WEEK );
day--;
int x = 0;
int y = 0;
for ( int i = 0; i < 42; i++)
{
if( i%7 == 0)
{
x++;
y = 0;
}
if( (i >= day) && i < ( a + day ) )
{
this.data[ x ][ y ] = (i - day)+ 1;
}
y++;
}
}
public int getColumnCount()
{
return columnNames.length;
}
public int getRowCount()
{
return data.length;
}
public String getColumnName(int col)
{
return columnNames[ col ];
}
public Object getValueAt(int row, int col)
{
return data[ row ][ col ];
}
public boolean isCellEditable(int row, int col)
{
if ( this.data[ row ][ col ] instanceof Integer )
{
final int selectedDate = (Integer) this.data[ row ][ col ];
final Calendar selectedCalendar = new CustomCalendar();
selectedCalendar.set( Calendar.DATE , selectedDate );
return panel.setSelectedDate( selectedCalendar );
}
else
{
return false;
}
}
public void setValueAt( final Object value, final int row, final int col)
{
}
}
| robbinmathew/centbunk | java/BunkAccountingApplication/BunkAccountingSwingApp/src/main/java/bronz/accounting/bunk/ui/model/CalendarTableModel.java | Java | unlicense | 2,231 |
var AppGlobal = {
exposePrivateVariablesForTesting: true
};
var testableObject = function (exposePrivateVariablesForTesting) {
var _privateVar = "can't see this";
var _publicVar = "we see this fine";
function _privateFunction() {
console.log("Executed Private");
}
function _exposedFunction() {
console.log("Exposed Function");
}
var returnValue = {
ExposedFunction: _exposedFunction,
ExposedVariable: _publicVar
};
if (exposePrivateVariablesForTesting) {
$.extend(returnValue, {
PrivateVar: _privateVar,
PrivateFunction: _privateFunction
});
}
return returnValue;
}(AppGlobal.exposePrivateVariablesForTesting);
testableObject.ExposedFunction();
console.log(testableObject.ExposedVariable);
testableObject.PrivateFunction();
console.log(testableObject.PrivateVar);
| Grax32/JurassicPlayground | JurassicPlayground/Scripts/RevealingModuleVariant.js | JavaScript | unlicense | 898 |
#!/usr/bin/env python
# -.- coding: utf-8 -.-y
import random
import socket
import os
import time
import threading
import Queue
import sys
import argparse
from multiprocessing import Process
print """\33[91m
═════════════════════════════════════════════════════════
███████ ██████ ███████
█ █ █ █ ║
█ █════╗ █ ╔═█ ║
█═════════════█ ╚█ ║█═══╝
█ ██████ ║█
█ █ █ ╚╗█ ╔═══════Server
█════════╗ █ █ ╚═█ ║
███████ ║ █ █ ███████
Chat Room Client════════╝
═════════════════════════════════════════════════════════
\33[92m"""
quit = Queue.Queue()
path = os.path.realpath(__file__)
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--screen", help="This is used by the script to make a screen. Not necessarily needed for regular users.")
args = parser.parse_args()
def outputscreen(messages, online):
rows, columns = os.popen('stty size', 'r').read().split()
rows = int(rows)
rows = rows - 1
columns = int(columns)
if len(messages) > rows:
messages = messages[len(messages) - rows:]
print messages
else:
pass
if len(online) > rows:
online = online[len(online) - rows:]
print online
else:
pass
output = []
for line in range(rows):
output.append(["", ""])
tick = 0
for message in messages:
output[tick][0] = message
tick = tick + 1
print tick
if len(output) <= len(online):
print "less or equal output then online"
for l in range(len(online) - len(output)):
output.append(["", ""])
print output
#for num in range(len(online)):
tick = 0
print output
for user in online:
output[tick][1] = user
tick = tick + 1
print output
else:
print "more output then online"
print rows
#for num in range(len(output)):
tick = 0
for user in online:
output[tick][1] = user
tick = tick + 1
for line in output:
space = int(columns)
outleng = len(line[0]) + len(line[1])
space = space - outleng
print line[0] + " "*space + line[1]
if args.screen:
sp = args.screen
sp = sp.split(":")
user = sp[2]
port = int(sp[1])
server = sp[0]
global cv
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (server, port)
sock.connect(server_address)
sock.send("screen:")
#print "\33[96m Type /stop to quit\33[91m"
quit = False
messages = []
import ast
online = sock.recv(1024)
online = ast.literal_eval(online)
tmp = online
while quit == False:
servercom = sock.recv(1024)
#print servercom
if servercom == "quitting:":
quit.put("1")
quit = True
os._exit(0)
elif "online:" in servercom:
online = ast.literal_eval(servercom[7:])
if tmp != online:
for line in tmp:
if line not in online:
messages.append(line + " has left the server...")
else:
pass
for line in online:
if line not in tmp:
messages.append(line + " has joined the server...")
else:
pass
else:
pass
if user not in online:
quit = True
sock.send("quitting:")
os._exit(0)
else:
sock.send("good:")
tmp = online
outputscreen(messages, online)
else:
messages.append(servercom)
outputscreen(messages, online)
time.sleep(.01)
if servercom == "ping":
sock.send("ping:pong")
else:
pass
else:
pass
cv = "1.0"
username = raw_input("Name:")
server = raw_input("Server IP[127.0.0.1]:")
port = raw_input("Server Port[22550]:")
if port == "":
port = "22550"
else:
pass
if server == "":
server = "127.0.0.1"
else:
pass
print port
class connect(object):
def __init__(self, server, port, username, quit):
self.quit = quit
self.server = server
self.port = port
self.username = username
self.con()
def con(self):
#try:
global cv
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (self.server, int(self.port))
self.sock.connect(server_address)
self.sock.settimeout(60)
self.sock.send("cv:" + cv)
compatible = self.sock.recv(1024)
if compatible == "comp:1":
pass
else:
print """\33[91m
***************************************************
Error Server is on version """ + compatible[7:] + """
***************************************************
"""
sys.exit()
self.sock.send("user:" + self.username)
nc = self.sock.recv(1024)
if "error:" in nc:
print """\33[91m
***************************************************
Error while sending username:
""" + nc[6:] + """
***************************************************
"""
os._exit(0)
#threading.Thread(target = self.ping, args=()).start()
#threading.Thread(target = self.screen, args=()).start()
#self.screen.start()
quit = False
while quit == False:
#inp = raw_input(">>")
#time.sleep(.2)
send = str(random.randint(0, 9))
self.sock.send(send)
print send
'''if inp == "/quit":
quit = True
self.quit.put("1")
self.sock.send("quitting:")
elif "" == inp:
"""\33[91m
***************************************************
Error no message entered
***************************************************
"""
elif "/help" == inp:
"""\33[91m
***************************************************
Error no help menu implemented yet
***************************************************
"""
else:
self.sock.send("mesg:" + inp)'''
else:
os._exit(0)
'''except:
print """\33[91m
***************************************************
Error while initiating connecting with server
***************************************************
"""
sys.exit()'''
def ping(self):
while True:
self.sock.send("ping:")
time.sleep(1)
#def screen(self):
global path
os.system("xterm -hold -e python " + "./ChatRoom1.0Client.py" + " -s " + self.server + ":" + self.port + ":" + self.username)
self.qt = True
self.quit.put("1")
def quitcheck(quit):
while True:
time.sleep(1)
if quit.empty() == True:
pass
else:
os._exit(0)
threading.Thread(target = quitcheck, args=(quit,)).start()
threading.Thread(target=connect, args=(server, port, username, quit)).start()
| YodaBytePrograming/ChatRoom | ChatRoom 1.0/ChatRoom1.0Doser.py | Python | unlicense | 8,273 |
package discord.jar;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class EmbedBuilder {
private String title;
private String type;
private String description;
private String url;
private Color color;
private Embed.EmbedFooter footer;
private Embed.EmbedImage image;
private Embed.EmbedImage thumbnail;
private Embed.EmbedMedia video;
private Embed.EmbedProvider provider;
private Embed.EmbedAuthor author;
private List<Embed.EmbedField> fields = new ArrayList<>();
public EmbedBuilder withTitle(String title) {
this.title = title;
return this;
}
public EmbedBuilder withType(String type) {
this.type = type;
return this;
}
public EmbedBuilder withDescription(String description) {
this.description = description;
return this;
}
public EmbedBuilder withUrl(String url) {
this.url = url;
return this;
}
public EmbedBuilder withColor(Color color) {
this.color = color;
return this;
}
public EmbedBuilder withFooter(Embed.EmbedFooter footer) {
this.footer = footer;
return this;
}
public EmbedBuilder withFooter(String text, String iconUrl) {
this.footer = new Embed.EmbedFooter(text, iconUrl, null);
return this;
}
public EmbedBuilder withImage(Embed.EmbedImage image) {
this.image = image;
return this;
}
public EmbedBuilder withImage(String url) {
this.image = new Embed.EmbedImage(url, null, -1, -1);
return this;
}
public EmbedBuilder withThumbnail(Embed.EmbedImage thumbnail) {
this.thumbnail = thumbnail;
return this;
}
public EmbedBuilder withThumbnail(String url) {
this.thumbnail = new Embed.EmbedImage(url, null, -1, -1);
return this;
}
public EmbedBuilder withVideo(Embed.EmbedMedia video) {
this.video = video;
return this;
}
public EmbedBuilder withVideo(String url) {
this.video = new Embed.EmbedMedia(url, -1, -1);
return this;
}
public EmbedBuilder withProvider(Embed.EmbedProvider provider) {
this.provider = provider;
return this;
}
public EmbedBuilder withProvider(String name, String url) {
this.provider = new Embed.EmbedProvider(name, url);
return this;
}
public EmbedBuilder withAuthor(Embed.EmbedAuthor author) {
this.author = author;
return this;
}
public EmbedBuilder withAuthor(String name, String url, String iconUrl) {
this.author = new Embed.EmbedAuthor(name, url, iconUrl, null);
return this;
}
public EmbedBuilder appendField(Embed.EmbedField field) {
this.fields.add(field);
return this;
}
public EmbedBuilder appendField(String name, String value, boolean inline) {
this.fields.add(new Embed.EmbedField(name, value, inline));
return this;
}
public Embed build() {
return new Embed(title, type, description, url, color, footer, image, thumbnail, video, provider, author, fields.toArray(new Embed.EmbedField[0]));
}
}
| discord-java/discord.jar | src/main/java/discord/jar/EmbedBuilder.java | Java | unlicense | 3,220 |
#include "version.h"
#include <boost/filesystem/operations.hpp>
#include <iostream>
#define PCRE2_CODE_UNIT_WIDTH 8
#include <pcre2.h>
#include "file.h"
#include "options.h"
#include "parser.h"
using namespace boost::filesystem;
using namespace std;
int errorcode;
PCRE2_SIZE erroffset;
inline unsigned int match(Parser* parser, Options* options) {
static const string color_filename {"\x1B[34;1m\x1B[K"}; // 32=blue, 1=bold
static const string color_match {"\x1B[31;1m\x1B[K"}; // 31=red, 1=bold
static const string color_lineno {"\x1B[32;1m\x1B[K"}; // 33=green, 1=bold
static const string color_normal {"\x1B[0m\x1B[K"}; // Reset/normal (all attributes off).
PCRE2_SIZE *ovector;
auto tmp = strndupa(parser->recordBegin(), parser->recordLength());
auto printLine = false;
for(auto const& linePattern: options->linePatterns()) {
pcre2_match_data *match_data = pcre2_match_data_create_from_pattern(linePattern, nullptr);
auto rc = 0;
while ((strlen(tmp) > 0) && ((rc = pcre2_jit_match(linePattern, reinterpret_cast<PCRE2_SPTR>(tmp), strlen(tmp), 0, 0, match_data, nullptr)) > 0)) {
if (!printLine && options->fileName()) {
cerr << color_filename;
cout << parser->fileName() << ":";
cerr << color_normal;
}
if (!printLine && options->lineNumber()) {
cerr << color_lineno;
cout << parser->recordNumber() << ":";
cerr << color_normal;
}
printLine = true;
ovector = pcre2_get_ovector_pointer(match_data);
for (int i = 0; i < rc; i++) {
cout << string(tmp, ovector[2 * i]);
cerr << color_match;
cout << string(tmp + ovector[2 * i], ovector[2 * i + 1] - ovector[2 * i]);
cerr << color_normal;
tmp = tmp + ovector[2 * i + 1];
}
}
pcre2_match_data_free(match_data);
}
if (printLine) {
cout << tmp << endl;
return 1;
}
return 0;
}
int main(int argc, const char **argv)
{
Options options;
try {
options.run(argc, argv);
}
catch (exception &e) {
cerr << e.what() << endl;
return 2;
}
if (options.version()) {
cout << "techlog "<< VERSION_MAJOR << "." << VERSION_MINOR << endl;
cout << LICENSE << endl;
cout << WRITTENBY << endl;
return 1;
}
if (options.linePatterns().empty() && options.propertyPatterns().empty() && options.events().empty()) {
cout << "usage: techlog [-ifl] [-s num] [-p pattern] [--event] [--property=pattern] [pattern]" << endl;
if (!options.help() && !options.helpEvents()) {
return 1;
}
}
if (options.help()) {
cout << options.visibleOptions() << endl;
return 1;
}
if (options.helpEvents()) {
cout << options.eventOptions() << endl;
return 1;
}
bool isRegularFile;
long unsigned linesSelected = 0;
boost::system::error_code ec;
pcre2_code *fileNamePattern = pcre2_compile(reinterpret_cast<PCRE2_SPTR>("^\\d{8}\\.log$"), PCRE2_ZERO_TERMINATED, PCRE2_CASELESS, &errorcode, &erroffset, nullptr);
pcre2_jit_compile(fileNamePattern, PCRE2_JIT_COMPLETE);
pcre2_match_data *fileNameMatchData = pcre2_match_data_create_from_pattern(fileNamePattern, nullptr);
for (recursive_directory_iterator it("./"); it != recursive_directory_iterator();) {
try {
isRegularFile = is_regular_file(it->path());
}
catch (const filesystem_error& ex) {
isRegularFile = false;
}
if (isRegularFile && (pcre2_jit_match(fileNamePattern, reinterpret_cast<PCRE2_SPTR>(it->path().filename().c_str()), it->path().filename().size(), 0, 0, fileNameMatchData, nullptr) > 0)) {
File file(it->path().c_str());
Parser parser(&file);
while (parser.next()) {
linesSelected += match(&parser, &options);
if (options.stopAfter() > 0 && linesSelected == options.stopAfter()) {
break;
}
}
if (options.stopAfter() > 0 && linesSelected == options.stopAfter()) {
break;
}
}
it.increment(ec);
}
pcre2_match_data_free(fileNameMatchData);
pcre2_code_free(fileNamePattern);
return linesSelected > 0 ? 0 : 1;
} | SkyCorvette/TechLog | src/main.cpp | C++ | unlicense | 4,535 |
namespace Spinvoice.Infrastructure.Pdf
{
internal interface IImageBasedPageParser : IPageParser
{
}
} | aukolov/Spinvoice | src/Server/Spinvoice.Infrastructure.Pdf/IImageBasedPageParser.cs | C# | unlicense | 113 |
#!/usr/bin/env python
"""
Assorted utilities for manipulating latitude and longitude values
"""
from __future__ import unicode_literals
__version__ = "1.4"
import math, struct
def signbit(value):
"""
Test whether the sign bit of the given floating-point value is
set. If it is set, this generally means the given value is
negative. However, this is not the same as comparing the value
to C{0.0}. For example:
>>> NEGATIVE_ZERO < 0.0
False
since negative zero is numerically equal to positive zero. But
the sign bit of negative zero is indeed set:
>>> signbit(NEGATIVE_ZERO)
True
>>> signbit(0.0)
False
@type value: float
@param value: a Python (double-precision) float value
@rtype: bool
@return: C{True} if the sign bit of C{value} is set;
C{False} if it is not set.
signbit and doubleToRawLongBits
are from Martin Jansche:
http://symptotic.com/mj/code.html (MIT license).
This is required to capture the difference between -0.0 and 0.0, which is
useful if someone wants to convert a latitude or longitude like:
-0.0degrees, 34minutes to 0d34'00"S
"""
return (doubleToRawLongBits(value) >> 63) == 1
def doubleToRawLongBits(value):
"""
@type value: float
@param value: a Python (double-precision) float value
@rtype: long
@return: the IEEE 754 bit representation (64 bits as a long integer)
of the given double-precision floating-point value.
"""
# pack double into 64 bits, then unpack as long int
return struct.unpack(b'Q', struct.pack(b'd', value))[0]
class LatLongConverter:
@classmethod
def ToDecDeg(self, d=0, m=0, s=0, ustring = False, max=180):
"""
DecDegrees = ToDecDeg(d=0, m=0, s=0)
converts degrees, minutes, seconds to decimal degrees (returned as a Float).
"""
if m < 0 or s < 0:
raise ValueError("Minutes and Seconds have to be positive")
if m > 60.0 or s > 60.0:
raise ValueError("Minutes and Seconds have to be between -180 and 180")
if abs(d) > max:
raise ValueError("Degrees have to be between -180 and 180")
if signbit(d):
Sign = -1
d = abs(d)
else:
Sign = 1
deg_has_fract = bool(math.modf(d)[0])
min_has_fract = bool(math.modf(m)[0])
if deg_has_fract and (m != 0.0 or s != 0.0):
raise ValueError("degrees cannot have fraction unless both minutes"
"and seconds are zero")
if min_has_fract and s != 0.0:
raise ValueError("minutes cannot have fraction unless seconds are zero")
DecDegrees = Sign * (d + m/60.0 + s/3600.0)
if ustring:
return u"%.6f\xb0"%(DecDegrees)
else:
return DecDegrees
@classmethod
def ToDegMin(self, DecDegrees, ustring = False):
"""
Converts from decimal (binary float) degrees to:
Degrees, Minutes
If the optional parameter: "ustring" is True,
a Unicode string is returned
"""
if signbit(DecDegrees):
Sign = -1
DecDegrees = abs(DecDegrees)
else:
Sign = 1
Degrees = int(DecDegrees)
DecMinutes = round((DecDegrees - Degrees + 1e-14) * 60, 10)# add a tiny bit then round to avoid binary rounding issues
if ustring:
if Sign == 1:
return u"%i\xb0 %.3f'"%(Degrees, DecMinutes)
else:
return u"-%i\xb0 %.3f'"%(Degrees, DecMinutes)
else:
return (Sign*float(Degrees), DecMinutes) # float to preserve -0.0
@classmethod
def ToDegMinSec(self, DecDegrees, ustring = False):
"""
Converts from decimal (binary float) degrees to:
Degrees, Minutes, Seconds
If the optional parameter: "ustring" is True,
a unicode string is returned
"""
if signbit(DecDegrees):
Sign = -1
DecDegrees = abs(DecDegrees)
else:
Sign = 1
Degrees = int(DecDegrees)
DecMinutes = (DecDegrees - Degrees + 1e-14) * 60 # add a tiny bit to avoid rounding issues
Minutes = int(DecMinutes)
Seconds = round(((DecMinutes - Minutes) * 60), 10 )
if ustring:
if Sign == 1:
return u"%i\xb0 %i' %.2f\""%(Degrees, Minutes, Seconds)
else:
return u"-%i\xb0 %i' %.2f\""%(Degrees, Minutes, Seconds)
else:
return (Sign * float(Degrees), Minutes, Seconds)
## These are classes used in our web apps: ResponseLink, etc.
## They provide a different interface to lat-long format conversion
class Latitude:
"""An object that can interpret a latitude in various formats.
Constructor:
Latitude(deg, min=0.0, sec=0.0, direction=None)
- 'deg' may be between -90.0 and 90.0.
- if 'min' is nonzero, 'deg' cannot have a fractional part.
(This means 5 and 5.0 are acceptable but 5.1 is not.)
- if 'sec' is nonzero, 'deg' and 'min' cannot have fractional parts.
- 'direction' may be a string beginning with 'N' or 'S' (case
insensitive), or None.
- if 'direction' is not None, 'deg' cannot be negative.
Attributes:
.value : a float in decimal degrees. Positive is North; negative is
South. (These apply to zero too; positive zero is North.)
Methods:
.degrees() -> (float, str)
.degrees_minutes() -> (int, float, str)
.degrees_minutes_seconds() -> (int, int, float, str)
The 'str' argument is the direction: "North" or "South".
Example:
>>> lat1 = Latitude(-120.7625)
>>> lat2 = Latitude(-120, 45.7500)
>>> lat3 = Latitude(-120, 45, 45)
>>> lat4 = Latitude(120.7625, direction='South')
>>> lat5 = Latitude(120, 45.7500, direction='S')
>>> lat6 = Latitude(120, 45, 45, direction='south')
>>> (lat1.value == lat2.value == lat3.value == lat4.value ==
... lat5.value == lat6.value)
True
>>> lat1.value
-120.7625
>>> lat1.degrees()
(120.7625, 'South')
>>> lat1.degrees_minutes()
(120, 45.750000000000171, 'South')
>>> lat1.degrees_minutes_seconds()
(120, 45, 45.000000000010232, 'South')
>>> print str(lat1)
Latitude(-120.762500)
"""
negative_direction = "South"
positive_direction = "North"
min = -90.0
max = 90.0
def __init__(self, deg, min=0.0, sec=0.0, direction=None):
ndir = self.negative_direction[0].upper()
pdir = self.positive_direction[0].upper()
if direction:
if deg < 0.0:
msg = "degrees cannot be negative if direction is specified"
raise ValueError(msg)
if direction[0].upper() == pdir:
pass
elif direction[0].upper() == ndir:
deg = -deg
else:
msg = "direction must start with %r or %r" % (pdir, ndir)
raise ValueError(msg)
self.value = LatLongConverter.ToDecDeg(deg, min, sec, max=self.max)
def direction(self):
if self.value < 0.0:
return self.negative_direction
else:
return self.positive_direction
def degrees(self):
deg = abs(self.value)
return deg, self.direction()
def degrees_minutes(self):
deg, min = LatLongConverter.ToDegMin(abs(self.value))
return deg, min, self.direction()
def degrees_minutes_seconds(self):
deg, min, sec = LatLongConverter.ToDegMinSec(abs(self.value))
return deg, min, sec, self.direction()
def __repr__(self):
try:
return "%s(%f)" % (self.__class__.__name__, self.value)
except AttributeError:
return "%s(uninitialized)" % self.__class__.__name__
def format(self, style):
"""
format(style)
returns formatted value as Unicode string with u'\xb0' (degree symbol).
style is one of:
1: decimal degrees
2: degrees, decimal minutes
3: degrees, minutes, seconds
"""
if style == 1:
return u'''%0.2f\xb0 %s''' % self.degrees()
elif style == 2:
return u'''%d\xb0 %0.2f' %s''' % self.degrees_minutes()
elif style == 3:
return u'''%d\xb0 %d' %0.2f" %s''' % self.degrees_minutes_seconds()
else:
raise ValueError("style must be 1, 2, or 3")
def format_html(self, style):
"""
format_html(style)
Backward compatibility for Quixote rlink and Pylons inews.
"""
return self.format(style).replace(u"\xb0", u"°").encode("ascii")
class Longitude(Latitude):
"""See Latitude docstring.
Positive is East; negative is West. Degrees must be between -180.0 and
180.0
"""
negative_direction = "West"
positive_direction = "East"
min = -180.0
max = 180.0
class DummyLatitude:
"""A pseudo-Latitude whose components are None.
Useful in building HTML forms where the value is not required.
Note: this class may be deleted if it doesn't turn out to be useful.
"""
value = None
def direction(self): return None
def degrees(self): return None, None
def degrees_minutes(self): return None, None, None
def degrees_minutes_seconds(self): return None, None, None, None
class DummyLongitude(DummyLatitude):
"""
Note: this class may be deleted if it doesn't turn out to be useful.
"""
pass
## The new simple API -- just methods that do what we need for ResponseLink, etc.
DEGREES = "\xb0" # "DEGREE SIGN"
MINUTES = "\u2032" # "PRIME"
SECONDS = "\u2033" # "DOUBLE PRIME"
LAT_POSITIVE_DIRECTION = "North"
LAT_NEGATIVE_DIRECTION = "South"
LON_POSITIVE_DIRECTION = "East"
LON_NEGATIVE_DIRECTION = "West"
FORMAT1 = "{:.2f}\N{DEGREE SIGN} {}"
FORMAT2 = "{:.0f}\N{DEGREE SIGN} {:.2f}\N{PRIME} {}"
FORMAT3 = "{:.0f}\N{DEGREE SIGN} {:.0f}\N{PRIME} {:.2f}\N{DOUBLE PRIME} {}"
def reduce_base_60(f):
"""extract the base 60 fractional portion of a floating point number.
i.e. minutes from degrees, seconds from minutes.
"""
fract, whole = math.modf(f)
# Add a tiny bit before rounding to avoid binary rounding errors.
fract = abs(fract)
fract = (fract + 1e-14) * 60
fract = round(fract, 10)
return whole, fract
def format_latlon2(f, positive_direction, negative_direction):
direction = positive_direction if f >= 0.0 else negative_direction
degrees, minutes = reduce_base_60(f)
degrees = abs(degrees)
return FORMAT2.format(degrees, minutes, direction)
def format_latlon3(f, positive_direction, negative_direction):
direction = positive_direction if f >= 0.0 else negative_direction
degrees, minutes = reduce_base_60(f)
minutes, seconds = reduce_base_60(minutes)
degrees = abs(degrees)
return FORMAT3.format(degrees, minutes, seconds, direction)
def format_lat(f):
return format_latlon2(f, LAT_POSITIVE_DIRECTION, LAT_NEGATIVE_DIRECTION)
def format_lon(f):
return format_latlon2(f, LON_POSITIVE_DIRECTION, LON_NEGATIVE_DIRECTION)
def format_lat_dms(f):
return format_latlon3(f, LAT_POSITIVE_DIRECTION, LAT_NEGATIVE_DIRECTION)
def format_lon_dms(f):
return format_latlon3(f, LON_POSITIVE_DIRECTION, LON_NEGATIVE_DIRECTION)
| NOAA-ORR-ERD/hazpy.unit_conversion | hazpy/unit_conversion/lat_long.py | Python | unlicense | 11,710 |
from math import log
def num_prime_factors(upper_limit):
"""
Create an array whose entries are the number of not necessarily distinct
prime factors of the index. The upper bound is the first number not
included.
"""
factor_count = [0] * upper_limit
prime = 2 #start with the first prime, which is 2
while True:
prime_power = prime
for exponent in range(int(log(upper_limit, prime))):
for hit in range(prime_power, upper_limit, prime_power):
factor_count[hit] += 1
prime_power *= prime
while True:
prime += 1
if prime >= upper_limit:
return factor_count
if factor_count[prime] == 0: break
print(sum(1 if n == 2 else 0 for n in num_prime_factors(100000000)))
| peterstace/project-euler | OLD_PY_CODE/project_euler_old_old/187/187.py | Python | unlicense | 813 |
package cz.muni.fi.pv243.et.model;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.IndexedEmbedded;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
@Indexed
public class ExpenseReport implements Serializable {
@Id
@GeneratedValue
private Long id;
@NotNull
private String name;
private String description;
private Boolean selected;
public ExpenseReport() {
}
public ExpenseReport(String name, String description, Person submitter, Person verifier, ReportStatus status) {
this.name = name;
this.description = description;
this.submitter = submitter;
this.verifier = verifier;
this.status = status;
}
@NotNull
@ManyToOne
@IndexedEmbedded
private Person submitter;
@ManyToOne(cascade= CascadeType.MERGE)
@IndexedEmbedded
private Person verifier;
@OneToMany(mappedBy = "report", cascade = CascadeType.MERGE)
@LazyCollection(LazyCollectionOption.FALSE)
private List<Payment> payments;
@OneToMany(mappedBy = "report", cascade = CascadeType.MERGE)
@LazyCollection(LazyCollectionOption.FALSE)
private List<MoneyTransfer> moneyTransfers;
@Temporal(TemporalType.TIMESTAMP)
private Date lastSubmittedDate;
@Temporal(TemporalType.TIMESTAMP)
private Date approvedDate;
@Temporal(TemporalType.TIMESTAMP)
private Date lastChangeDate;
@Field
@Enumerated(EnumType.ORDINAL)
@IndexedEmbedded
private ReportStatus status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Person getSubmitter() {
return submitter;
}
public void setSubmitter(Person submitter) {
this.submitter = submitter;
}
public Person getVerifier() {
return verifier;
}
public void setVerifier(Person verifier) {
this.verifier = verifier;
}
public List<Payment> getPayments() {
return payments;
}
public void setPayments(List<Payment> payments) {
this.payments = payments;
}
public List<MoneyTransfer> getMoneyTransfers() {
return moneyTransfers;
}
public void setMoneyTransfers(List<MoneyTransfer> moneyTransfers) {
this.moneyTransfers = moneyTransfers;
}
public Date getLastSubmittedDate() {
return lastSubmittedDate;
}
public void setLastSubmittedDate(Date lastSubmittedDate) {
this.lastSubmittedDate = lastSubmittedDate;
}
public Date getApprovedDate() {
return approvedDate;
}
public void setApprovedDate(Date approvedDate) {
this.approvedDate = approvedDate;
}
public ReportStatus getStatus() {
return status;
}
public void setStatus(ReportStatus status) {
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getLastChangeDate() {
return lastChangeDate;
}
public void setLastChangeDate(Date lastChangeDate) {
this.lastChangeDate = lastChangeDate;
}
public Boolean getSelected() {
return selected;
}
public void setSelected(Boolean selected) {
this.selected = selected;
}
@Override
public final boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ExpenseReport)) return false;
ExpenseReport report = (ExpenseReport) o;
if (getId() != null ? !getId().equals(report.getId()) : report.getId() != null) return false;
return true;
}
@Override
public int hashCode() {
return getId() != null ? getId().hashCode() : 0;
}
@Override
public String toString() {
return "ExpenseReport{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
", submitter=" + submitter +
", verifier=" + verifier +
", payments=" + payments +
", moneyTransfers=" + moneyTransfers +
", lastSubmittedDate=" + lastSubmittedDate +
", approvedDate=" + approvedDate +
", lastChangeDate=" + lastChangeDate +
", status=" + status +
", selected=" + selected +
'}';
}
}
| rsmeral/pv243-jboss | project/project-et-ejb/src/main/java/cz/muni/fi/pv243/et/model/ExpenseReport.java | Java | unlicense | 4,903 |
Rails.application.routes.draw do
resources :transactions
resources :ratings
resources :user_identifications
root 'react#home'
resources :items
devise_for :user, only: []
# for facebook & twitter login
devise_for :users, controllers: { omniauth_callbacks: 'omniauth_callbacks' },
skip: [:invitations, :session, :registration],
path: ''
namespace :auth, defaults: { format: :json } do
get 'login' => 'sessions#login'
post 'register' => 'sessions#register'
end
end
| jennyyuejin/projectFox | config/routes.rb | Ruby | unlicense | 540 |
<?php
namespace Google\Service\Calendar;
class Colors extends \Google\Model
{
protected $calendarType = 'Google\Service\Calendar\ColorDefinition';
protected $calendarDataType = 'map';
protected $eventType = 'Google\Service\Calendar\ColorDefinition';
protected $eventDataType = 'map';
public $kind;
public $updated;
public function setCalendar($calendar)
{
$this->calendar = $calendar;
}
public function getCalendar()
{
return $this->calendar;
}
public function setEvent($event)
{
$this->event = $event;
}
public function getEvent()
{
return $this->event;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setUpdated($updated)
{
$this->updated = $updated;
}
public function getUpdated()
{
return $this->updated;
}
}
| inri13666/google-api-php-client-v2 | libs/Google/Service/Calendar/Colors.php | PHP | unlicense | 890 |
import when from 'when';
import { post } from 'utils/http';
import baseUrl from 'utils/baseUrl';
export function requestPasswordReset( email ) {
return when(
post( baseUrl( 'auth/reset_password' ), {
params: {
email
}
} )
);
}
export function verifyResetPasswordToken( token, password) {
return when(
post( baseUrl( 'auth/verify_reset_password_token' ), {
params: {
token,
password
}
} )
);
}
| FrontSmith/FSFramework | client/src/app/resources/resets.js | JavaScript | unlicense | 540 |
using Lib.Graph;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lib.Extensions;
namespace _079
{
/// <summary>
/// A common security method used for online banking is to ask the user for three random characters from a passcode.
/// For example, if the passcode was 531278, they may ask for the 2nd, 3rd, and 5th characters; the expected reply would be: 317.
///
/// The text file, keylog.txt, contains fifty successful login attempts.
///
/// Given that the three characters are always asked for in order, analyse the file so as to determine the shortest possible secret passcode of unknown length.
/// </summary>
class Program
{
static void Main(string[] args)
{
var lines = File.ReadAllLines(@"keylog.txt");
var graph = new Graph<int?>();
foreach (var line in lines)
{
int? lastnum = null;
for (int i = 0; i < line.Length; i++)
{
var num = line.ParseDigit(i);
graph.AddValue(num, lastnum);
lastnum = num;
}
}
var sorted = graph.TopologicalSort();
Console.WriteLine(String.Join("", sorted));
Console.ReadKey();
}
}
}
| nadrees/ProjectEuler | 079/Program.cs | C# | unlicense | 1,408 |
// ADDING JAVASCRIPT
function fp_scripts()
{
// Register the script like this for a theme:
// wp_register_script( $handle, $src, $deps, $ver, $in_footer );
wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js', array( 'jquery', 'jquery-ui-core' ), '20131118', true );
// use the array to grab a library already included in WordPress, in this case 'jquery' and 'jquery-ui-core'
// For either a plugin or a theme, you can then enqueue the script:
wp_enqueue_script( 'custom-script' );
}
// add_action( $tag, $function_to_add, $priority, $accepted_args );
add_action( 'wp_enqueue_scripts', 'fp_scripts' );
// ADDING STYLES
function fp_styles()
{
// Register the style like this for a theme:
// wp_register_style( $handle, $src, $deps, $ver, $media ); note "$media" instead of $in_footer
// $media parameter can take 'all', 'screen', 'handheld', or 'print' values
wp_register_style( 'custom-style', get_stylesheet_directory() . '/css/custom-style.css', array(), '20131118', 'all' );
// note replacing get_template_directory_uri with get_stylesheet_directory_uri
// http://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri
// http://codex.wordpress.org/Child_Themes
// get_stylesheet_directory() points to your child theme's directory (not the parent theme's directory).
// http://www.wpbeginner.com/wp-tutorials/how-to-properly-add-javascripts-and-styles-in-wordpress/
// If you are working with a child theme, then use get_stylesheet_directory_uri()
// For either a plugin or a theme, you can then enqueue the style:
wp_enqueue_style( 'custom-style' );
}
add_action( 'wp_enqueue_scripts', 'fp_styles' );
// from http://wp.tutsplus.com/articles/how-to-include-javascript-and-css-in-your-wordpress-themes-and-plugins/
// Agrument that you *should not* move scripts to the footer
// --> http://code.tutsplus.com/articles/a-beginners-guide-to-enqueuing-jquery--wp-30615
// Also - load scripts only on plugin pages http://codex.wordpress.org/Function_Reference/wp_enqueue_script#Load_scripts_only_on_plugin_pages
| PittsburghChris/usingWp_enqueue_script | functions.php | PHP | unlicense | 2,176 |
package com.ushaqi.zhuishushenqi.util;
import com.ushaqi.zhuishushenqi.a.e;
import com.ushaqi.zhuishushenqi.api.ApiService;
import com.ushaqi.zhuishushenqi.api.b;
import com.ushaqi.zhuishushenqi.model.ResultStatus;
final class l extends e<String, Void, ResultStatus>
{
private l(k paramk)
{
}
private static ResultStatus a(String[] paramArrayOfString)
{
try
{
b.a();
ResultStatus localResultStatus = b.b().n(paramArrayOfString[0], paramArrayOfString[1], paramArrayOfString[2]);
return localResultStatus;
}
catch (Exception localException)
{
localException.printStackTrace();
}
return null;
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ushaqi.zhuishushenqi.util.l
* JD-Core Version: 0.6.0
*/ | clilystudio/NetBook | allsrc/com/ushaqi/zhuishushenqi/util/l(1).java | Java | unlicense | 833 |
<?php
/* @var $this CouponController */
/* @var $model Coupon */
$this->breadcrumbs=array(
'Coupons'=>array('index'),
$model->coupon_id=>array('view','id'=>$model->coupon_id),
'Update',
);
$this->menu=array(
array('label'=>'List Coupon', 'url'=>array('index')),
array('label'=>'Create Coupon', 'url'=>array('create')),
array('label'=>'View Coupon', 'url'=>array('view', 'id'=>$model->coupon_id)),
array('label'=>'Manage Coupon', 'url'=>array('admin')),
);
?>
<h1>Update Coupon <?php echo $model->coupon_id; ?></h1>
<?php $this->renderPartial('_form', array('model'=>$model)); ?> | tierous/yiirisma | protected/views/coupon/update.php | PHP | unlicense | 589 |
/// @file SNIIS_Mac.cpp
/// Mac OSX implementation of input system
#include "SNIIS_Mac.h"
#include "SNIIS_Intern.h"
#if SNIIS_SYSTEM_MAC
using namespace SNIIS;
// --------------------------------------------------------------------------------------------------------------------
// Constructor
MacInput::MacInput(id pWindowId)
{
mWindow = pWindowId;
// create the manager
mHidManager = IOHIDManagerCreate( kCFAllocatorDefault, 0);
if( !mHidManager )
throw std::runtime_error( "Failed to create HIDManager");
// tell 'em we want it all
IOHIDManagerSetDeviceMatching( mHidManager, nullptr);
// register our enumeration callback
IOHIDManagerRegisterDeviceMatchingCallback( mHidManager, &MacInput::HandleNewDeviceCallback, (void*) this);
// register us for running the event loop
IOHIDManagerScheduleWithRunLoop( mHidManager, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
// and open the manager, enumerating all devices along with it
IOReturn res = IOHIDManagerOpen( mHidManager, 0);
Log( "IOHIDManagerOpen() returned %d", res);
if( res != kIOReturnSuccess )
throw std::runtime_error( "Failed to open HIDManager / enumerate devices");
// run the update loop to get the callbacks for new devices
while( CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, TRUE) == kCFRunLoopRunHandledSource )
/**/;
// remove the manager from the callbacks and runloop
IOHIDManagerRegisterDeviceMatchingCallback( mHidManager, nullptr, nullptr);
// Since some OSX update the Unschedule() thingy also unschedules all devices, so we never get any event notifications
// simply leaving it be should be fine, as we unregistered the callback
// IOHIDManagerUnscheduleFromRunLoop( mHidManager, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
}
// --------------------------------------------------------------------------------------------------------------------
// Destructor
MacInput::~MacInput()
{
for( auto d : mDevices )
delete d;
if( mHidManager )
IOHIDManagerClose( mHidManager, 0);
CFRelease( mHidManager);
}
// --------------------------------------------------------------------------------------------------------------------
// Updates the inputs, to be called before handling system messages
void MacInput::Update()
{
// Basis work
InputSystem::Update();
// device work
for( size_t a = 0; a < mMacDevices.size(); ++a )
{
MacDevice* d = mMacDevices[a];
d->StartUpdate();
}
// then run the update loop
while( CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, TRUE) == kCFRunLoopRunHandledSource )
/**/;
// Mice need postprocessing
for( auto d : mDevices )
{
if( auto m = dynamic_cast<MacMouse*> (d) )
m->EndUpdate();
// from now on everything generates signals
d->ResetFirstUpdateFlag();
}
}
// --------------------------------------------------------------------------------------------------------------------
// Notifies the input system that the application has lost/gained focus.
void MacInput::InternSetFocus( bool pHasFocus)
{
for( auto d : mMacDevices )
d->SetFocus( pHasFocus);
}
// --------------------------------------------------------------------------------------------------------------------
void MacInput::InternSetMouseGrab( bool enabled)
{
auto wr = MacHelper_GetWindowRect( mWindow);
Pos p;
if( enabled )
{
// if enabled, move system mouse to window center and start taking offsets from there
p.x = wr.w / 2; p.y = wr.h / 2;
} else
{
// if disabled, move mouse to last reported mouse position to achieve a smooth non-jumpy transition between the modes
p.x = std::max( 0.0f, std::min( wr.w, float( GetMouseX())));
p.y = std::max( 0.0f, std::min( wr.h, float( GetMouseY())));
}
Pos gp = MacHelper_WinToDisplay( mWindow, p);
MacHelper_SetMousePos( gp);
}
// --------------------------------------------------------------------------------------------------------------------
// Callback for each enumerated device
void MacInput::HandleNewDeviceCallback( void* context, IOReturn result, void* sender, IOHIDDeviceRef device)
{
SNIIS_UNUSED( sender);
if( result == kIOReturnSuccess )
{
auto inp = reinterpret_cast<MacInput*> (context);
inp->HandleNewDevice( device);
}
}
// --------------------------------------------------------------------------------------------------------------------
// Handle a newly detected device
void MacInput::HandleNewDevice( IOHIDDeviceRef device)
{
// get usage page and usage
int32_t usepage = 0, usage = 0;
auto ref = IOHIDDeviceGetProperty( device, CFSTR( kIOHIDPrimaryUsagePageKey));
if( ref )
CFNumberGetValue( (CFNumberRef) ref, kCFNumberSInt32Type, &usepage);
ref = IOHIDDeviceGetProperty( device, CFSTR( kIOHIDPrimaryUsageKey));
if( ref )
CFNumberGetValue( (CFNumberRef) ref, kCFNumberSInt32Type, &usage);
// get the names
auto cfstr = (CFStringRef) IOHIDDeviceGetProperty( device, CFSTR(kIOHIDProductKey));
auto cfstr2 = (CFStringRef) IOHIDDeviceGetProperty( device, CFSTR(kIOHIDManufacturerKey));
std::vector<char> tmp( 500, 0);
if( cfstr )
CFStringGetCString( cfstr, &tmp[0], tmp.size(), kCFStringEncodingUTF8);
else
sprintf( &tmp[0], "(null)");
size_t l = strlen( tmp.data());
tmp[l++] = '|';
if( cfstr2 )
CFStringGetCString( cfstr2, &tmp[l], tmp.size() - l, kCFStringEncodingUTF8);
else
sprintf( &tmp[l], "(null)");
Log( "HandleNewDevice \"%s\", page %d, usage %d", tmp.data(), usepage, usage);
if( usepage != kHIDPage_GenericDesktop )
return;
Log( "New device \"%s\" at page %d, usage %d", tmp.data(), usepage, usage);
// extra ugly: store last mouse because we might have to add the second trackpad to it
static MacMouse* lastMouse = nullptr;
switch( usage )
{
case kHIDUsage_GD_Mouse:
case kHIDUsage_GD_Pointer:
{
try {
bool isTrackpad = strncmp( tmp.data(), "Apple Internal Keyboard / Trackpad", 34) == 0;
if( isTrackpad && lastMouse && lastMouse->IsTrackpad() )
{
Log( "-> second HID of internal trackpad, adding to Mouse %d (id %d)", lastMouse->GetCount(), lastMouse->GetId());
lastMouse->AddDevice( device);
}
else
{
Log( "-> Mouse %d (id %d)", mNumMice, mDevices.size());
auto m = new MacMouse( this, mDevices.size(), device, isTrackpad);
InputSystemHelper::AddDevice( m);
mMacDevices.push_back( m);
if( isTrackpad )
lastMouse = m;
}
} catch( std::exception& e)
{
Log( "Exception: %s", e.what());
}
break;
}
case kHIDUsage_GD_Keyboard:
case kHIDUsage_GD_Keypad:
{
try {
Log( "-> Keyboard %d (id %d)", mNumKeyboards, mDevices.size());
auto k = new MacKeyboard( this, mDevices.size(), device);
InputSystemHelper::AddDevice( k);
mMacDevices.push_back( k);
} catch( std::exception& e)
{
Log( "Exception: %s", e.what());
}
break;
}
case kHIDUsage_GD_Joystick:
case kHIDUsage_GD_GamePad:
case kHIDUsage_GD_MultiAxisController:
{
try {
Log( "-> Controller %d (id %d)", mNumJoysticks, mDevices.size());
auto j = new MacJoystick( this, mDevices.size(), device);
InputSystemHelper::AddDevice( j);
mMacDevices.push_back( j);
} catch( std::exception& e)
{
Log( "Exception: %s", e.what());
}
break;
}
}
}
// --------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------
std::vector<MacControl> EnumerateDeviceControls( IOHIDDeviceRef devref)
{
// enumerate all controls of that device
std::vector<MacControl> controls;
CFArrayRef elements = IOHIDDeviceCopyMatchingElements( devref, nullptr, kIOHIDOptionsTypeNone);
for( size_t a = 0, count = CFArrayGetCount( elements); a < count; ++a )
{
auto elmref = (IOHIDElementRef) CFArrayGetValueAtIndex( elements, CFIndex( a));
auto type = IOHIDElementGetType( elmref);
auto usepage = IOHIDElementGetUsagePage( elmref), usage = IOHIDElementGetUsage( elmref);
size_t prevSize = controls.size();
if( type == kIOHIDElementTypeInput_Axis || type == kIOHIDElementTypeInput_Misc )
{
auto min = IOHIDElementGetLogicalMin( elmref), max = IOHIDElementGetLogicalMax( elmref);
if( usage == kHIDUsage_GD_Hatswitch )
{
controls.push_back( MacControl{ devref, MacControl::Type_Hat, "", 0, usepage, usage, min, max });
controls.push_back( MacControl{ devref, MacControl::Type_Hat_Second, "", 0, usepage, usage, min, max });
}
else
{
controls.push_back( MacControl{ devref, MacControl::Type_Axis, "", 0, usepage, usage, min, max });
}
}
else if( type == kIOHIDElementTypeInput_Button )
{
controls.push_back( MacControl{ devref, MacControl::Type_Button, "", 0, usepage, usage, 0, 1 });
}
// add a few things afterwards if we got new controls
for( size_t a = prevSize; a < controls.size(); ++a )
{
controls[a].mCookie = IOHIDElementGetCookie( elmref);
auto name = IOHIDElementGetName( elmref);
if( name )
{
std::vector<char> tmp( 500, 0);
CFStringGetCString( name, &tmp[0], tmp.size(), kCFStringEncodingUTF8);
controls[a].mName = &tmp[0];
}
}
}
return controls;
}
void InputElementValueChangeCallback( void* ctx, IOReturn res, void* sender, IOHIDValueRef val)
{
SNIIS_UNUSED( sender);
if( res != kIOReturnSuccess )
return;
//also ignore all events if we ain't focus'd. Did I use that word correctly?
if( !gInstance->HasFocus() )
return;
auto dev = static_cast<MacDevice*> (ctx);
auto elm = IOHIDValueGetElement( val);
auto keksie = IOHIDElementGetCookie( elm);
auto value = IOHIDValueGetIntegerValue( val);
auto usepage = IOHIDElementGetUsagePage( elm), usage = IOHIDElementGetUsage( elm);
auto hiddev = IOHIDElementGetDevice( elm);
dev->HandleEvent( hiddev, keksie, usepage, usage, value);
}
std::pair<float, float> ConvertHatToAxes( long min, long max, long value)
{
std::pair<float, float> axes;
// Hats deliver a value that starts at North (x=0, y=-1) and goes a full circle clockwise within the value range
// We need to decompose this into two axes from roughly 8 standard cases with a little safety each
float v = float( value - min) / float( max - min);
if( v > 0.1f && v < 0.4f )
axes.first = 1.0f;
else if( v > 0.6f && v < 0.9f )
axes.first = -1.0f;
else
axes.first = 0.0f;
if( v < 0.15f || v > 0.85f )
axes.second = -1.0f;
else if( v > 0.35f && v < 0.65f )
axes.second = 1.0f;
else
axes.second = 0.0f;
return axes;
}
// --------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------
// Initializes the input system with the given InitArgs. When successful, gInstance is not Null.
bool InputSystem::Initialize(void* pInitArg)
{
if( gInstance )
throw std::runtime_error( "Input already initialized");
try
{
gInstance = new MacInput( pInitArg);
} catch( std::exception& e)
{
// nope
if( gLogCallback )
gLogCallback( (std::string( "Exception while creating SNIIS instance: ") + e.what()).c_str());
gInstance = nullptr;
return false;
}
return true;
}
// --------------------------------------------------------------------------------------------------------------------
// Destroys the input system. After returning gInstance is Null again
void InputSystem::Shutdown()
{
delete gInstance;
gInstance = nullptr;
}
#endif // SNIIS_SYSTEM_MAC
| Schrompf/sniis | SNIIS_Mac.cpp | C++ | unlicense | 11,937 |
#include "cpp_header.h"
class Solution {
public:
int lengthOfLIS(vector<int>& nums)
{
vector<int> lens(nums.size(), 1);
int longest = 0;
for(int i = 0; i < nums.size(); i++)
{
for(int j = 0; j < i; j++)
{
if(nums[i] > nums[j])
{
lens[i] = max(lens[i], lens[j] + 1);
}
}
if(longest < lens[i])
{
longest = lens[i];
}
}
return longest;
}
int lengthOfLIS2(vector<int>& nums)
{
if(nums.size() < 2)
return nums.size();
// sorted sub sequence of nums
// it is one of the longest sub increasing sub sequence
// which has minimum minus of the biggest and smallest.
vector<int> lis;
for(auto & num : nums)
{
// position in lis that greater or equal than num
auto idx = lower_bound(lis.begin(), lis.end(), num) - lis.begin();
if(idx >= lis.size())
lis.push_back(num);
else
lis[idx] = num;
}
for(auto x : lis)
cout << x << " ";
cout << "\n";
return lis.size();
}
};
int testcase(vector<int> nums, int res, int casenum)
{
Solution sol;
if(sol.lengthOfLIS2(nums) == res)
{
cout << casenum << " pass\n";
}
else
{
cout << casenum << " no pass\n";
}
}
int main()
{
vector<int> nums;
int res;
int casenum;
nums = {10, 9, 2, 5, 3, 7, 101, 18};
res = 4;
casenum = 1;
testcase(nums, res, casenum);
}
| sczzq/symmetrical-spoon | leetcode/docu/300.cpp | C++ | unlicense | 1,318 |
module Bitcache
##
# A Bloom filter for Bitcache identifiers.
#
# Bloom filters are space-efficient probabilistic data structures used to
# test whether an element is a member of a set. False positives are
# possible, but false negatives are not. Elements can be added to the set,
# but not removed. The more elements that are added to the set, the larger
# the probability of false positives.
#
# Time Complexity
# ---------------
#
# The time needed to either add an identifier or to check whether an
# identifier is a member of the set is a fixed constant, `O(k)`,
# completely independent of the number of identifiers already in the set.
#
# The constant `k` is proportional to the length of the specific type of
# identifier used; `k=4` for MD5 identifiers, `k=5` for SHA-1 identifiers,
# and `k=8` for SHA-256 identifiers.
#
# Note: all time complexity information given for methods refers to the
# `libbitcache` implementation. The pure-Ruby method implementations may
# perform differently.
#
# Space Requirements
# ------------------
#
# The Bitcache implementation of Bloom filters is tuned to by default use
# 8 bits per element, giving a false positive probability of around ~2%.
#
# Limitations
# -----------
#
# Identifiers can't be removed from a filter except by recreating the
# filter afresh. This could be addressed by implementing a counting Bloom
# filter, but that would add complexity as well as quadruple the space
# requirements of filters. Still, counting filters may be provided as an
# option in the future if there is demand for the feature.
#
# @see http://en.wikipedia.org/wiki/Bloom_filter
class Filter < Struct
include Inspectable
DEFAULT_CAPACITY = 4096 # elements
BITS_PER_ELEMENT = 8 # bits
##
# Deserializes a filter from the given `input` stream or file.
#
# @param [File, IO, StringIO] input
# the input stream to read from
# @param [Hash{Symbol => Object}] options
# any additional options
# @return [Filter] a new filter
def self.load(input, options = {})
input = StringIO.new(input) if input.is_a?(String)
read = input.respond_to?(:readbytes) ? :readbytes : :read
bytesize = input.send(read, 8).unpack('Q').first # uint64 in native byte order
self.new(input.send(read, bytesize))
end
##
# Constructs a filter from the identifiers yielded by `enum`.
#
# Unless explicitly otherwise specified, the filter will have a capacity
# that matches the number of elements in `enum`.
#
# @example Constructing a filter from an array
# Filter.for([id1, id2, id3])
#
# @example Constructing a filter from a list
# Filter.for(List[id1, id2, id3])
#
# @example Constructing a filter from a set
# Filter.for(Set[id1, id2, id3])
#
# @example Rounding up the capacity to the nearest power of two
# Filter.for(enum, :capacity => (1 << enum.count.to_s(2).length))
#
# @param [Enumerable<Identifier, #to_id>] enum
# an enumerable that yields identifiers
# @param [Hash{Symbol => Object}] options
# any additional options
# @option options [Integer] :capacity (enum.count)
# the capacity to create the filter with
# @return [Filter] a new filter
def self.for(enum, options = {})
if enum.respond_to?(:to_filter)
enum.to_filter
else
self.new(options[:capacity] || enum.count) do |filter|
enum.each { |element| filter.insert(element.to_id) }
end
end
end
##
# Initializes a new filter from the given `bitmap`.
#
# @example Constructing a new filter
# Filter.new
#
# @param [String, Integer] bitmap
# the initial bitmap for the filter
# @yield [filter]
# @yieldparam [Filter] `self`
# @yieldreturn [void] ignored
def initialize(bitmap = nil, &block)
@bitmap = case bitmap
when nil then "\0" * DEFAULT_CAPACITY
when Integer then "\0" * bitmap
when String then bitmap.dup
else raise ArgumentError, "expected a String or Integer, but got #{bitmap.inspect}"
end
@bitmap.force_encoding(Encoding::BINARY) if @bitmap.respond_to?(:force_encoding) # for Ruby 1.9+
@bitsize = @bitmap.size * 8
if block_given?
case block.arity
when 0 then instance_eval(&block)
else block.call(self)
end
end
end
##
# Initializes a filter cloned from `original`.
#
# @param [Filter] original
# @return [void]
def initialize_copy(original)
@bitmap = original.instance_variable_get(:@bitmap).clone
end
##
# Prevents further modifications to this filter.
#
# @return [void] `self`
def freeze
bitmap.freeze
super
end
##
# @private
attr_reader :bitmap
##
# Returns the capacity of this filter.
#
# The time complexity of this operation is `O(1)`.
#
# @return [Integer] a positive integer
def capacity
bitmap.bytesize
end
alias_method :size, :capacity
alias_method :bytesize, :capacity
alias_method :length, :capacity
##
# Returns `true` if no elements have been inserted into this filter.
#
# The time complexity of this operation is `O(n)`, with `n` being the
# octet length of the filter.
#
# @return [Boolean] `true` or `false`
def empty?
/\A\x00+\z/ === bitmap
end
alias_method :zero?, :empty?
##
# Returns the percentage of unused space in this filter.
#
# The time complexity of this operation is `O(n)`, with `n` being the
# octet length of the filter.
#
# @return [Float] `(0.0..1.0)`
def space
space = 0
bitmap.each_byte do |byte|
if byte.zero?
space += 8
else
0.upto(7) do |r|
space += 1 if (byte & (1 << r)).zero?
end
end
end
space / @bitsize.to_f
end
##
# Returns `1` if this filter contains the identifier `id`, and `0`
# otherwise.
#
# This method may return a false positive, but it will never return a
# false negative.
#
# The time complexity of this operation is `O(k)`, with `k` being a
# constant proportional to the length of the identifier.
#
# @param [Identifier, #to_id] id
# @return [Integer] `1` or `0`
def count(id)
has_identifier?(id) ? 1 : 0
end
##
# Returns `true` if this filter contains the identifier `id`.
#
# This method may return a false positive, but it will never return a
# false negative.
#
# The time complexity of this operation is `O(k)`, with `k` being a
# constant proportional to the length of the identifier.
#
# @param [Identifier, #to_id] id
# @return [Boolean] `true` or `false`
def has_identifier?(id)
id.to_id.hashes.each do |hash|
return false unless self[hash % @bitsize]
end
return true # may return a false positive
end
alias_method :has_id?, :has_identifier?
alias_method :include?, :has_identifier?
alias_method :member?, :has_identifier?
##
# Returns `true` if this filter is equal to the given `other` filter or
# byte string.
#
# @param [Object] other
# @return [Boolean] `true` or `false`
def ==(other)
return true if self.equal?(other)
case other
when Filter
bytesize.eql?(other.bytesize) && bitmap.eql?(other.bitmap)
when String
bytesize.eql?(other.bytesize) && bitmap.eql?(other)
else false
end
end
##
# Returns `true` if this filter is identical to the given `other`
# filter.
#
# @param [Object] other
# @return [Boolean] `true` or `false`
def eql?(other)
return true if self.equal?(other)
case other
when Filter
self == other
else false
end
end
##
# Returns the hash code for this filter.
#
# @return [Fixnum]
def hash
bitmap.hash
end
##
# Returns the bit at the given `index`.
#
# The time complexity of this operation is `O(1)`.
#
# @example Checking the state of a given bit
# filter[42] #=> true or false
#
# @param [Integer, #to_i] index
# a bit offset
# @return [Boolean] `true` or `false`; `nil` if `index` is out of bounds
def [](index)
q, r = index.to_i.divmod(8)
byte = bitmap[q]
byte ? !((byte.ord & (1 << r)).zero?) : nil
end
##
# Updates the bit at the given `index` to `value`.
#
# The time complexity of this operation is `O(1)`.
#
# @example Toggling the state of a given bit
# filter[42] = true # sets the bit at position 42
# filter[42] = false # clears the bit at position 42
#
# @param [Integer] index
# a bit offset
# @param [Boolean] value
# `true` or `false`
# @return [Boolean] `value`
# @raise [IndexError] if `index` is out of bounds
# @raise [TypeError] if the filter is frozen
def []=(index, value)
q, r = index.to_i.divmod(8)
byte = bitmap[q]
raise IndexError, "index #{index} is out of bounds" unless byte
raise TypeError, "can't modify frozen filter" if frozen?
bitmap[q] = value ?
(byte.ord | (1 << r)).chr :
(byte.ord & (0xff ^ (1 << r))).chr
end
##
# Inserts the given identifier `id` into this filter.
#
# The time complexity of this operation is `O(k)`, with `k` being a
# constant proportional to the length of the identifier.
#
# @param [Identifier, #to_id] id
# @return [void] `self`
# @raise [TypeError] if the filter is frozen
def insert(id)
raise TypeError, "can't modify frozen filter" if frozen?
id.to_id.hashes.each do |hash|
self[hash % @bitsize] = true
end
return self
end
alias_method :add, :insert
alias_method :<<, :insert
##
# Resets this filter, removing any and all information about inserted
# elements.
#
# The time complexity of this operation is `O(n)`, with `n` being the
# octet length of the filter.
#
# @return [void] `self`
# @raise [TypeError] if the filter is frozen
def clear
raise TypeError, "can't modify frozen filter" if frozen?
bitmap.gsub!(/./m, "\0")
return self
end
alias_method :clear!, :clear
alias_method :reset!, :clear
##
# Returns a new filter resulting from merging this filter and the given
# `other` filter or byte string.
#
# @param [Filter, #to_str] other
# a filter or byte string of equal size
# @param [Symbol, #to_sym] op
# the bitwise operation to use: `:|`, `:&`, or `:^`
# @return [Filter] a new filter
def merge(other, op = :|)
dup.merge!(other, op)
end
##
# Merges the given `other` filter or byte string into this filter.
#
# @param [Filter, #to_str] other
# a filter or byte string of equal size
# @param [Symbol, #to_sym] op
# the bitwise operation to use: `:|`, `:&`, or `:^`
# @return [void] `self`
# @raise [TypeError] if the filter is frozen
def merge!(other, op = :|)
raise TypeError, "can't modify frozen filter" if frozen?
other = other.is_a?(Filter) ? other.bitmap : other.to_str
raise ArgumentError, "incompatible filter sizes" unless bytesize.eql?(other.bytesize)
if bitmap.respond_to?(fast_method = :"#{op}!")
bitmap.send(fast_method, other)
else
bitmap.each_byte.with_index do |byte, index|
bitmap[index] = byte.send(op, other[index].ord).chr
end
end
return self
end
##
# Returns the union of this filter and the given `other` filter or byte
# string.
#
# This operation is loss-less in the sense that the resulting filter is
# equal to a filter created from scratch using the union of the two sets
# of identifiers.
#
# @param [Filter, #to_str] other
# a filter or byte string of equal size
# @return [Filter] a new filter
def or(other)
merge(other, :|)
end
alias_method :|, :or
##
# Merges the given `other` filter or byte string into this filter using
# a bitwise `OR` operation.
#
# @param [Filter, #to_str] other
# a filter or byte string of equal size
# @return [void] `self`
# @raise [TypeError] if the filter is frozen
def or!(other)
merge!(other, :|)
end
##
# Returns the intersection of this filter and the given `other` filter
# or byte string.
#
# The false-positive probability in the resulting filter is at most the
# false-positive probability of one of the constituent filters, and may
# be larger than the false-positive probability in a filter created from
# scratch using the intersection of the two sets of identifiers.
#
# @param [Filter, #to_str] other
# a filter or byte string of equal size
# @return [Filter] a new filter
def and(other)
merge(other, :&)
end
alias_method :&, :and
##
# Merges the given `other` filter or byte string into this filter using
# a bitwise `AND` operation.
#
# @param [Filter, #to_str] other
# a filter or byte string of equal size
# @return [void] `self`
# @raise [TypeError] if the filter is frozen
def and!(other)
merge!(other, :&)
end
##
# Returns the difference of this filter and the given `other` filter
# or byte string.
#
# @param [Filter, #to_str] other
# a filter or byte string of equal size
# @return [Filter] a new filter
def xor(other)
merge(other, :^)
end
alias_method :^, :xor
##
# Merges the given `other` filter or byte string into this filter using
# a bitwise `XOR` operation.
#
# @param [Filter, #to_str] other
# a filter or byte string of equal size
# @return [void] `self`
# @raise [TypeError] if the filter is frozen
def xor!(other)
merge!(other, :^)
end
##
# Returns `self`.
#
# @return [Filter] `self`
def to_filter
self
end
##
# Returns the byte string representation of this filter.
#
# @return [String]
def to_str
bitmap.dup
end
##
# Returns the hexadecimal string representation of this filter.
#
# @param [Integer] base
# the numeric base to convert to: `2` or `16`
# @return [String]
# @raise [ArgumentError] if `base` is invalid
def to_s(base = 16)
case base
when 16 then bitmap.unpack('H*').first
when 2 then bitmap.unpack('B*').first
else raise ArgumentError, "invalid radix #{base}"
end
end
##
# Returns a developer-friendly representation of this filter.
#
# @return [String]
def inspect
super
end
##
# Serializes the filter to the given `output` stream or file.
#
# @param [File, IO, StringIO] output
# the output stream to write to
# @param [Hash{Symbol => Object}] options
# any additional options
# @option options [Boolean] :header (false)
# whether to write an initial Bitcache header
# @return [void] `self`
def dump(output, options = {})
output.write([MAGIC].pack('S')) if options[:header]
output.write([bytesize].pack('Q')) # uint64 in native byte order
output.write(bitmap)
return self
end
protected
##
# @private
# @return [Array]
# @see Marshal.dump
def marshal_dump
[@bitmap]
end
##
# @private
# @param [Array] data
# @return [void]
# @see Marshal.load
def marshal_load(data)
@bitmap = data.first
@bitsize = @bitmap.size * 8
end
# Load optimized method implementations when available:
#send(:include, Bitcache::FFI::Filter) if defined?(Bitcache::FFI::Filter)
end # Filter
end # Bitcache
| bendiken/bitcache | lib/bitcache/mri/filter.rb | Ruby | unlicense | 16,195 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
using RimWorld;
using Verse.AI;
namespace MountainMiner
{
class JobDriver_DrillUp : JobDriver
{
const int ticks = GenDate.TicksPerDay;
Building_MountainDrill comp => (Building_MountainDrill)TargetA.Thing;
protected override IEnumerable<Toil> MakeNewToils()
{
this.FailOn(() => {
if (comp.CanDrillNow()) return false;
return true;
});
yield return Toils_Reserve.Reserve(TargetIndex.A).FailOnDespawnedNullOrForbidden(TargetIndex.A);
yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch).FailOnDespawnedNullOrForbidden(TargetIndex.A);
Toil mine = new Toil();
mine.WithEffect(EffecterDefOf.Drill, TargetIndex.A);
mine.WithProgressBar(TargetIndex.A, () => comp.Progress);
mine.tickAction = delegate
{
var pawn = mine.actor;
comp.Drill(pawn.GetStatValue(StatDefOf.MiningSpeed) / ticks);
pawn.skills.Learn(SkillDefOf.Mining, 0.125f);
if (comp.Progress>=1)
{
comp.DrillWorkDone(pawn);
EndJobWith(JobCondition.Succeeded);
pawn.records.Increment(RecordDefOf.CellsMined);
}
};
mine.WithEffect(TargetThingA.def.repairEffect, TargetIndex.A);
mine.defaultCompleteMode = ToilCompleteMode.Never;
yield return mine;
}
}
}
| hunt3rkill3r/HcSK-HK | HcSK-HK/Mods/MountainMiner/Source/JobDriver_DrillUp.cs | C# | unlicense | 1,620 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Conveyor_JSONRPC_API._3._0._0
{
public class SliceCommand : Command
{
bool add_start_end;
string input_file;
ConveyorSliceJobMetadata job_metadata;
string output_file;
string profile_name;
string slicer_name;
ConveyorSlicerSettings slicer_settings;
string thumbnail_dir;
public SliceCommand(int RpcId, bool Add_start_end, string Input_file, ConveyorSliceJobMetadata Job_metadata, string Output_file,
string Profile_name, string Slicer_name, ConveyorSlicerSettings Slicer_settings,
string Thumbnail_dir)
{
rpcid = RpcId;
Recieved = false;
Reply = null;
add_start_end = Add_start_end;
input_file = Input_file;
job_metadata = Job_metadata;
output_file = Output_file;
profile_name = Profile_name;
slicer_name = Slicer_name;
slicer_settings = Slicer_settings;
thumbnail_dir = Thumbnail_dir;
}
public override string GetJSONString()
{
return ServerAPI.Slice(rpcid, add_start_end, input_file, job_metadata, output_file,
profile_name, slicer_name, slicer_settings,
thumbnail_dir);
}
}
}
| wildbillcat/RepRancher | Conveyor_JSONRPC_API/3.0.0/SliceCommand.cs | C# | unlicense | 1,430 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace MakerFarm.Models
{
public class Print
{
public long PrintId { get; set; } /* Generic Id for the Print Job */
[Display(Name = "File Name", Description = "The file name of the print submitted")]
public string FileName { get; set; } /* The file name of the print submitted */
[Display(Name = "User Name", Description = "User Name of the person whom submitted the print")]
public string UserName { get; set; } /* User ID of the person whom submitted the print */
[Display(Name = "Material", Description = "This is the Material(s) that should be used for each printer.")]
public string MaterialIds { get; set; } /* This is an array listing the MaterialIDs of the types of materials requested for the printer job */
[Display(Name = "Estimated Material Usage", Description = "Estimated amount of Material usage given by the software")]
public double EstMaterialUse { get; set; } /* The print cost originally estimated by the print software */
[DataType(DataType.Date)]
[Display(Name = "Submission Time", Description = "Time the Submission was made")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yy H:mm:ss}", ApplyFormatInEditMode = true)]
public DateTime SubmissionTime { get; set; } /* This is the time the print is submitted to the application */
[Range(1, int.MaxValue, ErrorMessage = "Value Should be between 1 and 2,147,483,647")]
[Display(Name = "Estimated Print Time (Minutes)", Description = "Estimated amount of time print will take in minutes")]
public int EstToolpathTime { get; set; } /* Estimated amount of time (in minutes) to complete the print job from the processing software */
[Display(Name = "Number of Authorized Attempts", Description = "Number of print attempts authorized to be tried at your cost.")]
public int AuthorizedAttempts { get; set; } /* Number of attempts that are requested to be attempted in at cost to the user. */
[Display(Name = "Printer Type", Description = "The Type of printer this print is made for")]
public int PrinterTypeId { get; set; } /* ID number of the printer type the file is meant for */
[Display(Name = "Staff Assisted Print", Description = "Denotes if a Printing staff member assisted with the submission of this print")]
public bool StaffAssistedPrint { get; set; } /* Denotes if a staff member assited with the print submission */
[Display(Name = "Processing Charge", Description = "Labor charge by the DM Office for the Processing of the file")]
public double ProcessingCharge { get; set; } /* The amount charge by the DM Office for assitance with prints */
public string Comment { get; set; } /*Commonly used to denote on multiple extruder machines which extruder gets */
[Display(Name = "Flagged Print", Description = "Denotes if a Print has been flagged by a staff member for some reason")]
public bool FlaggedPrint { get; set; }
[Display(Name = "Flagged Comment", Description = "This comment is set to note why a print was Flagged for future reference")]
public string FlaggedComment { get; set; } /*Commonly used to denote on multiple extruder machines which extruder gets */
[DataType(DataType.Date)]
[Display(Name = "Terms and Conditions", Description = "Time the Submission Terms and Conditions were agreed to")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yy H:mm:ss}", ApplyFormatInEditMode = true)]
public DateTime? TermsAndConditionsAgreement { get; set; } /*Commonly used to denote on multiple extruder machines which extruder gets */
[Display(Name = "Full Color Print", Description = "This denotes if you would like the print in full color, instead of the default monochrome material color.")]
public bool FullColorPrint { get; set; } /*Denotes if user wants a full color print*/
[Display(Name = "Print submitted by internal user?")]
public bool InternalUser { get; set; }
[Display(Name = "Print has been billed to user?")]
public bool BilledUser { get; set; }
public virtual PrinterType PrinterType { get; set; }
public virtual ICollection<PrintEvent> PrintEvents { get; set; }
public Printer GetLastPrinter()
{
Printer P = null;
foreach (PrintEvent E in PrintEvents)
{
if (!E.Printer.PrinterName.Equals("Null Printer"))
{
P = E.Printer;
}
}
return P;
}
public string GetPath()
{
string OriginalPath = string.Concat(AppDomain.CurrentDomain.GetData("DataDirectory"), "\\3DPrints\\", SubmissionTime.ToString("yyyy-MMM-d"), "\\", PrintId, "_", FileName);
return OriginalPath;
}
public string GetFlaggedPath()
{
string FlaggedPath = string.Concat(AppDomain.CurrentDomain.GetData("DataDirectory"), "\\Flagged\\", SubmissionTime.ToString("yyyy-MMM-d"), "\\", PrintId, "_", FileName);
return FlaggedPath;
}
}
} | wildbillcat/MakerFarm | MakerFarm/Models/PrintModel.cs | C# | unlicense | 5,297 |
'use strict';
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('gftApp'));
var MainCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
// place here mocked dependencies
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(MainCtrl.awesomeThings.length).toBe(3);
});
});
| murilobeltrame/gft | ui/test/spec/controllers/main.js | JavaScript | unlicense | 545 |
package com.smartgwt.mobile.client.internal.widgets.events;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HasHandlers;
public class ValuesSelectedEvent extends GwtEvent<ValuesSelectedHandler> {
private static Type<ValuesSelectedHandler> TYPE = null;
public static Type<ValuesSelectedHandler> getType() {
if (TYPE == null) TYPE = new Type<ValuesSelectedHandler>();
return TYPE;
}
public static <S extends HasValuesSelectedHandlers & HasHandlers> void fire(S source, Object[] values) {
if (TYPE != null) {
final ValuesSelectedEvent event = new ValuesSelectedEvent(values);
source.fireEvent(event);
}
}
private Object[] values;
private ValuesSelectedEvent(Object[] values) {
this.values = values;
}
public final Object[] getValues() {
return values;
}
@Override
public final Type<ValuesSelectedHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(ValuesSelectedHandler handler) {
handler._onValuesSelected(this);
}
}
| will-gilbert/SmartGWT-Mobile | mobile/src/main/java/com/smartgwt/mobile/client/internal/widgets/events/ValuesSelectedEvent.java | Java | unlicense | 1,137 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("03_Array_Manipulator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("03_Array_Manipulator")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c4ec9d1f-b958-4770-b8f0-632277e546ba")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| GoldenR1618/SoftUni-Exercises-and-Exams | 03.Programming_Fundamentals/05_Lists/Exercises/03_Array_Manipulator/Properties/AssemblyInfo.cs | C# | unlicense | 1,411 |
export { piMatch } from './pimatch'
export { titleCapitalize } from './titlecapitalization'
export { wordScore } from './wordscore' | mattmazzola/interview-questions | src/pluralsight/index.ts | TypeScript | unlicense | 131 |
/**
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2009-2010], VMware, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
*/
package org.hyperic.hq.bizapp.shared;
import java.util.List;
import java.util.Map;
import javax.security.auth.login.LoginException;
import org.hyperic.hq.appdef.shared.AppdefEntityID;
import org.hyperic.hq.appdef.shared.AppdefEntityNotFoundException;
import org.hyperic.hq.appdef.shared.AppdefEntityTypeID;
import org.hyperic.hq.auth.shared.SessionException;
import org.hyperic.hq.auth.shared.SessionNotFoundException;
import org.hyperic.hq.auth.shared.SessionTimeoutException;
import org.hyperic.hq.authz.server.session.AuthzSubject;
import org.hyperic.hq.authz.shared.PermissionException;
import org.hyperic.hq.common.ApplicationException;
import org.hyperic.hq.common.DuplicateObjectException;
import org.hyperic.hq.escalation.server.session.Escalatable;
import org.hyperic.hq.escalation.server.session.Escalation;
import org.hyperic.hq.escalation.server.session.EscalationAlertType;
import org.hyperic.hq.escalation.server.session.EscalationState;
import org.hyperic.hq.events.ActionConfigInterface;
import org.hyperic.hq.events.ActionCreateException;
import org.hyperic.hq.events.ActionExecuteException;
import org.hyperic.hq.events.AlertConditionCreateException;
import org.hyperic.hq.events.AlertDefinitionCreateException;
import org.hyperic.hq.events.AlertNotFoundException;
import org.hyperic.hq.events.MaintenanceEvent;
import org.hyperic.hq.events.TriggerCreateException;
import org.hyperic.hq.events.server.session.Action;
import org.hyperic.hq.events.server.session.Alert;
import org.hyperic.hq.events.shared.ActionValue;
import org.hyperic.hq.events.shared.AlertDefinitionValue;
import org.hyperic.util.ConfigPropertyException;
import org.hyperic.util.config.ConfigResponse;
import org.hyperic.util.config.ConfigSchema;
import org.hyperic.util.config.InvalidOptionException;
import org.hyperic.util.config.InvalidOptionValueException;
import org.hyperic.util.pager.PageControl;
import org.hyperic.util.pager.PageList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.quartz.SchedulerException;
import org.springframework.transaction.annotation.Transactional;
/**
* Local interface for EventsBoss.
*/
public interface EventsBoss {
/**
* Get the number of alerts for the given array of AppdefEntityID's
*/
public int[] getAlertCount(int sessionID, org.hyperic.hq.appdef.shared.AppdefEntityID[] ids)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Get the number of alerts for the given array of AppdefEntityID's, mapping AppdefEntityID to it's alerts count
*
*/
@Transactional(readOnly = true)
public Map<AppdefEntityID, Integer> getAlertCountMapped(int sessionID, AppdefEntityID[] ids)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Create an alert definition
*/
public AlertDefinitionValue createAlertDefinition(int sessionID, AlertDefinitionValue adval)
throws org.hyperic.hq.events.AlertDefinitionCreateException, PermissionException,
InvalidOptionException, InvalidOptionValueException, SessionException;
/**
* Create an alert definition for a resource type
*/
public AlertDefinitionValue createResourceTypeAlertDefinition(int sessionID,
AppdefEntityTypeID aetid,
AlertDefinitionValue adval)
throws org.hyperic.hq.events.AlertDefinitionCreateException, PermissionException,
InvalidOptionException, InvalidOptionValueException, SessionNotFoundException,
SessionTimeoutException;
public Action createAction(int sessionID, Integer adid, String className, ConfigResponse config)
throws SessionNotFoundException, SessionTimeoutException, ActionCreateException,
PermissionException;
/**
* Activate/deactivate a collection of alert definitions
*/
public void activateAlertDefinitions(int sessionID, java.lang.Integer[] ids, boolean activate)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Activate or deactivate alert definitions by AppdefEntityID.
*/
public void activateAlertDefinitions(int sessionID,
org.hyperic.hq.appdef.shared.AppdefEntityID[] eids,
boolean activate) throws SessionNotFoundException,
SessionTimeoutException, AppdefEntityNotFoundException, PermissionException;
/**
* Update just the basics
*/
public void updateAlertDefinitionBasic(int sessionID, Integer alertDefId, String name,
String desc, int priority, boolean activate)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
public void updateAlertDefinition(int sessionID, AlertDefinitionValue adval)
throws TriggerCreateException, InvalidOptionException, InvalidOptionValueException,
AlertConditionCreateException, ActionCreateException, SessionNotFoundException,
SessionTimeoutException;
/**
* Get actions for a given alert.
* @param alertId the alert id
*/
public List<ActionValue> getActionsForAlert(int sessionId, Integer alertId)
throws SessionNotFoundException, SessionTimeoutException;
/**
* Update an action
*/
public void updateAction(int sessionID, ActionValue aval) throws SessionNotFoundException,
SessionTimeoutException;
/**
* Delete a collection of alert definitions
*/
public void deleteAlertDefinitions(int sessionID, java.lang.Integer[] ids)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Delete list of alerts
*/
public void deleteAlerts(int sessionID, java.lang.Integer[] ids)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Delete all alerts for a list of alert definitions
*
*/
public int deleteAlertsForDefinitions(int sessionID, java.lang.Integer[] adids)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Get an alert definition by ID
*/
public AlertDefinitionValue getAlertDefinition(int sessionID, Integer id)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Find an alert by ID
*/
public Alert getAlert(int sessionID, Integer id) throws SessionNotFoundException,
SessionTimeoutException, AlertNotFoundException;
/**
* Get a list of all alert definitions
*/
public PageList<AlertDefinitionValue> findAllAlertDefinitions(int sessionID)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Get a collection of alert definitions for a resource
*/
public PageList<AlertDefinitionValue> findAlertDefinitions(int sessionID, AppdefEntityID id,
PageControl pc)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Get a collection of alert definitions for a resource or resource type
*/
public PageList<AlertDefinitionValue> findAlertDefinitions(int sessionID,
AppdefEntityTypeID id, PageControl pc)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Find all alert definition names for a resource
* @return Map of AlertDefinition names and IDs
*/
public Map<String, Integer> findAlertDefinitionNames(int sessionID, AppdefEntityID id,
Integer parentId)
throws SessionNotFoundException, SessionTimeoutException, AppdefEntityNotFoundException,
PermissionException;
/**
* Find all alerts for an appdef resource
*/
public PageList<Alert> findAlerts(int sessionID, AppdefEntityID id, long begin, long end,
PageControl pc) throws SessionNotFoundException,
SessionTimeoutException, PermissionException;
/**
* Search alerts given a set of criteria
* @param username the username
* @param count the maximum number of alerts to return
* @param priority allowable values: 0 (all), 1, 2, or 3
* @param timeRange the amount of time from current time to include
* @param ids the IDs of resources to include or null for ALL
* @return a list of {@link Escalatable}s
*/
public List<Escalatable> findRecentAlerts(String username, int count, int priority,
long timeRange,
org.hyperic.hq.appdef.shared.AppdefEntityID[] ids)
throws LoginException, ApplicationException, ConfigPropertyException;
/**
* Search recent alerts given a set of criteria
* @param sessionID the session token
* @param count the maximum number of alerts to return
* @param priority allowable values: 0 (all), 1, 2, or 3
* @param timeRange the amount of time from current time to include
* @param ids the IDs of resources to include or null for ALL
* @return a list of {@link Escalatable}s
*/
public List<Escalatable> findRecentAlerts(int sessionID, int count, int priority,
long timeRange,
org.hyperic.hq.appdef.shared.AppdefEntityID[] ids)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Get config schema info for an action class
*/
public ConfigSchema getActionConfigSchema(int sessionID, String actionClass)
throws SessionNotFoundException, SessionTimeoutException,
org.hyperic.util.config.EncodingException;
/**
* Get config schema info for a trigger class
*/
public ConfigSchema getRegisteredTriggerConfigSchema(int sessionID, String triggerClass)
throws SessionNotFoundException, SessionTimeoutException,
org.hyperic.util.config.EncodingException;
public void deleteEscalationByName(int sessionID, String name) throws SessionTimeoutException,
SessionNotFoundException, PermissionException, org.hyperic.hq.common.ApplicationException;
public void deleteEscalationById(int sessionID, Integer id) throws SessionTimeoutException,
SessionNotFoundException, PermissionException, org.hyperic.hq.common.ApplicationException;
/**
* remove escalation by id
*/
public void deleteEscalationById(int sessionID, java.lang.Integer[] ids)
throws SessionTimeoutException, SessionNotFoundException, PermissionException,
org.hyperic.hq.common.ApplicationException;
/**
* retrieve escalation name by alert definition id.
*/
public Integer getEscalationIdByAlertDefId(int sessionID, Integer id,
EscalationAlertType alertType)
throws SessionTimeoutException, SessionNotFoundException, PermissionException;
/**
* set escalation name by alert definition id.
*/
public void setEscalationByAlertDefId(int sessionID, Integer id, Integer escId,
EscalationAlertType alertType)
throws SessionTimeoutException, SessionNotFoundException, PermissionException;
/**
* unset escalation by alert definition id.
*/
public void unsetEscalationByAlertDefId(int sessionID, Integer id, EscalationAlertType alertType)
throws SessionTimeoutException, SessionNotFoundException, PermissionException;
/**
* retrieve escalation JSONObject by alert definition id.
*/
public JSONObject jsonEscalationByAlertDefId(int sessionID, Integer id,
EscalationAlertType alertType)
throws org.hyperic.hq.auth.shared.SessionException, PermissionException, JSONException;
/**
* retrieve escalation object by escalation id.
*/
public Escalation findEscalationById(int sessionID, Integer id) throws SessionTimeoutException,
SessionNotFoundException, PermissionException;
public void addAction(int sessionID, Escalation e, ActionConfigInterface cfg, long waitTime)
throws SessionTimeoutException, SessionNotFoundException, PermissionException;
public void removeAction(int sessionID, Integer escId, Integer actId)
throws SessionTimeoutException, SessionNotFoundException, PermissionException;
/**
* Retrieve a list of {@link EscalationState}s, representing the active
* escalations in the system.
*/
public List<EscalationState> getActiveEscalations(int sessionId, int maxEscalations)
throws org.hyperic.hq.auth.shared.SessionException;
/**
* Gets the escalatable associated with the specified state
*/
public Escalatable getEscalatable(int sessionId, EscalationState state)
throws org.hyperic.hq.auth.shared.SessionException;
/**
* retrieve all escalation policy names as a Array of JSONObject. Escalation
* json finders begin with json* to be consistent with DAO finder convention
*/
public JSONArray listAllEscalationName(int sessionID) throws JSONException,
SessionTimeoutException, SessionNotFoundException, PermissionException;
/**
* Create a new escalation. If alertDefId is non-null, the escalation will
* also be associated with the given alert definition.
*/
public Escalation createEscalation(int sessionID, String name, String desc, boolean allowPause,
long maxWaitTime, boolean notifyAll, boolean repeat,
EscalationAlertType alertType, Integer alertDefId)
throws SessionTimeoutException, SessionNotFoundException, PermissionException,
DuplicateObjectException;
/**
* Update basic escalation properties
*/
public void updateEscalation(int sessionID, Escalation escalation, String name, String desc,
long maxWait, boolean pausable, boolean notifyAll, boolean repeat)
throws SessionTimeoutException, SessionNotFoundException, PermissionException,
DuplicateObjectException;
public boolean acknowledgeAlert(int sessionID, EscalationAlertType alertType, Integer alertID,
long pauseWaitTime, String moreInfo)
throws SessionTimeoutException, SessionNotFoundException, PermissionException,
ActionExecuteException;
/**
* Fix a single alert. Method is "NotSupported" since all the alert fixes
* may take longer than the transaction timeout. No need for a transaction
* in this context.
*/
public void fixAlert(int sessionID, EscalationAlertType alertType, Integer alertID,
String moreInfo) throws SessionTimeoutException, SessionNotFoundException,
PermissionException, ActionExecuteException;
/**
* Fix a batch of alerts. Method is "NotSupported" since all the alert fixes
* may take longer than the transaction timeout. No need for a transaction
* in this context.
*/
public void fixAlert(int sessionID, EscalationAlertType alertType, Integer alertID,
String moreInfo, boolean fixAllPrevious) throws SessionTimeoutException,
SessionNotFoundException, PermissionException, ActionExecuteException;
/**
* Get the last fix if available
*/
public String getLastFix(int sessionID, Integer defId) throws SessionNotFoundException,
SessionTimeoutException, PermissionException;
/**
* Get a maintenance event by group id
*/
public MaintenanceEvent getMaintenanceEvent(int sessionId, Integer groupId)
throws SessionNotFoundException, SessionTimeoutException, PermissionException,
SchedulerException;
/**
* Schedule a maintenance event
*/
public MaintenanceEvent scheduleMaintenanceEvent(int sessionId, MaintenanceEvent event)
throws SessionNotFoundException, SessionTimeoutException, PermissionException,
SchedulerException;
/**
* Schedule a maintenance event
*/
public void unscheduleMaintenanceEvent(int sessionId, MaintenanceEvent event)
throws SessionNotFoundException, SessionTimeoutException, PermissionException,
SchedulerException;
}
| cc14514/hq6 | hq-server/src/main/java/org/hyperic/hq/bizapp/shared/EventsBoss.java | Java | unlicense | 17,838 |
# coding: utf-8
from __future__ import unicode_literals
import base64
import functools
import json
import re
import itertools
from .common import InfoExtractor
from ..compat import (
compat_kwargs,
compat_HTTPError,
compat_str,
compat_urlparse,
)
from ..utils import (
clean_html,
determine_ext,
dict_get,
ExtractorError,
js_to_json,
int_or_none,
merge_dicts,
OnDemandPagedList,
parse_filesize,
RegexNotFoundError,
sanitized_Request,
smuggle_url,
std_headers,
str_or_none,
try_get,
unified_timestamp,
unsmuggle_url,
urlencode_postdata,
urljoin,
unescapeHTML,
)
class VimeoBaseInfoExtractor(InfoExtractor):
_NETRC_MACHINE = 'vimeo'
_LOGIN_REQUIRED = False
_LOGIN_URL = 'https://vimeo.com/log_in'
def _login(self):
username, password = self._get_login_info()
if username is None:
if self._LOGIN_REQUIRED:
raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
return
webpage = self._download_webpage(
self._LOGIN_URL, None, 'Downloading login page')
token, vuid = self._extract_xsrft_and_vuid(webpage)
data = {
'action': 'login',
'email': username,
'password': password,
'service': 'vimeo',
'token': token,
}
self._set_vimeo_cookie('vuid', vuid)
try:
self._download_webpage(
self._LOGIN_URL, None, 'Logging in',
data=urlencode_postdata(data), headers={
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': self._LOGIN_URL,
})
except ExtractorError as e:
if isinstance(e.cause, compat_HTTPError) and e.cause.code == 418:
raise ExtractorError(
'Unable to log in: bad username or password',
expected=True)
raise ExtractorError('Unable to log in')
def _verify_video_password(self, url, video_id, webpage):
password = self._downloader.params.get('videopassword')
if password is None:
raise ExtractorError('This video is protected by a password, use the --video-password option', expected=True)
token, vuid = self._extract_xsrft_and_vuid(webpage)
data = urlencode_postdata({
'password': password,
'token': token,
})
if url.startswith('http://'):
# vimeo only supports https now, but the user can give an http url
url = url.replace('http://', 'https://')
password_request = sanitized_Request(url + '/password', data)
password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
password_request.add_header('Referer', url)
self._set_vimeo_cookie('vuid', vuid)
return self._download_webpage(
password_request, video_id,
'Verifying the password', 'Wrong password')
def _extract_xsrft_and_vuid(self, webpage):
xsrft = self._search_regex(
r'(?:(?P<q1>["\'])xsrft(?P=q1)\s*:|xsrft\s*[=:])\s*(?P<q>["\'])(?P<xsrft>.+?)(?P=q)',
webpage, 'login token', group='xsrft')
vuid = self._search_regex(
r'["\']vuid["\']\s*:\s*(["\'])(?P<vuid>.+?)\1',
webpage, 'vuid', group='vuid')
return xsrft, vuid
def _extract_vimeo_config(self, webpage, video_id, *args, **kwargs):
vimeo_config = self._search_regex(
r'vimeo\.config\s*=\s*(?:({.+?})|_extend\([^,]+,\s+({.+?})\));',
webpage, 'vimeo config', *args, **compat_kwargs(kwargs))
if vimeo_config:
return self._parse_json(vimeo_config, video_id)
def _set_vimeo_cookie(self, name, value):
self._set_cookie('vimeo.com', name, value)
def _vimeo_sort_formats(self, formats):
# Bitrates are completely broken. Single m3u8 may contain entries in kbps and bps
# at the same time without actual units specified. This lead to wrong sorting.
self._sort_formats(formats, field_preference=('preference', 'height', 'width', 'fps', 'tbr', 'format_id'))
def _parse_config(self, config, video_id):
video_data = config['video']
video_title = video_data['title']
live_event = video_data.get('live_event') or {}
is_live = live_event.get('status') == 'started'
formats = []
config_files = video_data.get('files') or config['request'].get('files', {})
for f in config_files.get('progressive', []):
video_url = f.get('url')
if not video_url:
continue
formats.append({
'url': video_url,
'format_id': 'http-%s' % f.get('quality'),
'width': int_or_none(f.get('width')),
'height': int_or_none(f.get('height')),
'fps': int_or_none(f.get('fps')),
'tbr': int_or_none(f.get('bitrate')),
})
# TODO: fix handling of 308 status code returned for live archive manifest requests
for files_type in ('hls', 'dash'):
for cdn_name, cdn_data in config_files.get(files_type, {}).get('cdns', {}).items():
manifest_url = cdn_data.get('url')
if not manifest_url:
continue
format_id = '%s-%s' % (files_type, cdn_name)
if files_type == 'hls':
formats.extend(self._extract_m3u8_formats(
manifest_url, video_id, 'mp4',
'm3u8' if is_live else 'm3u8_native', m3u8_id=format_id,
note='Downloading %s m3u8 information' % cdn_name,
fatal=False))
elif files_type == 'dash':
mpd_pattern = r'/%s/(?:sep/)?video/' % video_id
mpd_manifest_urls = []
if re.search(mpd_pattern, manifest_url):
for suffix, repl in (('', 'video'), ('_sep', 'sep/video')):
mpd_manifest_urls.append((format_id + suffix, re.sub(
mpd_pattern, '/%s/%s/' % (video_id, repl), manifest_url)))
else:
mpd_manifest_urls = [(format_id, manifest_url)]
for f_id, m_url in mpd_manifest_urls:
if 'json=1' in m_url:
real_m_url = (self._download_json(m_url, video_id, fatal=False) or {}).get('url')
if real_m_url:
m_url = real_m_url
mpd_formats = self._extract_mpd_formats(
m_url.replace('/master.json', '/master.mpd'), video_id, f_id,
'Downloading %s MPD information' % cdn_name,
fatal=False)
for f in mpd_formats:
if f.get('vcodec') == 'none':
f['preference'] = -50
elif f.get('acodec') == 'none':
f['preference'] = -40
formats.extend(mpd_formats)
live_archive = live_event.get('archive') or {}
live_archive_source_url = live_archive.get('source_url')
if live_archive_source_url and live_archive.get('status') == 'done':
formats.append({
'format_id': 'live-archive-source',
'url': live_archive_source_url,
'preference': 1,
})
subtitles = {}
text_tracks = config['request'].get('text_tracks')
if text_tracks:
for tt in text_tracks:
subtitles[tt['lang']] = [{
'ext': 'vtt',
'url': urljoin('https://vimeo.com', tt['url']),
}]
thumbnails = []
if not is_live:
for key, thumb in video_data.get('thumbs', {}).items():
thumbnails.append({
'id': key,
'width': int_or_none(key),
'url': thumb,
})
thumbnail = video_data.get('thumbnail')
if thumbnail:
thumbnails.append({
'url': thumbnail,
})
owner = video_data.get('owner') or {}
video_uploader_url = owner.get('url')
return {
'id': str_or_none(video_data.get('id')) or video_id,
'title': self._live_title(video_title) if is_live else video_title,
'uploader': owner.get('name'),
'uploader_id': video_uploader_url.split('/')[-1] if video_uploader_url else None,
'uploader_url': video_uploader_url,
'thumbnails': thumbnails,
'duration': int_or_none(video_data.get('duration')),
'formats': formats,
'subtitles': subtitles,
'is_live': is_live,
}
def _extract_original_format(self, url, video_id):
download_data = self._download_json(
url, video_id, fatal=False,
query={'action': 'load_download_config'},
headers={'X-Requested-With': 'XMLHttpRequest'})
if download_data:
source_file = download_data.get('source_file')
if isinstance(source_file, dict):
download_url = source_file.get('download_url')
if download_url and not source_file.get('is_cold') and not source_file.get('is_defrosting'):
source_name = source_file.get('public_name', 'Original')
if self._is_valid_url(download_url, video_id, '%s video' % source_name):
ext = (try_get(
source_file, lambda x: x['extension'],
compat_str) or determine_ext(
download_url, None) or 'mp4').lower()
return {
'url': download_url,
'ext': ext,
'width': int_or_none(source_file.get('width')),
'height': int_or_none(source_file.get('height')),
'filesize': parse_filesize(source_file.get('size')),
'format_id': source_name,
'preference': 1,
}
class VimeoIE(VimeoBaseInfoExtractor):
"""Information extractor for vimeo.com."""
# _VALID_URL matches Vimeo URLs
_VALID_URL = r'''(?x)
https?://
(?:
(?:
www|
player
)
\.
)?
vimeo(?:pro)?\.com/
(?!(?:channels|album|showcase)/[^/?#]+/?(?:$|[?#])|[^/]+/review/|ondemand/)
(?:.*?/)?
(?:
(?:
play_redirect_hls|
moogaloop\.swf)\?clip_id=
)?
(?:videos?/)?
(?P<id>[0-9]+)
(?:/[\da-f]+)?
/?(?:[?&].*)?(?:[#].*)?$
'''
IE_NAME = 'vimeo'
_TESTS = [
{
'url': 'http://vimeo.com/56015672#at=0',
'md5': '8879b6cc097e987f02484baf890129e5',
'info_dict': {
'id': '56015672',
'ext': 'mp4',
'title': "youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
'description': 'md5:2d3305bad981a06ff79f027f19865021',
'timestamp': 1355990239,
'upload_date': '20121220',
'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user7108434',
'uploader_id': 'user7108434',
'uploader': 'Filippo Valsorda',
'duration': 10,
'license': 'by-sa',
},
'params': {
'format': 'best[protocol=https]',
},
},
{
'url': 'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
'md5': '3b5ca6aa22b60dfeeadf50b72e44ed82',
'note': 'Vimeo Pro video (#1197)',
'info_dict': {
'id': '68093876',
'ext': 'mp4',
'uploader_url': r're:https?://(?:www\.)?vimeo\.com/openstreetmapus',
'uploader_id': 'openstreetmapus',
'uploader': 'OpenStreetMap US',
'title': 'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
'description': 'md5:2c362968038d4499f4d79f88458590c1',
'duration': 1595,
'upload_date': '20130610',
'timestamp': 1370893156,
},
'params': {
'format': 'best[protocol=https]',
},
},
{
'url': 'http://player.vimeo.com/video/54469442',
'md5': '619b811a4417aa4abe78dc653becf511',
'note': 'Videos that embed the url in the player page',
'info_dict': {
'id': '54469442',
'ext': 'mp4',
'title': 'Kathy Sierra: Building the minimum Badass User, Business of Software 2012',
'uploader': 'The BLN & Business of Software',
'uploader_url': r're:https?://(?:www\.)?vimeo\.com/theblnbusinessofsoftware',
'uploader_id': 'theblnbusinessofsoftware',
'duration': 3610,
'description': None,
},
'params': {
'format': 'best[protocol=https]',
},
'expected_warnings': ['Unable to download JSON metadata'],
},
{
'url': 'http://vimeo.com/68375962',
'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
'note': 'Video protected with password',
'info_dict': {
'id': '68375962',
'ext': 'mp4',
'title': 'youtube-dl password protected test video',
'timestamp': 1371200155,
'upload_date': '20130614',
'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user18948128',
'uploader_id': 'user18948128',
'uploader': 'Jaime Marquínez Ferrándiz',
'duration': 10,
'description': 'md5:dca3ea23adb29ee387127bc4ddfce63f',
},
'params': {
'format': 'best[protocol=https]',
'videopassword': 'youtube-dl',
},
},
{
'url': 'http://vimeo.com/channels/keypeele/75629013',
'md5': '2f86a05afe9d7abc0b9126d229bbe15d',
'info_dict': {
'id': '75629013',
'ext': 'mp4',
'title': 'Key & Peele: Terrorist Interrogation',
'description': 'md5:8678b246399b070816b12313e8b4eb5c',
'uploader_url': r're:https?://(?:www\.)?vimeo\.com/atencio',
'uploader_id': 'atencio',
'uploader': 'Peter Atencio',
'channel_id': 'keypeele',
'channel_url': r're:https?://(?:www\.)?vimeo\.com/channels/keypeele',
'timestamp': 1380339469,
'upload_date': '20130928',
'duration': 187,
},
'expected_warnings': ['Unable to download JSON metadata'],
},
{
'url': 'http://vimeo.com/76979871',
'note': 'Video with subtitles',
'info_dict': {
'id': '76979871',
'ext': 'mp4',
'title': 'The New Vimeo Player (You Know, For Videos)',
'description': 'md5:2ec900bf97c3f389378a96aee11260ea',
'timestamp': 1381846109,
'upload_date': '20131015',
'uploader_url': r're:https?://(?:www\.)?vimeo\.com/staff',
'uploader_id': 'staff',
'uploader': 'Vimeo Staff',
'duration': 62,
}
},
{
# from https://www.ouya.tv/game/Pier-Solar-and-the-Great-Architects/
'url': 'https://player.vimeo.com/video/98044508',
'note': 'The js code contains assignments to the same variable as the config',
'info_dict': {
'id': '98044508',
'ext': 'mp4',
'title': 'Pier Solar OUYA Official Trailer',
'uploader': 'Tulio Gonçalves',
'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user28849593',
'uploader_id': 'user28849593',
},
},
{
# contains original format
'url': 'https://vimeo.com/33951933',
'md5': '53c688fa95a55bf4b7293d37a89c5c53',
'info_dict': {
'id': '33951933',
'ext': 'mp4',
'title': 'FOX CLASSICS - Forever Classic ID - A Full Minute',
'uploader': 'The DMCI',
'uploader_url': r're:https?://(?:www\.)?vimeo\.com/dmci',
'uploader_id': 'dmci',
'timestamp': 1324343742,
'upload_date': '20111220',
'description': 'md5:ae23671e82d05415868f7ad1aec21147',
},
},
{
# only available via https://vimeo.com/channels/tributes/6213729 and
# not via https://vimeo.com/6213729
'url': 'https://vimeo.com/channels/tributes/6213729',
'info_dict': {
'id': '6213729',
'ext': 'mp4',
'title': 'Vimeo Tribute: The Shining',
'uploader': 'Casey Donahue',
'uploader_url': r're:https?://(?:www\.)?vimeo\.com/caseydonahue',
'uploader_id': 'caseydonahue',
'channel_url': r're:https?://(?:www\.)?vimeo\.com/channels/tributes',
'channel_id': 'tributes',
'timestamp': 1250886430,
'upload_date': '20090821',
'description': 'md5:bdbf314014e58713e6e5b66eb252f4a6',
},
'params': {
'skip_download': True,
},
'expected_warnings': ['Unable to download JSON metadata'],
},
{
# redirects to ondemand extractor and should be passed through it
# for successful extraction
'url': 'https://vimeo.com/73445910',
'info_dict': {
'id': '73445910',
'ext': 'mp4',
'title': 'The Reluctant Revolutionary',
'uploader': '10Ft Films',
'uploader_url': r're:https?://(?:www\.)?vimeo\.com/tenfootfilms',
'uploader_id': 'tenfootfilms',
'description': 'md5:0fa704e05b04f91f40b7f3ca2e801384',
'upload_date': '20130830',
'timestamp': 1377853339,
},
'params': {
'skip_download': True,
},
'expected_warnings': ['Unable to download JSON metadata'],
},
{
'url': 'http://player.vimeo.com/video/68375962',
'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
'info_dict': {
'id': '68375962',
'ext': 'mp4',
'title': 'youtube-dl password protected test video',
'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user18948128',
'uploader_id': 'user18948128',
'uploader': 'Jaime Marquínez Ferrándiz',
'duration': 10,
},
'params': {
'format': 'best[protocol=https]',
'videopassword': 'youtube-dl',
},
},
{
'url': 'http://vimeo.com/moogaloop.swf?clip_id=2539741',
'only_matching': True,
},
{
'url': 'https://vimeo.com/109815029',
'note': 'Video not completely processed, "failed" seed status',
'only_matching': True,
},
{
'url': 'https://vimeo.com/groups/travelhd/videos/22439234',
'only_matching': True,
},
{
'url': 'https://vimeo.com/album/2632481/video/79010983',
'only_matching': True,
},
{
# source file returns 403: Forbidden
'url': 'https://vimeo.com/7809605',
'only_matching': True,
},
{
'url': 'https://vimeo.com/160743502/abd0e13fb4',
'only_matching': True,
}
# https://gettingthingsdone.com/workflowmap/
# vimeo embed with check-password page protected by Referer header
]
@staticmethod
def _smuggle_referrer(url, referrer_url):
return smuggle_url(url, {'http_headers': {'Referer': referrer_url}})
@staticmethod
def _extract_urls(url, webpage):
urls = []
# Look for embedded (iframe) Vimeo player
for mobj in re.finditer(
r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//player\.vimeo\.com/video/\d+.*?)\1',
webpage):
urls.append(VimeoIE._smuggle_referrer(unescapeHTML(mobj.group('url')), url))
PLAIN_EMBED_RE = (
# Look for embedded (swf embed) Vimeo player
r'<embed[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?vimeo\.com/moogaloop\.swf.+?)\1',
# Look more for non-standard embedded Vimeo player
r'<video[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?vimeo\.com/[0-9]+)\1',
)
for embed_re in PLAIN_EMBED_RE:
for mobj in re.finditer(embed_re, webpage):
urls.append(mobj.group('url'))
return urls
@staticmethod
def _extract_url(url, webpage):
urls = VimeoIE._extract_urls(url, webpage)
return urls[0] if urls else None
def _verify_player_video_password(self, url, video_id, headers):
password = self._downloader.params.get('videopassword')
if password is None:
raise ExtractorError('This video is protected by a password, use the --video-password option', expected=True)
data = urlencode_postdata({
'password': base64.b64encode(password.encode()),
})
headers = merge_dicts(headers, {
'Content-Type': 'application/x-www-form-urlencoded',
})
checked = self._download_json(
url + '/check-password', video_id,
'Verifying the password', data=data, headers=headers)
if checked is False:
raise ExtractorError('Wrong video password', expected=True)
return checked
def _real_initialize(self):
self._login()
def _real_extract(self, url):
url, data = unsmuggle_url(url, {})
headers = std_headers.copy()
if 'http_headers' in data:
headers.update(data['http_headers'])
if 'Referer' not in headers:
headers['Referer'] = url
channel_id = self._search_regex(
r'vimeo\.com/channels/([^/]+)', url, 'channel id', default=None)
# Extract ID from URL
video_id = self._match_id(url)
orig_url = url
is_pro = 'vimeopro.com/' in url
is_player = '://player.vimeo.com/video/' in url
if is_pro:
# some videos require portfolio_id to be present in player url
# https://github.com/ytdl-org/youtube-dl/issues/20070
url = self._extract_url(url, self._download_webpage(url, video_id))
if not url:
url = 'https://vimeo.com/' + video_id
elif is_player:
url = 'https://player.vimeo.com/video/' + video_id
elif any(p in url for p in ('play_redirect_hls', 'moogaloop.swf')):
url = 'https://vimeo.com/' + video_id
try:
# Retrieve video webpage to extract further information
webpage, urlh = self._download_webpage_handle(
url, video_id, headers=headers)
redirect_url = urlh.geturl()
except ExtractorError as ee:
if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
errmsg = ee.cause.read()
if b'Because of its privacy settings, this video cannot be played here' in errmsg:
raise ExtractorError(
'Cannot download embed-only video without embedding '
'URL. Please call youtube-dl with the URL of the page '
'that embeds this video.',
expected=True)
raise
# Now we begin extracting as much information as we can from what we
# retrieved. First we extract the information common to all extractors,
# and latter we extract those that are Vimeo specific.
self.report_extraction(video_id)
vimeo_config = self._extract_vimeo_config(webpage, video_id, default=None)
if vimeo_config:
seed_status = vimeo_config.get('seed_status', {})
if seed_status.get('state') == 'failed':
raise ExtractorError(
'%s said: %s' % (self.IE_NAME, seed_status['title']),
expected=True)
cc_license = None
timestamp = None
video_description = None
# Extract the config JSON
try:
try:
config_url = self._html_search_regex(
r' data-config-url="(.+?)"', webpage,
'config URL', default=None)
if not config_url:
# Sometimes new react-based page is served instead of old one that require
# different config URL extraction approach (see
# https://github.com/ytdl-org/youtube-dl/pull/7209)
page_config = self._parse_json(self._search_regex(
r'vimeo\.(?:clip|vod_title)_page_config\s*=\s*({.+?});',
webpage, 'page config'), video_id)
config_url = page_config['player']['config_url']
cc_license = page_config.get('cc_license')
timestamp = try_get(
page_config, lambda x: x['clip']['uploaded_on'],
compat_str)
video_description = clean_html(dict_get(
page_config, ('description', 'description_html_escaped')))
config = self._download_json(config_url, video_id)
except RegexNotFoundError:
# For pro videos or player.vimeo.com urls
# We try to find out to which variable is assigned the config dic
m_variable_name = re.search(r'(\w)\.video\.id', webpage)
if m_variable_name is not None:
config_re = [r'%s=({[^}].+?});' % re.escape(m_variable_name.group(1))]
else:
config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
config_re.append(r'\bvar\s+r\s*=\s*({.+?})\s*;')
config_re.append(r'\bconfig\s*=\s*({.+?})\s*;')
config = self._search_regex(config_re, webpage, 'info section',
flags=re.DOTALL)
config = json.loads(config)
except Exception as e:
if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
if re.search(r'<form[^>]+?id="pw_form"', webpage) is not None:
if '_video_password_verified' in data:
raise ExtractorError('video password verification failed!')
self._verify_video_password(redirect_url, video_id, webpage)
return self._real_extract(
smuggle_url(redirect_url, {'_video_password_verified': 'verified'}))
else:
raise ExtractorError('Unable to extract info section',
cause=e)
else:
if config.get('view') == 4:
config = self._verify_player_video_password(redirect_url, video_id, headers)
vod = config.get('video', {}).get('vod', {})
def is_rented():
if '>You rented this title.<' in webpage:
return True
if config.get('user', {}).get('purchased'):
return True
for purchase_option in vod.get('purchase_options', []):
if purchase_option.get('purchased'):
return True
label = purchase_option.get('label_string')
if label and (label.startswith('You rented this') or label.endswith(' remaining')):
return True
return False
if is_rented() and vod.get('is_trailer'):
feature_id = vod.get('feature_id')
if feature_id and not data.get('force_feature_id', False):
return self.url_result(smuggle_url(
'https://player.vimeo.com/player/%s' % feature_id,
{'force_feature_id': True}), 'Vimeo')
# Extract video description
if not video_description:
video_description = self._html_search_regex(
r'(?s)<div\s+class="[^"]*description[^"]*"[^>]*>(.*?)</div>',
webpage, 'description', default=None)
if not video_description:
video_description = self._html_search_meta(
'description', webpage, default=None)
if not video_description and is_pro:
orig_webpage = self._download_webpage(
orig_url, video_id,
note='Downloading webpage for description',
fatal=False)
if orig_webpage:
video_description = self._html_search_meta(
'description', orig_webpage, default=None)
if not video_description and not is_player:
self._downloader.report_warning('Cannot find video description')
# Extract upload date
if not timestamp:
timestamp = self._search_regex(
r'<time[^>]+datetime="([^"]+)"', webpage,
'timestamp', default=None)
try:
view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
except RegexNotFoundError:
# This info is only available in vimeo.com/{id} urls
view_count = None
like_count = None
comment_count = None
formats = []
source_format = self._extract_original_format(
'https://vimeo.com/' + video_id, video_id)
if source_format:
formats.append(source_format)
info_dict_config = self._parse_config(config, video_id)
formats.extend(info_dict_config['formats'])
self._vimeo_sort_formats(formats)
json_ld = self._search_json_ld(webpage, video_id, default={})
if not cc_license:
cc_license = self._search_regex(
r'<link[^>]+rel=["\']license["\'][^>]+href=(["\'])(?P<license>(?:(?!\1).)+)\1',
webpage, 'license', default=None, group='license')
channel_url = 'https://vimeo.com/channels/%s' % channel_id if channel_id else None
info_dict = {
'formats': formats,
'timestamp': unified_timestamp(timestamp),
'description': video_description,
'webpage_url': url,
'view_count': view_count,
'like_count': like_count,
'comment_count': comment_count,
'license': cc_license,
'channel_id': channel_id,
'channel_url': channel_url,
}
info_dict = merge_dicts(info_dict, info_dict_config, json_ld)
return info_dict
class VimeoOndemandIE(VimeoIE):
IE_NAME = 'vimeo:ondemand'
_VALID_URL = r'https?://(?:www\.)?vimeo\.com/ondemand/([^/]+/)?(?P<id>[^/?#&]+)'
_TESTS = [{
# ondemand video not available via https://vimeo.com/id
'url': 'https://vimeo.com/ondemand/20704',
'md5': 'c424deda8c7f73c1dfb3edd7630e2f35',
'info_dict': {
'id': '105442900',
'ext': 'mp4',
'title': 'המעבדה - במאי יותם פלדמן',
'uploader': 'גם סרטים',
'uploader_url': r're:https?://(?:www\.)?vimeo\.com/gumfilms',
'uploader_id': 'gumfilms',
'description': 'md5:4c027c965e439de4baab621e48b60791',
'upload_date': '20140906',
'timestamp': 1410032453,
},
'params': {
'format': 'best[protocol=https]',
},
'expected_warnings': ['Unable to download JSON metadata'],
}, {
# requires Referer to be passed along with og:video:url
'url': 'https://vimeo.com/ondemand/36938/126682985',
'info_dict': {
'id': '126584684',
'ext': 'mp4',
'title': 'Rävlock, rätt läte på rätt plats',
'uploader': 'Lindroth & Norin',
'uploader_url': r're:https?://(?:www\.)?vimeo\.com/lindrothnorin',
'uploader_id': 'lindrothnorin',
'description': 'md5:c3c46a90529612c8279fb6af803fc0df',
'upload_date': '20150502',
'timestamp': 1430586422,
},
'params': {
'skip_download': True,
},
'expected_warnings': ['Unable to download JSON metadata'],
}, {
'url': 'https://vimeo.com/ondemand/nazmaalik',
'only_matching': True,
}, {
'url': 'https://vimeo.com/ondemand/141692381',
'only_matching': True,
}, {
'url': 'https://vimeo.com/ondemand/thelastcolony/150274832',
'only_matching': True,
}]
class VimeoChannelIE(VimeoBaseInfoExtractor):
IE_NAME = 'vimeo:channel'
_VALID_URL = r'https://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
_MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
_TITLE = None
_TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
_TESTS = [{
'url': 'https://vimeo.com/channels/tributes',
'info_dict': {
'id': 'tributes',
'title': 'Vimeo Tributes',
},
'playlist_mincount': 25,
}]
_BASE_URL_TEMPL = 'https://vimeo.com/channels/%s'
def _page_url(self, base_url, pagenum):
return '%s/videos/page:%d/' % (base_url, pagenum)
def _extract_list_title(self, webpage):
return self._TITLE or self._html_search_regex(
self._TITLE_RE, webpage, 'list title', fatal=False)
def _title_and_entries(self, list_id, base_url):
for pagenum in itertools.count(1):
page_url = self._page_url(base_url, pagenum)
webpage = self._download_webpage(
page_url, list_id,
'Downloading page %s' % pagenum)
if pagenum == 1:
yield self._extract_list_title(webpage)
# Try extracting href first since not all videos are available via
# short https://vimeo.com/id URL (e.g. https://vimeo.com/channels/tributes/6213729)
clips = re.findall(
r'id="clip_(\d+)"[^>]*>\s*<a[^>]+href="(/(?:[^/]+/)*\1)(?:[^>]+\btitle="([^"]+)")?', webpage)
if clips:
for video_id, video_url, video_title in clips:
yield self.url_result(
compat_urlparse.urljoin(base_url, video_url),
VimeoIE.ie_key(), video_id=video_id, video_title=video_title)
# More relaxed fallback
else:
for video_id in re.findall(r'id=["\']clip_(\d+)', webpage):
yield self.url_result(
'https://vimeo.com/%s' % video_id,
VimeoIE.ie_key(), video_id=video_id)
if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
break
def _extract_videos(self, list_id, base_url):
title_and_entries = self._title_and_entries(list_id, base_url)
list_title = next(title_and_entries)
return self.playlist_result(title_and_entries, list_id, list_title)
def _real_extract(self, url):
channel_id = self._match_id(url)
return self._extract_videos(channel_id, self._BASE_URL_TEMPL % channel_id)
class VimeoUserIE(VimeoChannelIE):
IE_NAME = 'vimeo:user'
_VALID_URL = r'https://vimeo\.com/(?!(?:[0-9]+|watchlater)(?:$|[?#/]))(?P<id>[^/]+)(?:/videos|[#?]|$)'
_TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
_TESTS = [{
'url': 'https://vimeo.com/nkistudio/videos',
'info_dict': {
'title': 'Nki',
'id': 'nkistudio',
},
'playlist_mincount': 66,
}]
_BASE_URL_TEMPL = 'https://vimeo.com/%s'
class VimeoAlbumIE(VimeoBaseInfoExtractor):
IE_NAME = 'vimeo:album'
_VALID_URL = r'https://vimeo\.com/(?:album|showcase)/(?P<id>\d+)(?:$|[?#]|/(?!video))'
_TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
_TESTS = [{
'url': 'https://vimeo.com/album/2632481',
'info_dict': {
'id': '2632481',
'title': 'Staff Favorites: November 2013',
},
'playlist_mincount': 13,
}, {
'note': 'Password-protected album',
'url': 'https://vimeo.com/album/3253534',
'info_dict': {
'title': 'test',
'id': '3253534',
},
'playlist_count': 1,
'params': {
'videopassword': 'youtube-dl',
}
}]
_PAGE_SIZE = 100
def _fetch_page(self, album_id, authorizaion, hashed_pass, page):
api_page = page + 1
query = {
'fields': 'link,uri',
'page': api_page,
'per_page': self._PAGE_SIZE,
}
if hashed_pass:
query['_hashed_pass'] = hashed_pass
videos = self._download_json(
'https://api.vimeo.com/albums/%s/videos' % album_id,
album_id, 'Downloading page %d' % api_page, query=query, headers={
'Authorization': 'jwt ' + authorizaion,
})['data']
for video in videos:
link = video.get('link')
if not link:
continue
uri = video.get('uri')
video_id = self._search_regex(r'/videos/(\d+)', uri, 'video_id', default=None) if uri else None
yield self.url_result(link, VimeoIE.ie_key(), video_id)
def _real_extract(self, url):
album_id = self._match_id(url)
webpage = self._download_webpage(url, album_id)
viewer = self._parse_json(self._search_regex(
r'bootstrap_data\s*=\s*({.+?})</script>',
webpage, 'bootstrap data'), album_id)['viewer']
jwt = viewer['jwt']
album = self._download_json(
'https://api.vimeo.com/albums/' + album_id,
album_id, headers={'Authorization': 'jwt ' + jwt},
query={'fields': 'description,name,privacy'})
hashed_pass = None
if try_get(album, lambda x: x['privacy']['view']) == 'password':
password = self._downloader.params.get('videopassword')
if not password:
raise ExtractorError(
'This album is protected by a password, use the --video-password option',
expected=True)
self._set_vimeo_cookie('vuid', viewer['vuid'])
try:
hashed_pass = self._download_json(
'https://vimeo.com/showcase/%s/auth' % album_id,
album_id, 'Verifying the password', data=urlencode_postdata({
'password': password,
'token': viewer['xsrft'],
}), headers={
'X-Requested-With': 'XMLHttpRequest',
})['hashed_pass']
except ExtractorError as e:
if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
raise ExtractorError('Wrong password', expected=True)
raise
entries = OnDemandPagedList(functools.partial(
self._fetch_page, album_id, jwt, hashed_pass), self._PAGE_SIZE)
return self.playlist_result(
entries, album_id, album.get('name'), album.get('description'))
class VimeoGroupsIE(VimeoChannelIE):
IE_NAME = 'vimeo:group'
_VALID_URL = r'https://vimeo\.com/groups/(?P<id>[^/]+)(?:/(?!videos?/\d+)|$)'
_TESTS = [{
'url': 'https://vimeo.com/groups/kattykay',
'info_dict': {
'id': 'kattykay',
'title': 'Katty Kay',
},
'playlist_mincount': 27,
}]
_BASE_URL_TEMPL = 'https://vimeo.com/groups/%s'
class VimeoReviewIE(VimeoBaseInfoExtractor):
IE_NAME = 'vimeo:review'
IE_DESC = 'Review pages on vimeo'
_VALID_URL = r'(?P<url>https://vimeo\.com/[^/]+/review/(?P<id>[^/]+)/[0-9a-f]{10})'
_TESTS = [{
'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
'md5': 'c507a72f780cacc12b2248bb4006d253',
'info_dict': {
'id': '75524534',
'ext': 'mp4',
'title': "DICK HARDWICK 'Comedian'",
'uploader': 'Richard Hardwick',
'uploader_id': 'user21297594',
'description': "Comedian Dick Hardwick's five minute demo filmed in front of a live theater audience.\nEdit by Doug Mattocks",
},
'expected_warnings': ['Unable to download JSON metadata'],
}, {
'note': 'video player needs Referer',
'url': 'https://vimeo.com/user22258446/review/91613211/13f927e053',
'md5': '6295fdab8f4bf6a002d058b2c6dce276',
'info_dict': {
'id': '91613211',
'ext': 'mp4',
'title': 're:(?i)^Death by dogma versus assembling agile . Sander Hoogendoorn',
'uploader': 'DevWeek Events',
'duration': 2773,
'thumbnail': r're:^https?://.*\.jpg$',
'uploader_id': 'user22258446',
},
'skip': 'video gone',
}, {
'note': 'Password protected',
'url': 'https://vimeo.com/user37284429/review/138823582/c4d865efde',
'info_dict': {
'id': '138823582',
'ext': 'mp4',
'title': 'EFFICIENT PICKUP MASTERCLASS MODULE 1',
'uploader': 'TMB',
'uploader_id': 'user37284429',
},
'params': {
'videopassword': 'holygrail',
},
'skip': 'video gone',
}]
def _real_initialize(self):
self._login()
def _real_extract(self, url):
page_url, video_id = re.match(self._VALID_URL, url).groups()
clip_data = self._download_json(
page_url.replace('/review/', '/review/data/'),
video_id)['clipData']
config_url = clip_data['configUrl']
config = self._download_json(config_url, video_id)
info_dict = self._parse_config(config, video_id)
source_format = self._extract_original_format(
page_url + '/action', video_id)
if source_format:
info_dict['formats'].append(source_format)
self._vimeo_sort_formats(info_dict['formats'])
info_dict['description'] = clean_html(clip_data.get('description'))
return info_dict
class VimeoWatchLaterIE(VimeoChannelIE):
IE_NAME = 'vimeo:watchlater'
IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
_VALID_URL = r'https://vimeo\.com/(?:home/)?watchlater|:vimeowatchlater'
_TITLE = 'Watch Later'
_LOGIN_REQUIRED = True
_TESTS = [{
'url': 'https://vimeo.com/watchlater',
'only_matching': True,
}]
def _real_initialize(self):
self._login()
def _page_url(self, base_url, pagenum):
url = '%s/page:%d/' % (base_url, pagenum)
request = sanitized_Request(url)
# Set the header to get a partial html page with the ids,
# the normal page doesn't contain them.
request.add_header('X-Requested-With', 'XMLHttpRequest')
return request
def _real_extract(self, url):
return self._extract_videos('watchlater', 'https://vimeo.com/watchlater')
class VimeoLikesIE(VimeoChannelIE):
_VALID_URL = r'https://(?:www\.)?vimeo\.com/(?P<id>[^/]+)/likes/?(?:$|[?#]|sort:)'
IE_NAME = 'vimeo:likes'
IE_DESC = 'Vimeo user likes'
_TESTS = [{
'url': 'https://vimeo.com/user755559/likes/',
'playlist_mincount': 293,
'info_dict': {
'id': 'user755559',
'title': 'urza’s Likes',
},
}, {
'url': 'https://vimeo.com/stormlapse/likes',
'only_matching': True,
}]
def _page_url(self, base_url, pagenum):
return '%s/page:%d/' % (base_url, pagenum)
def _real_extract(self, url):
user_id = self._match_id(url)
return self._extract_videos(user_id, 'https://vimeo.com/%s/likes' % user_id)
class VHXEmbedIE(VimeoBaseInfoExtractor):
IE_NAME = 'vhx:embed'
_VALID_URL = r'https?://embed\.vhx\.tv/videos/(?P<id>\d+)'
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
config_url = self._parse_json(self._search_regex(
r'window\.OTTData\s*=\s*({.+})', webpage,
'ott data'), video_id, js_to_json)['config_url']
config = self._download_json(config_url, video_id)
info = self._parse_config(config, video_id)
self._vimeo_sort_formats(info['formats'])
return info
| remitamine/youtube-dl | youtube_dl/extractor/vimeo.py | Python | unlicense | 46,520 |
(function(synth, lang, langIndex) {
var voice = synth.getVoices().filter(voice => voice.lang === lang)[langIndex],
text = window.getSelection().toString();
function speak(text, voice) {
var utterance = new SpeechSynthesisUtterance(text);
utterance.voice = voice;
utterance.lang = lang;
utterance.rate = .4;
synth.speak(utterance);
}
speak(text, voice);
})(window.speechSynthesis, 'pt-PT', 0);
| pansay/tts_bookmarklets | read_selection_in_pt_PT.js | JavaScript | unlicense | 461 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mx.neftaly.hackerrank.algorithms;
import java.util.Scanner;
/**
*
* @author samas
*/
public class Kangaroo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
int x1 = in.nextInt();
int v1 = in.nextInt();
int x2 = in.nextInt();
int v2 = in.nextInt();
if (x2 >= x1 && v2 >= v1) {
System.out.println("NO");
} else if ((x1 - x2) % (v2 - v1) == 0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
| neftalyluis/HRSolutions | src/main/java/mx/neftaly/hackerrank/algorithms/Kangaroo.java | Java | unlicense | 882 |
package us.aaronweiss.pixalia.core;
import us.aaronweiss.pixalia.tools.Vector;
public class Player extends Pixal {
public Player(String hostname) {
super(hostname);
}
public void setColor(Vector color) {
this.color = color;
}
}
| aatxe/pixalia | src/main/java/us/aaronweiss/pixalia/core/Player.java | Java | unlicense | 240 |
package code.one;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//Given an array of strings, group anagrams together.
//
//For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
//Return:
//
//[
// ["ate", "eat","tea"],
// ["nat","tan"],
// ["bat"]
//]
public class GroupAnagrams_time {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0) {
return new ArrayList<>();
}
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
char[] c = str.toCharArray();
Arrays.sort(c);
String s = new String(c);
if (!map.containsKey(s)) {
map.put(s, new ArrayList<>());
}
map.get(s).add(str);
}
return new ArrayList<>(map.values());
}
public List<List<String>> groupAnagrams1(String[] strs) {
List<List<String>> array = new ArrayList<>();
List<String> list = new ArrayList<>();
List<char[]> list1 = new ArrayList<>();
for (int i = 0; i < strs.length; i++) {
char[] c = strs[i].toCharArray();
Arrays.sort(c);
list1.add(c);
list.add(strs[i]);
}
while (!list.isEmpty()) {
List<String> l = new ArrayList<>();
l.add(list.remove(0));
char[] c = list1.remove(0);
for (int i = 0; i < list.size(); i++) {
if (equal(c, list1.get(i))) {
l.add(list.remove(i));
list1.remove(i);
i--;
}
}
array.add(l);
}
return array;
}
private boolean equal(char[] c, char[] ds) {
if (c.length != ds.length) {
return false;
}
for (int i = 0; i < ds.length; i++) {
if (c[i] != ds[i]) {
return false;
}
}
return true;
}
}
| POKLpokl112/leetcode | leetcode/src/code/one/GroupAnagrams_time.java | Java | unlicense | 1,763 |
#include<cstdio>
int t;
char c[250][250],u[250];
char go(int v)
{
if(v==t)return 1;
if(u[v])return 0;
u[v]=1;
for(int i=0;i<=t;i++)
if(c[v][i])
{
c[v][i]--;
if(go(i))
{
c[i][v]++;
return 1;
}
c[v][i]++;
}
return 0;
}
int flow()
{
int sum=0;
while(1)
{
for(int i=0;i<=t;i++)u[i]=0;
if(!go(0))break;
sum++;
}
return sum;
}
main()
{
int i,j,n,m,T;
scanf("%d",&T);
while(T--)
{
scanf("%d %d",&n,&m);
t=n*2+1;
for(i=0;i<=t;i++)
for(j=0;j<=t;j++)
c[i][j]=0;
while(m--)
{
scanf("%d %d",&i,&j);
c[i][n+j]=1;
}
for(i=1;i<=n;i++)
c[0][i]=c[n+i][t]=1;
printf("%d\n",n-flow());
}
}
| dk00/old-stuff | live-archive/2696.cpp | C++ | unlicense | 898 |
<script type="text/javascript">
$(document).ready(function(){
$('#form_data').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
nama: {
validators: {
notEmpty: {
message : 'Nama tidak boleh kosong'
}
}
},
alamat: {
validators: {
notEmpty: {
message : 'Alamat tidak boleh kosong'
}
}
},
p1: {
validators: {
notEmpty: {
message : 'Password tidak boleh kosong'
},
stringLength: {
min: 6,
message: 'Panjang minimal 6 karakter'
}
}
},
nomor_hp: {
validators: {
notEmpty: {
message : 'No. HP tidak boleh kosong'
},
stringLength: {
min: 11,
message: 'Panjang minimal 11 karakter'
}
}
},
p2: {
validators: {
notEmpty: {
message: 'Tidak boleh kosong'
},
identical: {
field: 'p1',
message: 'Passwod yang anda masukkan tidak sesuai'
}
}
},
email: {
validators: {
notEmpty: {
message : 'Email tidak boleh kosong'
},
emailAddress: {
message : 'Email harus valid'
},
remote: {
type: 'POST',
url: "<?php echo site_url($this->controller.'/cekEmail'); ?>",
message: 'Dealer dengan email ini sudah terdaftar',
delay: 200
}
}
}
}
});
$('#reset').click(function() {
$('#form_data').data('bootstrapValidator').resetForm(true);
});
$("#simpan").click(function(){
console.log('tests');
$.ajax({
url:'<?php echo site_url("$this->controller/simpan"); ?>',
data : $('#form_data').serialize(),
type : 'post',
dataType : 'json',
success : function(obj){
console.log(obj.error);
if(obj.error == false) { // berhasil
// alert('hooooo.. error false');
BootstrapDialog.alert({
type: BootstrapDialog.TYPE_PRIMARY,
title: 'Informasi',
message: obj.message,
callback: function(result) {
location.href='<?php echo site_url("dealer"); ?>';
}
});
$('#form_data').data('bootstrapValidator').resetForm(true);
}
else {
BootstrapDialog.alert({
type: BootstrapDialog.TYPE_DANGER,
title: 'Error',
message: obj.message
});
}
}
});
return false;
});
$("#update").click(function(){
$.ajax({
url:'<?php echo site_url("$this->controller/update"); ?>',
data : $('#form_data').serialize(),
type : 'post',
dataType : 'json',
success : function(obj){
console.log(obj.error);
if(obj.error == false) { // berhasil
// alert('hooooo.. error false');
BootstrapDialog.alert({
type: BootstrapDialog.TYPE_PRIMARY,
title: 'Informasi',
message: obj.message,
callback: function(result) {
location.href='<?php echo site_url("user"); ?>';
}
});
// $('#form_data').data('bootstrapValidator').resetForm(true);
}
else {
BootstrapDialog.alert({
type: BootstrapDialog.TYPE_DANGER,
title: 'Error',
message: obj.message
});
}
}
});
return false;
});
});
</script> | NizarHafizulllah/app_import_data | application/modules/user_profil/views/user_profil_view_js.php | PHP | unlicense | 5,814 |
#include<queue>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N = 20012, inf = 2000000000;
int p[N], f[N], t[N], s[N], dg[N];
int main() {
int i, j, n;
while (scanf("%d", &n) == 1 && n) {
fill(dg, dg+n, 0);
fill(s, s+n, inf);
for (i = 0; i < n; ++i) {
scanf("%d %d %d", p+i, f+i, t+i);
++dg[--p[i]];
}
queue<int> Q;
for (i = 0; i < n; ++i)
if (dg[i] == 0) {
s[i] = 0;
Q.push(i);
}
while (!Q.empty()) {
i = Q.front();
Q.pop();
if (p[i] < 0) continue;
j = (t[i] + s[i])*2 + !f[i];
if (j < s[p[i]]) s[p[i]] = j;
if (!--dg[p[i]]) Q.push(p[i]);
}
for (i = 0; p[i] >= 0; ++i);
printf("%d\n", s[i] + t[i]);
}
}
| dk00/old-stuff | ntuj/0948.cpp | C++ | unlicense | 748 |
package net.lardcave.keepassnfc.nfccomms;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Parcelable;
import net.lardcave.keepassnfc.Settings;
import java.io.IOException;
import java.util.Arrays;
public class KPNdef {
private static final String nfc_ndef_mime_type = "application/x-keepassnfc-3";
// Stored on the tag:
private static final int KEY_TYPE_RAW = 1; // Password is stored directly on the card (basic NTAG203 memory-only tag)
private static final int KEY_TYPE_APP = 2; // Password is stored in the KeepassNFC applet (JavaCard smartcard).
private static final int key_type_length = 1;
private byte[] secretKey;
private boolean _successfulNdefRead = false;
/** Construct an NDEF message for writing containing a secret key. */
public KPNdef(byte[] secretKey) {
this.secretKey = secretKey;
}
/** Construct an NDEF message for writing without any secret information (for use with applet) */
public KPNdef() {
// TODO this is unused because the applet code bypasses Android's NDEF support (since it
// TODO already has an isodep channel open). harmonise this & applet NDEF code.
this.secretKey = null;
}
public static IntentFilter getIntentFilter() {
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType(nfc_ndef_mime_type);
}
catch (IntentFilter.MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
return ndef;
}
/** Read an NDEF message from an Intent */
public KPNdef(Intent intent) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs != null) {
NdefMessage [] msgs = new NdefMessage[rawMsgs.length];
for (int j = 0; j < rawMsgs.length; j++) {
msgs[j] = (NdefMessage) rawMsgs[j];
NdefRecord record = msgs[j].getRecords()[0];
if (record.getTnf() == NdefRecord.TNF_MIME_MEDIA)
{
String mimetype = record.toMimeType();
if (mimetype.equals(nfc_ndef_mime_type)) {
_successfulNdefRead = true;
decodePayload(record.getPayload());
}
}
}
}
}
public boolean readWasSuccessful() {
return _successfulNdefRead;
}
public byte[] getSecretKey() {
return secretKey;
}
/** Write NDEF to the tag to wake up KPNFC when it's presented. */
public boolean write(Tag tag) {
if(secretKey == null) {
return writeMessageInternal(tag, createWakeOnlyNdefMessage());
} else {
return writeMessageInternal(tag, createRandomBytesNdefMessage(secretKey));
}
}
private void decodePayload(byte[] payload) {
switch(payload[0]) {
case KEY_TYPE_RAW:
secretKey = Arrays.copyOfRange(payload, 1, payload.length);
break;
case KEY_TYPE_APP:
secretKey = null;
break;
}
}
private static boolean writeMessageInternal(Tag tag, NdefMessage message) {
// Write the payload to the tag.
android.nfc.tech.Ndef ndef = android.nfc.tech.Ndef.get(tag);
try {
ndef.connect();
ndef.writeNdefMessage(message);
ndef.close();
return true;
} catch (IOException | FormatException e) {
e.printStackTrace();
}
return false;
}
private static NdefMessage createRandomBytesNdefMessage(byte[] secretKey)
{
byte[] messageBytes;
messageBytes = new byte[key_type_length + Settings.key_length];
messageBytes[0] = (byte)KEY_TYPE_RAW;
System.arraycopy(secretKey, 0, messageBytes, 1, Settings.key_length);
return ndefFromBytes(messageBytes);
}
static NdefMessage createWakeOnlyNdefMessage()
{
byte[] messageBytes;
messageBytes = new byte[key_type_length];
messageBytes[0] = (byte)KEY_TYPE_APP;
return ndefFromBytes(messageBytes);
}
private static NdefMessage ndefFromBytes(byte[] messageBytes) {
NdefRecord ndef_records = NdefRecord.createMime(nfc_ndef_mime_type, messageBytes);
return new NdefMessage(ndef_records);
}
}
| nfd/KeePassNFC | app/src/main/java/net/lardcave/keepassnfc/nfccomms/KPNdef.java | Java | unlicense | 3,998 |
<div class="panel-group col-md-6 col-sm-12" id="accordion" style="padding-left: 0">
<div class="panel panel-primary">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
<i class="fa fa-plus"></i>
Nieuwe route </a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
<form action="/walkpath" method="post">
{{ csrf_field() }}
{!! \Nvd\Crud\Form::input('name','text')->show() !!}
{!! \Nvd\Crud\Form::input('description','text')->show() !!}
<!--{!! \Nvd\Crud\Form::input('status','text')->show() !!}-->
<div class="row form-group">
<label class="col-lg-1" for="status">Status</label>
<div class="col-lg-11">
<select name="status" id="status" class="form-control" value="" type="text">
<option value="0">Inactief</option>
<option value="1">Actief</option>
</select>
</div>
</div>
<!-- deze maar even verstoppen.. -->
<input id="status" name="status" value="0" disabled="disabled" style="display:none;" />
<button type="submit" class="btn btn-primary">Create</button>
</form>
</div>
</div>
</div>
</div>
| ericfennis/bhp | resources/views/walkpath/create.blade.php | PHP | apache-2.0 | 1,467 |
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.widget.tree;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Matcher;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.ObjectType;
import org.ofbiz.base.util.PatternFactory;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.UtilXml;
import org.ofbiz.base.util.collections.FlexibleMapAccessor;
import org.ofbiz.base.util.string.FlexibleStringExpander;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entityext.permission.EntityPermissionChecker;
import org.ofbiz.minilang.operation.BaseCompare;
import org.ofbiz.security.Security;
import org.w3c.dom.Element;
/**
* Widget Library - Screen model condition class
*/
public class ModelTreeCondition {
public static final String module = ModelTreeCondition.class.getName();
protected ModelTree modelTree;
protected TreeCondition rootCondition;
public ModelTreeCondition(ModelTree modelTree, Element conditionElement) {
this.modelTree = modelTree;
Element firstChildElement = UtilXml.firstChildElement(conditionElement);
this.rootCondition = readCondition(modelTree, firstChildElement);
}
public boolean eval(Map<String, ? extends Object> context) {
if (rootCondition == null) {
return true;
}
return rootCondition.eval(context);
}
public static abstract class TreeCondition {
protected ModelTree modelTree;
public TreeCondition(ModelTree modelTree, Element conditionElement) {
this.modelTree = modelTree;
}
public abstract boolean eval(Map<String, ? extends Object> context);
}
public static List<TreeCondition> readSubConditions(ModelTree modelTree, Element conditionElement) {
List<TreeCondition> condList = new ArrayList<TreeCondition>();
for (Element subElement: UtilXml.childElementList(conditionElement)) {
condList.add(readCondition(modelTree, subElement));
}
return condList;
}
public static TreeCondition readCondition(ModelTree modelTree, Element conditionElement) {
if (conditionElement == null) {
return null;
}
if ("and".equals(conditionElement.getNodeName())) {
return new And(modelTree, conditionElement);
} else if ("xor".equals(conditionElement.getNodeName())) {
return new Xor(modelTree, conditionElement);
} else if ("or".equals(conditionElement.getNodeName())) {
return new Or(modelTree, conditionElement);
} else if ("not".equals(conditionElement.getNodeName())) {
return new Not(modelTree, conditionElement);
} else if ("if-has-permission".equals(conditionElement.getNodeName())) {
return new IfHasPermission(modelTree, conditionElement);
} else if ("if-validate-method".equals(conditionElement.getNodeName())) {
return new IfValidateMethod(modelTree, conditionElement);
} else if ("if-compare".equals(conditionElement.getNodeName())) {
return new IfCompare(modelTree, conditionElement);
} else if ("if-compare-field".equals(conditionElement.getNodeName())) {
return new IfCompareField(modelTree, conditionElement);
} else if ("if-regexp".equals(conditionElement.getNodeName())) {
return new IfRegexp(modelTree, conditionElement);
} else if ("if-empty".equals(conditionElement.getNodeName())) {
return new IfEmpty(modelTree, conditionElement);
} else if ("if-entity-permission".equals(conditionElement.getNodeName())) {
return new IfEntityPermission(modelTree, conditionElement);
} else {
throw new IllegalArgumentException("Condition element not supported with name: " + conditionElement.getNodeName());
}
}
public static class And extends TreeCondition {
protected List<? extends TreeCondition> subConditions;
public And(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.subConditions = readSubConditions(modelTree, condElement);
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
// return false for the first one in the list that is false, basic and algo
for (TreeCondition subCondition: subConditions) {
if (!subCondition.eval(context)) {
return false;
}
}
return true;
}
}
public static class Xor extends TreeCondition {
protected List<? extends TreeCondition> subConditions;
public Xor(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.subConditions = readSubConditions(modelTree, condElement);
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
// if more than one is true stop immediately and return false; if all are false return false; if only one is true return true
boolean foundOneTrue = false;
for (TreeCondition subCondition: subConditions) {
if (subCondition.eval(context)) {
if (foundOneTrue) {
// now found two true, so return false
return false;
} else {
foundOneTrue = true;
}
}
}
return foundOneTrue;
}
}
public static class Or extends TreeCondition {
protected List<? extends TreeCondition> subConditions;
public Or(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.subConditions = readSubConditions(modelTree, condElement);
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
// return true for the first one in the list that is true, basic or algo
for (TreeCondition subCondition: subConditions) {
if (subCondition.eval(context)) {
return true;
}
}
return false;
}
}
public static class Not extends TreeCondition {
protected TreeCondition subCondition;
public Not(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
Element firstChildElement = UtilXml.firstChildElement(condElement);
this.subCondition = readCondition(modelTree, firstChildElement);
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
return !this.subCondition.eval(context);
}
}
public static class IfHasPermission extends TreeCondition {
protected FlexibleStringExpander permissionExdr;
protected FlexibleStringExpander actionExdr;
public IfHasPermission(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.permissionExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("permission"));
this.actionExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("action"));
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
// if no user is logged in, treat as if the user does not have permission
GenericValue userLogin = (GenericValue) context.get("userLogin");
if (userLogin != null) {
String permission = permissionExdr.expandString(context);
String action = actionExdr.expandString(context);
Security security = (Security) context.get("security");
if (UtilValidate.isNotEmpty(action)) {
// run hasEntityPermission
if (security.hasEntityPermission(permission, action, userLogin)) {
return true;
}
} else {
// run hasPermission
if (security.hasPermission(permission, userLogin)) {
return true;
}
}
}
return false;
}
}
public static class IfValidateMethod extends TreeCondition {
protected FlexibleMapAccessor<Object> fieldAcsr;
protected FlexibleStringExpander methodExdr;
protected FlexibleStringExpander classExdr;
public IfValidateMethod(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field"));
if (this.fieldAcsr.isEmpty()) this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field-name"));
this.methodExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("method"));
this.classExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("class"));
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
String methodName = this.methodExdr.expandString(context);
String className = this.classExdr.expandString(context);
Object fieldVal = this.fieldAcsr.get(context);
String fieldString = null;
if (fieldVal != null) {
try {
fieldString = (String) ObjectType.simpleTypeConvert(fieldVal, "String", null, (TimeZone) context.get("timeZone"), (Locale) context.get("locale"), true);
} catch (GeneralException e) {
Debug.logError(e, "Could not convert object to String, using empty String", module);
}
}
// always use an empty string by default
if (fieldString == null) fieldString = "";
Class<?>[] paramTypes = new Class[] {String.class};
Object[] params = new Object[] {fieldString};
Class<?> valClass;
try {
valClass = ObjectType.loadClass(className);
} catch (ClassNotFoundException cnfe) {
Debug.logError("Could not find validation class: " + className, module);
return false;
}
Method valMethod;
try {
valMethod = valClass.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException cnfe) {
Debug.logError("Could not find validation method: " + methodName + " of class " + className, module);
return false;
}
Boolean resultBool = Boolean.FALSE;
try {
resultBool = (Boolean) valMethod.invoke(null, params);
} catch (Exception e) {
Debug.logError(e, "Error in IfValidationMethod " + methodName + " of class " + className + ", defaulting to false ", module);
}
return resultBool.booleanValue();
}
}
public static class IfCompare extends TreeCondition {
protected FlexibleMapAccessor<Object> fieldAcsr;
protected FlexibleStringExpander valueExdr;
protected String operator;
protected String type;
protected FlexibleStringExpander formatExdr;
public IfCompare(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field"));
if (this.fieldAcsr.isEmpty()) this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field-name"));
this.valueExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("value"));
this.operator = condElement.getAttribute("operator");
this.type = condElement.getAttribute("type");
this.formatExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("format"));
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
String value = this.valueExdr.expandString(context);
String format = this.formatExdr.expandString(context);
Object fieldVal = this.fieldAcsr.get(context);
// always use an empty string by default
if (fieldVal == null) {
fieldVal = "";
}
List<Object> messages = new LinkedList<Object>();
Boolean resultBool = BaseCompare.doRealCompare(fieldVal, value, operator, type, format, messages, null, null, true);
if (messages.size() > 0) {
messages.add(0, "Error with comparison in if-compare between field [" + fieldAcsr.toString() + "] with value [" + fieldVal + "] and value [" + value + "] with operator [" + operator + "] and type [" + type + "]: ");
StringBuilder fullString = new StringBuilder();
for (Object message: messages) {
fullString.append((String) message);
}
Debug.logWarning(fullString.toString(), module);
throw new IllegalArgumentException(fullString.toString());
}
return resultBool.booleanValue();
}
}
public static class IfCompareField extends TreeCondition {
protected FlexibleMapAccessor<Object> fieldAcsr;
protected FlexibleMapAccessor<Object> toFieldAcsr;
protected String operator;
protected String type;
protected FlexibleStringExpander formatExdr;
public IfCompareField(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field"));
if (this.fieldAcsr.isEmpty()) this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field-name"));
this.toFieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("to-field"));
if (this.toFieldAcsr.isEmpty()) this.toFieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("to-field-name"));
this.operator = condElement.getAttribute("operator");
this.type = condElement.getAttribute("type");
this.formatExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("format"));
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
String format = this.formatExdr.expandString(context);
Object fieldVal = this.fieldAcsr.get(context);
Object toFieldVal = this.toFieldAcsr.get(context);
// always use an empty string by default
if (fieldVal == null) {
fieldVal = "";
}
List<Object> messages = new LinkedList<Object>();
Boolean resultBool = BaseCompare.doRealCompare(fieldVal, toFieldVal, operator, type, format, messages, null, null, false);
if (messages.size() > 0) {
messages.add(0, "Error with comparison in if-compare-field between field [" + fieldAcsr.toString() + "] with value [" + fieldVal + "] and to-field [" + toFieldVal.toString() + "] with value [" + toFieldVal + "] with operator [" + operator + "] and type [" + type + "]: ");
StringBuilder fullString = new StringBuilder();
for (Object message: messages) {
fullString.append((String) message);
}
Debug.logWarning(fullString.toString(), module);
throw new IllegalArgumentException(fullString.toString());
}
return resultBool.booleanValue();
}
}
public static class IfRegexp extends TreeCondition {
protected FlexibleMapAccessor<Object> fieldAcsr;
protected FlexibleStringExpander exprExdr;
public IfRegexp(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field"));
if (this.fieldAcsr.isEmpty()) this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field-name"));
this.exprExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("expr"));
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
Object fieldVal = this.fieldAcsr.get(context);
String expr = this.exprExdr.expandString(context);
Pattern pattern = null;
try {
pattern = PatternFactory.createOrGetPerl5CompiledPattern(expr, true);
} catch (MalformedPatternException e) {
String errMsg = "Error in evaluation in if-regexp in screen: " + e.toString();
Debug.logError(e, errMsg, module);
throw new IllegalArgumentException(errMsg);
}
String fieldString = null;
try {
fieldString = (String) ObjectType.simpleTypeConvert(fieldVal, "String", null, (TimeZone) context.get("timeZone"), (Locale) context.get("locale"), true);
} catch (GeneralException e) {
Debug.logError(e, "Could not convert object to String, using empty String", module);
}
// always use an empty string by default
if (fieldString == null) fieldString = "";
PatternMatcher matcher = new Perl5Matcher();
return matcher.matches(fieldString, pattern);
}
}
public static class IfEmpty extends TreeCondition {
protected FlexibleMapAccessor<Object> fieldAcsr;
public IfEmpty(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field"));
if (this.fieldAcsr.isEmpty()) this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field-name"));
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
Object fieldVal = this.fieldAcsr.get(context);
return ObjectType.isEmpty(fieldVal);
}
}
public static class IfEntityPermission extends TreeCondition {
protected EntityPermissionChecker permissionChecker;
public IfEntityPermission(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.permissionChecker = new EntityPermissionChecker(condElement);
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
boolean passed = permissionChecker.runPermissionCheck(context);
return passed;
}
}
}
| ofbizfriends/vogue | framework/widget/src/org/ofbiz/widget/tree/ModelTreeCondition.java | Java | apache-2.0 | 20,242 |
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.elastictranscoder.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import com.amazonaws.services.elastictranscoder.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* CreateJobPlaylist JSON Unmarshaller
*/
public class CreateJobPlaylistJsonUnmarshaller implements
Unmarshaller<CreateJobPlaylist, JsonUnmarshallerContext> {
public CreateJobPlaylist unmarshall(JsonUnmarshallerContext context)
throws Exception {
CreateJobPlaylist createJobPlaylist = new CreateJobPlaylist();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL)
return null;
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Name", targetDepth)) {
context.nextToken();
createJobPlaylist.setName(StringJsonUnmarshaller
.getInstance().unmarshall(context));
}
if (context.testExpression("Format", targetDepth)) {
context.nextToken();
createJobPlaylist.setFormat(StringJsonUnmarshaller
.getInstance().unmarshall(context));
}
if (context.testExpression("OutputKeys", targetDepth)) {
context.nextToken();
createJobPlaylist
.setOutputKeys(new ListUnmarshaller<String>(
StringJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("HlsContentProtection", targetDepth)) {
context.nextToken();
createJobPlaylist
.setHlsContentProtection(HlsContentProtectionJsonUnmarshaller
.getInstance().unmarshall(context));
}
if (context.testExpression("PlayReadyDrm", targetDepth)) {
context.nextToken();
createJobPlaylist
.setPlayReadyDrm(PlayReadyDrmJsonUnmarshaller
.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null
|| context.getLastParsedParentElement().equals(
currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return createJobPlaylist;
}
private static CreateJobPlaylistJsonUnmarshaller instance;
public static CreateJobPlaylistJsonUnmarshaller getInstance() {
if (instance == null)
instance = new CreateJobPlaylistJsonUnmarshaller();
return instance;
}
}
| dump247/aws-sdk-java | aws-java-sdk-elastictranscoder/src/main/java/com/amazonaws/services/elastictranscoder/model/transform/CreateJobPlaylistJsonUnmarshaller.java | Java | apache-2.0 | 4,113 |
/*
* #%L
* GwtMaterial
* %%
* Copyright (C) 2015 - 2018 GwtMaterialDesign
* %%
* 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.
* #L%
*/
package gwt.material.design.incubator.client.keyboard.events;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HasHandlers;
//@formatter:off
/**
* Executes the callback function on input change. Returns the current input’s string.
*
* @author kevzlou7979
*/
public class ChangeEvent extends GwtEvent<ChangeEvent.ChangeHandler> {
public static final Type<ChangeHandler> TYPE = new Type<>();
private String input;
public ChangeEvent(String input) {
this.input = input;
}
public static Type<ChangeHandler> getType() {
return TYPE;
}
public static void fire(HasHandlers source, String message) {
source.fireEvent(new ChangeEvent(message));
}
@Override
public Type<ChangeHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(ChangeHandler handler) {
handler.onChange(this);
}
public String getInput() {
return input;
}
public interface ChangeHandler extends EventHandler {
void onChange(ChangeEvent event);
}
}
| GwtMaterialDesign/gwt-material-addins | src/main/java/gwt/material/design/incubator/client/keyboard/events/ChangeEvent.java | Java | apache-2.0 | 1,811 |
__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
| RobotTurtles/mid-level-routines | Apps/TurtleCommands.py | Python | apache-2.0 | 1,101 |
package com.compomics.pride_asa_pipeline.core.repository.impl.webservice;
import com.compomics.pride_asa_pipeline.core.model.modification.source.PRIDEModificationFactory;
import com.compomics.pride_asa_pipeline.core.model.modification.impl.AsapModificationAdapter;
import com.compomics.pride_asa_pipeline.core.repository.ModificationRepository;
import com.compomics.pride_asa_pipeline.model.Modification;
import com.compomics.util.pride.PrideWebService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import uk.ac.ebi.pride.archive.web.service.model.assay.AssayDetail;
/**
*
* @author Kenneth Verheggen
*/
public class WSModificationRepository implements ModificationRepository {
private static final Logger LOGGER = Logger.getLogger(WSModificationRepository.class);
@Override
public List<Modification> getModificationsByPeptideId(long peptideId) {
throw new UnsupportedOperationException("Currently not supported through the webservice");
}
@Override
public List<Modification> getModificationsByExperimentId(String experimentId) {
LOGGER.debug("Loading modifications for experimentid " + experimentId);
List<Modification> modifications = new ArrayList<>();
AsapModificationAdapter adapter = new AsapModificationAdapter();
try {
AssayDetail assayDetail = PrideWebService.getAssayDetail(String.valueOf(experimentId));
for (String aPtmName : assayDetail.getPtmNames()) {
PRIDEModificationFactory.getInstance().getModification(adapter, aPtmName);
}
LOGGER.debug("Finished loading modifications for pride experiment with id " + experimentId);
return modifications;
} catch (IOException ex) {
LOGGER.error(ex);
}
return modifications;
}
}
| compomics/pride-asa-pipeline | pride-asa-pipeline-core/src/main/java/com/compomics/pride_asa_pipeline/core/repository/impl/webservice/WSModificationRepository.java | Java | apache-2.0 | 1,930 |
class TemplateField
attr_accessor :page, :name, :type, :rect
# :internal => :external
def self.attribute_map
{
:page => :page, :name => :name, :type => :type, :rect => :rect
}
end
def initialize(attributes = {})
# Morph attribute keys into undescored rubyish style
if attributes.to_s != ""
if TemplateField.attribute_map["page".to_sym] != nil
name = "page".to_sym
value = attributes["page"]
send("#{name}=", value) if self.respond_to?(name)
end
if TemplateField.attribute_map["name".to_sym] != nil
name = "name".to_sym
value = attributes["name"]
send("#{name}=", value) if self.respond_to?(name)
end
if TemplateField.attribute_map["type".to_sym] != nil
name = "type".to_sym
value = attributes["type"]
send("#{name}=", value) if self.respond_to?(name)
end
if TemplateField.attribute_map["rect".to_sym] != nil
name = "rect".to_sym
value = attributes["rect"]
send("#{name}=", value) if self.respond_to?(name)
end
end
end
def to_body
body = {}
TemplateField.attribute_map.each_pair do |key,value|
body[value] = self.send(key) unless self.send(key).nil?
end
body
end
end
| liosha2007/groupdocs-ruby | groupdocs/models/templatefield.rb | Ruby | apache-2.0 | 1,282 |
/*
Copyright 2019 Nationale-Nederlanden
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 nl.nn.adapterframework.extensions.cmis.servlets;
import nl.nn.adapterframework.lifecycle.IbisInitializer;
@IbisInitializer
public class AtomPub10 extends AtomPubServletBase {
private static final long serialVersionUID = 1L;
@Override
public String getUrlMapping() {
return "/cmis/atompub10/*";
}
@Override
protected String getCmisVersionStr() {
return "1.0";
}
}
| ibissource/iaf | cmis/src/main/java/nl/nn/adapterframework/extensions/cmis/servlets/AtomPub10.java | Java | apache-2.0 | 985 |
package alien4cloud.tosca.parser.impl.base;
import java.util.Map;
import java.util.Set;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.ScalarNode;
import alien4cloud.tosca.parser.INodeParser;
import alien4cloud.tosca.parser.ParsingContextExecution;
import alien4cloud.tosca.parser.ParsingError;
import alien4cloud.tosca.parser.impl.ErrorCode;
import alien4cloud.tosca.parser.mapping.DefaultParser;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* Map using a child parser based on a discriminator key (valid only for MappingNode).
*/
public class KeyDiscriminatorParser<T> extends DefaultParser<T> {
private static final String MAPPING_NODE_FALLBACK_KEY = "__";
private Map<String, INodeParser<T>> parserByExistKey;
private INodeParser<T> fallbackParser;
/**
* Create a new key discriminator parser instance.
*
* @param parserByExistKey A map of existing keys to the parser to use in case the key exists.
* @param fallbackParser The parser to use if none of the key is actually found or if the node type is not a MappingNode.
*/
public KeyDiscriminatorParser(Map<String, INodeParser<T>> parserByExistKey, INodeParser<T> fallbackParser) {
if (parserByExistKey == null) {
this.parserByExistKey = Maps.newLinkedHashMap();
} else {
this.parserByExistKey = parserByExistKey;
}
this.fallbackParser = fallbackParser;
}
@Override
public T parse(Node node, ParsingContextExecution context) {
Set<String> keySet = Sets.newHashSet();
if (node instanceof MappingNode) {
// create a set of available keys
MappingNode mappingNode = (MappingNode) node;
for (NodeTuple tuple : mappingNode.getValue()) {
keySet.add(((ScalarNode) tuple.getKeyNode()).getValue());
}
INodeParser<T> mappingNodeFallbackParser = null;
// check if one of the discriminator key exists and if so use it for parsing.
for (Map.Entry<String, INodeParser<T>> entry : parserByExistKey.entrySet()) {
if (keySet.contains(entry.getKey())) {
return entry.getValue().parse(node, context);
} else if (MAPPING_NODE_FALLBACK_KEY.equals(entry.getKey())) {
mappingNodeFallbackParser = entry.getValue();
}
}
// if not we should use the mapping node fallback parser.
if (mappingNodeFallbackParser != null) {
return mappingNodeFallbackParser.parse(node, context);
}
}
if (fallbackParser != null) {
return fallbackParser.parse(node, context);
} else {
context.getParsingErrors().add(new ParsingError(ErrorCode.UNKNWON_DISCRIMINATOR_KEY, "Invalid scalar value.", node.getStartMark(),
"Tosca type cannot be expressed with the given scalar value.", node.getEndMark(), keySet.toString()));
}
return null;
}
}
| PierreLemordant/alien4cloud | alien4cloud-core/src/main/java/alien4cloud/tosca/parser/impl/base/KeyDiscriminatorParser.java | Java | apache-2.0 | 3,172 |
(function (parent, $, element) {
function loadEvents() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
return [
{
title: 'Appointment 1',
start: new Date(y, m, d, 10),
end: new Date(y, m, d, 11),
allDay: false,
editable: true,
startEditable: true,
durationEditable: true,
plantpot: 'coffeetable'
},
{
title: 'Appointment 2',
start: new Date(y, m, d, 11, 30),
end: new Date(y, m, d, 12),
allDay: false
}
];
}
function onEventClick(event) {
alert(event.plantpot);
alert($(element).fullCalendar('clientEvents').length);
}
function render() {
$(document).ready(function() {
$(element).fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: loadEvents(),
eventClick: onEventClick
});
});
}
parent.schedule = {
load: render
};
})(window, $, '#calendar');
window.schedule.load(); | lowds/scheduler | src/Scheduler.UI/js/schedule.js | JavaScript | apache-2.0 | 1,409 |
package com.meituan.davy.myapplication.github;
import android.support.v4.app.Fragment;
import com.meituan.davy.myapplication.ContainerActivity;
public class GithubActivity extends ContainerActivity {
@Override
protected Fragment getFragment() {
return new GithubFragment();
}
} | davyjoneswang/UsefulDemSuit | app/src/main/java/com/meituan/davy/myapplication/github/GithubActivity.java | Java | apache-2.0 | 300 |