code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
<div submittable> <div class="modal-body"> <p class="text-center">Voucher created successfully!</p> <p>It is available at <a ng-href="((voucher.url))">((voucher.url))</a></p> </div> <div class="modal-footer"> <div class=""> <button class="btn btn-danger" ng-click="$dismiss()">Закрыть</button> </div> </div> </div> <div class="printable"> <h1><img src="/static/img/logos/logo-greenaddress.png" alt="GreenAddress"> GreenAddress<br><small>https://greenaddress.it</small></h1> <p class="small">This is a GreenAddress voucher for (( voucher.satoshis|format_btc:wallet.unit ))</p> <p ng-show="voucher.text">(( voucher.text ))</p> <p class="small">The QR code below contains a URL for redeeming the funds:</p> <qr class="qrcode" text="(( voucher.url ))" size="212"></qr> <p class="small" ng-hide="voucher.encrypted">Alternatively, you can sweep funds to a wallet supporting Wallet Import Format using the following QR code:</p> <p class="small" ng-show="voucher.encrypted">Alternatively, you can sweep funds to a wallet supporting BIP38 using the following QR code:</p> <qr class="qrcode" text="(( voucher.enckey ))" size="212"></qr> </div>
ralic/WalletCordova
www/greenaddress.it/ru/wallet/partials/wallet_modal_voucher.html
HTML
lgpl-2.1
1,244
/** * DSS - Digital Signature Services * Copyright (C) 2015 European Commission, provided under the CEF programme * * This file is part of the "DSS - Digital Signature Services" project. * * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA */ package eu.europa.esig.dss.asic.signature.asics; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.UnsupportedEncodingException; import java.util.Date; import org.junit.Before; import eu.europa.esig.dss.ASiCContainerType; import eu.europa.esig.dss.DSSDocument; import eu.europa.esig.dss.DSSUtils; import eu.europa.esig.dss.InMemoryDocument; import eu.europa.esig.dss.MimeType; import eu.europa.esig.dss.SignatureLevel; import eu.europa.esig.dss.asic.ASiCExtractResult; import eu.europa.esig.dss.asic.ASiCWithCAdESContainerExtractor; import eu.europa.esig.dss.asic.ASiCWithCAdESSignatureParameters; import eu.europa.esig.dss.asic.AbstractASiCContainerExtractor; import eu.europa.esig.dss.asic.signature.ASiCWithCAdESService; import eu.europa.esig.dss.signature.DocumentSignatureService; public class ASiCSCAdESLevelBWithMimeTypeTest extends AbstractASiCSCAdESTestSignature { private static final String APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT = "application/vnd.oasis.opendocument.text"; private DocumentSignatureService<ASiCWithCAdESSignatureParameters> service; private ASiCWithCAdESSignatureParameters signatureParameters; private DSSDocument documentToSign; @Before public void init() throws Exception { documentToSign = new InMemoryDocument("Hello World !".getBytes(), "test.text", MimeType.TEXT); signatureParameters = new ASiCWithCAdESSignatureParameters(); signatureParameters.bLevel().setSigningDate(new Date()); signatureParameters.setSigningCertificate(getSigningCert()); signatureParameters.setCertificateChain(getCertificateChain()); signatureParameters.setSignatureLevel(SignatureLevel.CAdES_BASELINE_B); signatureParameters.aSiC().setContainerType(ASiCContainerType.ASiC_S); signatureParameters.aSiC().setMimeType(APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT); service = new ASiCWithCAdESService(getCompleteCertificateVerifier()); } @Override protected void onDocumentSigned(byte[] byteArray) { InMemoryDocument doc = new InMemoryDocument(byteArray); AbstractASiCContainerExtractor extractor = new ASiCWithCAdESContainerExtractor(doc); ASiCExtractResult extract = extractor.extract(); DSSDocument mimeTypeDocument = extract.getMimeTypeDocument(); byte[] mimeTypeContent = DSSUtils.toByteArray(mimeTypeDocument); try { assertEquals(APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT, new String(mimeTypeContent, "UTF-8")); } catch (UnsupportedEncodingException e) { fail(e.getMessage()); } } @Override protected DocumentSignatureService<ASiCWithCAdESSignatureParameters> getService() { return service; } @Override protected ASiCWithCAdESSignatureParameters getSignatureParameters() { return signatureParameters; } @Override protected DSSDocument getDocumentToSign() { return documentToSign; } @Override protected String getSigningAlias() { return GOOD_USER; } }
zsoltii/dss
dss-asic-cades/src/test/java/eu/europa/esig/dss/asic/signature/asics/ASiCSCAdESLevelBWithMimeTypeTest.java
Java
lgpl-2.1
3,831
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ /* * GData Client * Copyright (C) Philip Withnall 2008-2009 <philip@tecnocode.co.uk> * * GData Client 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. * * GData Client 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 GData Client. If not, see <http://www.gnu.org/licenses/>. */ #include <glib.h> #ifndef GDATA_TYPES_H #define GDATA_TYPES_H G_BEGIN_DECLS /** * GDataColor: * @red: red color intensity, from 0–255 * @green: green color intensity, from 0–255 * @blue: blue color intensity, from 0–255 * * Describes a color, such as used in the Google Calendar interface to * differentiate calendars. */ typedef struct { /*< public >*/ guint16 red; guint16 green; guint16 blue; } GDataColor; #define GDATA_TYPE_COLOR (gdata_color_get_type ()) GType gdata_color_get_type (void) G_GNUC_CONST; gboolean gdata_color_from_hexadecimal (const gchar *hexadecimal, GDataColor *color); gchar *gdata_color_to_hexadecimal (const GDataColor *color) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; G_END_DECLS #endif /* !GDATA_TYPES_H */
pwithnall/libgdata
gdata/gdata-types.h
C
lgpl-2.1
1,599
/* Copyright(C) 2015-2016 Brazil This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. 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 Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "../grn_ctx.h" #ifdef __cplusplus extern "C" { #endif mrb_value grn_mrb_options_get_static(mrb_state *mrb, mrb_value mrb_options, const char *key, size_t key_size); #define grn_mrb_options_get_lit(mrb, mrb_options, literal) \ grn_mrb_options_get_static(mrb, mrb_options, \ (literal), mrb_strlen_lit(literal)) #ifdef __cplusplus } #endif
groonga/groonga
lib/mrb/mrb_options.h
C
lgpl-2.1
1,248
/* * Copyright (C) 2004, 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if !USE(GOOGLEURL) #include "KURL.h" #include "CString.h" #include "PlatformString.h" #include "TextEncoding.h" #include <wtf/StdLibExtras.h> #if USE(ICU_UNICODE) #include <unicode/uidna.h> #elif USE(QT4_UNICODE) #include <QUrl> #endif #include <stdio.h> using namespace std; using namespace WTF; namespace WebCore { typedef Vector<char, 512> CharBuffer; typedef Vector<UChar, 512> UCharBuffer; // FIXME: This file makes too much use of the + operator on String. // We either have to optimize that operator so it doesn't involve // so many allocations, or change this to use Vector<UChar> instead. enum URLCharacterClasses { // alpha SchemeFirstChar = 1 << 0, // ( alpha | digit | "+" | "-" | "." ) SchemeChar = 1 << 1, // mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" // unreserved = alphanum | mark // ( unreserved | escaped | ";" | ":" | "&" | "=" | "+" | "$" | "," ) UserInfoChar = 1 << 2, // alnum | "." | "-" | "%" // The above is what the specification says, but we are lenient to // match existing practice and also allow: // "_" HostnameChar = 1 << 3, // hexdigit | ":" | "%" IPv6Char = 1 << 4, // "#" | "?" | "/" | nul PathSegmentEndChar = 1 << 5, // not allowed in path BadChar = 1 << 6 }; static const char hexDigits[17] = "0123456789ABCDEF"; static const unsigned char characterClassTable[256] = { /* 0 nul */ PathSegmentEndChar, /* 1 soh */ BadChar, /* 2 stx */ BadChar, /* 3 etx */ BadChar, /* 4 eot */ BadChar, /* 5 enq */ BadChar, /* 6 ack */ BadChar, /* 7 bel */ BadChar, /* 8 bs */ BadChar, /* 9 ht */ BadChar, /* 10 nl */ BadChar, /* 11 vt */ BadChar, /* 12 np */ BadChar, /* 13 cr */ BadChar, /* 14 so */ BadChar, /* 15 si */ BadChar, /* 16 dle */ BadChar, /* 17 dc1 */ BadChar, /* 18 dc2 */ BadChar, /* 19 dc3 */ BadChar, /* 20 dc4 */ BadChar, /* 21 nak */ BadChar, /* 22 syn */ BadChar, /* 23 etb */ BadChar, /* 24 can */ BadChar, /* 25 em */ BadChar, /* 26 sub */ BadChar, /* 27 esc */ BadChar, /* 28 fs */ BadChar, /* 29 gs */ BadChar, /* 30 rs */ BadChar, /* 31 us */ BadChar, /* 32 sp */ BadChar, /* 33 ! */ UserInfoChar, /* 34 " */ BadChar, /* 35 # */ PathSegmentEndChar | BadChar, /* 36 $ */ UserInfoChar, /* 37 % */ UserInfoChar | HostnameChar | IPv6Char | BadChar, /* 38 & */ UserInfoChar, /* 39 ' */ UserInfoChar, /* 40 ( */ UserInfoChar, /* 41 ) */ UserInfoChar, /* 42 * */ UserInfoChar, /* 43 + */ SchemeChar | UserInfoChar, /* 44 , */ UserInfoChar, /* 45 - */ SchemeChar | UserInfoChar | HostnameChar, /* 46 . */ SchemeChar | UserInfoChar | HostnameChar, /* 47 / */ PathSegmentEndChar, /* 48 0 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 49 1 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 50 2 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 51 3 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 52 4 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 53 5 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 54 6 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 55 7 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 56 8 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 57 9 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 58 : */ UserInfoChar | IPv6Char, /* 59 ; */ UserInfoChar, /* 60 < */ BadChar, /* 61 = */ UserInfoChar, /* 62 > */ BadChar, /* 63 ? */ PathSegmentEndChar | BadChar, /* 64 @ */ 0, /* 65 A */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 66 B */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 67 C */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 68 D */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 69 E */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 70 F */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 71 G */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 72 H */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 73 I */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 74 J */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 75 K */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 76 L */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 77 M */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 78 N */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 79 O */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 80 P */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 81 Q */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 82 R */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 83 S */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 84 T */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 85 U */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 86 V */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 87 W */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 88 X */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 89 Y */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 90 Z */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 91 [ */ 0, /* 92 \ */ 0, /* 93 ] */ 0, /* 94 ^ */ 0, /* 95 _ */ UserInfoChar | HostnameChar, /* 96 ` */ 0, /* 97 a */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 98 b */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 99 c */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 100 d */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 101 e */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 102 f */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char, /* 103 g */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 104 h */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 105 i */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 106 j */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 107 k */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 108 l */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 109 m */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 110 n */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 111 o */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 112 p */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 113 q */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 114 r */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 115 s */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 116 t */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 117 u */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 118 v */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 119 w */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 120 x */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 121 y */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 122 z */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar, /* 123 { */ 0, /* 124 | */ 0, /* 125 } */ 0, /* 126 ~ */ UserInfoChar, /* 127 del */ BadChar, /* 128 */ BadChar, /* 129 */ BadChar, /* 130 */ BadChar, /* 131 */ BadChar, /* 132 */ BadChar, /* 133 */ BadChar, /* 134 */ BadChar, /* 135 */ BadChar, /* 136 */ BadChar, /* 137 */ BadChar, /* 138 */ BadChar, /* 139 */ BadChar, /* 140 */ BadChar, /* 141 */ BadChar, /* 142 */ BadChar, /* 143 */ BadChar, /* 144 */ BadChar, /* 145 */ BadChar, /* 146 */ BadChar, /* 147 */ BadChar, /* 148 */ BadChar, /* 149 */ BadChar, /* 150 */ BadChar, /* 151 */ BadChar, /* 152 */ BadChar, /* 153 */ BadChar, /* 154 */ BadChar, /* 155 */ BadChar, /* 156 */ BadChar, /* 157 */ BadChar, /* 158 */ BadChar, /* 159 */ BadChar, /* 160 */ BadChar, /* 161 */ BadChar, /* 162 */ BadChar, /* 163 */ BadChar, /* 164 */ BadChar, /* 165 */ BadChar, /* 166 */ BadChar, /* 167 */ BadChar, /* 168 */ BadChar, /* 169 */ BadChar, /* 170 */ BadChar, /* 171 */ BadChar, /* 172 */ BadChar, /* 173 */ BadChar, /* 174 */ BadChar, /* 175 */ BadChar, /* 176 */ BadChar, /* 177 */ BadChar, /* 178 */ BadChar, /* 179 */ BadChar, /* 180 */ BadChar, /* 181 */ BadChar, /* 182 */ BadChar, /* 183 */ BadChar, /* 184 */ BadChar, /* 185 */ BadChar, /* 186 */ BadChar, /* 187 */ BadChar, /* 188 */ BadChar, /* 189 */ BadChar, /* 190 */ BadChar, /* 191 */ BadChar, /* 192 */ BadChar, /* 193 */ BadChar, /* 194 */ BadChar, /* 195 */ BadChar, /* 196 */ BadChar, /* 197 */ BadChar, /* 198 */ BadChar, /* 199 */ BadChar, /* 200 */ BadChar, /* 201 */ BadChar, /* 202 */ BadChar, /* 203 */ BadChar, /* 204 */ BadChar, /* 205 */ BadChar, /* 206 */ BadChar, /* 207 */ BadChar, /* 208 */ BadChar, /* 209 */ BadChar, /* 210 */ BadChar, /* 211 */ BadChar, /* 212 */ BadChar, /* 213 */ BadChar, /* 214 */ BadChar, /* 215 */ BadChar, /* 216 */ BadChar, /* 217 */ BadChar, /* 218 */ BadChar, /* 219 */ BadChar, /* 220 */ BadChar, /* 221 */ BadChar, /* 222 */ BadChar, /* 223 */ BadChar, /* 224 */ BadChar, /* 225 */ BadChar, /* 226 */ BadChar, /* 227 */ BadChar, /* 228 */ BadChar, /* 229 */ BadChar, /* 230 */ BadChar, /* 231 */ BadChar, /* 232 */ BadChar, /* 233 */ BadChar, /* 234 */ BadChar, /* 235 */ BadChar, /* 236 */ BadChar, /* 237 */ BadChar, /* 238 */ BadChar, /* 239 */ BadChar, /* 240 */ BadChar, /* 241 */ BadChar, /* 242 */ BadChar, /* 243 */ BadChar, /* 244 */ BadChar, /* 245 */ BadChar, /* 246 */ BadChar, /* 247 */ BadChar, /* 248 */ BadChar, /* 249 */ BadChar, /* 250 */ BadChar, /* 251 */ BadChar, /* 252 */ BadChar, /* 253 */ BadChar, /* 254 */ BadChar, /* 255 */ BadChar }; static int copyPathRemovingDots(char* dst, const char* src, int srcStart, int srcEnd); static void encodeRelativeString(const String& rel, const TextEncoding&, CharBuffer& ouput); static String substituteBackslashes(const String&); static inline bool isSchemeFirstChar(char c) { return characterClassTable[static_cast<unsigned char>(c)] & SchemeFirstChar; } static inline bool isSchemeFirstChar(UChar c) { return c <= 0xff && (characterClassTable[c] & SchemeFirstChar); } static inline bool isSchemeChar(char c) { return characterClassTable[static_cast<unsigned char>(c)] & SchemeChar; } static inline bool isSchemeChar(UChar c) { return c <= 0xff && (characterClassTable[c] & SchemeChar); } static inline bool isUserInfoChar(unsigned char c) { return characterClassTable[c] & UserInfoChar; } static inline bool isHostnameChar(unsigned char c) { return characterClassTable[c] & HostnameChar; } static inline bool isIPv6Char(unsigned char c) { return characterClassTable[c] & IPv6Char; } static inline bool isPathSegmentEndChar(char c) { return characterClassTable[static_cast<unsigned char>(c)] & PathSegmentEndChar; } static inline bool isPathSegmentEndChar(UChar c) { return c <= 0xff && (characterClassTable[c] & PathSegmentEndChar); } static inline bool isBadChar(unsigned char c) { return characterClassTable[c] & BadChar; } static inline int hexDigitValue(UChar c) { ASSERT(isASCIIHexDigit(c)); if (c < 'A') return c - '0'; return (c - 'A' + 10) & 0xF; // handle both upper and lower case without a branch } // Copies the source to the destination, assuming all the source characters are // ASCII. The destination buffer must be large enough. Null characters are allowed // in the source string, and no attempt is made to null-terminate the result. static void copyASCII(const UChar* src, int length, char* dest) { for (int i = 0; i < length; i++) dest[i] = static_cast<char>(src[i]); } static void appendASCII(const String& base, const char* rel, size_t len, CharBuffer& buffer) { buffer.resize(base.length() + len + 1); copyASCII(base.characters(), base.length(), buffer.data()); memcpy(buffer.data() + base.length(), rel, len); buffer[buffer.size() - 1] = '\0'; } // FIXME: Move to PlatformString.h eventually. // Returns the index of the first index in string |s| of any of the characters // in |toFind|. |toFind| should be a null-terminated string, all characters up // to the null will be searched. Returns int if not found. static int findFirstOf(const UChar* s, int sLen, int startPos, const char* toFind) { for (int i = startPos; i < sLen; i++) { const char* cur = toFind; while (*cur) { if (s[i] == *(cur++)) return i; } } return -1; } #ifndef NDEBUG static void checkEncodedString(const String& url) { for (unsigned i = 0; i < url.length(); ++i) ASSERT(!(url[i] & ~0x7F)); ASSERT(!url.length() || isSchemeFirstChar(url[0])); } #else static inline void checkEncodedString(const String&) { } #endif inline bool KURL::protocolIs(const String& string, const char* protocol) { return WebCore::protocolIs(string, protocol); } void KURL::invalidate() { m_isValid = false; m_protocolInHTTPFamily = false; m_schemeEnd = 0; m_userStart = 0; m_userEnd = 0; m_passwordEnd = 0; m_hostEnd = 0; m_portEnd = 0; m_pathEnd = 0; m_pathAfterLastSlash = 0; m_queryEnd = 0; m_fragmentEnd = 0; } KURL::KURL(ParsedURLStringTag, const char* url) { parse(url, 0); ASSERT(url == m_string); } KURL::KURL(ParsedURLStringTag, const String& url) { parse(url); ASSERT(url == m_string); } KURL::KURL(const KURL& base, const String& relative) { init(base, relative, UTF8Encoding()); } KURL::KURL(const KURL& base, const String& relative, const TextEncoding& encoding) { // For UTF-{7,16,32}, we want to use UTF-8 for the query part as // we do when submitting a form. A form with GET method // has its contents added to a URL as query params and it makes sense // to be consistent. init(base, relative, encoding.encodingForFormSubmission()); } void KURL::init(const KURL& base, const String& relative, const TextEncoding& encoding) { // Allow resolutions with a null or empty base URL, but not with any other invalid one. // FIXME: Is this a good rule? if (!base.m_isValid && !base.isEmpty()) { m_string = relative; invalidate(); return; } // For compatibility with Win IE, treat backslashes as if they were slashes, // as long as we're not dealing with javascript: or data: URLs. String rel = relative; if (rel.contains('\\') && !(protocolIsJavaScript(rel) || protocolIs(rel, "data"))) rel = substituteBackslashes(rel); String* originalString = &rel; bool allASCII = charactersAreAllASCII(rel.characters(), rel.length()); CharBuffer strBuffer; char* str; size_t len; if (allASCII) { len = rel.length(); strBuffer.resize(len + 1); copyASCII(rel.characters(), len, strBuffer.data()); strBuffer[len] = 0; str = strBuffer.data(); } else { originalString = 0; encodeRelativeString(rel, encoding, strBuffer); str = strBuffer.data(); len = strlen(str); } // Get rid of leading whitespace. while (*str == ' ') { originalString = 0; str++; --len; } // Get rid of trailing whitespace. while (len && str[len - 1] == ' ') { originalString = 0; str[--len] = '\0'; } // According to the RFC, the reference should be interpreted as an // absolute URI if possible, using the "leftmost, longest" // algorithm. If the URI reference is absolute it will have a // scheme, meaning that it will have a colon before the first // non-scheme element. bool absolute = false; char* p = str; if (isSchemeFirstChar(*p)) { ++p; while (isSchemeChar(*p)) { ++p; } if (*p == ':') { if (p[1] != '/' && equalIgnoringCase(base.protocol(), String(str, p - str)) && base.isHierarchical()) { str = p + 1; originalString = 0; } else absolute = true; } } CharBuffer parseBuffer; if (absolute) { parse(str, originalString); } else { // If the base is empty or opaque (e.g. data: or javascript:), then the URL is invalid // unless the relative URL is a single fragment. if (!base.isHierarchical()) { if (str[0] == '#') { appendASCII(base.m_string.left(base.m_queryEnd), str, len, parseBuffer); parse(parseBuffer.data(), 0); } else { m_string = relative; invalidate(); } return; } switch (str[0]) { case '\0': // the reference must be empty - the RFC says this is a // reference to the same document *this = base; break; case '#': { // must be fragment-only reference appendASCII(base.m_string.left(base.m_queryEnd), str, len, parseBuffer); parse(parseBuffer.data(), 0); break; } case '?': { // query-only reference, special case needed for non-URL results appendASCII(base.m_string.left(base.m_pathEnd), str, len, parseBuffer); parse(parseBuffer.data(), 0); break; } case '/': // must be net-path or absolute-path reference if (str[1] == '/') { // net-path appendASCII(base.m_string.left(base.m_schemeEnd + 1), str, len, parseBuffer); parse(parseBuffer.data(), 0); } else { // abs-path appendASCII(base.m_string.left(base.m_portEnd), str, len, parseBuffer); parse(parseBuffer.data(), 0); } break; default: { // must be relative-path reference // Base part plus relative part plus one possible slash added in between plus terminating \0 byte. parseBuffer.resize(base.m_pathEnd + 1 + len + 1); char* bufferPos = parseBuffer.data(); // first copy everything before the path from the base unsigned baseLength = base.m_string.length(); const UChar* baseCharacters = base.m_string.characters(); CharBuffer baseStringBuffer(baseLength); copyASCII(baseCharacters, baseLength, baseStringBuffer.data()); const char* baseString = baseStringBuffer.data(); const char* baseStringStart = baseString; const char* pathStart = baseStringStart + base.m_portEnd; while (baseStringStart < pathStart) *bufferPos++ = *baseStringStart++; char* bufferPathStart = bufferPos; // now copy the base path const char* baseStringEnd = baseString + base.m_pathEnd; // go back to the last slash while (baseStringEnd > baseStringStart && baseStringEnd[-1] != '/') baseStringEnd--; if (baseStringEnd == baseStringStart) { // no path in base, add a path separator if necessary if (base.m_schemeEnd + 1 != base.m_pathEnd && *str && *str != '?' && *str != '#') *bufferPos++ = '/'; } else { bufferPos += copyPathRemovingDots(bufferPos, baseStringStart, 0, baseStringEnd - baseStringStart); } const char* relStringStart = str; const char* relStringPos = relStringStart; while (*relStringPos && *relStringPos != '?' && *relStringPos != '#') { if (relStringPos[0] == '.' && bufferPos[-1] == '/') { if (isPathSegmentEndChar(relStringPos[1])) { // skip over "." segment relStringPos += 1; if (relStringPos[0] == '/') relStringPos++; continue; } else if (relStringPos[1] == '.' && isPathSegmentEndChar(relStringPos[2])) { // skip over ".." segment and rewind the last segment // the RFC leaves it up to the app to decide what to do with excess // ".." segments - we choose to drop them since some web content // relies on this. relStringPos += 2; if (relStringPos[0] == '/') relStringPos++; if (bufferPos > bufferPathStart + 1) bufferPos--; while (bufferPos > bufferPathStart + 1 && bufferPos[-1] != '/') bufferPos--; continue; } } *bufferPos = *relStringPos; relStringPos++; bufferPos++; } // all done with the path work, now copy any remainder // of the relative reference; this will also add a null terminator strcpy(bufferPos, relStringPos); parse(parseBuffer.data(), 0); ASSERT(strlen(parseBuffer.data()) + 1 <= parseBuffer.size()); break; } } } } KURL KURL::copy() const { KURL result = *this; result.m_string = result.m_string.crossThreadString(); return result; } bool KURL::hasPath() const { return m_pathEnd != m_portEnd; } String KURL::lastPathComponent() const { if (!hasPath()) return String(); int end = m_pathEnd - 1; if (m_string[end] == '/') --end; int start = m_string.reverseFind('/', end); if (start < m_portEnd) return String(); ++start; return m_string.substring(start, end - start + 1); } String KURL::protocol() const { return m_string.left(m_schemeEnd); } String KURL::host() const { int start = hostStart(); return decodeURLEscapeSequences(m_string.substring(start, m_hostEnd - start)); } unsigned short KURL::port() const { if (m_hostEnd == m_portEnd) return 0; int number = m_string.substring(m_hostEnd + 1, m_portEnd - m_hostEnd - 1).toInt(); if (number < 0 || number > 0xFFFF) return 0; return number; } String KURL::pass() const { if (m_passwordEnd == m_userEnd) return String(); return decodeURLEscapeSequences(m_string.substring(m_userEnd + 1, m_passwordEnd - m_userEnd - 1)); } String KURL::user() const { return decodeURLEscapeSequences(m_string.substring(m_userStart, m_userEnd - m_userStart)); } String KURL::fragmentIdentifier() const { if (m_fragmentEnd == m_queryEnd) return String(); return m_string.substring(m_queryEnd + 1, m_fragmentEnd - (m_queryEnd + 1)); } bool KURL::hasFragmentIdentifier() const { return m_fragmentEnd != m_queryEnd; } String KURL::baseAsString() const { return m_string.left(m_pathAfterLastSlash); } #ifdef NDEBUG static inline void assertProtocolIsGood(const char*) { } #else static void assertProtocolIsGood(const char* protocol) { const char* p = protocol; while (*p) { ASSERT(*p > ' ' && *p < 0x7F && !(*p >= 'A' && *p <= 'Z')); ++p; } } #endif bool KURL::protocolIs(const char* protocol) const { assertProtocolIsGood(protocol); // JavaScript URLs are "valid" and should be executed even if KURL decides they are invalid. // The free function protocolIsJavaScript() should be used instead. ASSERT(strcmp(protocol, "javascript") != 0); if (!m_isValid) return false; // Do the comparison without making a new string object. for (int i = 0; i < m_schemeEnd; ++i) { if (!protocol[i] || toASCIILower(m_string[i]) != protocol[i]) return false; } return !protocol[m_schemeEnd]; // We should have consumed all characters in the argument. } String KURL::query() const { if (m_queryEnd == m_pathEnd) return String(); return m_string.substring(m_pathEnd + 1, m_queryEnd - (m_pathEnd + 1)); } String KURL::path() const { return decodeURLEscapeSequences(m_string.substring(m_portEnd, m_pathEnd - m_portEnd)); } void KURL::setProtocol(const String& s) { // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations, // and to avoid changing more than just the protocol. if (!m_isValid) { parse(s + ":" + m_string); return; } parse(s + m_string.substring(m_schemeEnd)); } void KURL::setHost(const String& s) { if (!m_isValid) return; // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations, // and to avoid changing more than just the host. bool slashSlashNeeded = m_userStart == m_schemeEnd + 1; parse(m_string.left(hostStart()) + (slashSlashNeeded ? "//" : "") + s + m_string.substring(m_hostEnd)); } void KURL::setPort(unsigned short i) { if (!m_isValid) return; if (i) { bool colonNeeded = m_portEnd == m_hostEnd; int portStart = (colonNeeded ? m_hostEnd : m_hostEnd + 1); parse(m_string.left(portStart) + (colonNeeded ? ":" : "") + String::number(i) + m_string.substring(m_portEnd)); } else parse(m_string.left(m_hostEnd) + m_string.substring(m_portEnd)); } void KURL::setHostAndPort(const String& hostAndPort) { if (!m_isValid) return; // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations, // and to avoid changing more than just host and port. bool slashSlashNeeded = m_userStart == m_schemeEnd + 1; parse(m_string.left(hostStart()) + (slashSlashNeeded ? "//" : "") + hostAndPort + m_string.substring(m_portEnd)); } void KURL::setUser(const String& user) { if (!m_isValid) return; // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations, // and to avoid changing more than just the user login. String u; int end = m_userEnd; if (!user.isEmpty()) { u = user; if (m_userStart == m_schemeEnd + 1) u = "//" + u; // Add '@' if we didn't have one before. if (end == m_hostEnd || (end == m_passwordEnd && m_string[end] != '@')) u.append('@'); } else { // Remove '@' if we now have neither user nor password. if (m_userEnd == m_passwordEnd && end != m_hostEnd && m_string[end] == '@') end += 1; } parse(m_string.left(m_userStart) + u + m_string.substring(end)); } void KURL::setPass(const String& password) { if (!m_isValid) return; // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations, // and to avoid changing more than just the user password. String p; int end = m_passwordEnd; if (!password.isEmpty()) { p = ":" + password + "@"; if (m_userEnd == m_schemeEnd + 1) p = "//" + p; // Eat the existing '@' since we are going to add our own. if (end != m_hostEnd && m_string[end] == '@') end += 1; } else { // Remove '@' if we now have neither user nor password. if (m_userStart == m_userEnd && end != m_hostEnd && m_string[end] == '@') end += 1; } parse(m_string.left(m_userEnd) + p + m_string.substring(end)); } void KURL::setFragmentIdentifier(const String& s) { if (!m_isValid) return; // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations. parse(m_string.left(m_queryEnd) + "#" + s); } void KURL::removeFragmentIdentifier() { if (!m_isValid) return; parse(m_string.left(m_queryEnd)); } void KURL::setQuery(const String& query) { if (!m_isValid) return; // FIXME: '#' and non-ASCII characters must be encoded and escaped. // Usually, the query is encoded using document encoding, not UTF-8, but we don't have // access to the document in this function. if ((query.isEmpty() || query[0] != '?') && !query.isNull()) parse(m_string.left(m_pathEnd) + "?" + query + m_string.substring(m_queryEnd)); else parse(m_string.left(m_pathEnd) + query + m_string.substring(m_queryEnd)); } void KURL::setPath(const String& s) { if (!m_isValid) return; // FIXME: encodeWithURLEscapeSequences does not correctly escape '#' and '?', so fragment and query parts // may be inadvertently affected. parse(m_string.left(m_portEnd) + encodeWithURLEscapeSequences(s) + m_string.substring(m_pathEnd)); } String KURL::prettyURL() const { if (!m_isValid) return m_string; Vector<UChar> result; append(result, protocol()); result.append(':'); Vector<UChar> authority; if (m_hostEnd != m_passwordEnd) { if (m_userEnd != m_userStart) { append(authority, user()); authority.append('@'); } append(authority, host()); if (port() != 0) { authority.append(':'); append(authority, String::number(port())); } } if (!authority.isEmpty()) { result.append('/'); result.append('/'); result.append(authority); } else if (protocolIs("file")) { result.append('/'); result.append('/'); } append(result, path()); if (m_pathEnd != m_queryEnd) { result.append('?'); append(result, query()); } if (m_fragmentEnd != m_queryEnd) { result.append('#'); append(result, fragmentIdentifier()); } return String::adopt(result); } String decodeURLEscapeSequences(const String& str) { return decodeURLEscapeSequences(str, UTF8Encoding()); } String decodeURLEscapeSequences(const String& str, const TextEncoding& encoding) { Vector<UChar> result; CharBuffer buffer; int length = str.length(); int decodedPosition = 0; int searchPosition = 0; int encodedRunPosition; while ((encodedRunPosition = str.find('%', searchPosition)) >= 0) { // Find the sequence of %-escape codes. int encodedRunEnd = encodedRunPosition; while (length - encodedRunEnd >= 3 && str[encodedRunEnd] == '%' && isASCIIHexDigit(str[encodedRunEnd + 1]) && isASCIIHexDigit(str[encodedRunEnd + 2])) encodedRunEnd += 3; if (encodedRunEnd == encodedRunPosition) { ++searchPosition; continue; } searchPosition = encodedRunEnd; // Decode the %-escapes into bytes. unsigned runLength = (encodedRunEnd - encodedRunPosition) / 3; buffer.resize(runLength); char* p = buffer.data(); const UChar* q = str.characters() + encodedRunPosition; for (unsigned i = 0; i < runLength; ++i) { *p++ = (hexDigitValue(q[1]) << 4) | hexDigitValue(q[2]); q += 3; } // Decode the bytes into Unicode characters. String decoded = (encoding.isValid() ? encoding : UTF8Encoding()).decode(buffer.data(), p - buffer.data()); if (decoded.isEmpty()) continue; // Build up the string with what we just skipped and what we just decoded. result.append(str.characters() + decodedPosition, encodedRunPosition - decodedPosition); result.append(decoded.characters(), decoded.length()); decodedPosition = encodedRunEnd; } result.append(str.characters() + decodedPosition, length - decodedPosition); return String::adopt(result); } bool KURL::isLocalFile() const { // Including feed here might be a bad idea since drag and drop uses this check // and including feed would allow feeds to potentially let someone's blog // read the contents of the clipboard on a drag, even without a drop. // Likewise with using the FrameLoader::shouldTreatURLAsLocal() function. return protocolIs("file"); } static void appendEscapingBadChars(char*& buffer, const char* strStart, size_t length) { char* p = buffer; const char* str = strStart; const char* strEnd = strStart + length; while (str < strEnd) { unsigned char c = *str++; if (isBadChar(c)) { if (c == '%' || c == '?') { *p++ = c; } else if (c != 0x09 && c != 0x0a && c != 0x0d) { *p++ = '%'; *p++ = hexDigits[c >> 4]; *p++ = hexDigits[c & 0xF]; } } else { *p++ = c; } } buffer = p; } // copy a path, accounting for "." and ".." segments static int copyPathRemovingDots(char* dst, const char* src, int srcStart, int srcEnd) { char* bufferPathStart = dst; // empty path is a special case, and need not have a leading slash if (srcStart != srcEnd) { const char* baseStringStart = src + srcStart; const char* baseStringEnd = src + srcEnd; const char* baseStringPos = baseStringStart; // this code is unprepared for paths that do not begin with a // slash and we should always have one in the source string ASSERT(baseStringPos[0] == '/'); // copy the leading slash into the destination *dst = *baseStringPos; baseStringPos++; dst++; while (baseStringPos < baseStringEnd) { if (baseStringPos[0] == '.' && dst[-1] == '/') { if (baseStringPos[1] == '/' || baseStringPos + 1 == baseStringEnd) { // skip over "." segment baseStringPos += 2; continue; } else if (baseStringPos[1] == '.' && (baseStringPos[2] == '/' || baseStringPos + 2 == baseStringEnd)) { // skip over ".." segment and rewind the last segment // the RFC leaves it up to the app to decide what to do with excess // ".." segments - we choose to drop them since some web content // relies on this. baseStringPos += 3; if (dst > bufferPathStart + 1) dst--; // Note that these two while blocks differ subtly. // The first helps to remove multiple adjoining slashes as we rewind. // The +1 to bufferPathStart in the first while block prevents eating a leading slash while (dst > bufferPathStart + 1 && dst[-1] == '/') dst--; while (dst > bufferPathStart && dst[-1] != '/') dst--; continue; } } *dst = *baseStringPos; baseStringPos++; dst++; } } *dst = '\0'; return dst - bufferPathStart; } static inline bool hasSlashDotOrDotDot(const char* str) { const unsigned char* p = reinterpret_cast<const unsigned char*>(str); if (!*p) return false; unsigned char pc = *p; while (unsigned char c = *++p) { if (c == '.' && (pc == '/' || pc == '.')) return true; pc = c; } return false; } static inline bool matchLetter(char c, char lowercaseLetter) { return (c | 0x20) == lowercaseLetter; } void KURL::parse(const String& string) { checkEncodedString(string); CharBuffer buffer(string.length() + 1); copyASCII(string.characters(), string.length(), buffer.data()); buffer[string.length()] = '\0'; parse(buffer.data(), &string); } void KURL::parse(const char* url, const String* originalString) { if (!url || url[0] == '\0') { // valid URL must be non-empty m_string = originalString ? *originalString : url; invalidate(); return; } if (!isSchemeFirstChar(url[0])) { // scheme must start with an alphabetic character m_string = originalString ? *originalString : url; invalidate(); return; } int schemeEnd = 0; while (isSchemeChar(url[schemeEnd])) schemeEnd++; if (url[schemeEnd] != ':') { m_string = originalString ? *originalString : url; invalidate(); return; } int userStart = schemeEnd + 1; int userEnd; int passwordStart; int passwordEnd; int hostStart; int hostEnd; int portStart; int portEnd; bool hierarchical = url[schemeEnd + 1] == '/'; bool isFile = schemeEnd == 4 && matchLetter(url[0], 'f') && matchLetter(url[1], 'i') && matchLetter(url[2], 'l') && matchLetter(url[3], 'e'); m_protocolInHTTPFamily = matchLetter(url[0], 'h') && matchLetter(url[1], 't') && matchLetter(url[2], 't') && matchLetter(url[3], 'p') && (url[4] == ':' || (matchLetter(url[4], 's') && url[5] == ':')); if (hierarchical && url[schemeEnd + 2] == '/') { // The part after the scheme is either a net_path or an abs_path whose first path segment is empty. // Attempt to find an authority. // FIXME: Authority characters may be scanned twice, and it would be nice to be faster. userStart += 2; userEnd = userStart; int colonPos = 0; while (isUserInfoChar(url[userEnd])) { if (url[userEnd] == ':' && colonPos == 0) colonPos = userEnd; userEnd++; } if (url[userEnd] == '@') { // actual end of the userinfo, start on the host if (colonPos != 0) { passwordEnd = userEnd; userEnd = colonPos; passwordStart = colonPos + 1; } else passwordStart = passwordEnd = userEnd; hostStart = passwordEnd + 1; } else if (url[userEnd] == '[' || isPathSegmentEndChar(url[userEnd])) { // hit the end of the authority, must have been no user // or looks like an IPv6 hostname // either way, try to parse it as a hostname userEnd = userStart; passwordStart = passwordEnd = userEnd; hostStart = userStart; } else { // invalid character m_string = originalString ? *originalString : url; invalidate(); return; } hostEnd = hostStart; // IPV6 IP address if (url[hostEnd] == '[') { hostEnd++; while (isIPv6Char(url[hostEnd])) hostEnd++; if (url[hostEnd] == ']') hostEnd++; else { // invalid character m_string = originalString ? *originalString : url; invalidate(); return; } } else { while (isHostnameChar(url[hostEnd])) hostEnd++; } if (url[hostEnd] == ':') { portStart = portEnd = hostEnd + 1; // possible start of port portEnd = portStart; while (isASCIIDigit(url[portEnd])) portEnd++; } else portStart = portEnd = hostEnd; if (!isPathSegmentEndChar(url[portEnd])) { // invalid character m_string = originalString ? *originalString : url; invalidate(); return; } if (userStart == portEnd && !m_protocolInHTTPFamily && !isFile) { // No authority found, which means that this is not a net_path, but rather an abs_path whose first two // path segments are empty. For file, http and https only, an empty authority is allowed. userStart -= 2; userEnd = userStart; passwordStart = userEnd; passwordEnd = passwordStart; hostStart = passwordEnd; hostEnd = hostStart; portStart = hostEnd; portEnd = hostEnd; } } else { // the part after the scheme must be an opaque_part or an abs_path userEnd = userStart; passwordStart = passwordEnd = userEnd; hostStart = hostEnd = passwordEnd; portStart = portEnd = hostEnd; } int pathStart = portEnd; int pathEnd = pathStart; while (url[pathEnd] && url[pathEnd] != '?' && url[pathEnd] != '#') pathEnd++; int queryStart = pathEnd; int queryEnd = queryStart; if (url[queryStart] == '?') { while (url[queryEnd] && url[queryEnd] != '#') queryEnd++; } int fragmentStart = queryEnd; int fragmentEnd = fragmentStart; if (url[fragmentStart] == '#') { fragmentStart++; fragmentEnd = fragmentStart; while (url[fragmentEnd]) fragmentEnd++; } // assemble it all, remembering the real ranges Vector<char, 4096> buffer(fragmentEnd * 3 + 1); char *p = buffer.data(); const char *strPtr = url; // copy in the scheme const char *schemeEndPtr = url + schemeEnd; while (strPtr < schemeEndPtr) *p++ = *strPtr++; m_schemeEnd = p - buffer.data(); bool hostIsLocalHost = portEnd - userStart == 9 && matchLetter(url[userStart], 'l') && matchLetter(url[userStart+1], 'o') && matchLetter(url[userStart+2], 'c') && matchLetter(url[userStart+3], 'a') && matchLetter(url[userStart+4], 'l') && matchLetter(url[userStart+5], 'h') && matchLetter(url[userStart+6], 'o') && matchLetter(url[userStart+7], 's') && matchLetter(url[userStart+8], 't'); // File URLs need a host part unless it is just file:// or file://localhost bool degenFilePath = pathStart == pathEnd && (hostStart == hostEnd || hostIsLocalHost); bool haveNonHostAuthorityPart = userStart != userEnd || passwordStart != passwordEnd || portStart != portEnd; // add ":" after scheme *p++ = ':'; // if we have at least one authority part or a file URL - add "//" and authority if (isFile ? !degenFilePath : (haveNonHostAuthorityPart || hostStart != hostEnd)) { *p++ = '/'; *p++ = '/'; m_userStart = p - buffer.data(); // copy in the user strPtr = url + userStart; const char* userEndPtr = url + userEnd; while (strPtr < userEndPtr) *p++ = *strPtr++; m_userEnd = p - buffer.data(); // copy in the password if (passwordEnd != passwordStart) { *p++ = ':'; strPtr = url + passwordStart; const char* passwordEndPtr = url + passwordEnd; while (strPtr < passwordEndPtr) *p++ = *strPtr++; } m_passwordEnd = p - buffer.data(); // If we had any user info, add "@" if (p - buffer.data() != m_userStart) *p++ = '@'; // copy in the host, except in the case of a file URL with authority="localhost" if (!(isFile && hostIsLocalHost && !haveNonHostAuthorityPart)) { strPtr = url + hostStart; const char* hostEndPtr = url + hostEnd; while (strPtr < hostEndPtr) *p++ = *strPtr++; } m_hostEnd = p - buffer.data(); // copy in the port if (hostEnd != portStart) { *p++ = ':'; strPtr = url + portStart; const char *portEndPtr = url + portEnd; while (strPtr < portEndPtr) *p++ = *strPtr++; } m_portEnd = p - buffer.data(); } else m_userStart = m_userEnd = m_passwordEnd = m_hostEnd = m_portEnd = p - buffer.data(); // For canonicalization, ensure we have a '/' for no path. // Do this only for hierarchical URL with protocol http or https. if (m_protocolInHTTPFamily && hierarchical && pathEnd == pathStart) *p++ = '/'; // add path, escaping bad characters if (!hierarchical || !hasSlashDotOrDotDot(url)) appendEscapingBadChars(p, url + pathStart, pathEnd - pathStart); else { CharBuffer pathBuffer(pathEnd - pathStart + 1); size_t length = copyPathRemovingDots(pathBuffer.data(), url, pathStart, pathEnd); appendEscapingBadChars(p, pathBuffer.data(), length); } m_pathEnd = p - buffer.data(); // Find the position after the last slash in the path, or // the position before the path if there are no slashes in it. int i; for (i = m_pathEnd; i > m_portEnd; --i) { if (buffer[i - 1] == '/') break; } m_pathAfterLastSlash = i; // add query, escaping bad characters appendEscapingBadChars(p, url + queryStart, queryEnd - queryStart); m_queryEnd = p - buffer.data(); // add fragment, escaping bad characters if (fragmentEnd != queryEnd) { *p++ = '#'; appendEscapingBadChars(p, url + fragmentStart, fragmentEnd - fragmentStart); } m_fragmentEnd = p - buffer.data(); ASSERT(p - buffer.data() <= static_cast<int>(buffer.size())); // If we didn't end up actually changing the original string and // it was already in a String, reuse it to avoid extra allocation. if (originalString && originalString->length() == static_cast<unsigned>(m_fragmentEnd) && strncmp(buffer.data(), url, m_fragmentEnd) == 0) m_string = *originalString; else m_string = String(buffer.data(), m_fragmentEnd); m_isValid = true; } bool equalIgnoringFragmentIdentifier(const KURL& a, const KURL& b) { if (a.m_queryEnd != b.m_queryEnd) return false; unsigned queryLength = a.m_queryEnd; for (unsigned i = 0; i < queryLength; ++i) if (a.string()[i] != b.string()[i]) return false; return true; } bool protocolHostAndPortAreEqual(const KURL& a, const KURL& b) { if (a.m_schemeEnd != b.m_schemeEnd) return false; int hostStartA = a.hostStart(); int hostStartB = b.hostStart(); if (a.m_hostEnd - hostStartA != b.m_hostEnd - hostStartB) return false; // Check the scheme for (int i = 0; i < a.m_schemeEnd; ++i) if (a.string()[i] != b.string()[i]) return false; // And the host for (int i = hostStartA; i < a.m_hostEnd; ++i) if (a.string()[i] != b.string()[i]) return false; if (a.port() != b.port()) return false; return true; } String encodeWithURLEscapeSequences(const String& notEncodedString) { CString asUTF8 = notEncodedString.utf8(); CharBuffer buffer(asUTF8.length() * 3 + 1); char* p = buffer.data(); const char* str = asUTF8.data(); const char* strEnd = str + asUTF8.length(); while (str < strEnd) { unsigned char c = *str++; if (isBadChar(c)) { *p++ = '%'; *p++ = hexDigits[c >> 4]; *p++ = hexDigits[c & 0xF]; } else *p++ = c; } ASSERT(p - buffer.data() <= static_cast<int>(buffer.size())); return String(buffer.data(), p - buffer.data()); } // Appends the punycoded hostname identified by the given string and length to // the output buffer. The result will not be null terminated. static void appendEncodedHostname(UCharBuffer& buffer, const UChar* str, unsigned strLen) { // Needs to be big enough to hold an IDN-encoded name. // For host names bigger than this, we won't do IDN encoding, which is almost certainly OK. const unsigned hostnameBufferLength = 2048; if (strLen > hostnameBufferLength || charactersAreAllASCII(str, strLen)) { buffer.append(str, strLen); return; } #if USE(ICU_UNICODE) UChar hostnameBuffer[hostnameBufferLength]; UErrorCode error = U_ZERO_ERROR; int32_t numCharactersConverted = uidna_IDNToASCII(str, strLen, hostnameBuffer, hostnameBufferLength, UIDNA_ALLOW_UNASSIGNED, 0, &error); if (error == U_ZERO_ERROR) buffer.append(hostnameBuffer, numCharactersConverted); #elif USE(QT4_UNICODE) QByteArray result = QUrl::toAce(String(str, strLen)); buffer.append(result.constData(), result.length()); #endif } static void findHostnamesInMailToURL(const UChar* str, int strLen, Vector<pair<int, int> >& nameRanges) { // In a mailto: URL, host names come after a '@' character and end with a '>' or ',' or '?' or end of string character. // Skip quoted strings so that characters in them don't confuse us. // When we find a '?' character, we are past the part of the URL that contains host names. nameRanges.clear(); int p = 0; while (1) { // Find start of host name or of quoted string. int hostnameOrStringStart = findFirstOf(str, strLen, p, "\"@?"); if (hostnameOrStringStart == -1) return; UChar c = str[hostnameOrStringStart]; p = hostnameOrStringStart + 1; if (c == '?') return; if (c == '@') { // Find end of host name. int hostnameStart = p; int hostnameEnd = findFirstOf(str, strLen, p, ">,?"); bool done; if (hostnameEnd == -1) { hostnameEnd = strLen; done = true; } else { p = hostnameEnd; done = false; } nameRanges.append(make_pair(hostnameStart, hostnameEnd)); if (done) return; } else { // Skip quoted string. ASSERT(c == '"'); while (1) { int escapedCharacterOrStringEnd = findFirstOf(str, strLen, p, "\"\\"); if (escapedCharacterOrStringEnd == -1) return; c = str[escapedCharacterOrStringEnd]; p = escapedCharacterOrStringEnd + 1; // If we are the end of the string, then break from the string loop back to the host name loop. if (c == '"') break; // Skip escaped character. ASSERT(c == '\\'); if (p == strLen) return; ++p; } } } } static bool findHostnameInHierarchicalURL(const UChar* str, int strLen, int& startOffset, int& endOffset) { // Find the host name in a hierarchical URL. // It comes after a "://" sequence, with scheme characters preceding, and // this should be the first colon in the string. // It ends with the end of the string or a ":" or a path segment ending character. // If there is a "@" character, the host part is just the part after the "@". int separator = findFirstOf(str, strLen, 0, ":"); if (separator == -1 || separator + 2 >= strLen || str[separator + 1] != '/' || str[separator + 2] != '/') return false; // Check that all characters before the :// are valid scheme characters. if (!isSchemeFirstChar(str[0])) return false; for (int i = 1; i < separator; ++i) { if (!isSchemeChar(str[i])) return false; } // Start after the separator. int authorityStart = separator + 3; // Find terminating character. int hostnameEnd = strLen; for (int i = authorityStart; i < strLen; ++i) { UChar c = str[i]; if (c == ':' || (isPathSegmentEndChar(c) && c != 0)) { hostnameEnd = i; break; } } // Find "@" for the start of the host name. int userInfoTerminator = findFirstOf(str, strLen, authorityStart, "@"); int hostnameStart; if (userInfoTerminator == -1 || userInfoTerminator > hostnameEnd) hostnameStart = authorityStart; else hostnameStart = userInfoTerminator + 1; startOffset = hostnameStart; endOffset = hostnameEnd; return true; } // Converts all hostnames found in the given input to punycode, preserving the // rest of the URL unchanged. The output will NOT be null-terminated. static void encodeHostnames(const String& str, UCharBuffer& output) { output.clear(); if (protocolIs(str, "mailto")) { Vector<pair<int, int> > hostnameRanges; findHostnamesInMailToURL(str.characters(), str.length(), hostnameRanges); int n = hostnameRanges.size(); int p = 0; for (int i = 0; i < n; ++i) { const pair<int, int>& r = hostnameRanges[i]; output.append(&str.characters()[p], r.first - p); appendEncodedHostname(output, &str.characters()[r.first], r.second - r.first); p = r.second; } // This will copy either everything after the last hostname, or the // whole thing if there is no hostname. output.append(&str.characters()[p], str.length() - p); } else { int hostStart, hostEnd; if (findHostnameInHierarchicalURL(str.characters(), str.length(), hostStart, hostEnd)) { output.append(str.characters(), hostStart); // Before hostname. appendEncodedHostname(output, &str.characters()[hostStart], hostEnd - hostStart); output.append(&str.characters()[hostEnd], str.length() - hostEnd); // After hostname. } else { // No hostname to encode, return the input. output.append(str.characters(), str.length()); } } } static void encodeRelativeString(const String& rel, const TextEncoding& encoding, CharBuffer& output) { UCharBuffer s; encodeHostnames(rel, s); TextEncoding pathEncoding(UTF8Encoding()); // Path is always encoded as UTF-8; other parts may depend on the scheme. int pathEnd = -1; if (encoding != pathEncoding && encoding.isValid() && !protocolIs(rel, "mailto") && !protocolIs(rel, "data") && !protocolIsJavaScript(rel)) { // Find the first instance of either # or ?, keep pathEnd at -1 otherwise. pathEnd = findFirstOf(s.data(), s.size(), 0, "#?"); } if (pathEnd == -1) { CString decoded = pathEncoding.encode(s.data(), s.size(), URLEncodedEntitiesForUnencodables); output.resize(decoded.length()); memcpy(output.data(), decoded.data(), decoded.length()); } else { CString pathDecoded = pathEncoding.encode(s.data(), pathEnd, URLEncodedEntitiesForUnencodables); // Unencodable characters in URLs are represented by converting // them to XML entities and escaping non-alphanumeric characters. CString otherDecoded = encoding.encode(s.data() + pathEnd, s.size() - pathEnd, URLEncodedEntitiesForUnencodables); output.resize(pathDecoded.length() + otherDecoded.length()); memcpy(output.data(), pathDecoded.data(), pathDecoded.length()); memcpy(output.data() + pathDecoded.length(), otherDecoded.data(), otherDecoded.length()); } output.append('\0'); // null-terminate the output. } static String substituteBackslashes(const String& string) { int questionPos = string.find('?'); int hashPos = string.find('#'); int pathEnd; if (hashPos >= 0 && (questionPos < 0 || questionPos > hashPos)) pathEnd = hashPos; else if (questionPos >= 0) pathEnd = questionPos; else pathEnd = string.length(); return string.left(pathEnd).replace('\\','/') + string.substring(pathEnd); } bool KURL::isHierarchical() const { if (!m_isValid) return false; ASSERT(m_string[m_schemeEnd] == ':'); return m_string[m_schemeEnd + 1] == '/'; } void KURL::copyToBuffer(CharBuffer& buffer) const { // FIXME: This throws away the high bytes of all the characters in the string! // That's fine for a valid URL, which is all ASCII, but not for invalid URLs. buffer.resize(m_string.length()); copyASCII(m_string.characters(), m_string.length(), buffer.data()); } bool protocolIs(const String& url, const char* protocol) { // Do the comparison without making a new string object. assertProtocolIsGood(protocol); for (int i = 0; ; ++i) { if (!protocol[i]) return url[i] == ':'; if (toASCIILower(url[i]) != protocol[i]) return false; } } bool protocolIsJavaScript(const String& url) { return protocolIs(url, "javascript"); } String mimeTypeFromDataURL(const String& url) { ASSERT(protocolIs(url, "data")); int index = url.find(';'); if (index == -1) index = url.find(','); if (index != -1) { int len = index - 5; if (len > 0) return url.substring(5, len); return "text/plain"; // Data URLs with no MIME type are considered text/plain. } return ""; } const KURL& blankURL() { DEFINE_STATIC_LOCAL(KURL, staticBlankURL, (ParsedURLString, "about:blank")); return staticBlankURL; } #ifndef NDEBUG void KURL::print() const { printf("%s\n", m_string.utf8().data()); } #endif } #endif // !USE(GOOGLEURL)
radekp/qt
src/3rdparty/webkit/WebCore/platform/KURL.cpp
C++
lgpl-2.1
59,394
/* Copyright (C) 2011 Fredrik Johansson This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */ #ifndef NMOD_POLY_MAT_H #define NMOD_POLY_MAT_H #ifdef NMOD_POLY_MAT_INLINES_C #define NMOD_POLY_MAT_INLINE FLINT_DLL #else #define NMOD_POLY_MAT_INLINE static __inline__ #endif #include <gmp.h> #include "flint.h" #include "ulong_extras.h" #include "nmod_vec.h" #include "nmod_poly.h" #include "nmod_mat.h" #ifdef __cplusplus extern "C" { #endif /* Types *********************************************************************/ typedef struct { nmod_poly_struct * entries; slong r; slong c; nmod_poly_struct ** rows; mp_limb_t modulus; } nmod_poly_mat_struct; typedef nmod_poly_mat_struct nmod_poly_mat_t[1]; NMOD_POLY_MAT_INLINE nmod_poly_struct * nmod_poly_mat_entry(const nmod_poly_mat_t mat, slong i, slong j) { return mat->rows[i] + j; } NMOD_POLY_MAT_INLINE slong nmod_poly_mat_nrows(const nmod_poly_mat_t mat) { return mat->r; } NMOD_POLY_MAT_INLINE slong nmod_poly_mat_ncols(const nmod_poly_mat_t mat) { return mat->c; } /* Memory management *********************************************************/ FLINT_DLL void nmod_poly_mat_init(nmod_poly_mat_t mat, slong rows, slong cols, mp_limb_t n); FLINT_DLL void nmod_poly_mat_init_set(nmod_poly_mat_t mat, const nmod_poly_mat_t src); FLINT_DLL void nmod_poly_mat_swap(nmod_poly_mat_t mat1, nmod_poly_mat_t mat2); NMOD_POLY_MAT_INLINE void nmod_poly_mat_swap_entrywise(nmod_poly_mat_t mat1, nmod_poly_mat_t mat2) { slong i, j; for (i = 0; i < nmod_poly_mat_nrows(mat1); i++) for (j = 0; j < nmod_poly_mat_ncols(mat1); j++) nmod_poly_swap(nmod_poly_mat_entry(mat2, i, j), nmod_poly_mat_entry(mat1, i, j)); } FLINT_DLL void nmod_poly_mat_set(nmod_poly_mat_t mat1, const nmod_poly_mat_t mat2); FLINT_DLL void nmod_poly_mat_clear(nmod_poly_mat_t mat); /* Basic properties **********************************************************/ NMOD_POLY_MAT_INLINE mp_limb_t nmod_poly_mat_modulus(const nmod_poly_mat_t mat) { return mat->modulus; } /* Comparison ****************************************************************/ FLINT_DLL int nmod_poly_mat_equal(const nmod_poly_mat_t mat1, const nmod_poly_mat_t mat2); FLINT_DLL int nmod_poly_mat_is_zero(const nmod_poly_mat_t mat); FLINT_DLL int nmod_poly_mat_is_one(const nmod_poly_mat_t mat); NMOD_POLY_MAT_INLINE int nmod_poly_mat_is_empty(const nmod_poly_mat_t mat) { return (mat->r == 0) || (mat->c == 0); } NMOD_POLY_MAT_INLINE int nmod_poly_mat_is_square(const nmod_poly_mat_t mat) { return (mat->r == mat->c); } /* Standard matrices *********************************************************/ FLINT_DLL void nmod_poly_mat_zero(nmod_poly_mat_t mat); FLINT_DLL void nmod_poly_mat_one(nmod_poly_mat_t mat); /* Random matrices ***********************************************************/ FLINT_DLL void nmod_poly_mat_randtest(nmod_poly_mat_t mat, flint_rand_t state, slong len); FLINT_DLL void nmod_poly_mat_randtest_sparse(nmod_poly_mat_t A, flint_rand_t state, slong len, float density); /* Windows and concatenation */ FLINT_DLL void nmod_poly_mat_window_init(nmod_poly_mat_t window, const nmod_poly_mat_t mat, slong r1, slong c1, slong r2, slong c2); FLINT_DLL void nmod_poly_mat_window_clear(nmod_poly_mat_t window); FLINT_DLL void nmod_poly_mat_concat_horizontal(nmod_poly_mat_t res, const nmod_poly_mat_t mat1, const nmod_poly_mat_t mat2); FLINT_DLL void nmod_poly_mat_concat_vertical(nmod_poly_mat_t res, const nmod_poly_mat_t mat1, const nmod_poly_mat_t mat2); /* Input and output **********************************************************/ FLINT_DLL void nmod_poly_mat_print(const nmod_poly_mat_t mat, const char * x); /* Norms *********************************************************************/ FLINT_DLL slong nmod_poly_mat_max_length(const nmod_poly_mat_t A); /* Scalar arithmetic *********************************************************/ FLINT_DLL void nmod_poly_mat_scalar_mul_nmod_poly(nmod_poly_mat_t B, const nmod_poly_mat_t A, const nmod_poly_t c); FLINT_DLL void nmod_poly_mat_scalar_mul_nmod(nmod_poly_mat_t B, const nmod_poly_mat_t A, mp_limb_t c); /* Matrix arithmetic *********************************************************/ FLINT_DLL void nmod_poly_mat_add(nmod_poly_mat_t C, const nmod_poly_mat_t A, const nmod_poly_mat_t B); FLINT_DLL void nmod_poly_mat_sub(nmod_poly_mat_t C, const nmod_poly_mat_t A, const nmod_poly_mat_t B); FLINT_DLL void nmod_poly_mat_neg(nmod_poly_mat_t B, const nmod_poly_mat_t A); FLINT_DLL void nmod_poly_mat_mul(nmod_poly_mat_t C, const nmod_poly_mat_t A, const nmod_poly_mat_t B); FLINT_DLL void nmod_poly_mat_mul_interpolate(nmod_poly_mat_t C, const nmod_poly_mat_t A, const nmod_poly_mat_t B); FLINT_DLL void nmod_poly_mat_mul_classical(nmod_poly_mat_t C, const nmod_poly_mat_t A, const nmod_poly_mat_t B); FLINT_DLL void nmod_poly_mat_mul_KS(nmod_poly_mat_t C, const nmod_poly_mat_t A, const nmod_poly_mat_t B); FLINT_DLL void nmod_poly_mat_sqr(nmod_poly_mat_t B, const nmod_poly_mat_t A); FLINT_DLL void nmod_poly_mat_sqr_classical(nmod_poly_mat_t B, const nmod_poly_mat_t A); FLINT_DLL void nmod_poly_mat_sqr_KS(nmod_poly_mat_t B, const nmod_poly_mat_t A); FLINT_DLL void nmod_poly_mat_sqr_interpolate(nmod_poly_mat_t B, const nmod_poly_mat_t A); FLINT_DLL void nmod_poly_mat_pow(nmod_poly_mat_t B, const nmod_poly_mat_t A, ulong exp); /* Evaluation ****************************************************************/ FLINT_DLL void nmod_poly_mat_evaluate_nmod(nmod_mat_t B, const nmod_poly_mat_t A, mp_limb_t x); /* Row reduction *************************************************************/ FLINT_DLL slong nmod_poly_mat_find_pivot_any(const nmod_poly_mat_t mat, slong start_row, slong end_row, slong c); FLINT_DLL slong nmod_poly_mat_find_pivot_partial(const nmod_poly_mat_t mat, slong start_row, slong end_row, slong c); FLINT_DLL slong nmod_poly_mat_fflu(nmod_poly_mat_t B, nmod_poly_t den, slong * perm, const nmod_poly_mat_t A, int rank_check); FLINT_DLL slong nmod_poly_mat_rref(nmod_poly_mat_t B, nmod_poly_t den, const nmod_poly_mat_t A); /* Trace *********************************************************************/ FLINT_DLL void nmod_poly_mat_trace(nmod_poly_t trace, const nmod_poly_mat_t mat); /* Determinant and rank ******************************************************/ FLINT_DLL void nmod_poly_mat_det(nmod_poly_t det, const nmod_poly_mat_t A); FLINT_DLL void nmod_poly_mat_det_fflu(nmod_poly_t det, const nmod_poly_mat_t A); FLINT_DLL void nmod_poly_mat_det_interpolate(nmod_poly_t det, const nmod_poly_mat_t A); FLINT_DLL slong nmod_poly_mat_rank(const nmod_poly_mat_t A); /* Inverse *******************************************************************/ FLINT_DLL int nmod_poly_mat_inv(nmod_poly_mat_t Ainv, nmod_poly_t den, const nmod_poly_mat_t A); /* Nullspace *****************************************************************/ FLINT_DLL slong nmod_poly_mat_nullspace(nmod_poly_mat_t res, const nmod_poly_mat_t mat); /* Solving *******************************************************************/ FLINT_DLL int nmod_poly_mat_solve(nmod_poly_mat_t X, nmod_poly_t den, const nmod_poly_mat_t A, const nmod_poly_mat_t B); FLINT_DLL int nmod_poly_mat_solve_fflu(nmod_poly_mat_t X, nmod_poly_t den, const nmod_poly_mat_t A, const nmod_poly_mat_t B); FLINT_DLL void nmod_poly_mat_solve_fflu_precomp(nmod_poly_mat_t X, const slong * perm, const nmod_poly_mat_t FFLU, const nmod_poly_mat_t B); #ifdef __cplusplus } #endif #endif
fredrik-johansson/flint2
nmod_poly_mat.h
C
lgpl-2.1
8,424
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "ambientproperties.h" #include <QtGui> QT_BEGIN_NAMESPACE AmbientProperties::AmbientProperties(QWidget *parent) : QDialog(parent), container(0) { setupUi(this); connect(buttonClose, SIGNAL(clicked()), this, SLOT(close())); } void AmbientProperties::setControl(QWidget *widget) { container = widget; QColor c = container->palette().color(container->backgroundRole()); QPalette p = backSample->palette(); p.setColor(backSample->backgroundRole(), c); backSample->setPalette(p); c = container->palette().color(container->foregroundRole()); p = foreSample->palette(); p.setColor(foreSample->backgroundRole(), c); foreSample->setPalette(p); fontSample->setFont( container->font() ); buttonEnabled->setChecked( container->isEnabled() ); enabledSample->setEnabled( container->isEnabled() ); } void AmbientProperties::on_buttonBackground_clicked() { QColor c = QColorDialog::getColor(backSample->palette().color(backSample->backgroundRole()), this); QPalette p = backSample->palette(); p.setColor(backSample->backgroundRole(), c); backSample->setPalette(p); p = container->palette(); p.setColor(container->backgroundRole(), c); container->setPalette(p); if (QWorkspace *ws = qobject_cast<QWorkspace*>(container)) { QWidgetList list( ws->windowList() ); for (int i = 0; i < list.count(); ++i) { QWidget *widget = list.at(i); p = widget->palette(); p.setColor(widget->backgroundRole(), c); widget->setPalette(p); } } } void AmbientProperties::on_buttonForeground_clicked() { QColor c = QColorDialog::getColor(foreSample->palette().color(foreSample->backgroundRole()), this); QPalette p = foreSample->palette(); p.setColor(foreSample->backgroundRole(), c); foreSample->setPalette(p); p = container->palette(); p.setColor(container->foregroundRole(), c); container->setPalette(p); if (QWorkspace *ws = qobject_cast<QWorkspace*>(container)) { QWidgetList list( ws->windowList() ); for (int i = 0; i < list.count(); ++i) { QWidget *widget = list.at(i); p = widget->palette(); p.setColor(widget->foregroundRole(), c); widget->setPalette(p); } } } void AmbientProperties::on_buttonFont_clicked() { bool ok; QFont f = QFontDialog::getFont( &ok, fontSample->font(), this ); if ( !ok ) return; fontSample->setFont( f ); container->setFont( f ); if (QWorkspace *ws = qobject_cast<QWorkspace*>(container)) { QWidgetList list( ws->windowList() ); for (int i = 0; i < list.count(); ++i) { QWidget *widget = list.at(i); widget->setFont( f ); } } } void AmbientProperties::on_buttonEnabled_toggled(bool on) { enabledSample->setEnabled( on ); container->setEnabled( on ); } QT_END_NAMESPACE
sunblithe/qt-everywhere-opensource-src-4.7.1
tools/activeqt/testcon/ambientproperties.cpp
C++
lgpl-2.1
4,694
/* Copyright (C) 2013 Mike Hansen This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */ #include "fq_zech_poly.h" #ifdef T #undef T #endif #define T fq_zech #define CAP_T FQ_ZECH #include "fq_poly_templates/truncate.c" #undef CAP_T #undef T
wbhart/flint2
fq_zech_poly/truncate.c
C
lgpl-2.1
534
/* * Ext JS Library 2.3.0 * Copyright(c) 2006-2009, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ /** * @class Ext.form.Action * <p>The subclasses of this class provide actions to perform upon {@link Ext.form.BasicForm Form}s.</p> * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when * the Form needs to perform an action such as submit or load. The Configuration options * listed for this class are set through the Form's action methods: {@link Ext.form.BasicForm#submit submit}, * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}</p> * <p>The instance of Action which performed the action is passed to the success * and failure callbacks of the Form's action methods ({@link Ext.form.BasicForm#submit submit}, * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}), * and to the {@link Ext.form.BasicForm#actioncomplete actioncomplete} and * {@link Ext.form.BasicForm#actionfailed actionfailed} event handlers.</p> */ Ext.form.Action = function(form, options){ this.form = form; this.options = options || {}; }; /** * Failure type returned when client side validation of the Form fails * thus aborting a submit action. * @type {String} * @static */ Ext.form.Action.CLIENT_INVALID = 'client'; /** * Failure type returned when server side validation of the Form fails * indicating that field-specific error messages have been returned in the * response's <tt style="font-weight:bold">errors</tt> property. * @type {String} * @static */ Ext.form.Action.SERVER_INVALID = 'server'; /** * Failure type returned when a communication error happens when attempting * to send a request to the remote server. * @type {String} * @static */ Ext.form.Action.CONNECT_FAILURE = 'connect'; /** * Failure type returned when no field values are returned in the response's * <tt style="font-weight:bold">data</tt> property. * @type {String} * @static */ Ext.form.Action.LOAD_FAILURE = 'load'; Ext.form.Action.prototype = { /** * @cfg {String} url The URL that the Action is to invoke. */ /** * @cfg {Boolean} reset When set to <tt><b>true</b></tt>, causes the Form to be * {@link Ext.form.BasicForm.reset reset} on Action success. If specified, this happens * <b>before</b> the {@link #success} callback is called and before the Form's * {@link Ext.form.BasicForm.actioncomplete actioncomplete} event fires. */ /** * @cfg {String} method The HTTP method to use to access the requested URL. Defaults to the * {@link Ext.form.BasicForm}'s method, or if that is not specified, the underlying DOM form's method. */ /** * @cfg {Mixed} params<p>Extra parameter values to pass. These are added to the Form's * {@link Ext.form.BasicForm#baseParams} and passed to the specified URL along with the Form's * input fields.</p> * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p> */ /** * @cfg {Number} timeout The number of milliseconds to wait for a server response before * failing with the {@link #failureType} as {@link #Action.CONNECT_FAILURE}. */ /** * @cfg {Function} success The function to call when a valid success return packet is recieved. * The function is passed the following parameters:<ul class="mdetail-params"> * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li> * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. The {@link #result} * property of this object may be examined to perform custom postprocessing.</div></li> * </ul> */ /** * @cfg {Function} failure The function to call when a failure packet was recieved, or when an * error ocurred in the Ajax communication. * The function is passed the following parameters:<ul class="mdetail-params"> * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li> * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. If an Ajax * error ocurred, the failure type will be in {@link #failureType}. The {@link #result} * property of this object may be examined to perform custom postprocessing.</div></li> * </ul> */ /** * @cfg {Object} scope The scope in which to call the callback functions (The <tt>this</tt> reference * for the callback functions). */ /** * @cfg {String} waitMsg The message to be displayed by a call to {@link Ext.MessageBox#wait} * during the time the action is being processed. */ /** * @cfg {String} waitTitle The title to be displayed by a call to {@link Ext.MessageBox#wait} * during the time the action is being processed. */ /** * The type of action this Action instance performs. * Currently only "submit" and "load" are supported. * @type {String} */ type : 'default', /** * The type of failure detected. See {@link link Ext.form.Action#Action.CLIENT_INVALID CLIENT_INVALID}, * {@link link Ext.form.Action#Action.SERVER_INVALID SERVER_INVALID}, * {@link #link Ext.form.ActionAction.CONNECT_FAILURE CONNECT_FAILURE}, {@link Ext.form.Action#Action.LOAD_FAILURE LOAD_FAILURE} * @property failureType * @type {String} *//** * The XMLHttpRequest object used to perform the action. * @property response * @type {Object} *//** * The decoded response object containing a boolean <tt style="font-weight:bold">success</tt> property and * other, action-specific properties. * @property result * @type {Object} */ // interface method run : function(options){ }, // interface method success : function(response){ }, // interface method handleResponse : function(response){ }, // default connection failure failure : function(response){ this.response = response; this.failureType = Ext.form.Action.CONNECT_FAILURE; this.form.afterAction(this, false); }, // private processResponse : function(response){ this.response = response; if(!response.responseText && !response.responseXML){ return true; } this.result = this.handleResponse(response); return this.result; }, // utility functions used internally getUrl : function(appendParams){ var url = this.options.url || this.form.url || this.form.el.dom.action; if(appendParams){ var p = this.getParams(); if(p){ url += (url.indexOf('?') != -1 ? '&' : '?') + p; } } return url; }, // private getMethod : function(){ return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase(); }, // private getParams : function(){ var bp = this.form.baseParams; var p = this.options.params; if(p){ if(typeof p == "object"){ p = Ext.urlEncode(Ext.applyIf(p, bp)); }else if(typeof p == 'string' && bp){ p += '&' + Ext.urlEncode(bp); } }else if(bp){ p = Ext.urlEncode(bp); } return p; }, // private createCallback : function(opts){ var opts = opts || {}; return { success: this.success, failure: this.failure, scope: this, timeout: (opts.timeout*1000) || (this.form.timeout*1000), upload: this.form.fileUpload ? this.success : undefined }; } }; /** * @class Ext.form.Action.Submit * @extends Ext.form.Action * <p>A class which handles submission of data from {@link Ext.form.BasicForm Form}s * and processes the returned response.</p> * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when * {@link Ext.form.BasicForm#submit submit}ting.</p> * <p>A response packet must contain a boolean <tt style="font-weight:bold">success</tt> property, and, optionally * an <tt style="font-weight:bold">errors</tt> property. The <tt style="font-weight:bold">errors</tt> property contains error * messages for invalid fields.</p> * <p>By default, response packets are assumed to be JSON, so a typical response * packet may look like this:</p><pre><code> { success: false, errors: { clientCode: "Client not found", portOfLoading: "This field must not be null" } }</code></pre> * <p>Other data may be placed into the response for processing by the {@link Ext.form.BasicForm}'s callback * or event handler methods. The object decoded from this JSON is available in the {@link #result} property.</p> * <p>Alternatively, if an {@link #errorReader} is specified as an {@link Ext.data.XmlReader XmlReader}:</p><pre><code> errorReader: new Ext.data.XmlReader({ record : 'field', success: '@success' }, [ 'id', 'msg' ] ) </code></pre> * <p>then the results may be sent back in XML format:</p><pre><code> &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;message success="false"&gt; &lt;errors&gt; &lt;field&gt; &lt;id&gt;clientCode&lt;/id&gt; &lt;msg&gt;&lt;![CDATA[Code not found. &lt;br /&gt;&lt;i&gt;This is a test validation message from the server &lt;/i&gt;]]&gt;&lt;/msg&gt; &lt;/field&gt; &lt;field&gt; &lt;id&gt;portOfLoading&lt;/id&gt; &lt;msg&gt;&lt;![CDATA[Port not found. &lt;br /&gt;&lt;i&gt;This is a test validation message from the server &lt;/i&gt;]]&gt;&lt;/msg&gt; &lt;/field&gt; &lt;/errors&gt; &lt;/message&gt; </code></pre> * <p>Other elements may be placed into the response XML for processing by the {@link Ext.form.BasicForm}'s callback * or event handler methods. The XML document is available in the {@link #errorReader}'s {@link Ext.data.XmlReader#xmlData xmlData} property.</p> */ Ext.form.Action.Submit = function(form, options){ Ext.form.Action.Submit.superclass.constructor.call(this, form, options); }; Ext.extend(Ext.form.Action.Submit, Ext.form.Action, { /** * @cfg {Ext.data.DataReader} errorReader <b>Optional. JSON is interpreted with no need for an errorReader.</b> * <p>A Reader which reads a single record from the returned data. The DataReader's <b>success</b> property specifies * how submission success is determined. The Record's data provides the error messages to apply to any invalid form Fields.</p>. */ /** * @cfg {boolean} clientValidation Determines whether a Form's fields are validated * in a final call to {@link Ext.form.BasicForm#isValid isValid} prior to submission. * Pass <tt>false</tt> in the Form's submit options to prevent this. If not defined, pre-submission field validation * is performed. */ type : 'submit', // private run : function(){ var o = this.options; var method = this.getMethod(); var isGet = method == 'GET'; if(o.clientValidation === false || this.form.isValid()){ Ext.Ajax.request(Ext.apply(this.createCallback(o), { form:this.form.el.dom, url:this.getUrl(isGet), method: method, headers: o.headers, params:!isGet ? this.getParams() : null, isUpload: this.form.fileUpload })); }else if (o.clientValidation !== false){ // client validation failed this.failureType = Ext.form.Action.CLIENT_INVALID; this.form.afterAction(this, false); } }, // private success : function(response){ var result = this.processResponse(response); if(result === true || result.success){ this.form.afterAction(this, true); return; } if(result.errors){ this.form.markInvalid(result.errors); this.failureType = Ext.form.Action.SERVER_INVALID; } this.form.afterAction(this, false); }, // private handleResponse : function(response){ if(this.form.errorReader){ var rs = this.form.errorReader.read(response); var errors = []; if(rs.records){ for(var i = 0, len = rs.records.length; i < len; i++) { var r = rs.records[i]; errors[i] = r.data; } } if(errors.length < 1){ errors = null; } return { success : rs.success, errors : errors }; } return Ext.decode(response.responseText); } }); /** * @class Ext.form.Action.Load * @extends Ext.form.Action * <p>A class which handles loading of data from a server into the Fields of an {@link Ext.form.BasicForm}.</p> * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when * {@link Ext.form.BasicForm#load load}ing.</p> * <p>A response packet <b>must</b> contain a boolean <tt style="font-weight:bold">success</tt> property, and * a <tt style="font-weight:bold">data</tt> property. The <tt style="font-weight:bold">data</tt> property * contains the values of Fields to load. The individual value object for each Field * is passed to the Field's {@link Ext.form.Field#setValue setValue} method.</p> * <p>By default, response packets are assumed to be JSON, so a typical response * packet may look like this:</p><pre><code> { success: true, data: { clientName: "Fred. Olsen Lines", portOfLoading: "FXT", portOfDischarge: "OSL" } }</code></pre> * <p>Other data may be placed into the response for processing the {@link Ext.form.BasicForm Form}'s callback * or event handler methods. The object decoded from this JSON is available in the {@link #result} property.</p> */ Ext.form.Action.Load = function(form, options){ Ext.form.Action.Load.superclass.constructor.call(this, form, options); this.reader = this.form.reader; }; Ext.extend(Ext.form.Action.Load, Ext.form.Action, { // private type : 'load', // private run : function(){ Ext.Ajax.request(Ext.apply( this.createCallback(this.options), { method:this.getMethod(), url:this.getUrl(false), headers: this.options.headers, params:this.getParams() })); }, // private success : function(response){ var result = this.processResponse(response); if(result === true || !result.success || !result.data){ this.failureType = Ext.form.Action.LOAD_FAILURE; this.form.afterAction(this, false); return; } this.form.clearInvalid(); this.form.setValues(result.data); this.form.afterAction(this, true); }, // private handleResponse : function(response){ if(this.form.reader){ var rs = this.form.reader.read(response); var data = rs.records && rs.records[0] ? rs.records[0].data : null; return { success : rs.success, data : data }; } return Ext.decode(response.responseText); } }); Ext.form.Action.ACTION_TYPES = { 'load' : Ext.form.Action.Load, 'submit' : Ext.form.Action.Submit };
xwiki-labs/sankoreorg
web/src/main/webapp/skins/curriki20/extjs/source/widgets/form/Action.js
JavaScript
lgpl-2.1
15,291
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Iwyu(CMakePackage): """include-what-you-use: A tool for use with clang to analyze #includes in C and C++ source files """ homepage = "https://include-what-you-use.org" url = "https://include-what-you-use.org/downloads/include-what-you-use-0.13.src.tar.gz" maintainers = ['sethrj'] version('0.14', sha256='43184397db57660c32e3298a6b1fd5ab82e808a1f5ab0591d6745f8d256200ef') version('0.13', sha256='49294270aa64e8c04182369212cd919f3b3e0e47601b1f935f038c761c265bc9') version('0.12', sha256='a5892fb0abccb820c394e4e245c00ef30fc94e4ae58a048b23f94047c0816025') version('0.11', sha256='2d2877726c4aed9518cbb37673ffbc2b7da9c239bf8fe29432da35c1c0ec367a') patch('iwyu-013-cmake.patch', when='@0.13:0.14') depends_on('llvm+clang@10.0:10.999', when='@0.14') depends_on('llvm+clang@9.0:9.999', when='@0.13') depends_on('llvm+clang@8.0:8.999', when='@0.12') depends_on('llvm+clang@7.0:7.999', when='@0.11') # Non-X86 CPU use all_targets variants because iwyu use X86AsmParser depends_on('llvm+all_targets', when='target=aarch64:') depends_on('llvm+all_targets', when='target=arm:') depends_on('llvm+all_targets', when='target=ppc:') depends_on('llvm+all_targets', when='target=ppcle:') depends_on('llvm+all_targets', when='target=ppc64:') depends_on('llvm+all_targets', when='target=ppc64le:') depends_on('llvm+all_targets', when='target=sparc:') depends_on('llvm+all_targets', when='target=sparc64:') @when('@0.14:') def cmake_args(self): return [self.define('CMAKE_CXX_STANDARD', 14), self.define('CMAKE_CXX_EXTENSIONS', False)]
iulian787/spack
var/spack/repos/builtin/packages/iwyu/package.py
Python
lgpl-2.1
1,882
/* * Chrysalix * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. Some portions may be licensed * to Red Hat, Inc. under one or more contributor license agreements. * See the AUTHORS.txt file in the distribution for a full listing of * individual contributors. * * Chrysalix is free software. Unless otherwise indicated, all code in Chrysalix * is licensed to you 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. * * Chrysalix 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.chrysalix.eclipse; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPerspectiveFactory; import org.chrysalix.eclipse.view.TransformView; import org.chrysalix.eclipse.view.WorkspaceView; /** * The Chrysalix perspective definition. */ public final class PerspectiveFactory implements IPerspectiveFactory { /** * {@inheritDoc} * * @see org.eclipse.ui.IPerspectiveFactory#createInitialLayout(org.eclipse.ui.IPageLayout) */ @Override public void createInitialLayout( final IPageLayout layout ) { final String editorAreaId = layout.getEditorArea(); layout.addView( WorkspaceView.ID, IPageLayout.LEFT, 0.25f, editorAreaId ); layout.addView( TransformView.ID, IPageLayout.TOP, 0.5f, editorAreaId ); } }
Polyglotter/chrysalix
chrysalix-eclipse/plugins/org.polyglotter.eclipse/src/org/polyglotter/eclipse/PerspectiveFactory.java
Java
lgpl-2.1
1,914
// Authors: // Rafael Mizrahi <rafim@mainsoft.com> // Erez Lotan <erezl@mainsoft.com> // Oren Gurfinkel <oreng@mainsoft.com> // Ofer Borstein // // Copyright (c) 2004 Mainsoft Co. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Text; using System.IO; using System.Data; using MonoTests.System.Data.Utils; namespace MonoTests_System.Data { [TestFixture] public class ConstraintExceptionTest { [Test] public void Generate() { DataTable dtParent= DataProvider.CreateParentDataTable(); DataTable dtChild = DataProvider.CreateChildDataTable(); DataSet ds = new DataSet(); ds.Tables.Add(dtChild); ds.Tables.Add(dtParent); //------ check UniqueConstraint --------- //create unique constraint UniqueConstraint uc; //Column type = int uc = new UniqueConstraint(dtParent.Columns[0]); dtParent.Constraints.Add(uc); // UniqueConstraint Exception - Column type = int try { //add exisiting value - will raise exception dtParent.Rows.Add(dtParent.Rows[0].ItemArray); Assert.Fail("CNE1: Rows.Add failed to raise ConstraintException."); } catch (ConstraintException) {} catch (AssertionException) { throw; } catch (Exception exc) { Assert.Fail("CNE2: Rows.Add wrong exception type. Got: " + exc); } //Column type = DateTime dtParent.Constraints.Clear(); uc = new UniqueConstraint(dtParent.Columns["ParentDateTime"]); dtParent.Constraints.Add(uc); // UniqueConstraint Exception - Column type = DateTime try { //add exisiting value - will raise exception dtParent.Rows.Add(dtParent.Rows[0].ItemArray); Assert.Fail("CNE3: Rows.Add failed to raise ConstraintException."); } catch (ConstraintException) {} catch (AssertionException) { throw; } catch (Exception exc) { Assert.Fail("CNE4: Rows.Add wrong exception type. Got: " + exc); } //Column type = double dtParent.Constraints.Clear(); uc = new UniqueConstraint(dtParent.Columns["ParentDouble"]); dtParent.Constraints.Add(uc); // UniqueConstraint Exception - Column type = double try { //add exisiting value - will raise exception dtParent.Rows.Add(dtParent.Rows[0].ItemArray); Assert.Fail("CNE5: Rows.Add failed to raise ConstraintException."); } catch (ConstraintException) {} catch (AssertionException) { throw; } catch (Exception exc) { Assert.Fail("CNE6: Rows.Add wrong exception type. Got: " + exc); } //Column type = string dtParent.Constraints.Clear(); uc = new UniqueConstraint(dtParent.Columns["String1"]); dtParent.Constraints.Add(uc); // UniqueConstraint Exception - Column type = String try { //add exisiting value - will raise exception dtParent.Rows.Add(dtParent.Rows[0].ItemArray); Assert.Fail("CNE7: Rows.Add failed to raise ConstraintException."); } catch (ConstraintException) {} catch (AssertionException) { throw; } catch (Exception exc) { Assert.Fail("CNE8: Rows.Add wrong exception type. Got: " + exc); } //Column type = string, ds.CaseSensitive = false; ds.CaseSensitive = false; dtParent.Constraints.Clear(); uc = new UniqueConstraint(dtParent.Columns["String1"]); dtParent.Constraints.Add(uc); DataRow dr = dtParent.NewRow(); dr.ItemArray = dtParent.Rows[0].ItemArray ; dr["String1"] = dr["String1"].ToString().ToUpper(); // UniqueConstraint Exception - Column type = String, CaseSensitive = false; try { dtParent.Rows.Add(dr); Assert.Fail("CNE9: Rows.Add failed to raise ConstraintException."); } catch (ConstraintException) {} catch (AssertionException) { throw; } catch (Exception exc) { Assert.Fail("CNE10: Rows.Add wrong exception type. Got: " + exc); } //Column type = string, ds.CaseSensitive = true; ds.CaseSensitive = true; dtParent.Constraints.Clear(); uc = new UniqueConstraint(dtParent.Columns["String1"]); dtParent.Constraints.Add(uc); // No UniqueConstraint Exception - Column type = String, CaseSensitive = true; dtParent.Rows.Add(dr); // Column type = string, ds.CaseSensitive = false; // UniqueConstraint Exception - Column type = String, Enable CaseSensitive = true; try { ds.CaseSensitive = false; Assert.Fail("CNE13: CaseSensitive failed to raise ConstraintException."); } catch (ConstraintException) {} catch (AssertionException) { throw; } catch (Exception exc) { Assert.Fail("CNE14: CaseSensitive wrong exception type. Got: " + exc); } dtChild.Constraints.Add(new UniqueConstraint(new DataColumn[] {dtChild.Columns[0],dtChild.Columns[1]})); ds.EnforceConstraints = false; dtChild.Rows.Add(dtChild.Rows[0].ItemArray); // UniqueConstraint Exception - ds.EnforceConstraints try { ds.EnforceConstraints = true; Assert.Fail("CNE15: EnforceConstraints failed to raise ConstraintException."); } catch (ConstraintException) {} catch (AssertionException) { throw; } catch (Exception exc) { Assert.Fail("CNE16: EnforceConstraints wrong exception type. Got: " + exc); } } } }
edwinspire/VSharp
class/System.Data/Test/System.Data/ConstraintExceptionTest.cs
C#
lgpl-3.0
6,204
<?php class UpdateController extends Application_Model_Controller_Api { public function syncViewsAction(){ $this->_response->setAction( 'sync-views' ); try{ Application_Model_ViewsMapper::install( $this->_user->username ); } catch( Exception $e ){ $this->_response->throwError( $e->getMessage() ); } echo $this->_response; } /** * This action will load sql updates from the file * databases.sql * and will affect all databases belonging to an anta users. * Use spceial string {{user}} */ public function syncDbAction(){ $this->_response->setAction( 'databases' ); // get database.sql queries() // read files $updateFile = APPLICATION_PATH."/../updates/databases.sql"; if( !file_exists( $updateFile ) ){ $this->_response->throwError( "file 'updates/".basename( $updateFile)."' not found" ); } $this->_response->file = "updates/".basename( $updateFile); // read and execute sql command $query = file_get_contents( $updateFile ); $this->_response->query = $query; $executed = array(); $users = Application_Model_UsersMapper::getUsers(); // prepare the queries for each user foreach ( $users as $user ){ $executed[ $user->username ] = array( "query"=>str_replace( '{{user}}', $user->username, $query ), "result"=>"none" ); // install / reinstall views try{ Application_Model_ViewsMapper::install( $user->username ); } catch( Exception $e ){ print_r ($e); } } foreach( $executed as $username => $query ){ $queries = explode( ";",$executed[ $username ]["query"] ); foreach( $queries as $query ){ echo $query."\n"; try{ Anta_Core::mysqli()->query( $query ); echo "\tok, done.\n"; } catch( Exception $e ){ echo "\tnot executed: ".$e->getMessage()."\n"; } } } // execute query for each $this->_response->executed = $executed; // get anta users echo $this->_response; } public function __call( $a, $b ){ $action = str_replace( "Action", "", $a ); $this->_response->setAction( $action ); $this->_response->throwError( "action not found" ); } }?>
tiagy/ANTA
application/controllers/UpdateController.php
PHP
lgpl-3.0
2,212
// Copyright 2014 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum 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 3 of the License, or // (at your option) any later version. // // The go-ethereum 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package vm import ( "github.com/expanse-org/go-expanse/common" "github.com/expanse-org/go-expanse/common/math" "github.com/holiman/uint256" ) // calcMemSize64 calculates the required memory size, and returns // the size and whether the result overflowed uint64 func calcMemSize64(off, l *uint256.Int) (uint64, bool) { if !l.IsUint64() { return 0, true } return calcMemSize64WithUint(off, l.Uint64()) } // calcMemSize64WithUint calculates the required memory size, and returns // the size and whether the result overflowed uint64 // Identical to calcMemSize64, but length is a uint64 func calcMemSize64WithUint(off *uint256.Int, length64 uint64) (uint64, bool) { // if length is zero, memsize is always zero, regardless of offset if length64 == 0 { return 0, false } // Check that offset doesn't overflow offset64, overflow := off.Uint64WithOverflow() if overflow { return 0, true } val := offset64 + length64 // if value < either of it's parts, then it overflowed return val, val < offset64 } // getData returns a slice from the data based on the start and size and pads // up to size with zero's. This function is overflow safe. func getData(data []byte, start uint64, size uint64) []byte { length := uint64(len(data)) if start > length { start = length } end := start + size if end > length { end = length } return common.RightPadBytes(data[start:end], int(size)) } // toWordSize returns the ceiled word size required for memory expansion. func toWordSize(size uint64) uint64 { if size > math.MaxUint64-31 { return math.MaxUint64/32 + 1 } return (size + 31) / 32 } func allZero(b []byte) bool { for _, byte := range b { if byte != 0 { return false } } return true }
expanse-org/go-expanse
core/vm/common.go
GO
lgpl-3.0
2,516
<?php /** * Class webasystLocaleCli */ class webasystLocaleCli extends webasystCreateCliController { /** * @return bool */ protected function init() { $init = parent::init(); $this->app_id = 'webasyst'; $slug = waRequest::param(0); return $init && $slug !== 'help'; } /** * @param array $params * @return array */ public function verifyParams($params = array()) { $errors = parent::verifyParams($params); if (!empty($params[0])) { $path = $this->parsePath($params[0]); if (empty($path['type'])) { $errors['type_id'] = 'Incorrect type'; } } return $errors; } /** * @param array $params * @return array * @throws waException */ protected function create($params = []) { $parsed_path = $this->parsePath($params[0]); $entity = $this->factory($parsed_path); $parser = new waGettextParser($entity, $this->getOptions($params)); $parser->exec(); return $parser->getReport(); } protected function getOptions($params) { $options = []; if (isset($params['debug'])) { $options['debug'] = true; } return $options; } protected function showHelp() { $help = <<<HELP Usage: php wa.php locale slug [params] Slug examples: myapp someapp/plugins/myplugin someapp/themes/mytheme someapp/widgets/mywidget wa-widgets/myotherwidget wa-plugins/payment/myplugin wa-plugins/shipping/myplugin wa-plugins/sms/myplugin HELP; print $help; parent::showHelp(); } /** * @param array $config * @param array $params * @see waGettextParser->getReport(); */ protected function showReport($config = array(), $params = array()) { $text = ''; foreach ($config as $report) { if ($report['result']) { $text .= <<<TEXT Result: SUCCESS. Words for {$report['locale']} locale: Total: {$report['total']} Updated: {$report['updated']} New: {$report['new']} TEXT; } else { $text .= "Result: FAIL. For {$report['locale']} locale \n"; } } print trim($text); } /** * @param $path * @return array * @see $this->showHelp(); */ protected function parsePath($path) { $result = [ 'type' => null, 'app' => null, 'entity_id' => null, ]; $chunks = explode('/', $path); $app = ifset($chunks, 0, false); // apps level if (count($chunks) === 1) { if ($chunks[0] === 'webasyst') { $result['app'] = 'webasyst'; $result['type'] = 'webasyst'; } else { $result['app'] = $chunks[0]; $result['type'] = 'app'; } } elseif (count($chunks) === 2) { // wa-widgets level if ($app === 'wa-widgets') { $result['type'] = 'wa-widgets'; $result['entity_id'] = $chunks[1]; } } elseif (count($chunks) === 3) { $result['app'] = $app; $type = $chunks[1]; $result['entity_id'] = $chunks[2]; if ($app === 'wa-plugins') { $result['type'] = 'wa-plugins'; $result['app'] = $chunks[1]; } elseif ($type === 'plugins') { $result['type'] = 'plugins'; } elseif ($type === 'widgets') { $result['type'] = 'widgets'; } elseif ($type === 'themes') { $result['type'] = 'themes'; } } return $result; } /** * @param $parsed_path * @return waLocaleParseEntityApp|waLocaleParseEntityTheme|waLocaleParseEntityWaPlugins|waLocaleParseEntityWaWidgets * @throws waException */ protected function factory($parsed_path) { $type = $parsed_path['type']; if ($type === 'webasyst') { $result = new waLocaleParseEntityWebasyst($parsed_path); } elseif ($type === 'app') { $result = new waLocaleParseEntityApp($parsed_path); } elseif ($type === 'plugins') { $result = new waLocaleParseEntityPlugins($parsed_path); } elseif ($type === 'widgets') { $result = new waLocaleParseEntityWidgets($parsed_path); } elseif ($type === 'themes') { $result = new waLocaleParseEntityTheme($parsed_path); } elseif ($type === 'wa-plugins') { $result = new waLocaleParseEntityWaPlugins($parsed_path); } elseif ($type === 'wa-widgets') { $result = new waLocaleParseEntityWaWidgets($parsed_path); } else { throw new waException('Unknown entity type'); } return $result; } }
webasyst/webasyst-framework
wa-system/webasyst/lib/cli/webasystLocale.cli.php
PHP
lgpl-3.0
4,997
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum 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 3 of the License, or // (at your option) any later version. // // The go-ethereum 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package api import ( "fmt" "io" "net/http" "regexp" "strings" "sync" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/swarm/storage" ) var ( hashMatcher = regexp.MustCompile("^[0-9A-Fa-f]{64}") slashes = regexp.MustCompile("/+") domainAndVersion = regexp.MustCompile("[@:;,]+") ) type Resolver interface { Resolve(string) (common.Hash, error) } /* Api implements webserver/file system related content storage and retrieval on top of the dpa it is the public interface of the dpa which is included in the ethereum stack */ type Api struct { dpa *storage.DPA dns Resolver } //the api constructor initialises func NewApi(dpa *storage.DPA, dns Resolver) (self *Api) { self = &Api{ dpa: dpa, dns: dns, } return } // DPA reader API func (self *Api) Retrieve(key storage.Key) storage.LazySectionReader { return self.dpa.Retrieve(key) } func (self *Api) Store(data io.Reader, size int64, wg *sync.WaitGroup) (key storage.Key, err error) { return self.dpa.Store(data, size, wg, nil) } type ErrResolve error // DNS Resolver func (self *Api) Resolve(hostPort string, nameresolver bool) (storage.Key, error) { log.Trace(fmt.Sprintf("Resolving : %v", hostPort)) if hashMatcher.MatchString(hostPort) || self.dns == nil { log.Trace(fmt.Sprintf("host is a contentHash: '%v'", hostPort)) return storage.Key(common.Hex2Bytes(hostPort)), nil } if !nameresolver { return nil, fmt.Errorf("'%s' is not a content hash value.", hostPort) } contentHash, err := self.dns.Resolve(hostPort) if err != nil { err = ErrResolve(err) log.Warn(fmt.Sprintf("DNS error : %v", err)) } log.Trace(fmt.Sprintf("host lookup: %v -> %v", hostPort, contentHash)) return contentHash[:], err } func Parse(uri string) (hostPort, path string) { if uri == "" { return } parts := slashes.Split(uri, 3) var i int if len(parts) == 0 { return } // beginning with slash is now optional for len(parts[i]) == 0 { i++ } hostPort = parts[i] for i < len(parts)-1 { i++ if len(path) > 0 { path = path + "/" + parts[i] } else { path = parts[i] } } log.Debug(fmt.Sprintf("host: '%s', path '%s' requested.", hostPort, path)) return } func (self *Api) parseAndResolve(uri string, nameresolver bool) (key storage.Key, hostPort, path string, err error) { hostPort, path = Parse(uri) //resolving host and port contentHash, err := self.Resolve(hostPort, nameresolver) log.Debug(fmt.Sprintf("Resolved '%s' to contentHash: '%s', path: '%s'", uri, contentHash, path)) return contentHash[:], hostPort, path, err } // Put provides singleton manifest creation on top of dpa store func (self *Api) Put(content, contentType string) (string, error) { r := strings.NewReader(content) wg := &sync.WaitGroup{} key, err := self.dpa.Store(r, int64(len(content)), wg, nil) if err != nil { return "", err } manifest := fmt.Sprintf(`{"entries":[{"hash":"%v","contentType":"%s"}]}`, key, contentType) r = strings.NewReader(manifest) key, err = self.dpa.Store(r, int64(len(manifest)), wg, nil) if err != nil { return "", err } wg.Wait() return key.String(), nil } // Get uses iterative manifest retrieval and prefix matching // to resolve path to content using dpa retrieve // it returns a section reader, mimeType, status and an error func (self *Api) Get(uri string, nameresolver bool) (reader storage.LazySectionReader, mimeType string, status int, err error) { key, _, path, err := self.parseAndResolve(uri, nameresolver) if err != nil { return nil, "", 500, fmt.Errorf("can't resolve: %v", err) } quitC := make(chan bool) trie, err := loadManifest(self.dpa, key, quitC) if err != nil { log.Warn(fmt.Sprintf("loadManifestTrie error: %v", err)) return } log.Trace(fmt.Sprintf("getEntry(%s)", path)) entry, _ := trie.getEntry(path) if entry != nil { key = common.Hex2Bytes(entry.Hash) status = entry.Status mimeType = entry.ContentType log.Trace(fmt.Sprintf("content lookup key: '%v' (%v)", key, mimeType)) reader = self.dpa.Retrieve(key) } else { status = http.StatusNotFound err = fmt.Errorf("manifest entry for '%s' not found", path) log.Warn(fmt.Sprintf("%v", err)) } return } func (self *Api) Modify(uri, contentHash, contentType string, nameresolver bool) (newRootHash string, err error) { root, _, path, err := self.parseAndResolve(uri, nameresolver) if err != nil { return "", fmt.Errorf("can't resolve: %v", err) } quitC := make(chan bool) trie, err := loadManifest(self.dpa, root, quitC) if err != nil { return } if contentHash != "" { entry := &manifestTrieEntry{ Path: path, Hash: contentHash, ContentType: contentType, } trie.addEntry(entry, quitC) } else { trie.deleteEntry(path, quitC) } err = trie.recalcAndStore() if err != nil { return } return trie.hash.String(), nil }
CTCDEVTEAM/adtonethereum
swarm/api/api.go
GO
lgpl-3.0
5,680
/* * Copyright 2006 Sony Computer Entertainment Inc. * * Licensed under the MIT Open Source License, for details please see license.txt or the website * http://www.opensource.org/licenses/mit-license.php * */ #include <sstream> #include <dae.h> #include <dom.h> #include <dae/daeDatabase.h> #include <dae/daeIOPluginCommon.h> #include <dae/daeMetaElement.h> #include <dae/daeErrorHandler.h> #include <dae/daeMetaElementAttribute.h> #ifndef NO_ZAE #include <dae/daeZAEUncompressHandler.h> #endif using namespace std; daeIOPluginCommon::daeIOPluginCommon() : database(NULL), topMeta(NULL) { } daeIOPluginCommon::~daeIOPluginCommon() { } daeInt daeIOPluginCommon::setMeta(daeMetaElement *_topMeta) { topMeta = _topMeta; return DAE_OK; } void daeIOPluginCommon::setDatabase(daeDatabase* _database) { database = _database; } // This function needs to be re-entrant, it can be called recursively from inside of resolveAll // to load files that the first file depends on. daeInt daeIOPluginCommon::read(const daeURI& uri, daeString docBuffer) { // Make sure topMeta has been set before proceeding if (topMeta == NULL) { return DAE_ERR_BACKEND_IO; } // Generate a version of the URI with the fragment removed daeURI fileURI(*uri.getDAE(), uri.str(), true); //check if document already exists if ( database->isDocumentLoaded( fileURI.getURI() ) ) { return DAE_ERR_COLLECTION_ALREADY_EXISTS; } daeElementRef domObject = docBuffer ? readFromMemory(docBuffer, fileURI) : readFromFile(fileURI); // Load from URI #ifdef NO_ZAE if (!domObject) { string msg = docBuffer ? "Failed to load XML document from memory\n" : string("Failed to load ") + fileURI.str() + "\n"; daeErrorHandler::get()->handleError(msg.c_str()); return DAE_ERR_BACKEND_IO; } // Insert the document into the database, the Database will keep a ref on the main dom, so it won't get deleted // until we clear the database daeDocument *document = NULL; int res = database->insertDocument(fileURI.getURI(),domObject,&document); if (res!= DAE_OK) return res; #else bool zaeRoot = false; string extractedURI = ""; if (!domObject) { daeZAEUncompressHandler zaeHandler(fileURI); if (zaeHandler.isZipFile()) { string rootFilePath = zaeHandler.obtainRootFilePath(); daeURI rootFileURI(*fileURI.getDAE(), rootFilePath); domObject = readFromFile(rootFileURI); if (!domObject) { string msg = string("Failed to load ") + fileURI.str() + "\n"; daeErrorHandler::get()->handleError(msg.c_str()); return DAE_ERR_BACKEND_IO; } zaeRoot = true; extractedURI = rootFileURI.str(); } else { string msg = docBuffer ? "Failed to load XML document from memory\n" : string("Failed to load ") + fileURI.str() + "\n"; daeErrorHandler::get()->handleError(msg.c_str()); return DAE_ERR_BACKEND_IO; } } // Insert the document into the database, the Database will keep a ref on the main dom, so it won't get deleted // until we clear the database daeDocument *document = NULL; int res = database->insertDocument(fileURI.getURI(),domObject,&document, zaeRoot, extractedURI); if (res!= DAE_OK) return res; #endif return DAE_OK; } daeElementRef daeIOPluginCommon::beginReadElement(daeElement* parentElement, daeString elementName, const vector<attrPair>& attributes, daeInt lineNumber) { daeMetaElement* parentMeta = parentElement ? parentElement->getMeta() : topMeta; daeElementRef element = parentMeta->create(elementName); if(!element) { ostringstream msg; msg << "The DOM was unable to create an element named " << elementName << " at line " << lineNumber << ". Probably a schema violation.\n"; daeErrorHandler::get()->handleWarning( msg.str().c_str() ); return NULL; } // Process the attributes for (size_t i = 0; i < attributes.size(); i++) { daeString name = attributes[i].first, value = attributes[i].second; if (!element->setAttribute(name, value)) { ostringstream msg; msg << "The DOM was unable to create an attribute " << name << " = " << value << " at line " << lineNumber << ".\nProbably a schema violation.\n"; daeErrorHandler::get()->handleWarning(msg.str().c_str()); } } if (parentElement == NULL) { // This is the root element. Check the COLLADA version. daeURI *xmlns = (daeURI*)(element->getMeta()->getMetaAttribute( "xmlns" )->getWritableMemory( element )); if ( strcmp( xmlns->getURI(), COLLADA_NAMESPACE ) != 0 ) { // Invalid COLLADA version daeErrorHandler::get()->handleError("Trying to load an invalid COLLADA version for this DOM build!"); return NULL; } } return element; } bool daeIOPluginCommon::readElementText(daeElement* element, daeString text, daeInt elementLineNumber) { if (element->setCharData(text)) return true; ostringstream msg; msg << "The DOM was unable to set a value for element of type " << element->getTypeName() << " at line " << elementLineNumber << ".\nProbably a schema violation.\n"; daeErrorHandler::get()->handleWarning(msg.str().c_str()); return false; }
Victor-Haefner/polyvr-packaging
ubuntu/collada-dom/dom/src/dae/daeIOPluginCommon.cpp
C++
lgpl-3.0
5,414
/* * Settings.h * * Created on: Jan 11, 2014 * Author: denia */ #include <map> #include <libconfig.h++> #ifndef SETTINGS_H_ #define SETTINGS_H_ namespace ydle { class SettingsParser { private: libconfig::Config * g_configuration; std::string config_file; public: SettingsParser(); int parseCommandLine(int argc, char **argv); int parseConfigFile(std::string config_file); int parseConfigFile(); int writeConfigFile(); int parseSettings(); bool configIsOk(); void showUsage(); void showConfig(); virtual ~SettingsParser(); std::map<std::string, std::string> getConfig(); }; } /* namespace ydle */ #endif /* SETTINGS_H_ */
onartz/ydle
src/SettingsParser.h
C
lgpl-3.0
651
<?php namespace application\modules\dashboard\controllers; use application\core\utils\Cache as CacheUtil; use application\core\utils\Convert; use application\core\utils\Env; use application\core\utils\Ibos; use application\core\utils\Module; use application\core\utils\Org; use application\core\utils\Page; use application\modules\role\model\AuthItemChild; use application\modules\role\model\Node; use application\modules\role\model\NodeRelated; use application\modules\role\model\Role; use application\modules\role\model\RoleRelated; use application\modules\role\utils\Auth; use application\modules\role\utils\Role as RoleUtil; use application\modules\user\model\User; class RoletypeController extends OrganizationBaseController { protected $roleType = Role::NORMAL_TYPE; /** * 浏览操作 * @return void */ public function actionIndex() { $roles = Role::model()->fetchRolesWithUser($this->roleType); $this->render('index', array('data' => $roles)); } /** * 新增操作 * @return void */ public function actionAdd() { if (Env::submitCheck('posSubmit')) { // 获取基本数据 $data = array( 'rolename' => \CHtml::encode(Env::getRequest('rolename')), 'roletype' => $this->roleType, ); // 获取插入ID,以便后续处理 $newId = Role::model()->add($data, true); // 权限处理 if (Env::getRequest('nodes', 'P')) { $this->updateAuthItem($newId, Env::getRequest('nodes', 'P'), Env::getRequest('data-privilege', 'P')); } CacheUtil::update('role'); $newId && Org::update(); switch ($this->roleType): case Role::NORMAL_TYPE: $param = 'role/edit'; break; case Role::ADMIN_TYPE: $param = 'roleadmin/edit'; break; default: $param = 'role/edit'; //找不到就默认去角色管理 break; endswitch; $this->success(Ibos::lang('Save succeed', 'message'), $this->createUrl($param, array('op' => 'member', 'id' => $newId))); } else { $authItem = Auth::loadAuthItem(); $this->filterAuth($authItem); $data['authItem'] = $authItem; $this->render('add', $data); } } /** * 角色编辑 * @return void */ public function actionEdit() { $id = Env::getRequest('id'); if (Env::getRequest('op') == 'member') { $this->member(); exit; } if (Env::submitCheck('posSubmit')) { if (isset($_POST['rolename'])) { $data["rolename"] = $_POST['rolename']; Role::model()->modify($id, $data); } // 权限处理 if (Env::getRequest('nodes', 'P')) { $this->updateAuthItem($id, Env::getRequest('nodes', 'P'), Env::getRequest('data-privilege', 'P')); } else { $this->updateAuthItem($id, '', Env::getRequest('data-privilege', 'P')); } CacheUtil::update('role'); Org::update(); CacheUtil::clear(); $this->success(Ibos::lang('Save succeed', 'message')); } else { $role = Role::model()->fetchByPk($id); // 关联角色的权限节点 $related = NodeRelated::model()->fetchAllByRoleId($id); // 合并为一个较容易输出视图的格式 $relateCombine = RoleUtil::combineRelated($related); $data['id'] = $id; $data['role'] = $role; $data['related'] = $relateCombine; // 所有权限节点 $authItem = Auth::loadAuthItem(); $this->filterAuth($authItem); $data['authItem'] = $authItem; $this->render('edit', $data); } } protected function filterAuth(&$authItem) { $this->filterAuthType($authItem); } /** * 删除操作 * @return void */ public function actionDel() { if (Ibos::app()->request->getIsAjaxRequest()) { $id = Env::getRequest('id'); $ids = explode(',', trim($id, ',')); foreach ($ids as $roleId) { // 删除角色 Role::model()->deleteByPk($roleId); $isInstallCrm = Module::getIsEnabled('crm'); // 删除角色对应授权 Ibos::app()->authManager->removeAuthItem($roleId); // 删除辅助角色关联 RoleRelated::model()->deleteAll('roleid = :roleid', array(':roleid' => $roleId)); // 删除节点与角色关联表 NodeRelated::model()->deleteAll('roleid = :roleid', array(':roleid' => $roleId)); $related = User::model()->fetchAll(array('select' => 'uid', 'condition' => "`roleid`={$roleId}")); $relatedIds = Convert::getSubByKey($related, 'uid'); // 更新用户岗位信息 if (!empty($relatedIds)) { User::model()->updateByUids($relatedIds, array('roleid' => 0)); } } CacheUtil::update('role'); Org::update(); CacheUtil::clear(); $this->ajaxReturn(array('isSuccess' => true), 'json'); } } /** * 成员 */ public function member() { $id = Env::getRequest('id'); if (!empty($id)) { if (Env::submitCheck('postsubmit')) { $member = Env::getRequest('member'); RoleUtil::setRole($id, $member); $this->success(Ibos::lang('Save succeed', 'message')); } else { // 该角色下人员 $uids = User::model()->fetchUidByRoleId($id, false, true); // 搜索处理 if (Env::submitCheck('search')) { $key = $_POST['keyword']; $uidStr = implode(',', $uids); $users = User::model()->fetchAll("`realname` LIKE '%{$key}%' AND FIND_IN_SET(`uid`, '{$uidStr}')"); $pageUids = Convert::getSubByKey($users, 'uid'); } else { $count = count($uids); $pages = Page::create($count, self::MEMBER_LIMIT); $offset = $pages->getOffset(); $limit = $pages->getLimit(); $pageUids = array_slice($uids, $offset, $limit); $data['pages'] = $pages; } $data['id'] = $id; // for input $data['uids'] = $uids; // for js $data['uidString'] = ''; foreach ($uids as $uid) { $data['uidString'] .= "'u_" . $uid . "',"; } $data['uidString'] = trim($data['uidString'], ','); // 当前页要显示的uid(只作显示,并不为实际表单提交数据) $data['pageUids'] = $pageUids; $uniqueId = explode('/', $this->getUniqueId()); $moduleName = isset($uniqueId[0]) ? $uniqueId[0] : 'main'; $controllerName = isset($uniqueId[1]) ? $uniqueId[1] : 'default'; $viewName = sprintf('application.modules.%s.views.%s.member', $moduleName, $controllerName); $this->render($viewName, $data); } } else { $this->error('该角色不存在或已删除!'); } } /** * 更新授权认证项(新增or编辑) * @param integer $roleId 角色ID * @param array $authItem 节点 * @param array $dataVal 数据类型节点的值 * @return void */ private function updateAuthItem($roleId, $authItem = array(), $dataVal = array()) { // 所有节点数据 $nodes = Node::model()->fetchAllSortByPk('id'); // 更新关联节点数据 NodeRelated::model()->deleteAllByRoleId($roleId); // 创建认证对象 $auth = Ibos::app()->authManager; $role = $auth->getAuthItem($roleId); if ($role === null) { // 为该角色创建认证项目 $role = $auth->createRole($roleId, '', '', ''); } // 删除当前授权角色所有子项 AuthItemChild::model()->deleteByParentExceptRouteA($roleId, AuthItemChild::model()->returnExceptRouteA()); if (!empty($authItem)) { foreach ($authItem as $key => $nodeId) { $node = $nodes[$key]; // id相同为普通节点,反之为数据节点 if (strcasecmp($key, $nodeId) !== 0 && $nodeId === 'data') { $vals = $dataVal[$key]; foreach ($vals as $valsKey => $valsValue) { if (empty($valsValue)) { unset($vals[$valsKey]); } } if (is_array($vals)) { NodeRelated::model()->addRelated('', $roleId, $node); foreach ($vals as $id => $val) { $childNode = Node::model()->fetchByPk($id); NodeRelated::model()->addRelated($val, $roleId, $childNode); Auth::addRoleChildItem($role, $childNode, explode(',', $childNode['routes'])); } } } else { NodeRelated::model()->addRelated('', $roleId, $node); // 处理普通类型节点操作认证项 $routes = explode(',', $node['routes']); Auth::addRoleChildItem($role, $node, $routes); } } } } }
vlinhd11/IBOS
system/modules/dashboard/controllers/RoletypeController.php
PHP
lgpl-3.0
10,050
// Copyright 2015 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum 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 3 of the License, or // (at your option) any later version. // // The go-ethereum 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package tests import ( "testing" "github.com/expanse-org/go-expanse/params" ) func TestTransaction(t *testing.T) { t.Parallel() txt := new(testMatcher) // These can't be parsed, invalid hex in RLP txt.skipLoad("^ttWrongRLP/.*") // We don't allow more than uint64 in gas amount // This is a pseudo-consensus vulnerability, but not in practice // because of the gas limit txt.skipLoad("^ttGasLimit/TransactionWithGasLimitxPriceOverflow.json") // We _do_ allow more than uint64 in gas price, as opposed to the tests // This is also not a concern, as long as tx.Cost() uses big.Int for // calculating the final cozt txt.skipLoad(".*TransactionWithGasPriceOverflow.*") // The nonce is too large for uint64. Not a concern, it means geth won't // accept transactions at a certain point in the distant future txt.skipLoad("^ttNonce/TransactionWithHighNonce256.json") // The value is larger than uint64, which according to the test is invalid. // Geth accepts it, which is not a consensus issue since we use big.Int's // internally to calculate the cost txt.skipLoad("^ttValue/TransactionWithHighValueOverflow.json") txt.walk(t, transactionTestDir, func(t *testing.T, name string, test *TransactionTest) { cfg := params.MainnetChainConfig if err := txt.checkFailure(t, name, test.Run(cfg)); err != nil { t.Error(err) } }) }
expanse-org/go-expanse
tests/transaction_test.go
GO
lgpl-3.0
2,146
/***************************************************************************** * * * PrimeSense Sensor 5.0 Alpha * * Copyright (C) 2010 PrimeSense Ltd. * * * * This file is part of PrimeSense Common. * * * * PrimeSense Sensor 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. * * * * PrimeSense Sensor 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 PrimeSense Sensor. If not, see <http://www.gnu.org/licenses/>. * * * *****************************************************************************/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include <XnModuleCppRegistratration.h> #include "XnExportedSensorDevice.h" #include "XnSensorDepthGenerator.h" #include "XnSensorImageGenerator.h" #include "XnSensorIRGenerator.h" #include "XnSensorAudioGenerator.h" #include "XnSensorClient.h" //--------------------------------------------------------------------------- // Exporting //--------------------------------------------------------------------------- XN_EXPORT_MODULE(xn::Module) XN_EXPORT_DEVICE(XnExportedSensorDevice) XN_EXPORT_DEPTH(XnExportedSensorDepthGenerator) XN_EXPORT_IMAGE(XnExportedSensorImageGenerator) XN_EXPORT_IR(XnExportedSensorIRGenerator) XN_EXPORT_AUDIO(XnExportedSensorAudioGenerator)
sanghi/metalab_rgbdemo
nestk/deps/openni/SensorKinect/Source/XnDeviceSensorV2/XnSensorOpenNiteImpl.cpp
C++
lgpl-3.0
2,555
/** * DataCleaner (community edition) * Copyright (C) 2014 Free Software Foundation, Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.datacleaner.reference; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.Arrays; import java.util.TreeMap; import java.util.TreeSet; import org.apache.commons.lang.SerializationUtils; import org.datacleaner.util.ChangeAwareObjectInputStream; import org.junit.Ignore; import junit.framework.TestCase; public class ReferenceDataDeserializationTest extends TestCase { public void testDeserializeSimpleDictionary() throws Exception { final SimpleDictionary obj = deserialize("src/test/resources/serialized_ref_data/dc_4_dictionary_simple.dat"); assertEquals("simple dictionary", obj.getName()); assertEquals("[bar, baz, foo]", new TreeSet<>(obj.getValueSet()).toString()); assertTrue(obj.isCaseSensitive()); } public void testDeserializeTextFileDictionary() throws Exception { final TextFileDictionary obj = deserialize("src/test/resources/serialized_ref_data/dc_4_dictionary_text_file.dat"); assertEquals("text file dictionary", obj.getName()); assertEquals("dictionary.txt", obj.getFilename()); assertEquals("UTF8", obj.getEncoding()); assertTrue(obj.isCaseSensitive()); } public void testDeserializeDatastoreDictionary() throws Exception { final DatastoreDictionary obj = deserialize("src/test/resources/serialized_ref_data/dc_4_dictionary_datastore.dat"); assertEquals("datastore dictionary", obj.getName()); assertEquals("orderdb", obj.getDatastoreName()); assertEquals("dictionary.term", obj.getQualifiedColumnName()); } public void testDeserializeSimpleSynonymCatalog() throws Exception { final SimpleSynonymCatalog obj = deserialize("src/test/resources/serialized_ref_data/dc_4_synonym_catalog_simple.dat"); assertEquals("simple synonym catalog", obj.getName()); assertEquals("{DK=DK, DNK=DK, Danmark=DK, Denmark=DK}", new TreeMap<>(obj.getSynonymMap()).toString()); assertTrue(obj.isCaseSensitive()); } public void testDeserializeTextFileSynonymCatalog() throws Exception { final TextFileSynonymCatalog obj = deserialize("src/test/resources/serialized_ref_data/dc_4_synonym_catalog_text_file.dat"); assertEquals("text file synonym catalog", obj.getName()); assertEquals("synonyms.txt", obj.getFilename()); assertEquals("UTF8", obj.getEncoding()); assertTrue(obj.isCaseSensitive()); } public void testDeserializeDatastoreSynonymCatalog() throws Exception { final DatastoreSynonymCatalog obj = deserialize("src/test/resources/serialized_ref_data/dc_4_synonym_catalog_datastore.dat"); assertEquals("datastore synonym catalog", obj.getName()); assertEquals("orderdb", obj.getDatastoreName()); assertEquals("synonyms.master", obj.getMasterTermColumnPath()); assertEquals("[synonyms.syn1, synonyms.syn2]", Arrays.toString(obj.getSynonymColumnPaths())); } @SuppressWarnings("unchecked") private <T> T deserialize(final String path) throws Exception { try (FileInputStream in = new FileInputStream(new File(path))) { try (ChangeAwareObjectInputStream objectInputStream = new ChangeAwareObjectInputStream(in)) { return (T) objectInputStream.readObject(); } } } @Ignore public void testSerialize() throws Exception { final Dictionary dict1 = new SimpleDictionary("simple dictionary", "foo", "bar", "baz"); serialize(dict1, "target/dc_4_dictionary_simple.dat"); final Dictionary dict2 = new TextFileDictionary("text file dictionary", "dictionary.txt", "UTF8"); serialize(dict2, "target/dc_4_dictionary_text_file.dat"); final Dictionary dict3 = new DatastoreDictionary("datastore dictionary", "orderdb", "dictionary.term"); serialize(dict3, "target/dc_4_dictionary_datastore.dat"); final Synonym synonym = new SimpleSynonym("DK", "Denmark", "Danmark", "DNK"); final SynonymCatalog sc1 = new SimpleSynonymCatalog("simple synonym catalog", synonym); serialize(sc1, "target/dc_4_synonym_catalog_simple.dat"); final SynonymCatalog sc2 = new TextFileSynonymCatalog("text file synonym catalog", "synonyms.txt", true, "UTF8"); serialize(sc2, "target/dc_4_synonym_catalog_text_file.dat"); final SynonymCatalog sc3 = new DatastoreSynonymCatalog("datastore synonym catalog", "orderdb", "synonyms.master", new String[] { "synonyms.syn1", "synonyms.syn2" }); serialize(sc3, "target/dc_4_synonym_catalog_datastore.dat"); } private void serialize(final Serializable obj, final String path) throws Exception { try (OutputStream out = new FileOutputStream(new File(path))) { SerializationUtils.serialize(obj, out); } } }
datacleaner/DataCleaner
engine/core/src/test/java/org/datacleaner/reference/ReferenceDataDeserializationTest.java
Java
lgpl-3.0
5,880
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc on Sat Aug 31 22:02:27 BST 2002 --> <TITLE> Cactus Framework 1.4.1: Uses of Class org.apache.cactus.client.JspHttpClient </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <!-- ========== START OF NAVBAR ========== --> <A NAME="navbar_top"><!-- --></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/cactus/client/JspHttpClient.html"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="JspHttpClient.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.cactus.client.JspHttpClient</B></H2> </CENTER> No usage of org.apache.cactus.client.JspHttpClient <P> <HR> <!-- ========== START OF NAVBAR ========== --> <A NAME="navbar_bottom"><!-- --></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/cactus/client/JspHttpClient.html"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="JspHttpClient.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> Copyright &copy; 2000-2002 Apache Software Foundation. All Rights Reserved. </BODY> </HTML>
simeshev/parabuild-ci
3rdparty/cactus141j2ee13/doc/api/framework-13/org/apache/cactus/client/class-use/JspHttpClient.html
HTML
lgpl-3.0
4,049
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobileTemplate.setCreatureName('rabid_mott') mobileTemplate.setLevel(6) mobileTemplate.setDifficulty(Difficulty.NORMAL) mobileTemplate.setMinSpawnDistance(4) mobileTemplate.setMaxSpawnDistance(8) mobileTemplate.setDeathblow(False) mobileTemplate.setScale(1) mobileTemplate.setMeatType("Carnivore Meat") mobileTemplate.setMeatAmount(15) mobileTemplate.setHideType("Bristly Hide") mobileTemplate.setHideAmount(15) mobileTemplate.setBoneType("Animal Bones") mobileTemplate.setBoneAmount(5) mobileTemplate.setSocialGroup("self") mobileTemplate.setAssistRange(2) mobileTemplate.setStalker(False) mobileTemplate.setOptionsBitmask(Options.ATTACKABLE) templates = Vector() templates.add('object/mobile/shared_mott.iff') mobileTemplate.setTemplates(templates) weaponTemplates = Vector() weapontemplate = WeaponTemplate('object/weapon/melee/unarmed/shared_unarmed_default.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic') weaponTemplates.add(weapontemplate) mobileTemplate.setWeaponTemplateVector(weaponTemplates) attacks = Vector() attacks.add('bm_charge_2') attacks.add('bm_slash_2') mobileTemplate.setDefaultAttack('creatureMeleeAttack') mobileTemplate.setAttacks(attacks) core.spawnService.addMobileTemplate('rabid_mott', mobileTemplate) return
agry/NGECore2
scripts/mobiles/naboo/rabid_mott.py
Python
lgpl-3.0
1,588
import React, {Component} from "react/addons"; import {createFolder} from "editor/actions/TreeActions"; class CreateFolder extends Component<{}, {}, {}> { constructor() { super(); this.handleApply = this.handleApply.bind(this); this.handleClose = this.handleClose.bind(this); } handleClose() { this.props.onClose(); } handleApply(e) { createFolder(this.props.options.get("parentId"), this.refs.nameInput.value); } render() { return ( <div className="modal-dialog width-500"> <div className="modal-content"> <div className="modal-header"> <button className="close" onClick={this.handleClose} aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 className="modal-title">Create folder</h4> </div> <div className="modal-body"> <input type="text" className="form-control" name="folderName" ref="nameInput" autoFocus={true} /> </div> <div className="modal-footer"> <button data-name="Cancel" type="button" className="btn btn-default" onClick={this.handleClose}>Cancel</button> <input data-name="Apply" type="submit" onClick={this.handleApply} className="btn btn-primary" value="Apply" /> </div> </div> </div> ); } }; export default CreateFolder;
MrPhantomT/hexlet-ide
src/editor/components/popup/CreateFolder.js
JavaScript
lgpl-3.0
1,342
# -*- coding: utf-8 -*- # Copyright(C) 2017 Phyks (Lucas Verney) # # This file is part of a weboob module. # # This weboob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This weboob module 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this weboob module. If not, see <http://www.gnu.org/licenses/>. from weboob.tools.test import BackendTest class RATPTest(BackendTest): MODULE = 'ratp' def test_ratp_gauges(self): l = list(self.backend.iter_gauges()) assert len(l) == 26 def test_ratp_gauges_filter(self): l = list(self.backend.iter_gauges(pattern="T3A")) assert len(l) == 1 def test_ratp_sensors(self): l = list(self.backend.iter_sensors("ligne_metro_4")) assert len(l) == 1 def test_ratp_status(self): m = self.backend.get_last_measure("ligne_metro_4_sensor") assert m.level <= 0.0
vicnet/weboob
modules/ratp/test.py
Python
lgpl-3.0
1,363
/* * --------------------------------------------------------------------------- * * CAMPAIGN * * --------------------------------------------------------------------------- * * This is part of the CAMPAIGN data clustering library originating from * * Simbios, the NIH National Center for Physics-Based Simulation of Biological * * Structures at Stanford, funded under the NIH Roadmap for Medical Research, * * grant U54 GM072970 (See https://simtk.org), and the FEATURE Project at * * Stanford, funded under the NIH grant LM05652 * * (See http://feature.stanford.edu/index.php). * * * * Portions copyright (c) 2010 Stanford University, Authors, and Contributors. * * Authors: Kai J. Kolhoff * * Contributors: Marc Sosnick, William Hsu * * * * 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/>. * * --------------------------------------------------------------------------- * */ /* $Id: rmsdGPU.h 158 2011-01-12 23:06:27Z msosnick $ */ /** * \file rmsdGPU.h * \brief A CUDA implementation of Theobald's algorithm * * An implementation of Theobald's algorithm for the calculation of * protein backbone C-alpha rmsds using quaternions for the GPU * * \author Author: Kai J. Kohlhoff, Contributors: Marc Sosnick, William Hsu * \date 10/22/2009 * \version 1.0 */ #ifndef HAVE_CONFIG_H #include <iostream> #include "../util/dataio.h" #include "../util/timing.h" #include "../util/gpudevices.h" #include "../util/defaults.h" #define FLOAT_TYPE float #else #include "../config.h" #include "../campaign.h" #endif #define DIM 3 #define isCentered false using namespace std; /** * \brief calculates center of mass of C-alphas and shifts all structures to origin * each thread works on one coordinate of one conformation (3 * numConf threads) * * \param numAtoms number of atoms in each conformation (DIM coordinates each) * \param numConf number of conformations in data set * \param conf coordinates of atoms in all conformations */ __global__ static void centerAllConformations(int numAtoms, int numConf, FLOAT_TYPE *conf); /** * \brief get rmsd for a set of two structures */ __global__ static void getRMSD(int numConf, int numAtoms, int ctrConf, FLOAT_TYPE *conf, FLOAT_TYPE *rmsd); /** * \brief Runs RMSD on the GPU. Requires CUDA-enabled grapnics processor. * * \param numAtoms number of atoms in each conformation (DIM coordinates each) * \param numConf number of conformations in data set * \param conf coordinates of atoms in all conformations */ FLOAT_TYPE* rmsdGPU(int numConf, int numAtoms, FLOAT_TYPE *conf, DataIO *data);
joanorrit/campaign-1.0
install/include/campaign-1.0/campaign/rmsdGPU.h
C
lgpl-3.0
3,883
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NHibernate.OData.Test.Domain; using NHibernate.OData.Test.Support; using NUnit.Framework; namespace NHibernate.OData.Test.Criterions { [TestFixture] internal class ImplicitVariable : DomainTestFixture { [Test] public void SimpleQuery() { Verify("$filter=$it/Int32 eq 2", Session.QueryOver<Parent>().Where(x => x.Int32 == 2).List()); } [Test] public void ThrowsOnEmptyMemberExpression() { VerifyThrows<ODataException>("$filter=$it"); } } }
pvginkel/NHibernate.OData
NHibernate.OData.Test/Criterions/ImplicitVariable.cs
C#
lgpl-3.0
640
/* * Copyright (C) 2015 eXo Platform SAS. * * This 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 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. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.task.dao; /** * @author <a href="mailto:tuyennt@exoplatform.com">Tuyen Nguyen The</a>. */ public interface DAOHandler { public ProjectHandler getProjectHandler(); public TaskHandler getTaskHandler(); public LabelHandler getLabelHandler(); public LabelTaskMappingHandler getLabelTaskMappingHandler(); public CommentHandler getCommentHandler(); public TaskLogHandler getTaskLogHandler(); public StatusHandler getStatusHandler(); public UserSettingHandler getUserSettingHandler(); }
exoplatform/task
services/src/main/java/org/exoplatform/task/dao/DAOHandler.java
Java
lgpl-3.0
1,358
#ifndef _TIME_H #define _TIME_H #ifndef _TIME_T #define _TIME_T typedef long time_t; // 从GMT 1970 年1 月1 日开始的以秒计数的时间(日历时间)。 #endif #ifndef _SIZE_T #define _SIZE_T typedef unsigned int size_t; #endif #define CLOCKS_PER_SEC 100 // 系统时钟滴答频率,100HZ。 typedef long clock_t; // 从进程开始系统经过的时钟滴答数。 struct tm { int tm_sec; // 秒数 [0,59]。 int tm_min; // 分钟数 [ 0,59]。 int tm_hour; // 小时数 [0,59]。 int tm_mday; // 1 个月的天数 [0,31]。 int tm_mon; // 1 年中月份 [0,11]。 int tm_year; // 从1900 年开始的年数。 int tm_wday; // 1 星期中的某天 [0,6](星期天 =0)。 int tm_yday; // 1 年中的某天 [0,365]。 int tm_isdst; // 夏令时标志。 }; // 以下是有关时间操作的函数原型。 // 确定处理器使用时间。返回程序所用处理器时间(滴答数)的近似值。 clock_t clock (void); // 取时间(秒数)。返回从1970.1.1:0:0:0 开始的秒数(称为日历时间)。 time_t time (time_t * tp); // 计算时间差。返回时间time2 与time1 之间经过的秒数。 double difftime (time_t time2, time_t time1); // 将tm 结构表示的时间转换成日历时间。 time_t mktime (struct tm *tp); // 将tm 结构表示的时间转换成一个字符串。返回指向该串的指针。 char *asctime (const struct tm *tp); // 将日历时间转换成一个字符串形式,如“Wed Jun 30 21:49:08:1993\n”。 char *ctime (const time_t * tp); // 将日历时间转换成tm 结构表示的UTC 时间(UTC - 世界时间代码Universal Time Code)。 struct tm *gmtime (const time_t * tp); // 将日历时间转换成tm 结构表示的指定时间区(timezone)的时间。 struct tm *localtime (const time_t * tp); // 将tm 结构表示的时间利用格式字符串fmt 转换成最大长度为smax 的字符串并将结果存储在s 中。 size_t strftime (char *s, size_t smax, const char *fmt, const struct tm *tp); // 初始化时间转换信息,使用环境变量TZ,对zname 变量进行初始化。 // 在与时间区相关的时间转换函数中将自动调用该函数。 void tzset (void); #endif
loveveryday/linux0.11
include/time.h
C
lgpl-3.0
2,244
<?php namespace Quark\ViewResources\WysiBB\JS; use Quark\QuarkJSViewResourceType; use Quark\ViewResources\WysiBB\IWysiBBLanguage; /** * Class LanguageRU * * @package Quark\ViewResources\WysiBB\JS */ class LanguageRU implements IWysiBBLanguage { /** * @return string */ public function Location () { return __DIR__ . '/ru.js'; } /** * @return string */ public function Type () { return new QuarkJSViewResourceType(); } /** * @return bool */ public function CacheControl () { return true; } }
saivarunk/quark
ViewResources/WysiBB/JS/LanguageRU.php
PHP
lgpl-3.0
525
#ifndef _WIMLIB_WIN32_COMMON_H #define _WIMLIB_WIN32_COMMON_H #include <ntstatus.h> #include <windows.h> #include <winternl.h> #ifdef ERROR # undef ERROR #endif #include "wimlib/types.h" #include "wimlib/win32.h" /* ntdll functions */ extern NTSTATUS (WINAPI *func_NtCreateFile)(PHANDLE FileHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PIO_STATUS_BLOCK IoStatusBlock, PLARGE_INTEGER AllocationSize, ULONG FileAttributes, ULONG ShareAccess, ULONG CreateDisposition, ULONG CreateOptions, PVOID EaBuffer, ULONG EaLength); #ifndef FILE_OPENED # define FILE_OPENED 0x00000001 #endif extern NTSTATUS (WINAPI *func_NtOpenFile) (PHANDLE FileHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PIO_STATUS_BLOCK IoStatusBlock, ULONG ShareAccess, ULONG OpenOptions); extern NTSTATUS (WINAPI *func_NtReadFile) (HANDLE FileHandle, HANDLE Event, PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer, ULONG Length, PLARGE_INTEGER ByteOffset, PULONG Key); extern NTSTATUS (WINAPI *func_NtWriteFile) (HANDLE FileHandle, HANDLE Event, PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer, ULONG Length, PLARGE_INTEGER ByteOffset, PULONG Key); extern NTSTATUS (WINAPI *func_NtQueryInformationFile)(HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID FileInformation, ULONG Length, FILE_INFORMATION_CLASS FileInformationClass); extern NTSTATUS (WINAPI *func_NtQuerySecurityObject)(HANDLE handle, SECURITY_INFORMATION SecurityInformation, PSECURITY_DESCRIPTOR SecurityDescriptor, ULONG Length, PULONG LengthNeeded); extern NTSTATUS (WINAPI *func_NtQueryDirectoryFile) (HANDLE FileHandle, HANDLE Event, PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, PVOID FileInformation, ULONG Length, FILE_INFORMATION_CLASS FileInformationClass, BOOLEAN ReturnSingleEntry, PUNICODE_STRING FileName, BOOLEAN RestartScan); extern NTSTATUS (WINAPI *func_NtQueryVolumeInformationFile) (HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID FsInformation, ULONG Length, FS_INFORMATION_CLASS FsInformationClass); extern NTSTATUS (WINAPI *func_NtSetInformationFile)(HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID FileInformation, ULONG Length, FILE_INFORMATION_CLASS FileInformationClass); extern NTSTATUS (WINAPI *func_NtSetSecurityObject)(HANDLE Handle, SECURITY_INFORMATION SecurityInformation, PSECURITY_DESCRIPTOR SecurityDescriptor); extern NTSTATUS (WINAPI *func_NtFsControlFile) (HANDLE FileHandle, HANDLE Event, PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, ULONG FsControlCode, PVOID InputBuffer, ULONG InputBufferLength, PVOID OutputBuffer, ULONG OutputBufferLength); extern NTSTATUS (WINAPI *func_NtClose) (HANDLE Handle); extern DWORD (WINAPI *func_RtlNtStatusToDosError)(NTSTATUS status); typedef struct _RTLP_CURDIR_REF { LONG RefCount; HANDLE Handle; } RTLP_CURDIR_REF, *PRTLP_CURDIR_REF; typedef struct _RTL_RELATIVE_NAME_U { UNICODE_STRING RelativeName; HANDLE ContainingDirectory; PRTLP_CURDIR_REF CurDirRef; } RTL_RELATIVE_NAME_U, *PRTL_RELATIVE_NAME_U; extern BOOLEAN (WINAPI *func_RtlDosPathNameToNtPathName_U) (IN PCWSTR DosName, OUT PUNICODE_STRING NtName, OUT PCWSTR *PartName, OUT PRTL_RELATIVE_NAME_U RelativeName); extern NTSTATUS (WINAPI *func_RtlDosPathNameToNtPathName_U_WithStatus) (IN PCWSTR DosName, OUT PUNICODE_STRING NtName, OUT PCWSTR *PartName, OUT PRTL_RELATIVE_NAME_U RelativeName); extern NTSTATUS (WINAPI *func_RtlCreateSystemVolumeInformationFolder) (PCUNICODE_STRING VolumeRootPath); #define FSCTL_SET_PERSISTENT_VOLUME_STATE 0x90238 #define PERSISTENT_VOLUME_STATE_SHORT_NAME_CREATION_DISABLED 0x00000001 typedef struct _FILE_FS_PERSISTENT_VOLUME_INFORMATION { ULONG VolumeFlags; ULONG FlagMask; ULONG Version; ULONG Reserved; } FILE_FS_PERSISTENT_VOLUME_INFORMATION, *PFILE_FS_PERSISTENT_VOLUME_INFORMATION; extern int win32_path_to_nt_path(const wchar_t *win32_path, UNICODE_STRING *nt_path); extern int win32_get_drive_path(const wchar_t *file_path, wchar_t drive_path[7]); extern void win32_warning(DWORD err, const wchar_t *format, ...) _cold_attribute; extern void win32_error(DWORD err, const wchar_t *format, ...) _cold_attribute; extern void winnt_warning(NTSTATUS status, const wchar_t *format, ...) _cold_attribute; extern void winnt_error(NTSTATUS status, const wchar_t *format, ...) _cold_attribute; #endif /* _WIMLIB_WIN32_COMMON_H */
jcpowermac/wimlib
include/wimlib/win32_common.h
C
lgpl-3.0
5,153
#ifndef PLEXY_GOOGLEWEATHER_I #define PLEXY_GOOGLEWEATHER_I #include <plexy.h> #include <abstractplugininterface.h> #include <datainterface.h> #include <widgetinterface.h> class VISIBLE_SYM googleweatherInterface : public PlexyDesk::AbstractPluginInterface { Q_OBJECT Q_INTERFACES(PlexyDesk::AbstractPluginInterface) public : googleweatherInterface(QObject *object = 0); PlexyDesk::BasePlugin *instance (); }; #endif
plexydesk/plexydesk-0.5-depricated-codebase
extensions/social/googleweather/googleweatherinterface.h
C
lgpl-3.0
443
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * Defines a simple key value pair. * <p> * A Map Entry has considerable additional semantics over and above a simple * key-value pair. This interface defines the minimum key value, with just the * two get methods. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public interface KeyValue { /** * Gets the key from the pair. * * @return the key */ Object getKey(); /** * Gets the value from the pair. * * @return the value */ Object getValue(); }
leodmurillo/sonar
plugins/sonar-squid-java-plugin/test-resources/commons-collections-3.2.1/src/org/apache/commons/collections/KeyValue.java
Java
lgpl-3.0
1,530
<?php /** * a flexible way to build mysqli related classes. * usage: * Application_Model_Project extends Application_Model_Configurable * new Application_Model_Project( array("property"=>"value") ) */ class Application_Model_Configurable{ public function __construct( array $properties = array() ){ foreach( $properties as $key => $value ){ $this->$key = $value; } } public static function load( $row ){ } }
medialab/ANTA
application/models/Configurable.php
PHP
lgpl-3.0
428
/*===========================================================================*/ /* */ /* This file is part of the SYMPHONY MILP Solver Framework. */ /* */ /* SYMPHONY was jointly developed by Ted Ralphs (ted@lehigh.edu) and */ /* Laci Ladanyi (ladanyi@us.ibm.com). */ /* */ /* (c) Copyright 2000-2011 Ted Ralphs. All Rights Reserved. */ /* */ /* This software is licensed under the Eclipse Public License. Please see */ /* accompanying file for terms. */ /* */ /*===========================================================================*/ #ifndef _CUT_POOL_PARAMS_H #define _CUT_POOL_PARAMS_H /*===========================================================================*\ * Contains the parameters necessary for the functioning of the cut pool \*===========================================================================*/ typedef struct CP_PARAMS{ int verbosity; int warm_start; char warm_start_file_name[MAX_FILE_NAME_LENGTH +1]; int logging; char log_file_name[MAX_FILE_NAME_LENGTH +1]; int block_size; int max_size; int max_number_of_cuts; int cuts_to_check; int delete_which; int touches_until_deletion; int min_to_delete; int check_which; }cp_params; #endif
tulip5/tulip
thirdparty/OGDF/include/coin/sym_cp_params.h
C
lgpl-3.0
1,761
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the demonstration applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "commands.h" static const int setShapeRectCommandId = 1; static const int setShapeColorCommandId = 2; /****************************************************************************** ** AddShapeCommand */ AddShapeCommand::AddShapeCommand(Document *doc, const Shape &shape, QUndoCommand *parent) : QUndoCommand(parent) { m_doc = doc; m_shape = shape; } void AddShapeCommand::undo() { m_doc->deleteShape(m_shapeName); } void AddShapeCommand::redo() { // A shape only gets a name when it is inserted into a document m_shapeName = m_doc->addShape(m_shape); setText(QObject::tr("Add %1").arg(m_shapeName)); } /****************************************************************************** ** RemoveShapeCommand */ RemoveShapeCommand::RemoveShapeCommand(Document *doc, const QString &shapeName, QUndoCommand *parent) : QUndoCommand(parent) { setText(QObject::tr("Remove %1").arg(shapeName)); m_doc = doc; m_shape = doc->shape(shapeName); m_shapeName = shapeName; } void RemoveShapeCommand::undo() { m_shapeName = m_doc->addShape(m_shape); } void RemoveShapeCommand::redo() { m_doc->deleteShape(m_shapeName); } /****************************************************************************** ** SetShapeColorCommand */ SetShapeColorCommand::SetShapeColorCommand(Document *doc, const QString &shapeName, const QColor &color, QUndoCommand *parent) : QUndoCommand(parent) { setText(QObject::tr("Set %1's color").arg(shapeName)); m_doc = doc; m_shapeName = shapeName; m_oldColor = doc->shape(shapeName).color(); m_newColor = color; } void SetShapeColorCommand::undo() { m_doc->setShapeColor(m_shapeName, m_oldColor); } void SetShapeColorCommand::redo() { m_doc->setShapeColor(m_shapeName, m_newColor); } bool SetShapeColorCommand::mergeWith(const QUndoCommand *command) { if (command->id() != setShapeColorCommandId) return false; const SetShapeColorCommand *other = static_cast<const SetShapeColorCommand*>(command); if (m_shapeName != other->m_shapeName) return false; m_newColor = other->m_newColor; return true; } int SetShapeColorCommand::id() const { return setShapeColorCommandId; } /****************************************************************************** ** SetShapeRectCommand */ SetShapeRectCommand::SetShapeRectCommand(Document *doc, const QString &shapeName, const QRect &rect, QUndoCommand *parent) : QUndoCommand(parent) { setText(QObject::tr("Change %1's geometry").arg(shapeName)); m_doc = doc; m_shapeName = shapeName; m_oldRect = doc->shape(shapeName).rect(); m_newRect = rect; } void SetShapeRectCommand::undo() { m_doc->setShapeRect(m_shapeName, m_oldRect); } void SetShapeRectCommand::redo() { m_doc->setShapeRect(m_shapeName, m_newRect); } bool SetShapeRectCommand::mergeWith(const QUndoCommand *command) { if (command->id() != setShapeRectCommandId) return false; const SetShapeRectCommand *other = static_cast<const SetShapeRectCommand*>(command); if (m_shapeName != other->m_shapeName) return false; m_newRect = other->m_newRect; return true; } int SetShapeRectCommand::id() const { return setShapeRectCommandId; }
ssangkong/NVRAM_KWU
qt-everywhere-opensource-src-4.7.4/demos/undo/commands.cpp
C++
lgpl-3.0
5,128
import sys from services.equipment import BonusSetTemplate from java.util import Vector def addBonusSet(core): bonusSet = BonusSetTemplate("set_bonus_smuggler_utility_b") bonusSet.addRequiredItem("item_band_set_smuggler_utility_b_01_01") bonusSet.addRequiredItem("item_ring_set_smuggler_utility_b_01_01") bonusSet.addRequiredItem("item_necklace_set_smuggler_utility_b_01_01") bonusSet.addRequiredItem("item_bracelet_r_set_smuggler_utility_b_01_01") bonusSet.addRequiredItem("item_bracelet_l_set_smuggler_utility_b_01_01") core.equipmentService.addBonusSetTemplate(bonusSet) def handleChange(core, creature, set): wornItems = set.getWornTemplateCount(creature) if wornItems == 3: core.buffService.addBuffToCreature(creature, "set_bonus_smuggler_utility_b_1", creature) creature.sendSystemMessage('@set_bonus:set_bonus_smuggler_utility_b_1_sys', 0) elif wornItems == 4: core.buffService.addBuffToCreature(creature, "set_bonus_smuggler_utility_b_2", creature) creature.sendSystemMessage('@set_bonus:set_bonus_smuggler_utility_b_2_sys', 0) elif wornItems == 5: core.buffService.addBuffToCreature(creature, "set_bonus_smuggler_utility_b_3", creature) creature.sendSystemMessage('@set_bonus:set_bonus_smuggler_utility_b_3_sys', 0) else: core.buffService.removeBuffFromCreatureByName(creature, "set_bonus_smuggler_utility_b_1") core.buffService.removeBuffFromCreatureByName(creature, "set_bonus_smuggler_utility_b_2") core.buffService.removeBuffFromCreatureByName(creature, "set_bonus_smuggler_utility_b_3")
agry/NGECore2
scripts/equipment/bonus_sets/set_bonus_smuggler_utility_b.py
Python
lgpl-3.0
1,539
<?php /*************************************************************************************/ /* This file is part of the Thelia package. */ /* */ /* Copyright (c) OpenStudio */ /* email : dev@thelia.net */ /* web : http://www.thelia.net */ /* */ /* For the full copyright and license information, please view the LICENSE.txt */ /* file that was distributed with this source code. */ /*************************************************************************************/ namespace Thelia\Core\HttpKernel; use Symfony\Component\HttpKernel\Client as BaseClient; use Thelia\Core\HttpFoundation\Request; use Symfony\Component\BrowserKit\Request as DomRequest; /** * Class Client * @package Thelia\Core\HttpKernel * @author Manuel Raynaud <mraynaud@openstudio.fr> */ class Client extends BaseClient { /** * Converts the BrowserKit request to a HttpKernel request. * * @param DomRequest $request A Request instance * * @return Request A Request instance */ protected function filterRequest(DomRequest $request) { $httpRequest = Request::create($request->getUri(), $request->getMethod(), $request->getParameters(), $request->getCookies(), $request->getFiles(), $request->getServer(), $request->getContent()); $httpRequest->files->replace($this->filterFiles($httpRequest->files->all())); return $httpRequest; } }
AznStyle/lwb2
core/lib/Thelia/Core/HttpKernel/Client.php
PHP
lgpl-3.0
1,801
define(['joose', 'Psc/UI/FormBuilder'], function(Joose) { /** * Ein Trait für ein Objekt welche einen FormBuilder benutzen * */ Joose.Role('Psc.UI.FormBuilding', { has: { formBuilder: { is : 'rw', required: false, isPrivate: true } }, before: { // after ist bissl schlecht, weil main z.b. den eventmanager schon beim after: initialize braucht, ich weiss aber nicht wie ich steuern kann, welches "after" zuerst ausgeführt wird?, before scheint aber erstmal gut zu laufen initialize: function (props) { if (!props.formBuilder) { this.$$formBuilder = new Psc.UI.FormBuilder(); } } } }); });
webforge-labs/psc-cms-js
lib/Psc/UI/FormBuilding.js
JavaScript
lgpl-3.0
675
/* * 11/19/04 1.0 moved to LGPL. *----------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 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 Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *---------------------------------------------------------------------- */ package sound.javazoom.decoder; import java.io.IOException; /** * Work in progress. * * Class to describe a seekable data source. * */ public interface Source { public static final long LENGTH_UNKNOWN = -1; public int read(byte[] b, int offs, int len) throws IOException; public boolean willReadBlock(); public boolean isSeekable(); public long length(); public long tell(); public long seek(long pos); }
etyllica/etyllica
src/main/java/sound/javazoom/decoder/Source.java
Java
lgpl-3.0
1,429
/* * Python object definition of the libvhdi disk types * * Copyright (C) 2012-2016, Joachim Metz <joachim.metz@gmail.com> * * Refer to AUTHORS for acknowledgements. * * This software 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 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 General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. */ #include <common.h> #include <types.h> #if defined( HAVE_STDLIB_H ) || defined( HAVE_WINAPI ) #include <stdlib.h> #endif #include "pyvhdi_disk_types.h" #include "pyvhdi_libvhdi.h" #include "pyvhdi_python.h" #include "pyvhdi_unused.h" PyTypeObject pyvhdi_disk_types_type_object = { PyVarObject_HEAD_INIT( NULL, 0 ) /* tp_name */ "pyvhdi.disk_types", /* tp_basicsize */ sizeof( pyvhdi_disk_types_t ), /* tp_itemsize */ 0, /* tp_dealloc */ (destructor) pyvhdi_disk_types_free, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ Py_TPFLAGS_DEFAULT, /* tp_doc */ "pyvhdi disk types object (wraps LIBVHDI_DISK_TYPES)", /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ (initproc) pyvhdi_disk_types_init, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ NULL, /* tp_mro */ NULL, /* tp_cache */ NULL, /* tp_subclasses */ NULL, /* tp_weaklist */ NULL, /* tp_del */ 0 }; /* Initializes the type object * Returns 1 if successful or -1 on error */ int pyvhdi_disk_types_init_type( PyTypeObject *type_object ) { PyObject *value_object = NULL; if( type_object == NULL ) { return( -1 ); } type_object->tp_dict = PyDict_New(); if( type_object->tp_dict == NULL ) { return( -1 ); } #if PY_MAJOR_VERSION >= 3 value_object = PyLong_FromLong( LIBVHDI_DISK_TYPE_FIXED ); #else value_object = PyInt_FromLong( LIBVHDI_DISK_TYPE_FIXED ); #endif if( PyDict_SetItemString( type_object->tp_dict, "FIXED", value_object ) != 0 ) { goto on_error; } #if PY_MAJOR_VERSION >= 3 value_object = PyLong_FromLong( LIBVHDI_DISK_TYPE_DYNAMIC ); #else value_object = PyInt_FromLong( LIBVHDI_DISK_TYPE_DYNAMIC ); #endif if( PyDict_SetItemString( type_object->tp_dict, "DYNAMIC", value_object ) != 0 ) { goto on_error; } #if PY_MAJOR_VERSION >= 3 value_object = PyLong_FromLong( LIBVHDI_DISK_TYPE_DIFFERENTIAL ); #else value_object = PyInt_FromLong( LIBVHDI_DISK_TYPE_DIFFERENTIAL ); #endif if( PyDict_SetItemString( type_object->tp_dict, "DIFFERENTIAL", value_object ) != 0 ) { goto on_error; } return( 1 ); on_error: if( type_object->tp_dict != NULL ) { Py_DecRef( type_object->tp_dict ); type_object->tp_dict = NULL; } return( -1 ); } /* Creates a new disk types object * Returns a Python object if successful or NULL on error */ PyObject *pyvhdi_disk_types_new( void ) { pyvhdi_disk_types_t *pyvhdi_disk_types = NULL; static char *function = "pyvhdi_disk_types_new"; pyvhdi_disk_types = PyObject_New( struct pyvhdi_disk_types, &pyvhdi_disk_types_type_object ); if( pyvhdi_disk_types == NULL ) { PyErr_Format( PyExc_MemoryError, "%s: unable to initialize disk types.", function ); goto on_error; } if( pyvhdi_disk_types_init( pyvhdi_disk_types ) != 0 ) { PyErr_Format( PyExc_MemoryError, "%s: unable to initialize disk types.", function ); goto on_error; } return( (PyObject *) pyvhdi_disk_types ); on_error: if( pyvhdi_disk_types != NULL ) { Py_DecRef( (PyObject *) pyvhdi_disk_types ); } return( NULL ); } /* Intializes a disk types object * Returns 0 if successful or -1 on error */ int pyvhdi_disk_types_init( pyvhdi_disk_types_t *pyvhdi_disk_types ) { static char *function = "pyvhdi_disk_types_init"; if( pyvhdi_disk_types == NULL ) { PyErr_Format( PyExc_TypeError, "%s: invalid disk types.", function ); return( -1 ); } return( 0 ); } /* Frees a disk types object */ void pyvhdi_disk_types_free( pyvhdi_disk_types_t *pyvhdi_disk_types ) { struct _typeobject *ob_type = NULL; static char *function = "pyvhdi_disk_types_free"; if( pyvhdi_disk_types == NULL ) { PyErr_Format( PyExc_TypeError, "%s: invalid disk types.", function ); return; } ob_type = Py_TYPE( pyvhdi_disk_types ); if( ob_type == NULL ) { PyErr_Format( PyExc_ValueError, "%s: missing ob_type.", function ); return; } if( ob_type->tp_free == NULL ) { PyErr_Format( PyExc_ValueError, "%s: invalid ob_type - missing tp_free.", function ); return; } ob_type->tp_free( (PyObject*) pyvhdi_disk_types ); }
rlugojr/libvhdi_64bit
pyvhdi/pyvhdi_disk_types.c
C
lgpl-3.0
5,754
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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. * * SonarQube 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. */ package org.sonar.server.measure; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.collect.Lists; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.sonar.api.measures.Metric; import org.sonar.api.resources.Qualifiers; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import java.util.Collections; import java.util.Date; import java.util.List; public class MeasureFilter { // conditions on resources private String baseResourceKey; // only if baseResourceKey or baseResourceId are set private boolean onBaseResourceChildren = false; private List<String> resourceScopes = Collections.emptyList(); private List<String> resourceQualifiers = Collections.emptyList(); private String resourceKey = null; private String resourceName = null; private Date fromDate = null, toDate = null; private boolean userFavourites = false; // conditions on measures private List<MeasureFilterCondition> measureConditions = Lists.newArrayList(); // sort private MeasureFilterSort sort = new MeasureFilterSort(); public String getBaseResourceKey() { return baseResourceKey; } public MeasureFilter setBaseResourceKey(String s) { this.baseResourceKey = s; return this; } public MeasureFilter setOnBaseResourceChildren(boolean b) { this.onBaseResourceChildren = b; return this; } public boolean isOnBaseResourceChildren() { return onBaseResourceChildren; } public MeasureFilter setResourceScopes(@Nullable List<String> list) { this.resourceScopes = sanitize(list); return this; } public MeasureFilter setResourceQualifiers(@Nullable List<String> list) { this.resourceQualifiers = sanitize(list); if (resourceQualifiers.contains(Qualifiers.FILE)) { resourceQualifiers.add(Qualifiers.CLASS); } if (resourceQualifiers.contains(Qualifiers.DIRECTORY)) { resourceQualifiers.add(Qualifiers.PACKAGE); } return this; } public MeasureFilter setUserFavourites(boolean b) { this.userFavourites = b; return this; } public boolean isOnFavourites() { return userFavourites; } @CheckForNull public String getResourceName() { return resourceName; } public MeasureFilter setResourceName(@Nullable String s) { this.resourceName = s; return this; } public String getResourceKey() { return resourceKey; } public MeasureFilter setResourceKey(String s) { this.resourceKey = s; return this; } public MeasureFilter addCondition(MeasureFilterCondition condition) { this.measureConditions.add(condition); return this; } public MeasureFilter setSortOn(MeasureFilterSort.Field sortField) { this.sort.setField(sortField); return this; } public MeasureFilter setSortAsc(boolean b) { this.sort.setAsc(b); return this; } public MeasureFilter setSortOnMetric(Metric m) { this.sort.setField(MeasureFilterSort.Field.METRIC); this.sort.setMetric(m); return this; } public MeasureFilter setSortOnPeriod(int period) { this.sort.setPeriod(period); return this; } public MeasureFilter setFromDate(@Nullable Date d) { this.fromDate = d; return this; } public MeasureFilter setToDate(@Nullable Date d) { this.toDate = d; return this; } @CheckForNull public Date getFromDate() { return fromDate; } @CheckForNull public Date getToDate() { return toDate; } public List<String> getResourceScopes() { return resourceScopes; } public List<String> getResourceQualifiers() { return resourceQualifiers; } public List<MeasureFilterCondition> getMeasureConditions() { return measureConditions; } MeasureFilterSort sort() { return sort; } public boolean isEmpty() { return resourceQualifiers.isEmpty() && resourceScopes.isEmpty() && StringUtils.isEmpty(baseResourceKey) && !userFavourites; } @VisibleForTesting static List<String> sanitize(@Nullable List<String> list) { return isEmptyList(list) ? Collections.<String> emptyList() : Lists.newArrayList(list); } private static boolean isEmptyList(@Nullable List<String> list) { boolean blank = false; if (list == null || list.isEmpty() || (list.size() == 1 && Strings.isNullOrEmpty(list.get(0)))) { blank = true; } return blank; } @Override public String toString() { return ReflectionToStringBuilder.toString(this); } }
teryk/sonarqube
server/sonar-server/src/main/java/org/sonar/server/measure/MeasureFilter.java
Java
lgpl-3.0
5,451
namespace FrbaCommerce.Vistas.Login { partial class CambiarPassword { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.groupBox1 = new System.Windows.Forms.GroupBox(); this.password1 = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.password2 = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.button1); this.groupBox1.Controls.Add(this.password1); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.password2); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Location = new System.Drawing.Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(225, 114); this.groupBox1.TabIndex = 11; this.groupBox1.TabStop = false; this.groupBox1.Text = "Cambiar password"; // // password1 // this.password1.Location = new System.Drawing.Point(84, 24); this.password1.MaxLength = 100; this.password1.Name = "password1"; this.password1.PasswordChar = '*'; this.password1.Size = new System.Drawing.Size(120, 20); this.password1.TabIndex = 11; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(29, 27); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(53, 13); this.label2.TabIndex = 12; this.label2.Text = "Password"; // // password2 // this.password2.Location = new System.Drawing.Point(84, 50); this.password2.MaxLength = 100; this.password2.Name = "password2"; this.password2.PasswordChar = '*'; this.password2.Size = new System.Drawing.Size(120, 20); this.password2.TabIndex = 13; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(12, 53); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(70, 13); this.label3.TabIndex = 14; this.label3.Text = "Re-Password"; // // button1 // this.button1.Location = new System.Drawing.Point(84, 85); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 15; this.button1.Text = "Cambiar"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // CambiarPassword // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(250, 140); this.Controls.Add(this.groupBox1); this.Name = "CambiarPassword"; this.Text = "CambiarPassword"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox password1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox password2; private System.Windows.Forms.Label label3; } }
barriosnahuel/merca-libre
entrega/src/FrbaCommerce/Vistas/Login/CambiarPassword.Designer.cs
C#
lgpl-3.0
4,877
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "private/qdeclarativeintegercache_p.h" #include "private/qdeclarativeengine_p.h" #include "private/qdeclarativemetatype_p.h" QT_BEGIN_NAMESPACE QDeclarativeIntegerCache::QDeclarativeIntegerCache(QDeclarativeEngine *e) : QDeclarativeCleanup(e), engine(e) { } QDeclarativeIntegerCache::~QDeclarativeIntegerCache() { clear(); } void QDeclarativeIntegerCache::clear() { qDeleteAll(stringCache); stringCache.clear(); identifierCache.clear(); engine = 0; } QString QDeclarativeIntegerCache::findId(int value) const { for (StringCache::ConstIterator iter = stringCache.begin(); iter != stringCache.end(); ++iter) { if (iter.value() && iter.value()->value == value) return iter.key(); } return QString(); } void QDeclarativeIntegerCache::add(const QString &id, int value) { Q_ASSERT(!stringCache.contains(id)); QDeclarativeEnginePrivate *enginePriv = QDeclarativeEnginePrivate::get(engine); // ### use contextClass Data *d = new Data(enginePriv->objectClass->createPersistentIdentifier(id), value); stringCache.insert(id, d); identifierCache.insert(d->identifier, d); } int QDeclarativeIntegerCache::value(const QString &id) { Data *d = stringCache.value(id); return d?d->value:-1; } QT_END_NAMESPACE
qtproject/qtquick1
src/declarative/qml/qdeclarativeintegercache.cpp
C++
lgpl-3.0
2,898
Given /^there aren't any projects$/ do end When /^I view the welcome page$/ do visit "/" end Then /^I am redirected to the "([^"]*)" project page$/ do |project| sleep 1 page.current_path.should include "/projects/#{project}" end When /^I select the project "([^"]*)"$/ do |project| select(project, :from => "projects") end Then /^I see the wally README$/ do page.should have_content "Wally is a web-based Cucumber viewer and navigator" end
BBC-News/wally
features/step_definitions/welcome_page.rb
Ruby
lgpl-3.0
454
/* * SonarAnalyzer for .NET * Copyright (C) 2015-2016 SonarSource SA * mailto:contact@sonarsource.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 02 */ using Microsoft.VisualStudio.TestTools.UnitTesting; using SonarAnalyzer.Rules.VisualBasic; namespace SonarAnalyzer.UnitTest.Rules { [TestClass] public class LocalVariableNameTest { [TestMethod] [TestCategory("Rule")] public void LocalVariableName() { Verifier.VerifyAnalyzer(@"TestCases\LocalVariableName.vb", new LocalVariableName()); } } }
tvsonar/sonarlint-vs
src/Tests/SonarAnalyzer.UnitTest/Rules/LocalVariableNameTest.cs
C#
lgpl-3.0
1,253
// -*- mode: c++; c-basic-style: "bsd"; c-basic-offset: 4; -*- /* * kdm/data/XMLSchema.cpp * Copyright (C) Cátedra SAES-UMU 2010 <andres.senac@um.es> * * EMF4CPP 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. * * EMF4CPP 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/>. */ #include "XMLSchema.hpp" #include <kdm/data/AbstractDataElement.hpp> #include <kdm/kdm/Attribute.hpp> #include <kdm/kdm/Annotation.hpp> #include <kdm/kdm/Stereotype.hpp> #include <kdm/kdm/ExtendedValue.hpp> #include <kdm/source/SourceRef.hpp> #include <kdm/data/AbstractDataRelationship.hpp> #include <kdm/action/ActionElement.hpp> #include <kdm/data/AbstractContentElement.hpp> #include <kdm/core/KDMRelationship.hpp> #include <kdm/core/AggregatedRelationship.hpp> #include <kdm/core/KDMEntity.hpp> #include <kdm/kdm/KDMModel.hpp> #include <ecore/EObject.hpp> #include <ecore/EClass.hpp> #include "kdm/data/DataPackage.hpp" #include <ecorecpp/mapping.hpp> #ifdef ECORECPP_NOTIFICATION_API #include <ecorecpp/notify.hpp> #endif using namespace ::kdm::data; // Default constructor XMLSchema::XMLSchema() { m_contentElement.reset( new ::ecorecpp::mapping::ReferenceEListImpl< ::kdm::data::AbstractContentElement, -1, true, false >( this, NULL)); /*PROTECTED REGION ID(XMLSchemaImpl__XMLSchemaImpl) START*/ // Please, enable the protected region if you add manually written code. // To do this, add the keyword ENABLED before START. /*PROTECTED REGION END*/ #ifdef ECORECPP_NOTIFICATION_API m_eDeliver = false; #endif } XMLSchema::~XMLSchema() { } /*PROTECTED REGION ID(XMLSchema.cpp) START*/ // Please, enable the protected region if you add manually written code. // To do this, add the keyword ENABLED before START. /*PROTECTED REGION END*/ // Attributes // References ::ecorecpp::mapping::EList< ::kdm::data::AbstractContentElement >& XMLSchema::getContentElement() { return *m_contentElement; }
wurfkeks/emf4cpp
emf4cpp.tests/kdm/kdm/data/XMLSchema.cpp
C++
lgpl-3.0
2,505
Lorem.js Dummy Text/Image Generator jQuery and Native JS ======================================================== A Lorem Ipsum creator service written on JavaScript. Implementation -------------- Implementation of Lorem.js is so simple, You just download and add <script src="path/to/lorem.js"></script> into your website/application and run. If you want to put a lorem text inside a DIV (etc.) tag just write: <div data-lorem="2p"></div> If you want a random length of lorem text within a range just write: <div data-lorem="2-4p"></div> Querying -------- Lorem.js has a simple query language: "how many?, what?" 2p = 2 paragraphs 5s = 5 sentences 6w = 6 words 1-6w = between 1 and 6 words That's it. Dummy Images ------------ And Lorem.js uses lorempixum.com for images for now. Usage: <img src="" data-lorem="sports/1/Test message" width="223" height="223"> <img src="" data-lorem="gray" width="100" height="124"> <img src="" data-lorem="gray animals" width="100" height="124"> And watch what happens :) Native JavaScript (without any framework) ---------------------------------------- If you want to use Lorem generator natively, (without jQuery). With Native support, you can lorem.js into your framework. Usage: var lorem = new Lorem; lorem.type = Lorem.TEXT; lorem.query = '2p'; lorem.createLorem(document.getElementById('lorem')); Feel free to ask questions.
klec/loremjs
README.md
Markdown
lgpl-3.0
1,448
package net.spy.memcached; import java.net.SocketAddress; import java.nio.channels.SocketChannel; import net.spy.memcached.protocol.binary.BinaryMemcachedNodeImpl; import net.spy.memcached.protocol.binary.BinaryOperationFactory; /** * Default connection factory for binary wire protocol connections. */ public class BinaryConnectionFactory extends DefaultConnectionFactory { /** * Create a DefaultConnectionFactory with the default parameters. */ public BinaryConnectionFactory() { super(); } /** * Create a BinaryConnectionFactory with the given maximum operation * queue length, and the given read buffer size. */ public BinaryConnectionFactory(int len, int bufSize) { super(len, bufSize); } /** * Construct a BinaryConnectionFactory with the given parameters. * * @param len the queue length. * @param bufSize the buffer size * @param hash the algorithm to use for hashing */ public BinaryConnectionFactory(int len, int bufSize, HashAlgorithm hash) { super(len, bufSize, hash); } @Override public MemcachedNode createMemcachedNode(SocketAddress sa, SocketChannel c, int bufSize) { boolean doAuth = false; return new BinaryMemcachedNodeImpl(sa, c, bufSize, createReadOperationQueue(), createWriteOperationQueue(), createOperationQueue(), getOpQueueMaxBlockTime(), doAuth, getOperationTimeout()); } @Override public OperationFactory getOperationFactory() { return new BinaryOperationFactory(); } @Override protected String getName() { return "BinaryConnectionFactory"; } }
haisamido/SFDaaS
src/net/spy/memcached/BinaryConnectionFactory.java
Java
lgpl-3.0
1,562
/* QMPlay2 is a video and audio player. Copyright (C) 2010-2022 Błażej Szczygieł 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/>. */ #include <Visualizations.hpp> #include <SimpleVis.hpp> #include <FFTSpectrum.hpp> Visualizations::Visualizations() : Module("Visualizations") { m_icon = QIcon(":/Visualizations.svgz"); constexpr int ms = 17; init("RefreshTime", ms); init("SimpleVis/SoundLength", ms); init("FFTSpectrum/Size", 8); } QList<Visualizations::Info> Visualizations::getModulesInfo(const bool) const { QList<Info> modulesInfo; modulesInfo += Info(SimpleVisName, QMPLAY2EXTENSION); modulesInfo += Info(FFTSpectrumName, QMPLAY2EXTENSION); return modulesInfo; } void *Visualizations::createInstance(const QString &name) { if (name == SimpleVisName) return new SimpleVis(*this); else if (name == FFTSpectrumName) return new FFTSpectrum(*this); return nullptr; } Visualizations::SettingsWidget *Visualizations::getSettingsWidget() { return new ModuleSettingsWidget(*this); } QMPLAY2_EXPORT_MODULE(Visualizations) /**/ #include <QFormLayout> #include <QCheckBox> #include <QSpinBox> #include <QLabel> ModuleSettingsWidget::ModuleSettingsWidget(Module &module) : Module::SettingsWidget(module) { if (!QMPlay2Core.isGlOnWindow()) { refTimeB = new QSpinBox; refTimeB->setRange(1, 500); refTimeB->setSuffix(" " + tr("ms")); refTimeB->setValue(sets().getInt("RefreshTime")); } sndLenB = new QSpinBox; sndLenB->setRange(1, 500); sndLenB->setSuffix(" " + tr("ms")); sndLenB->setValue(sets().getInt("SimpleVis/SoundLength")); fftSizeB = new QSpinBox; fftSizeB->setRange(5, 12); fftSizeB->setPrefix("2^"); fftSizeB->setValue(sets().getInt("FFTSpectrum/Size")); m_fftLinearScaleB = new QCheckBox(tr("Linear scale")); m_fftLinearScaleB->setChecked(sets().getBool("FFTSpectrum/LinearScale")); QFormLayout *layout = new QFormLayout(this); if (refTimeB) layout->addRow(tr("Refresh time") + ": ", refTimeB); layout->addRow(tr("Displayed sound length") + ": ", sndLenB); layout->addRow(tr("FFT spectrum size") + ": ", fftSizeB); layout->addRow(m_fftLinearScaleB); if (refTimeB) connect(refTimeB, SIGNAL(valueChanged(int)), sndLenB, SLOT(setValue(int))); } void ModuleSettingsWidget::saveSettings() { if (refTimeB) sets().set("RefreshTime", refTimeB->value()); sets().set("SimpleVis/SoundLength", sndLenB->value()); sets().set("FFTSpectrum/Size", fftSizeB->value()); sets().set("FFTSpectrum/LinearScale", m_fftLinearScaleB->isChecked()); }
arthurzam/QMPlay2
src/modules/Visualizations/Visualizations.cpp
C++
lgpl-3.0
3,305
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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. * * SonarQube 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. */ package org.sonar.batch.cache; import org.sonar.home.cache.PersistentCache; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import static org.junit.Assert.*; import static org.assertj.core.api.Assertions.assertThat; import org.sonar.batch.bootstrap.GlobalProperties; import org.junit.Before; import org.junit.Test; import org.junit.Rule; import org.junit.rules.TemporaryFolder; public class GlobalPersistentCacheProviderTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private GlobalPersistentCacheProvider provider; private GlobalProperties globalProperties; @Before public void setUp() { HashMap<String, String> map = new HashMap<String, String>(); map.put("sonar.userHome", temp.getRoot().getAbsolutePath()); globalProperties = new GlobalProperties(map); provider = new GlobalPersistentCacheProvider(); } @Test public void test_path() { PersistentCache cache = provider.provide(globalProperties); assertThat(cache.getDirectory()).isEqualTo(temp.getRoot().toPath() .resolve("ws_cache") .resolve("http%3A%2F%2Flocalhost%3A9000") .resolve("global")); } @Test public void test_singleton() { assertTrue(provider.provide(globalProperties) == provider.provide(globalProperties)); } @Test public void test_without_sonar_home() { globalProperties = new GlobalProperties(new HashMap<String, String>()); PersistentCache cache = provider.provide(globalProperties); assertThat(cache.getDirectory().toAbsolutePath().toString()).startsWith(findHome().toAbsolutePath().toString()); } private static Path findHome() { String home = System.getenv("SONAR_USER_HOME"); if (home != null) { return Paths.get(home); } home = System.getProperty("user.home"); return Paths.get(home, ".sonar"); } }
abbeyj/sonarqube
sonar-batch/src/test/java/org/sonar/batch/cache/GlobalPersistentCacheProviderTest.java
Java
lgpl-3.0
2,743
// // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Data; using System.Xml; using System.Xml.Serialization; namespace System.Data { #if STANDALONE_DRIVER_TEST public class Driver { public static void Main (string [] args) { if (args.Length == 0) { Console.WriteLine ("usage: mono xmldatareader.exe filename"); return; } Console.WriteLine ("Target file: " + args [0]); DataSet ds = new DataSet (); // ds.InferXmlSchema (args [0], null); try { ds.ReadXml (args [0]); } catch (Exception ex) { Console.WriteLine ("ReadXml() borked: " + ex.Message); return; } Console.WriteLine ("---- DataSet ----------------"); StringWriter sw = new StringWriter (); PrintDataSet (ds, sw); PrintDataSet (ds, Console.Out); ds = new DataSet (); ds.InferXmlSchema (args [0], null); XmlDataReader.ReadXml (ds, new XmlTextReader (args [0])); Console.WriteLine ("---- XmlDataReader ----------------"); StringWriter sw2 = new StringWriter (); PrintDataSet (ds, sw2); if (sw.ToString () == sw2.ToString ()) Console.WriteLine ("Successful."); else Console.WriteLine ("Different *************************************************\n" + sw2); } private static void PrintDataSet (DataSet ds, TextWriter tw) { tw.WriteLine ("DS::" + ds.DataSetName + ", " + ds.Tables.Count + ", " + ds.Relations.Count); foreach (DataTable dt in ds.Tables) tw.WriteLine ("DT:" + dt.TableName + ", " + dt.Columns.Count + ", " + dt.Rows.Count); ds.WriteXml (tw); tw.WriteLine (); } } #endif internal class XmlDataReader { const string xmlnsNS = "http://www.w3.org/2000/xmlns/"; public static void ReadXml ( DataSet dataset, XmlReader reader, XmlReadMode mode) { new XmlDataReader (dataset, reader, mode).Process (); } DataSet dataset; XmlReader reader; XmlReadMode mode; public XmlDataReader (DataSet ds, XmlReader xr, XmlReadMode m) { dataset = ds; reader =xr; mode = m; } private void Process () { bool savedEnforceConstraints = dataset.EnforceConstraints; try { dataset.EnforceConstraints = false; reader.MoveToContent (); if (mode == XmlReadMode.Fragment) { while (reader.NodeType == XmlNodeType.Element && !reader.EOF) { ReadTopLevelElement (); } } else ReadTopLevelElement (); } finally { dataset.EnforceConstraints = savedEnforceConstraints; } } private bool IsTopLevelDataSet () { string local = XmlHelper.Decode (reader.LocalName); // No need to check DataSetName. In fact, it is ignored. DataTable dt = dataset.Tables [local]; if (dt == null) return true; XmlDocument doc = new XmlDocument (); XmlElement el = (XmlElement) doc.ReadNode (reader); doc.AppendChild (el); reader = new XmlNodeReader (el); reader.MoveToContent (); return !XmlDataInferenceLoader.IsDocumentElementTable ( el, null); } private void ReadTopLevelElement () { if (mode == XmlReadMode.Fragment && (XmlHelper.Decode (reader.LocalName) != dataset.DataSetName || reader.NamespaceURI != dataset.Namespace)) reader.Skip (); else if (mode == XmlReadMode.Fragment || IsTopLevelDataSet ()) { int depth = reader.Depth; reader.Read (); reader.MoveToContent (); do { ReadDataSetContent (); } while (reader.Depth > depth && !reader.EOF); if (reader.NodeType == XmlNodeType.EndElement) reader.ReadEndElement (); reader.MoveToContent (); } else ReadDataSetContent (); } private void ReadDataSetContent () { DataTable table = dataset.Tables [XmlHelper.Decode (reader.LocalName)]; if (table == null || table.Namespace != reader.NamespaceURI) { reader.Skip (); reader.MoveToContent (); return; // skip if there is no matching table } // skip if namespace does not match. if (table.Namespace != reader.NamespaceURI) { reader.Skip (); reader.MoveToContent (); return; // skip if there is no matching table } DataRow row = table.NewRow (); ReadElement (row); table.Rows.Add (row); } private void ReadElement (DataRow row) { // Consume attributes if (reader.MoveToFirstAttribute ()) { do { if (reader.NamespaceURI == XmlConstants.XmlnsNS #if NET_2_0 || reader.NamespaceURI == XmlConstants.XmlNS #endif ) continue; ReadElementAttribute (row); } while (reader.MoveToNextAttribute ()); reader.MoveToElement (); } // If not empty element, read content. if (reader.IsEmptyElement) { reader.Skip (); reader.MoveToContent (); } else { int depth = reader.Depth; reader.Read (); reader.MoveToContent (); do { ReadElementContent (row); } while (reader.Depth > depth && !reader.EOF); if (reader.IsEmptyElement) reader.Read (); if (reader.NodeType == XmlNodeType.EndElement) reader.ReadEndElement (); reader.MoveToContent (); } } private void ReadElementAttribute (DataRow row) { DataColumn col = row.Table.Columns [XmlHelper.Decode (reader.LocalName)]; if (col == null || col.Namespace != reader.NamespaceURI) return; row [col] = StringToObject (col.DataType, reader.Value); } private void ReadElementContent (DataRow row) { switch (reader.NodeType) { case XmlNodeType.EndElement: // This happens when the content was only whitespace (and skipped by MoveToContent()). return; case XmlNodeType.Element: ReadElementElement (row); break; case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.SignificantWhitespace: DataColumn simple = null; DataColumnCollection cols = row.Table.Columns; for (int i = 0; i < cols.Count; i++) { DataColumn col = cols [i]; if (col.ColumnMapping == MappingType.SimpleContent) { simple = col; break; } } string s = reader.ReadString (); reader.MoveToContent (); #if SILLY_MS_COMPATIBLE // As to MS, "test string" and "test <!-- comment -->string" are different :P if (simple != null && row.IsNull (simple)) row [simple] = StringToObject (simple.DataType, s); #else // But it does not mean we support "123<!-- comment -->456". just allowed for string if (simple != null) row [simple] += s; #endif break; case XmlNodeType.Whitespace: reader.ReadString (); break; } } private void ReadElementElement (DataRow row) { // This child element (for row) might be either simple // content element, or child element // MS.NET crashes here... but it seems just a bug. DataColumn col = row.Table.Columns [XmlHelper.Decode (reader.LocalName)]; if (col == null || col.Namespace != reader.NamespaceURI) col = null; // if col exists, then it should be MappingType.Element if (col != null && col.ColumnMapping == MappingType.Element) { // TODO: This part is suspicious for // MS compatibility (test required) if (col.Namespace != reader.NamespaceURI) { reader.Skip (); return; } bool wasEmpty = reader.IsEmptyElement; int depth = reader.Depth; if (typeof (IXmlSerializable).IsAssignableFrom (col.DataType)) { #if NET_2_0 try { // NOTE: ReadElementString works fine with proper XML with CDATA etc, // however doesn't behave well with XMLs like the one in // https://bugzilla.novell.com/show_bug.cgi?id=377146 which is // apparently supported by MS.NET - to maintain compatibility, // If the obj implements IXmlSerializable, let obj's ReadXml do the reading IXmlSerializable obj = (IXmlSerializable) Activator.CreateInstance (col.DataType, new object [0]); if (!reader.IsEmptyElement) { obj.ReadXml (reader); reader.ReadEndElement (); } else { reader.Skip (); } row [col] = obj; } catch (XmlException) { #endif // XML is not in accordance to expected standards, try reading the content as an xml doc row [col] = reader.ReadInnerXml (); #if NET_2_0 } catch (InvalidOperationException) { row [col] = reader.ReadInnerXml (); } #endif } else { row [col] = StringToObject (col.DataType, reader.ReadElementString ()); } if (!wasEmpty && reader.Depth > depth) { // This means, instance does not match with // the schema (because the instance element // contains complex content, while specified as // simple), so just skip to the end of the // element. while (reader.Depth > depth) reader.Read (); reader.Read (); } reader.MoveToContent (); return; } else if (col != null) { // Mismatch column type. Just skip reader.Skip (); reader.MoveToContent (); return; } // Otherwise, it might be child table element DataRelationCollection rels = row.Table.ChildRelations; for (int i = 0; i < rels.Count; i++) { DataRelation rel = rels [i]; if (!rel.Nested) continue; DataTable ct = rel.ChildTable; if (ct.TableName != XmlHelper.Decode (reader.LocalName) || ct.Namespace != reader.NamespaceURI) continue; DataRow childRow = rel.ChildTable.NewRow (); ReadElement (childRow); for (int c = 0; c < rel.ChildColumns.Length; c++) { childRow [rel.ChildColumns [c]] = row [rel.ParentColumns [c]]; } rel.ChildTable.Rows.Add (childRow); return; } // Matched neither of the above: just skip reader.Skip (); reader.MoveToContent (); } internal static object StringToObject (Type type, string value) { if (type == null) return value; switch (Type.GetTypeCode (type)) { case TypeCode.Boolean: return XmlConvert.ToBoolean (value); case TypeCode.Byte: return XmlConvert.ToByte (value); case TypeCode.Char: return (char)XmlConvert.ToInt32 (value); #if NET_2_0 case TypeCode.DateTime: return XmlConvert.ToDateTime (value, XmlDateTimeSerializationMode.Unspecified); #else case TypeCode.DateTime: return XmlConvert.ToDateTime (value); #endif case TypeCode.Decimal: return XmlConvert.ToDecimal (value); case TypeCode.Double: return XmlConvert.ToDouble (value); case TypeCode.Int16: return XmlConvert.ToInt16 (value); case TypeCode.Int32: return XmlConvert.ToInt32 (value); case TypeCode.Int64: return XmlConvert.ToInt64 (value); case TypeCode.SByte: return XmlConvert.ToSByte (value); case TypeCode.Single: return XmlConvert.ToSingle (value); case TypeCode.UInt16: return XmlConvert.ToUInt16 (value); case TypeCode.UInt32: return XmlConvert.ToUInt32 (value); case TypeCode.UInt64: return XmlConvert.ToUInt64 (value); } if (type == typeof (TimeSpan)) return XmlConvert.ToTimeSpan (value); if (type == typeof (Guid)) return XmlConvert.ToGuid (value); if (type == typeof (byte[])) return Convert.FromBase64String (value); if (type == typeof (System.Type)) return System.Type.GetType (value); return Convert.ChangeType (value, type); } } }
edwinspire/VSharp
class/System.Data/System.Data/XmlDataReader.cs
C#
lgpl-3.0
12,544
/* * LuoYing is a program used to make 3D RPG game. * Copyright (c) 2014-2016 Huliqing <31703299@qq.com> * * This file is part of LuoYing. * * LuoYing 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. * * LuoYing 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 LuoYing. If not, see <http://www.gnu.org/licenses/>. */ package name.huliqing.editor.converter.field; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.value.ObservableValue; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.ToolBar; import javafx.scene.layout.VBox; import name.huliqing.editor.component.ComponentDefine; import name.huliqing.editor.constants.AssetConstants; import name.huliqing.editor.constants.StyleConstants; import name.huliqing.editor.converter.DataConverter; import name.huliqing.editor.converter.SimpleFieldConverter; import name.huliqing.editor.edit.UndoRedo; import name.huliqing.editor.edit.scene.JfxSceneEdit; import name.huliqing.editor.manager.ComponentManager; import name.huliqing.editor.manager.ConverterManager; import name.huliqing.editor.ui.ComponentSearch; import name.huliqing.editor.ui.utils.JfxUtils; import name.huliqing.fxswing.Jfx; import name.huliqing.luoying.data.EntityData; import name.huliqing.luoying.object.Loader; import name.huliqing.luoying.xml.ObjectData; /** * 用于转换Entity的objectDatas字段,可以指定DataType和ComponentType. * 所有包含在EntityData的objectDatas字段中的列表数据都需要继承自这个类, 例如:SkillData,ChannelData,EffectData,LogicDatas...等等 * @author huliqing */ public class EntityObjectDatasConverter extends SimpleFieldConverter<JfxSceneEdit, EntityData>{ private static final Logger LOG = Logger.getLogger(EntityObjectDatasConverter.class.getName()); private final static String FEATURE_DATA_TYPE = "dataType"; private final static String FEATURE_COMPONENT_TYPE = "componentType"; private Class<? extends ObjectData> dataType; private String componentType; protected ComponentSearch<ComponentDefine> componentList = new ComponentSearch(); protected final VBox layout = new VBox(); protected final ToolBar toolbar = new ToolBar(); protected final ListView<ObjectData> listView = new ListView(); private DataConverter dataConverter; public EntityObjectDatasConverter() { Button add = new Button("", JfxUtils.createIcon(AssetConstants.INTERFACE_ICON_ADD)); Button remove = new Button("", JfxUtils.createIcon(AssetConstants.INTERFACE_ICON_SUBTRACT)); add.setOnAction(e -> { componentList.show(add, -10, -10); }); remove.setOnAction(e -> { List<ObjectData> eds = listView.getSelectionModel().getSelectedItems(); if (eds == null || eds.isEmpty()) return; Jfx.runOnJme(() -> { ObjectData od = listView.getSelectionModel().getSelectedItem(); if (od != null) { ObjectDataRemovedUndoRedo ur = new ObjectDataRemovedUndoRedo(od); ur.redo(); jfxEdit.getJmeEdit().addUndoRedo(ur); } }); }); componentList.getListView().setOnMouseClicked(e -> { ComponentDefine cd = componentList.getListView().getSelectionModel().getSelectedItem(); if (cd != null) { Jfx.runOnJme(() -> { ObjectData od = Loader.loadData(cd.getId()); if (od != null) { ObjectDataAddedUndoRedo ur = new ObjectDataAddedUndoRedo(od); ur.redo(); jfxEdit.getJmeEdit().addUndoRedo(ur); } }); } componentList.hide(); }); listView.setCellFactory((ListView<ObjectData> param) -> new ListCell<ObjectData>(){ @Override protected void updateItem(ObjectData item, boolean empty) { super.updateItem(item, empty); setText(null); setGraphic(null); if (!empty) { String name = item.getName(); if (name != null && !name.isEmpty()) { setText(item.getId() + "(" + name + ")"); } else { setText(item.getId()); } } } }); listView.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends ObjectData> observable , ObjectData oldValue, ObjectData newValue) -> { if (dataConverter != null && dataConverter.isInitialized()) { dataConverter.cleanup(); } // 注:newVaue是有可能为null的,当删除了列表中的节点时可能发生,所以要避免NPE if (newValue == null) { return; } dataConverter = ConverterManager.createDataConverter(jfxEdit, newValue, EntityObjectDatasConverter.this); dataConverter.initialize(); // getParent().setChildContent(newValue.getId(), dataConverter.getLayout()); getParent().setChildLayout(newValue.getId(), dataConverter); }); listView.setPrefHeight(160); toolbar.getItems().addAll(add, remove); layout.getStyleClass().add(StyleConstants.CLASS_HVBOX); layout.getChildren().addAll(toolbar, listView); } @Override public void notifyChanged() { listView.refresh();// 这一句允许刷新列表中的物体名称。 super.notifyChanged(); } @Override public void initialize() { super.initialize(); String tempDataType = featureHelper.getAsString(FEATURE_DATA_TYPE); try { dataType = (Class<? extends ObjectData>) Class.forName(tempDataType); } catch (Exception ex) { dataType = ObjectData.class; LOG.log(Level.WARNING , "Unknow dataType! dataType=" + tempDataType + ", field=" + field + ", data=" + data.getId() , ex); } componentType = featureHelper.getAsString(FEATURE_COMPONENT_TYPE); if (componentType != null) { componentList.setComponents(ComponentManager.getComponentsByType(componentType)); } else { componentList.setComponents(ComponentManager.getComponents(null)); } } @Override public void cleanup() { if (dataConverter != null) { if (dataConverter.isInitialized()) { dataConverter.cleanup(); } dataConverter = null; } super.cleanup(); } @Override protected Node createLayout() { return layout; } @Override protected void updateUI() { List dataList = new ArrayList(); data.getObjectDatas(dataType, dataList); listView.getItems().clear(); listView.getItems().addAll(dataList); } private class ObjectDataAddedUndoRedo implements UndoRedo { private final ObjectData added; public ObjectDataAddedUndoRedo(ObjectData added) { this.added = added; } @Override public void undo() { data.removeObjectData(added); Jfx.runOnJfx(() -> { listView.getItems().remove(added); notifyChanged(); }); } @Override public void redo() { data.addObjectData(added); Jfx.runOnJfx(() -> { listView.getItems().add(added); notifyChanged(); }); } } private class ObjectDataRemovedUndoRedo implements UndoRedo { private final ObjectData removed; public ObjectDataRemovedUndoRedo(ObjectData removed) { this.removed = removed; } @Override public void undo() { data.addObjectData(removed); Jfx.runOnJfx(() -> { listView.getItems().add(removed); notifyChanged(); }); } @Override public void redo() { data.removeObjectData(removed); Jfx.runOnJfx(() -> { listView.getItems().remove(removed); notifyChanged(); }); } } }
huliqing/LuoYing
ly-editor/src/name/huliqing/editor/converter/field/EntityObjectDatasConverter.java
Java
lgpl-3.0
9,393
static char rcsid[] = "$Id$"; /* * $TSUKUBA_Release: Omni OpenMP Compiler 3 $ * $TSUKUBA_Copyright: * PLEASE DESCRIBE LICENSE AGREEMENT HERE * $ */ /* error case of reduction 015 : * reduction ¤Ç»ØÄꤵ¤ì¤Æ operation ¤È±é»»¤¬°Û¤Ê¤ë¾ì¹ç¡£ */ #include <omp.h> #include "omni.h" int errors = 0; int thds; int rdct; main () { int i; thds = omp_get_max_threads (); if (thds == 1) { printf ("should be run this program on multi threads.\n"); exit (0); } omp_set_dynamic (0); #pragma omp parallel for reduction(+:rdct) for (i=0; i<thds; i++) { rdct += 1; } #pragma omp parallel for reduction(+:rdct) for (i=0; i<thds; i++) { rdct -= 1; } #pragma omp parallel for reduction(+:rdct) for (i=0; i<thds; i++) { rdct *= 1; } #pragma omp parallel for reduction(+:rdct) for (i=0; i<thds; i++) { rdct &= 1; } #pragma omp parallel for reduction(+:rdct) for (i=0; i<thds; i++) { rdct |= 1; } #pragma omp parallel for reduction(+:rdct) for (i=0; i<thds; i++) { rdct ^= 1; } #pragma omp parallel for reduction(+:rdct) for (i=0; i<thds; i++) { rdct = rdct && 1; } #pragma omp parallel for reduction(+:rdct) for (i=0; i<thds; i++) { rdct = rdct && 1; } printf ("err_reduction 015 : FAILED, can not compile this program.\n"); return 1; }
omni-compiler/omni-compiler
tests/old/C-test/directive/data/rdctn/err_reduction_015.c
C
lgpl-3.0
1,345
<?php /*************************************************************************************/ /* This file is part of the Thelia package. */ /* */ /* Copyright (c) OpenStudio */ /* email : dev@thelia.net */ /* web : http://www.thelia.net */ /* */ /* For the full copyright and license information, please view the LICENSE.txt */ /* file that was distributed with this source code. */ /*************************************************************************************/ namespace Thelia\Core\FileFormat\Formatting; use Thelia\Core\FileFormat\FormatInterface; use Thelia\Core\Translation\Translator; use Thelia\Log\Tlog; /** * Class AbstractFormatter * @package Thelia\Core\FileFormat\Formatting * @author Benjamin Perche <bperche@openstudio.fr> */ abstract class AbstractFormatter implements FormatInterface, FormatterInterface { const FILENAME = "data"; /** @var \Thelia\Core\Translation\Translator */ protected $translator; /** @var \Thelia\Log\Tlog */ protected $logger; /** @var array */ protected $order = array(); public function __construct() { $this->translator = Translator::getInstance(); $this->logger = Tlog::getInstance(); } public function getOrder() { return $this->order; } public function setOrder(array $order) { $this->order = $order; return $this; } public function checkOrders(array $values) { foreach ($this->getOrder() as $order) { if (!array_key_exists($order, $values)) { throw new \ErrorException( $this->translator->trans( "The column %column that you want to sort doesn't exist", [ "%column" => $order ] ) ); } } } }
AznStyle/lwb2
core/lib/Thelia/Core/FileFormat/Formatting/AbstractFormatter.php
PHP
lgpl-3.0
2,305
// // OutputCacheParametersTest.cs // - Unit tests for System.Web.UI.OutputCacheParameters // // Author: // Noam Lampert (noaml@mainsoft.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_2_0 using System; using System.IO; using System.Web.UI; using NUnit.Framework; using System.Collections; namespace MonoTests.System.Web.UI { [TestFixture] public class OutputCacheParametersTest { [Test] public void InitialValues () { OutputCacheParameters o = new OutputCacheParameters (); Assert.IsNull (o.CacheProfile, "CacheProfile"); Assert.IsTrue (o.Duration == 0, "Duration"); Assert.IsTrue (o.Enabled, "Enabled"); Assert.IsTrue (o.Location == OutputCacheLocation.Any, "OutputCacheLocation"); Assert.IsFalse (o.NoStore, "NoStore"); Assert.IsNull (o.SqlDependency, "SqlDependency"); Assert.IsNull (o.VaryByControl, "VaryByControl"); Assert.IsNull (o.VaryByCustom, "VaryByCustom"); Assert.IsNull (o.VaryByHeader, "VaryByHeader"); Assert.IsNull (o.VaryByParam, "VaryByParam"); } } } #endif
edwinspire/VSharp
class/System.Web/Test/System.Web.UI/OutputCacheParametersTest.cs
C#
lgpl-3.0
2,077
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_16) on Thu Feb 26 13:28:55 PST 2009 --> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <TITLE> B-Index (JavaMail API documentation) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="B-Index (JavaMail API documentation)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="index-1.html"><B>PREV LETTER</B></A>&nbsp; &nbsp;<A HREF="index-3.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-2.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-2.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">J</A> <A HREF="index-11.html">K</A> <A HREF="index-12.html">L</A> <A HREF="index-13.html">M</A> <A HREF="index-14.html">N</A> <A HREF="index-15.html">O</A> <A HREF="index-16.html">P</A> <A HREF="index-17.html">Q</A> <A HREF="index-18.html">R</A> <A HREF="index-19.html">S</A> <A HREF="index-20.html">T</A> <A HREF="index-21.html">U</A> <A HREF="index-22.html">V</A> <A HREF="index-23.html">W</A> <A HREF="index-24.html">X</A> <HR> <A NAME="_B_"><!-- --></A><H2> <B>B</B></H2> <DL> <DT><A HREF="../javax/mail/Message.RecipientType.html#BCC"><B>BCC</B></A> - Static variable in class javax.mail.<A HREF="../javax/mail/Message.RecipientType.html" title="class in javax.mail">Message.RecipientType</A> <DD>The "Bcc" (blind carbon copy) recipients. <DT><A HREF="../javax/mail/BodyPart.html" title="class in javax.mail"><B>BodyPart</B></A> - Class in <A HREF="../javax/mail/package-summary.html">javax.mail</A><DD>This class models a Part that is contained within a Multipart.<DT><A HREF="../javax/mail/BodyPart.html#BodyPart()"><B>BodyPart()</B></A> - Constructor for class javax.mail.<A HREF="../javax/mail/BodyPart.html" title="class in javax.mail">BodyPart</A> <DD>&nbsp; <DT><A HREF="../javax/mail/search/BodyTerm.html" title="class in javax.mail.search"><B>BodyTerm</B></A> - Class in <A HREF="../javax/mail/search/package-summary.html">javax.mail.search</A><DD>This class implements searches on a Message Body.<DT><A HREF="../javax/mail/search/BodyTerm.html#BodyTerm(java.lang.String)"><B>BodyTerm(String)</B></A> - Constructor for class javax.mail.search.<A HREF="../javax/mail/search/BodyTerm.html" title="class in javax.mail.search">BodyTerm</A> <DD>Constructor <DT><A HREF="../com/sun/mail/imap/IMAPMessage.html#bs"><B>bs</B></A> - Variable in class com.sun.mail.imap.<A HREF="../com/sun/mail/imap/IMAPMessage.html" title="class in com.sun.mail.imap">IMAPMessage</A> <DD>&nbsp; <DT><A HREF="../javax/mail/util/SharedFileInputStream.html#bufpos"><B>bufpos</B></A> - Variable in class javax.mail.util.<A HREF="../javax/mail/util/SharedFileInputStream.html" title="class in javax.mail.util">SharedFileInputStream</A> <DD>The file offset that corresponds to the first byte in the read buffer. <DT><A HREF="../javax/mail/util/SharedFileInputStream.html#bufsize"><B>bufsize</B></A> - Variable in class javax.mail.util.<A HREF="../javax/mail/util/SharedFileInputStream.html" title="class in javax.mail.util">SharedFileInputStream</A> <DD>The normal size of the read buffer. <DT><A HREF="../javax/mail/util/ByteArrayDataSource.html" title="class in javax.mail.util"><B>ByteArrayDataSource</B></A> - Class in <A HREF="../javax/mail/util/package-summary.html">javax.mail.util</A><DD>A DataSource backed by a byte array.<DT><A HREF="../javax/mail/util/ByteArrayDataSource.html#ByteArrayDataSource(java.io.InputStream, java.lang.String)"><B>ByteArrayDataSource(InputStream, String)</B></A> - Constructor for class javax.mail.util.<A HREF="../javax/mail/util/ByteArrayDataSource.html" title="class in javax.mail.util">ByteArrayDataSource</A> <DD>Create a ByteArrayDataSource with data from the specified InputStream and with the specified MIME type. <DT><A HREF="../javax/mail/util/ByteArrayDataSource.html#ByteArrayDataSource(byte[], java.lang.String)"><B>ByteArrayDataSource(byte[], String)</B></A> - Constructor for class javax.mail.util.<A HREF="../javax/mail/util/ByteArrayDataSource.html" title="class in javax.mail.util">ByteArrayDataSource</A> <DD>Create a ByteArrayDataSource with data from the specified byte array and with the specified MIME type. <DT><A HREF="../javax/mail/util/ByteArrayDataSource.html#ByteArrayDataSource(java.lang.String, java.lang.String)"><B>ByteArrayDataSource(String, String)</B></A> - Constructor for class javax.mail.util.<A HREF="../javax/mail/util/ByteArrayDataSource.html" title="class in javax.mail.util">ByteArrayDataSource</A> <DD>Create a ByteArrayDataSource with data from the specified String and with the specified MIME type. </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="index-1.html"><B>PREV LETTER</B></A>&nbsp; &nbsp;<A HREF="index-3.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-2.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-2.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">J</A> <A HREF="index-11.html">K</A> <A HREF="index-12.html">L</A> <A HREF="index-13.html">M</A> <A HREF="index-14.html">N</A> <A HREF="index-15.html">O</A> <A HREF="index-16.html">P</A> <A HREF="index-17.html">Q</A> <A HREF="index-18.html">R</A> <A HREF="index-19.html">S</A> <A HREF="index-20.html">T</A> <A HREF="index-21.html">U</A> <A HREF="index-22.html">V</A> <A HREF="index-23.html">W</A> <A HREF="index-24.html">X</A> <HR> Copyright &#169; 2009 <a href="http://www.sun.com">Sun Microsystems, Inc.</a>. All Rights Reserved. </BODY> </HTML>
simeshev/parabuild-ci
3rdparty/javamail-1.4.2/docs/javadocs/index-files/index-2.html
HTML
lgpl-3.0
10,261
# Copyright (C) 2015 Kevin Ross # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. from lib.cuckoo.common.abstracts import Signature class DisablesWER(Signature): name = "disables_wer" description = "Attempts to disable Windows Error Reporting" severity = 3 categories = ["stealth"] authors = ["Kevin Ross"] minimum = "1.2" def run(self): if self.check_write_key(pattern=".*\\\\SOFTWARE\\\\(Wow6432Node\\\\)?Microsoft\\\\Windows\\\\Windows\\ Error\\ Reporting\\\\Disabled$", regex=True): return True return False
lixiangning888/whole_project
modules/signatures_orignal/disables_wer.py
Python
lgpl-3.0
645
# -*- coding: utf-8 -*- import unittest import warnings from tcdb import adb class TestADBSimple(unittest.TestCase): def setUp(self): self.adb = adb.ADBSimple() self.adb.open('*') def tearDown(self): self.adb.close() self.adb = None def test_setgetitem(self): self.adb['key'] = 'some string' self.assertEqual(self.adb['key'], 'some string') self.assertRaises(KeyError, self.adb.__getitem__, 'nonexistent key') def test_put(self): self.adb.put('key', 'some string') self.assertEqual(self.adb.get('key'), 'some string') self.assertEqual(self.adb.get('nonexistent key'), None) self.assertEqual(self.adb.get('nonexistent key', 'def'), 'def') def test_putkeep(self): self.adb.putkeep('key', 'some string') self.assertEqual(self.adb.get('key'), 'some string') self.adb.putkeep('key', 'Never stored') self.assertEqual(self.adb.get('key'), 'some string') def test_putcat(self): self.adb.putcat('key', 'some') self.adb.putcat('key', ' text') self.assertEquals(self.adb.get('key'), 'some text') def test_out_and_contains(self): self.assert_('key' not in self.adb) self.adb.put('key', 'some text') self.assert_('key' in self.adb) self.adb.out('key') self.assert_('key' not in self.adb) self.adb.put('key', 'some text') self.assert_('key' in self.adb) del self.adb['key'] self.assert_('key' not in self.adb) def test_vsiz(self): self.adb.put('key', 'some text') self.assertEqual(self.adb.vsiz('key'), len('some text')) def test_iters(self): keys = ['key1', 'key2', 'key3', 'key4', 'key5'] for key in keys: self.adb.put(key, key) self.assertEqual(len(self.adb.keys()), len(keys)) self.assertEqual(len(self.adb.values()), len(keys)) self.assertEqual(len(zip(keys, keys)), len(self.adb.items())) for key in self.adb: self.assert_(key in keys) for value in self.adb.itervalues(): self.assert_(value in keys) def test_fwmkeys(self): objs = ['aa', 'ab', 'ac', 'xx', 'ad'] for obj in objs: self.adb.put(obj, 'same value') self.assertEqual(len(self.adb.fwmkeys('a')), len(['aa', 'ab', 'ac', 'ad'])) self.assertEqual(self.adb.fwmkeys('x'), ['xx']) self.assertEqual(self.adb.fwmkeys('nonexistent key'), []) def test_admin_functions(self): keys = ['key1', 'key2', 'key3', 'key4', 'key5'] for key in keys: self.adb.put(key, key) self.assertEquals(self.adb.path(), '*') self.adb.sync() self.assertEquals(len(self.adb), 5) self.assertEquals(self.adb.size(), 525656) self.adb.vanish() self.assertEquals(self.adb.size(), 525376) # def test_transaction(self): # keys = ['key1', 'key2', 'key3', 'key4', 'key5'] # with self.adb as db: # for key in keys: # db.put(key, key) # self.assertEquals(len(self.adb), 5) # self.adb.vanish() # try: # with self.adb: # for key in keys: # self.adb.put(key, key) # self.adb['bad key'] # except KeyError: # pass # self.assertEquals(len(self.adb), 0) def test_foreach(self): keys = ['key1', 'key2', 'key3', 'key4', 'key5'] def proc(key, value, op): self.assertEquals(key, value) self.assert_(key in keys) self.assertEquals(op, 'test') return True for key in keys: self.adb.put(key, key) self.adb.foreach(proc, 'test') class TestADB(unittest.TestCase): def setUp(self): self.adb = adb.ADB() self.adb.open('*') def tearDown(self): self.adb.close() self.adb = None def test_setgetitem(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj1 in objs: self.adb['obj'] = obj1 obj2 = self.adb['obj'] self.assertEqual(obj1, obj2) self.adb[obj1] = obj1 obj2 = self.adb[obj1] self.assertEqual(obj1, obj2) self.assertRaises(KeyError, self.adb.__getitem__, 'nonexistent key') def test_put(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj1 in objs: self.adb.put(obj1, obj1) obj2 = self.adb.get(obj1) self.assertEqual(obj1, obj2) self.adb.put(obj1, obj1, raw_key=True) obj2 = self.adb.get(obj1, raw_key=True) self.assertEqual(obj1, obj2) self.assertEqual(self.adb.get('nonexistent key'), None) self.assertEqual(self.adb.get('nonexistent key', 'def'), 'def') def test_put_str(self): str1 = 'some text [áéíóú]' objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put_str(obj, str1) str2 = self.adb.get_str(obj) self.assertEqual(str1, str2) self.adb.put_str(obj, str1, as_raw=True) str2 = self.adb.get_str(obj, as_raw=True) self.assertEqual(str1, str2) unicode1 = u'unicode text [áéíóú]' for obj in objs: self.adb.put_str(obj, unicode1.encode('utf8')) unicode2 = unicode(self.adb.get_str(obj), 'utf8') self.assertEqual(unicode1, unicode2) self.assertRaises(AssertionError, self.adb.put_str, 'key', 10) self.assertEqual(self.adb.get_str('nonexistent key'), None) self.assertEqual(self.adb.get_str('nonexistent key', 'def'), 'def') def test_put_unicode(self): unicode1 = u'unicode text [áéíóú]' objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put_unicode(obj, unicode1) unicode2 = self.adb.get_unicode(obj) self.assertEqual(unicode1, unicode2) self.adb.put_unicode(obj, unicode1, as_raw=True) unicode2 = self.adb.get_unicode(obj, as_raw=True) self.assertEqual(unicode1, unicode2) self.assertRaises(AssertionError, self.adb.put_unicode, 'key', 10) self.assertEqual(self.adb.get_unicode('nonexistent key'), None) self.assertEqual(self.adb.get_unicode('nonexistent key', 'def'), 'def') def test_put_int(self): int1 = 10 objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put_int(obj, int1) int2 = self.adb.get_int(obj) self.assertEqual(int1, int2) self.adb.put_int(obj, int1, as_raw=True) int2 = self.adb.get_int(obj, as_raw=True) self.assertEqual(int1, int2) self.assertRaises(AssertionError, self.adb.put_int, 'key', '10') self.assertEqual(self.adb.get_int('nonexistent key'), None) self.assertEqual(self.adb.get_int('nonexistent key', 'def'), 'def') def test_put_float(self): float1 = 10.10 objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put_float(obj, float1) float2 = self.adb.get_float(obj) self.assertEqual(float1, float2) self.adb.put_float(obj, float1, as_raw=True) float2 = self.adb.get_float(obj, as_raw=True) self.assertEqual(float1, float2) self.assertRaises(AssertionError, self.adb.put_float, 'key', 10) self.assertEqual(self.adb.get_float('nonexistent key'), None) self.assertEqual(self.adb.get_float('nonexistent key', 'def'), 'def') def test_putkeep(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj1 in objs: self.adb.putkeep(obj1, obj1) obj2 = self.adb.get(obj1) self.assertEqual(obj1, obj2) self.adb.putkeep(obj1, 'Never stored') obj2 = self.adb.get(obj1) self.assertEqual(obj1, obj2) def test_putkeep_str(self): str1 = 'some text [áéíóú]' objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.putkeep_str(obj, str1) str2 = self.adb.get_str(obj) self.assertEqual(str1, str2) self.adb.putkeep_str(obj, 'Never stored') str2 = self.adb.get_str(obj) self.assertEqual(str1, str2) self.assertRaises(AssertionError, self.adb.putkeep_str, 'key', 10) def test_putkeep_unicode(self): unicode1 = u'unicode text [áéíóú]' objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.putkeep_unicode(obj, unicode1) unicode2 = self.adb.get_unicode(obj) self.assertEqual(unicode1, unicode2) self.adb.putkeep_unicode(obj, u'Never stored') unicode2 = self.adb.get_unicode(obj) self.assertEqual(unicode1, unicode2) self.assertRaises(AssertionError, self.adb.putkeep_unicode, 'key', 10) def test_putkeep_int(self): int1 = 10 objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.putkeep_int(obj, int1) int2 = self.adb.get_int(obj) self.assertEqual(int1, int2) self.adb.putkeep_int(obj, int1*10) int2 = self.adb.get_int(obj) self.assertEqual(int1, int2) self.assertRaises(AssertionError, self.adb.putkeep_int, 'key', '10') def test_putkeep_float(self): float1 = 10.10 objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.putkeep_float(obj, float1) float2 = self.adb.get_float(obj) self.assertEqual(float1, float2) self.adb.putkeep_float(obj, float1*10) float2 = self.adb.get_float(obj) self.assertEqual(float1, float2) self.assertRaises(AssertionError, self.adb.put_float, 'key', 10) def test_putcat_str(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.putcat_str(obj, 'some') for obj in objs: self.adb.putcat_str(obj, ' text') for obj in objs: self.assertEquals(self.adb.get_str(obj), 'some text') def test_putcat_unicode(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.putcat_unicode(obj, u'some') for obj in objs: self.adb.putcat_unicode(obj, u' text') for obj in objs: self.assertEquals(self.adb.get_unicode(obj), u'some text') def test_out_and_contains(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put(obj, obj) self.assert_(obj in self.adb) self.adb.out(obj) self.assert_(obj not in self.adb) for obj in objs: self.adb.put(obj, obj) self.assert_(obj in self.adb) del self.adb[obj] self.assert_(obj not in self.adb) def test_vsiz(self): obj = 1+1j self.adb.put(obj, obj) vsiz = self.adb.vsiz(obj) self.assertEqual(vsiz, 48) obj = 'some text [áéíóú]' self.adb.put_str(obj, obj) vsiz = self.adb.vsiz(obj) self.assertEqual(vsiz, 22) obj = u'unicode text [áéíóú]' self.adb.put_str(obj, obj.encode('utf8')) vsiz = self.adb.vsiz(obj) self.assertEqual(vsiz, 25) obj = 10 self.adb.put_int(obj, obj) vsiz = self.adb.vsiz(obj) self.assertEqual(vsiz, 4) obj = 10.10 self.adb.put_float(obj, obj) vsiz = self.adb.vsiz(obj) self.assertEqual(vsiz, 8) def test_iters(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put(obj, obj) self.assertEqual(len(self.adb.keys()), len(objs)) self.assertEqual(len(self.adb.values()), len(objs)) for key in self.adb: with warnings.catch_warnings(): warnings.simplefilter("ignore") self.assert_(key in objs) for value in self.adb.itervalues(): with warnings.catch_warnings(): warnings.simplefilter("ignore") self.assert_(value in objs) def test_fwmkeys(self): objs = ['aa', 'ab', 'ac', 'xx', 'ad'] for obj in objs: self.adb.put(obj, 'same value', raw_key=True) self.assertEqual(len(self.adb.fwmkeys('a')), len(['aa', 'ab', 'ac', 'ad'])) self.assertEqual(self.adb.fwmkeys('x'), ['xx']) self.assertEqual(self.adb.fwmkeys('nonexistent key'), []) def test_add_int(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put_int(obj, 10) for key in self.adb: self.adb.add_int(key, 2) for key in self.adb: self.assertEqual(self.adb.get_int(key), 12) def test_add_float(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put_float(obj, 10.0) for key in self.adb: self.adb.add_float(key, 2.0) for key in self.adb: self.assertEqual(self.adb.get_float(key), 12.0) def test_admin_functions(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put(obj, obj) self.assertEquals(self.adb.path(), '*') self.adb.sync() self.assertEquals(len(self.adb), 5) self.assertEquals(self.adb.size(), 525874) self.adb.vanish() self.assertEquals(self.adb.size(), 525376) # def test_transaction(self): # objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] # with self.adb as db: # for obj in objs: # db.put(obj, obj) # self.assertEquals(len(self.adb), 5) # self.adb.vanish() # try: # with self.adb: # for obj in objs: # self.adb.put(obj, obj) # self.adb.get('Not exist key') # except KeyError: # pass # self.assertEquals(len(self.adb), 0) def test_foreach(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] def proc(key, value, op): self.assertEquals(key, value) with warnings.catch_warnings(): warnings.simplefilter("ignore") self.assert_(key in objs) self.assertEquals(op, 'test') return True for obj in objs: self.adb.put(obj, obj) self.adb.foreach(proc, 'test') if __name__ == '__main__': unittest.main()
aplanas/py-tcdb
test/test-adb.py
Python
lgpl-3.0
15,634
/* ========================================================================= * This file is part of NITRO * ========================================================================= * * (C) Copyright 2004 - 2014, MDA Information Systems LLC * * NITRO 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, If not, * see <http://www.gnu.org/licenses/>. * */ #include <import/nitf.hpp> #include <import/sys.h> #include <import/except.h> int main(int, char**) { try { std::cout << "Crazy FileHeader test" << std::endl; //Sticking a second in breaks the paradigm!!! nitf::FileHeader fileHeader; std::cout << "Created FileHeader" << std::endl; //fileHeader.name = "1"; nitf::FileHeader two = fileHeader; std::cout << "Copied FileHeader" << std::endl; //two.name = "2"; nitf::FileHeader three = two; std::cout << "Copied FileHeader copy" << std::endl; //three.name = "3"; nitf::FileHeader alone; std::cout << "Created another FileHeader" << std::endl; //alone.name = "4"; // This guy should be different nitf::FileHeader myFileHeader; std::cout << "Created yet another FileHeader" << std::endl; //myFileHeader.name = "5"; nitf::FileHeader myFileCopy = myFileHeader; std::cout << "Copied yet another FileHeader" << std::endl; //myFileCopy.name = "6"; { std::unique_ptr<nitf::FileHeader> myNewCopy(new nitf::FileHeader(myFileCopy)); std::cout << "New-allocated copy of FileHeader" << std::endl; //myNewCopy->name = "7"; } std::cout << "Deleted new-allocated copy of FileHeader" << std::endl; { std::unique_ptr<nitf::FileHeader> myNonCopy(new nitf::FileHeader); std::cout << "New-allocated a FileHeader" << std::endl; //myNonCopy->name = "8"; } std::cout << "Deleted new-allocated FileHeader" << std::endl; std::cout << "Setting file header" << std::endl; fileHeader.getFileHeader().set("NITF"); std::cout << "Setting file version" << std::endl; fileHeader.getFileVersion().set("2.1"); two = fileHeader; std::cout << "Setting file header" << std::endl; myFileHeader.getFileHeader().set("FTIN"); std::cout << "Setting file version" << std::endl; myFileHeader.getFileVersion().set("1.2"); nitf::Extensions ext; nitf::HashTable hash; ext.setHash(hash); std::cout << fileHeader.fileHeader() << "\n"; std::cout << fileHeader.fileVersion() << "\n"; std::cout << two.fileHeader() << "\n"; std::cout << two.fileVersion() << "\n"; std::cout << myFileHeader.fileHeader() << "\n"; std::cout << myFileHeader.fileVersion() << "\n"; return 0; } catch (const except::Throwable& t) { std::cout << t.getTrace() << std::endl; } }
mdaus/nitro
modules/c++/nitf/tests/test_fh.cpp
C++
lgpl-3.0
3,560
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qdeclarativedatatest.h> #include <QtTest/QtTest> #include <QtTest/QSignalSpy> #include <private/qlistmodelinterface_p.h> #include <QtDeclarative/qdeclarativeengine.h> #include <QtDeclarative/qdeclarativeview.h> #include <QtDeclarative/qdeclarativecontext.h> #include <QtDeclarative/qdeclarativeexpression.h> #include <private/qdeclarativerepeater_p.h> #include <private/qdeclarativetext_p.h> class tst_QDeclarativeRepeater : public QDeclarativeDataTest { Q_OBJECT public: tst_QDeclarativeRepeater(); private slots: void numberModel(); void objectList(); void stringList(); void dataModel_adding(); void dataModel_removing(); void dataModel_changes(); void itemModel(); void resetModel(); void modelChanged(); void properties(); void testQtQuick11Attributes(); void testQtQuick11Attributes_data(); private: QDeclarativeView *createView(); template<typename T> T *findItem(QGraphicsObject *parent, const QString &objectName, int index); template<typename T> T *findItem(QGraphicsObject *parent, const QString &id); }; class TestObject : public QObject { Q_OBJECT Q_PROPERTY(bool error READ error WRITE setError) Q_PROPERTY(bool useModel READ useModel NOTIFY useModelChanged) public: TestObject() : QObject(), mError(true), mUseModel(false) {} bool error() const { return mError; } void setError(bool err) { mError = err; } bool useModel() const { return mUseModel; } void setUseModel(bool use) { mUseModel = use; emit useModelChanged(); } signals: void useModelChanged(); private: bool mError; bool mUseModel; }; class TestModel : public QAbstractListModel { public: enum Roles { Name = Qt::UserRole+1, Number = Qt::UserRole+2 }; TestModel(QObject *parent=0) : QAbstractListModel(parent) { QHash<int, QByteArray> roles; roles[Name] = "name"; roles[Number] = "number"; setRoleNames(roles); } int rowCount(const QModelIndex &parent=QModelIndex()) const { Q_UNUSED(parent); return list.count(); } QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const { QVariant rv; if (role == Name) rv = list.at(index.row()).first; else if (role == Number) rv = list.at(index.row()).second; return rv; } int count() const { return rowCount(); } QString name(int index) const { return list.at(index).first; } QString number(int index) const { return list.at(index).second; } void addItem(const QString &name, const QString &number) { emit beginInsertRows(QModelIndex(), list.count(), list.count()); list.append(QPair<QString,QString>(name, number)); emit endInsertRows(); } void insertItem(int index, const QString &name, const QString &number) { emit beginInsertRows(QModelIndex(), index, index); list.insert(index, QPair<QString,QString>(name, number)); emit endInsertRows(); } void removeItem(int index) { emit beginRemoveRows(QModelIndex(), index, index); list.removeAt(index); emit endRemoveRows(); } void moveItem(int from, int to) { emit beginMoveRows(QModelIndex(), from, from, QModelIndex(), to); list.move(from, to); emit endMoveRows(); } void modifyItem(int idx, const QString &name, const QString &number) { list[idx] = QPair<QString,QString>(name, number); emit dataChanged(index(idx,0), index(idx,0)); } private: QList<QPair<QString,QString> > list; }; tst_QDeclarativeRepeater::tst_QDeclarativeRepeater() { } void tst_QDeclarativeRepeater::numberModel() { QDeclarativeView *canvas = createView(); QDeclarativeContext *ctxt = canvas->rootContext(); ctxt->setContextProperty("testData", 5); TestObject *testObject = new TestObject; ctxt->setContextProperty("testObject", testObject); canvas->setSource(testFileUrl("intmodel.qml")); qApp->processEvents(); QDeclarativeRepeater *repeater = findItem<QDeclarativeRepeater>(canvas->rootObject(), "repeater"); QVERIFY(repeater != 0); QCOMPARE(repeater->parentItem()->childItems().count(), 5+1); QVERIFY(!repeater->itemAt(-1)); for (int i=0; i<repeater->count(); i++) QCOMPARE(repeater->itemAt(i), repeater->parentItem()->childItems().at(i)); QVERIFY(!repeater->itemAt(repeater->count())); QMetaObject::invokeMethod(canvas->rootObject(), "checkProperties"); QVERIFY(testObject->error() == false); delete testObject; delete canvas; } class MyObject : public QObject { Q_OBJECT Q_PROPERTY(int idx READ idx CONSTANT) public: MyObject(int i) : QObject(), m_idx(i) {} int idx() const { return m_idx; } int m_idx; }; void tst_QDeclarativeRepeater::objectList() { QDeclarativeView *canvas = createView(); QObjectList data; for(int i=0; i<100; i++) data << new MyObject(i); QDeclarativeContext *ctxt = canvas->rootContext(); ctxt->setContextProperty("testData", QVariant::fromValue(data)); canvas->setSource(testFileUrl("objlist.qml")); qApp->processEvents(); QDeclarativeRepeater *repeater = findItem<QDeclarativeRepeater>(canvas->rootObject(), "repeater"); QVERIFY(repeater != 0); QCOMPARE(repeater->property("errors").toInt(), 0);//If this fails either they are out of order or can't find the object's data QCOMPARE(repeater->property("instantiated").toInt(), 100); QVERIFY(!repeater->itemAt(-1)); for (int i=0; i<data.count(); i++) QCOMPARE(repeater->itemAt(i), repeater->parentItem()->childItems().at(i)); QVERIFY(!repeater->itemAt(data.count())); QSignalSpy addedSpy(repeater, SIGNAL(itemAdded(int,QDeclarativeItem*))); QSignalSpy removedSpy(repeater, SIGNAL(itemRemoved(int,QDeclarativeItem*))); ctxt->setContextProperty("testData", QVariant::fromValue(data)); QCOMPARE(addedSpy.count(), data.count()); QCOMPARE(removedSpy.count(), data.count()); qDeleteAll(data); delete canvas; } /* The Repeater element creates children at its own position in its parent's stacking order. In this test we insert a repeater between two other Text elements to test this. */ void tst_QDeclarativeRepeater::stringList() { QDeclarativeView *canvas = createView(); QStringList data; data << "One"; data << "Two"; data << "Three"; data << "Four"; QDeclarativeContext *ctxt = canvas->rootContext(); ctxt->setContextProperty("testData", data); canvas->setSource(testFileUrl("repeater1.qml")); qApp->processEvents(); QDeclarativeRepeater *repeater = findItem<QDeclarativeRepeater>(canvas->rootObject(), "repeater"); QVERIFY(repeater != 0); QDeclarativeItem *container = findItem<QDeclarativeItem>(canvas->rootObject(), "container"); QVERIFY(container != 0); QCOMPARE(container->childItems().count(), data.count() + 3); bool saw_repeater = false; for (int i = 0; i < container->childItems().count(); ++i) { if (i == 0) { QDeclarativeText *name = qobject_cast<QDeclarativeText*>(container->childItems().at(i)); QVERIFY(name != 0); QCOMPARE(name->text(), QLatin1String("Zero")); } else if (i == container->childItems().count() - 2) { // The repeater itself QDeclarativeRepeater *rep = qobject_cast<QDeclarativeRepeater*>(container->childItems().at(i)); QCOMPARE(rep, repeater); saw_repeater = true; continue; } else if (i == container->childItems().count() - 1) { QDeclarativeText *name = qobject_cast<QDeclarativeText*>(container->childItems().at(i)); QVERIFY(name != 0); QCOMPARE(name->text(), QLatin1String("Last")); } else { QDeclarativeText *name = qobject_cast<QDeclarativeText*>(container->childItems().at(i)); QVERIFY(name != 0); QCOMPARE(name->text(), data.at(i-1)); } } QVERIFY(saw_repeater); delete canvas; } void tst_QDeclarativeRepeater::dataModel_adding() { QDeclarativeView *canvas = createView(); QDeclarativeContext *ctxt = canvas->rootContext(); TestObject *testObject = new TestObject; ctxt->setContextProperty("testObject", testObject); TestModel testModel; ctxt->setContextProperty("testData", &testModel); canvas->setSource(testFileUrl("repeater2.qml")); qApp->processEvents(); QDeclarativeRepeater *repeater = findItem<QDeclarativeRepeater>(canvas->rootObject(), "repeater"); QVERIFY(repeater != 0); QDeclarativeItem *container = findItem<QDeclarativeItem>(canvas->rootObject(), "container"); QVERIFY(container != 0); QVERIFY(!repeater->itemAt(0)); QSignalSpy countSpy(repeater, SIGNAL(countChanged())); QSignalSpy addedSpy(repeater, SIGNAL(itemAdded(int,QDeclarativeItem*))); // add to empty model testModel.addItem("two", "2"); QCOMPARE(repeater->itemAt(0), container->childItems().at(0)); QCOMPARE(countSpy.count(), 1); countSpy.clear(); QCOMPARE(addedSpy.count(), 1); QCOMPARE(addedSpy.at(0).at(0).toInt(), 0); QCOMPARE(addedSpy.at(0).at(1).value<QDeclarativeItem*>(), container->childItems().at(0)); addedSpy.clear(); // insert at start testModel.insertItem(0, "one", "1"); QCOMPARE(repeater->itemAt(0), container->childItems().at(0)); QCOMPARE(countSpy.count(), 1); countSpy.clear(); QCOMPARE(addedSpy.count(), 1); QCOMPARE(addedSpy.at(0).at(0).toInt(), 0); QCOMPARE(addedSpy.at(0).at(1).value<QDeclarativeItem*>(), container->childItems().at(0)); addedSpy.clear(); // insert at end testModel.insertItem(2, "four", "4"); QCOMPARE(repeater->itemAt(2), container->childItems().at(2)); QCOMPARE(countSpy.count(), 1); countSpy.clear(); QCOMPARE(addedSpy.count(), 1); QCOMPARE(addedSpy.at(0).at(0).toInt(), 2); QCOMPARE(addedSpy.at(0).at(1).value<QDeclarativeItem*>(), container->childItems().at(2)); addedSpy.clear(); // insert in middle testModel.insertItem(2, "three", "3"); QCOMPARE(repeater->itemAt(2), container->childItems().at(2)); QCOMPARE(countSpy.count(), 1); countSpy.clear(); QCOMPARE(addedSpy.count(), 1); QCOMPARE(addedSpy.at(0).at(0).toInt(), 2); QCOMPARE(addedSpy.at(0).at(1).value<QDeclarativeItem*>(), container->childItems().at(2)); addedSpy.clear(); delete testObject; delete canvas; } void tst_QDeclarativeRepeater::dataModel_removing() { QDeclarativeView *canvas = createView(); QDeclarativeContext *ctxt = canvas->rootContext(); TestObject *testObject = new TestObject; ctxt->setContextProperty("testObject", testObject); TestModel testModel; testModel.addItem("one", "1"); testModel.addItem("two", "2"); testModel.addItem("three", "3"); testModel.addItem("four", "4"); testModel.addItem("five", "5"); ctxt->setContextProperty("testData", &testModel); canvas->setSource(testFileUrl("repeater2.qml")); qApp->processEvents(); QDeclarativeRepeater *repeater = findItem<QDeclarativeRepeater>(canvas->rootObject(), "repeater"); QVERIFY(repeater != 0); QDeclarativeItem *container = findItem<QDeclarativeItem>(canvas->rootObject(), "container"); QVERIFY(container != 0); QCOMPARE(container->childItems().count(), repeater->count()+1); QSignalSpy countSpy(repeater, SIGNAL(countChanged())); QSignalSpy removedSpy(repeater, SIGNAL(itemRemoved(int,QDeclarativeItem*))); // remove at start QDeclarativeItem *item = repeater->itemAt(0); QCOMPARE(item, container->childItems().at(0)); testModel.removeItem(0); QVERIFY(repeater->itemAt(0) != item); QCOMPARE(countSpy.count(), 1); countSpy.clear(); QCOMPARE(removedSpy.count(), 1); QCOMPARE(removedSpy.at(0).at(0).toInt(), 0); QCOMPARE(removedSpy.at(0).at(1).value<QDeclarativeItem*>(), item); removedSpy.clear(); // remove at end int lastIndex = testModel.count()-1; item = repeater->itemAt(lastIndex); QCOMPARE(item, container->childItems().at(lastIndex)); testModel.removeItem(lastIndex); QVERIFY(repeater->itemAt(lastIndex) != item); QCOMPARE(countSpy.count(), 1); countSpy.clear(); QCOMPARE(removedSpy.count(), 1); QCOMPARE(removedSpy.at(0).at(0).toInt(), lastIndex); QCOMPARE(removedSpy.at(0).at(1).value<QDeclarativeItem*>(), item); removedSpy.clear(); // remove from middle item = repeater->itemAt(1); QCOMPARE(item, container->childItems().at(1)); testModel.removeItem(1); QVERIFY(repeater->itemAt(lastIndex) != item); QCOMPARE(countSpy.count(), 1); countSpy.clear(); QCOMPARE(removedSpy.count(), 1); QCOMPARE(removedSpy.at(0).at(0).toInt(), 1); QCOMPARE(removedSpy.at(0).at(1).value<QDeclarativeItem*>(), item); removedSpy.clear(); delete testObject; delete canvas; } void tst_QDeclarativeRepeater::dataModel_changes() { QDeclarativeView *canvas = createView(); QDeclarativeContext *ctxt = canvas->rootContext(); TestObject *testObject = new TestObject; ctxt->setContextProperty("testObject", testObject); TestModel testModel; testModel.addItem("one", "1"); testModel.addItem("two", "2"); testModel.addItem("three", "3"); ctxt->setContextProperty("testData", &testModel); canvas->setSource(testFileUrl("repeater2.qml")); qApp->processEvents(); QDeclarativeRepeater *repeater = findItem<QDeclarativeRepeater>(canvas->rootObject(), "repeater"); QVERIFY(repeater != 0); QDeclarativeItem *container = findItem<QDeclarativeItem>(canvas->rootObject(), "container"); QVERIFY(container != 0); QCOMPARE(container->childItems().count(), repeater->count()+1); // Check that model changes are propagated QDeclarativeText *text = findItem<QDeclarativeText>(canvas->rootObject(), "myName", 1); QVERIFY(text); QCOMPARE(text->text(), QString("two")); testModel.modifyItem(1, "Item two", "_2"); text = findItem<QDeclarativeText>(canvas->rootObject(), "myName", 1); QVERIFY(text); QCOMPARE(text->text(), QString("Item two")); text = findItem<QDeclarativeText>(canvas->rootObject(), "myNumber", 1); QVERIFY(text); QCOMPARE(text->text(), QString("_2")); delete testObject; delete canvas; } void tst_QDeclarativeRepeater::itemModel() { QDeclarativeView *canvas = createView(); QDeclarativeContext *ctxt = canvas->rootContext(); TestObject *testObject = new TestObject; ctxt->setContextProperty("testObject", testObject); canvas->setSource(testFileUrl("itemlist.qml")); qApp->processEvents(); QDeclarativeRepeater *repeater = findItem<QDeclarativeRepeater>(canvas->rootObject(), "repeater"); QVERIFY(repeater != 0); QDeclarativeItem *container = findItem<QDeclarativeItem>(canvas->rootObject(), "container"); QVERIFY(container != 0); QCOMPARE(container->childItems().count(), 1); testObject->setUseModel(true); QMetaObject::invokeMethod(canvas->rootObject(), "checkProperties"); QVERIFY(testObject->error() == false); QCOMPARE(container->childItems().count(), 4); QVERIFY(qobject_cast<QObject*>(container->childItems().at(0))->objectName() == "item1"); QVERIFY(qobject_cast<QObject*>(container->childItems().at(1))->objectName() == "item2"); QVERIFY(qobject_cast<QObject*>(container->childItems().at(2))->objectName() == "item3"); QVERIFY(container->childItems().at(3) == repeater); QMetaObject::invokeMethod(canvas->rootObject(), "switchModel"); QCOMPARE(container->childItems().count(), 3); QVERIFY(qobject_cast<QObject*>(container->childItems().at(0))->objectName() == "item4"); QVERIFY(qobject_cast<QObject*>(container->childItems().at(1))->objectName() == "item5"); QVERIFY(container->childItems().at(2) == repeater); testObject->setUseModel(false); QCOMPARE(container->childItems().count(), 1); delete testObject; delete canvas; } void tst_QDeclarativeRepeater::resetModel() { QDeclarativeView *canvas = createView(); QStringList dataA; for (int i=0; i<10; i++) dataA << QString::number(i); QDeclarativeContext *ctxt = canvas->rootContext(); ctxt->setContextProperty("testData", dataA); canvas->setSource(testFileUrl("repeater1.qml")); qApp->processEvents(); QDeclarativeRepeater *repeater = findItem<QDeclarativeRepeater>(canvas->rootObject(), "repeater"); QVERIFY(repeater != 0); QDeclarativeItem *container = findItem<QDeclarativeItem>(canvas->rootObject(), "container"); QVERIFY(container != 0); QCOMPARE(repeater->count(), dataA.count()); for (int i=0; i<repeater->count(); i++) QCOMPARE(repeater->itemAt(i), container->childItems().at(i+1)); // +1 to skip first Text object QSignalSpy modelChangedSpy(repeater, SIGNAL(modelChanged())); QSignalSpy countSpy(repeater, SIGNAL(countChanged())); QSignalSpy addedSpy(repeater, SIGNAL(itemAdded(int,QDeclarativeItem*))); QSignalSpy removedSpy(repeater, SIGNAL(itemRemoved(int,QDeclarativeItem*))); QStringList dataB; for (int i=0; i<20; i++) dataB << QString::number(i); // reset context property ctxt->setContextProperty("testData", dataB); QCOMPARE(repeater->count(), dataB.count()); QCOMPARE(modelChangedSpy.count(), 1); QCOMPARE(countSpy.count(), 1); QCOMPARE(removedSpy.count(), dataA.count()); QCOMPARE(addedSpy.count(), dataB.count()); for (int i=0; i<dataB.count(); i++) { QCOMPARE(addedSpy.at(i).at(0).toInt(), i); QCOMPARE(addedSpy.at(i).at(1).value<QDeclarativeItem*>(), repeater->itemAt(i)); } modelChangedSpy.clear(); countSpy.clear(); removedSpy.clear(); addedSpy.clear(); // reset via setModel() repeater->setModel(dataA); QCOMPARE(repeater->count(), dataA.count()); QCOMPARE(modelChangedSpy.count(), 1); QCOMPARE(countSpy.count(), 1); QCOMPARE(removedSpy.count(), dataB.count()); QCOMPARE(addedSpy.count(), dataA.count()); for (int i=0; i<dataA.count(); i++) { QCOMPARE(addedSpy.at(i).at(0).toInt(), i); QCOMPARE(addedSpy.at(i).at(1).value<QDeclarativeItem*>(), repeater->itemAt(i)); } delete canvas; } // QTBUG-17156 void tst_QDeclarativeRepeater::modelChanged() { QDeclarativeEngine engine; QDeclarativeComponent component(&engine, testFileUrl("modelChanged.qml")); QDeclarativeItem *rootObject = qobject_cast<QDeclarativeItem*>(component.create()); QVERIFY(rootObject); QDeclarativeRepeater *repeater = findItem<QDeclarativeRepeater>(rootObject, "repeater"); QVERIFY(repeater); repeater->setModel(4); QCOMPARE(repeater->count(), 4); QCOMPARE(repeater->property("itemsCount").toInt(), 4); QCOMPARE(repeater->property("itemsFound").toList().count(), 4); repeater->setModel(10); QCOMPARE(repeater->count(), 10); QCOMPARE(repeater->property("itemsCount").toInt(), 10); QCOMPARE(repeater->property("itemsFound").toList().count(), 10); delete rootObject; } void tst_QDeclarativeRepeater::properties() { QDeclarativeEngine engine; QDeclarativeComponent component(&engine, testFileUrl("properties.qml")); QDeclarativeItem *rootObject = qobject_cast<QDeclarativeItem*>(component.create()); QVERIFY(rootObject); QDeclarativeRepeater *repeater = findItem<QDeclarativeRepeater>(rootObject, "repeater"); QVERIFY(repeater); QSignalSpy modelSpy(repeater, SIGNAL(modelChanged())); repeater->setModel(3); QCOMPARE(modelSpy.count(),1); repeater->setModel(3); QCOMPARE(modelSpy.count(),1); QSignalSpy delegateSpy(repeater, SIGNAL(delegateChanged())); QDeclarativeComponent rectComponent(&engine); rectComponent.setData("import QtQuick 1.0; Rectangle {}", QUrl::fromLocalFile("")); repeater->setDelegate(&rectComponent); QCOMPARE(delegateSpy.count(),1); repeater->setDelegate(&rectComponent); QCOMPARE(delegateSpy.count(),1); delete rootObject; } void tst_QDeclarativeRepeater::testQtQuick11Attributes() { QFETCH(QString, code); QFETCH(QString, warning); QFETCH(QString, error); QDeclarativeEngine engine; QObject *obj; QDeclarativeComponent invalid(&engine); invalid.setData("import QtQuick 1.0; Repeater { " + code.toUtf8() + " }", QUrl("")); QTest::ignoreMessage(QtWarningMsg, warning.toUtf8()); obj = invalid.create(); QCOMPARE(invalid.errorString(), error); delete obj; QDeclarativeComponent valid(&engine); valid.setData("import QtQuick 1.1; Repeater { " + code.toUtf8() + " }", QUrl("")); obj = valid.create(); QVERIFY(obj); QVERIFY(valid.errorString().isEmpty()); delete obj; } void tst_QDeclarativeRepeater::testQtQuick11Attributes_data() { QTest::addColumn<QString>("code"); QTest::addColumn<QString>("warning"); QTest::addColumn<QString>("error"); QTest::newRow("itemAdded") << "onItemAdded: count" << "QDeclarativeComponent: Component is not ready" << ":1 \"Repeater.onItemAdded\" is not available in QtQuick 1.0.\n"; QTest::newRow("itemRemoved") << "onItemRemoved: count" << "QDeclarativeComponent: Component is not ready" << ":1 \"Repeater.onItemRemoved\" is not available in QtQuick 1.0.\n"; QTest::newRow("itemAt") << "Component.onCompleted: itemAt(0)" << "<Unknown File>:1: ReferenceError: Can't find variable: itemAt" << ""; } QDeclarativeView *tst_QDeclarativeRepeater::createView() { QDeclarativeView *canvas = new QDeclarativeView(0); canvas->setFixedSize(240,320); return canvas; } template<typename T> T *tst_QDeclarativeRepeater::findItem(QGraphicsObject *parent, const QString &objectName, int index) { const QMetaObject &mo = T::staticMetaObject; //qDebug() << parent->childItems().count() << "children"; for (int i = 0; i < parent->childItems().count(); ++i) { QDeclarativeItem *item = qobject_cast<QDeclarativeItem*>(parent->childItems().at(i)); if(!item) continue; //qDebug() << "try" << item; if (mo.cast(item) && (objectName.isEmpty() || item->objectName() == objectName)) { if (index != -1) { QDeclarativeExpression e(qmlContext(item), item, "index"); if (e.evaluate().toInt() == index) return static_cast<T*>(item); } else { return static_cast<T*>(item); } } item = findItem<T>(item, objectName, index); if (item) return static_cast<T*>(item); } return 0; } template<typename T> T *tst_QDeclarativeRepeater::findItem(QGraphicsObject *parent, const QString &objectName) { const QMetaObject &mo = T::staticMetaObject; if (mo.cast(parent) && (objectName.isEmpty() || parent->objectName() == objectName)) return static_cast<T*>(parent); for (int i = 0; i < parent->childItems().count(); ++i) { QDeclarativeItem *child = qobject_cast<QDeclarativeItem*>(parent->childItems().at(i)); if (!child) continue; QDeclarativeItem *item = findItem<T>(child, objectName); if (item) return static_cast<T*>(item); } return 0; } QTEST_MAIN(tst_QDeclarativeRepeater) #include "tst_qdeclarativerepeater.moc"
Distrotech/qtquick1
tests/auto/declarative/qdeclarativerepeater/tst_qdeclarativerepeater.cpp
C++
lgpl-3.0
25,035
#ifndef COMBINE_HPP_1441632935__ #define COMBINE_HPP_1441632935__ #include <vector> #include "framework/component/unit.hpp" namespace strangeio { namespace spec { class combine : public strangeio::component::unit { public: combine(std::string model, std::string label); virtual void feed_line(strangeio::memory::cache_ptr samples, int line) = 0; virtual void sync_line(strangeio::component::sync_profile& profile, strangeio::component::sync_flag flags, unsigned int line); #if DEVBUILD bool db_input_active(unsigned int id) { return input_active(id); }; #endif protected: virtual strangeio::component::cycle_state cycle() = 0; virtual strangeio::component::cycle_state init() = 0; void init_input_states(); bool input_active(unsigned int id); bool all_inactive(); bool all_active(); private: std::vector<bool> m_input_state; }; } } #endif
carrotsrc/StrangeIO
framework/include/framework/spec/combine.hpp
C++
lgpl-3.0
874
--- wrapper_template: "cube/study/_markdown.html" markdown_includes: nav: "cube/study/_navigation.md" context: title: "Installation and Package Management" description: "Installation and Package Management" auto_paginate: True --- In Ubuntu, there are two primary means of installing, upgrading, and removing software: 1. [Debian packages](https://packages.debian.org) are binary packages using a management framework that Ubuntu inherits from the [Debian Project](https://www.debian.org/), a free GNU/Linux operating system distribution. 2. [Snaps](https://snapcraft.io/) are a packaging format that is specific to Ubuntu. In this section, we will explore both package types, starting with the Debian package format. ## What is a Debian Package? A Debian package is a `.deb` file that contains the packaged application, and a machine-readable set of instructions to install it. A `.deb` file contains two compressed `tar` archives: * One that contains the control information (the installation instruction set). * One that contains the data to be installed. The two archives are wrapped in *another* archive, using the `ar` archive format. As such, you can unpack the contents of any `.deb` file with the `ar` utility. Consider the following example (from the [`cmatrix`](https://packages.ubuntu.com/bionic/cmatrix) package): ``` $ ar xv cmatrix_2.0-2_amd64.deb x - debian-binary x - control.tar.xz x - data.tar.xz ``` The control information is used by the `dpkg` utility (and its higher-level companion, `apt`) to manage the package. The information in the control file describes the source package, supported architecture, the maintainer of the package, and the dependencies needed to install the package, among other critical information. It can look like this: ``` $ cat control Package: cmatrix Version: 2.0-2 Architecture: amd64 Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com> Original-Maintainer: Boyuan Yang <byang@debian.org> Installed-Size: 51 Depends: libc6 (>= 2.4), libncurses6 (>= 6), libtinfo6 (>= 6) Recommends: kbd Suggests: cmatrix-xfont Section: misc Priority: optional Homepage: https://github.com/abishekvashok/cmatrix Description: simulates the display from "The Matrix" Screen saver for the terminal based in the movie "The Matrix". It works in terminals of all dimensions and have the following features: * Support terminal resize. * Screen saver mode: any key closes it. * Selectable color. * Change text scroll rate. ``` Unless you are a developer looking to create your own Debian packages (for either Debian, or Ubuntu), chances are that you will never create or even modify a **control** file. But it is important to understand that this file contains everything that the package needs to tell the system about which other packages it depends on (`Depends:`), which it recommends you install alongside it (`Recommends:`), what system architecture it depends on (`Architecture:`), and so on. Most of the time, you will not even need to *look* at the **control** file directly, because there are plenty of low-level and high-level package management tools that parse and index the package’s information, so that you can query and search it. ## What is a Snap Package? A snap package is a `.snap` file. Unlike a `.deb` package, which is a bunch of files in an archive, a `.snap` is a containerized software package with bundled dependencies for all major Linux systems. Rather than having to work with one `.deb` *per* system architecture, we have one `.snap` for *all* system architectures. The `.snap` file format, and its deployment tool `snappy`, were developed by Canonical. The `.snap` file is a compressed file system, based on `Squashfs`, as shown in the following example. ``` $ snap download certbot Fetching snap "certbot" Fetching assertions for "certbot" Install the snap with: snap ack certbot_652.assert snap install certbot_652.snap ubuntu@deploy:~$ file certbot_652.snap certbot_652.snap: Squashfs filesystem, little endian, version 1024.0, compressed, 4026208179854508032 bytes, -1978007552 inodes, blocksize: 512 bytes, created: Mon Oct 26 23:16:47 1992 ``` When you install a `.snap` file to a system, the `snappy` daemon mounts its Squashfs filesystem, read-only, to `/snap/<snap name>/<revision>/`. ``` $ df -h | grep -i certbot /dev/loop4 48M 48M 0 100% /snap/certbot/652 ``` The snap system then interprets the metadata associated with the snap in order to set up a secure sandbox or container for the application.
canonical-websites/www.ubuntu.com
templates/cube/study/packages/part-1.md
Markdown
lgpl-3.0
4,573
--- layout: index title: Ultrasonic Sensor scripts: [ '/static/bonescript-demo.js' ] --- {% include side_menu.html title="Demos" %} <div class="t3_content_1"><div id='connect-status'></div><div id="content_child"> <h1>Demo: Maxbotic Ultrasonic Sensor</h1> <p>The <a href="http://www.maxbotix.com/Ultrasonic_Sensors/MB1020.htm">LV-MaxSonar-EZ2 High Performance Sonar Range Finder</a> provides very short to long-range detection and ranging, in an incredibly small package. The sonar detects objects from 0-254 inches and provides sonar range information from 6-inches out to 254-inches with 1-inch resolution. </p> <i>Note: Each time after the Sonar is powered up, it will calibrate during its first read cycle. The sensor uses this stored information to range a near object. It is important that objects not be close to the sensor during this calibration cycle. The best sensitivity is obtained when it is clear for fourteen inches, but good results are common when clear for at least seven inches. If an object is too bear the Sonar during the calibration cycle, the sensor may then ignore the objects at that distance. To calibrate the LV-MAX Sonar, cycle power then command a read cycle.</i><br><br> The AN pin outputs a voltage with a scaling factor of (V<sub>cc</sub>/512) per inch. Since the AIN pin has a maximum voltage capacity of 1.8V, we will set a voltage divider to account for that difference. With the voltage divider, a supply of 5V yields ~6.99mV/in. and 3.3V yields ~4.57mV/in. <br> <h2>Example <button class="dynlink" onclick="demoRun('code')">run</button> <button class="dynlink" onclick="demoRestore('code')">restore</button> </h2> <pre id="code" class="use-editor" style="height:310px;"> var b = require('bonescript'); var analogVoltage = 0; /* Check the sensor values every 2 seconds*/ setInterval(read, 2000); function read(){ b.analogRead('P9_40', printStatus); } function printStatus(x) { var distanceInches; analogVoltage = x.value*1.8; // ADC Value converted to voltage console.log('x.value = ' + analogVoltage); distanceInches = analogVoltage / 0.00699; console.log("There is an object " + parseFloat(distanceInches).toFixed(3) + " inches away."); } </pre> <div readonly id='console-output' style="height:100px;"></div> <br></br> <img align="right" width="60%" src="{{site.baseurl}}/static/images/VD%20Ultrasonic%20Sensor.PNG"/> <br></br> <h2>Build and execute instructions</h2> <ul> <li>Connect the "GND" pin from the sensor to P9_1 of the board</li> <li>Connect the "+5" pin from the sensor to P9_3 of the board</li> <li>Connect the 1.2kohm resistor to the AN pin of the supersonic sensor.</li> <li>Connect the 3k ohm resistor in series with the 1.2k ohm resistor and tie the bottom to ground, as shown in the diagram.</li> <li>Connect P9_40 of BeagleBone in series with the 3k ohm and 1.k ohm resistor.</li> <li>Click "Run" on the code and it will output the distance, in inches, that the sensor is detecting... updating every 5 seconds</li> <li>Move the sensor nearer to or farther from an object to see the change in distance</li> </ul> <h2>See also</h2> <h3>Related functions</h3> <ul> <li><a href="{{site.baseurl}}/Support/BoneScript/#require">require</a></li> <li><a href="{{site.baseurl}}/Support/BoneScript/analogRead/">analogRead</a></li> <li><a href="http://beagleboard.org/Support/BoneScript/#timers">setInterval</a></li> </ul> </div> <div id="list"> </div> <br/> <div id="createtime">Last updated by juan_cortez on Fri Aug 16 2013 11:14:43 GMT-0500 (CDT).</div> </div>
maaydogmus/bone101
Support/BoneScript/Ultrasonic_Sensor/index.html
HTML
lgpl-3.0
3,651
/* * Copyright (C) 2015 Raquel Pau and Albert Coroleu. * * Walkmod 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. * * Walkmod 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 Walkmod. If * not, see <http://www.gnu.org/licenses/>. */ package org.walkmod.javalang.compiler.symbols; import java.util.List; import org.walkmod.javalang.ast.Node; public interface SymbolFactory { public Symbol<?> create(String symbolName, ReferenceType referenceType, SymbolType symbolType, Node location); public Symbol<?> create(String symbolName, ReferenceType referenceType, SymbolType symbolType, Node location, SymbolAction action); public Symbol<?> create(String symbolName, ReferenceType referenceType, SymbolType symbolType, Node location, List<SymbolAction> actions); }
rpau/javalang-compiler
src/main/java/org/walkmod/javalang/compiler/symbols/SymbolFactory.java
Java
lgpl-3.0
1,277
Ext.ns('Docs'); Docs.ApiViewport = Ext.extend(Ext.Viewport, { constructor : function(cfg) { cfg = Ext.apply(cfg ||{}, { layout:'border', items : this.buildItems() }); this.constructor.superclass.constructor.call(this,cfg); }, buildItems : function() { return [ //North { cls: 'docs-header', height: 36, region:'north', xtype:'box', el:'header', border:false, margins: '0 0 5 0' }, //West { xtype : 'apitreepanel', itemId : 'apiTreePanel', region:'west', split:true, width: 280, minSize: 175, maxSize: 500, margins:'0 0 5 5', cmargins:'0 0 0 0', collapsible: true, collapseMode:'mini', listeners : { scope : this, click : this.onApiTreePanelClick, afterrender : function(treePanel) { treePanel.expandPath('/root/apidocs'); } } }, //Central { xtype : 'apitabpanel', itemId : 'apiTabPanel', id:'doc-body', region:'center', margins:'0 5 5 0', listeners : { scope : this, tabchange : this.onApiTabPanelTabChange, render : { delay : 250, fn : this.onAfterRenderLoadClass } } } ]; }, getApiTabPanel : function() { return this.getComponent('apiTabPanel'); }, getApiTreePanel : function() { return this.getComponent('apiTreePanel'); }, onAfterRenderLoadClass : function() { var page = window.location.href.split('?')[1]; if(page){ var ps = Ext.urlDecode(page), cls = ps['class']; this.getApiTabPanel().loadClass('output/' + cls + '.html', cls, ps.member); } this.doLayout(); }, onApiTreePanelClick : function(node, evtObj) { if(node.isLeaf()){ evtObj.stopEvent(); this.getApiTabPanel().loadClass(node.attributes.href, node.id); } }, onApiTabPanelTabChange : function(tp, tab){ this.getApiTreePanel().selectClass(tab.cclass); } });
piseth/neos-package
Build/Resources/Java/ext-doc/template/ext/resources/Docs/ApiViewport.js
JavaScript
lgpl-3.0
2,639
package com.yidumen.cms.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "wechat_message_link") public class LinkMessage extends Message { @Column(name = "title", length = 50) private String title; @Column(name = "description", length = 100) private String description; @Column(name = "link_url", length = 100) private String url; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
yidumen/cms-platform
src/main/java/com/yidumen/cms/entity/LinkMessage.java
Java
lgpl-3.0
871
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System.Windows; namespace Microsoft.Practices.Prism.Composition.Tests.Mocks { class MockDependencyObject : DependencyObject { } class MockFrameworkElement : FrameworkElement { } }
SiddharthMishraPersonal/InterviewPreperation
WPF/Installers/Prism/PrismLibrary/Desktop/Prism.Tests/Mocks/MockDependencyObject.cs
C#
unlicense
334
<?php /* * $Id: Builder.php 6401 2009-09-24 16:12:04Z guilhermeblanco $ * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.phpdoctrine.org>. */ /** * Doctrine_Import_Builder * * Import builder is responsible of building Doctrine_Record classes * based on a database schema. * * @package Doctrine * @subpackage Import * @link www.phpdoctrine.org * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @since 1.0 * @version $Revision: 6401 $ * @author Konsta Vesterinen <kvesteri@cc.hut.fi> * @author Jukka Hassinen <Jukka.Hassinen@BrainAlliance.com> * @author Nicolas Bérard-Nault <nicobn@php.net> * @author Jonathan H. Wage <jwage@mac.com> */ class Doctrine_Import_Builder extends Doctrine_Builder { /** * _path * * the path where imported files are being generated * * @var string $_path */ protected $_path = ''; /** * _packagesPrefix * * @var string */ protected $_packagesPrefix = 'Package'; /** * _packagesPath * * @var string */ protected $_packagesPath = ''; /** * _packagesFolderName * * @var string */ protected $_packagesFolderName = 'packages'; /** * _suffix * * File suffix to use when writing class definitions * * @var string $suffix */ protected $_suffix = '.php'; /** * _generateBaseClasses * * Bool true/false for whether or not to generate base classes * * @var boolean $generateBaseClasses */ protected $_generateBaseClasses = true; /** * _generateTableClasses * * Bool true/false for whether or not to generate child table classes * * @var boolean $generateTableClasses */ protected $_generateTableClasses = false; /** * _base * * Prefix to use for generated base classes * * @var string */ protected $_baseClassPrefix = 'Base'; /** * _baseClassesDirectory * * Directory to put the generate base classes in * * @var string $suffix */ protected $_baseClassesDirectory = 'generated'; /** * _baseClassName * * @var string */ protected $_baseClassName = 'Doctrine_Record'; /** * Prefix to all generated classes * * @var string */ protected $_classPrefix = null; /** * The package name to use for the generated php docs * * @var string */ protected $_phpDocPackage = '##PACKAGE##'; /** * The subpackage name to use for the generated php docs * * @var string */ protected $_phpDocSubpackage = '##SUBPACKAGE##'; /** * Full name of the author to use for the generated php docs * * @var string */ protected $_phpDocName = '##NAME##'; /** * Email of the author to use for the generated php docs * * @var string */ protected $_phpDocEmail = '##EMAIL##'; /** * _tpl * * Class template used for writing classes * * @var $_tpl */ protected static $_tpl; /** * __construct * * @return void */ public function __construct() { $this->loadTemplate(); } /** * setTargetPath * * @param string path the path where imported files are being generated * @return */ public function setTargetPath($path) { if ($path) { if ( ! $this->_packagesPath) { $this->setPackagesPath($path . DIRECTORY_SEPARATOR . $this->_packagesFolderName); } $this->_path = $path; } } /** * setPackagePath * * @param string $packagesPrefix * @return void */ public function setPackagesPrefix($packagesPrefix) { $this->_packagesPrefix = $packagesPrefix; } /** * setPackagesPath * * @param string $packagesPath * @return void */ public function setPackagesPath($packagesPath) { if ($packagesPath) { $this->_packagesPath = $packagesPath; } } /** * generateBaseClasses * * Specify whether or not to generate classes which extend from generated base classes * * @param boolean $bool * @return boolean $bool */ public function generateBaseClasses($bool = null) { if ($bool !== null) { $this->_generateBaseClasses = $bool; } return $this->_generateBaseClasses; } /** * generateTableClasses * * Specify whether or not to generate children table classes * * @param boolean $bool * @return boolean $bool */ public function generateTableClasses($bool = null) { if ($bool !== null) { $this->_generateTableClasses = $bool; } return $this->_generateTableClasses; } /** * setBaseClassPrefix * * @param string $prefix * @return void */ public function setBaseClassPrefix($prefix) { $this->_baseClassPrefix = $prefix; } /** * getBaseClassPrefix * * @return void */ public function getBaseClassPrefix() { return $this->_baseClassPrefix; } /** * setBaseClassesDirectory * * @return void */ public function setBaseClassesDirectory($baseClassesDirectory) { $this->_baseClassesDirectory = $baseClassesDirectory; } /** * setBaseClassName * * @package default */ public function setBaseClassName($className) { $this->_baseClassName = $className; } /** * setSuffix * * @param string $suffix * @return void */ public function setSuffix($suffix) { $this->_suffix = $suffix; } /** * getTargetPath * * @return string the path where imported files are being generated */ public function getTargetPath() { return $this->_path; } /** * setOptions * * @param string $options * @return void */ public function setOptions($options) { if ( ! empty($options)) { foreach ($options as $key => $value) { $this->setOption($key, $value); } } } /** * setOption * * @param string $key * @param string $value * @return void */ public function setOption($key, $value) { $name = 'set' . Doctrine_Inflector::classify($key); if (method_exists($this, $name)) { $this->$name($value); } else { $key = '_' . $key; $this->$key = $value; } } /** * loadTemplate * * Loads the class template used for generating classes * * @return void */ public function loadTemplate() { if (isset(self::$_tpl)) { return; } self::$_tpl = '/**' . '%s' . PHP_EOL . ' */' . PHP_EOL . '%sclass %s extends %s' . PHP_EOL . '{' . '%s' . PHP_EOL . '%s' . PHP_EOL . '}'; } /* * Build the table definition of a Doctrine_Record object * * @param string $table * @param array $tableColumns */ public function buildTableDefinition(array $definition) { if (isset($definition['inheritance']['type']) && ($definition['inheritance']['type'] == 'simple' || $definition['inheritance']['type'] == 'column_aggregation')) { return; } $ret = array(); $i = 0; if (isset($definition['inheritance']['type']) && $definition['inheritance']['type'] == 'concrete') { $ret[$i] = " parent::setTableDefinition();"; $i++; } if (isset($definition['tableName']) && !empty($definition['tableName'])) { $ret[$i] = " ".'$this->setTableName(\''. $definition['tableName'].'\');'; $i++; } if (isset($definition['columns']) && is_array($definition['columns']) && !empty($definition['columns'])) { $ret[$i] = $this->buildColumns($definition['columns']); $i++; } if (isset($definition['indexes']) && is_array($definition['indexes']) && !empty($definition['indexes'])) { $ret[$i] = $this->buildIndexes($definition['indexes']); $i++; } if (isset($definition['attributes']) && is_array($definition['attributes']) && !empty($definition['attributes'])) { $ret[$i] = $this->buildAttributes($definition['attributes']); $i++; } if (isset($definition['options']) && is_array($definition['options']) && !empty($definition['options'])) { $ret[$i] = $this->buildOptions($definition['options']); $i++; } if (isset($definition['checks']) && is_array($definition['checks']) && !empty($definition['checks'])) { $ret[$i] = $this->buildChecks($definition['checks']); $i++; } if (isset($definition['inheritance']['subclasses']) && ! empty($definition['inheritance']['subclasses'])) { $ret[$i] = " ".'$this->setSubClasses('. $this->varExport($definition['inheritance']['subclasses']).');'; $i++; } $code = implode(PHP_EOL, $ret); $code = trim($code); return PHP_EOL . " public function setTableDefinition()" . PHP_EOL . ' {' . PHP_EOL . ' ' . $code . PHP_EOL . ' }'; } /** * buildSetUp * * @param array $options * @param array $columns * @param array $relations * @return string */ public function buildSetUp(array $definition) { $ret = array(); $i = 0; if (isset($definition['relations']) && is_array($definition['relations']) && ! empty($definition['relations'])) { foreach ($definition['relations'] as $name => $relation) { $class = isset($relation['class']) ? $relation['class']:$name; $alias = (isset($relation['alias']) && $relation['alias'] !== $relation['class']) ? ' as ' . $relation['alias'] : ''; if ( ! isset($relation['type'])) { $relation['type'] = Doctrine_Relation::ONE; } if ($relation['type'] === Doctrine_Relation::ONE) { $ret[$i] = " ".'$this->hasOne(\'' . $class . $alias . '\''; } else { $ret[$i] = " ".'$this->hasMany(\'' . $class . $alias . '\''; } $a = array(); if (isset($relation['refClass'])) { $a[] = '\'refClass\' => ' . $this->varExport($relation['refClass']); } if (isset($relation['refClassRelationAlias'])) { $a[] = '\'refClassRelationAlias\' => ' . $this->varExport($relation['refClassRelationAlias']); } if (isset($relation['deferred']) && $relation['deferred']) { $a[] = '\'default\' => ' . $this->varExport($relation['deferred']); } if (isset($relation['local']) && $relation['local']) { $a[] = '\'local\' => ' . $this->varExport($relation['local']); } if (isset($relation['foreign']) && $relation['foreign']) { $a[] = '\'foreign\' => ' . $this->varExport($relation['foreign']); } if (isset($relation['onDelete']) && $relation['onDelete']) { $a[] = '\'onDelete\' => ' . $this->varExport($relation['onDelete']); } if (isset($relation['onUpdate']) && $relation['onUpdate']) { $a[] = '\'onUpdate\' => ' . $this->varExport($relation['onUpdate']); } if (isset($relation['cascade']) && $relation['cascade']) { $a[] = '\'cascade\' => ' . $this->varExport($relation['cascade']); } if (isset($relation['equal']) && $relation['equal']) { $a[] = '\'equal\' => ' . $this->varExport($relation['equal']); } if (isset($relation['owningSide']) && $relation['owningSide']) { $a[] = '\'owningSide\' => ' . $this->varExport($relation['owningSide']); } if ( ! empty($a)) { $ret[$i] .= ', ' . 'array(' . PHP_EOL . str_repeat(' ', 13); $length = strlen($ret[$i]); $ret[$i] .= implode(',' . PHP_EOL . str_repeat(' ', 13), $a) . ')'; } $ret[$i] .= ');'.PHP_EOL; $i++; } } if (isset($definition['actAs']) && is_array($definition['actAs']) && !empty($definition['actAs'])) { $ret[$i] = $this->buildActAs($definition['actAs']); $i++; } if (isset($definition['listeners']) && is_array($definition['listeners']) && !empty($definition['listeners'])) { $ret[$i] = $this->buildListeners($definition['listeners']); $i++; } $code = implode(PHP_EOL, $ret); $code = trim($code); // If the body of the function has contents then we need to if ($code) { // If the body of the function has contents and we are using inheritance // then we need call the parent::setUp() before the body of the function // Class table inheritance is the only one we shouldn't call parent::setUp() for if ( ! isset($definition['inheritance']['type']) || $definition['inheritance']['type'] != 'class_table') { $code = "parent::setUp();" . PHP_EOL . ' ' . $code; } } // If we have some code for the function then lets define it and return it if ($code) { return ' public function setUp()' . PHP_EOL . ' {' . PHP_EOL . ' ' . $code . PHP_EOL . ' }'; } } /** * Build php code for record checks * * @param array $checks * @return string $build */ public function buildChecks($checks) { $build = ''; foreach ($checks as $check) { $build .= " \$this->check('" . $check . "');" . PHP_EOL; } return $build; } /** * buildColumns * * @param string $array * @return void */ public function buildColumns(array $columns) { $build = null; foreach ($columns as $name => $column) { $columnName = isset($column['name']) ? $column['name']:$name; $build .= " ".'$this->hasColumn(\'' . $columnName . '\', \'' . $column['type'] . '\''; if ($column['length']) { $build .= ', ' . $column['length']; } else { $build .= ', null'; } $options = $column; // Remove name, alltypes, ntype. They are not needed in options array unset($options['name']); unset($options['alltypes']); unset($options['ntype']); // Remove notnull => true if the column is primary // Primary columns are implied to be notnull in Doctrine if (isset($options['primary']) && $options['primary'] == true && (isset($options['notnull']) && $options['notnull'] == true)) { unset($options['notnull']); } // Remove default if the value is 0 and the column is a primary key // Doctrine defaults to 0 if it is a primary key if (isset($options['primary']) && $options['primary'] == true && (isset($options['default']) && $options['default'] == 0)) { unset($options['default']); } // Remove null and empty array values foreach ($options as $key => $value) { if (is_null($value) || (is_array($value) && empty($value))) { unset($options[$key]); } } if (is_array($options) && !empty($options)) { $build .= ', ' . $this->varExport($options); } $build .= ');' . PHP_EOL; } return $build; } /* * Build the accessors * * @param string $table * @param array $columns */ public function buildAccessors(array $definition) { $accessors = array(); foreach (array_keys($definition['columns']) as $name) { $accessors[] = $name; } foreach ($definition['relations'] as $relation) { $accessors[] = $relation['alias']; } $ret = ''; foreach ($accessors as $name) { // getters $ret .= PHP_EOL . ' public function get' . Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)) . "(\$load = true)" . PHP_EOL; $ret .= " {" . PHP_EOL; $ret .= " return \$this->get('{$name}', \$load);" . PHP_EOL; $ret .= " }" . PHP_EOL; // setters $ret .= PHP_EOL . ' public function set' . Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)) . "(\${$name}, \$load = true)" . PHP_EOL; $ret .= " {" . PHP_EOL; $ret .= " return \$this->set('{$name}', \${$name}, \$load);" . PHP_EOL; $ret .= " }" . PHP_EOL; } return $ret; } /* * Build the phpDoc for a class definition * * @param array $definition */ public function buildPhpDocs(array $definition) { $ret = array(); $ret[] = $definition['className']; $ret[] = ''; $ret[] = 'This class has been auto-generated by the Doctrine ORM Framework'; $ret[] = ''; if ((isset($definition['is_base_class']) && $definition['is_base_class']) || ! $this->generateBaseClasses()) { foreach ($definition['columns'] as $name => $column) { $name = isset($column['name']) ? $column['name']:$name; // extract column name & field name if (stripos($name, ' as ')) { if (strpos($name, ' as')) { $parts = explode(' as ', $name); } else { $parts = explode(' AS ', $name); } if (count($parts) > 1) { $fieldName = $parts[1]; } else { $fieldName = $parts[0]; } $name = $parts[0]; } else { $fieldName = $name; $name = $name; } $name = trim($name); $fieldName = trim($fieldName); $ret[] = '@property ' . $column['type'] . ' $' . $fieldName; } if (isset($definition['relations']) && ! empty($definition['relations'])) { foreach ($definition['relations'] as $relation) { $type = (isset($relation['type']) && $relation['type'] == Doctrine_Relation::MANY) ? 'Doctrine_Collection':$relation['class']; $ret[] = '@property ' . $type . ' $' . $relation['alias']; } } $ret[] = ''; } $ret[] = '@package ' . $this->_phpDocPackage; $ret[] = '@subpackage ' . $this->_phpDocSubpackage; $ret[] = '@author ' . $this->_phpDocName . ' <' . $this->_phpDocEmail . '>'; $fileName = $definition['className'] . $this->_suffix; $ret[] = '@version SVN: $Id: Builder.php 6401 2009-09-24 16:12:04Z guilhermeblanco $'; $ret = ' * ' . implode(PHP_EOL . ' * ', $ret); $ret = ' ' . trim($ret); return $ret; } /** * emit a behavior assign * * @param int $level * @param string $name * @param string $option * @return string assignation code */ private function emitAssign($level, $name, $option) { // find class matching $name $classname = $name; if (class_exists("Doctrine_Template_$name", true)) { $classname = "Doctrine_Template_$name"; } return " \$" . strtolower($name) . "$level = new $classname($option);". PHP_EOL; } /** * emit an addChild * * @param int $level * @param string $name * @param string $option * @return string addChild code */ private function emitAddChild($level, $parent, $name) { return " \$" . strtolower($parent) . ($level - 1) . "->addChild(\$" . strtolower($name) . "$level);" . PHP_EOL; } /** * emit an indented actAs * * @param int $level * @param string $name * @param string $option * @return string actAs code */ private function emitActAs($level, $name) { return " \$this->actAs(\$" . strtolower($name) . "$level);" . PHP_EOL; } /** * buildActAs: builds a complete actAs code. It supports hierarchy of plugins * @param array $actAs array of plugin definitions and options */ public function buildActAs($actAs) { $emittedActAs = array(); $build = $this->innerBuildActAs($actAs, 0, null, $emittedActAs); foreach($emittedActAs as $str) { $build .= $str; } return $build; } /** * innerBuildActAs: build a complete actAs code that handles hierarchy of plugins * * @param array $actAs array of plugin definitions and options * @param int $level current indentation level * @param string $parent name of the parent template/plugin * @param array $emittedActAs contains on output an array of actAs command to be appended to output * @return string actAs full definition */ private function innerBuildActAs($actAs, $level = 0, $parent = null, array &$emittedActAs) { // rewrite special case of actAs: [Behavior] which gave [0] => Behavior if(is_array($actAs) && isset($actAs[0]) && !is_array($actAs[0])) { $actAs = array_flip($actAs); } $build = ''; $currentParent = $parent; if(is_array($actAs)) { foreach($actAs as $template => $options) { if ($template == 'actAs') { // found another actAs $build .= $this->innerBuildActAs($options, $level + 1, $parent, $emittedActAs); } else if (is_array($options)) { // remove actAs from options $realOptions = array(); $leftActAs = array(); foreach($options as $name => $value) { if ($name != 'actAs') { $realOptions[$name] = $options[$name]; } else { $leftActAs[$name] = $options[$name]; } } $optionPHP = $this->varExport($realOptions); $build .= $this->emitAssign($level, $template, $optionPHP); if ($level == 0) { $emittedActAs[] = $this->emitActAs($level, $template); } else { $build .= $this->emitAddChild($level, $currentParent, $template); } // descend for the remainings actAs $parent = $template; $build .= $this->innerBuildActAs($leftActAs, $level, $template, $emittedActAs); } else { $build .= $this->emitAssign($level, $template, null); if ($level == 0) { $emittedActAs[] = $this->emitActAs($level, $template); } else { $build .= $this->emitAddChild($level, $currentParent, $template); } $parent = $template; } } } else { $build .= $this->emitAssign($level, $actAs, null); if ($level == 0) { $emittedActAs[] = $this->emitActAs($level, $actAs); } else { $build .= $this->emitAddChild($level, $currentParent, $actAs); } } return $build; } /** * Build php code for adding record listeners * * @param string $listeners * @return string $build */ public function buildListeners($listeners) { $build = ''; foreach($listeners as $name => $options) { if ( ! is_array($options) && $options !== null) { $name = $options; $options = null; } $useOptions = ( ! empty($options) && isset($options['useOptions']) && $options['useOptions'] == true) ? '$this->_options' : ''; $class = ( ! empty($options) && isset($options['class'])) ? $options['class'] : $name; $build .= " \$this->addListener(new " . $class . "(" . $useOptions . "), '" . $name . "');" . PHP_EOL; } return $build; } /** * buildAttributes * * @param string $array * @return void */ public function buildAttributes(array $attributes) { $build = PHP_EOL; foreach ($attributes as $key => $value) { $values = array(); if (is_bool($value)) { $values[] = $value ? 'true':'false'; } else { if ( ! is_array($value)) { $value = array($value); } foreach ($value as $attr) { $const = "Doctrine::" . strtoupper($key) . "_" . strtoupper($attr); if (defined($const)) { $values[] = $const; } else { $values[] = "'" . $attr . "'"; } } } $string = implode(' ^ ', $values); $build .= " \$this->setAttribute(Doctrine::ATTR_" . strtoupper($key) . ", " . $string . ");" . PHP_EOL; } return $build; } /** * buildTableOptions * * @param string $array * @return void */ public function buildOptions(array $options) { $build = ''; foreach ($options as $name => $value) { $build .= " \$this->option('$name', " . $this->varExport($value) . ");" . PHP_EOL; } return $build; } /** * buildIndexes * * @param string $array * @return void */ public function buildIndexes(array $indexes) { $build = ''; foreach ($indexes as $indexName => $definitions) { $build .= PHP_EOL . " \$this->index('" . $indexName . "'"; $build .= ', ' . $this->varExport($definitions); $build .= ');'; } return $build; } /** * buildDefinition * * @param array $definition * @return string */ public function buildDefinition(array $definition) { if ( ! isset($definition['className'])) { throw new Doctrine_Import_Builder_Exception('Missing class name.'); } $abstract = isset($definition['abstract']) && $definition['abstract'] === true ? 'abstract ':null; $className = $definition['className']; $extends = isset($definition['inheritance']['extends']) ? $definition['inheritance']['extends']:$this->_baseClassName; if ( ! (isset($definition['no_definition']) && $definition['no_definition'] === true)) { $tableDefinitionCode = $this->buildTableDefinition($definition); $setUpCode = $this->buildSetUp($definition); } else { $tableDefinitionCode = null; $setUpCode = null; } if ($tableDefinitionCode && $setUpCode) { $setUpCode = PHP_EOL . $setUpCode; } $docs = PHP_EOL . $this->buildPhpDocs($definition); $content = sprintf(self::$_tpl, $docs, $abstract, $className, $extends, $tableDefinitionCode, $setUpCode); return $content; } /** * buildRecord * * @param array $options * @param array $columns * @param array $relations * @param array $indexes * @param array $attributes * @param array $templates * @param array $actAs * @return void= */ public function buildRecord(array $definition) { if ( ! isset($definition['className'])) { throw new Doctrine_Import_Builder_Exception('Missing class name.'); } $definition['topLevelClassName'] = $definition['className']; if ($this->generateBaseClasses()) { $definition['is_package'] = (isset($definition['package']) && $definition['package']) ? true:false; if ($definition['is_package']) { $e = explode('.', trim($definition['package'])); $definition['package_name'] = $e[0]; $definition['package_path'] = ! empty($e) ? implode(DIRECTORY_SEPARATOR, $e):$definition['package_name']; } // Top level definition that extends from all the others $topLevel = $definition; unset($topLevel['tableName']); // If we have a package then we need to make this extend the package definition and not the base definition // The package definition will then extends the base definition $topLevel['inheritance']['extends'] = (isset($topLevel['package']) && $topLevel['package']) ? $this->_packagesPrefix . $topLevel['className']:$this->_baseClassPrefix . $topLevel['className']; $topLevel['no_definition'] = true; $topLevel['generate_once'] = true; $topLevel['is_main_class'] = true; unset($topLevel['connection']); // Package level definition that extends from the base definition if (isset($definition['package'])) { $packageLevel = $definition; $packageLevel['className'] = $topLevel['inheritance']['extends']; $packageLevel['inheritance']['extends'] = $this->_baseClassPrefix . $topLevel['className']; $packageLevel['no_definition'] = true; $packageLevel['abstract'] = true; $packageLevel['override_parent'] = true; $packageLevel['generate_once'] = true; $packageLevel['is_package_class'] = true; unset($packageLevel['connection']); $packageLevel['tableClassName'] = $packageLevel['className'] . 'Table'; $packageLevel['inheritance']['tableExtends'] = isset($definition['inheritance']['extends']) ? $definition['inheritance']['extends'] . 'Table':'Doctrine_Table'; $topLevel['tableClassName'] = $topLevel['topLevelClassName'] . 'Table'; $topLevel['inheritance']['tableExtends'] = $packageLevel['className'] . 'Table'; } else { $topLevel['tableClassName'] = $topLevel['className'] . 'Table'; $topLevel['inheritance']['tableExtends'] = isset($definition['inheritance']['extends']) ? $definition['inheritance']['extends'] . 'Table':'Doctrine_Table'; } $baseClass = $definition; $baseClass['className'] = $this->_baseClassPrefix . $baseClass['className']; $baseClass['abstract'] = true; $baseClass['override_parent'] = false; $baseClass['is_base_class'] = true; $this->writeDefinition($baseClass); if ( ! empty($packageLevel)) { $this->writeDefinition($packageLevel); } $this->writeDefinition($topLevel); } else { $this->writeDefinition($definition); } } /** * writeTableDefinition * * @return void */ public function writeTableDefinition($className, $path, $options = array()) { $content = '<?php' . PHP_EOL; $content .= sprintf(self::$_tpl, null, false, $className, isset($options['extends']) ? $options['extends']:'Doctrine_Table', null, null, null ); Doctrine_Lib::makeDirectories($path); $writePath = $path . DIRECTORY_SEPARATOR . $className . $this->_suffix; Doctrine::loadModel($className, $writePath); if ( ! file_exists($writePath)) { file_put_contents($writePath, $content); } } /** * writeDefinition * * @param array $options * @param array $columns * @param array $relations * @param array $indexes * @param array $attributes * @param array $templates * @param array $actAs * @return void */ public function writeDefinition(array $definition) { $originalClassName = $definition['className']; if ($prefix = $this->_classPrefix) { if (isset($definition['tableClassName'])) { $definition['tableClassName'] = $prefix . $definition['tableClassName']; } $definition['className'] = $prefix . $definition['className']; if (isset($definition['connectionClassName'])) { $definition['connectionClassName'] = $prefix . $definition['connectionClassName']; } $definition['topLevelClassName'] = $prefix . $definition['topLevelClassName']; if (isset($definition['inheritance']['extends'])) { $definition['inheritance']['extends'] = $prefix . $definition['inheritance']['extends']; } } $definitionCode = $this->buildDefinition($definition); if ($prefix) { $definitionCode = str_replace("this->hasOne('", "this->hasOne('$prefix", $definitionCode); $definitionCode = str_replace("this->hasMany('", "this->hasMany('$prefix", $definitionCode); $definitionCode = str_replace("'refClass' => '", "'refClass' => '$prefix", $definitionCode); } $fileName = $definition['className'] . $this->_suffix; $packagesPath = $this->_packagesPath ? $this->_packagesPath:$this->_path; // If this is a main class that either extends from Base or Package class if (isset($definition['is_main_class']) && $definition['is_main_class']) { // If is package then we need to put it in a package subfolder if (isset($definition['is_package']) && $definition['is_package']) { $writePath = $this->_path . DIRECTORY_SEPARATOR . $definition['package_name']; // Otherwise lets just put it in the root of the path } else { $writePath = $this->_path; } if ($this->generateTableClasses()) { $this->writeTableDefinition($definition['tableClassName'], $writePath, array('extends' => $definition['inheritance']['tableExtends'])); } } // If is the package class then we need to make the path to the complete package else if (isset($definition['is_package_class']) && $definition['is_package_class']) { if (isset($definition['package_custom_path'])) { $writePath = $definition['package_custom_path']; } else { $writePath = $packagesPath . DIRECTORY_SEPARATOR . $definition['package_path']; } if ($this->generateTableClasses()) { $this->writeTableDefinition($definition['tableClassName'], $writePath, array('extends' => $definition['inheritance']['tableExtends'])); } } // If it is the base class of the doctrine record definition else if (isset($definition['is_base_class']) && $definition['is_base_class']) { // If it is a part of a package then we need to put it in a package subfolder if (isset($definition['is_package']) && $definition['is_package']) { $basePath = $this->_path . DIRECTORY_SEPARATOR . $definition['package_name']; $writePath = $basePath . DIRECTORY_SEPARATOR . $this->_baseClassesDirectory; // Otherwise lets just put it in the root generated folder } else { $writePath = $this->_path . DIRECTORY_SEPARATOR . $this->_baseClassesDirectory; } } // If we have a writePath from the if else conditionals above then use it if (isset($writePath)) { Doctrine_Lib::makeDirectories($writePath); $writePath .= DIRECTORY_SEPARATOR . $fileName; // Otherwise none of the conditions were met and we aren't generating base classes } else { Doctrine_Lib::makeDirectories($this->_path); $writePath = $this->_path . DIRECTORY_SEPARATOR . $fileName; } $code = "<?php" . PHP_EOL; if (isset($definition['connection']) && $definition['connection']) { $code .= "// Connection Component Binding" . PHP_EOL; $code .= "Doctrine_Manager::getInstance()->bindComponent('" . $definition['connectionClassName'] . "', '" . $definition['connection'] . "');" . PHP_EOL; } $code .= PHP_EOL . $definitionCode; if (isset($definition['generate_once']) && $definition['generate_once'] === true) { if ( ! file_exists($writePath)) { $bytes = file_put_contents($writePath, $code); } } else { $bytes = file_put_contents($writePath, $code); } if (isset($bytes) && $bytes === false) { throw new Doctrine_Import_Builder_Exception("Couldn't write file " . $writePath); } Doctrine::loadModel($definition['className'], $writePath); } }
alpho07/NQCL_LIMS
system/database/Doctrine/Import/Builder.php
PHP
unlicense
40,930
# mdJson 2.0 writer - duration # History: # Stan Smith 2017-03-14 refactored for mdJson/mdTranslator 2.0 # Josh Bradley original script require 'jbuilder' module ADIWG module Mdtranslator module Writers module MdJson module Duration def self.build(hDuration) Jbuilder.new do |json| json.years hDuration[:years] unless hDuration[:years] == 0 json.months hDuration[:months] unless hDuration[:months] == 0 json.days hDuration[:days] unless hDuration[:days] == 0 json.hours hDuration[:hours] unless hDuration[:hours] == 0 json.minutes hDuration[:minutes] unless hDuration[:minutes] == 0 json.seconds hDuration[:seconds] unless hDuration[:seconds] == 0 end end # build end # TimePeriod end end end end
adiwg/mdTranslator
lib/adiwg/mdtranslator/writers/mdJson/sections/mdJson_duration.rb
Ruby
unlicense
961
import java.util.Scanner; /** This program shows a simple quiz with two questions. */ public class QuestionDemo { public static void main(String[] args) { Scanner in = new Scanner(System.in); ChoiceQuestion first = new ChoiceQuestion(); first.setText("What was the original name of the Java language?"); first.addChoice("*7", false); first.addChoice("Duke", false); first.addChoice("Oak", true); first.addChoice("Gosling", false); ChoiceQuestion second = new ChoiceQuestion(); second.setText("In which country was the inventor of Java born?"); second.addChoice("Australia", false); second.addChoice("Canada", true); second.addChoice("Denmark", false); second.addChoice("United States", false); int score = 0; score = score + presentQuestion(first, in); score = score + presentQuestion(second, in); System.out.println("Your score: " + score); } /** Presents a question to the user and obtains a response. @param q the question to present @param in the scanner from which to read the user input @return the score (1 if correct, 0 if incorrect) */ public static int presentQuestion(Question q, Scanner in) { q.display(); System.out.println("Your answer:"); String response = in.nextLine(); boolean outcome = q.checkAnswer(response); System.out.println(outcome); if (outcome) { return 1; } else { return 0; } } }
W0mpRat/IntroToProgramming
Code/lesson9/quiz4/QuestionDemo.java
Java
unlicense
1,626
from sys import argv from xml.dom import minidom import csv stem = argv[1][:-4] if argv[1].endswith('.xml') else argv[1] xmldoc = minidom.parse('%s.xml'%stem) labellist = xmldoc.getElementsByTagName('label') labels = [l.attributes['name'].value for l in labellist] labelset = set(labels) for split in 'train','test': with open('%s-%s.csv'%(stem,split), 'rb') as csvfile: reader = csv.DictReader(csvfile) features = [f for f in reader.fieldnames if f not in labelset] x = open('%s-%s.x.txt'%(stem,split), 'w') y = open('%s-%s.y.txt'%(stem,split), 'w') for row in reader: xbuf = ' '.join([row[f] for f in features]) ybuf = ' '.join([row[l] for l in labels]) x.write('%s\n'%xbuf) y.write("%s\n"%ybuf) x.close() y.close()
pmineiro/randembed
mulan/xmlcsv2xy.py
Python
unlicense
829
package mekanism.api; import net.minecraft.entity.Entity; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; /** * Chunk3D - an integer-based way to keep track of and perform operations on chunks in a Minecraft-based environment. This also takes * in account the dimension the chunk is in. * @author aidancbrady * */ public class Chunk3D { public int dimensionId; public int xCoord; public int zCoord; /** * Creates a Chunk3D object from the given x and z coordinates, as well as a dimension. * @param x - chunk x location * @param z - chunk z location * @param dimension - the dimension this Chunk3D is in */ public Chunk3D(int x, int z, int dimension) { xCoord = x; zCoord = z; dimensionId = dimension; } /** * Creates a Chunk3D from an entity based on it's location and dimension. * @param entity - the entity to get the Chunk3D object from */ public Chunk3D(Entity entity) { xCoord = ((int)entity.posX) >> 4; zCoord = ((int)entity.posZ) >> 4; dimensionId = entity.dimension; } /** * Creates a Chunk3D from a Coord4D based on it's coordinates and dimension. * @param coord - the Coord4D object to get this Chunk3D from */ public Chunk3D(Coord4D coord) { xCoord = coord.xCoord >> 4; zCoord = coord.zCoord >> 4; dimensionId = coord.dimensionId; } /** * Whether or not this chunk exists in the given world. * @param world - the world to check in * @return if the chunk exists */ public boolean exists(World world) { return world.getChunkProvider().chunkExists(xCoord, zCoord); } /** * Gets a Chunk object corresponding to this Chunk3D's coordinates. * @param world - the world to get the Chunk object from * @return the corresponding Chunk object */ public Chunk getChunk(World world) { return world.getChunkFromChunkCoords(xCoord, zCoord); } @Override public Coord4D clone() { return new Coord4D(xCoord, zCoord, dimensionId); } @Override public String toString() { return "[Chunk3D: " + xCoord + ", " + zCoord + ", dim=" + dimensionId + "]"; } @Override public boolean equals(Object obj) { return obj instanceof Chunk3D && ((Chunk3D)obj).xCoord == xCoord && ((Chunk3D)obj).zCoord == zCoord && ((Chunk3D)obj).dimensionId == dimensionId; } @Override public int hashCode() { int code = 1; code = 31 * code + xCoord; code = 31 * code + zCoord; code = 31 * code + dimensionId; return code; } }
Vexatos/EnderIO
src/main/java/mekanism/api/Chunk3D.java
Java
unlicense
2,473
$.extend(window.lang_id, { "Title": "Apakah Anda Melainkan ..", "installApp": "Gunakan Aplikasi untuk membagikan jajak pendapat ini!", "installAppComments": "Download gratis.", "haveApp": "Aku sudah App!", "SecondPageButton": "Bermain", "Welcome": "Halo selamat datang!", "rules": "1. Klik link aplikasi untuk memuat votasi <br/> 2. Pilih suara anda <br/> 3. Bagikan gambar yang diperbarui kepada siapa saja!", "MakeNew": "Poll baru", "Create": "Membuat", "VotedPolls": "Voting polling:", "swipeToRemove": "Gesek untuk menghapus", "showYourPolls": "Tunjukkan jajak pendapatmu", "Return": "Kembali", "Share+": "Bagikan +", "Share": "Bagikan", "Save": "Menyimpan", "Voters": "Pemilih", "Cancel": "Membatalkan", "needsPhone": "Untuk mendapatkan suara di poling umum, kami mencegah agar bots mengirim SMS ke nomor telepon Anda", "needsPhoneComment": "Identifikasi ini disediakan oleh rangkaian pengembangan twitter auth dan aplikasi ini akan mengenkripsi nomor telepon Anda.", "multipleChoice": "Biarkan memilih beberapa pilihan.", "onlyDevice": "Pilih hanya suara dari App.", "openVotes": "Membuka suara", "firstOk": "Baik", "Activate": "Mengaktifkan", "downloadAppStore": "Pasang aplikasi dan bagikan!", "createPoll": "Bagikan polis ke manapun Anda inginkan:", "QuestionPlaceholder": "Tuliskan disini pertanyaannya, sertakan info tambahan di jalur lain.", "OptionsPlaceholder": "Masukkan setiap pilihan pada baris yang berbeda.", "UsernamePlaceholder": "Nama anda (opsional)", "PublicOnlyFromApp": "Untuk memilih di poling umum, Anda perlu menggunakan <u> APP </ u>", "PollOnlyAvailableIn": "Jajak pendapat ini hanya tersedia di", "AllowAppServices": "Tolong, <b> perbaiki </ b> pengalaman pengguna Anda sehingga memungkinkan penggunaan akses <b> '</ b>.", "whyNeedServicesPermission": "Mengapa perlu ini? <br/> Sejak versi 5.0 Lollipop 5.0, diperlukan izin khusus untuk membaca penggunaan aplikasi. Kami membutuhkan ini untuk meningkatkan penerapan dengan aplikasi sosial lainnya.", "votationNotExists": "Pemungutan suara tidak ada", "votationNotSaved": "Tidak dapat terhubung ke server: voting tidak disimpan", "waitingKey": "Membuat demokrasi ..", "waitingKeyExpired": "Kesalahan saat menyimpan jajak pendapat Coba lagi..", "onlyMostVotedShows": "Secara default hanya 4 pilihan yang paling terpilih yang ditampilkan di gambar bersama.", "hidePolls": "Menyembunyikan jajak pendapat", "notPublicUsers": "Tidak ada nama pemilih", "missingAjaxKey": "Batas waktu meminta kunci polling, silakan cek koneksi internet anda.", "more": "lebih", "min1Option": "Letakkan setidaknya 1 pilihan", "min2Options": "Pilihan tidak boleh kosong", "duplicatedOptions": "Pilihan duplikat!", "myName": "Masukkan nama panggilan", "requiredName": "Masukkan nama anda (wajib)", "privateNeedUserName": "Tambahkan nama Anda diperlukan (hanya untuk polling pribadi)", "unknown": "Tidak diketahui", "browser": "Browser", "notInApp": "Gunakan App untuk meneruskan polling.", "pollWillVisible": "Terima kasih. Jajak pendapat akan terlihat dalam beberapa jam ke depan!", "error": "kesalahan", "errorAjaxResponse": "Kesalahan saat mengambil respon ajax", "votationNotFound": "Pemungutan suara tidak ditemukan", "WrongCountry": "Anda tidak berada di tempat", "notValidUserId": "Id pengguna tidak valid", "notLoadingPolls": "Kesalahan pemuatan jajak pendapat", "warnNotPublic": "Peringatkan: jajak pendapat ini bersifat pribadi dan tidak memvalidasi pemilih, jadi tidak berlaku untuk pemungutan suara publik", "e_noDataReceived": "Tidak ada data yang diambil", "e_phoneValidationNotWork": "Masalah untuk melakukan verifikasi SMS? Tolong kalau begitu hubungi kami.", "warnMaximumOptions": "Verifikasi gambar tidak dipotong di lingkungan bersama", "e_retrievingData": "Polling tidak ditemukan, periksa koneksi internet anda:", "loadingPublicKey": "Memvalidasi nomor telepon, tunggu sebentar dan coba lagi ..", "PopularPolls": "Jajak pendapat populer:", "total": "total", "New": "Baru", "search": "pencarian", "showAll": "Tunjukkan semua negara", "showMine": "Default", "duplicatedKey": "Digandakan kunci", "noPollsFound": "Bukan jajak pendapat yang ditemukan", "forgetPoll": "lupakan ini", "UNDO": "MEMBUKA", "Votes": "Suara", "ClickTheLink": "Link untuk memilih!", "CustomStyles": "Gaya default:", "defaults": "Default", "Symbol": "Simbol:", "ChooseFile": "Upload gambar", "QuestionColor": "Warna pertanyaan:", "OptionTextColor": "Warna teks opsi:", "BackgroundColor": "Warna latar belakang:", "GradientBackground": "Latar belakang gradasi:", "GradientColor1": "Gradien warna 1:", "GradientColor2": "Warna gradien 2:", "LimitByCountry": "Batas menurut wilayah:", "WillShowPublic": "- Jajak pendapat publik akan ditampilkan di halaman 'jajak pendapat publik'.", "ChooseCountry": "Memilih", "ExampleQuestion": "Ini adalah contoh pertanyaan <br> Dan ini adalah beberapa teks tambahan", "OptionExample1": "Contoh pilihan A", "OptionExample2": "Contoh pilihan B", "ownerNameExample": "nama pemilik", "AddPollLink": "Tambahkan LINK web tambahan untuk polling ini", "Public": "Publik", "StyleNamePlaceholder": "Nama gaya", "SaveStyle": "Menyimpan", "Delete": "Menghapus", "allCountries": "Negara manapun ..", "Yes": "iya nih", "Not": "Tidak", "cantChangePublic": "Jajak pendapat ini sudah disimpan. Untuk mengubah nilai Publik, batalkan ini dan buatlah yang baru.", "noUserCountryFound": "Kesalahan: tidak dapat mengambil negara telepon Anda, hubungi kami", "p_notEditable": "Tidak tersedia pilihan disini.", "e_votationRemoved": "Maaf, pemungutan suara ini telah dihapus", "e_connectionLost": "Koneksi terputus", "e_votationWithErrors": "Maaf, pemungutan suara memiliki kesalahan. Silahkan hubungi kami.", "e_flagNotFound": "Tidak bisa memuat bendera", "e_parsingIndexFile": "Kesalahan parsing file _index.txt", "e_connection": "Silahkan cek koneksi internet anda dan coba lagi", "e_publicPolls": "Tidak ditemukan jajak pendapat umum", "e_imageNotFound": "Kesalahan: gambar tidak ditemukan", });
trollderius/wouldyourather_phonegap
www/~lang/id.js
JavaScript
unlicense
5,953
/* */ var baseDifference = require('./_baseDifference'), baseFlatten = require('./_baseFlatten'), isArrayLikeObject = require('./isArrayLikeObject'), rest = require('./rest'); var difference = rest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, true)) : []; }); module.exports = difference;
EpitaJS/js-class-2016
jspm_packages/npm/lodash@4.6.1/difference.js
JavaScript
unlicense
364
# ISO <<Class>> LI_ProcessStep # 19115-2 writer output in XML # History: # Stan Smith 2018-04-10 add error and warning messaging # Stan Smith 2017-08-30 added support for step sources # Stan Smith 2016-12-13 refactored for mdTranslator/mdJson 2.0 # Stan Smith 2015-07-14 refactored to eliminate namespace globals $WriterNS and $IsoNS # Stan Smith 2015-07-14 refactored to make iso19110 independent of iso19115_2 classes # Stan Smith 2015-06-22 replace global ($response) with passed in object (hResponseObj) # Stan Smith 2014-12-12 refactored to handle namespacing readers and writers # Stan Smith 2014-07-09 modify require statements to function in RubyGem structure # Stan Smith 2013-11-20 original script. require_relative '../iso19115_2_writer' require_relative 'class_responsibleParty' require_relative 'class_source' module ADIWG module Mdtranslator module Writers module Iso19115_2 class LI_ProcessStep def initialize(xml, hResponseObj) @xml = xml @hResponseObj = hResponseObj @NameSpace = ADIWG::Mdtranslator::Writers::Iso19115_2 end def writeXML(hStep, inContext = nil) # classes used partyClass = CI_ResponsibleParty.new(@xml, @hResponseObj) sourceClass = Source.new(@xml, @hResponseObj) outContext = 'process step' outContext = outContext + ' ' + hStep[:stepId].to_s unless hStep[:stepId].nil? outContext = inContext + ' ' + outContext unless inContext.nil? # process step - id attributes = {} s = hStep[:stepId] unless s.nil? attributes = { id: s.gsub(/[^0-9A-Za-z]/,'') } end @xml.tag!('gmd:LI_ProcessStep', attributes) do # process step - description (required) s = hStep[:description] unless s.nil? @xml.tag!('gmd:description') do @xml.tag!('gco:CharacterString', s) end end if s.nil? @NameSpace.issueWarning(260, 'gmd:description', outContext) end # process step - rationale s = hStep[:rationale] unless s.nil? @xml.tag!('gmd:rationale') do @xml.tag!('gco:CharacterString', s) end end if s.nil? && @hResponseObj[:writerShowTags] @xml.tag!('gmd:rationale') end # process step - datetime hPeriod = hStep[:timePeriod] unless hPeriod.empty? hDate = hPeriod[:startDateTime] if hDate.empty? hDate = hPeriod[:endDateTime] end date = hDate[:dateTime] dateResolution = hDate[:dateResolution] s = AdiwgDateTimeFun.stringDateTimeFromDateTime(date, dateResolution) if s != 'ERROR' @xml.tag!('gmd:dateTime') do @xml.tag!('gco:DateTime', s) end end end if hPeriod.empty? && @hResponseObj[:writerShowTags] @xml.tag!('gmd:dateTime') end # process step - processor [] {CI_ResponsibleParty} aParties = hStep[:processors] aParties.each do |hRParty| role = hRParty[:roleName] aParties = hRParty[:parties] aParties.each do |hParty| @xml.tag!('gmd:processor') do partyClass.writeXML(role, hParty, outContext) end end end if aParties.empty? && @hResponseObj[:writerShowTags] @xml.tag!('gmd:processor') end # process step - source [] {Source} aSources = hStep[:stepSources] aSources.each do |hSource| @xml.tag!('gmd:source') do sourceClass.writeXML(hSource) end end if aSources.empty? && @hResponseObj[:writerShowTags] @xml.tag!('gmd:source') end end # gmd:LI_ProcessStep tag end # writeXML end # LI_ProcessStep class end end end end
stansmith907/mdTranslator
lib/adiwg/mdtranslator/writers/iso19115_2/classes/class_liProcessStep.rb
Ruby
unlicense
5,039
#include <cstdio> #include <cstring> #define MAXS 512 #define Zero(v) memset(v, 0, sizeof(v)) int b, w; char maze[MAXS][MAXS]; int cnt[MAXS][MAXS]; int ans[5]; const int dd[4][2] = { { 0, 1 }, // East { -1, 0 }, // North { 0, -1 }, // West { 1, 0 } // South }; bool valid_pos(int r, int c) { return r >= 0 && r < b && c >= 0 && c < w; } bool can_move(int r, int c, int dir) { int r2 = r + dd[dir][0]; int c2 = c + dd[dir][1]; return valid_pos(r2, c2) && maze[r2][c2] == '0'; } int move_left(int dir) { return (dir + 1) % 4; } int move_right(int dir) { return dir == 0 ? 3 : dir - 1; } bool wall_right(int r, int c, int dir) { int d2 = move_right(dir); int r2 = r + dd[d2][0]; int c2 = c + dd[d2][1]; return (!valid_pos(r2, c2)) || maze[r2][c2] == '1'; } void solve() { Zero(ans); Zero(cnt); int r = b - 1; int c = 0; int dir = 0; for (int i = 0; i < b; ++i) for (int j = 0; j < w; ++j) if (maze[i][j] == '0') ++ans[0]; while (true) { while (! can_move(r, c, dir)) dir = move_left(dir); r += dd[dir][0]; c += dd[dir][1]; if (cnt[r][c] <= 4) --ans[cnt[r][c]]; ++cnt[r][c]; if (cnt[r][c] <= 4) ++ans[cnt[r][c]]; if (r == b - 1 && c == 0) break; if (! wall_right(r, c, dir)) dir = move_right(dir); } } int main() { while (true) { scanf("%d%d", &b, &w); if (b == 0 && w == 0) break; for (int i = 0; i < b; ++i) scanf("%s", maze[i]); solve(); printf("%3d%3d%3d%3d%3d\n", ans[0], ans[1], ans[2], ans[3], ans[4]); } return 0; }
M4573R/pc-code
solved/0-b/amazing/amazing.cpp
C++
unlicense
1,702
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcVersion4Internet.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; return View(); } public ActionResult About() { ViewBag.Message = "Your app description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
JamesSkemp/AspNetMvcVersions
Visual Studio 2012/MvcVersion4Internet/Controllers/HomeController.cs
C#
unlicense
563
#include <algorithm> #include <cstdio> #include <vector> using namespace std; #define cFor(t,v,c) for(t::const_iterator v=c.begin(); v != c.end(); ++v) typedef long long i64; typedef vector<i64> IV; typedef IV::iterator IVi; const i64 Max = 1000000000000LL; i64 A, B; IV ns; // very lucky numbers void uniq(IV &v) { sort(v.begin(), v.end()); IVi it = unique(v.begin(), v.end()); v.resize(it - v.begin()); } void prepare() { IV l1; IV x; x.push_back(0); for (int i = 1; i <= 12; ++i) { IV y; cFor (IV, n, x) { i64 m = *n * 10 + 4; l1.push_back(m); y.push_back(m); m = *n * 10 + 7; l1.push_back(m); y.push_back(m); } x = y; } x = l1; uniq(x); ns.insert(ns.end(), x.begin(), x.end()); while (true) { IV y; cFor (IV, n, l1) { i64 q = Max / *n; int cnt = 0; cFor (IV, m, x) { if (*m > q) break; i64 p = *n * *m; y.push_back(p); ++cnt; } if (cnt == 0) break; } if (y.size() == 0) break; x = y; uniq(x); ns.insert(ns.end(), x.begin(), x.end()); } uniq(ns); } int lucky_count(i64 n) { IVi it = upper_bound(ns.begin(), ns.end(), n); return it - ns.begin(); } int solve() { return lucky_count(B) - lucky_count(A - 1); } int main() { prepare(); int T; scanf("%d", &T); int ncase = 0; while (T--) { scanf("%lld%lld", &A, &B); printf("Case %d: %d\n", ++ncase, solve()); } return 0; }
lbv/pc-code
solved/u-w/very-lucky-numbers/lucky.cpp
C++
unlicense
1,702
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.client; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.tests.util.SpawnedVMSupport; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.journal.PreparedTransactionInfo; import org.apache.activemq.artemis.core.journal.RecordInfo; import org.apache.activemq.artemis.core.journal.impl.JournalImpl; import org.apache.activemq.artemis.core.journal.impl.NIOSequentialFileFactory; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Test; public class JournalCrashTest extends ActiveMQTestBase { private static final int FIRST_RUN = 4; private static final int SECOND_RUN = 8; private static final int THIRD_RUN = 100; private static final int FOURTH_RUN = 400; private ActiveMQServer server; private ClientSessionFactory factory; private final SimpleString QUEUE = new SimpleString("queue"); private ServerLocator locator; protected void startServer() throws Exception { Configuration config = createDefaultInVMConfig() .setJournalFileSize(ActiveMQDefaultConfiguration.getDefaultJournalFileSize()) .setJournalCompactMinFiles(ActiveMQDefaultConfiguration.getDefaultJournalCompactMinFiles()) .setJournalCompactPercentage(ActiveMQDefaultConfiguration.getDefaultJournalCompactPercentage()) .setJournalMinFiles(2); server = super.createServer(true, config); server.start(); locator = createInVMNonHALocator(); factory = createSessionFactory(locator); } protected void stopServer() throws Exception { locator.close(); closeSessionFactory(factory); factory = null; stopComponent(server); server = null; } /** * The test needs another VM, that will be "killed" right after commit. This main will do this job. */ public static void main(final String[] arg) { try { if (arg.length != 3) { throw new IllegalArgumentException(Arrays.toString(arg)); } String testDir = arg[0]; final int start = Integer.parseInt(arg[1]); final int end = Integer.parseInt(arg[2]); JournalCrashTest restart = new JournalCrashTest(); restart.setTestDir(testDir); restart.startServer(); restart.sendMessages(start, end); // System.out.println("....end"); // System.out.flush(); Runtime.getRuntime().halt(100); } catch (Exception e) { e.printStackTrace(System.out); System.exit(1); } } public void sendMessages(final int start, final int end) throws Exception { ClientSession session = null; try { session = factory.createSession(false, false); try { session.createQueue(QUEUE, QUEUE, true); } catch (Exception ignored) { } ClientProducer prod = session.createProducer(QUEUE); for (int i = start; i < end; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty(new SimpleString("key"), i); msg.getBodyBuffer().writeUTF("message " + i); prod.send(msg); } session.commit(); session.close(); // server.stop(); -- this test was not supposed to stop the server, it should crash } finally { session.close(); } } @Test public void testRestartJournal() throws Throwable { runExternalProcess(getTestDir(), 0, JournalCrashTest.FIRST_RUN); runExternalProcess(getTestDir(), JournalCrashTest.FIRST_RUN, JournalCrashTest.SECOND_RUN); runExternalProcess(getTestDir(), JournalCrashTest.SECOND_RUN, JournalCrashTest.THIRD_RUN); runExternalProcess(getTestDir(), JournalCrashTest.THIRD_RUN, JournalCrashTest.FOURTH_RUN); printJournal(); ClientSession session = null; try { startServer(); session = factory.createSession(true, true); ClientConsumer consumer = session.createConsumer(QUEUE); session.start(); for (int i = 0; i < JournalCrashTest.FOURTH_RUN; i++) { ClientMessage msg = consumer.receive(5000); Assert.assertNotNull("Msg at " + i, msg); msg.acknowledge(); Assert.assertEquals(i, msg.getObjectProperty(new SimpleString("key"))); } session.close(); } finally { try { session.close(); } catch (Throwable ignored) { } } } /** * @throws Exception * @throws InterruptedException */ private void runExternalProcess(final String tempDir, final int start, final int end) throws Exception { System.err.println("running external process..."); Process process = SpawnedVMSupport.spawnVM(this.getClass().getCanonicalName(), "-Xms128m", "-Xmx128m", new String[]{}, true, true, tempDir, Integer.toString(start), Integer.toString(end)); Assert.assertEquals(100, process.waitFor()); } /** * @throws Exception */ private void printJournal() throws Exception { NIOSequentialFileFactory factory = new NIOSequentialFileFactory(new File(getJournalDir())); JournalImpl journal = new JournalImpl(ActiveMQDefaultConfiguration.getDefaultJournalFileSize(), 2, 0, 0, factory, "activemq-data", "amq", 100); ArrayList<RecordInfo> records = new ArrayList<RecordInfo>(); ArrayList<PreparedTransactionInfo> transactions = new ArrayList<PreparedTransactionInfo>(); journal.start(); journal.load(records, transactions, null); // System.out.println("==============================================="); // System.out.println("Journal records at the end:"); // // for (RecordInfo record : records) // { // System.out.println(record.id + ", update = " + record.isUpdate); // } journal.stop(); } }
ryanemerson/activemq-artemis
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/JournalCrashTest.java
Java
apache-2.0
7,994
// Code generated by smithy-go-codegen DO NOT EDIT. package ec2 import ( "context" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Deprovision a CIDR provisioned from an IPAM pool. If you deprovision a CIDR from // a pool that has a source pool, the CIDR is recycled back into the source pool. // For more information, see Deprovision pool CIDRs in the Amazon VPC IPAM User // Guide. func (c *Client) DeprovisionIpamPoolCidr(ctx context.Context, params *DeprovisionIpamPoolCidrInput, optFns ...func(*Options)) (*DeprovisionIpamPoolCidrOutput, error) { if params == nil { params = &DeprovisionIpamPoolCidrInput{} } result, metadata, err := c.invokeOperation(ctx, "DeprovisionIpamPoolCidr", params, optFns, c.addOperationDeprovisionIpamPoolCidrMiddlewares) if err != nil { return nil, err } out := result.(*DeprovisionIpamPoolCidrOutput) out.ResultMetadata = metadata return out, nil } type DeprovisionIpamPoolCidrInput struct { // The ID of the pool that has the CIDR you want to deprovision. // // This member is required. IpamPoolId *string // The CIDR which you want to deprovision from the pool. Cidr *string // A check for whether you have the required permissions for the action without // actually making the request and provides an error response. If you have the // required permissions, the error response is DryRunOperation. Otherwise, it is // UnauthorizedOperation. DryRun *bool noSmithyDocumentSerde } type DeprovisionIpamPoolCidrOutput struct { // The deprovisioned pool CIDR. IpamPoolCidr *types.IpamPoolCidr // Metadata pertaining to the operation's result. ResultMetadata middleware.Metadata noSmithyDocumentSerde } func (c *Client) addOperationDeprovisionIpamPoolCidrMiddlewares(stack *middleware.Stack, options Options) (err error) { err = stack.Serialize.Add(&awsEc2query_serializeOpDeprovisionIpamPoolCidr{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsEc2query_deserializeOpDeprovisionIpamPoolCidr{}, middleware.After) if err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { return err } if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { return err } if err = addRetryMiddlewares(stack, options); err != nil { return err } if err = addHTTPSignerV4Middleware(stack, options); err != nil { return err } if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { return err } if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { return err } if err = addClientUserAgent(stack); err != nil { return err } if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { return err } if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } if err = addOpDeprovisionIpamPoolCidrValidationMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeprovisionIpamPoolCidr(options.Region), middleware.Before); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { return err } if err = addResponseErrorMiddleware(stack); err != nil { return err } if err = addRequestResponseLogging(stack, options); err != nil { return err } return nil } func newServiceMetadataMiddleware_opDeprovisionIpamPoolCidr(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "ec2", OperationName: "DeprovisionIpamPoolCidr", } }
michi-covalent/cilium
vendor/github.com/aws/aws-sdk-go-v2/service/ec2/api_op_DeprovisionIpamPoolCidr.go
GO
apache-2.0
4,063
/** * PlasmaSDO™ License * * This is a community release of PlasmaSDO™, a dual-license * Service Data Object (SDO) 2.1 implementation. * This particular copy of the software is released under the * version 2 of the GNU General Public License. PlasmaSDO™ was developed by * TerraMeta Software, Inc. * * Copyright (c) 2013, TerraMeta Software, Inc. All rights reserved. * * General License information can be found below. * * This distribution may include materials developed by third * parties. For license and attribution notices for these * materials, please refer to the documentation that accompanies * this distribution (see the "Licenses for Third-Party Components" * appendix) or view the online documentation at * <http://plasma-sdo.org/licenses/>. * */ package org.plasma.sdo.access.provider.jdbc; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.plasma.sdo.PlasmaType; /** * Simple collection managing SQL table aliases */ public class AliasMap { private Map<PlasmaType, String> map = null; @SuppressWarnings("unused") private AliasMap() { } public AliasMap(PlasmaType root) { this.map = new HashMap<PlasmaType, String>(); this.map.put(root, "t0"); } /** * Returns the table alias for the given type * * @param type * the type * @return the alias */ public String getAlias(PlasmaType type) { return this.map.get(type); } /** * Return the types which are keys for this map. * * @return the type keys */ public Iterator<PlasmaType> getTypes() { return this.map.keySet().iterator(); } /** * Returs the alias names for this map * * @return the alias names */ public Collection<String> getAliases() { return this.map.values(); } /** * Adds and returns the table alias for the given type, or existing alias of * already mapped * * @param type * the type * @return the new alias or existing alias of already mapped */ public String addAlias(PlasmaType type) { String existing = this.map.get(type); if (existing == null) { String alias = "t" + String.valueOf(this.map.size()); this.map.put(type, alias); return alias; } return existing; } }
plasma-framework/plasma
plasma-jdbc/src/main/java/org/plasma/sdo/access/provider/jdbc/AliasMap.java
Java
apache-2.0
2,341
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.config.update; import com.thoughtworks.go.config.CruiseConfig; import com.thoughtworks.go.config.PipelineConfig; import com.thoughtworks.go.config.exceptions.EntityType; import com.thoughtworks.go.domain.packagerepository.PackageRepositories; import com.thoughtworks.go.domain.packagerepository.PackageRepository; import com.thoughtworks.go.server.domain.Username; import com.thoughtworks.go.server.service.EntityHashingService; import com.thoughtworks.go.server.service.GoConfigService; import com.thoughtworks.go.server.service.materials.PackageRepositoryService; import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult; import java.util.List; public class UpdatePackageRepositoryCommand extends PackageRepositoryCommand { private final GoConfigService goConfigService; private final PackageRepository newRepo; private final String digest; private final EntityHashingService entityHashingService; private final HttpLocalizedOperationResult result; private String oldRepoId; public UpdatePackageRepositoryCommand(GoConfigService goConfigService, PackageRepositoryService packageRepositoryService, PackageRepository newRepo, Username username, String digest, EntityHashingService entityHashingService, HttpLocalizedOperationResult result, String oldRepoId) { super(packageRepositoryService, newRepo, result, goConfigService, username); this.goConfigService = goConfigService; this.newRepo = newRepo; this.digest = digest; this.entityHashingService = entityHashingService; this.result = result; this.oldRepoId = oldRepoId; } @Override public void update(CruiseConfig modifiedConfig) { PackageRepository oldRepo = modifiedConfig.getPackageRepositories().find(newRepo.getRepoId()); this.newRepo.setPackages(oldRepo.getPackages()); PackageRepositories repositories = modifiedConfig.getPackageRepositories(); repositories.replace(oldRepo, newRepo); modifiedConfig.setPackageRepositories(repositories); updatePackageRepositoryConfigurationOnAssociatedPipelines(modifiedConfig); } @Override public boolean canContinue(CruiseConfig cruiseConfig) { return super.canContinue(cruiseConfig) && isIdSame() && isRequestFresh(); } private void updatePackageRepositoryConfigurationOnAssociatedPipelines(CruiseConfig modifiedConfig) { List<PipelineConfig> pipelinesWithPackageRepo = modifiedConfig.pipelinesAssociatedWithPackageRepository(newRepo); pipelinesWithPackageRepo.forEach(pipelineConfig -> { pipelineConfig.packageMaterialConfigs().forEach(packageMaterialConfig -> { if (packageMaterialConfig.getPackageDefinition().getRepository().getId().equals(newRepo.getId())) { packageMaterialConfig.getPackageDefinition().setRepository(newRepo); } }); }); } private boolean isIdSame() { boolean isRepoIdSame = newRepo.getRepoId().equals(oldRepoId); if (!isRepoIdSame) { result.unprocessableEntity("Changing the repository id is not supported by this API."); } return isRepoIdSame; } private boolean isRequestFresh() { PackageRepository oldRepo = goConfigService.getPackageRepository(newRepo.getRepoId()); boolean freshRequest = entityHashingService.hashForEntity(oldRepo).equals(digest); if (!freshRequest) { result.stale(EntityType.PackageRepository.staleConfig(newRepo.getRepoId())); } return freshRequest; } }
marques-work/gocd
server/src/main/java/com/thoughtworks/go/config/update/UpdatePackageRepositoryCommand.java
Java
apache-2.0
4,246
package org.ovirt.engine.ui.uicommonweb.models.templates; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.compat.StringFormat; import org.ovirt.engine.ui.uicommonweb.models.vms.VmListModel; @SuppressWarnings("unused") public class TemplateVmListModel extends VmListModel { @Override public VmTemplate getEntity() { return (VmTemplate) ((super.getEntity() instanceof VmTemplate) ? super.getEntity() : null); } public void setEntity(VmTemplate value) { super.setEntity(value); } public TemplateVmListModel() { setTitle("Virtual Machines"); } @Override protected void OnEntityChanged() { super.OnEntityChanged(); getSearchCommand().Execute(); } @Override public void Search() { if (getEntity() != null) { setSearchString(StringFormat.format("Vms: template.name=%1$s", getEntity().getname())); super.Search(); } } }
Dhandapani/gluster-ovirt
frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/templates/TemplateVmListModel.java
Java
apache-2.0
1,025
package info.ineighborhood.cardme.vcard.features; /** * Copyright (c) 2004, Neighborhood Technologies * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Neighborhood Technologies nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * * @author George El-Haddad * <br/> * Feb 4, 2010 * * <p><b>RFC 2426</b><br/> * <b>3.3.3 MAILER Type Definition</b> * <ul> * <li><b>Type name:</b> MAILER</li> * <li><b>Type purpose:</b> To specify the type of electronic mail software that is used by the individual associated with the vCard.</li> * <li><b>Type encoding:</b> 8bit</li> * <li><b>Type value:</b> A single text value.</li> * <li><b>Type special note:</b> This information can provide assistance to a correspondent regarding the type of data representation which can be used, and how they can be packaged. This property is based on the private MIME type X-Mailer that is generally implemented by MIME user agent products.</li> * </ul> * </p> */ public interface MailerFeature extends TypeTools { /** * <p>Returns the mailer.</p> * * @return {@link String} */ public String getMailer(); /** * <p>Sets the mailer.</p> * * @param mailer */ public void setMailer(String mailer); /** * <p>Clears the mailer.</p> */ public void clearMailer(); /** * <p>Returns true if the mailer exists.</p> */ public boolean hasMailer(); /** * <p>Returns a full copy of this object.</p> * * @return {@link MailerFeature} */ public MailerFeature clone(); }
skoulouzis/lobcder
milton/milton-caldav/src/main/java/info/ineighborhood/cardme/vcard/features/MailerFeature.java
Java
apache-2.0
2,911
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hbase.archetypes.exemplars.client; import java.io.IOException; import java.util.Map.Entry; import java.util.NavigableMap; import org.apache.hadoop.hbase.NamespaceDescriptor; import org.apache.hadoop.hbase.NamespaceNotFoundException; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.client.TableDescriptor; import org.apache.hadoop.hbase.client.TableDescriptorBuilder; import org.apache.hadoop.hbase.util.Bytes; /** * Successful running of this application requires access to an active instance * of HBase. For install instructions for a standalone instance of HBase, please * refer to https://hbase.apache.org/book.html#quickstart */ public final class HelloHBase { protected static final String MY_NAMESPACE_NAME = "myTestNamespace"; static final TableName MY_TABLE_NAME = TableName.valueOf("myTestTable"); static final byte[] MY_COLUMN_FAMILY_NAME = Bytes.toBytes("cf"); static final byte[] MY_FIRST_COLUMN_QUALIFIER = Bytes.toBytes("myFirstColumn"); static final byte[] MY_SECOND_COLUMN_QUALIFIER = Bytes.toBytes("mySecondColumn"); static final byte[] MY_ROW_ID = Bytes.toBytes("rowId01"); // Private constructor included here to avoid checkstyle warnings private HelloHBase() { } public static void main(final String[] args) throws IOException { final boolean deleteAllAtEOJ = true; /** * ConnectionFactory#createConnection() automatically looks for * hbase-site.xml (HBase configuration parameters) on the system's * CLASSPATH, to enable creation of Connection to HBase via ZooKeeper. */ try (Connection connection = ConnectionFactory.createConnection(); Admin admin = connection.getAdmin()) { admin.getClusterStatus(); // assure connection successfully established System.out.println("\n*** Hello HBase! -- Connection has been " + "established via ZooKeeper!!\n"); createNamespaceAndTable(admin); System.out.println("Getting a Table object for [" + MY_TABLE_NAME + "] with which to perform CRUD operations in HBase."); try (Table table = connection.getTable(MY_TABLE_NAME)) { putRowToTable(table); getAndPrintRowContents(table); if (deleteAllAtEOJ) { deleteRow(table); } } if (deleteAllAtEOJ) { deleteNamespaceAndTable(admin); } } } /** * Invokes Admin#createNamespace and Admin#createTable to create a namespace * with a table that has one column-family. * * @param admin Standard Admin object * @throws IOException If IO problem encountered */ static void createNamespaceAndTable(final Admin admin) throws IOException { if (!namespaceExists(admin, MY_NAMESPACE_NAME)) { System.out.println("Creating Namespace [" + MY_NAMESPACE_NAME + "]."); admin.createNamespace(NamespaceDescriptor .create(MY_NAMESPACE_NAME).build()); } if (!admin.tableExists(MY_TABLE_NAME)) { System.out.println("Creating Table [" + MY_TABLE_NAME.getNameAsString() + "], with one Column Family [" + Bytes.toString(MY_COLUMN_FAMILY_NAME) + "]."); TableDescriptor desc = TableDescriptorBuilder.newBuilder(MY_TABLE_NAME) .addColumnFamily(ColumnFamilyDescriptorBuilder.of(MY_COLUMN_FAMILY_NAME)) .build(); admin.createTable(desc); } } /** * Invokes Table#put to store a row (with two new columns created 'on the * fly') into the table. * * @param table Standard Table object (used for CRUD operations). * @throws IOException If IO problem encountered */ static void putRowToTable(final Table table) throws IOException { table.put(new Put(MY_ROW_ID).addColumn(MY_COLUMN_FAMILY_NAME, MY_FIRST_COLUMN_QUALIFIER, Bytes.toBytes("Hello")).addColumn(MY_COLUMN_FAMILY_NAME, MY_SECOND_COLUMN_QUALIFIER, Bytes.toBytes("World!"))); System.out.println("Row [" + Bytes.toString(MY_ROW_ID) + "] was put into Table [" + table.getName().getNameAsString() + "] in HBase;\n" + " the row's two columns (created 'on the fly') are: [" + Bytes.toString(MY_COLUMN_FAMILY_NAME) + ":" + Bytes.toString(MY_FIRST_COLUMN_QUALIFIER) + "] and [" + Bytes.toString(MY_COLUMN_FAMILY_NAME) + ":" + Bytes.toString(MY_SECOND_COLUMN_QUALIFIER) + "]"); } /** * Invokes Table#get and prints out the contents of the retrieved row. * * @param table Standard Table object * @throws IOException If IO problem encountered */ static void getAndPrintRowContents(final Table table) throws IOException { Result row = table.get(new Get(MY_ROW_ID)); System.out.println("Row [" + Bytes.toString(row.getRow()) + "] was retrieved from Table [" + table.getName().getNameAsString() + "] in HBase, with the following content:"); for (Entry<byte[], NavigableMap<byte[], byte[]>> colFamilyEntry : row.getNoVersionMap().entrySet()) { String columnFamilyName = Bytes.toString(colFamilyEntry.getKey()); System.out.println(" Columns in Column Family [" + columnFamilyName + "]:"); for (Entry<byte[], byte[]> columnNameAndValueMap : colFamilyEntry.getValue().entrySet()) { System.out.println(" Value of Column [" + columnFamilyName + ":" + Bytes.toString(columnNameAndValueMap.getKey()) + "] == " + Bytes.toString(columnNameAndValueMap.getValue())); } } } /** * Checks to see whether a namespace exists. * * @param admin Standard Admin object * @param namespaceName Name of namespace * @return true If namespace exists * @throws IOException If IO problem encountered */ static boolean namespaceExists(final Admin admin, final String namespaceName) throws IOException { try { admin.getNamespaceDescriptor(namespaceName); } catch (NamespaceNotFoundException e) { return false; } return true; } /** * Invokes Table#delete to delete test data (i.e. the row) * * @param table Standard Table object * @throws IOException If IO problem is encountered */ static void deleteRow(final Table table) throws IOException { System.out.println("Deleting row [" + Bytes.toString(MY_ROW_ID) + "] from Table [" + table.getName().getNameAsString() + "]."); table.delete(new Delete(MY_ROW_ID)); } /** * Invokes Admin#disableTable, Admin#deleteTable, and Admin#deleteNamespace to * disable/delete Table and delete Namespace. * * @param admin Standard Admin object * @throws IOException If IO problem is encountered */ static void deleteNamespaceAndTable(final Admin admin) throws IOException { if (admin.tableExists(MY_TABLE_NAME)) { System.out.println("Disabling/deleting Table [" + MY_TABLE_NAME.getNameAsString() + "]."); admin.disableTable(MY_TABLE_NAME); // Disable a table before deleting it. admin.deleteTable(MY_TABLE_NAME); } if (namespaceExists(admin, MY_NAMESPACE_NAME)) { System.out.println("Deleting Namespace [" + MY_NAMESPACE_NAME + "]."); admin.deleteNamespace(MY_NAMESPACE_NAME); } } }
JingchengDu/hbase
hbase-archetypes/hbase-client-project/src/main/java/org/apache/hbase/archetypes/exemplars/client/HelloHBase.java
Java
apache-2.0
8,641
/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "jerryscript.h" #include "test-common.h" static void compare_str (jerry_value_t value, const char *str_p, size_t str_len) { jerry_size_t size = jerry_string_size (value, JERRY_ENCODING_CESU8); TEST_ASSERT (str_len == size); JERRY_VLA (jerry_char_t, str_buff, size); jerry_string_to_buffer (value, JERRY_ENCODING_CESU8, str_buff, size); TEST_ASSERT (!memcmp (str_p, str_buff, str_len)); } /* compare_str */ int main (void) { TEST_INIT (); jerry_init (JERRY_INIT_EMPTY); jerry_value_t obj_val = jerry_object (); obj_val = jerry_throw_value (obj_val, true); jerry_value_t err_val = jerry_value_copy (obj_val); obj_val = jerry_exception_value (err_val, true); TEST_ASSERT (obj_val != err_val); jerry_value_free (err_val); jerry_value_free (obj_val); const char pterodactylus[] = "Pterodactylus"; const size_t pterodactylus_size = sizeof (pterodactylus) - 1; jerry_value_t str = jerry_string_sz (pterodactylus); jerry_value_t error = jerry_throw_value (str, true); str = jerry_exception_value (error, true); compare_str (str, pterodactylus, pterodactylus_size); jerry_value_free (str); str = jerry_string_sz (pterodactylus); error = jerry_throw_value (str, false); jerry_value_free (str); str = jerry_exception_value (error, true); compare_str (str, pterodactylus, pterodactylus_size); jerry_value_free (str); str = jerry_string_sz (pterodactylus); error = jerry_throw_abort (str, true); str = jerry_exception_value (error, true); compare_str (str, pterodactylus, pterodactylus_size); jerry_value_free (str); str = jerry_string_sz (pterodactylus); error = jerry_throw_abort (str, false); jerry_value_free (str); str = jerry_exception_value (error, true); compare_str (str, pterodactylus, pterodactylus_size); jerry_value_free (str); str = jerry_string_sz (pterodactylus); error = jerry_throw_value (str, true); error = jerry_throw_abort (error, true); TEST_ASSERT (jerry_value_is_abort (error)); str = jerry_exception_value (error, true); compare_str (str, pterodactylus, pterodactylus_size); jerry_value_free (str); str = jerry_string_sz (pterodactylus); error = jerry_throw_value (str, true); jerry_value_t error2 = jerry_throw_abort (error, false); TEST_ASSERT (jerry_value_is_abort (error2)); jerry_value_free (error); str = jerry_exception_value (error2, true); compare_str (str, pterodactylus, pterodactylus_size); jerry_value_free (str); double test_num = 3.1415926; jerry_value_t num = jerry_number (test_num); jerry_value_t num2 = jerry_throw_value (num, false); TEST_ASSERT (jerry_value_is_exception (num2)); jerry_value_free (num); num2 = jerry_exception_value (num2, true); TEST_ASSERT (jerry_value_as_number (num2) == test_num); jerry_value_free (num2); num = jerry_number (test_num); num2 = jerry_throw_value (num, true); TEST_ASSERT (jerry_value_is_exception (num2)); num2 = jerry_exception_value (num2, true); TEST_ASSERT (jerry_value_as_number (num2) == test_num); jerry_value_free (num2); num = jerry_number (test_num); num2 = jerry_throw_value (num, false); TEST_ASSERT (jerry_value_is_exception (num2)); jerry_value_free (num); jerry_value_t num3 = jerry_throw_value (num2, false); TEST_ASSERT (jerry_value_is_exception (num3)); jerry_value_free (num2); num2 = jerry_exception_value (num3, true); TEST_ASSERT (jerry_value_as_number (num2) == test_num); jerry_value_free (num2); num = jerry_number (test_num); num2 = jerry_throw_value (num, true); TEST_ASSERT (jerry_value_is_exception (num2)); num3 = jerry_throw_value (num2, true); TEST_ASSERT (jerry_value_is_exception (num3)); num2 = jerry_exception_value (num3, true); TEST_ASSERT (jerry_value_as_number (num2) == test_num); jerry_value_free (num2); num = jerry_number (test_num); error = jerry_throw_abort (num, true); TEST_ASSERT (jerry_value_is_abort (error)); num2 = jerry_throw_value (error, true); TEST_ASSERT (jerry_value_is_exception (num2)); num = jerry_exception_value (num2, true); TEST_ASSERT (jerry_value_as_number (num) == test_num); jerry_value_free (num); num = jerry_number (test_num); error = jerry_throw_abort (num, false); jerry_value_free (num); TEST_ASSERT (jerry_value_is_abort (error)); num2 = jerry_throw_value (error, true); TEST_ASSERT (jerry_value_is_exception (num2)); num = jerry_exception_value (num2, true); TEST_ASSERT (jerry_value_as_number (num) == test_num); jerry_value_free (num); num = jerry_number (test_num); error = jerry_throw_abort (num, true); TEST_ASSERT (jerry_value_is_abort (error)); num2 = jerry_throw_value (error, false); jerry_value_free (error); TEST_ASSERT (jerry_value_is_exception (num2)); num = jerry_exception_value (num2, true); TEST_ASSERT (jerry_value_as_number (num) == test_num); jerry_value_free (num); num = jerry_number (test_num); error = jerry_throw_abort (num, false); jerry_value_free (num); TEST_ASSERT (jerry_value_is_abort (error)); num2 = jerry_throw_value (error, false); jerry_value_free (error); TEST_ASSERT (jerry_value_is_exception (num2)); num = jerry_exception_value (num2, true); TEST_ASSERT (jerry_value_as_number (num) == test_num); jerry_value_free (num); jerry_value_t value = jerry_number (42); value = jerry_exception_value (value, true); jerry_value_free (value); value = jerry_number (42); jerry_value_t value2 = jerry_exception_value (value, false); jerry_value_free (value); jerry_value_free (value2); value = jerry_number (42); error = jerry_throw_value (value, true); error = jerry_throw_value (error, true); jerry_value_free (error); value = jerry_number (42); error = jerry_throw_abort (value, true); error = jerry_throw_abort (error, true); jerry_value_free (error); value = jerry_number (42); error = jerry_throw_value (value, true); error2 = jerry_throw_value (error, false); jerry_value_free (error); jerry_value_free (error2); value = jerry_number (42); error = jerry_throw_abort (value, true); error2 = jerry_throw_abort (error, false); jerry_value_free (error); jerry_value_free (error2); jerry_cleanup (); } /* main */
dbatyai/jerryscript
tests/unit-core/test-api-set-and-clear-error-flag.c
C
apache-2.0
6,865
.player-bar { position: fixed; bottom: 0; left: 0; right: 0; height: 150px; background: rgba(255, 255, 255, 0.3); z-index: 100; } .player-bar a { font-size: 1.1rem; vertical-align: middle; } .player-bar a, .player-bar a:hover { color: white; cursor: pointer; text-decoration: none; } .player-bar .container { display: table; padding: 0; width: 90%; min-height: 100%; } .player-bar .control-group { display: table-cell; vertical-align: middle; } .player-bar .main-controls { width: 25%; text-align: left; padding-right: 1rem; } .player-bar .main-controls .previous { margin-right: 16.5%; } .player-bar .main-controls .play-pause { margin-right: 15%; font-size: 1.6rem; } .player-bar .currently-playing { width: 50%; text-align: center; position: relative; } .player-bar .currently-playing .song-name, .player-bar .currently-playing .artist-name, .player-bar .currently-playing .artist-song-mobile { text-align: center; font-size: 0.75rem; margin: 0; position: absolute; width: 100%; font-weight: 300; } .player-bar .currently-playing .song-name, .player-bar .currently-playing .artist-song-mobile { top: 1.1rem; } .player-bar .currently-playing .artist-name { bottom: 1.1rem; } .player-bar .currently-playing .artist-song-mobile { display: none; } .seek-control { position: relative; font-size: 0.8rem; } .seek-control .current-time { position: absolute; top: 0.5rem; } .seek-control .total-time { position: absolute; right: 0; top: 0.5rem; } .seek-bar { height: 0.25rem; background: rgba(255, 255, 255, 0.3); border-radius: 2px; position: relative; cursor: pointer; } .seek-bar .fill { background: white; width: 0%; height: 0.25rem; border-radius: 2px; } .seek-bar .thumb { position: absolute; height: 0.5rem; widows: 0.5rem; background: white; left: 36%; top: 50%; margin-left: -0.25rem; margin-top: -0.25rem; border-radius: 50%; cursor: pointer; -webkit-transition: width 100ms ease-in-out, height 100ms ease-in-out, margin-top 100ms ease-in-out, margin-left 100ms ease-in-out; -moz-transition: width 100ms ease-in-out, height 100ms ease-in-out, margin-top 100ms ease-in-out, margin-left 100ms ease-in-out; transition: width 100ms ease-in-out, height 100ms ease-in-out, margin-top 100ms ease-in-out, margin-left 100ms ease-in-out; } .seek-bar:hover .thumb { width: 1.1rem; height: 1.1rem; margin-top: -0.5rem; margin-left: -0.5rem; } .player-bar .volume { width: 25%; text-align: right; } .player-bar .volume .icon { font-size: 1.1rem; display: inline-block; vertical-align: middle; } .player-bar .volume .seek-bar { display: inline-block; width: 5.75rem; vertical-align: middle; } @media (max-width: 40rem) { .player-bar { padding: 1rem; background: rgba(0,0,0,0.6); } .player-bar .main-controls, .player-bar .currently-playing, .player-bar .volume { display: inline-block; margin: 0 auto; padding: 0; width: 100%; text-align: center; } .player-bar .main-controls, .player-bar .volume { min-height: 3.5rem; } .player-bar .currently-playing { min-height: 2.5rem; } .player-bar .artist-name, .player-bar .song-name { display: none; } .player-bar .artist-song-mobile { display: block; } }
StaciaHoov/bloc-jam-angular
dist/styles/player_bar.css
CSS
apache-2.0
3,576
/* * Copyright (c) 1998-2003 by The FlexiProvider Group, * Technische Universitaet Darmstadt * * For conditions of usage and distribution please refer to the * file COPYING in the root directory of this package. * */ package de.flexiprovider.core.mersa; import codec.asn1.ASN1Integer; import codec.asn1.ASN1Null; import codec.asn1.ASN1ObjectIdentifier; import codec.asn1.ASN1Sequence; import codec.asn1.ASN1Type; import de.flexiprovider.common.math.FlexiBigInt; import de.flexiprovider.common.util.ASN1Tools; import de.flexiprovider.core.rsa.RSAPrivateCrtKey; /** * This class implements the MeRSAPrivateKey interface. * * @author Erik Dahmen * @author Paul Nguentcheu * @see de.flexiprovider.core.mersa.MeRSAKeyPairGenerator */ public class MeRSAPrivateKey extends RSAPrivateCrtKey { /** * The exponent k. */ private FlexiBigInt k; /** * The number e<sup><font size="-2">-1</font></sup> mod p. */ private FlexiBigInt eInvP; /** * Generate a new MeRSA private key. * * @param n * the number n = p*q; * @param e * the public exponent e. * @param d * the private exponent d. * @param p * the prime p. * @param q * the prime q. * @param dP * the number d mod (p-1). * @param dQ * the number d mod (q-1). * @param crtCoeff * the coefficient for MeRSA decryption with the CRT. * @param k * the exponent k. * @param eInvP * the inverse of the public exponent modulo p. * @see MeRSAKeyPairGenerator */ protected MeRSAPrivateKey(FlexiBigInt n, FlexiBigInt e, FlexiBigInt d, FlexiBigInt p, FlexiBigInt q, FlexiBigInt dP, FlexiBigInt dQ, FlexiBigInt crtCoeff, FlexiBigInt k, FlexiBigInt eInvP) { super(n, e, d, p, q, dP, dQ, crtCoeff); this.eInvP = eInvP; this.crtCoeff = crtCoeff; this.k = k; } /** * Construct an MeRSAPrivateKey out of the given key specification. * * @param keySpec * the key specification */ protected MeRSAPrivateKey(MeRSAPrivateKeySpec keySpec) { this(keySpec.getN(), keySpec.getE(), keySpec.getD(), keySpec.getP(), keySpec.getQ(), keySpec.getDp(), keySpec.getDq(), keySpec .getCRTCoeff(), keySpec.getK(), keySpec.getEInvP()); } /** * @return the exponent k */ public FlexiBigInt getK() { return k; } /** * @return the inverse of the public exponent modulo p */ public FlexiBigInt getEInvP() { return eInvP; } /** * Compare this key with another object. * * @param other * the other object * @return the result of the comparison */ public boolean equals(Object other) { if (other == null || !(other instanceof MeRSAPrivateKey)) { return false; } MeRSAPrivateKey otherKey = (MeRSAPrivateKey) other; if (n.equals(otherKey.n) && p.equals(otherKey.p) && q.equals(otherKey.q) && d.equals(otherKey.d) && e.equals(otherKey.e) && dP.equals(otherKey.dP) && dQ.equals(otherKey.dQ) && k.equals(otherKey.k) && eInvP.equals(otherKey.eInvP) && crtCoeff.equals(otherKey.crtCoeff)) { return true; } return false; } /** * @return a human readable form of the key */ public String toString() { String out = ""; out += "modulus n: 0x" + n.toString(16) + "\n"; out += "public exponent e: 0x" + e.toString(16) + "\n"; out += "exponent k: 0x" + k.toString(16) + "\n"; out += "private exponent d: 0x" + d.toString(16) + "\n"; out += "prime P: 0x" + p.toString(16) + "\n"; out += "prime Q: 0x" + q.toString(16) + "\n"; out += "prime exponent P: 0x" + dP.toString(16) + "\n"; out += "prime exponent Q: 0x" + dQ.toString(16) + "\n"; out += "inverse of e mod p: 0x" + dQ.toString(16) + "\n"; out += "crt coefficient: 0x" + crtCoeff.toString(16) + "\n"; return out; } public int hashCode() { return n.hashCode() + e.hashCode() + k.hashCode() + d.hashCode() + p.hashCode() + q.hashCode() + dP.hashCode() + dQ.hashCode() + eInvP.hashCode() + +crtCoeff.hashCode(); } /** * @return the OID to encode in the SubjectPublicKeyInfo structure */ protected ASN1ObjectIdentifier getOID() { // TODO assign correct OID return new ASN1ObjectIdentifier(); } /** * @return the algorithm parameters to encode in the SubjectPublicKeyInfo * structure */ protected ASN1Type getAlgParams() { return new ASN1Null(); } /** * @return the keyData to encode in the SubjectPublicKeyInfo structure */ protected byte[] getKeyData() { ASN1Sequence keyData = new ASN1Sequence(); keyData.add(new ASN1Integer(0)); keyData.add(ASN1Tools.createInteger(n)); keyData.add(ASN1Tools.createInteger(e)); keyData.add(ASN1Tools.createInteger(k)); keyData.add(ASN1Tools.createInteger(d)); keyData.add(ASN1Tools.createInteger(p)); keyData.add(ASN1Tools.createInteger(q)); keyData.add(ASN1Tools.createInteger(dP)); keyData.add(ASN1Tools.createInteger(dQ)); keyData.add(ASN1Tools.createInteger(eInvP)); keyData.add(ASN1Tools.createInteger(crtCoeff)); return ASN1Tools.derEncode(keyData); } }
besom/bbossgroups-mvn
bboss_security/src/main/java/de/flexiprovider/core/mersa/MeRSAPrivateKey.java
Java
apache-2.0
5,423
/** * Copyright 2011-2019 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.vocabulary.operator; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.asakusafw.vocabulary.flow.processor.PartialAggregation; import com.asakusafw.vocabulary.model.Key; //TODO i18n /** * 畳み込み演算子を表すメソッドに付与する注釈。 * <p> * この演算子は、単一の入力を特定の項目でグループ化し、グループ内で畳みこんだ結果を出力する。 * </p> * <p> * 同じモデル型の二つの引数を取り、メソッドの本体で第一引数の内容を変更するプログラムを記述する。 * また、第一引数には{@link Key}注釈を指定し、 * {@link Key#group() グループ化}のためのプロパティ名を指定する必要がある * ({@link Key#order() 整列}のためのプロパティ名および整列方向は無視される)。 * </p> * <p> * 引数には同メソッドで宣言した型変数を利用できる。 * </p> * <p> * この注釈を付与するメソッドは、一般的な演算子メソッドの要件の他に、 * 下記の要件をすべて満たす必要がある。 * </p> * <ul> * <li> 返戻型に{@code void}を指定する </li> * <li> 以下の引数を宣言する * <ul> * <li> * ここまでの畳み込みの結果を表すモデルオブジェクト型の引数、 * さらに{@link Key}注釈でグループ化のための情報を指定する * </li> * <li> * 畳み込み対象のモデルオブジェクト型の引数 * </li> * </ul> * </li> * <li> 以下の修飾子を付与する * <ul> * <li> {@code abstract} </li> * </ul> * </li> * <li> 以下の修飾子を付与する * <ul> * <li> (特になし) </li> * </ul> * </li> * <li> 以下の修飾子は付与しない * <ul> * <li> {@code abstract} </li> * </ul> * </li> * </ul> * <p> * 例: * </p> <pre><code> /** &#42; レコードHogeを畳み込む。 &#42; &#64;param left ここまでの畳み込みの結果 &#42; &#64;param right 畳み込む対象 &#42;&#47; &#64;Fold public void fold(&#64;Key(group = &quot;name&quot;) Hoge left, Hoge right) { // &#64;Summarizeを手動で行うイメージで、leftに次々とrightを加える left.setValue(left.getValue() + right.getValue()); } </code></pre> */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Fold { /** * The input port number. */ int ID_INPUT = 0; /** * The output port number. */ int ID_OUTPUT = 0; /** * The default input port name. */ String INPUT = "in"; //$NON-NLS-1$ /** * 部分集約の設定。 * <p> * この演算子で部分集約を可能にした場合、現在はメソッド内でフレームワークAPIを利用できなくなる。 * </p> * @since 0.2.0 */ PartialAggregation partialAggregation() default PartialAggregation.DEFAULT; /** * The default output port name. */ String outputPort() default "out"; }
akirakw/asakusafw
dsl-project/asakusa-dsl-vocabulary/src/main/java/com/asakusafw/vocabulary/operator/Fold.java
Java
apache-2.0
3,844
<html devsite><head> <title>Diretas dengan spam</title> <meta name="project_path" value="/web/fundamentals/_project.yaml"/> <meta name="book_path" value="/web/fundamentals/_book.yaml"/> <meta name="devsite_continuous_localization_fp" value="cgvbEhX8evRWhUnr+VH8xDCQ+wwt7IRCyUlOF1mn5e9caMUNwesLeYoX6Z1IYkyCybqRdNPFbA4TsWS5Nsl0oiRuWuQSMrx9OVAMP/A/1H4cVJCDfJVTk2wdQAyer+PT"></meta><meta name="devsite_continuous_localization_translatable_html_file_type" value="source"></meta></head> <body> <p>Langkah ini berkaitan dengan peretasan situs untuk menghosting spam, yang biasanya menampilkan peringatan <em>"Situs ini mungkin diretas"</em> di hasil penelusuran. Ini adalah salah satu langkah terpanjang dalam proses pemulihan. Pada langkah ini, Anda akan mengompilasi daftar file yang dirusak di situs. Anda akan menggunakan daftar ini pada langkah berikutnya, <a href="clean_site">Membersihkan dan memelihara situs</a>.</p> <p>Jika situs Anda diserang dengan malware dan ditandai dengan peringatan <em>"Situs ini dapat membahayakan komputer Anda"</em> di hasil penelusuran, lihat artikel yang sesuai, <a href="hacked_with_malware">Menaksir kerusakan akibat malware (Diretas dengan malware)</a>.</p> <div class="video-wrapper"> <iframe class="devsite-embedded-youtube-video" allowfullscreen="" data-autohide="1" data-showinfo="0" data-video-id="lG5lOix9b9k" frameborder="0" l10n-attrs-original-order="class,data-video-id,data-autohide,data-showinfo,frameborder,allowfullscreen"> </iframe> </div> <p>Karena kampanye peretasan tertentu memengaruhi ratusan dan ribuan situs dengan cara yang mirip, situs dapat dibersihkan melalui serangkaian langkah spesifik. Jika salah satu dari kampanye peretasan ini menggambarkan peretasan di situs Anda, klik untuk membaca panduannya. </p><ul> <li><a href="/web/fundamentals/security/hacked/fixing_the_japanese_keyword_hack"> Memperbaiki Peretasan Kata Kunci Jepang</a></li> <li><a href="/web/fundamentals/security/hacked/fixing_the_gibberish_hack"> Memperbaiki Peretasan Nonsens</a></li> <li><a href="/web/fundamentals/security/hacked/fixing_the_cloaked_keywords_hack"> Memperbaiki Peretasan Penyelubungan Kata Kunci dan Link</a></li> </ul> <p></p> <h2>Langkah berikutnya</h2> <p>Langkah selanjutnya dalam proses ini adalah <a href="vulnerability">Mengidentifikasi kerentanan</a>.</p> </body></html>
sonyarianto/WebFundamentals
src/content/id/fundamentals/security/hacked/hacked_with_spam.html
HTML
apache-2.0
2,411
#include "source/common/config/well_known_names.h" #include "absl/strings/str_replace.h" namespace Envoy { namespace Config { namespace { const absl::string_view TAG_VALUE_REGEX = R"([^\.]+)"; // To allow for more readable regular expressions to be declared below, and to // reduce duplication, define a few common pattern substitutions for regex // segments. std::string expandRegex(const std::string& regex) { return absl::StrReplaceAll( regex, {// Regex to look for either IPv4 or IPv6 addresses plus port number after underscore. {"<ADDRESS>", R"((?:(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[[a-fA-F_\d]+\])_\d+))"}, // Cipher names can contain alphanumerics with dashes and // underscores. {"<CIPHER>", R"([\w-]+)"}, // A generic name can contain any character except dots. {"<TAG_VALUE>", TAG_VALUE_REGEX}, // Route names may contain dots in addition to alphanumerics and // dashes with underscores. {"<ROUTE_CONFIG_NAME>", R"([\w-\.]+)"}}); } const Regex::CompiledGoogleReMatcher& validTagValueRegex() { CONSTRUCT_ON_FIRST_USE(Regex::CompiledGoogleReMatcher, absl::StrCat("^", TAG_VALUE_REGEX, "$"), false); } } // namespace bool doesTagNameValueMatchInvalidCharRegex(absl::string_view name) { return validTagValueRegex().match(name); } TagNameValues::TagNameValues() { // Note: the default regexes are defined below in the order that they will typically be matched // (see the TagExtractor class definition for an explanation of the iterative matching process). // This ordering is roughly from most specific to least specific. Despite the fact that these // regexes are defined with a particular ordering in mind, users can customize the ordering of the // processing of the default tag extraction regexes and include custom tags with regexes via the // bootstrap configuration. Because of this flexibility, these regexes are designed to not // interfere with one another no matter the ordering. They are tested in forward and reverse // ordering to ensure they will be safe in most ordering configurations. // To give a more user-friendly explanation of the intended behavior of each regex, each is // preceded by a comment with a simplified notation to explain what the regex is designed to // match: // - The text that the regex is intended to capture will be enclosed in (). // - Other default tags that are expected to exist in the name (and may or may not have been // removed before this regex has been applied) are enclosed in []. // - Stand-ins for a variable segment of the name (including inside capture groups) will be // enclosed in <>. // - Typical * notation will be used to denote an arbitrary set of characters. // *_rq(_<response_code>) addRe2(RESPONSE_CODE, R"(_rq(_(\d{3}))$)", "_rq_"); // *_rq_(<response_code_class>)xx addRe2(RESPONSE_CODE_CLASS, R"(_rq_((\d))xx$)", "_rq_"); // http.[<stat_prefix>.]dynamodb.table.[<table_name>.]capacity.[<operation_name>.](__partition_id=<last_seven_characters_from_partition_id>) addRe2( DYNAMO_PARTITION_ID, R"(^http\.<TAG_VALUE>\.dynamodb\.table\.<TAG_VALUE>\.capacity\.<TAG_VALUE>(\.__partition_id=(\w{7}))$)", ".dynamodb.table."); // http.[<stat_prefix>.]dynamodb.operation.(<operation_name>.)* or // http.[<stat_prefix>.]dynamodb.table.[<table_name>.]capacity.(<operation_name>.)[<partition_id>] addRe2( DYNAMO_OPERATION, R"(^http\.<TAG_VALUE>\.dynamodb.(?:operation|table\.<TAG_VALUE>\.capacity)(\.(<TAG_VALUE>))(?:\.|$))", ".dynamodb."); // mongo.[<stat_prefix>.]collection.[<collection>.]callsite.(<callsite>.)query.* addTokenized(MONGO_CALLSITE, "mongo.*.collection.*.callsite.$.query.**"); // http.[<stat_prefix>.]dynamodb.table.(<table_name>.)* or // http.[<stat_prefix>.]dynamodb.error.(<table_name>.)* addRe2(DYNAMO_TABLE, R"(^http\.<TAG_VALUE>\.dynamodb.(?:table|error)\.((<TAG_VALUE>)\.))", ".dynamodb."); // mongo.[<stat_prefix>.]collection.(<collection>.)query.* addTokenized(MONGO_COLLECTION, "mongo.*.collection.$.**.query.*"); // mongo.[<stat_prefix>.]cmd.(<cmd>.)* addTokenized(MONGO_CMD, "mongo.*.cmd.$.**"); // cluster.[<route_target_cluster>.]grpc.[<grpc_service>.](<grpc_method>.)* addTokenized(GRPC_BRIDGE_METHOD, "cluster.*.grpc.*.$.**"); // http.[<stat_prefix>.]user_agent.(<user_agent>.)* addTokenized(HTTP_USER_AGENT, "http.*.user_agent.$.**"); // vhost.[<virtual host name>.]vcluster.(<virtual_cluster_name>.)* addTokenized(VIRTUAL_CLUSTER, "vhost.*.vcluster.$.**"); // http.[<stat_prefix>.]fault.(<downstream_cluster>.)* addTokenized(FAULT_DOWNSTREAM_CLUSTER, "http.*.fault.$.**"); // listener.[<address>.]ssl.cipher.(<cipher>) addRe2(SSL_CIPHER, R"(^listener\..*?\.ssl\.cipher(\.(<CIPHER>))$)"); // cluster.[<cluster_name>.]ssl.ciphers.(<cipher>) addRe2(SSL_CIPHER_SUITE, R"(^cluster\.<TAG_VALUE>\.ssl\.ciphers(\.(<CIPHER>))$)", ".ssl.ciphers."); // cluster.[<route_target_cluster>.]grpc.(<grpc_service>.)* addTokenized(GRPC_BRIDGE_SERVICE, "cluster.*.grpc.$.**"); // tcp.(<stat_prefix>.)* addTokenized(TCP_PREFIX, "tcp.$.**"); // udp.(<stat_prefix>.)* addTokenized(UDP_PREFIX, "udp.$.**"); // auth.clientssl.(<stat_prefix>.)* addTokenized(CLIENTSSL_PREFIX, "auth.clientssl.$.**"); // ratelimit.(<stat_prefix>.)* addTokenized(RATELIMIT_PREFIX, "ratelimit.$.**"); // cluster.(<cluster_name>.)* addTokenized(CLUSTER_NAME, "cluster.$.**"); // listener.[<address>.]http.(<stat_prefix>.)* // The <address> part can be anything here (.*?) for the sake of a simpler // internal state of the regex which performs better. addRe2(HTTP_CONN_MANAGER_PREFIX, R"(^listener\..*?\.http\.((<TAG_VALUE>)\.))", ".http."); // http.(<stat_prefix>.)* addTokenized(HTTP_CONN_MANAGER_PREFIX, "http.$.**"); // listener.(<address>.)* addRe2(LISTENER_ADDRESS, R"(^listener\.((<ADDRESS>)\.))"); // vhost.(<virtual host name>.)* addTokenized(VIRTUAL_HOST, "vhost.$.**"); // mongo.(<stat_prefix>.)* addTokenized(MONGO_PREFIX, "mongo.$.**"); // http.[<stat_prefix>.]rds.(<route_config_name>.)<base_stat> // Note: <route_config_name> can contain dots thus we have to maintain full // match. addRe2(RDS_ROUTE_CONFIG, R"(^http\.<TAG_VALUE>\.rds\.((<ROUTE_CONFIG_NAME>)\.)\w+?$)", ".rds."); // listener_manager.(worker_<id>.)* addRe2(WORKER_ID, R"(^listener_manager\.((worker_\d+)\.))", "listener_manager.worker_"); } void TagNameValues::addRe2(const std::string& name, const std::string& regex, const std::string& substr) { descriptor_vec_.emplace_back(Descriptor{name, expandRegex(regex), substr, Regex::Type::Re2}); } void TagNameValues::addTokenized(const std::string& name, const std::string& tokens) { tokenized_descriptor_vec_.emplace_back(TokenizedDescriptor{name, tokens}); } } // namespace Config } // namespace Envoy
envoyproxy/envoy
source/common/config/well_known_names.cc
C++
apache-2.0
7,034
package integration_test import ( "fmt" "regexp" "runtime" "strings" . "github.com/onsi/ginkgo" "github.com/onsi/ginkgo/types" . "github.com/onsi/gomega" "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" ) var _ = Describe("Running Specs", func() { var pathToTest string isWindows := (runtime.GOOS == "windows") denoter := "•" if isWindows { denoter = "+" } Context("when pointed at the current directory", func() { BeforeEach(func() { pathToTest = tmpPath("ginkgo") copyIn("passing_ginkgo_tests", pathToTest) }) It("should run the tests in the working directory", func() { session := startGinkgo(pathToTest, "--noColor") Eventually(session).Should(gexec.Exit(0)) output := string(session.Out.Contents()) Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) Ω(output).Should(ContainSubstring(strings.Repeat(denoter, 4))) Ω(output).Should(ContainSubstring("SUCCESS! -- 4 Passed")) Ω(output).Should(ContainSubstring("Test Suite Passed")) }) }) Context("when passed an explicit package to run", func() { BeforeEach(func() { pathToTest = tmpPath("ginkgo") copyIn("passing_ginkgo_tests", pathToTest) }) It("should run the ginkgo style tests", func() { session := startGinkgo(tmpDir, "--noColor", pathToTest) Eventually(session).Should(gexec.Exit(0)) output := string(session.Out.Contents()) Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) Ω(output).Should(ContainSubstring(strings.Repeat(denoter, 4))) Ω(output).Should(ContainSubstring("SUCCESS! -- 4 Passed")) Ω(output).Should(ContainSubstring("Test Suite Passed")) }) }) Context("when passed a number of packages to run", func() { BeforeEach(func() { pathToTest = tmpPath("ginkgo") otherPathToTest := tmpPath("other") copyIn("passing_ginkgo_tests", pathToTest) copyIn("more_ginkgo_tests", otherPathToTest) }) It("should run the ginkgo style tests", func() { session := startGinkgo(tmpDir, "--noColor", "--succinct=false", "ginkgo", "./other") Eventually(session).Should(gexec.Exit(0)) output := string(session.Out.Contents()) Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) Ω(output).Should(ContainSubstring("Running Suite: More_ginkgo_tests Suite")) Ω(output).Should(ContainSubstring("Test Suite Passed")) }) }) Context("when passed a number of packages to run, some of which have focused tests", func() { BeforeEach(func() { pathToTest = tmpPath("ginkgo") otherPathToTest := tmpPath("other") focusedPathToTest := tmpPath("focused") copyIn("passing_ginkgo_tests", pathToTest) copyIn("more_ginkgo_tests", otherPathToTest) copyIn("focused_fixture", focusedPathToTest) }) It("should exit with a status code of 2 and explain why", func() { session := startGinkgo(tmpDir, "--noColor", "--succinct=false", "-r") Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) output := string(session.Out.Contents()) Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) Ω(output).Should(ContainSubstring("Running Suite: More_ginkgo_tests Suite")) Ω(output).Should(ContainSubstring("Test Suite Passed")) Ω(output).Should(ContainSubstring("Detected Programmatic Focus - setting exit status to %d", types.GINKGO_FOCUS_EXIT_CODE)) }) }) Context("when told to skipPackages", func() { BeforeEach(func() { pathToTest = tmpPath("ginkgo") otherPathToTest := tmpPath("other") focusedPathToTest := tmpPath("focused") copyIn("passing_ginkgo_tests", pathToTest) copyIn("more_ginkgo_tests", otherPathToTest) copyIn("focused_fixture", focusedPathToTest) }) It("should skip packages that match the list", func() { session := startGinkgo(tmpDir, "--noColor", "--skipPackage=other,focused", "-r") Eventually(session).Should(gexec.Exit(0)) output := string(session.Out.Contents()) Ω(output).Should(ContainSubstring("Passing_ginkgo_tests Suite")) Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite")) Ω(output).ShouldNot(ContainSubstring("Focused_fixture Suite")) Ω(output).Should(ContainSubstring("Test Suite Passed")) }) Context("when all packages are skipped", func() { It("should not run anything, but still exit 0", func() { session := startGinkgo(tmpDir, "--noColor", "--skipPackage=other,focused,ginkgo", "-r") Eventually(session).Should(gexec.Exit(0)) output := string(session.Out.Contents()) Ω(output).Should(ContainSubstring("All tests skipped!")) Ω(output).ShouldNot(ContainSubstring("Passing_ginkgo_tests Suite")) Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite")) Ω(output).ShouldNot(ContainSubstring("Focused_fixture Suite")) Ω(output).ShouldNot(ContainSubstring("Test Suite Passed")) }) }) }) Context("when there are no tests to run", func() { It("should exit 1", func() { session := startGinkgo(tmpDir, "--noColor", "--skipPackage=other,focused", "-r") Eventually(session).Should(gexec.Exit(1)) output := string(session.Err.Contents()) Ω(output).Should(ContainSubstring("Found no test suites")) }) }) Context("when told to randomizeSuites", func() { BeforeEach(func() { pathToTest = tmpPath("ginkgo") otherPathToTest := tmpPath("other") copyIn("passing_ginkgo_tests", pathToTest) copyIn("more_ginkgo_tests", otherPathToTest) }) It("should skip packages that match the regexp", func() { session := startGinkgo(tmpDir, "--noColor", "--randomizeSuites", "-r", "--seed=2") Eventually(session).Should(gexec.Exit(0)) Ω(session).Should(gbytes.Say("More_ginkgo_tests Suite")) Ω(session).Should(gbytes.Say("Passing_ginkgo_tests Suite")) session = startGinkgo(tmpDir, "--noColor", "--randomizeSuites", "-r", "--seed=3") Eventually(session).Should(gexec.Exit(0)) Ω(session).Should(gbytes.Say("Passing_ginkgo_tests Suite")) Ω(session).Should(gbytes.Say("More_ginkgo_tests Suite")) }) }) Context("when pointed at a package with xunit style tests", func() { BeforeEach(func() { pathToTest = tmpPath("xunit") copyIn("xunit_tests", pathToTest) }) It("should run the xunit style tests", func() { session := startGinkgo(pathToTest) Eventually(session).Should(gexec.Exit(0)) output := string(session.Out.Contents()) Ω(output).Should(ContainSubstring("--- PASS: TestAlwaysTrue")) Ω(output).Should(ContainSubstring("Test Suite Passed")) }) }) Context("when pointed at a package with no tests", func() { BeforeEach(func() { pathToTest = tmpPath("no_tests") copyIn("no_tests", pathToTest) }) It("should fail", func() { session := startGinkgo(pathToTest, "--noColor") Eventually(session).Should(gexec.Exit(1)) Ω(session.Err.Contents()).Should(ContainSubstring("Found no test suites")) }) }) Context("when pointed at a package that fails to compile", func() { BeforeEach(func() { pathToTest = tmpPath("does_not_compile") copyIn("does_not_compile", pathToTest) }) It("should fail", func() { session := startGinkgo(pathToTest, "--noColor") Eventually(session).Should(gexec.Exit(1)) output := string(session.Out.Contents()) Ω(output).Should(ContainSubstring("Failed to compile")) }) }) Context("when running in parallel", func() { BeforeEach(func() { pathToTest = tmpPath("ginkgo") copyIn("passing_ginkgo_tests", pathToTest) }) Context("with a specific number of -nodes", func() { It("should use the specified number of nodes", func() { session := startGinkgo(pathToTest, "--noColor", "-succinct", "-nodes=2") Eventually(session).Should(gexec.Exit(0)) output := string(session.Out.Contents()) Ω(output).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs - 2 nodes [%s]{4} SUCCESS! \d+(\.\d+)?[muµ]s`, regexp.QuoteMeta(denoter))) Ω(output).Should(ContainSubstring("Test Suite Passed")) }) }) Context("with -p", func() { It("it should autocompute the number of nodes", func() { session := startGinkgo(pathToTest, "--noColor", "-succinct", "-p") Eventually(session).Should(gexec.Exit(0)) output := string(session.Out.Contents()) nodes := runtime.NumCPU() if nodes == 1 { Skip("Can't test parallel testings with 1 CPU") } if nodes > 4 { nodes = nodes - 1 } Ω(output).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs - %d nodes [%s]{4} SUCCESS! \d+(\.\d+)?[muµ]s`, nodes, regexp.QuoteMeta(denoter))) Ω(output).Should(ContainSubstring("Test Suite Passed")) }) }) }) Context("when streaming in parallel", func() { BeforeEach(func() { pathToTest = tmpPath("ginkgo") copyIn("passing_ginkgo_tests", pathToTest) }) It("should print output in realtime", func() { session := startGinkgo(pathToTest, "--noColor", "-stream", "-nodes=2") Eventually(session).Should(gexec.Exit(0)) output := string(session.Out.Contents()) Ω(output).Should(ContainSubstring(`[1] Parallel test node 1/2.`)) Ω(output).Should(ContainSubstring(`[2] Parallel test node 2/2.`)) Ω(output).Should(ContainSubstring(`[1] SUCCESS!`)) Ω(output).Should(ContainSubstring(`[2] SUCCESS!`)) Ω(output).Should(ContainSubstring("Test Suite Passed")) }) }) Context("when running recursively", func() { BeforeEach(func() { passingTest := tmpPath("A") otherPassingTest := tmpPath("E") copyIn("passing_ginkgo_tests", passingTest) copyIn("more_ginkgo_tests", otherPassingTest) }) Context("when all the tests pass", func() { Context("with the -r flag", func() { It("should run all the tests (in succinct mode) and succeed", func() { session := startGinkgo(tmpDir, "--noColor", "-r", ".") Eventually(session).Should(gexec.Exit(0)) output := string(session.Out.Contents()) outputLines := strings.Split(output, "\n") Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs [%s]{4} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter))) Ω(outputLines[1]).Should(MatchRegexp(`\[\d+\] More_ginkgo_tests Suite - 2/2 specs [%s]{2} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter))) Ω(output).Should(ContainSubstring("Test Suite Passed")) }) }) Context("with a trailing /...", func() { It("should run all the tests (in succinct mode) and succeed", func() { session := startGinkgo(tmpDir, "--noColor", "./...") Eventually(session).Should(gexec.Exit(0)) output := string(session.Out.Contents()) outputLines := strings.Split(output, "\n") Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs [%s]{4} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter))) Ω(outputLines[1]).Should(MatchRegexp(`\[\d+\] More_ginkgo_tests Suite - 2/2 specs [%s]{2} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter))) Ω(output).Should(ContainSubstring("Test Suite Passed")) }) }) }) Context("when one of the packages has a failing tests", func() { BeforeEach(func() { failingTest := tmpPath("C") copyIn("failing_ginkgo_tests", failingTest) }) It("should fail and stop running tests", func() { session := startGinkgo(tmpDir, "--noColor", "-r") Eventually(session).Should(gexec.Exit(1)) output := string(session.Out.Contents()) outputLines := strings.Split(output, "\n") Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs [%s]{4} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter))) Ω(outputLines[1]).Should(MatchRegexp(`\[\d+\] Failing_ginkgo_tests Suite - 2/2 specs`)) Ω(output).Should(ContainSubstring(fmt.Sprintf("%s Failure", denoter))) Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite")) Ω(output).Should(ContainSubstring("Test Suite Failed")) Ω(output).Should(ContainSubstring("Summarizing 1 Failure:")) Ω(output).Should(ContainSubstring("[Fail] FailingGinkgoTests [It] should fail")) }) }) Context("when one of the packages fails to compile", func() { BeforeEach(func() { doesNotCompileTest := tmpPath("C") copyIn("does_not_compile", doesNotCompileTest) }) It("should fail and stop running tests", func() { session := startGinkgo(tmpDir, "--noColor", "-r") Eventually(session).Should(gexec.Exit(1)) output := string(session.Out.Contents()) outputLines := strings.Split(output, "\n") Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs [%s]{4} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter))) Ω(outputLines[1]).Should(ContainSubstring("Failed to compile C:")) Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite")) Ω(output).Should(ContainSubstring("Test Suite Failed")) }) }) Context("when either is the case, but the keepGoing flag is set", func() { BeforeEach(func() { doesNotCompileTest := tmpPath("B") copyIn("does_not_compile", doesNotCompileTest) failingTest := tmpPath("C") copyIn("failing_ginkgo_tests", failingTest) }) It("should soldier on", func() { session := startGinkgo(tmpDir, "--noColor", "-r", "-keepGoing") Eventually(session).Should(gexec.Exit(1)) output := string(session.Out.Contents()) outputLines := strings.Split(output, "\n") Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs [%s]{4} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter))) Ω(outputLines[1]).Should(ContainSubstring("Failed to compile B:")) Ω(output).Should(MatchRegexp(`\[\d+\] Failing_ginkgo_tests Suite - 2/2 specs`)) Ω(output).Should(ContainSubstring(fmt.Sprintf("%s Failure", denoter))) Ω(output).Should(MatchRegexp(`\[\d+\] More_ginkgo_tests Suite - 2/2 specs [%s]{2} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter))) Ω(output).Should(ContainSubstring("Test Suite Failed")) }) }) }) Context("when told to keep going --untilItFails", func() { BeforeEach(func() { copyIn("eventually_failing", tmpDir) }) It("should keep rerunning the tests, until a failure occurs", func() { session := startGinkgo(tmpDir, "--untilItFails", "--noColor") Eventually(session).Should(gexec.Exit(1)) Ω(session).Should(gbytes.Say("This was attempt #1")) Ω(session).Should(gbytes.Say("This was attempt #2")) Ω(session).Should(gbytes.Say("Tests failed on attempt #3")) //it should change the random seed between each test lines := strings.Split(string(session.Out.Contents()), "\n") randomSeeds := []string{} for _, line := range lines { if strings.Contains(line, "Random Seed:") { randomSeeds = append(randomSeeds, strings.Split(line, ": ")[1]) } } Ω(randomSeeds[0]).ShouldNot(Equal(randomSeeds[1])) Ω(randomSeeds[1]).ShouldNot(Equal(randomSeeds[2])) Ω(randomSeeds[0]).ShouldNot(Equal(randomSeeds[2])) }) }) })
antoni/kubernetes-entrypoint
vendor/github.com/onsi/ginkgo/integration/run_test.go
GO
apache-2.0
15,049
/* * Copyright (c) 2008-2016 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.haulmont.cuba.core.entity; import com.haulmont.chile.core.annotations.MetaClass; import com.haulmont.cuba.core.entity.annotation.UnavailableInSecurityConstraints; import javax.persistence.*; /** * Base class for entities with Long Identity identifier. */ @MappedSuperclass @MetaClass(name = "sys$BaseIdentityIdEntity") @UnavailableInSecurityConstraints public abstract class BaseIdentityIdEntity extends BaseDbGeneratedIdEntity<Long> { private static final long serialVersionUID = 3083677558630811496L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") protected Long id; @Override protected void setDbGeneratedId(Long id) { this.id = id; } @Override protected Long getDbGeneratedId() { return id; } }
cuba-platform/cuba
modules/global/src/com/haulmont/cuba/core/entity/BaseIdentityIdEntity.java
Java
apache-2.0
1,411
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.model.bpmn.impl.instance; import org.camunda.bpm.model.bpmn.instance.Expression; import org.camunda.bpm.model.xml.ModelBuilder; import org.camunda.bpm.model.xml.impl.instance.ModelTypeInstanceContext; import org.camunda.bpm.model.xml.type.ModelElementTypeBuilder; import static org.camunda.bpm.model.bpmn.impl.BpmnModelConstants.BPMN20_NS; import static org.camunda.bpm.model.bpmn.impl.BpmnModelConstants.BPMN_ELEMENT_FROM; /** * The BPMN from element of the BPMN tAssignment type * * @author Sebastian Menski */ public class From extends ExpressionImpl { public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(From.class, BPMN_ELEMENT_FROM) .namespaceUri(BPMN20_NS) .extendsType(Expression.class) .instanceProvider(new ModelElementTypeBuilder.ModelTypeInstanceProvider<From>() { public From newInstance(ModelTypeInstanceContext instanceContext) { return new From(instanceContext); } }); typeBuilder.build(); } public From(ModelTypeInstanceContext instanceContext) { super(instanceContext); } }
filiphr/camunda-bpmn-model
src/main/java/org/camunda/bpm/model/bpmn/impl/instance/From.java
Java
apache-2.0
1,727
/** ****************************************************************************** * @file TIM/TIM_7PWMOutput/stm32f4xx_it.h * @author MCD Application Team * @version V1.4.0 * @date 04-August-2014 * @brief This file contains the headers of the interrupt handlers. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2013 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2 * * 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_IT_H #define __STM32F4xx_IT_H /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void NMI_Handler(void); void HardFault_Handler(void); void MemManage_Handler(void); void BusFault_Handler(void); void UsageFault_Handler(void); void SVC_Handler(void); void DebugMon_Handler(void); void PendSV_Handler(void); void SysTick_Handler(void); #endif /* __STM32F4xx_IT_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
MikeStitt/lowLevelProgrammingByExample
presentations/20170726-meetup-embedded-gr/hal.stm.stm32PeripheralLib/Project/STM32F4xx_StdPeriph_Examples/TIM/TIM_7PWMOutput/stm32f4xx_it.h
C
apache-2.0
2,124
<?php /* * gateways.widget.php * * part of pfSense (https://www.pfsense.org) * Copyright (c) 2008 Seth Mos * Copyright (c) 2004-2016 Rubicon Communications, LLC (Netgate) * All rights reserved. * * originally part of m0n0wall (http://m0n0.ch/wall) * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ $nocsrf = true; require_once("guiconfig.inc"); require_once("pfsense-utils.inc"); require_once("functions.inc"); require_once("/usr/local/www/widgets/include/gateways.inc"); // Compose the table contents and pass it back to the ajax caller if ($_REQUEST && $_REQUEST['ajax']) { print(compose_table_body_contents()); exit; } if ($_POST) { if (!is_array($user_settings["widgets"]["gateways_widget"])) { $user_settings["widgets"]["gateways_widget"] = array(); } if (isset($_POST["display_type"])) { $user_settings["widgets"]["gateways_widget"]["display_type"] = $_POST["display_type"]; } if (is_array($_POST['show'])) { $validNames = array(); $a_gateways = return_gateways_array(); foreach ($a_gateways as $gname => $gateway) { array_push($validNames, $gname); } $user_settings["widgets"]["gateways_widget"]["gatewaysfilter"] = implode(',', array_diff($validNames, $_POST['show'])); } else { $user_settings["widgets"]["gateways_widget"]["gatewaysfilter"] = ""; } save_widget_settings($_SESSION['Username'], $user_settings["widgets"], gettext("Updated gateways widget settings via dashboard.")); header("Location: /"); exit(0); } $widgetperiod = isset($config['widgets']['period']) ? $config['widgets']['period'] * 1000 : 10000; ?> <div class="table-responsive"> <table class="table table-striped table-hover table-condensed"> <thead> <tr> <th><?=gettext("Name")?></th> <th>RTT</th> <th>RTTsd</th> <th><?=gettext("Loss")?></th> <th><?=gettext("Status")?></th> </tr> </thead> <tbody id="gwtblbody"> <?php print(compose_table_body_contents()); ?> </tbody> </table> </div> <!-- close the body we're wrapped in and add a configuration-panel --> </div><div id="widget-<?=$widgetname?>_panel-footer" class="panel-footer collapse"> <form action="/widgets/widgets/gateways.widget.php" method="post" class="form-horizontal"> <div class="form-group"> <label class="col-sm-3 control-label"><?=gettext('Display')?></label> <?php $display_type_gw_ip = "checked"; $display_type_monitor_ip = ""; $display_type_both_ip = ""; if (isset($user_settings["widgets"]["gateways_widget"]["display_type"])) { $selected_radio = $user_settings["widgets"]["gateways_widget"]["display_type"]; if ($selected_radio == "gw_ip") { $display_type_gw_ip = "checked"; $display_type_monitor_ip = ""; $display_type_both_ip = ""; } else if ($selected_radio == "monitor_ip") { $display_type_gw_ip = ""; $display_type_monitor_ip = "checked"; $display_type_both_ip = ""; } else if ($selected_radio == "both_ip") { $display_type_gw_ip = ""; $display_type_monitor_ip = ""; $display_type_both_ip = "checked"; } } ?> <div class="col-sm-6"> <div class="radio"> <label><input name="display_type" type="radio" id="display_type_gw_ip" value="gw_ip" <?=$display_type_gw_ip;?> onchange="updateGatewayDisplays();" /> <?=gettext('Gateway IP')?></label> </div> <div class="radio"> <label><input name="display_type" type="radio" id="display_type_monitor_ip" value="monitor_ip" <?=$display_type_monitor_ip;?> onchange="updateGatewayDisplays();" /><?=gettext('Monitor IP')?></label> </div> <div class="radio"> <label><input name="display_type" type="radio" id="display_type_both_ip" value="both_ip" <?=$display_type_both_ip;?> onchange="updateGatewayDisplays();" /><?=gettext('Both')?></label> </div> </div> </div> <br /> <div class="panel panel-default col-sm-10"> <div class="panel-body"> <div class="table responsive"> <table class="table table-striped table-hover table-condensed"> <thead> <tr> <th><?=gettext("Gateway")?></th> <th><?=gettext("Show")?></th> </tr> </thead> <tbody> <?php $a_gateways = return_gateways_array(); $hiddengateways = explode(",", $user_settings["widgets"]["gateways_widget"]["gatewaysfilter"]); $idx = 0; foreach ($a_gateways as $gname => $gateway): ?> <tr> <td><?=$gname?></td> <td class="col-sm-2"><input id="show[]" name ="show[]" value="<?=$gname?>" type="checkbox" <?=(!in_array($gname, $hiddengateways) ? 'checked':'')?>></td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-3 col-sm-6"> <button type="submit" class="btn btn-primary"><i class="fa fa-save icon-embed-btn"></i><?=gettext('Save')?></button> <button id="showallgateways" type="button" class="btn btn-info"><i class="fa fa-undo icon-embed-btn"></i><?=gettext('All')?></button> </div> </div> </form> <script> //<![CDATA[ function get_gw_stats() { var ajaxRequest; ajaxRequest = $.ajax({ url: "/widgets/widgets/gateways.widget.php", type: "post", data: { ajax: "ajax"} }); // Deal with the results of the above ajax call ajaxRequest.done(function (response, textStatus, jqXHR) { $('#gwtblbody').html(response); // and do it again setTimeout(get_gw_stats, "<?=$widgetperiod?>"); }); } events.push(function(){ $("#showallgateways").click(function() { $("#widget-<?=$widgetname?>_panel-footer [id^=show]").each(function() { $(this).prop("checked", true); }); }); // Start polling for updates some small random number of seconds from now (so that all the widgets don't // hit the server at exactly the same time) setTimeout(get_gw_stats, Math.floor((Math.random() * 10000) + 1000)); }); //]]> </script> <?php function compose_table_body_contents() { global $user_settings; $rtnstr = ''; $a_gateways = return_gateways_array(); $gateways_status = array(); $gateways_status = return_gateways_status(true); if (isset($user_settings["widgets"]["gateways_widget"]["display_type"])) { $display_type = $user_settings["widgets"]["gateways_widget"]["display_type"]; } else { $display_type = "gw_ip"; } $hiddengateways = explode(",", $user_settings["widgets"]["gateways_widget"]["gatewaysfilter"]); $gw_displayed = false; foreach ($a_gateways as $gname => $gateway) { if (in_array($gname, $hiddengateways)) { continue; } $gw_displayed = true; $rtnstr .= "<tr>\n"; $rtnstr .= "<td>\n"; $rtnstr .= htmlspecialchars($gateway['name']) . "<br />"; $rtnstr .= '<div id="gateway' . $counter . '" style="display:inline"><b>'; $monitor_address = ""; $monitor_address_disp = ""; if ($display_type == "monitor_ip" || $display_type == "both_ip") { $monitor_address = $gateway['monitor']; if ($monitor_address != "" && $display_type == "both_ip") { $monitor_address_disp = " (" . $monitor_address . ")"; } else { $monitor_address_disp = $monitor_address; } } $if_gw = ''; // If the user asked to display Gateway IP or both IPs, or asked for just monitor IP but the monitor IP is blank // then find the gateway IP (which is also the monitor IP if the monitor IP was not explicitly set). if ($display_type == "gw_ip" || $display_type == "both_ip" || ($display_type == "monitor_ip" && $monitor_address == "")) { if (is_ipaddr($gateway['gateway'])) { $if_gw = htmlspecialchars($gateway['gateway']); } else { if ($gateway['ipprotocol'] == "inet") { $if_gw = htmlspecialchars(get_interface_gateway($gateway['friendlyiface'])); } if ($gateway['ipprotocol'] == "inet6") { $if_gw = htmlspecialchars(get_interface_gateway_v6($gateway['friendlyiface'])); } } if ($if_gw == "") { $if_gw = "~"; } } if ($monitor_address == $if_gw) { $monitor_address_disp = ""; } $rtnstr .= $if_gw . $monitor_address_disp; unset ($if_gw); unset ($monitor_address); unset ($monitor_address_disp); $counter++; $rtnstr .= "</b>"; $rtnstr .= "</div>\n"; $rtnstr .= "</td>\n"; if ($gateways_status[$gname]) { if (stristr($gateways_status[$gname]['status'], "force_down")) { $online = gettext("Offline (forced)"); $bgcolor = "danger"; // lightcoral } elseif (stristr($gateways_status[$gname]['status'], "down")) { $online = gettext("Offline"); $bgcolor = "danger"; // lightcoral } elseif (stristr($gateways_status[$gname]['status'], "highloss")) { $online = gettext("Packetloss"); $bgcolor = "danger"; // lightcoral } elseif (stristr($gateways_status[$gname]['status'], "loss")) { $online = gettext("Packetloss"); $bgcolor = "warning"; // khaki } elseif (stristr($gateways_status[$gname]['status'], "highdelay")) { $online = gettext("Latency"); $bgcolor = "danger"; // lightcoral } elseif (stristr($gateways_status[$gname]['status'], "delay")) { $online = gettext("Latency"); $bgcolor = "warning"; // khaki } elseif ($gateways_status[$gname]['status'] == "none") { if ($gateways_status[$gname]['monitor_disable'] || ($gateways_status[$gname]['monitorip'] == "none")) { $online = gettext("Online <br/>(unmonitored)"); } else { $online = gettext("Online"); } $bgcolor = "success"; // lightgreen } elseif ($gateways_status[$gname]['status'] == "") { $online = gettext("Pending"); $bgcolor = "info"; // lightgray } } else { $online = gettext("Unknown"); $bgcolor = "info"; // lightblue } $rtnstr .= "<td>" . ($gateways_status[$gname] ? htmlspecialchars($gateways_status[$gname]['delay']) : gettext("Pending")) . "</td>\n"; $rtnstr .= "<td>" . ($gateways_status[$gname] ? htmlspecialchars($gateways_status[$gname]['stddev']) : gettext("Pending")) . "</td>\n"; $rtnstr .= "<td>" . ($gateways_status[$gname] ? htmlspecialchars($gateways_status[$gname]['loss']) : gettext("Pending")) . "</td>\n"; $rtnstr .= '<td class="bg-' . $bgcolor . '">' . $online . "</td>\n"; $rtnstr .= "</tr>\n"; } if (!$gw_displayed) { $rtnstr .= '<tr>'; $rtnstr .= '<td colspan="5">'; if (count($a_gateways)) { $rtnstr .= gettext('All gateways are hidden.'); } else { $rtnstr .= gettext('No gateways found.'); } $rtnstr .= '</td>'; $rtnstr .= '</tr>'; } return($rtnstr); } ?>
brunostein/pfsense
src/usr/local/www/widgets/widgets/gateways.widget.php
PHP
apache-2.0
10,908
#include "main.h" extern "C" { EXPORT void btConstraintSolver_allSolved(btConstraintSolver* obj, const btContactSolverInfo* __unnamed0, btIDebugDraw* __unnamed1); EXPORT btConstraintSolverType btConstraintSolver_getSolverType(btConstraintSolver* obj); EXPORT void btConstraintSolver_prepareSolve(btConstraintSolver* obj, int __unnamed0, int __unnamed1); EXPORT void btConstraintSolver_reset(btConstraintSolver* obj); EXPORT btScalar btConstraintSolver_solveGroup(btConstraintSolver* obj, btCollisionObject** bodies, int numBodies, btPersistentManifold** manifold, int numManifolds, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo* info, btIDebugDraw* debugDrawer, btDispatcher* dispatcher); EXPORT void btConstraintSolver_delete(btConstraintSolver* obj); }
wuyuntao/Nostradamus
NotradamusUnity/Assets/Plugins/BulletUnity/Native/iOS/btConstraintSolver_wrap.h
C
apache-2.0
795
// CHANGE FOR APPS HOSTED IN SUBDIRECTORY FCKRelativePath = ''; // DON'T CHANGE THESE FCKConfig.LinkBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Connector='+FCKRelativePath+'/fckeditor/command'; FCKConfig.ImageBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Image&Connector='+FCKRelativePath+'/fckeditor/command'; FCKConfig.FlashBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Flash&Connector='+FCKRelativePath+'/fckeditor/command'; FCKConfig.LinkUploadURL = FCKRelativePath+'/fckeditor/upload'; FCKConfig.ImageUploadURL = FCKRelativePath+'/fckeditor/upload?Type=Image'; FCKConfig.FlashUploadURL = FCKRelativePath+'/fckeditor/upload?Type=Flash'; FCKConfig.SpellerPagesServerScript = FCKRelativePath+'/fckeditor/check_spelling'; FCKConfig.AllowQueryStringDebug = false; FCKConfig.SpellChecker = 'SpellerPages'; // ONLY CHANGE BELOW HERE FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/silver/'; FCKConfig.ToolbarSets["Simple"] = [ ['Source','-','-','Templates'], ['Cut','Copy','Paste','PasteWord','-','Print','SpellCheck'], ['Undo','Redo','-','Find','Replace','-','SelectAll'], '/', ['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'], ['OrderedList','UnorderedList','-','Outdent','Indent'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'], ['Link','Unlink'], '/', ['Image','Table','Rule','Smiley'], ['FontName','FontSize'], ['TextColor','BGColor'], ['-','About'] ] ;
Fedena/XueDu
vendor/plugins/fckeditor/public/javascripts/fckcustom.js
JavaScript
apache-2.0
1,552