text
stringlengths
2
1.04M
meta
dict
import NavigateClient from "../../../src/background/clients/NavigateClient"; export default class MockNavigateClient implements NavigateClient { historyNext(_tabId: number): Promise<void> { throw new Error("not implemented"); } historyPrev(_tabId: number): Promise<void> { throw new Error("not implemented"); } linkNext(_tabId: number): Promise<void> { throw new Error("not implemented"); } linkPrev(_tabId: number): Promise<void> { throw new Error("not implemented"); } }
{ "content_hash": "d45ac7c2d274dfa6ec86e76287cbc196", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 76, "avg_line_length": 26.789473684210527, "alnum_prop": 0.6915520628683693, "repo_name": "ueokande/vim-vixen", "id": "d9442a428822b3bf3ffce63ebb428bbe3e9d9142", "size": "509", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/background/mock/MockNavigateClient.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "384" }, { "name": "HTML", "bytes": "409" }, { "name": "JavaScript", "bytes": "4716" }, { "name": "TypeScript", "bytes": "695148" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (1.8.0_73) on Sat Mar 05 16:18:23 CET 2016 --> <title>Uses of Interface de.soulan.example.rmi.object.Hello</title> <meta name="date" content="2016-03-05"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface de.soulan.example.rmi.object.Hello"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../de/soulan/example/rmi/object/Hello.html" title="interface in de.soulan.example.rmi.object">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?de/soulan/example/rmi/object/class-use/Hello.html" target="_top">Frames</a></li> <li><a href="Hello.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface de.soulan.example.rmi.object.Hello" class="title">Uses of Interface<br>de.soulan.example.rmi.object.Hello</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../de/soulan/example/rmi/object/Hello.html" title="interface in de.soulan.example.rmi.object">Hello</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#de.soulan.example.rmi.object">de.soulan.example.rmi.object</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="de.soulan.example.rmi.object"> <!-- --> </a> <h3>Uses of <a href="../../../../../../de/soulan/example/rmi/object/Hello.html" title="interface in de.soulan.example.rmi.object">Hello</a> in <a href="../../../../../../de/soulan/example/rmi/object/package-summary.html">de.soulan.example.rmi.object</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../de/soulan/example/rmi/object/package-summary.html">de.soulan.example.rmi.object</a> that implement <a href="../../../../../../de/soulan/example/rmi/object/Hello.html" title="interface in de.soulan.example.rmi.object">Hello</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../de/soulan/example/rmi/object/HelloImpl.html" title="class in de.soulan.example.rmi.object">HelloImpl</a></span></code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../de/soulan/example/rmi/object/Hello.html" title="interface in de.soulan.example.rmi.object">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?de/soulan/example/rmi/object/class-use/Hello.html" target="_top">Frames</a></li> <li><a href="Hello.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "95c52df07df0fd5d166b64327fa758ff", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 330, "avg_line_length": 38.853658536585364, "alnum_prop": 0.6213119899560577, "repo_name": "soulan/JavaRMIWithCustomCA", "id": "3d1829f8699188bdfbef1459795bf4635bfa0048", "size": "6372", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/de/soulan/example/rmi/object/class-use/Hello.html", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "11221" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Libertella platani Ellis & Everh. ### Remarks null
{ "content_hash": "dd70870de644f06c896fb6b12bb9010b", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 33, "avg_line_length": 10.615384615384615, "alnum_prop": 0.7028985507246377, "repo_name": "mdoering/backbone", "id": "a8083ef2798afc83b0cbfc16390c0f8ec2d00e49", "size": "195", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Sordariomycetes/Xylariales/Diatrypaceae/Libertella/Libertella platani/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/** * @file bits.h * @brief Bit vector manipulation */ #ifndef _COAP_BITS_H_ #define _COAP_BITS_H_ #include <stdint.h> /** * Sets the bit @p bit in bit-vector @p vec. This function returns @c 1 if bit * was set or @c -1 on error (i.e. when the given bit does not fit in the * vector). * * @param vec The bit-vector to change. * @param size The size of @p vec in bytes. * @param bit The bit to set in @p vec. * * @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise. */ inline static int bits_setb(uint8_t *vec, size_t size, uint8_t bit) { if (size <= (bit >> 3)) return -1; *(vec + (bit >> 3)) |= (uint8_t)(1 << (bit & 0x07)); return 1; } /** * Clears the bit @p bit from bit-vector @p vec. This function returns @c 1 if * bit was cleared or @c -1 on error (i.e. when the given bit does not fit in * the vector). * * @param vec The bit-vector to change. * @param size The size of @p vec in bytes. * @param bit The bit to clear from @p vec. * * @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise. */ inline static int bits_clrb(uint8_t *vec, size_t size, uint8_t bit) { if (size <= (bit >> 3)) return -1; *(vec + (bit >> 3)) &= (uint8_t)(~(1 << (bit & 0x07))); return 1; } /** * Gets the status of bit @p bit from bit-vector @p vec. This function returns * @c 1 if the bit is set, @c 0 otherwise (even in case of an error). * * @param vec The bit-vector to read from. * @param size The size of @p vec in bytes. * @param bit The bit to get from @p vec. * * @return @c 1 if the bit is set, @c 0 otherwise. */ inline static int bits_getb(const uint8_t *vec, size_t size, uint8_t bit) { if (size <= (bit >> 3)) return -1; return (*(vec + (bit >> 3)) & (1 << (bit & 0x07))) != 0; } #endif /* _COAP_BITS_H_ */
{ "content_hash": "ef087bcd5d5502250d1122db1b3a4fca", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 78, "avg_line_length": 25.6056338028169, "alnum_prop": 0.594059405940594, "repo_name": "gebart/libcoap", "id": "0b269166d57e6a44800d130f0a84aae29257103d", "size": "2016", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "include/coap/bits.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "468761" }, { "name": "C++", "bytes": "1454" }, { "name": "M4", "bytes": "21597" }, { "name": "Makefile", "bytes": "6438" }, { "name": "Shell", "bytes": "3870" } ], "symlink_target": "" }
package ro.robertgabriel.repositories; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; import ro.robertgabriel.entities.AccessLog; import java.util.List; @Repository public interface AccessLogRepository extends PagingAndSortingRepository<AccessLog, String> { List<AccessLog> findAll(); }
{ "content_hash": "9233708c28e6e3d4a2e8fbc3a543963c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 92, "avg_line_length": 28.384615384615383, "alnum_prop": 0.8401084010840109, "repo_name": "vjroby/todo-list", "id": "0c36ab6cfbd08d41b74ab7e4f3cd31e875dfed55", "size": "369", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/ro/robertgabriel/repositories/AccessLogRepository.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "123177" }, { "name": "HTML", "bytes": "41711" }, { "name": "Java", "bytes": "119545" }, { "name": "JavaScript", "bytes": "28474" }, { "name": "Shell", "bytes": "205" } ], "symlink_target": "" }
{-# LANGUAGE CPP #-} module Kind ( -- * Main data type Kind, typeKind, -- ** Predicates on Kinds isLiftedTypeKind, isUnliftedTypeKind, isConstraintKind, returnsTyCon, returnsConstraintKind, isConstraintKindCon, okArrowArgKind, okArrowResultKind, classifiesTypeWithValues, isStarKind, isStarKindSynonymTyCon, isRuntimeRepPolymorphic ) where #include "HsVersions.h" import {-# SOURCE #-} Type ( typeKind, coreViewOneStarKind ) import TyCoRep import TyCon import VarSet ( isEmptyVarSet ) import PrelNames import Util ( (<&&>) ) {- ************************************************************************ * * Functions over Kinds * * ************************************************************************ Note [Kind Constraint and kind *] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The kind Constraint is the kind of classes and other type constraints. The special thing about types of kind Constraint is that * They are displayed with double arrow: f :: Ord a => a -> a * They are implicitly instantiated at call sites; so the type inference engine inserts an extra argument of type (Ord a) at every call site to f. However, once type inference is over, there is *no* distinction between Constraint and *. Indeed we can have coercions between the two. Consider class C a where op :: a -> a For this single-method class we may generate a newtype, which in turn generates an axiom witnessing C a ~ (a -> a) so on the left we have Constraint, and on the right we have *. See Trac #7451. Bottom line: although '*' and 'Constraint' are distinct TyCons, with distinct uniques, they are treated as equal at all times except during type inference. -} isConstraintKind :: Kind -> Bool isConstraintKindCon :: TyCon -> Bool isConstraintKindCon tc = tyConUnique tc == constraintKindTyConKey isConstraintKind (TyConApp tc _) = isConstraintKindCon tc isConstraintKind _ = False -- | Does the given type "end" in the given tycon? For example @k -> [a] -> *@ -- ends in @*@ and @Maybe a -> [a]@ ends in @[]@. returnsTyCon :: Unique -> Type -> Bool returnsTyCon tc_u (ForAllTy _ ty) = returnsTyCon tc_u ty returnsTyCon tc_u (TyConApp tc' _) = tc' `hasKey` tc_u returnsTyCon _ _ = False returnsConstraintKind :: Kind -> Bool returnsConstraintKind = returnsTyCon constraintKindTyConKey -- | Tests whether the given type (which should look like "TYPE ...") has any -- free variables isRuntimeRepPolymorphic :: Kind -> Bool isRuntimeRepPolymorphic k = not $ isEmptyVarSet $ tyCoVarsOfType k -------------------------------------------- -- Kinding for arrow (->) -- Says when a kind is acceptable on lhs or rhs of an arrow -- arg -> res okArrowArgKind, okArrowResultKind :: Kind -> Bool okArrowArgKind = classifiesTypeWithValues <&&> (not . isRuntimeRepPolymorphic) okArrowResultKind = classifiesTypeWithValues ----------------------------------------- -- Subkinding -- The tc variants are used during type-checking, where ConstraintKind -- is distinct from all other kinds -- After type-checking (in core), Constraint and liftedTypeKind are -- indistinguishable -- | Does this classify a type allowed to have values? Responds True to things -- like *, #, TYPE Lifted, TYPE v, Constraint. classifiesTypeWithValues :: Kind -> Bool -- ^ True of any sub-kind of OpenTypeKind classifiesTypeWithValues t | Just t' <- coreViewOneStarKind t = classifiesTypeWithValues t' classifiesTypeWithValues (TyConApp tc [_]) = tc `hasKey` tYPETyConKey classifiesTypeWithValues _ = False -- | Is this kind equivalent to *? isStarKind :: Kind -> Bool isStarKind k | Just k' <- coreViewOneStarKind k = isStarKind k' isStarKind (TyConApp tc [TyConApp ptr_rep []]) = tc `hasKey` tYPETyConKey && ptr_rep `hasKey` ptrRepLiftedDataConKey isStarKind _ = False -- See Note [Kind Constraint and kind *] -- | Is the tycon @Constraint@? isStarKindSynonymTyCon :: TyCon -> Bool isStarKindSynonymTyCon tc = tc `hasKey` constraintKindTyConKey
{ "content_hash": "12db7c80485c8b65f3940787b70bfea6", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 91, "avg_line_length": 35.94117647058823, "alnum_prop": 0.6352583586626139, "repo_name": "vikraman/ghc", "id": "e3cebcd6fbc49cfa28b00de2998b3c9e580551fa", "size": "4321", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "compiler/types/Kind.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "8740" }, { "name": "Batchfile", "bytes": "394" }, { "name": "C", "bytes": "2643957" }, { "name": "C++", "bytes": "29163" }, { "name": "CSS", "bytes": "984" }, { "name": "DTrace", "bytes": "3887" }, { "name": "Emacs Lisp", "bytes": "734" }, { "name": "Game Maker Language", "bytes": "14164" }, { "name": "Gnuplot", "bytes": "103851" }, { "name": "Groff", "bytes": "3840" }, { "name": "HTML", "bytes": "6144" }, { "name": "Haskell", "bytes": "20032983" }, { "name": "Haxe", "bytes": "218" }, { "name": "Logos", "bytes": "128668" }, { "name": "M4", "bytes": "51844" }, { "name": "Makefile", "bytes": "547376" }, { "name": "Objective-C", "bytes": "20042" }, { "name": "Objective-C++", "bytes": "535" }, { "name": "Pascal", "bytes": "114025" }, { "name": "Perl", "bytes": "23067" }, { "name": "Perl6", "bytes": "42455" }, { "name": "PostScript", "bytes": "63" }, { "name": "Python", "bytes": "126185" }, { "name": "Shell", "bytes": "76831" }, { "name": "TeX", "bytes": "667" }, { "name": "Terra", "bytes": "412215" }, { "name": "Yacc", "bytes": "62812" } ], "symlink_target": "" }
// NOTE: This file was generated by the ServiceGenerator. // ---------------------------------------------------------------------------- // API: // Enterprise License Manager API (licensing/v1) // Description: // Licensing API to view and manage license for your domain. // Documentation: // https://developers.google.com/google-apps/licensing/ #if GTLR_BUILT_AS_FRAMEWORK #import "GTLR/GTLRQuery.h" #else #import "GTLRQuery.h" #endif #if GTLR_RUNTIME_VERSION != 3000 #error This file was generated by a different version of ServiceGenerator which is incompatible with this GTLR library source. #endif @class GTLRLicensing_LicenseAssignment; @class GTLRLicensing_LicenseAssignmentInsert; NS_ASSUME_NONNULL_BEGIN /** * Parent class for other Licensing query classes. */ @interface GTLRLicensingQuery : GTLRQuery /** Selector specifying which fields to include in a partial response. */ @property(copy, nullable) NSString *fields; @end /** * Revoke License. * * Method: licensing.licenseAssignments.delete * * Authorization scope(s): * @c kGTLRAuthScopeLicensingAppsLicensing */ @interface GTLRLicensingQuery_LicenseAssignmentsDelete : GTLRLicensingQuery // Previous library name was // +[GTLQueryLicensing queryForLicenseAssignmentsDeleteWithproductId:skuId:userId:] /** Name for product */ @property(copy, nullable) NSString *productId; /** Name for sku */ @property(copy, nullable) NSString *skuId; /** email id or unique Id of the user */ @property(copy, nullable) NSString *userId; /** * Upon successful completion, the callback's object and error parameters will * be nil. This query does not fetch an object. * * Revoke License. * * @param productId Name for product * @param skuId Name for sku * @param userId email id or unique Id of the user * * @returns GTLRLicensingQuery_LicenseAssignmentsDelete */ + (instancetype)queryWithProductId:(NSString *)productId skuId:(NSString *)skuId userId:(NSString *)userId; @end /** * Get license assignment of a particular product and sku for a user * * Method: licensing.licenseAssignments.get * * Authorization scope(s): * @c kGTLRAuthScopeLicensingAppsLicensing */ @interface GTLRLicensingQuery_LicenseAssignmentsGet : GTLRLicensingQuery // Previous library name was // +[GTLQueryLicensing queryForLicenseAssignmentsGetWithproductId:skuId:userId:] /** Name for product */ @property(copy, nullable) NSString *productId; /** Name for sku */ @property(copy, nullable) NSString *skuId; /** email id or unique Id of the user */ @property(copy, nullable) NSString *userId; /** * Fetches a @c GTLRLicensing_LicenseAssignment. * * Get license assignment of a particular product and sku for a user * * @param productId Name for product * @param skuId Name for sku * @param userId email id or unique Id of the user * * @returns GTLRLicensingQuery_LicenseAssignmentsGet */ + (instancetype)queryWithProductId:(NSString *)productId skuId:(NSString *)skuId userId:(NSString *)userId; @end /** * Assign License. * * Method: licensing.licenseAssignments.insert * * Authorization scope(s): * @c kGTLRAuthScopeLicensingAppsLicensing */ @interface GTLRLicensingQuery_LicenseAssignmentsInsert : GTLRLicensingQuery // Previous library name was // +[GTLQueryLicensing queryForLicenseAssignmentsInsertWithObject:productId:skuId:] /** Name for product */ @property(copy, nullable) NSString *productId; /** Name for sku */ @property(copy, nullable) NSString *skuId; /** * Fetches a @c GTLRLicensing_LicenseAssignment. * * Assign License. * * @param object The @c GTLRLicensing_LicenseAssignmentInsert to include in the * query. * @param productId Name for product * @param skuId Name for sku * * @returns GTLRLicensingQuery_LicenseAssignmentsInsert */ + (instancetype)queryWithObject:(GTLRLicensing_LicenseAssignmentInsert *)object productId:(NSString *)productId skuId:(NSString *)skuId; @end /** * List license assignments for given product of the customer. * * Method: licensing.licenseAssignments.listForProduct * * Authorization scope(s): * @c kGTLRAuthScopeLicensingAppsLicensing */ @interface GTLRLicensingQuery_LicenseAssignmentsListForProduct : GTLRLicensingQuery // Previous library name was // +[GTLQueryLicensing queryForLicenseAssignmentsListForProductWithproductId:customerId:] /** * CustomerId represents the customer for whom licenseassignments are queried */ @property(copy, nullable) NSString *customerId; /** * Maximum number of campaigns to return at one time. Must be positive. * Optional. Default value is 100. * * @note If not set, the documented server-side default will be 100 (from the * range 1..1000). */ @property(assign) NSUInteger maxResults; /** * Token to fetch the next page.Optional. By default server will return first * page */ @property(copy, nullable) NSString *pageToken; /** Name for product */ @property(copy, nullable) NSString *productId; /** * Fetches a @c GTLRLicensing_LicenseAssignmentList. * * List license assignments for given product of the customer. * * @param productId Name for product * @param customerId CustomerId represents the customer for whom * licenseassignments are queried * * @returns GTLRLicensingQuery_LicenseAssignmentsListForProduct * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)queryWithProductId:(NSString *)productId customerId:(NSString *)customerId; @end /** * List license assignments for given product and sku of the customer. * * Method: licensing.licenseAssignments.listForProductAndSku * * Authorization scope(s): * @c kGTLRAuthScopeLicensingAppsLicensing */ @interface GTLRLicensingQuery_LicenseAssignmentsListForProductAndSku : GTLRLicensingQuery // Previous library name was // +[GTLQueryLicensing queryForLicenseAssignmentsListForProductAndSkuWithproductId:skuId:customerId:] /** * CustomerId represents the customer for whom licenseassignments are queried */ @property(copy, nullable) NSString *customerId; /** * Maximum number of campaigns to return at one time. Must be positive. * Optional. Default value is 100. * * @note If not set, the documented server-side default will be 100 (from the * range 1..1000). */ @property(assign) NSUInteger maxResults; /** * Token to fetch the next page.Optional. By default server will return first * page */ @property(copy, nullable) NSString *pageToken; /** Name for product */ @property(copy, nullable) NSString *productId; /** Name for sku */ @property(copy, nullable) NSString *skuId; /** * Fetches a @c GTLRLicensing_LicenseAssignmentList. * * List license assignments for given product and sku of the customer. * * @param productId Name for product * @param skuId Name for sku * @param customerId CustomerId represents the customer for whom * licenseassignments are queried * * @returns GTLRLicensingQuery_LicenseAssignmentsListForProductAndSku * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)queryWithProductId:(NSString *)productId skuId:(NSString *)skuId customerId:(NSString *)customerId; @end /** * Assign License. This method supports patch semantics. * * Method: licensing.licenseAssignments.patch * * Authorization scope(s): * @c kGTLRAuthScopeLicensingAppsLicensing */ @interface GTLRLicensingQuery_LicenseAssignmentsPatch : GTLRLicensingQuery // Previous library name was // +[GTLQueryLicensing queryForLicenseAssignmentsPatchWithObject:productId:skuId:userId:] /** Name for product */ @property(copy, nullable) NSString *productId; /** Name for sku for which license would be revoked */ @property(copy, nullable) NSString *skuId; /** email id or unique Id of the user */ @property(copy, nullable) NSString *userId; /** * Fetches a @c GTLRLicensing_LicenseAssignment. * * Assign License. This method supports patch semantics. * * @param object The @c GTLRLicensing_LicenseAssignment to include in the * query. * @param productId Name for product * @param skuId Name for sku for which license would be revoked * @param userId email id or unique Id of the user * * @returns GTLRLicensingQuery_LicenseAssignmentsPatch */ + (instancetype)queryWithObject:(GTLRLicensing_LicenseAssignment *)object productId:(NSString *)productId skuId:(NSString *)skuId userId:(NSString *)userId; @end /** * Assign License. * * Method: licensing.licenseAssignments.update * * Authorization scope(s): * @c kGTLRAuthScopeLicensingAppsLicensing */ @interface GTLRLicensingQuery_LicenseAssignmentsUpdate : GTLRLicensingQuery // Previous library name was // +[GTLQueryLicensing queryForLicenseAssignmentsUpdateWithObject:productId:skuId:userId:] /** Name for product */ @property(copy, nullable) NSString *productId; /** Name for sku for which license would be revoked */ @property(copy, nullable) NSString *skuId; /** email id or unique Id of the user */ @property(copy, nullable) NSString *userId; /** * Fetches a @c GTLRLicensing_LicenseAssignment. * * Assign License. * * @param object The @c GTLRLicensing_LicenseAssignment to include in the * query. * @param productId Name for product * @param skuId Name for sku for which license would be revoked * @param userId email id or unique Id of the user * * @returns GTLRLicensingQuery_LicenseAssignmentsUpdate */ + (instancetype)queryWithObject:(GTLRLicensing_LicenseAssignment *)object productId:(NSString *)productId skuId:(NSString *)skuId userId:(NSString *)userId; @end NS_ASSUME_NONNULL_END
{ "content_hash": "a1beca48320ef42a2c96512d107ac5fa", "timestamp": "", "source": "github", "line_count": 346, "max_line_length": 126, "avg_line_length": 29.546242774566473, "alnum_prop": 0.7139782842609801, "repo_name": "googlecreativelab/Sprayscape", "id": "84e9c60c0cf1b216619e64458a094089befeabb6", "size": "10223", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Sprayscape/Assets/Plugins/GoogleDrivePlugin/Plugins/iOS/google-api-objectivec-client-for-rest/Source/GeneratedServices/Licensing/GTLRLicensingQuery.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "590239" }, { "name": "HLSL", "bytes": "4730" }, { "name": "Java", "bytes": "30392" }, { "name": "JavaScript", "bytes": "1554" }, { "name": "Objective-C", "bytes": "10576417" }, { "name": "Objective-C++", "bytes": "30880" }, { "name": "Ruby", "bytes": "16874" }, { "name": "ShaderLab", "bytes": "17021" }, { "name": "Shell", "bytes": "3452" } ], "symlink_target": "" }
name: compiler-options/closure-warnings see also: - compiler-options/warnings --- ## Summary Control specific warnings generated by the Closure compiler. Each warning must map to either `:error`, `:warning`, or `:off`. ```clj :closure-warnings {:externs-validation :off} ``` ## Details ## Examples
{ "content_hash": "499edc75df6bbe8dc9a9bb288fd1eee3", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 74, "avg_line_length": 18, "alnum_prop": 0.7156862745098039, "repo_name": "cljsinfo/cljs-api-docs", "id": "85b99462a77147133fa6c0dde6d44568b532249d", "size": "310", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docfiles/compiler-options/closure-warnings.md", "mode": "33188", "license": "mit", "language": [ { "name": "Clojure", "bytes": "166023" } ], "symlink_target": "" }
module SimpleSentiment VERSION = "0.0.1" end
{ "content_hash": "b3fcd82e5af9e108097be45b635ae50c", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 22, "avg_line_length": 15.666666666666666, "alnum_prop": 0.723404255319149, "repo_name": "jherr/sentiment", "id": "37e651ff93def0cd131be5cccd0a1f4deab17d19", "size": "47", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/simple_sentiment/version.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "38688" } ], "symlink_target": "" }
<?php /** * Created by IntelliJ IDEA. * User: Besitzer * Date: 12.09.2016 * Time: 08:00 */ namespace FbBasic\GraphNodes; use Facebook\GraphNodes\GraphPicture; class Attachment extends GraphPicture implements GraphInterface { protected static $graphObjectFields = [ "description", "description_tags", "media", "target", "title", "type", "url", ]; /** * @var array Maps object key names to Graph object types. */ protected static $graphObjectMap = [ 'media' => '\FbBasic\GraphNodes\StoryAttachmentMedia', ]; /** * Getter for $graphObjectFields. * * @return array */ public static function getObjectFields() { return static::$graphObjectFields; } /** * Getter for $graphObjectEdgesMap. * * @return array */ public static function getObjectEdges() { if(static::$graphObjectEdgesMap){ return static::$graphObjectEdgesMap; } else{ return array(); } } }
{ "content_hash": "ba5a4762d70f12a32c6032cfdd0a5e24", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 63, "avg_line_length": 19.410714285714285, "alnum_prop": 0.5666973321067157, "repo_name": "flod1/FacebookApi", "id": "41d6efa25951821e43e3bc976804390aec9c5134", "size": "1087", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/FbBasic/GraphNodes/Attachment.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "7649" }, { "name": "PHP", "bytes": "94163" } ], "symlink_target": "" }
<!-- build:js js/jquery.js --> <script src="js/jquery.js"></script> <!-- endbuild --> <!-- build:js js/index.js --> <script src="js/index.js"></script> <!-- endbuild -->
{ "content_hash": "58510c06d3437ca162f12bd4b780fd5d", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 40, "avg_line_length": 31.5, "alnum_prop": 0.5185185185185185, "repo_name": "qiruiyin/yungui-m", "id": "aa523e5c5f6d65febdbba95a2f0ed693c5e7d951", "size": "191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/partial/js.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6577" }, { "name": "HTML", "bytes": "61270" }, { "name": "JavaScript", "bytes": "6246" } ], "symlink_target": "" }
<?php class Google_Service_DataLabeling_GoogleCloudDatalabelingV1beta1ImportDataOperationMetadata extends Google_Collection { protected $collection_key = 'partialFailures'; public $createTime; public $dataset; protected $partialFailuresType = 'Google_Service_DataLabeling_GoogleRpcStatus'; protected $partialFailuresDataType = 'array'; public function setCreateTime($createTime) { $this->createTime = $createTime; } public function getCreateTime() { return $this->createTime; } public function setDataset($dataset) { $this->dataset = $dataset; } public function getDataset() { return $this->dataset; } /** * @param Google_Service_DataLabeling_GoogleRpcStatus[] */ public function setPartialFailures($partialFailures) { $this->partialFailures = $partialFailures; } /** * @return Google_Service_DataLabeling_GoogleRpcStatus[] */ public function getPartialFailures() { return $this->partialFailures; } }
{ "content_hash": "0f6a39e6131471f4d1df9af8cbb4a842", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 117, "avg_line_length": 23.571428571428573, "alnum_prop": 0.7181818181818181, "repo_name": "bshaffer/google-api-php-client-services", "id": "2372e5cc1c60b3fb55b673c3b61059b5701de2b0", "size": "1580", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Google/Service/DataLabeling/GoogleCloudDatalabelingV1beta1ImportDataOperationMetadata.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "9540154" } ], "symlink_target": "" }
import Express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import config from './config'; import favicon from 'serve-favicon'; import compression from 'compression'; import httpProxy from 'http-proxy'; import path from 'path'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import Html from './helpers/Html'; import PrettyError from 'pretty-error'; import http from 'http'; import { match } from 'react-router'; import { ReduxAsyncConnect, loadOnServer } from 'redux-async-connect'; import createHistory from 'react-router/lib/createMemoryHistory'; import {Provider} from 'react-redux'; import getRoutes from './routes'; const targetUrl = 'http://' + config.apiHost + ':' + config.apiPort; const pretty = new PrettyError(); const app = new Express(); const server = new http.Server(app); app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); app.use(Express.static(path.join(__dirname, '..', 'static'))); server.on('upgrade', (req, socket, head) => { proxy.ws(req, socket, head); }); // added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527 app.use((req, res) => { if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } const client = new ApiClient(req); const history = createHistory(req.originalUrl); const store = createStore(history, client); function hydrateOnClient() { res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store}/>)); } if (__DISABLE_SSR__) { hydrateOnClient(); return; } match({ history, routes: getRoutes(store), location: req.originalUrl }, (error, redirectLocation, renderProps) => { if (redirectLocation) { res.redirect(redirectLocation.pathname + redirectLocation.search); } else if (error) { console.error('ROUTER ERROR:', pretty.render(error)); res.status(500); hydrateOnClient(); } else if (renderProps) { loadOnServer({...renderProps, store, helpers: {client}}).then(() => { const component = ( <Provider store={store} key="provider"> <ReduxAsyncConnect {...renderProps} /> </Provider> ); res.status(200); global.navigator = {userAgent: req.headers['user-agent']}; res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>)); }); } else { res.status(404).send('Not found'); } }); }); if (config.port) { server.listen(config.port, (err) => { if (err) { console.error(err); } console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.title, config.apiPort); console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, config.port); }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
{ "content_hash": "98c0c64d4bd0c9e315f258a162a627bf", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 121, "avg_line_length": 32.74226804123711, "alnum_prop": 0.6590050377833753, "repo_name": "rmwdeveloper/portfolio", "id": "1f83a0f44ec0253e8b38d8bf02d5d68690d6f898", "size": "3181", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/server.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2680" }, { "name": "JavaScript", "bytes": "52492" } ], "symlink_target": "" }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. cr.define('print_preview', function() { 'use strict'; /** * Creates a LayoutSettings object. This object encapsulates all settings and * logic related to layout mode (portrait/landscape). * @param {!print_preview.ticket_items.Landscape} landscapeTicketItem Used to * get the layout written to the print ticket. * @constructor * @extends {print_preview.SettingsSection} */ function LayoutSettings(landscapeTicketItem) { print_preview.SettingsSection.call(this); /** * Used to get the layout written to the print ticket. * @type {!print_preview.ticket_items.Landscape} * @private */ this.landscapeTicketItem_ = landscapeTicketItem; }; /** * CSS classes used by the layout settings. * @enum {string} * @private */ LayoutSettings.Classes_ = { LANDSCAPE_RADIO: 'layout-settings-landscape-radio', PORTRAIT_RADIO: 'layout-settings-portrait-radio' }; LayoutSettings.prototype = { __proto__: print_preview.SettingsSection.prototype, /** @override */ isAvailable: function() { return this.landscapeTicketItem_.isCapabilityAvailable(); }, /** @override */ hasCollapsibleContent: function() { return false; }, /** @override */ set isEnabled(isEnabled) { this.landscapeRadioButton_.disabled = !isEnabled; this.portraitRadioButton_.disabled = !isEnabled; }, /** @override */ enterDocument: function() { print_preview.SettingsSection.prototype.enterDocument.call(this); this.tracker.add( this.portraitRadioButton_, 'click', this.onLayoutButtonClick_.bind(this)); this.tracker.add( this.landscapeRadioButton_, 'click', this.onLayoutButtonClick_.bind(this)); this.tracker.add( this.landscapeTicketItem_, print_preview.ticket_items.TicketItem.EventType.CHANGE, this.onLandscapeTicketItemChange_.bind(this)); }, /** * @return {HTMLInputElement} The portrait orientation radio button. * @private */ get portraitRadioButton_() { return this.getElement().getElementsByClassName( LayoutSettings.Classes_.PORTRAIT_RADIO)[0]; }, /** * @return {HTMLInputElement} The landscape orientation radio button. * @private */ get landscapeRadioButton_() { return this.getElement().getElementsByClassName( LayoutSettings.Classes_.LANDSCAPE_RADIO)[0]; }, /** * Called when one of the radio buttons is clicked. Updates the print ticket * store. * @private */ onLayoutButtonClick_: function() { this.landscapeTicketItem_.updateValue(this.landscapeRadioButton_.checked); }, /** * Called when the print ticket store changes state. Updates the state of * the radio buttons and hides the setting if necessary. * @private */ onLandscapeTicketItemChange_: function() { if (this.isAvailable()) { var isLandscapeEnabled = this.landscapeTicketItem_.getValue(); this.portraitRadioButton_.checked = !isLandscapeEnabled; this.landscapeRadioButton_.checked = isLandscapeEnabled; } this.updateUiStateInternal(); } }; // Export return { LayoutSettings: LayoutSettings }; });
{ "content_hash": "9bafb0d6df46e2f7dd0a7c790c673edc", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 80, "avg_line_length": 29.386554621848738, "alnum_prop": 0.6534172147555047, "repo_name": "7kbird/chrome", "id": "057f48a44c01badd0fe5203a79d7991d7d5e6a44", "size": "3497", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "chrome/browser/resources/print_preview/settings/layout_settings.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "35318" }, { "name": "Batchfile", "bytes": "7198" }, { "name": "C", "bytes": "3677808" }, { "name": "C++", "bytes": "212205607" }, { "name": "CSS", "bytes": "871288" }, { "name": "HTML", "bytes": "24532775" }, { "name": "Java", "bytes": "5466890" }, { "name": "JavaScript", "bytes": "17937570" }, { "name": "Makefile", "bytes": "37731" }, { "name": "Objective-C", "bytes": "1120421" }, { "name": "Objective-C++", "bytes": "7054476" }, { "name": "PHP", "bytes": "97817" }, { "name": "PLpgSQL", "bytes": "218361" }, { "name": "Perl", "bytes": "69392" }, { "name": "Protocol Buffer", "bytes": "388742" }, { "name": "Python", "bytes": "6953688" }, { "name": "Shell", "bytes": "465194" }, { "name": "Standard ML", "bytes": "4131" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "15206" } ], "symlink_target": "" }
/** * @file DOM iterator, which iterates over list items, lines and paragraphs. */ CKEDITOR.plugins.add( 'domiterator' ); (function() { /** * @name CKEDITOR.dom.iterator */ function iterator( range ) { if ( arguments.length < 1 ) return; this.range = range; this.forceBrBreak = 0; // Whether include <br>s into the enlarged range.(#3730). this.enlargeBr = 1; this.enforceRealBlocks = 0; this._ || ( this._ = {} ); } var beginWhitespaceRegex = /^[\r\n\t ]+$/, // Ignore bookmark nodes.(#3783) bookmarkGuard = CKEDITOR.dom.walker.bookmark( false, true ); // Get a reference for the next element, bookmark nodes are skipped. function getNextSourceNode( node, startFromSibling, lastNode ) { var next = node.getNextSourceNode( startFromSibling, null, lastNode ); while ( !bookmarkGuard( next ) ) next = next.getNextSourceNode( startFromSibling, null, lastNode ); return next; } iterator.prototype = { getNextParagraph : function( blockTag ) { // The block element to be returned. var block; // The range object used to identify the paragraph contents. var range; // Indicats that the current element in the loop is the last one. var isLast; // Indicate at least one of the range boundaries is inside a preformat block. var touchPre; // Instructs to cleanup remaining BRs. var removePreviousBr, removeLastBr; // This is the first iteration. Let's initialize it. if ( !this._.lastNode ) { range = this.range.clone(); // Shrink the range to exclude harmful "noises" (#4087, #4450, #5435). range.shrink( CKEDITOR.NODE_ELEMENT, true ); touchPre = range.endContainer.hasAscendant( 'pre', true ) || range.startContainer.hasAscendant( 'pre', true ); range.enlarge( this.forceBrBreak && !touchPre || !this.enlargeBr ? CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS : CKEDITOR.ENLARGE_BLOCK_CONTENTS ); var walker = new CKEDITOR.dom.walker( range ), ignoreBookmarkTextEvaluator = CKEDITOR.dom.walker.bookmark( true, true ); // Avoid anchor inside bookmark inner text. walker.evaluator = ignoreBookmarkTextEvaluator; this._.nextNode = walker.next(); // TODO: It's better to have walker.reset() used here. walker = new CKEDITOR.dom.walker( range ); walker.evaluator = ignoreBookmarkTextEvaluator; var lastNode = walker.previous(); this._.lastNode = lastNode.getNextSourceNode( true ); // We may have an empty text node at the end of block due to [3770]. // If that node is the lastNode, it would cause our logic to leak to the // next block.(#3887) if ( this._.lastNode && this._.lastNode.type == CKEDITOR.NODE_TEXT && !CKEDITOR.tools.trim( this._.lastNode.getText() ) && this._.lastNode.getParent().isBlockBoundary() ) { var testRange = new CKEDITOR.dom.range( range.document ); testRange.moveToPosition( this._.lastNode, CKEDITOR.POSITION_AFTER_END ); if ( testRange.checkEndOfBlock() ) { var path = new CKEDITOR.dom.elementPath( testRange.endContainer ); var lastBlock = path.block || path.blockLimit; this._.lastNode = lastBlock.getNextSourceNode( true ); } } // Probably the document end is reached, we need a marker node. if ( !this._.lastNode ) { this._.lastNode = this._.docEndMarker = range.document.createText( '' ); this._.lastNode.insertAfter( lastNode ); } // Let's reuse this variable. range = null; } var currentNode = this._.nextNode; lastNode = this._.lastNode; this._.nextNode = null; while ( currentNode ) { // closeRange indicates that a paragraph boundary has been found, // so the range can be closed. var closeRange = 0, parentPre = currentNode.hasAscendant( 'pre' ); // includeNode indicates that the current node is good to be part // of the range. By default, any non-element node is ok for it. var includeNode = ( currentNode.type != CKEDITOR.NODE_ELEMENT ), continueFromSibling = 0; // If it is an element node, let's check if it can be part of the // range. if ( !includeNode ) { var nodeName = currentNode.getName(); if ( currentNode.isBlockBoundary( this.forceBrBreak && !parentPre && { br : 1 } ) ) { // <br> boundaries must be part of the range. It will // happen only if ForceBrBreak. if ( nodeName == 'br' ) includeNode = 1; else if ( !range && !currentNode.getChildCount() && nodeName != 'hr' ) { // If we have found an empty block, and haven't started // the range yet, it means we must return this block. block = currentNode; isLast = currentNode.equals( lastNode ); break; } // The range must finish right before the boundary, // including possibly skipped empty spaces. (#1603) if ( range ) { range.setEndAt( currentNode, CKEDITOR.POSITION_BEFORE_START ); // The found boundary must be set as the next one at this // point. (#1717) if ( nodeName != 'br' ) this._.nextNode = currentNode; } closeRange = 1; } else { // If we have child nodes, let's check them. if ( currentNode.getFirst() ) { // If we don't have a range yet, let's start it. if ( !range ) { range = new CKEDITOR.dom.range( this.range.document ); range.setStartAt( currentNode, CKEDITOR.POSITION_BEFORE_START ); } currentNode = currentNode.getFirst(); continue; } includeNode = 1; } } else if ( currentNode.type == CKEDITOR.NODE_TEXT ) { // Ignore normal whitespaces (i.e. not including &nbsp; or // other unicode whitespaces) before/after a block node. if ( beginWhitespaceRegex.test( currentNode.getText() ) ) includeNode = 0; } // The current node is good to be part of the range and we are // starting a new range, initialize it first. if ( includeNode && !range ) { range = new CKEDITOR.dom.range( this.range.document ); range.setStartAt( currentNode, CKEDITOR.POSITION_BEFORE_START ); } // The last node has been found. isLast = ( ( !closeRange || includeNode ) && currentNode.equals( lastNode ) ); // If we are in an element boundary, let's check if it is time // to close the range, otherwise we include the parent within it. if ( range && !closeRange ) { while ( !currentNode.getNext( bookmarkGuard ) && !isLast ) { var parentNode = currentNode.getParent(); if ( parentNode.isBlockBoundary( this.forceBrBreak && !parentPre && { br : 1 } ) ) { closeRange = 1; isLast = isLast || ( parentNode.equals( lastNode) ); break; } currentNode = parentNode; includeNode = 1; isLast = ( currentNode.equals( lastNode ) ); continueFromSibling = 1; } } // Now finally include the node. if ( includeNode ) range.setEndAt( currentNode, CKEDITOR.POSITION_AFTER_END ); currentNode = getNextSourceNode ( currentNode, continueFromSibling, lastNode ); isLast = !currentNode; // We have found a block boundary. Let's close the range and move out of the // loop. if ( isLast || ( closeRange && range ) ) break; } // Now, based on the processed range, look for (or create) the block to be returned. if ( !block ) { // If no range has been found, this is the end. if ( !range ) { this._.docEndMarker && this._.docEndMarker.remove(); this._.nextNode = null; return null; } var startPath = new CKEDITOR.dom.elementPath( range.startContainer ); var startBlockLimit = startPath.blockLimit, checkLimits = { div : 1, th : 1, td : 1 }; block = startPath.block; if ( !block && !this.enforceRealBlocks && checkLimits[ startBlockLimit.getName() ] && range.checkStartOfBlock() && range.checkEndOfBlock() ) block = startBlockLimit; else if ( !block || ( this.enforceRealBlocks && block.getName() == 'li' ) ) { // Create the fixed block. block = this.range.document.createElement( blockTag || 'p' ); // Move the contents of the temporary range to the fixed block. range.extractContents().appendTo( block ); block.trim(); // Insert the fixed block into the DOM. range.insertNode( block ); removePreviousBr = removeLastBr = true; } else if ( block.getName() != 'li' ) { // If the range doesn't includes the entire contents of the // block, we must split it, isolating the range in a dedicated // block. if ( !range.checkStartOfBlock() || !range.checkEndOfBlock() ) { // The resulting block will be a clone of the current one. block = block.clone( false ); // Extract the range contents, moving it to the new block. range.extractContents().appendTo( block ); block.trim(); // Split the block. At this point, the range will be in the // right position for our intents. var splitInfo = range.splitBlock(); removePreviousBr = !splitInfo.wasStartOfBlock; removeLastBr = !splitInfo.wasEndOfBlock; // Insert the new block into the DOM. range.insertNode( block ); } } else if ( !isLast ) { // LIs are returned as is, with all their children (due to the // nested lists). But, the next node is the node right after // the current range, which could be an <li> child (nested // lists) or the next sibling <li>. this._.nextNode = ( block.equals( lastNode ) ? null : getNextSourceNode( range.getBoundaryNodes().endNode, 1, lastNode ) ); } } if ( removePreviousBr ) { var previousSibling = block.getPrevious(); if ( previousSibling && previousSibling.type == CKEDITOR.NODE_ELEMENT ) { if ( previousSibling.getName() == 'br' ) previousSibling.remove(); else if ( previousSibling.getLast() && previousSibling.getLast().$.nodeName.toLowerCase() == 'br' ) previousSibling.getLast().remove(); } } if ( removeLastBr ) { var lastChild = block.getLast(); if ( lastChild && lastChild.type == CKEDITOR.NODE_ELEMENT && lastChild.getName() == 'br' ) { // Take care not to remove the block expanding <br> in non-IE browsers. if ( CKEDITOR.env.ie || lastChild.getPrevious( bookmarkGuard ) || lastChild.getNext( bookmarkGuard ) ) lastChild.remove(); } } // Get a reference for the next element. This is important because the // above block can be removed or changed, so we can rely on it for the // next interation. if ( !this._.nextNode ) { this._.nextNode = ( isLast || block.equals( lastNode ) ) ? null : getNextSourceNode( block, 1, lastNode ); } return block; } }; CKEDITOR.dom.range.prototype.createIterator = function() { return new iterator( this ); }; })();
{ "content_hash": "6648ed2f9f0ff10ebc517f4778470af3", "timestamp": "", "source": "github", "line_count": 353, "max_line_length": 128, "avg_line_length": 32.28045325779037, "alnum_prop": 0.6095655989469065, "repo_name": "fredd-for/codice.v.1.1", "id": "7e3bad11818a059ee2deba2366e9a7b0fb6b0db8", "size": "11542", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ckeditor/_source/plugins/domiterator/plugin.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "48011" }, { "name": "JavaScript", "bytes": "3958445" }, { "name": "Lasso", "bytes": "3545" }, { "name": "PHP", "bytes": "37610743" }, { "name": "Shell", "bytes": "526" } ], "symlink_target": "" }
from setuptools import setup, find_packages setup( name='formencode_jsonschema', version='0.1.1dev', description='Dump formencode schema JSON schema using Marshmallow', author='Choi Geonu', author_email='[email protected]', url='https://github.com/hardtack/formencode_jsonschema', packages=find_packages(), include_package_data=True, install_requires=['marshmallow>=2.3.0', 'formencode'], zip_safe=False, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], )
{ "content_hash": "66656aa0c3943862ad3f84cf8616f922", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 71, "avg_line_length": 33.2, "alnum_prop": 0.6536144578313253, "repo_name": "Hardtack/formencode_jsonschema", "id": "52669932939738b68655aefc8cd85b6a0e26dd81", "size": "664", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "setup.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "14790" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@color/shoppingcar_delete_p"/> <item android:drawable="@color/shoppingcar_delete"/> </selector>
{ "content_hash": "4f1911467207646042de7569ccc446df", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 87, "avg_line_length": 53, "alnum_prop": 0.7245283018867924, "repo_name": "cowthan/Ayo2022", "id": "54ce5a7b563c5065363774a6f2ea5ad42a9240ce", "size": "265", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Ayo/app-mall/src/main/res/drawable/selector_shoppingcar_delete.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5114" }, { "name": "HTML", "bytes": "2365" }, { "name": "Java", "bytes": "9575777" }, { "name": "JavaScript", "bytes": "27653" }, { "name": "Makefile", "bytes": "891" } ], "symlink_target": "" }
import { TestBed, inject } from '@angular/core/testing'; import { CatsService } from './cats.service'; describe('CatsService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [CatsService] }); }); it('should be created', inject([CatsService], (service: CatsService) => { expect(service).toBeTruthy(); })); });
{ "content_hash": "5350bb5a788544c048538e26b6229386", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 75, "avg_line_length": 24.133333333333333, "alnum_prop": 0.6243093922651933, "repo_name": "google/angular-a11y-workshop", "id": "af26f547500d7432b95f98c5a6f58418a788c311", "size": "362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/services/cats.service.spec.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2939" }, { "name": "HTML", "bytes": "6592" }, { "name": "JavaScript", "bytes": "2904" }, { "name": "TypeScript", "bytes": "38875" } ], "symlink_target": "" }
<?php // src/MDW/DemoBundle/Controller/ArticulosController.php namespace MDW\DemoBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use MDW\DemoBundle\Entity\Articles; class ArticulosController extends Controller{ public function listarAction(){ } public function crearAction(){ $articulo = new Articles(); $articulo->setTitle('Articulo de ejemplo 1'); $articulo->setAuthor('John Doe'); $articulo->setContent('Contenido'); $articulo->setTags('ejemplo'); $articulo->setCreated(new \DateTime()); $articulo->setUpdated(new \DateTime()); $articulo->setSlug('articulo-de-ejemplo-1'); $articulo->setCategory('ejemplo'); } public function editarAction($id){ } public function visualizarAction($id){ } public function borrarAction($id){ } }
{ "content_hash": "055ebba1929d6946426bd7a06dc3dbd2", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 57, "avg_line_length": 25.28205128205128, "alnum_prop": 0.6369168356997972, "repo_name": "victordonet/Symfony2", "id": "7655d235090767c01f281915ccd7e138b38d658a", "size": "986", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/MDW/DemoBundle/Controller/ArticulosController.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5438" }, { "name": "JavaScript", "bytes": "2182" }, { "name": "PHP", "bytes": "124466" }, { "name": "SQL", "bytes": "2102" } ], "symlink_target": "" }
module Authorization module BlockAccess protected # Checks if a certain action can be accessed by the role. # If you want to check for <tt>action_allowed?</tt>, <tt>resource_allowed?</tt> and <tt>block_allowed?</tt> # use <tt>access_allowed?</tt>. # action_allowed?({:action => :show, :id => 1}, :editor) def action_allowed?(params, role=:all) ::ActiveSupport::Deprecation.warn("action_allowed? has been deprecated.", caller) _die_if_undefined return false if (rules = access_allowed_for[role]).nil? !rules.detect { |rule| action_allowed_by_rule?(rule, params, role) }.nil? end def action_allowed_by_rule?(rule, params, role) #:nodoc: ::ActiveSupport::Deprecation.warn("action_allowed_by_rule? has been deprecated.", caller) return false if (action = params[:action]).nil? directives = rule[:directives] return false if directives[:only].kind_of?(Array) and !directives[:only].include?(action.to_sym) return false if directives[:only].kind_of?(Symbol) and directives[:only] != action.to_sym return false if directives[:except].kind_of?(Array) and directives[:except].include?(action.to_sym) return false if directives[:except].kind_of?(Symbol) and directives[:except] == action.to_sym true end # Checks if the resource indicated by the params can be accessed by user. # If you want to check for <tt>action_allowed?</tt>, <tt>resource_allowed?</tt> and <tt>block_allowed?</tt> # use <tt>access_allowed?</tt>. # resource_allowed?({:id => 1, :organization_id => 12}, :guest, @authenticated) def resource_allowed?(params, role=:all, user=nil) ::ActiveSupport::Deprecation.warn("resource_allowed? has been deprecated.", caller) user ||= @authenticated _die_if_undefined return false if (rules = access_allowed_for[role]).nil? !rules.detect { |rule| resource_allowed_by_rule?(rule, params, role, user) }.nil? end def resource_allowed_by_rule?(rule, params, role, user) #:nodoc: ::ActiveSupport::Deprecation.warn("resource_allowed_by_rule? has been deprecated.", caller) directives = rule[:directives] if directives[:authenticated] return false unless user end begin if directives[:user_resource] return false if params[:id].nil? or user.id.nil? return false if params[:id].to_i != user.id.to_i end rescue NoMethodError end begin if scope = directives[:scope] assoc_id = params["#{scope}_id"].to_i begin object_id = user.send(scope).id.to_i rescue NoMethodError return false end return false if assoc_id.nil? or object_id.nil? return false if assoc_id != object_id end rescue NoMethodError end true end # Checks if the blocks associated with the rules doesn't stop the user from acessing the resource. # If you want to check for <tt>action_allowed?</tt>, <tt>resource_allowed?</tt> and <tt>block_allowed?</tt> # use <tt>access_allowed?</tt>. # block_allowed?(:guest) def block_allowed?(role) ::ActiveSupport::Deprecation.warn("block_allowed? has been deprecated.", caller) _die_if_undefined return false if (rules = access_allowed_for[role]).nil? !rules.detect { |rule| block_allowed_by_rule?(rule) }.nil? end def block_allowed_by_rule?(rule) #:nodoc: ::ActiveSupport::Deprecation.warn("block_allowed_by_rule? has been deprecated.", caller) return false if !rule[:block].nil? and !rule[:block].bind(self).call true end end end
{ "content_hash": "f4bcb9a35fb1b2a33eb38aff7d2c040a", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 111, "avg_line_length": 43.904761904761905, "alnum_prop": 0.6442516268980477, "repo_name": "Fingertips/authorization-san", "id": "da8ad7c7a8a00e3d99c8b7ffa4dae2f205c26101", "size": "3688", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/authorization/deprecated.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "47408" }, { "name": "Shell", "bytes": "235" } ], "symlink_target": "" }
package com.intellij.codeInsight.generation; import com.intellij.codeInsight.hint.HintManager; import com.intellij.lang.StdLanguages; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.ui.ComponentWithBrowseButton; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiEnumConstant; import com.intellij.psi.PsiField; import com.intellij.ui.ListCellRendererWrapper; import com.intellij.util.IncorrectOperationException; import com.intellij.util.NotNullFunction; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.java.generate.exception.GenerateCodeException; import org.jetbrains.java.generate.template.TemplateResource; import org.jetbrains.java.generate.template.TemplatesManager; import org.jetbrains.java.generate.view.TemplatesPanel; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public abstract class GenerateGetterSetterHandlerBase extends GenerateMembersHandlerBase { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.generation.GenerateGetterSetterHandlerBase"); static { GenerateAccessorProviderRegistrar.registerProvider(new NotNullFunction<PsiClass, Collection<EncapsulatableClassMember>>() { @Override @NotNull public Collection<EncapsulatableClassMember> fun(PsiClass s) { if (s.getLanguage() != StdLanguages.JAVA) return Collections.emptyList(); final List<EncapsulatableClassMember> result = new ArrayList<EncapsulatableClassMember>(); for (PsiField field : s.getFields()) { if (!(field instanceof PsiEnumConstant)) { result.add(new PsiFieldMember(field)); } } return result; } }); } public GenerateGetterSetterHandlerBase(String chooserTitle) { super(chooserTitle); } @Override protected boolean hasMembers(@NotNull PsiClass aClass) { return !GenerateAccessorProviderRegistrar.getEncapsulatableClassMembers(aClass).isEmpty(); } @Override protected String getHelpId() { return "Getter and Setter Templates Dialog"; } @Override protected ClassMember[] chooseOriginalMembers(PsiClass aClass, Project project, Editor editor) { final ClassMember[] allMembers = getAllOriginalMembers(aClass); if (allMembers == null) { HintManager.getInstance().showErrorHint(editor, getNothingFoundMessage()); return null; } if (allMembers.length == 0) { HintManager.getInstance().showErrorHint(editor, getNothingAcceptedMessage()); return null; } return chooseMembers(allMembers, false, false, project, editor); } protected static JComponent getHeaderPanel(final Project project, final TemplatesManager templatesManager, final String templatesTitle) { final JPanel panel = new JPanel(new BorderLayout()); final JLabel templateChooserLabel = new JLabel(templatesTitle); panel.add(templateChooserLabel, BorderLayout.WEST); final ComboBox comboBox = new ComboBox(); templateChooserLabel.setLabelFor(comboBox); comboBox.setRenderer(new ListCellRendererWrapper<TemplateResource>() { @Override public void customize(JList list, TemplateResource value, int index, boolean selected, boolean hasFocus) { setText(value.getName()); } }); final ComponentWithBrowseButton<ComboBox> comboBoxWithBrowseButton = new ComponentWithBrowseButton<ComboBox>(comboBox, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final TemplatesPanel ui = new TemplatesPanel(project, templatesManager) { @Override protected boolean onMultipleFields() { return false; } @Nls @Override public String getDisplayName() { return StringUtil.capitalizeWords(UIUtil.removeMnemonic(StringUtil.trimEnd(templatesTitle, ":")), true); } }; ui.setHint("Visibility is applied according to File | Settings | Editor | Code Style | Java | Code Generation"); ui.selectNodeInTree(templatesManager.getDefaultTemplate()); if (ShowSettingsUtil.getInstance().editConfigurable(panel, ui)) { setComboboxModel(templatesManager, comboBox); } }}); setComboboxModel(templatesManager, comboBox); comboBox.addActionListener(new ActionListener() { public void actionPerformed(@NotNull final ActionEvent M) { templatesManager.setDefaultTemplate((TemplateResource)comboBox.getSelectedItem()); } }); panel.add(comboBoxWithBrowseButton, BorderLayout.CENTER); return panel; } private static void setComboboxModel(TemplatesManager templatesManager, ComboBox comboBox) { final Collection<TemplateResource> templates = templatesManager.getAllTemplates(); comboBox.setModel(new DefaultComboBoxModel(templates.toArray(new TemplateResource[templates.size()]))); comboBox.setSelectedItem(templatesManager.getDefaultTemplate()); } @Override protected abstract String getNothingFoundMessage(); protected abstract String getNothingAcceptedMessage(); public boolean canBeAppliedTo(PsiClass targetClass) { final ClassMember[] allMembers = getAllOriginalMembers(targetClass); return allMembers != null && allMembers.length != 0; } @Override @Nullable protected ClassMember[] getAllOriginalMembers(final PsiClass aClass) { final List<EncapsulatableClassMember> list = GenerateAccessorProviderRegistrar.getEncapsulatableClassMembers(aClass); if (list.isEmpty()) { return null; } final List<EncapsulatableClassMember> members = ContainerUtil.findAll(list, new Condition<EncapsulatableClassMember>() { @Override public boolean value(EncapsulatableClassMember member) { try { return generateMemberPrototypes(aClass, member).length > 0; } catch (GenerateCodeException e) { return true; } catch (IncorrectOperationException e) { LOG.error(e); return false; } } }); return members.toArray(new ClassMember[members.size()]); } }
{ "content_hash": "6d785948e5621cd2972f901ca75ba044", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 139, "avg_line_length": 39.01724137931034, "alnum_prop": 0.7338341434673737, "repo_name": "lucafavatella/intellij-community", "id": "efce7063dac823d45badc18542487d7b848c937f", "size": "7389", "binary": false, "copies": "4", "ref": "refs/heads/cli-wip", "path": "java/java-impl/src/com/intellij/codeInsight/generation/GenerateGetterSetterHandlerBase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "20665" }, { "name": "AspectJ", "bytes": "182" }, { "name": "Batchfile", "bytes": "63896" }, { "name": "C", "bytes": "214817" }, { "name": "C#", "bytes": "1538" }, { "name": "C++", "bytes": "191650" }, { "name": "CSS", "bytes": "195482" }, { "name": "CoffeeScript", "bytes": "1759" }, { "name": "Cucumber", "bytes": "14382" }, { "name": "Erlang", "bytes": "10" }, { "name": "Groff", "bytes": "35232" }, { "name": "Groovy", "bytes": "2470587" }, { "name": "HLSL", "bytes": "57" }, { "name": "HTML", "bytes": "1804175" }, { "name": "J", "bytes": "5050" }, { "name": "Java", "bytes": "155219443" }, { "name": "JavaScript", "bytes": "562259" }, { "name": "Jupyter Notebook", "bytes": "92629" }, { "name": "Kotlin", "bytes": "1454397" }, { "name": "Lex", "bytes": "179878" }, { "name": "Makefile", "bytes": "2352" }, { "name": "NSIS", "bytes": "53411" }, { "name": "Objective-C", "bytes": "27183" }, { "name": "Perl", "bytes": "903" }, { "name": "Perl6", "bytes": "26" }, { "name": "Protocol Buffer", "bytes": "6570" }, { "name": "Python", "bytes": "23630760" }, { "name": "Ruby", "bytes": "1213" }, { "name": "Scala", "bytes": "11698" }, { "name": "Shell", "bytes": "70829" }, { "name": "Smalltalk", "bytes": "64" }, { "name": "TeX", "bytes": "25473" }, { "name": "TypeScript", "bytes": "9469" }, { "name": "XSLT", "bytes": "113040" } ], "symlink_target": "" }
namespace Microsoft.Azure.Management.Synapse { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// LibrariesOperations operations. /// </summary> internal partial class LibrariesOperations : IServiceOperations<SynapseManagementClient>, ILibrariesOperations { /// <summary> /// Initializes a new instance of the LibrariesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal LibrariesOperations(SynapseManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the SynapseManagementClient /// </summary> public SynapseManagementClient Client { get; private set; } /// <summary> /// List the libraries in a workspace. /// </summary> /// <remarks> /// List libraries in a workspace. /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// The name of the workspace. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LibraryResource>>> ListByWorkspaceWithHttpMessagesAsync(string resourceGroupName, string workspaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.SubscriptionId != null) { if (Client.SubscriptionId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "Client.SubscriptionId", 1); } } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (workspaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workspaceName"); } string apiVersion = "2021-06-01-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workspaceName", workspaceName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByWorkspace", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Synapse/workspaces/{workspaceName}/libraries").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(workspaceName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LibraryResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LibraryResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// List the libraries in a workspace. /// </summary> /// <remarks> /// List libraries in a workspace. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LibraryResource>>> ListByWorkspaceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByWorkspaceNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LibraryResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LibraryResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
{ "content_hash": "4d68080473378589cd9c2e1bc96ae99a", "timestamp": "", "source": "github", "line_count": 425, "max_line_length": 279, "avg_line_length": 43.995294117647056, "alnum_prop": 0.5487752700823617, "repo_name": "Azure/azure-sdk-for-net", "id": "dfd7d6123ad579d1cc6aed9ca3131e970b0ff8e7", "size": "19051", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/synapse/Microsoft.Azure.Management.Synapse/src/Generated/LibrariesOperations.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package io.baardl.presenter; import org.testng.annotations.Test; import static org.testng.Assert.assertTrue; /** * Show gropuping functionallity for TestNG */ public class FastTestExamples { @Test(groups = { "fast"}) public void testWithGroup() throws Exception { assertTrue(true); } @Test public void testMe() throws Exception { assertTrue(true); } }
{ "content_hash": "b581a280b2f8d8fc184193540ea832e9", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 50, "avg_line_length": 16.08, "alnum_prop": 0.6691542288557214, "repo_name": "baardl/iot-presenter", "id": "10d5397ccffddcf229efd5409894698a09d1924e", "size": "402", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/io/baardl/presenter/FastTestExamples.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4226" }, { "name": "HTML", "bytes": "44228" }, { "name": "Java", "bytes": "12961" }, { "name": "JavaScript", "bytes": "8301" } ], "symlink_target": "" }
<?php class RokSprocket_Provider_Wordpress extends RokSprocket_Provider_AbstarctWordpressBasedProvider { /** * @static * @return bool */ public static function isAvailable() { if (class_exists('WP_Widget')) { return true; } else { return false; } } /** * @param array $filters * @param array $sort_filters */ public function __construct($filters = array(), $sort_filters = array()) { parent::__construct('wordpress'); $this->setFilterChoices($filters, $sort_filters); } /** * @param $raw_item * @param int $dborder * * @return \RokSprocket_Item */ protected function convertRawToItem($raw_item, $dborder = 0) { $item = new RokSprocket_Item(); $item->setProvider($this->provider_name); $item->setId($raw_item->post_id); $item->setAlias($raw_item->post_name); $item->setAuthor(($raw_item->display_name) ? $raw_item->display_name : $raw_item->user_nicename); $item->setTitle($raw_item->post_title); $item->setDate($raw_item->post_date); $item->setPublished(($raw_item->post_status == "publish") ? true : false); $text = apply_filters( 'widget_text', empty( $raw_item->post_content) ? '' :$raw_item->post_content); $item->setText(strip_shortcodes($text)); $item->setCategory($raw_item->categories); $item->setHits(null); $item->setRating(null); $item->setMetaKey(null); $item->setMetaDesc(null); $item->setMetaData(null); //Set up texts array $texts = array(); $texts['text_post_content'] = $raw_item->post_content; $texts['text_post_excerpt'] = $raw_item->post_excerpt; $item->setTextFields($texts); //set up images array $images = array(); if (isset($raw_item->thumbnail_id) && !empty($raw_item->thumbnail_id)) { $image = new RokSprocket_Item_Image(); $image->setSource(wp_get_attachment_url($raw_item->thumbnail_id)); $image->setIdentifier('image_thumbnail'); $image->setCaption($raw_item->image_intro_caption); $image->setAlttext($raw_item->image_intro_alt); $images[$image->getIdentifier()] = $image; } $item->setImages($images); $item->setPrimaryImage($images['image_thumbnail']); //set up links array $links = array(); $item->setLinks($links); $primary_link = new RokSprocket_Item_Link(); $primary_link->setUrl(get_permalink($raw_item->post_id)); $primary_link->getIdentifier('article_link'); $item->setPrimaryLink($primary_link); $item->setCommentCount($raw_item->comment_count); if (!empty($raw_item->tags)) { $tags = (explode(',', $raw_item->tags)) ? explode(',', $raw_item->tags) : array(); $item->setTags($tags); } $item->setDbOrder($dborder); return $item; } /** * @param $id * * @return string */ protected function getArticleEditUrl($id) { return admin_url('post.php?post='.$id.'&action=edit'); } /** * @return array the array of image type and label */ public static function getImageTypes() { return; } /** * @return array the array of link types and label */ public static function getLinkTypes() { return; } /** * @return array the array of link types and label */ public static function getTextTypes() { $list = array( 'text_post_content' => array('group' => null, 'display' => 'Post Content'), 'text_post_excerpt' => array('group' => null, 'display' => 'Post Excerpt'), ); return $list; } }
{ "content_hash": "beb9275758a6abb5a0003f0ea5c38318", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 106, "avg_line_length": 29.66412213740458, "alnum_prop": 0.5524961399897066, "repo_name": "creative2020/f4u", "id": "4c23ba5a9c77a0fa11e4ce86b3f05cb1a9d1eead", "size": "4092", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "components/com_roksprocket/lib/RokSprocket/Provider/Wordpress.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3575" }, { "name": "CSS", "bytes": "1833367" }, { "name": "HTML", "bytes": "437498" }, { "name": "JavaScript", "bytes": "1933348" }, { "name": "PHP", "bytes": "19706784" } ], "symlink_target": "" }
<nav class="navbar navbar-ddd"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i> </button> <a class="navbar-brand page-scroll nav-title" href="/">Diamond Clover</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li> <!--start search--> <div id="search-demo-container"> <input type="text" id="search-input" placeholder="{{site.data.strings.search_placeholder_text}}"> <ul id="results-container"></ul> </div> <script src="{{ "js/jekyll-search.js"}}" type="text/javascript"></script> <script type="text/javascript"> SimpleJekyllSearch.init({ searchInput: document.getElementById('search-input'), resultsContainer: document.getElementById('results-container'), dataSource: '{{ "search.json" }}', searchResultTemplate: '<li><a href="{url}" title="{{page.title | replace: "\'", "\"}}">{title}</a></li>', noResultsText: '{{site.data.strings.search_no_results_text}}', limit: 10, fuzzy: true, }) </script> <!--end search--> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav>
{ "content_hash": "3a6dbcce34e401a7676c89c270046d5b", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 137, "avg_line_length": 54.205128205128204, "alnum_prop": 0.4645222327341533, "repo_name": "WolfOfTheNorth/diamondclover", "id": "b01148c1778c9fb439243ef497fe5ac6b20efec1", "size": "2114", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_includes/topnav.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "51393" }, { "name": "HTML", "bytes": "97234" }, { "name": "JavaScript", "bytes": "9952" }, { "name": "Ruby", "bytes": "7197" }, { "name": "Shell", "bytes": "1358" } ], "symlink_target": "" }
<?php /* Safe sample input : get the UserData field of $_SESSION SANITIZE : use in_array to check if $tainted is in the white list construction : interpretation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = $_SESSION['UserData']; $legal_table = array("safe1", "safe2"); if (in_array($tainted, $legal_table, true)) { $tainted = $tainted; } else { $tainted = $legal_table[0]; } $query = "echo $'$tainted';"; $res = eval($query); ?>
{ "content_hash": "c2a9ec9b18f85d10f3dbcd95fae2d7bd", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 75, "avg_line_length": 23.017241379310345, "alnum_prop": 0.7528089887640449, "repo_name": "stivalet/PHP-Vulnerability-test-suite", "id": "670190f7b47dc80b6f3e3114981916c72d9be003", "size": "1335", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Injection/CWE_95/safe/CWE_95__SESSION__whitelist_using_array__echo-interpretation_simple_quote.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "64184004" } ], "symlink_target": "" }
<?xml version="1.0" ?> <container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <!-- <services> <service id="wsf_social.example" class="WSF\SocialBundle\Example"> <argument type="service" id="service_id" /> <argument>plain_value</argument> <argument>%parameter_name%</argument> </service> </services> --> </container>
{ "content_hash": "cb121be102a313136aadcf817610cb75", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 120, "avg_line_length": 35.5, "alnum_prop": 0.6320422535211268, "repo_name": "KillianKemps/WSF-Social-by-CoolKids", "id": "2a5cf8a26599db350c06d26fc64eb1b47d2a78ab", "size": "568", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/WSF/SocialBundle/Resources/config/services.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15716" }, { "name": "PHP", "bytes": "51879" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v4.4.1: v8::JitCodeEvent Struct Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v4.4.1 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="structv8_1_1JitCodeEvent.html">JitCodeEvent</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> &#124; <a href="#pub-types">Public Types</a> &#124; <a href="#pub-attribs">Public Attributes</a> &#124; <a href="structv8_1_1JitCodeEvent-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">v8::JitCodeEvent Struct Reference</div> </div> </div><!--header--> <div class="contents"> <p><code>#include &lt;<a class="el" href="v8_8h_source.html">v8.h</a>&gt;</code></p> <div class="dynheader"> Collaboration diagram for v8::JitCodeEvent:</div> <div class="dyncontent"> <div class="center"><img src="structv8_1_1JitCodeEvent__coll__graph.png" border="0" usemap="#v8_1_1JitCodeEvent_coll__map" alt="Collaboration graph"/></div> <map name="v8_1_1JitCodeEvent_coll__map" id="v8_1_1JitCodeEvent_coll__map"> </map> <center><span class="legend">[<a href="graph_legend.html">legend</a>]</span></center></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a> Classes</h2></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structv8_1_1JitCodeEvent_1_1line__info__t.html">line_info_t</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structv8_1_1JitCodeEvent_1_1name__t.html">name_t</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-types"></a> Public Types</h2></td></tr> <tr class="memitem:ac4f8e391762567a2710eb5552b5f11f7"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ac4f8e391762567a2710eb5552b5f11f7"></a>enum &#160;</td><td class="memItemRight" valign="bottom"><b>EventType</b> { <br /> &#160;&#160;<b>CODE_ADDED</b>, <b>CODE_MOVED</b>, <b>CODE_REMOVED</b>, <b>CODE_ADD_LINE_POS_INFO</b>, <br /> &#160;&#160;<b>CODE_START_LINE_INFO_RECORDING</b>, <b>CODE_END_LINE_INFO_RECORDING</b> <br /> }</td></tr> <tr class="separator:ac4f8e391762567a2710eb5552b5f11f7"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a02ca6a3e363d0d95142591fd454c8ba9"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a02ca6a3e363d0d95142591fd454c8ba9"></a>enum &#160;</td><td class="memItemRight" valign="bottom"><b>PositionType</b> { <b>POSITION</b>, <b>STATEMENT_POSITION</b> }</td></tr> <tr class="separator:a02ca6a3e363d0d95142591fd454c8ba9"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a> Public Attributes</h2></td></tr> <tr class="memitem:ace1fbc4119ac3ef609d8e0f89cbc2c9f"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ace1fbc4119ac3ef609d8e0f89cbc2c9f"></a> EventType&#160;</td><td class="memItemRight" valign="bottom"><b>type</b></td></tr> <tr class="separator:ace1fbc4119ac3ef609d8e0f89cbc2c9f"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aeeac614e6c125bf08bf785b070090d0f"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aeeac614e6c125bf08bf785b070090d0f"></a> void *&#160;</td><td class="memItemRight" valign="bottom"><b>code_start</b></td></tr> <tr class="separator:aeeac614e6c125bf08bf785b070090d0f"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ad56f78749d03f5db29ed417c2f3b4666"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad56f78749d03f5db29ed417c2f3b4666"></a> size_t&#160;</td><td class="memItemRight" valign="bottom"><b>code_len</b></td></tr> <tr class="separator:ad56f78749d03f5db29ed417c2f3b4666"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a50ac4979f3d15900647b6b29dae3db76"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a50ac4979f3d15900647b6b29dae3db76"></a> <a class="el" href="classv8_1_1Local.html">Local</a>&lt; <a class="el" href="classv8_1_1UnboundScript.html">UnboundScript</a> &gt;&#160;</td><td class="memItemRight" valign="bottom"><b>script</b></td></tr> <tr class="separator:a50ac4979f3d15900647b6b29dae3db76"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a90597e06440ebd68fe582bd1361d6de6"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a90597e06440ebd68fe582bd1361d6de6"></a> void *&#160;</td><td class="memItemRight" valign="bottom"><b>user_data</b></td></tr> <tr class="separator:a90597e06440ebd68fe582bd1361d6de6"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a4c66ebaa0d14b47a28601446150ae617"><td class="memItemLeft" ><a class="anchor" id="a4c66ebaa0d14b47a28601446150ae617"></a> union {</td></tr> <tr class="memitem:ae56846701a780df8c2165233e28fac86"><td class="memItemLeft" > &#160;&#160;&#160;struct <a class="el" href="structv8_1_1JitCodeEvent_1_1name__t.html">name_t</a>&#160;&#160;&#160;<b>name</b></td></tr> <tr class="separator:ae56846701a780df8c2165233e28fac86"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a680308707435b753f825b6fd29d157ba"><td class="memItemLeft" > &#160;&#160;&#160;struct <a class="el" href="structv8_1_1JitCodeEvent_1_1line__info__t.html">line_info_t</a>&#160;&#160;&#160;<b>line_info</b></td></tr> <tr class="separator:a680308707435b753f825b6fd29d157ba"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a6e6236871dc02d6b88d311d27fbedb4b"><td class="memItemLeft" > &#160;&#160;&#160;void *&#160;&#160;&#160;<b>new_code_start</b></td></tr> <tr class="separator:a6e6236871dc02d6b88d311d27fbedb4b"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a4c66ebaa0d14b47a28601446150ae617"><td class="memItemLeft" valign="top">};&#160;</td><td class="memItemRight" valign="bottom"></td></tr> <tr class="separator:a4c66ebaa0d14b47a28601446150ae617"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>A JIT code event is issued each time code is added, moved or removed.</p> <dl class="section note"><dt>Note</dt><dd>removal events are not currently issued. </dd></dl> </div><hr/>The documentation for this struct was generated from the following file:<ul> <li>deps/v8/include/<a class="el" href="v8_8h_source.html">v8.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "11d0e0d5d2119a153de2e1b3f716a7d5", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 262, "avg_line_length": 59.772222222222226, "alnum_prop": 0.6853796821265917, "repo_name": "v8-dox/v8-dox.github.io", "id": "1c0fc1d7d3a4257075cecb67122d39bee9cd8018", "size": "10759", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "d7b81b5/html/structv8_1_1JitCodeEvent.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="topbar"> <attr name="lefttext" format="string"/> <attr name="leftdrawable" format="reference"/> <attr name="lefttextcolor" format="color"/> <attr name="lefttextsize" format="dimension"/> <attr name="rightbackground" format="reference"/> <attr name="rightwidth" format="dimension"/> <attr name="rightheight" format="dimension"/> </declare-styleable> <declare-styleable name="ViewPagerIndicator"> <!-- Style of the tab indicator's tabs. --> <attr name="vpiTabPageIndicatorStyle" format="reference"/> </declare-styleable> </resources>
{ "content_hash": "a3dbef21b9239cbd2d75df581c803597", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 66, "avg_line_length": 38.72222222222222, "alnum_prop": 0.6413199426111909, "repo_name": "0359xiaodong/osChina-app", "id": "4bf7b5d747ec1efe390ab52532f1ffaced56a635", "size": "697", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/src/main/res/values/attrs.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "42538" } ], "symlink_target": "" }
package com.github.grimpy.botifier.plugins.liveware; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; /** * The extension receiver receives the extension intents and starts the * extension service when it arrives. */ public class SWExtensionReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { intent.setClass(context, SWExtensionService.class); context.startService(intent); } }
{ "content_hash": "f35ebec5ff289a6251b97d7ea7955725", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 71, "avg_line_length": 31.235294117647058, "alnum_prop": 0.7702448210922788, "repo_name": "grimpy/Botifier", "id": "5f37ea4122751732a0178047405e2d0a0808ff76", "size": "531", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/github/grimpy/botifier/plugins/liveware/SWExtensionReceiver.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Java", "bytes": "80847" }, { "name": "Makefile", "bytes": "1205" } ], "symlink_target": "" }
$packageName = 'chromehistoryview' $url = 'http://www.nirsoft.net/utils/chromehistoryview.zip' $checksum = 'f6eba7aca7dfa88328e52a0cfb466b8e9c9ebc857737957577ef3e488ce70ab8' $checksumType = 'sha256' $toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" $installFile = Join-Path $toolsDir "$($packageName).exe" Install-ChocolateyZipPackage -PackageName "$packageName" ` -Url "$url" ` -UnzipLocation "$toolsDir" ` -Checksum "$checksum" ` -ChecksumType "$checksumType" Set-Content -Path ("$installFile.gui") ` -Value $null
{ "content_hash": "96ca1e9e007d048c0996ca6dbce88255", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 78, "avg_line_length": 44.4, "alnum_prop": 0.6171171171171171, "repo_name": "dtgm/chocolatey-packages", "id": "c98d834c5f140abb8f66e10ddc8490e8009a05c2", "size": "666", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "automatic/_output/chromehistoryview/1.32/tools/chocolateyInstall.ps1", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AutoHotkey", "bytes": "347616" }, { "name": "AutoIt", "bytes": "13530" }, { "name": "Batchfile", "bytes": "1404" }, { "name": "C#", "bytes": "8134" }, { "name": "HTML", "bytes": "80818" }, { "name": "PowerShell", "bytes": "13124493" } ], "symlink_target": "" }
fm.Package("jfm.util"); fm.Base("jfm.util.Store"); fm.Interface("Map"); jfm.util.Map = function ( me){this.setMe=function(_me){me=_me;}; this.containsValue = function(){}; this.containsKey = function(){}; this.get = function(){}; this.put = function(){}; this.putAll = function(){}; this.keySet = function(){}; this.values = function(){}; this.entrySet = function(){}; };
{ "content_hash": "68eb7f18a46b5806d11fbb6f83aec4e8", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 64, "avg_line_length": 18.523809523809526, "alnum_prop": 0.6246786632390745, "repo_name": "anoopchaurasia/jsfm", "id": "eb82a5427daf5e731224811d1ed893572d069652", "size": "389", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jfm/util/Map.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "13" }, { "name": "HTML", "bytes": "81" }, { "name": "JavaScript", "bytes": "138732" } ], "symlink_target": "" }
<HTML> <BODY BGCOLOR="white"> <PRE> <FONT color="green">001</FONT> <a name="line.16"></a> <FONT color="green">017</FONT> package org.apache.commons.math3.analysis.interpolation;<a name="line.17"></a> <FONT color="green">018</FONT> <a name="line.18"></a> <FONT color="green">019</FONT> import org.apache.commons.math3.analysis.MultivariateFunction;<a name="line.19"></a> <FONT color="green">020</FONT> <a name="line.20"></a> <FONT color="green">021</FONT> /**<a name="line.21"></a> <FONT color="green">022</FONT> * Interface representing a univariate real interpolating function.<a name="line.22"></a> <FONT color="green">023</FONT> *<a name="line.23"></a> <FONT color="green">024</FONT> * @since 2.1<a name="line.24"></a> <FONT color="green">025</FONT> * @version $Id: MultivariateInterpolator.java 1364387 2012-07-22 18:14:11Z tn $<a name="line.25"></a> <FONT color="green">026</FONT> */<a name="line.26"></a> <FONT color="green">027</FONT> public interface MultivariateInterpolator {<a name="line.27"></a> <FONT color="green">028</FONT> <a name="line.28"></a> <FONT color="green">029</FONT> /**<a name="line.29"></a> <FONT color="green">030</FONT> * Computes an interpolating function for the data set.<a name="line.30"></a> <FONT color="green">031</FONT> *<a name="line.31"></a> <FONT color="green">032</FONT> * @param xval the arguments for the interpolation points.<a name="line.32"></a> <FONT color="green">033</FONT> * {@code xval[i][0]} is the first component of interpolation point<a name="line.33"></a> <FONT color="green">034</FONT> * {@code i}, {@code xval[i][1]} is the second component, and so on<a name="line.34"></a> <FONT color="green">035</FONT> * until {@code xval[i][d-1]}, the last component of that interpolation<a name="line.35"></a> <FONT color="green">036</FONT> * point (where {@code d} is thus the dimension of the space).<a name="line.36"></a> <FONT color="green">037</FONT> * @param yval the values for the interpolation points<a name="line.37"></a> <FONT color="green">038</FONT> * @return a function which interpolates the data set<a name="line.38"></a> <FONT color="green">039</FONT> * @throws org.apache.commons.math3.exception.MathIllegalArgumentException<a name="line.39"></a> <FONT color="green">040</FONT> * if the arguments violate assumptions made by the interpolation<a name="line.40"></a> <FONT color="green">041</FONT> * algorithm.<a name="line.41"></a> <FONT color="green">042</FONT> * @throws org.apache.commons.math3.exception.DimensionMismatchException<a name="line.42"></a> <FONT color="green">043</FONT> * when the array dimensions are not consistent.<a name="line.43"></a> <FONT color="green">044</FONT> * @throws org.apache.commons.math3.exception.NoDataException if an<a name="line.44"></a> <FONT color="green">045</FONT> * array has zero-length.<a name="line.45"></a> <FONT color="green">046</FONT> * @throws org.apache.commons.math3.exception.NullArgumentException if<a name="line.46"></a> <FONT color="green">047</FONT> * the arguments are {@code null}.<a name="line.47"></a> <FONT color="green">048</FONT> */<a name="line.48"></a> <FONT color="green">049</FONT> MultivariateFunction interpolate(double[][] xval, double[] yval);<a name="line.49"></a> <FONT color="green">050</FONT> }<a name="line.50"></a> </PRE> </BODY> </HTML>
{ "content_hash": "8da5e7025aaf7eaca87db92981d31116", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 136, "avg_line_length": 35.20792079207921, "alnum_prop": 0.6327334083239595, "repo_name": "vaisaghvt/gameAnalyzer", "id": "56b21965aa15b1101545e636c372b96884ce89fa", "size": "5189", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "commons-math3-3.1.1-bin/commons-math3-3.1.1/docs/apidocs/src-html/org/apache/commons/math3/analysis/interpolation/MultivariateInterpolator.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1466" }, { "name": "CSS", "bytes": "3795" }, { "name": "Common Lisp", "bytes": "1369" }, { "name": "HTML", "bytes": "76889612" }, { "name": "Java", "bytes": "18165919" }, { "name": "Makefile", "bytes": "4432" }, { "name": "Python", "bytes": "5563" }, { "name": "Shell", "bytes": "1892" }, { "name": "TeX", "bytes": "1053" }, { "name": "XSLT", "bytes": "5008" } ], "symlink_target": "" }
```js var Ctrl = require('minio-controller-js'); var Controller = new Ctrl("http://<CONTROLLER-IPADDRESS:9001/rpc"); Controller.APIMETHOD(ARGUMENT) .then(function(data) { console.log("success : ", data); }) .catch(function(error) { console.log("fail : ", error.toString()); }); ``` ## List of Controller APIs implemented [GenerateAuth("myuser")](./examples/gen-auth.js) [FetchAuth("myuser")](./examples/fetch-auth.js) [ResetAuth("myuser")](./examples/reset-auth.js) [AddServer({host:192.168.1.2})](./examples/add-server.js) [ListServers()](./examples/list-servers.js) [GetServerMemStats({host:192.168.1.2})](./examples/get-server-memstats.js) [GetServerDiskStats({host:192.168.1.2})](./examples/get-server-diskstats.js) [GetServerSysInfo({host:192.168.1.2})](./examples/get-server-sysinfo.js) [GetServerVersion({host:192.168.1.2})](./examples/get-server-version.js) ## More Examples ```js var Ctrl = require('minio-controller-js'); var Controller = new Ctrl("http://192.168.1.2:9001/rpc"); // Generate S3 key/secret Controller.GenerateAuth("admin") .then(function(data) { console.log("success : ", data); }) .catch(function(error) { console.log("fail : ", error.toString()); }); // Add 3 servers Controller.AddServer({host:"192.168.1.2"}) .then(function(data) { return Controller.AddServer({host:"192.168.1.3"}) }) .then(function(data) { return Controller.AddServer({host:"192.168.1.4"}) }) .then(function(data) { // List added servers return Controller.ListServers() }) .then(function(data) { console.log("success : ", data); }) .catch(function(error) { console.log("fail : ", error.toString()); }); // Get Server memory stats Controller.GetServerMemStats({host:"192.168.1.4"}) .then(function(data) { console.log("success : ", data); }) .catch(function(error) { console.log("fail : ", error.toString()); });
{ "content_hash": "bda8e4da0db6d0d52b9f94a51c0dc714", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 76, "avg_line_length": 25.794871794871796, "alnum_prop": 0.6272365805168986, "repo_name": "krishnasrinivas/minio-controller-js", "id": "6e7ddbfc07df94ef033b1e12cc1922b04bda3849", "size": "2080", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "5180" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Provides custom values associated with <see cref="SourceText"/> instances using the given computeValue delegate. /// </summary> public sealed class SourceTextValueProvider<TValue> { internal AnalysisValueProvider<SourceText, TValue> CoreValueProvider { get; private set; } /// <summary> /// Provides custom values associated with <see cref="SourceText"/> instances using the given <paramref name="computeValue"/>. /// </summary> /// <param name="computeValue">Delegate to compute the value associated with a given <see cref="SourceText"/> instance.</param> /// <param name="sourceTextComparer">Optional equality comparer to determine equivalent <see cref="SourceText"/> instances that have the same value. /// If no comparer is provided, then <see cref="SourceTextComparer"/> is used by default.</param> public SourceTextValueProvider(Func<SourceText, TValue> computeValue, IEqualityComparer<SourceText>? sourceTextComparer = null) { CoreValueProvider = new AnalysisValueProvider<SourceText, TValue>(computeValue, sourceTextComparer ?? SourceTextComparer.Instance); } } }
{ "content_hash": "b8fc85d2cde6bdf68c4f27b91ea4509d", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 156, "avg_line_length": 50.354838709677416, "alnum_prop": 0.7226137091607944, "repo_name": "davkean/roslyn", "id": "679ccb1d0801dd0fb307f23b8e79908c83f4f4ae", "size": "1563", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/Compilers/Core/Portable/DiagnosticAnalyzer/SourceTextValueProvider.cs", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "289100" }, { "name": "Batchfile", "bytes": "9059" }, { "name": "C#", "bytes": "134997671" }, { "name": "C++", "bytes": "5602" }, { "name": "CMake", "bytes": "9153" }, { "name": "Dockerfile", "bytes": "2450" }, { "name": "F#", "bytes": "549" }, { "name": "PowerShell", "bytes": "233223" }, { "name": "Shell", "bytes": "92956" }, { "name": "Visual Basic .NET", "bytes": "71479723" } ], "symlink_target": "" }
export GPIO_PIN=23 export ROOM=Attic export SENSOR=Window_${ROOM}_Bottom_Left $(dirname $0)/publish_contact_data.py \ --loops=20 \ --http_base=http://pitaya:7878 \ --pin=${GPIO_PIN} \ --name=${SENSOR}
{ "content_hash": "4819b81d6eb8821f4dea354255a72abf", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 40, "avg_line_length": 25.11111111111111, "alnum_prop": 0.6150442477876106, "repo_name": "hakan42/openhab-sensor-scripts", "id": "3368b96babdd5bd967a50b6dde1c320b2b39e6a2", "size": "237", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Contact-Python/publish_attic_window_bottom_left.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "2767" }, { "name": "Shell", "bytes": "944" } ], "symlink_target": "" }
namespace utils { namespace detail { /// Internal type-safe representation for the none type. struct none_t {}; } // namespace detail /// The none value. /// /// This has internal linkage so it is OK to define it in the header file. /// However, pointers to none from different translation units will be /// different. Just don't do that. const detail::none_t none = {}; /// Holds a data value or none. /// /// This class allows users to represent values that may be uninitialized. /// Instead of having to keep separate variables to track whether a variable is /// supposed to have a value or not, this class allows multiplexing the /// behaviors. /// /// This class is a simplified version of Boost.Optional. template< class T > class optional { /// Internal representation of the optional data value. T* _data; public: optional(void); optional(utils::detail::none_t); optional(const optional< T >&); explicit optional(const T&); ~optional(void); optional& operator=(utils::detail::none_t); optional& operator=(const T&); optional& operator=(const optional< T >&); bool operator==(const optional< T >&) const; bool operator!=(const optional< T >&) const; operator bool(void) const; const T& get(void) const; const T& get_default(const T&) const; T& get(void); }; template< class T > std::ostream& operator<<(std::ostream&, const optional< T >&); template< class T > optional< T > make_optional(const T&); } // namespace utils #endif // !defined(UTILS_OPTIONAL_HPP)
{ "content_hash": "fcfb9cf8d68e6932fbb06e5dd004bf5e", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 79, "avg_line_length": 22.91176470588235, "alnum_prop": 0.6732991014120667, "repo_name": "ayyucedemirbas/Minix-Source-Code", "id": "34bcad6ab22267ef824a276b7ab402626d03ffbd", "size": "3370", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "minix-master/external/bsd/kyua-cli/dist/utils/optional.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Arc", "bytes": "2839" }, { "name": "Assembly", "bytes": "2637160" }, { "name": "Awk", "bytes": "39398" }, { "name": "Brainfuck", "bytes": "5114" }, { "name": "C", "bytes": "45099473" }, { "name": "C++", "bytes": "622042" }, { "name": "CSS", "bytes": "254" }, { "name": "Emacs Lisp", "bytes": "4528" }, { "name": "Groff", "bytes": "6259659" }, { "name": "HTML", "bytes": "57800" }, { "name": "IGOR Pro", "bytes": "2975" }, { "name": "JavaScript", "bytes": "20307" }, { "name": "Lex", "bytes": "26563" }, { "name": "Limbo", "bytes": "4037" }, { "name": "Logos", "bytes": "14672" }, { "name": "Lua", "bytes": "4385" }, { "name": "M4", "bytes": "48559" }, { "name": "Makefile", "bytes": "893777" }, { "name": "Max", "bytes": "3667" }, { "name": "Objective-C", "bytes": "26287" }, { "name": "Perl", "bytes": "93049" }, { "name": "Perl6", "bytes": "143" }, { "name": "Prolog", "bytes": "97" }, { "name": "R", "bytes": "764" }, { "name": "Rebol", "bytes": "738" }, { "name": "Shell", "bytes": "2194049" }, { "name": "Terra", "bytes": "89" }, { "name": "Yacc", "bytes": "137952" } ], "symlink_target": "" }
'use strict'; var isInteger = require('../../utils/number').isInteger; function factory (type, config, load, typed) { var asc = load(require('../relational/compare')); function desc(a, b) { return -asc(a, b); } /** * Partition-based selection of an array or 1D matrix. * Will find the kth smallest value, and mutates the input array. * Uses Quickselect. * * Syntax: * * math.partitionSelect(x, k) * math.partitionSelect(x, k, compare) * * Examples: * * math.partitionSelect([5, 10, 1], 2); // returns 10 * math.partitionSelect(['C', 'B', 'A', 'D'], 1); // returns 'B' * * function sortByLength (a, b) { * return a.length - b.length; * } * math.partitionSelect(['Langdon', 'Tom', 'Sara'], 2, sortByLength); // returns 'Langdon' * * See also: * * sort * * @param {Matrix | Array} x A one dimensional matrix or array to sort * @param {Number} k The kth smallest value to be retrieved; zero-based index * @param {Function | 'asc' | 'desc'} [compare='asc'] * An optional comparator function. The function is called as * `compare(a, b)`, and must return 1 when a > b, -1 when a < b, * and 0 when a == b. * @return {*} Returns the kth lowest value. */ return typed('partitionSelect', { 'Array | Matrix, number': function (x, k) { return _partitionSelect(x, k, asc); }, 'Array | Matrix, number, string': function (x, k, compare) { if (compare === 'asc') { return _partitionSelect(x, k, asc); } else if (compare === 'desc') { return _partitionSelect(x, k, desc); } else { throw new Error('Compare string must be "asc" or "desc"'); } }, 'Array | Matrix, number, function': _partitionSelect }); function _partitionSelect(x, k, compare) { if (!isInteger(k) || k < 0) { throw new Error('k must be a non-negative integer'); } if (type.isMatrix(x)) { var size = x.size(); if (size.length > 1) { throw new Error('Only one dimensional matrices supported'); } return quickSelect(x.valueOf(), k, compare); } if (Array.isArray(x)) { return quickSelect(x, k, compare); } } /** * Quickselect algorithm. * Code adapted from: * http://blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html * * @param {Array} arr * @param {Number} k * @param {Function} compare * @private */ function quickSelect(arr, k, compare) { if (k >= arr.length) { throw new Error('k out of bounds'); } var from = 0; var to = arr.length - 1; // if from == to we reached the kth element while (from < to) { var r = from; var w = to; var pivot = arr[Math.floor(Math.random() * (to - from + 1)) + from]; // stop if the reader and writer meets while (r < w) { // arr[r] >= pivot if (compare(arr[r], pivot) >= 0) { // put the large values at the end var tmp = arr[w]; arr[w] = arr[r]; arr[r] = tmp; --w; } else { // the value is smaller than the pivot, skip ++r; } } // if we stepped up (r++) we need to step one down (arr[r] > pivot) if (compare(arr[r], pivot) > 0) { --r; } // the r pointer is on the end of the first k elements if (k <= r) { to = r; } else { from = r + 1; } } return arr[k]; } } exports.name = 'partitionSelect'; exports.factory = factory;
{ "content_hash": "0821a89eff32fe6bcb18ee8b8ad306a9", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 95, "avg_line_length": 26.727941176470587, "alnum_prop": 0.5375515818431912, "repo_name": "ocadni/citychrone", "id": "8805cbe4bf20af8f04ae9b9fd4497d800a13e4ea", "size": "3635", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "node_modules/mathjs/lib/function/matrix/partitionSelect.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "46395" }, { "name": "HTML", "bytes": "18635" }, { "name": "JavaScript", "bytes": "183571" }, { "name": "Jupyter Notebook", "bytes": "72" }, { "name": "Shell", "bytes": "296" } ], "symlink_target": "" }
import datetime from hashlib import sha256 import warnings from urllib import quote from attr import assoc from twisted.internet.defer import succeed from twisted.trial.unittest import TestCase from twisted.web.http_headers import Headers from txaws.credentials import AWSCredentials from txaws.client.base import RequestDetails from txaws.s3 import client from txaws.s3.acls import AccessControlPolicy from txaws.s3.model import (RequestPayment, MultipartInitiationResponse, MultipartCompletionResponse) from txaws.testing.producers import StringBodyProducer from txaws.testing.s3_tests import s3_integration_tests from txaws.service import AWSServiceEndpoint, REGION_US_EAST_1 from txaws.testing import payload from txaws.testing.integration import get_live_service from txaws.util import calculate_md5 EMPTY_CONTENT_SHA256 = sha256(b"").hexdigest().decode("ascii") class URLContextTestCase(TestCase): endpoint = AWSServiceEndpoint("https://s3.amazonaws.com/") def test_get_host_with_no_bucket(self): url_context = client.URLContext(self.endpoint) self.assertEquals(url_context.get_host(), b"s3.amazonaws.com") def test_get_host_with_bucket(self): url_context = client.URLContext(self.endpoint, "mystuff") self.assertEquals(url_context.get_host(), b"s3.amazonaws.com") def test_get_path_with_no_bucket(self): url_context = client.URLContext(self.endpoint) self.assertEquals(url_context.get_path(), b"/") def test_get_path_with_bucket(self): url_context = client.URLContext(self.endpoint, bucket="mystuff") self.assertEquals(url_context.get_path(), b"/mystuff/") def test_get_path_with_bucket_and_object(self): url_context = client.URLContext( self.endpoint, bucket="mystuff", object_name="/images/thing.jpg") self.assertEquals(url_context.get_host(), b"s3.amazonaws.com") self.assertEquals(url_context.get_path(), b"/mystuff/images/thing.jpg") def test_get_path_with_bucket_and_object_without_slash(self): url_context = client.URLContext( self.endpoint, bucket="mystuff", object_name="images/thing.jpg") self.assertEquals(url_context.get_host(), b"s3.amazonaws.com") self.assertEquals(url_context.get_path(), b"/mystuff/images/thing.jpg") def test_get_url_with_bucket_and_object_with_resource(self): url_context = client.URLContext( self.endpoint, bucket="mystuff", object_name="thing.jpg?acls") self.assertEquals( url_context.get_url(), b"https://s3.amazonaws.com/mystuff/thing.jpg?acls", ) def test_get_url_with_bucket_and_query(self): url_context = client.URLContext( self.endpoint, bucket="mystuff", object_name="?max-keys=3") self.assertEquals( url_context.get_url(), b"https://s3.amazonaws.com/mystuff/?max-keys=3", ) def test_get_url_with_custom_endpoint(self): endpoint = AWSServiceEndpoint("http://localhost/") url_context = client.URLContext(endpoint) self.assertEquals(url_context.get_url(), b"http://localhost/") def test_get_uri_with_endpoint_bucket_and_object(self): endpoint = AWSServiceEndpoint("http://localhost/") url_context = client.URLContext( endpoint, bucket="mydocs", object_name="notes.txt") self.assertEquals( url_context.get_url(), b"http://localhost/mydocs/notes.txt") def test_custom_port_endpoint(self): test_uri = b'http://0.0.0.0:12345/' endpoint = AWSServiceEndpoint(uri=test_uri) self.assertEquals(endpoint.port, 12345) self.assertEquals(endpoint.scheme, 'http') context = client.URLContext(service_endpoint=endpoint, bucket="foo", object_name="bar") self.assertEquals(context.get_host(), b'0.0.0.0') self.assertEquals(context.get_url(), test_uri + b'foo/bar') def test_custom_port_endpoint_https(self): test_uri = 'https://0.0.0.0:12345/' endpoint = AWSServiceEndpoint(uri=test_uri) self.assertEquals(endpoint.port, 12345) self.assertEquals(endpoint.scheme, 'https') context = client.URLContext(service_endpoint=endpoint, bucket="foo", object_name="bar") self.assertEquals(context.get_host(), b'0.0.0.0') self.assertEquals(context.get_url(), test_uri + b'foo/bar') class S3URLContextTestCase(TestCase): """ Tests for L{s3_url_context}. """ def test_unicode_bucket(self): """ If a unicode bucket is given, the resulting url is nevertheless bytes. """ test_uri = b"https://0.0.0.0:12345/" endpoint = AWSServiceEndpoint(uri=test_uri) bucket = u"\N{SNOWMAN}" context = client.s3_url_context(endpoint, bucket) url = context.get_url() self.assertIsInstance(url, bytes) self.assertEqual( test_uri + quote(bucket.encode("utf-8"), safe=b"") + b"/", url, ) def test_unicode_object_name(self): """ If a unicode bucket is given, the resulting url is nevertheless bytes. """ test_uri = b"https://0.0.0.0:12345/" endpoint = AWSServiceEndpoint(uri=test_uri) bucket = b"mybucket" object_name = u"\N{SNOWMAN}" context = client.s3_url_context(endpoint, bucket, object_name) url = context.get_url() self.assertIsInstance(url, bytes) self.assertEqual( test_uri + (bucket + b"/" + quote(object_name.encode("utf-8"), safe=b"")), url, ) def mock_query_factory(response_body): class Response(object): responseHeaders = Headers() class MockQuery(object): def __init__(self, credentials, details): self.__class__.credentials = credentials self.__class__.details = details def submit(self, agent, receiver_factory, utcnow): return succeed((Response(), response_body)) return MockQuery class S3ClientTestCase(TestCase): def setUp(self): self.endpoint = AWSServiceEndpoint() def test_list_buckets(self): query_factory = mock_query_factory(payload.sample_list_buckets_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_list_buckets(results): bucket1, bucket2 = results self.assertEquals(bucket1.name, "quotes") self.assertEquals( bucket1.creation_date.timetuple(), (2006, 2, 3, 16, 45, 9, 4, 34, 0)) self.assertEquals(bucket2.name, "samples") self.assertEquals( bucket2.creation_date.timetuple(), (2006, 2, 3, 16, 41, 58, 4, 34, 0)) creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.list_buckets() d.addCallback(check_query_args) d.addCallback(check_list_buckets) return d def test_create_bucket(self): query_factory = mock_query_factory(None) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"PUT", url_context=client.s3_url_context(self.endpoint, "mybucket"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.create_bucket("mybucket") d.addCallback(check_query_args) return d def test_get_bucket(self): query_factory = mock_query_factory(payload.sample_get_bucket_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint, "mybucket"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_results(listing): self.assertEquals(listing.name, "mybucket") self.assertEquals(listing.prefix, "N") self.assertEquals(listing.marker, "Ned") self.assertEquals(listing.max_keys, "40") self.assertEquals(listing.is_truncated, "false") self.assertEquals(len(listing.contents), 2) content1 = listing.contents[0] self.assertEquals(content1.key, "Nelson") self.assertEquals( content1.modification_date.timetuple(), (2006, 1, 1, 12, 0, 0, 6, 1, 0)) self.assertEquals( content1.etag, '"828ef3fdfa96f00ad9f27c383fc9ac7f"') self.assertEquals(content1.size, "5") self.assertEquals(content1.storage_class, "STANDARD") owner = content1.owner self.assertEquals(owner.id, "bcaf1ffd86f41caff1a493dc2ad8c2c281e37522a640e16" "1ca5fb16fd081034f") self.assertEquals(owner.display_name, "webfile") creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_bucket("mybucket") d.addCallback(check_query_args) d.addCallback(check_results) return d def test_get_bucket_pagination(self): """ L{S3Client.get_bucket} accepts C{marker} and C{max_keys} arguments to control pagination of results. """ query_factory = mock_query_factory(payload.sample_get_bucket_result) def check_query_args(passthrough): self.assertEqual( b"http:///mybucket/?marker=abcdef&max-keys=42", query_factory.details.url_context.get_encoded_url(), ) return passthrough creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_bucket("mybucket", marker="abcdef", max_keys=42) d.addCallback(check_query_args) return d def test_get_bucket_prefix(self): """ L{S3Client.get_bucket} accepts a C{prefix} argument to ask the server to limit its response to objects beginning with a certain prefix. """ query_factory = mock_query_factory(payload.sample_get_bucket_result) def check_query_args(passthrough): self.assertEqual( b"http:///mybucket/?prefix=foobar", query_factory.details.url_context.get_encoded_url(), ) return passthrough creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_bucket("mybucket", prefix=b"foobar") d.addCallback(check_query_args) return d def test_get_bucket_location(self): """ L{S3Client.get_bucket_location} creates a L{Query} to get a bucket's location. It parses the returned C{LocationConstraint} XML document and returns a C{Deferred} that requests the bucket's location constraint. """ query_factory = mock_query_factory(payload.sample_get_bucket_location_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint, "mybucket", "?location"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_results(location_constraint): self.assertEquals(location_constraint, "EU") creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_bucket_location("mybucket") d.addCallback(check_query_args) d.addCallback(check_results) return d def test_get_bucket_lifecycle_multiple_rules(self): """ L{S3Client.get_bucket_lifecycle} creates a L{Query} to get a bucket's lifecycle. It parses the returned C{LifecycleConfiguration} XML document and returns a C{Deferred} that requests the bucket's lifecycle configuration with multiple rules. """ query_factory = mock_query_factory(payload.sample_s3_get_bucket_lifecycle_multiple_rules_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint, "mybucket", "?lifecycle"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_results(lifecycle_config): self.assertTrue(len(lifecycle_config.rules) == 2) rule = lifecycle_config.rules[1] self.assertEquals(rule.id, 'another-id') self.assertEquals(rule.prefix, 'another-logs') self.assertEquals(rule.status, 'Disabled') self.assertEquals(rule.expiration, 37) creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_bucket_lifecycle("mybucket") d.addCallback(check_query_args) d.addCallback(check_results) return d def test_get_bucket_lifecycle(self): """ L{S3Client.get_bucket_lifecycle} creates a L{Query} to get a bucket's lifecycle. It parses the returned C{LifecycleConfiguration} XML document and returns a C{Deferred} that requests the bucket's lifecycle configuration. """ query_factory = mock_query_factory(payload.sample_s3_get_bucket_lifecycle_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint, "mybucket", "?lifecycle"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_results(lifecycle_config): rule = lifecycle_config.rules[0] self.assertEquals(rule.id, '30-day-log-deletion-rule') self.assertEquals(rule.prefix, 'logs') self.assertEquals(rule.status, 'Enabled') self.assertEquals(rule.expiration, 30) creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_bucket_lifecycle("mybucket") d.addCallback(check_query_args) d.addCallback(check_results) return d def test_get_bucket_website_config(self): """ L{S3Client.get_bucket_website_config} creates a L{Query} to get a bucket's website configurtion. It parses the returned C{WebsiteConfiguration} XML document and returns a C{Deferred} that requests the bucket's website configuration. """ query_factory = mock_query_factory(payload.sample_s3_get_bucket_website_no_error_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint, "mybucket", "?website"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_results(website_config): self.assertEquals(website_config.index_suffix, "index.html") self.assertEquals(website_config.error_key, None) creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_bucket_website_config("mybucket") d.addCallback(check_query_args) d.addCallback(check_results) return d def test_get_bucket_website_config_with_error_doc(self): """ L{S3Client.get_bucket_website_config} creates a L{Query} to get a bucket's website configurtion. It parses the returned C{WebsiteConfiguration} XML document and returns a C{Deferred} that requests the bucket's website configuration with the error document. """ query_factory = mock_query_factory(payload.sample_s3_get_bucket_website_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint, "mybucket", "?website"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_results(website_config): self.assertEquals(website_config.index_suffix, "index.html") self.assertEquals(website_config.error_key, "404.html") creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_bucket_website_config("mybucket") d.addCallback(check_query_args) d.addCallback(check_results) return d def test_get_bucket_notification_config(self): """ L{S3Client.get_bucket_notification_config} creates a L{Query} to get a bucket's notification configuration. It parses the returned C{NotificationConfiguration} XML document and returns a C{Deferred} that requests the bucket's notification configuration. """ query_factory = mock_query_factory(payload.sample_s3_get_bucket_notification_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint, "mybucket", "?notification"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_results(notification_config): self.assertEquals(notification_config.topic, None) self.assertEquals(notification_config.event, None) creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_bucket_notification_config("mybucket") d.addCallback(check_query_args) d.addCallback(check_results) return d def test_get_bucket_notification_config_with_topic(self): """ L{S3Client.get_bucket_notification_config} creates a L{Query} to get a bucket's notification configuration. It parses the returned C{NotificationConfiguration} XML document and returns a C{Deferred} that requests the bucket's notification configuration with a topic. """ query_factory = mock_query_factory(payload.sample_s3_get_bucket_notification_with_topic_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint, "mybucket", "?notification"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_results(notification_config): self.assertEquals(notification_config.topic, "arn:aws:sns:us-east-1:123456789012:myTopic") self.assertEquals(notification_config.event, "s3:ReducedRedundancyLostObject") creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_bucket_notification_config("mybucket") d.addCallback(check_query_args) d.addCallback(check_results) return d def test_get_bucket_versioning_config(self): """ L{S3Client.get_bucket_versioning_configuration} creates a L{Query} to get a bucket's versioning status. It parses the returned C{VersioningConfiguration} XML document and returns a C{Deferred} that requests the bucket's versioning configuration. """ query_factory = mock_query_factory(payload.sample_s3_get_bucket_versioning_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint, "mybucket", "?versioning"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_results(versioning_config): self.assertEquals(versioning_config.status, None) creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_bucket_versioning_config("mybucket") d.addCallback(check_query_args) d.addCallback(check_results) return d def test_get_bucket_versioning_config_enabled(self): """ L{S3Client.get_bucket_versioning_config} creates a L{Query} to get a bucket's versioning configuration. It parses the returned C{VersioningConfiguration} XML document and returns a C{Deferred} that requests the bucket's versioning configuration that has a enabled C{Status}. """ query_factory = mock_query_factory(payload.sample_s3_get_bucket_versioning_enabled_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint, "mybucket", "?versioning"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_results(versioning_config): self.assertEquals(versioning_config.status, 'Enabled') creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_bucket_versioning_config("mybucket") d.addCallback(check_query_args) d.addCallback(check_results) return d def test_get_bucket_versioning_config_mfa_disabled(self): """ L{S3Client.get_bucket_versioning_config} creates a L{Query} to get a bucket's versioning configuration. It parses the returned C{VersioningConfiguration} XML document and returns a C{Deferred} that requests the bucket's versioning configuration that has a disabled C{MfaDelete}. """ query_factory = mock_query_factory(payload.sample_s3_get_bucket_versioning_mfa_disabled_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint, "mybucket", "?versioning"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_results(versioning_config): self.assertEquals(versioning_config.mfa_delete, 'Disabled') creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_bucket_versioning_config("mybucket") d.addCallback(check_query_args) d.addCallback(check_results) return d def test_delete_bucket(self): query_factory = mock_query_factory(None) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"DELETE", url_context=client.s3_url_context(self.endpoint, "mybucket"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.delete_bucket("mybucket") d.addCallback(check_query_args) return d def test_put_bucket_acl(self): query_factory = mock_query_factory(payload.sample_access_control_policy_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"PUT", url_context=client.s3_url_context(self.endpoint, "mybucket", "?acl"), content_sha256=sha256( payload.sample_access_control_policy_result ).hexdigest().decode("ascii"), ), assoc(query_factory.details, body_producer=None), ) return passthrough def check_result(result): self.assertIsInstance(result, AccessControlPolicy) creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) policy = AccessControlPolicy.from_xml( payload.sample_access_control_policy_result) d = s3.put_bucket_acl("mybucket", policy) d.addCallback(check_query_args) d.addCallback(check_result) return d def test_get_bucket_acl(self): query_factory = mock_query_factory(payload.sample_access_control_policy_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint, "mybucket", "?acl"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_result(result): self.assert_(isinstance(result, AccessControlPolicy)) creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_bucket_acl("mybucket") d.addCallback(check_query_args) d.addCallback(check_result) return d def test_put_request_payment(self): """ L{S3Client.put_request_payment} creates a L{Query} to set payment information. An C{RequestPaymentConfiguration} XML document is built and sent to the endpoint and a C{Deferred} is returned that fires with the results of the request. """ query_factory = mock_query_factory(None) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") xml = ("<RequestPaymentConfiguration " 'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n' " <Payer>Requester</Payer>\n" "</RequestPaymentConfiguration>") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"PUT", url_context=client.s3_url_context(self.endpoint, "mybucket", "?requestPayment"), content_sha256=sha256(xml).hexdigest().decode("ascii"), ), assoc(query_factory.details, body_producer=None), ) return passthrough creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.put_request_payment("mybucket", "Requester") d.addCallback(check_query_args) return d def test_get_request_payment(self): """ L{S3Client.get_request_payment} creates a L{Query} to get payment information. It parses the returned C{RequestPaymentConfiguration} XML document and returns a C{Deferred} that fires with the payer's name. """ query_factory = mock_query_factory(payload.sample_request_payment) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint, "mybucket", "?requestPayment"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_request_payment(result): self.assertEquals(result, "Requester") creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_request_payment("mybucket") d.addCallback(check_query_args) d.addCallback(check_request_payment) return d def test_put_object(self): query_factory = mock_query_factory(None) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"PUT", url_context=client.s3_url_context(self.endpoint, "mybucket", "objectname"), headers=Headers({u"content-type": [u"text/plain"]}), metadata={"key": "some meta data"}, amz_headers={ "acl": "public-read", }, content_sha256=sha256(b"some data").hexdigest().decode("ascii"), ), assoc(query_factory.details, body_producer=None), ) return passthrough creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.put_object( "mybucket", "objectname", "some data", content_type="text/plain", metadata={"key": "some meta data"}, amz_headers={"acl": "public-read"}, ) d.addCallback(check_query_args) return d def test_put_object_with_custom_body_producer(self): query_factory = mock_query_factory(None) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"PUT", url_context=client.s3_url_context(self.endpoint, "mybucket", "objectname"), headers=Headers({u"content-type": [u"text/plain"]}), metadata={"key": "some meta data"}, amz_headers={ "acl": "public-read", }, body_producer=string_producer, ), query_factory.details, ) string_producer = StringBodyProducer("some data") creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.put_object( "mybucket", "objectname", content_type="text/plain", metadata={"key": "some meta data"}, amz_headers={"acl": "public-read"}, body_producer=string_producer, ) d.addCallback(check_query_args) return d def test_copy_object(self): """ L{S3Client.copy_object} creates a L{Query} to copy an object from one bucket to another. """ query_factory = mock_query_factory(None) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"PUT", url_context=client.s3_url_context(self.endpoint, "newbucket", "newobjectname"), metadata={"key": "some meta data"}, amz_headers={ "copy-source": "/mybucket/objectname", }, content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.copy_object( "mybucket", "objectname", "newbucket", "newobjectname", metadata={"key": "some meta data"}, ) d.addCallback(check_query_args) return d def test_get_object(self): query_factory = mock_query_factory(None) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint, "mybucket", "objectname"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_object("mybucket", "objectname") d.addCallback(check_query_args) return d def test_head_object(self): query_factory = mock_query_factory(None) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"HEAD", url_context=client.s3_url_context(self.endpoint, "mybucket", "objectname"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.head_object("mybucket", "objectname") d.addCallback(check_query_args) return d def test_delete_object(self): query_factory = mock_query_factory(None) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"DELETE", url_context=client.s3_url_context(self.endpoint, "mybucket", "objectname"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.delete_object("mybucket", "objectname") d.addCallback(check_query_args) return d def test_put_object_acl(self): query_factory = mock_query_factory(payload.sample_access_control_policy_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"PUT", url_context=client.s3_url_context(self.endpoint, "mybucket", "myobject?acl"), content_sha256=sha256( payload.sample_access_control_policy_result ).hexdigest().decode("ascii"), ), assoc(query_factory.details, body_producer=None), ) return passthrough def check_result(result): self.assertIsInstance(result, AccessControlPolicy) creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) policy = AccessControlPolicy.from_xml( payload.sample_access_control_policy_result) d = s3.put_object_acl("mybucket", "myobject", policy) d.addCallback(check_query_args) d.addCallback(check_result) return d def test_get_object_acl(self): query_factory = mock_query_factory(payload.sample_access_control_policy_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"GET", url_context=client.s3_url_context(self.endpoint, "mybucket", "myobject?acl"), content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_result(result): self.assertIsInstance(result, AccessControlPolicy) creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.get_object_acl("mybucket", "myobject") d.addCallback(check_query_args) d.addCallback(check_result) return d def test_init_multipart_upload(self): query_factory = mock_query_factory(payload.sample_s3_init_multipart_upload_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"POST", url_context=client.s3_url_context( self.endpoint, "example-bucket", "example-object?uploads", ), amz_headers={ "acl": "public", }, content_sha256=EMPTY_CONTENT_SHA256, ), query_factory.details, ) return passthrough def check_result(result): self.assert_(isinstance(result, MultipartInitiationResponse)) self.assertEqual(result.bucket, "example-bucket") self.assertEqual(result.object_name, "example-object") self.assertEqual(result.upload_id, "deadbeef") creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.init_multipart_upload("example-bucket", "example-object", amz_headers={"acl": "public"}) d.addCallback(check_query_args) d.addCallback(check_result) return d def test_upload_part(self): query_factory = mock_query_factory(None) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"PUT", url_context=client.s3_url_context( self.endpoint, "example-bucket", "example-object?partNumber=3&uploadId=testid" ), content_sha256=sha256(b"some data").hexdigest().decode("ascii"), ), assoc(query_factory.details, body_producer=None), ) return passthrough creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.upload_part( "example-bucket", "example-object", "testid", 3, "some data", ) d.addCallback(check_query_args) return d def test_complete_multipart_upload(self): query_factory = mock_query_factory(payload.sample_s3_complete_multipart_upload_result) def check_query_args(passthrough): self.assertEqual(query_factory.credentials.access_key, "foo") self.assertEqual(query_factory.credentials.secret_key, "bar") xml = ( "<CompleteMultipartUpload>\n" "<Part>\n<PartNumber>1</PartNumber>\n<ETag>a</ETag>\n" "</Part>\n<Part>\n<PartNumber>2</PartNumber>\n" "<ETag>b</ETag>\n</Part>\n</CompleteMultipartUpload>" ) self.assertEqual( RequestDetails( service=b"s3", region=REGION_US_EAST_1, method=b"POST", url_context=client.s3_url_context( self.endpoint, "example-bucket", "example-object?uploadId=testid" ), content_sha256=sha256(xml).hexdigest().decode("ascii"), ), assoc(query_factory.details, body_producer=None), ) return passthrough def check_result(result): self.assert_(isinstance(result, MultipartCompletionResponse)) self.assertEqual(result.bucket, "example-bucket") self.assertEqual(result.object_name, "example-object") self.assertEqual(result.location, "http://example-bucket.s3.amazonaws.com/example-object") self.assertEqual(result.etag, '"3858f62230ac3c915f300c664312c11f-9"') creds = AWSCredentials("foo", "bar") s3 = client.S3Client(creds, query_factory=query_factory) d = s3.complete_multipart_upload( "example-bucket", "example-object", "testid", [(1, "a"), (2, "b")] ) d.addCallback(check_query_args) d.addCallback(check_result) return d class QueryTestCase(TestCase): creds = AWSCredentials(access_key="fookeyid", secret_key="barsecretkey") endpoint = AWSServiceEndpoint("https://choopy.s3.amazonaws.com/") utc_instant = datetime.datetime(2015, 8, 30, 12, 36) def fake_sign(self, headers, data, url_context, instant, method): return "Authorization header" def test_default_creation(self): query = client.Query(action="PUT") self.assertEquals(query.bucket, None) self.assertEquals(query.object_name, None) self.assertEquals(query.data, "") self.assertEquals(query.content_type, None) self.assertEquals(query.metadata, {}) def test_default_endpoint(self): query = client.Query(action="PUT") self.assertEquals(self.endpoint.host, "choopy.s3.amazonaws.com") self.assertEquals(query.endpoint.host, "s3.amazonaws.com") self.assertEquals(self.endpoint.method, "GET") self.assertEquals(query.endpoint.method, "PUT") def test_set_content_type_no_object_name(self): query = client.Query(action="PUT") query.set_content_type() self.assertEquals(query.content_type, None) def test_set_content_type(self): query = client.Query(action="PUT", object_name="advicedog.jpg") query.set_content_type() self.assertEquals(query.content_type, "image/jpeg") def test_set_content_type_with_content_type_already_set(self): query = client.Query( action="PUT", object_name="data.txt", content_type="text/csv") query.set_content_type() self.assertNotEquals(query.content_type, "text/plain") self.assertEquals(query.content_type, "text/csv") def test_get_headers(self): query = client.Query( action="GET", creds=self.creds, bucket="mystuff", object_name="/images/thing.jpg") headers = query.get_headers(self.utc_instant) self.assertEquals(headers.get("Content-Type"), "image/jpeg") self.assertEquals( headers.get("x-amz-content-sha256"), sha256(b"").hexdigest(), ) self.assertEqual(headers.get("x-amz-date"), "20150830T123600Z") self.assertTrue( headers.get("Authorization").startswith("AWS4-HMAC-SHA256")) self.assertTrue(len(headers.get("Authorization")) > 40) def test_get_headers_with_data(self): query = client.Query( action="PUT", creds=self.creds, bucket="mystuff", object_name="/images/thing.jpg", data="BINARY IMAGE DATA") headers = query.get_headers(self.utc_instant) self.assertEquals(headers.get("Content-Type"), "image/jpeg") self.assertEqual(headers.get("x-amz-date"), "20150830T123600Z") self.assertTrue( headers.get("Authorization").startswith("AWS4-HMAC-SHA256")) self.assertTrue(len(headers.get("Authorization")) > 40) def test_sign(self): query = client.Query(action="PUT", creds=self.creds, data="data") signed = query.sign(headers={"x-amz-date": "20150830T123600Z"}, data="some data", url_context=client.URLContext(query.endpoint, query.bucket, query.object_name), instant=self.utc_instant, method=query.action) self.assertEquals( signed, 'AWS4-HMAC-SHA256 ' 'Credential=fookeyid/20150830/us-east-1/s3/aws4_request, ' 'SignedHeaders=host;x-amz-date, ' 'Signature=99e8224887926c76e8e3053cf10f26249798fe2274d717b7d28e6ef' '3311d1735') def test_object_query(self): """ Test that a request addressing an object is created correctly. """ DATA = b"objectData" DIGEST = sha256(DATA).hexdigest() request = client.Query( action="PUT", bucket="somebucket", object_name="object/name/here", data=DATA, content_type="text/plain", metadata={"foo": "bar"}, amz_headers={"acl": "public-read"}, creds=self.creds, endpoint=self.endpoint) request.sign = self.fake_sign self.assertEqual(request.action, "PUT") headers = request.get_headers(self.utc_instant) self.assertNotEqual(headers.pop("x-amz-date"), "") self.assertEqual(headers, {"Authorization": "Authorization header", "Content-Type": "text/plain", "x-amz-content-sha256": DIGEST, "x-amz-meta-foo": "bar", "x-amz-acl": "public-read"}) self.assertEqual(request.data, "objectData") def test_bucket_query(self): """ Test that a request addressing a bucket is created correctly. """ DIGEST = ("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b785" "2b855") query = client.Query( action="GET", bucket="somebucket", creds=self.creds, endpoint=self.endpoint) query.sign = self.fake_sign self.assertEqual(query.action, "GET") headers = query.get_headers(self.utc_instant) self.assertNotEqual(headers.pop("x-amz-date"), "") self.assertEqual( headers, { "Authorization": "Authorization header", "x-amz-content-sha256": DIGEST}) self.assertEqual(query.data, "") def test_submit(self): """ Submitting the request should invoke getPage correctly. """ class StubQuery(client.Query): def __init__(query, action, creds, endpoint, bucket, body_producer=None, receiver_factory=None): super(StubQuery, query).__init__( action=action, creds=creds, bucket=bucket) self.assertEquals(action, "GET") self.assertEqual(creds.access_key, "fookeyid") self.assertEqual(creds.secret_key, "barsecretkey") self.assertEqual(query.bucket, "somebucket") self.assertEqual(query.object_name, None) self.assertEqual(query.data, "") self.assertEqual(query.metadata, {}) def submit(query): return succeed("") query = StubQuery(action="GET", creds=self.creds, endpoint=self.endpoint, bucket="somebucket") return query.submit() def test_authentication(self): query = client.Query( action="GET", creds=self.creds, endpoint=self.endpoint) query.sign = self.fake_sign headers = query.get_headers(self.utc_instant) self.assertEqual( headers["Authorization"], "Authorization header") def test_date_attribute_deprecated(self): query = client.Query( action="GET", creds=self.creds, endpoint=self.endpoint) with warnings.catch_warnings(record=True) as caught_warnings: self.assertGreater(len(query.date), 20) self.assertEqual(len(caught_warnings), 1) (warning,) = caught_warnings self.assertTrue(issubclass(warning.category, DeprecationWarning)) self.assertEqual( str(warning.message), "txaws.s3.client.Query.date is a deprecated attribute") def test_date_attribute_settable(self): query = client.Query( action="GET", creds=self.creds, endpoint=self.endpoint) query.date = "XYZ" with warnings.catch_warnings(record=True): self.assertEqual(query.date, "XYZ") class MiscellaneousTestCase(TestCase): def test_content_md5(self): self.assertEqual(calculate_md5("somedata"), "rvr3UC1SmUw7AZV2NqPN0g==") def test_request_payment_enum(self): """ Only 'Requester' or 'BucketOwner' may be provided when a L{RequestPayment} is instantiated. """ RequestPayment("Requester") RequestPayment("BucketOwner") self.assertRaises(ValueError, RequestPayment, "Bob") def get_live_client(case): return get_live_service(case).get_s3_client() class LiveS3TestCase(s3_integration_tests(get_live_client)): """ Tests for the real S3 implementation against AWS itself. """
{ "content_hash": "3b7e12121afe0867e0eb592759cc176a", "timestamp": "", "source": "github", "line_count": 1361, "max_line_length": 104, "avg_line_length": 41.262307127112415, "alnum_prop": 0.5824637629545212, "repo_name": "oubiwann/txaws", "id": "77dbe6af7479bf027c735b4cd230e425b002c0bd", "size": "56158", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "txaws/s3/tests/test_client.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "3962" }, { "name": "Python", "bytes": "606696" }, { "name": "Shell", "bytes": "44" } ], "symlink_target": "" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sdm.core.util.mail; /** * * @author Htoonlin */ public class MailInfo { private String from; private String to; private String cc; private String bcc; private String subject; private String body; public MailInfo() { } public MailInfo(String to, String subject, String body) { this.to = to; this.subject = subject; this.body = body; } public MailInfo(String from, String to, String subject, String body) { this.from = from; this.to = to; this.subject = subject; this.body = body; } public MailInfo(String from, String to, String cc, String bcc, String subject, String body) { this.from = from; this.to = to; this.cc = cc; this.bcc = bcc; this.subject = subject; this.body = body; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getCc() { return cc; } public void setCc(String cc) { this.cc = cc; } public String getBcc() { return bcc; } public void setBcc(String bcc) { this.bcc = bcc; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } }
{ "content_hash": "8f6a3ae7f28d61cd5c181f39367066e6", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 97, "avg_line_length": 20.537634408602152, "alnum_prop": 0.5408376963350785, "repo_name": "Htoonlin/MasterAPI", "id": "7c5586bf730aa0806ddaa13ae0c40584689d6546", "size": "1910", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/sdm/core/util/mail/MailInfo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "361538" } ], "symlink_target": "" }
/*! * Modernizr v2.6.2 * www.modernizr.com * * Copyright (c) Faruk Ates, Paul Irish, Alex Sexton * Available under the BSD and MIT licenses: www.modernizr.com/license/ */ /* * Modernizr tests which native CSS3 and HTML5 features are available in * the current UA and makes the results available to you in two ways: * as properties on a global Modernizr object, and as classes on the * <html> element. This information allows you to progressively enhance * your pages with a granular level of control over the experience. * * Modernizr has an optional (not included) conditional resource loader * called Modernizr.load(), based on Yepnope.js (yepnopejs.com). * To get a build that includes Modernizr.load(), as well as choosing * which tests to include, go to www.modernizr.com/download/ * * Authors Faruk Ates, Paul Irish, Alex Sexton * Contributors Ryan Seddon, Ben Alman */ window.Modernizr = (function( window, document, undefined ) { var version = '2.6.2', Modernizr = {}, /*>>cssclasses*/ // option for enabling the HTML classes to be added enableClasses = true, /*>>cssclasses*/ docElement = document.documentElement, /** * Create our "modernizr" element that we do most feature tests on. */ mod = 'modernizr', modElem = document.createElement(mod), mStyle = modElem.style, /** * Create the input element for various Web Forms feature tests. */ inputElem /*>>inputelem*/ = document.createElement('input') /*>>inputelem*/ , /*>>smile*/ smile = ':)', /*>>smile*/ toString = {}.toString, // TODO :: make the prefixes more granular /*>>prefixes*/ // List of property values to set for css tests. See ticket #21 prefixes = ' -webkit- -moz- -o- -ms- '.split(' '), /*>>prefixes*/ /*>>domprefixes*/ // Following spec is to expose vendor-specific style properties as: // elem.style.WebkitBorderRadius // and the following would be incorrect: // elem.style.webkitBorderRadius // Webkit ghosts their properties in lowercase but Opera & Moz do not. // Microsoft uses a lowercase `ms` instead of the correct `Ms` in IE8+ // erik.eae.net/archives/2008/03/10/21.48.10/ // More here: github.com/Modernizr/Modernizr/issues/issue/21 omPrefixes = 'Webkit Moz O ms', cssomPrefixes = omPrefixes.split(' '), domPrefixes = omPrefixes.toLowerCase().split(' '), /*>>domprefixes*/ /*>>ns*/ ns = {'svg': 'http://www.w3.org/2000/svg'}, /*>>ns*/ tests = {}, inputs = {}, attrs = {}, classes = [], slice = classes.slice, featureName, // used in testing loop /*>>teststyles*/ // Inject element with style element and some CSS rules injectElementWithStyles = function( rule, callback, nodes, testnames ) { var style, ret, node, docOverflow, div = document.createElement('div'), // After page load injecting a fake body doesn't work so check if body exists body = document.body, // IE6 and 7 won't return offsetWidth or offsetHeight unless it's in the body element, so we fake it. fakeBody = body || document.createElement('body'); if ( parseInt(nodes, 10) ) { // In order not to give false positives we create a node for each test // This also allows the method to scale for unspecified uses while ( nodes-- ) { node = document.createElement('div'); node.id = testnames ? testnames[nodes] : mod + (nodes + 1); div.appendChild(node); } } // <style> elements in IE6-9 are considered 'NoScope' elements and therefore will be removed // when injected with innerHTML. To get around this you need to prepend the 'NoScope' element // with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements. // msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx // Documents served as xml will throw if using &shy; so use xml friendly encoded version. See issue #277 style = ['&#173;','<style id="s', mod, '">', rule, '</style>'].join(''); div.id = mod; // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody. // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270 (body ? div : fakeBody).innerHTML += style; fakeBody.appendChild(div); if ( !body ) { //avoid crashing IE8, if background image is used fakeBody.style.background = ''; //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible fakeBody.style.overflow = 'hidden'; docOverflow = docElement.style.overflow; docElement.style.overflow = 'hidden'; docElement.appendChild(fakeBody); } ret = callback(div, rule); // If this is done after page load we don't want to remove the body so check if body exists if ( !body ) { fakeBody.parentNode.removeChild(fakeBody); docElement.style.overflow = docOverflow; } else { div.parentNode.removeChild(div); } return !!ret; }, /*>>teststyles*/ /*>>mq*/ // adapted from matchMedia polyfill // by Scott Jehl and Paul Irish // gist.github.com/786768 testMediaQuery = function( mq ) { var matchMedia = window.matchMedia || window.msMatchMedia; if ( matchMedia ) { return matchMedia(mq).matches; } var bool; injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) { bool = (window.getComputedStyle ? getComputedStyle(node, null) : node.currentStyle)['position'] == 'absolute'; }); return bool; }, /*>>mq*/ /*>>hasevent*/ // // isEventSupported determines if a given element supports the given event // kangax.github.com/iseventsupported/ // // The following results are known incorrects: // Modernizr.hasEvent("webkitTransitionEnd", elem) // false negative // Modernizr.hasEvent("textInput") // in Webkit. github.com/Modernizr/Modernizr/issues/333 // ... isEventSupported = (function() { var TAGNAMES = { 'select': 'input', 'change': 'input', 'submit': 'form', 'reset': 'form', 'error': 'img', 'load': 'img', 'abort': 'img' }; function isEventSupported( eventName, element ) { element = element || document.createElement(TAGNAMES[eventName] || 'div'); eventName = 'on' + eventName; // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those var isSupported = eventName in element; if ( !isSupported ) { // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element if ( !element.setAttribute ) { element = document.createElement('div'); } if ( element.setAttribute && element.removeAttribute ) { element.setAttribute(eventName, ''); isSupported = is(element[eventName], 'function'); // If property was created, "remove it" (by setting value to `undefined`) if ( !is(element[eventName], 'undefined') ) { element[eventName] = undefined; } element.removeAttribute(eventName); } } element = null; return isSupported; } return isEventSupported; })(), /*>>hasevent*/ // TODO :: Add flag for hasownprop ? didn't last time // hasOwnProperty shim by kangax needed for Safari 2.0 support _hasOwnProperty = ({}).hasOwnProperty, hasOwnProp; if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) { hasOwnProp = function (object, property) { return _hasOwnProperty.call(object, property); }; } else { hasOwnProp = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */ return ((property in object) && is(object.constructor.prototype[property], 'undefined')); }; } // Adapted from ES5-shim https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js // es5.github.com/#x15.3.4.5 if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { var target = this; if (typeof target != "function") { throw new TypeError(); } var args = slice.call(arguments, 1), bound = function () { if (this instanceof bound) { var F = function(){}; F.prototype = target.prototype; var self = new F(); var result = target.apply( self, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return self; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; return bound; }; } /** * setCss applies given styles to the Modernizr DOM node. */ function setCss( str ) { mStyle.cssText = str; } /** * setCssAll extrapolates all vendor-specific css strings. */ function setCssAll( str1, str2 ) { return setCss(prefixes.join(str1 + ';') + ( str2 || '' )); } /** * is returns a boolean for if typeof obj is exactly type. */ function is( obj, type ) { return typeof obj === type; } /** * contains returns a boolean for if substr is found within str. */ function contains( str, substr ) { return !!~('' + str).indexOf(substr); } /*>>testprop*/ // testProps is a generic CSS / DOM property test. // In testing support for a given CSS property, it's legit to test: // `elem.style[styleName] !== undefined` // If the property is supported it will return an empty string, // if unsupported it will return undefined. // We'll take advantage of this quick test and skip setting a style // on our modernizr element, but instead just testing undefined vs // empty string. // Because the testing of the CSS property names (with "-", as // opposed to the camelCase DOM properties) is non-portable and // non-standard but works in WebKit and IE (but not Gecko or Opera), // we explicitly reject properties with dashes so that authors // developing in WebKit or IE first don't end up with // browser-specific content by accident. function testProps( props, prefixed ) { for ( var i in props ) { var prop = props[i]; if ( !contains(prop, "-") && mStyle[prop] !== undefined ) { return prefixed == 'pfx' ? prop : true; } } return false; } /*>>testprop*/ // TODO :: add testDOMProps /** * testDOMProps is a generic DOM property test; if a browser supports * a certain property, it won't return undefined for it. */ function testDOMProps( props, obj, elem ) { for ( var i in props ) { var item = obj[props[i]]; if ( item !== undefined) { // return the property name as a string if (elem === false) return props[i]; // let's bind a function if (is(item, 'function')){ // default to autobind unless override return item.bind(elem || obj); } // return the unbound function or obj or value return item; } } return false; } /*>>testallprops*/ /** * testPropsAll tests a list of DOM properties we want to check against. * We specify literally ALL possible (known and/or likely) properties on * the element including the non-vendor prefixed one, for forward- * compatibility. */ function testPropsAll( prop, prefixed, elem ) { var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1), props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' '); // did they call .prefixed('boxSizing') or are we just testing a prop? if(is(prefixed, "string") || is(prefixed, "undefined")) { return testProps(props, prefixed); // otherwise, they called .prefixed('requestAnimationFrame', window[, elem]) } else { props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' '); return testDOMProps(props, prefixed, elem); } } /*>>testallprops*/ /** * Tests * ----- */ // The *new* flexbox // dev.w3.org/csswg/css3-flexbox tests['flexbox'] = function() { return testPropsAll('flexWrap'); }; // The *old* flexbox // www.w3.org/TR/2009/WD-css3-flexbox-20090723/ tests['flexboxlegacy'] = function() { return testPropsAll('boxDirection'); }; // On the S60 and BB Storm, getContext exists, but always returns undefined // so we actually have to call getContext() to verify // github.com/Modernizr/Modernizr/issues/issue/97/ tests['canvas'] = function() { var elem = document.createElement('canvas'); return !!(elem.getContext && elem.getContext('2d')); }; tests['canvastext'] = function() { return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function')); }; // webk.it/70117 is tracking a legit WebGL feature detect proposal // We do a soft detect which may false positive in order to avoid // an expensive context creation: bugzil.la/732441 tests['webgl'] = function() { return !!window.WebGLRenderingContext; }; /* * The Modernizr.touch test only indicates if the browser supports * touch events, which does not necessarily reflect a touchscreen * device, as evidenced by tablets running Windows 7 or, alas, * the Palm Pre / WebOS (touch) phones. * * Additionally, Chrome (desktop) used to lie about its support on this, * but that has since been rectified: crbug.com/36415 * * We also test for Firefox 4 Multitouch Support. * * For more info, see: modernizr.github.com/Modernizr/touch.html */ tests['touch'] = function() { var bool; if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) { bool = true; } else { injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function( node ) { bool = node.offsetTop === 9; }); } return bool; }; // geolocation is often considered a trivial feature detect... // Turns out, it's quite tricky to get right: // // Using !!navigator.geolocation does two things we don't want. It: // 1. Leaks memory in IE9: github.com/Modernizr/Modernizr/issues/513 // 2. Disables page caching in WebKit: webk.it/43956 // // Meanwhile, in Firefox < 8, an about:config setting could expose // a false positive that would throw an exception: bugzil.la/688158 tests['geolocation'] = function() { return 'geolocation' in navigator; }; tests['postmessage'] = function() { return !!window.postMessage; }; // Chrome incognito mode used to throw an exception when using openDatabase // It doesn't anymore. tests['websqldatabase'] = function() { return !!window.openDatabase; }; // Vendors had inconsistent prefixing with the experimental Indexed DB: // - Webkit's implementation is accessible through webkitIndexedDB // - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB // For speed, we don't test the legacy (and beta-only) indexedDB tests['indexedDB'] = function() { return !!testPropsAll("indexedDB", window); }; // documentMode logic from YUI to filter out IE8 Compat Mode // which false positives. tests['hashchange'] = function() { return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7); }; // Per 1.6: // This used to be Modernizr.historymanagement but the longer // name has been deprecated in favor of a shorter and property-matching one. // The old API is still available in 1.6, but as of 2.0 will throw a warning, // and in the first release thereafter disappear entirely. tests['history'] = function() { return !!(window.history && history.pushState); }; tests['draganddrop'] = function() { var div = document.createElement('div'); return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div); }; // FF3.6 was EOL'ed on 4/24/12, but the ESR version of FF10 // will be supported until FF19 (2/12/13), at which time, ESR becomes FF17. // FF10 still uses prefixes, so check for it until then. // for more ESR info, see: mozilla.org/en-US/firefox/organizations/faq/ tests['websockets'] = function() { return 'WebSocket' in window || 'MozWebSocket' in window; }; // css-tricks.com/rgba-browser-support/ tests['rgba'] = function() { // Set an rgba() color and check the returned value setCss('background-color:rgba(150,255,150,.5)'); return contains(mStyle.backgroundColor, 'rgba'); }; tests['hsla'] = function() { // Same as rgba(), in fact, browsers re-map hsla() to rgba() internally, // except IE9 who retains it as hsla setCss('background-color:hsla(120,40%,100%,.5)'); return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla'); }; tests['multiplebgs'] = function() { // Setting multiple images AND a color on the background shorthand property // and then querying the style.background property value for the number of // occurrences of "url(" is a reliable method for detecting ACTUAL support for this! setCss('background:url(https://),url(https://),red url(https://)'); // If the UA supports multiple backgrounds, there should be three occurrences // of the string "url(" in the return value for elemStyle.background return (/(url\s*\(.*?){3}/).test(mStyle.background); }; // this will false positive in Opera Mini // github.com/Modernizr/Modernizr/issues/396 tests['backgroundsize'] = function() { return testPropsAll('backgroundSize'); }; tests['borderimage'] = function() { return testPropsAll('borderImage'); }; // Super comprehensive table about all the unique implementations of // border-radius: muddledramblings.com/table-of-css3-border-radius-compliance tests['borderradius'] = function() { return testPropsAll('borderRadius'); }; // WebOS unfortunately false positives on this test. tests['boxshadow'] = function() { return testPropsAll('boxShadow'); }; // FF3.0 will false positive on this test tests['textshadow'] = function() { return document.createElement('div').style.textShadow === ''; }; tests['opacity'] = function() { // Browsers that actually have CSS Opacity implemented have done so // according to spec, which means their return values are within the // range of [0.0,1.0] - including the leading zero. setCssAll('opacity:.55'); // The non-literal . in this regex is intentional: // German Chrome returns this value as 0,55 // github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632 return (/^0.55$/).test(mStyle.opacity); }; // Note, Android < 4 will pass this test, but can only animate // a single property at a time // daneden.me/2011/12/putting-up-with-androids-bullshit/ tests['cssanimations'] = function() { return testPropsAll('animationName'); }; tests['csscolumns'] = function() { return testPropsAll('columnCount'); }; tests['cssgradients'] = function() { /** * For CSS Gradients syntax, please see: * webkit.org/blog/175/introducing-css-gradients/ * developer.mozilla.org/en/CSS/-moz-linear-gradient * developer.mozilla.org/en/CSS/-moz-radial-gradient * dev.w3.org/csswg/css3-images/#gradients- */ var str1 = 'background-image:', str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));', str3 = 'linear-gradient(left top,#9f9, white);'; setCss( // legacy webkit syntax (FIXME: remove when syntax not in use anymore) (str1 + '-webkit- '.split(' ').join(str2 + str1) + // standard syntax // trailing 'background-image:' prefixes.join(str3 + str1)).slice(0, -str1.length) ); return contains(mStyle.backgroundImage, 'gradient'); }; tests['cssreflections'] = function() { return testPropsAll('boxReflect'); }; tests['csstransforms'] = function() { return !!testPropsAll('transform'); }; tests['csstransforms3d'] = function() { var ret = !!testPropsAll('perspective'); // Webkit's 3D transforms are passed off to the browser's own graphics renderer. // It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in // some conditions. As a result, Webkit typically recognizes the syntax but // will sometimes throw a false positive, thus we must do a more thorough check: if ( ret && 'webkitPerspective' in docElement.style ) { // Webkit allows this media query to succeed only if the feature is enabled. // `@media (transform-3d),(-webkit-transform-3d){ ... }` injectElementWithStyles('@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}', function( node, rule ) { ret = node.offsetLeft === 9 && node.offsetHeight === 3; }); } return ret; }; tests['csstransitions'] = function() { return testPropsAll('transition'); }; /*>>fontface*/ // @font-face detection routine by Diego Perini // javascript.nwbox.com/CSSSupport/ // false positives: // WebOS github.com/Modernizr/Modernizr/issues/342 // WP7 github.com/Modernizr/Modernizr/issues/538 tests['fontface'] = function() { var bool; injectElementWithStyles('@font-face {font-family:"font";src:url("https://")}', function( node, rule ) { var style = document.getElementById('smodernizr'), sheet = style.sheet || style.styleSheet, cssText = sheet ? (sheet.cssRules && sheet.cssRules[0] ? sheet.cssRules[0].cssText : sheet.cssText || '') : ''; bool = /src/i.test(cssText) && cssText.indexOf(rule.split(' ')[0]) === 0; }); return bool; }; /*>>fontface*/ // CSS generated content detection tests['generatedcontent'] = function() { var bool; injectElementWithStyles(['#',mod,'{font:0/0 a}#',mod,':after{content:"',smile,'";visibility:hidden;font:3px/1 a}'].join(''), function( node ) { bool = node.offsetHeight >= 3; }); return bool; }; // These tests evaluate support of the video/audio elements, as well as // testing what types of content they support. // // We're using the Boolean constructor here, so that we can extend the value // e.g. Modernizr.video // true // Modernizr.video.ogg // 'probably' // // Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845 // thx to NielsLeenheer and zcorpan // Note: in some older browsers, "no" was a return value instead of empty string. // It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2 // It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5 tests['video'] = function() { var elem = document.createElement('video'), bool = false; // IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224 try { if ( bool = !!elem.canPlayType ) { bool = new Boolean(bool); bool.ogg = elem.canPlayType('video/ogg; codecs="theora"') .replace(/^no$/,''); // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,''); bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,''); } } catch(e) { } return bool; }; tests['audio'] = function() { var elem = document.createElement('audio'), bool = false; try { if ( bool = !!elem.canPlayType ) { bool = new Boolean(bool); bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,''); bool.mp3 = elem.canPlayType('audio/mpeg;') .replace(/^no$/,''); // Mimetypes accepted: // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements // bit.ly/iphoneoscodecs bool.wav = elem.canPlayType('audio/wav; codecs="1"') .replace(/^no$/,''); bool.m4a = ( elem.canPlayType('audio/x-m4a;') || elem.canPlayType('audio/aac;')) .replace(/^no$/,''); } } catch(e) { } return bool; }; // In FF4, if disabled, window.localStorage should === null. // Normally, we could not test that directly and need to do a // `('localStorage' in window) && ` test first because otherwise Firefox will // throw bugzil.la/365772 if cookies are disabled // Also in iOS5 Private Browsing mode, attempting to use localStorage.setItem // will throw the exception: // QUOTA_EXCEEDED_ERRROR DOM Exception 22. // Peculiarly, getItem and removeItem calls do not throw. // Because we are forced to try/catch this, we'll go aggressive. // Just FWIW: IE8 Compat mode supports these features completely: // www.quirksmode.org/dom/html5.html // But IE8 doesn't support either with local files tests['localstorage'] = function() { try { localStorage.setItem(mod, mod); localStorage.removeItem(mod); return true; } catch(e) { return false; } }; tests['sessionstorage'] = function() { try { sessionStorage.setItem(mod, mod); sessionStorage.removeItem(mod); return true; } catch(e) { return false; } }; tests['webworkers'] = function() { return !!window.Worker; }; tests['applicationcache'] = function() { return !!window.applicationCache; }; // Thanks to Erik Dahlstrom tests['svg'] = function() { return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect; }; // specifically for SVG inline in HTML, not within XHTML // test page: paulirish.com/demo/inline-svg tests['inlinesvg'] = function() { var div = document.createElement('div'); div.innerHTML = '<svg/>'; return (div.firstChild && div.firstChild.namespaceURI) == ns.svg; }; // SVG SMIL animation tests['smil'] = function() { return !!document.createElementNS && /SVGAnimate/.test(toString.call(document.createElementNS(ns.svg, 'animate'))); }; // This test is only for clip paths in SVG proper, not clip paths on HTML content // demo: srufaculty.sru.edu/david.dailey/svg/newstuff/clipPath4.svg // However read the comments to dig into applying SVG clippaths to HTML content here: // github.com/Modernizr/Modernizr/issues/213#issuecomment-1149491 tests['svgclippaths'] = function() { return !!document.createElementNS && /SVGClipPath/.test(toString.call(document.createElementNS(ns.svg, 'clipPath'))); }; /*>>webforms*/ // input features and input types go directly onto the ret object, bypassing the tests loop. // Hold this guy to execute in a moment. function webforms() { /*>>input*/ // Run through HTML5's new input attributes to see if the UA understands any. // We're using f which is the <input> element created early on // Mike Taylr has created a comprehensive resource for testing these attributes // when applied to all input types: // miketaylr.com/code/input-type-attr.html // spec: www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary // Only input placeholder is tested while textarea's placeholder is not. // Currently Safari 4 and Opera 11 have support only for the input placeholder // Both tests are available in feature-detects/forms-placeholder.js Modernizr['input'] = (function( props ) { for ( var i = 0, len = props.length; i < len; i++ ) { attrs[ props[i] ] = !!(props[i] in inputElem); } if (attrs.list){ // safari false positive's on datalist: webk.it/74252 // see also github.com/Modernizr/Modernizr/issues/146 attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement); } return attrs; })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' ')); /*>>input*/ /*>>inputtypes*/ // Run through HTML5's new input types to see if the UA understands any. // This is put behind the tests runloop because it doesn't return a // true/false like all the other tests; instead, it returns an object // containing each input type with its corresponding true/false value // Big thanks to @miketaylr for the html5 forms expertise. miketaylr.com/ Modernizr['inputtypes'] = (function(props) { for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) { inputElem.setAttribute('type', inputElemType = props[i]); bool = inputElem.type !== 'text'; // We first check to see if the type we give it sticks.. // If the type does, we feed it a textual value, which shouldn't be valid. // If the value doesn't stick, we know there's input sanitization which infers a custom UI if ( bool ) { inputElem.value = smile; inputElem.style.cssText = 'position:absolute;visibility:hidden;'; if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) { docElement.appendChild(inputElem); defaultView = document.defaultView; // Safari 2-4 allows the smiley as a value, despite making a slider bool = defaultView.getComputedStyle && defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' && // Mobile android web browser has false positive, so must // check the height to see if the widget is actually there. (inputElem.offsetHeight !== 0); docElement.removeChild(inputElem); } else if ( /^(search|tel)$/.test(inputElemType) ){ // Spec doesn't define any special parsing or detectable UI // behaviors so we pass these through as true // Interestingly, opera fails the earlier test, so it doesn't // even make it here. } else if ( /^(url|email)$/.test(inputElemType) ) { // Real url and email support comes with prebaked validation. bool = inputElem.checkValidity && inputElem.checkValidity() === false; } else { // If the upgraded input compontent rejects the :) text, we got a winner bool = inputElem.value != smile; } } inputs[ props[i] ] = !!bool; } return inputs; })('search tel url email datetime date month week time datetime-local number range color'.split(' ')); /*>>inputtypes*/ } /*>>webforms*/ // End of test definitions // ----------------------- // Run through all tests and detect their support in the current UA. // todo: hypothetically we could be doing an array of tests and use a basic loop here. for ( var feature in tests ) { if ( hasOwnProp(tests, feature) ) { // run the test, throw the return value into the Modernizr, // then based on that boolean, define an appropriate className // and push it into an array of classes we'll join later. featureName = feature.toLowerCase(); Modernizr[featureName] = tests[feature](); classes.push((Modernizr[featureName] ? '' : 'no-') + featureName); } } /*>>webforms*/ // input tests need to run. Modernizr.input || webforms(); /*>>webforms*/ /** * addTest allows the user to define their own feature tests * the result will be added onto the Modernizr object, * as well as an appropriate className set on the html element * * @param feature - String naming the feature * @param test - Function returning true if feature is supported, false if not */ Modernizr.addTest = function ( feature, test ) { if ( typeof feature == 'object' ) { for ( var key in feature ) { if ( hasOwnProp( feature, key ) ) { Modernizr.addTest( key, feature[ key ] ); } } } else { feature = feature.toLowerCase(); if ( Modernizr[feature] !== undefined ) { // we're going to quit if you're trying to overwrite an existing test // if we were to allow it, we'd do this: // var re = new RegExp("\\b(no-)?" + feature + "\\b"); // docElement.className = docElement.className.replace( re, '' ); // but, no rly, stuff 'em. return Modernizr; } test = typeof test == 'function' ? test() : test; if (typeof enableClasses !== "undefined" && enableClasses) { docElement.className += ' ' + (test ? '' : 'no-') + feature; } Modernizr[feature] = test; } return Modernizr; // allow chaining. }; // Reset modElem.cssText to nothing to reduce memory footprint. setCss(''); modElem = inputElem = null; /*>>shiv*/ /*! HTML5 Shiv v3.6.1 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed */ ;(function(window, document) { /*jshint evil:true */ /** Preset options */ var options = window.html5 || {}; /** Used to skip problem elements */ var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i; /** Not all elements can be cloned in IE **/ var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i; /** Detect whether the browser supports default html5 styles */ var supportsHtml5Styles; /** Name of the expando, to work with multiple documents or to re-shiv one document */ var expando = '_html5shiv'; /** The id for the the documents expando */ var expanID = 0; /** Cached data for each document */ var expandoData = {}; /** Detect whether the browser supports unknown elements */ var supportsUnknownElements; (function() { try { var a = document.createElement('a'); a.innerHTML = '<xyz></xyz>'; //if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles supportsHtml5Styles = ('hidden' in a); supportsUnknownElements = a.childNodes.length == 1 || (function() { // assign a false positive if unable to shiv (document.createElement)('a'); var frag = document.createDocumentFragment(); return ( typeof frag.cloneNode == 'undefined' || typeof frag.createDocumentFragment == 'undefined' || typeof frag.createElement == 'undefined' ); }()); } catch(e) { supportsHtml5Styles = true; supportsUnknownElements = true; } }()); /*--------------------------------------------------------------------------*/ /** * Creates a style sheet with the given CSS text and adds it to the document. * @private * @param {Document} ownerDocument The document. * @param {String} cssText The CSS text. * @returns {StyleSheet} The style element. */ function addStyleSheet(ownerDocument, cssText) { var p = ownerDocument.createElement('p'), parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; p.innerHTML = 'x<style>' + cssText + '</style>'; return parent.insertBefore(p.lastChild, parent.firstChild); } /** * Returns the value of `html5.elements` as an array. * @private * @returns {Array} An array of shived element node names. */ function getElements() { var elements = html5.elements; return typeof elements == 'string' ? elements.split(' ') : elements; } /** * Returns the data associated to the given document * @private * @param {Document} ownerDocument The document. * @returns {Object} An object of data. */ function getExpandoData(ownerDocument) { var data = expandoData[ownerDocument[expando]]; if (!data) { data = {}; expanID++; ownerDocument[expando] = expanID; expandoData[expanID] = data; } return data; } /** * returns a shived element for the given nodeName and document * @memberOf html5 * @param {String} nodeName name of the element * @param {Document} ownerDocument The context document. * @returns {Object} The shived element. */ function createElement(nodeName, ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createElement(nodeName); } if (!data) { data = getExpandoData(ownerDocument); } var node; if (data.cache[nodeName]) { node = data.cache[nodeName].cloneNode(); } else if (saveClones.test(nodeName)) { node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode(); } else { node = data.createElem(nodeName); } // Avoid adding some elements to fragments in IE < 9 because // * Attributes like `name` or `type` cannot be set/changed once an element // is inserted into a document/fragment // * Link elements with `src` attributes that are inaccessible, as with // a 403 response, will cause the tab/window to crash // * Script elements appended to fragments will execute when their `src` // or `text` property is set return node.canHaveChildren && !reSkip.test(nodeName) ? data.frag.appendChild(node) : node; } /** * returns a shived DocumentFragment for the given document * @memberOf html5 * @param {Document} ownerDocument The context document. * @returns {Object} The shived DocumentFragment. */ function createDocumentFragment(ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createDocumentFragment(); } data = data || getExpandoData(ownerDocument); var clone = data.frag.cloneNode(), i = 0, elems = getElements(), l = elems.length; for(;i<l;i++){ clone.createElement(elems[i]); } return clone; } /** * Shivs the `createElement` and `createDocumentFragment` methods of the document. * @private * @param {Document|DocumentFragment} ownerDocument The document. * @param {Object} data of the document. */ function shivMethods(ownerDocument, data) { if (!data.cache) { data.cache = {}; data.createElem = ownerDocument.createElement; data.createFrag = ownerDocument.createDocumentFragment; data.frag = data.createFrag(); } ownerDocument.createElement = function(nodeName) { //abort shiv if (!html5.shivMethods) { return data.createElem(nodeName); } return createElement(nodeName, ownerDocument, data); }; ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' + 'var n=f.cloneNode(),c=n.createElement;' + 'h.shivMethods&&(' + // unroll the `createElement` calls getElements().join().replace(/\w+/g, function(nodeName) { data.createElem(nodeName); data.frag.createElement(nodeName); return 'c("' + nodeName + '")'; }) + ');return n}' )(html5, data.frag); } /*--------------------------------------------------------------------------*/ /** * Shivs the given document. * @memberOf html5 * @param {Document} ownerDocument The document to shiv. * @returns {Document} The shived document. */ function shivDocument(ownerDocument) { if (!ownerDocument) { ownerDocument = document; } var data = getExpandoData(ownerDocument); if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) { data.hasCSS = !!addStyleSheet(ownerDocument, // corrects block display not defined in IE6/7/8/9 'article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}' + // adds styling not present in IE6/7/8/9 'mark{background:#FF0;color:#000}' ); } if (!supportsUnknownElements) { shivMethods(ownerDocument, data); } return ownerDocument; } /*--------------------------------------------------------------------------*/ /** * The `html5` object is exposed so that more elements can be shived and * existing shiving can be detected on iframes. * @type Object * @example * * // options can be changed before the script is included * html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false }; */ var html5 = { /** * An array or space separated string of node names of the elements to shiv. * @memberOf html5 * @type Array|String */ 'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video', /** * A flag to indicate that the HTML5 style sheet should be inserted. * @memberOf html5 * @type Boolean */ 'shivCSS': (options.shivCSS !== false), /** * Is equal to true if a browser supports creating unknown/HTML5 elements * @memberOf html5 * @type boolean */ 'supportsUnknownElements': supportsUnknownElements, /** * A flag to indicate that the document's `createElement` and `createDocumentFragment` * methods should be overwritten. * @memberOf html5 * @type Boolean */ 'shivMethods': (options.shivMethods !== false), /** * A string to describe the type of `html5` object ("default" or "default print"). * @memberOf html5 * @type String */ 'type': 'default', // shivs the document according to the specified `html5` object options 'shivDocument': shivDocument, //creates a shived element createElement: createElement, //creates a shived documentFragment createDocumentFragment: createDocumentFragment }; /*--------------------------------------------------------------------------*/ // expose html5 window.html5 = html5; // shiv the document shivDocument(document); }(this, document)); /*>>shiv*/ // Assign private properties to the return object with prefix Modernizr._version = version; // expose these for the plugin API. Look in the source for how to join() them against your input /*>>prefixes*/ Modernizr._prefixes = prefixes; /*>>prefixes*/ /*>>domprefixes*/ Modernizr._domPrefixes = domPrefixes; Modernizr._cssomPrefixes = cssomPrefixes; /*>>domprefixes*/ /*>>mq*/ // Modernizr.mq tests a given media query, live against the current state of the window // A few important notes: // * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false // * A max-width or orientation query will be evaluated against the current state, which may change later. // * You must specify values. Eg. If you are testing support for the min-width media query use: // Modernizr.mq('(min-width:0)') // usage: // Modernizr.mq('only screen and (max-width:768)') Modernizr.mq = testMediaQuery; /*>>mq*/ /*>>hasevent*/ // Modernizr.hasEvent() detects support for a given event, with an optional element to test on // Modernizr.hasEvent('gesturestart', elem) Modernizr.hasEvent = isEventSupported; /*>>hasevent*/ /*>>testprop*/ // Modernizr.testProp() investigates whether a given style property is recognized // Note that the property names must be provided in the camelCase variant. // Modernizr.testProp('pointerEvents') Modernizr.testProp = function(prop){ return testProps([prop]); }; /*>>testprop*/ /*>>testallprops*/ // Modernizr.testAllProps() investigates whether a given style property, // or any of its vendor-prefixed variants, is recognized // Note that the property names must be provided in the camelCase variant. // Modernizr.testAllProps('boxSizing') Modernizr.testAllProps = testPropsAll; /*>>testallprops*/ /*>>teststyles*/ // Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards // Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... }) Modernizr.testStyles = injectElementWithStyles; /*>>teststyles*/ /*>>prefixed*/ // Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input // Modernizr.prefixed('boxSizing') // 'MozBoxSizing' // Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style. // Return values will also be the camelCase variant, if you need to translate that to hypenated style use: // // str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-'); // If you're trying to ascertain which transition end event to bind to, you might do something like... // // var transEndEventNames = { // 'WebkitTransition' : 'webkitTransitionEnd', // 'MozTransition' : 'transitionend', // 'OTransition' : 'oTransitionEnd', // 'msTransition' : 'MSTransitionEnd', // 'transition' : 'transitionend' // }, // transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ]; Modernizr.prefixed = function(prop, obj, elem){ if(!obj) { return testPropsAll(prop, 'pfx'); } else { // Testing DOM property e.g. Modernizr.prefixed('requestAnimationFrame', window) // 'mozRequestAnimationFrame' return testPropsAll(prop, obj, elem); } }; /*>>prefixed*/ /*>>cssclasses*/ // Remove "no-js" class from <html> element, if it exists: docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') + // Add the new classes to the <html> element. (enableClasses ? ' js ' + classes.join(' ') : ''); /*>>cssclasses*/ return Modernizr; })(this, this.document); // SIG // Begin signature block // SIG // MIIdkQYJKoZIhvcNAQcCoIIdgjCCHX4CAQExCzAJBgUr // SIG // DgMCGgUAMGcGCisGAQQBgjcCAQSgWTBXMDIGCisGAQQB // SIG // gjcCAR4wJAIBAQQQEODJBs441BGiowAQS9NQkAIBAAIB // SIG // AAIBAAIBAAIBADAhMAkGBSsOAwIaBQAEFJLG0Sn7wluC // SIG // PcS9XWSOaKmBre9moIIYUzCCBMIwggOqoAMCAQICEzMA // SIG // AAC6ajbeGq29PB8AAAAAALowDQYJKoZIhvcNAQEFBQAw // SIG // dzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0 // SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p // SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEhMB8GA1UEAxMYTWlj // SIG // cm9zb2Z0IFRpbWUtU3RhbXAgUENBMB4XDTE2MDkwNzE3 // SIG // NTg0NloXDTE4MDkwNzE3NTg0NlowgbIxCzAJBgNVBAYT // SIG // AlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQH // SIG // EwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29y // SIG // cG9yYXRpb24xDDAKBgNVBAsTA0FPQzEnMCUGA1UECxMe // SIG // bkNpcGhlciBEU0UgRVNOOkY2RkYtMkRBNy1CQjc1MSUw // SIG // IwYDVQQDExxNaWNyb3NvZnQgVGltZS1TdGFtcCBTZXJ2 // SIG // aWNlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC // SIG // AQEA25HNI9Q3pGCG3lTLSR3d5Mbwr0J8VQtHTXHNk77v // SIG // XQwbSC7eKTWg5DvMYRBSMzoLFbnFeVGWkB7Zrr3MLxtx // SIG // dca4CgkwxoEYXQm9fyRgbOuyu3ppCJBfHYG5mbSEwEhk // SIG // o8M8to4ZSvnjJ3EgbrqGrbrU8UkvOoycXjeaZpdh1fs+ // SIG // uPK/q5KlZiaUy0dhJyNO0HF7dJ2f4PSf5PwO5n0nxRnh // SIG // R0R7FXP2m8qSXVDVkhr9UVWCexaInMVKF7nW4mAXUw37 // SIG // Mr2T6zidvPUvCqGeylMRrkhhg5Mn3LUIGaGRSPl5Q/PS // SIG // piojW2oavYRuZucHkhsFXj38P/fSRxkyPowtuQIDAQAB // SIG // o4IBCTCCAQUwHQYDVR0OBBYEFFvsDxcNijka+bDhgxSB // SIG // e9m4SBygMB8GA1UdIwQYMBaAFCM0+NlSRnAK7UD7dvuz // SIG // K7DDNbMPMFQGA1UdHwRNMEswSaBHoEWGQ2h0dHA6Ly9j // SIG // cmwubWljcm9zb2Z0LmNvbS9wa2kvY3JsL3Byb2R1Y3Rz // SIG // L01pY3Jvc29mdFRpbWVTdGFtcFBDQS5jcmwwWAYIKwYB // SIG // BQUHAQEETDBKMEgGCCsGAQUFBzAChjxodHRwOi8vd3d3 // SIG // Lm1pY3Jvc29mdC5jb20vcGtpL2NlcnRzL01pY3Jvc29m // SIG // dFRpbWVTdGFtcFBDQS5jcnQwEwYDVR0lBAwwCgYIKwYB // SIG // BQUHAwgwDQYJKoZIhvcNAQEFBQADggEBAAeBQyzwVNTK // SIG // 7apDx+GNCpo7MqFVIEIUDfx77luOo9A6yqA1a3JaCW9t // SIG // UjdgkHvaCmqxX48sX5l2dwoSpgeNjAWh5BE6qPSwBttq // SIG // t3KcW2DvFtLpHuEaWAP61fFfkt9dL3sWs8Fyw64XXVkM // SIG // 2kSUE9wa6vx+k9i8Aald35NJilF0yqD39ka0LuPrQJmS // SIG // Qb+UDsYZjUYkeBGs6hEaeEFJiCX4j8Pb5sn9Ct5p+opw // SIG // YWBSBY+MM4SNQnyqcvycDNVqMwDaMJmpWGKwVHDWv5ZN // SIG // vvWXssIyPE8p5xKPR8bT4YroMNqhlZjisiWSBXXEtpT6 // SIG // Bjz5Lj4k4pHeIqSYCBQHO0swggYAMIID6KADAgECAhMz // SIG // AAAAww6bp9iy3PcsAAAAAADDMA0GCSqGSIb3DQEBCwUA // SIG // MH4xCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5n // SIG // dG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVN // SIG // aWNyb3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01p // SIG // Y3Jvc29mdCBDb2RlIFNpZ25pbmcgUENBIDIwMTEwHhcN // SIG // MTcwODExMjAyMDI0WhcNMTgwODExMjAyMDI0WjB0MQsw // SIG // CQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQ // SIG // MA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9z // SIG // b2Z0IENvcnBvcmF0aW9uMR4wHAYDVQQDExVNaWNyb3Nv // SIG // ZnQgQ29ycG9yYXRpb24wggEiMA0GCSqGSIb3DQEBAQUA // SIG // A4IBDwAwggEKAoIBAQC7V9c40bEGf0ktqW2zY596urY6 // SIG // IVu0mK6N1KSBoMV1xSzvgkAqt4FTd/NjAQq8zjeEA0BD // SIG // V4JLzu0ftv2AbcnCkV0Fx9xWWQDhDOtX3v3xuJAnv3VK // SIG // /HWycli2xUibM2IF0ZWUpb85Iq2NEk1GYtoyGc6qIlxW // SIG // SLFvRclndmJdMIijLyjFH1Aq2YbbGhElgcL09Wcu53kd // SIG // 9eIcdfROzMf8578LgEcp/8/NabEMC2DrZ+aEG5tN/W1H // SIG // OsfZwWFh8pUSoQ0HrmMh2PSZHP94VYHupXnoIIJfCtq1 // SIG // UxlUAVcNh5GNwnzxVIaA4WLbgnM+Jl7wQBLSOdUmAw2F // SIG // iDFfCguLAgMBAAGjggF/MIIBezAfBgNVHSUEGDAWBgor // SIG // BgEEAYI3TAgBBggrBgEFBQcDAzAdBgNVHQ4EFgQUpxNd // SIG // HyGJVegD7p4XNuryVIg1Ga8wUQYDVR0RBEowSKRGMEQx // SIG // DDAKBgNVBAsTA0FPQzE0MDIGA1UEBRMrMjMwMDEyK2M4 // SIG // MDRiNWVhLTQ5YjQtNDIzOC04MzYyLWQ4NTFmYTIyNTRm // SIG // YzAfBgNVHSMEGDAWgBRIbmTlUAXTgqoXNzcitW2oynUC // SIG // lTBUBgNVHR8ETTBLMEmgR6BFhkNodHRwOi8vd3d3Lm1p // SIG // Y3Jvc29mdC5jb20vcGtpb3BzL2NybC9NaWNDb2RTaWdQ // SIG // Q0EyMDExXzIwMTEtMDctMDguY3JsMGEGCCsGAQUFBwEB // SIG // BFUwUzBRBggrBgEFBQcwAoZFaHR0cDovL3d3dy5taWNy // SIG // b3NvZnQuY29tL3BraW9wcy9jZXJ0cy9NaWNDb2RTaWdQ // SIG // Q0EyMDExXzIwMTEtMDctMDguY3J0MAwGA1UdEwEB/wQC // SIG // MAAwDQYJKoZIhvcNAQELBQADggIBAE2XTzR+8XCTnOPV // SIG // GkucEX5rJsSlJPTfRNQkurNqCImZmssx53Cb/xQdsAc5 // SIG // f+QwOxMi3g7IlWe7bn74fJWkkII3k6aD00kCwaytWe+R // SIG // t6dmAA6iTCXU3OddBwLKKDRlOzmDrZUqjsqg6Ag6HP4+ // SIG // e0BJlE2OVCUK5bHHCu5xN8abXjb1p0JE+7yHsA3ANdkm // SIG // h1//Z+8odPeKMAQRimfMSzVgaiHnw40Hg16bq51xHykm // SIG // CRHU9YLT0jYHKa7okm2QfwDJqFvu0ARl+6EOV1PM8piJ // SIG // 858Vk8gGxGNSYQJPV0gc9ft1Esq1+fTCaV+7oZ0NaYMn // SIG // 64M+HWsxw+4O8cSEQ4fuMZwGADJ8tyCKuQgj6lawGNSy // SIG // vRXsN+1k02sVAiPGijOHOtGbtsCWWSygAVOEAV/ye8F6 // SIG // sOzU2FL2X3WBRFkWOCdTu1DzXnHf99dR3DHVGmM1Kpd+ // SIG // n2Y3X89VM++yyrwsI6pEHu77Z0i06ELDD4pRWKJGAmEm // SIG // Whm/XJTpqEBw51swTHyA1FBnoqXuDus9tfHleR7h9VgZ // SIG // b7uJbXjiIFgl/+RIs+av8bJABBdGUNQMbJEUfe7K4vYm // SIG // 3hs7BGdRLg+kF/dC/z+RiTH4p7yz5TpS3Cozf0pkkWXY // SIG // ZRG222q3tGxS/L+LcRbELM5zmqDpXQjBRUWlKYbsATFt // SIG // XnTGVjELMIIGBzCCA++gAwIBAgIKYRZoNAAAAAAAHDAN // SIG // BgkqhkiG9w0BAQUFADBfMRMwEQYKCZImiZPyLGQBGRYD // SIG // Y29tMRkwFwYKCZImiZPyLGQBGRYJbWljcm9zb2Z0MS0w // SIG // KwYDVQQDEyRNaWNyb3NvZnQgUm9vdCBDZXJ0aWZpY2F0 // SIG // ZSBBdXRob3JpdHkwHhcNMDcwNDAzMTI1MzA5WhcNMjEw // SIG // NDAzMTMwMzA5WjB3MQswCQYDVQQGEwJVUzETMBEGA1UE // SIG // CBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEe // SIG // MBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEw // SIG // HwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0Ew // SIG // ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCf // SIG // oWyx39tIkip8ay4Z4b3i48WZUSNQrc7dGE4kD+7Rp9FM // SIG // rXQwIBHrB9VUlRVJlBtCkq6YXDAm2gBr6Hu97IkHD/cO // SIG // BJjwicwfyzMkh53y9GccLPx754gd6udOo6HBI1PKjfpF // SIG // zwnQXq/QsEIEovmmbJNn1yjcRlOwhtDlKEYuJ6yGT1VS // SIG // DOQDLPtqkJAwbofzWTCd+n7Wl7PoIZd++NIT8wi3U21S // SIG // tEWQn0gASkdmEScpZqiX5NMGgUqi+YSnEUcUCYKfhO1V // SIG // eP4Bmh1QCIUAEDBG7bfeI0a7xC1Un68eeEExd8yb3zuD // SIG // k6FhArUdDbH895uyAc4iS1T/+QXDwiALAgMBAAGjggGr // SIG // MIIBpzAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBQj // SIG // NPjZUkZwCu1A+3b7syuwwzWzDzALBgNVHQ8EBAMCAYYw // SIG // EAYJKwYBBAGCNxUBBAMCAQAwgZgGA1UdIwSBkDCBjYAU // SIG // DqyCYEBWJ5flJRP8KuEKU5VZ5KShY6RhMF8xEzARBgoJ // SIG // kiaJk/IsZAEZFgNjb20xGTAXBgoJkiaJk/IsZAEZFglt // SIG // aWNyb3NvZnQxLTArBgNVBAMTJE1pY3Jvc29mdCBSb290 // SIG // IENlcnRpZmljYXRlIEF1dGhvcml0eYIQea0WoUqgpa1M // SIG // c1j0BxMuZTBQBgNVHR8ESTBHMEWgQ6BBhj9odHRwOi8v // SIG // Y3JsLm1pY3Jvc29mdC5jb20vcGtpL2NybC9wcm9kdWN0 // SIG // cy9taWNyb3NvZnRyb290Y2VydC5jcmwwVAYIKwYBBQUH // SIG // AQEESDBGMEQGCCsGAQUFBzAChjhodHRwOi8vd3d3Lm1p // SIG // Y3Jvc29mdC5jb20vcGtpL2NlcnRzL01pY3Jvc29mdFJv // SIG // b3RDZXJ0LmNydDATBgNVHSUEDDAKBggrBgEFBQcDCDAN // SIG // BgkqhkiG9w0BAQUFAAOCAgEAEJeKw1wDRDbd6bStd9vO // SIG // eVFNAbEudHFbbQwTq86+e4+4LtQSooxtYrhXAstOIBNQ // SIG // md16QOJXu69YmhzhHQGGrLt48ovQ7DsB7uK+jwoFyI1I // SIG // 4vBTFd1Pq5Lk541q1YDB5pTyBi+FA+mRKiQicPv2/OR4 // SIG // mS4N9wficLwYTp2OawpylbihOZxnLcVRDupiXD8WmIsg // SIG // P+IHGjL5zDFKdjE9K3ILyOpwPf+FChPfwgphjvDXuBfr // SIG // Tot/xTUrXqO/67x9C0J71FNyIe4wyrt4ZVxbARcKFA7S // SIG // 2hSY9Ty5ZlizLS/n+YWGzFFW6J1wlGysOUzU9nm/qhh6 // SIG // YinvopspNAZ3GmLJPR5tH4LwC8csu89Ds+X57H2146So // SIG // dDW4TsVxIxImdgs8UoxxWkZDFLyzs7BNZ8ifQv+AeSGA // SIG // nhUwZuhCEl4ayJ4iIdBD6Svpu/RIzCzU2DKATCYqSCRf // SIG // WupW76bemZ3KOm+9gSd0BhHudiG/m4LBJ1S2sWo9iaF2 // SIG // YbRuoROmv6pH8BJv/YoybLL+31HIjCPJZr2dHYcSZAI9 // SIG // La9Zj7jkIeW1sMpjtHhUBdRBLlCslLCleKuzoJZ1GtmS // SIG // hxN1Ii8yqAhuoFuMJb+g74TKIdbrHk/Jmu5J4PcBZW+J // SIG // C33Iacjmbuqnl84xKf8OxVtc2E0bodj6L54/LlUWa8kT // SIG // o/0wggd6MIIFYqADAgECAgphDpDSAAAAAAADMA0GCSqG // SIG // SIb3DQEBCwUAMIGIMQswCQYDVQQGEwJVUzETMBEGA1UE // SIG // CBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEe // SIG // MBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTIw // SIG // MAYDVQQDEylNaWNyb3NvZnQgUm9vdCBDZXJ0aWZpY2F0 // SIG // ZSBBdXRob3JpdHkgMjAxMTAeFw0xMTA3MDgyMDU5MDla // SIG // Fw0yNjA3MDgyMTA5MDlaMH4xCzAJBgNVBAYTAlVTMRMw // SIG // EQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRt // SIG // b25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRp // SIG // b24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p // SIG // bmcgUENBIDIwMTEwggIiMA0GCSqGSIb3DQEBAQUAA4IC // SIG // DwAwggIKAoICAQCr8PpyEBwurdhuqoIQTTS68rZYIZ9C // SIG // Gypr6VpQqrgGOBoESbp/wwwe3TdrxhLYC/A4wpkGsMg5 // SIG // 1QEUMULTiQ15ZId+lGAkbK+eSZzpaF7S35tTsgosw6/Z // SIG // qSuuegmv15ZZymAaBelmdugyUiYSL+erCFDPs0S3XdjE // SIG // LgN1q2jzy23zOlyhFvRGuuA4ZKxuZDV4pqBjDy3TQJP4 // SIG // 494HDdVceaVJKecNvqATd76UPe/74ytaEB9NViiienLg // SIG // Ejq3SV7Y7e1DkYPZe7J7hhvZPrGMXeiJT4Qa8qEvWeSQ // SIG // Oy2uM1jFtz7+MtOzAz2xsq+SOH7SnYAs9U5WkSE1JcM5 // SIG // bmR/U7qcD60ZI4TL9LoDho33X/DQUr+MlIe8wCF0JV8Y // SIG // KLbMJyg4JZg5SjbPfLGSrhwjp6lm7GEfauEoSZ1fiOIl // SIG // XdMhSz5SxLVXPyQD8NF6Wy/VI+NwXQ9RRnez+ADhvKwC // SIG // gl/bwBWzvRvUVUvnOaEP6SNJvBi4RHxF5MHDcnrgcuck // SIG // 379GmcXvwhxX24ON7E1JMKerjt/sW5+v/N2wZuLBl4F7 // SIG // 7dbtS+dJKacTKKanfWeA5opieF+yL4TXV5xcv3coKPHt // SIG // bcMojyyPQDdPweGFRInECUzF1KVDL3SV9274eCBYLBNd // SIG // YJWaPk8zhNqwiBfenk70lrC8RqBsmNLg1oiMCwIDAQAB // SIG // o4IB7TCCAekwEAYJKwYBBAGCNxUBBAMCAQAwHQYDVR0O // SIG // BBYEFEhuZOVQBdOCqhc3NyK1bajKdQKVMBkGCSsGAQQB // SIG // gjcUAgQMHgoAUwB1AGIAQwBBMAsGA1UdDwQEAwIBhjAP // SIG // BgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFHItOgIx // SIG // kEO5FAVO4eqnxzHRI4k0MFoGA1UdHwRTMFEwT6BNoEuG // SIG // SWh0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3Js // SIG // L3Byb2R1Y3RzL01pY1Jvb0NlckF1dDIwMTFfMjAxMV8w // SIG // M18yMi5jcmwwXgYIKwYBBQUHAQEEUjBQME4GCCsGAQUF // SIG // BzAChkJodHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtp // SIG // L2NlcnRzL01pY1Jvb0NlckF1dDIwMTFfMjAxMV8wM18y // SIG // Mi5jcnQwgZ8GA1UdIASBlzCBlDCBkQYJKwYBBAGCNy4D // SIG // MIGDMD8GCCsGAQUFBwIBFjNodHRwOi8vd3d3Lm1pY3Jv // SIG // c29mdC5jb20vcGtpb3BzL2RvY3MvcHJpbWFyeWNwcy5o // SIG // dG0wQAYIKwYBBQUHAgIwNB4yIB0ATABlAGcAYQBsAF8A // SIG // cABvAGwAaQBjAHkAXwBzAHQAYQB0AGUAbQBlAG4AdAAu // SIG // IB0wDQYJKoZIhvcNAQELBQADggIBAGfyhqWY4FR5Gi7T // SIG // 2HRnIpsLlhHhY5KZQpZ90nkMkMFlXy4sPvjDctFtg/6+ // SIG // P+gKyju/R6mj82nbY78iNaWXXWWEkH2LRlBV2AySfNIa // SIG // SxzzPEKLUtCw/WvjPgcuKZvmPRul1LUdd5Q54ulkyUQ9 // SIG // eHoj8xN9ppB0g430yyYCRirCihC7pKkFDJvtaPpoLpWg // SIG // Kj8qa1hJYx8JaW5amJbkg/TAj/NGK978O9C9Ne9uJa7l // SIG // ryft0N3zDq+ZKJeYTQ49C/IIidYfwzIY4vDFLc5bnrRJ // SIG // OQrGCsLGra7lstnbFYhRRVg4MnEnGn+x9Cf43iw6IGmY // SIG // slmJaG5vp7d0w0AFBqYBKig+gj8TTWYLwLNN9eGPfxxv // SIG // FX1Fp3blQCplo8NdUmKGwx1jNpeG39rz+PIWoZon4c2l // SIG // l9DuXWNB41sHnIc+BncG0QaxdR8UvmFhtfDcxhsEvt9B // SIG // xw4o7t5lL+yX9qFcltgA1qFGvVnzl6UJS0gQmYAf0AAp // SIG // xbGbpT9Fdx41xtKiop96eiL6SJUfq/tHI4D1nvi/a7dL // SIG // l+LrdXga7Oo3mXkYS//WsyNodeav+vyL6wuA6mk7r/ww // SIG // 7QRMjt/fdW1jkT3RnVZOT7+AVyKheBEyIXrvQQqxP/uo // SIG // zKRdwaGIm1dxVk5IRcBCyZt2WwqASGv9eZ/BvW1taslS // SIG // cxMNelDNMYIEqjCCBKYCAQEwgZUwfjELMAkGA1UEBhMC // SIG // VVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcT // SIG // B1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jw // SIG // b3JhdGlvbjEoMCYGA1UEAxMfTWljcm9zb2Z0IENvZGUg // SIG // U2lnbmluZyBQQ0EgMjAxMQITMwAAAMMOm6fYstz3LAAA // SIG // AAAAwzAJBgUrDgMCGgUAoIG+MBkGCSqGSIb3DQEJAzEM // SIG // BgorBgEEAYI3AgEEMBwGCisGAQQBgjcCAQsxDjAMBgor // SIG // BgEEAYI3AgEVMCMGCSqGSIb3DQEJBDEWBBT+mUvwTCDO // SIG // wIIfSocQbS5cibSMOjBeBgorBgEEAYI3AgEMMVAwTqAm // SIG // gCQATQBpAGMAcgBvAHMAbwBmAHQAIABMAGUAYQByAG4A // SIG // aQBuAGehJIAiaHR0cDovL3d3dy5taWNyb3NvZnQuY29t // SIG // L2xlYXJuaW5nIDANBgkqhkiG9w0BAQEFAASCAQBEfdT0 // SIG // CzZgB+nU9kK4ZRFJIdG6LpMCpncqXnQyWpV81ZYXQwcx // SIG // 5kOvEKZIGgfBQaW2tZpz4IO2Gsl4yS+klGHoCbdgU5os // SIG // QHfSFufVI30Y6biscU3m9YWf1qOA2wIODn98dfH/9Uxm // SIG // A5GwF9vMd8/hHWYNSP299THOV7oRe4m9lfcRPwKvwoVb // SIG // HXqbW3i1AYlk0AmGgYYReiN6xHabij0wdlVioJcWmWzA // SIG // LJBvyoQxY9S8cPM13qtZwxjvrQow4zf+u3osylzgX65s // SIG // dfAwzjh3DytcfLVFRX7pJSkRzSIEyHrXFoCoEjiJF/pr // SIG // BkuvmgZJ60x5xDNJmR+UaIzHgsLloYICKDCCAiQGCSqG // SIG // SIb3DQEJBjGCAhUwggIRAgEBMIGOMHcxCzAJBgNVBAYT // SIG // AlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQH // SIG // EwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29y // SIG // cG9yYXRpb24xITAfBgNVBAMTGE1pY3Jvc29mdCBUaW1l // SIG // LVN0YW1wIFBDQQITMwAAALpqNt4arb08HwAAAAAAujAJ // SIG // BgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3 // SIG // DQEHATAcBgkqhkiG9w0BCQUxDxcNMTcxMjI3MDgyMjIw // SIG // WjAjBgkqhkiG9w0BCQQxFgQUPZOwO5mNts6a1ovOGwpD // SIG // mvH6HRkwDQYJKoZIhvcNAQEFBQAEggEAiycMLyKfsbzT // SIG // 48sdwqGJhTsbUdKxZ0uOicadMSP5hAdCoFrBRO1Fmer6 // SIG // MJilEQVY8GJd+BTXadk71Tcbcyi9agJ+tX7/3He0Eldx // SIG // S3i7xh92PdJATdFJrB5RFGeREojq9pEmzF3GtxGYidZY // SIG // 2KBCppJr6P3wu4CxliyJ7zIwUXtDyHO6o2tbyqkEWZGv // SIG // lrDtxIpwbLwKgex1IAXU4zmjOwkekfmSZTqfMwLex6K8 // SIG // y8Nw1ox4pUEim5Wbo9knCheUcpuigRsbVdWo/sf15+Dk // SIG // GPliNvHwfQDNAvKFl+QpHU9b7fPr++WkdaqxKnG1B23u // SIG // /EdNLzRH+AooIh2vAdKBNw== // SIG // End signature block
{ "content_hash": "0dcd1de426bb52e95e8b1f73f1ded0e2", "timestamp": "", "source": "github", "line_count": 1628, "max_line_length": 197, "avg_line_length": 38.59889434889435, "alnum_prop": 0.6388707649707984, "repo_name": "MicrosoftLearning/20486-DevelopingASPNETMVCWebApplications", "id": "8c0d8bfe7b59c685c564c988ebc51f3ed449f1ef", "size": "64151", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Allfiles/20486C/Mod09/Democode/OperasWebsites_09_end/OperasWebsites/Scripts/modernizr-2.6.2.js", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "70874" }, { "name": "C#", "bytes": "1202611" }, { "name": "CSS", "bytes": "602949" }, { "name": "HTML", "bytes": "643357" }, { "name": "JavaScript", "bytes": "3856005" }, { "name": "PowerShell", "bytes": "7943209" } ], "symlink_target": "" }
package org.assertj.core.api.list; import static junit.framework.Assert.assertSame; import static org.mockito.MockitoAnnotations.initMocks; import java.util.Comparator; import java.util.List; import org.assertj.core.api.ListAssert; import org.assertj.core.api.ListAssertBaseTest; import org.junit.Before; import org.mockito.Mock; /** * Tests for <code>{@link ListAssert#usingComparator(java.util.Comparator)}</code> and * <code>{@link ListAssert#usingDefaultComparator()}</code>. * * @author Joel Costigliola * @author Mikhail Mazursky */ public class ListAssert_usingComparator_Test extends ListAssertBaseTest { @Mock private Comparator<List<? extends String>> comparator; @Before public void before() { initMocks(this); } @Override protected ListAssert<String> invoke_api_method() { return assertions.usingComparator(comparator); } @Override protected void verify_internal_effects() { assertSame(getObjects(assertions).getComparator(), comparator); } }
{ "content_hash": "889cc3c7d8021d0999bfcd3ece7d7153", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 86, "avg_line_length": 24.29268292682927, "alnum_prop": 0.7620481927710844, "repo_name": "AlexBischof/assertj-core", "id": "e1c23db6a0ae2b08b990b372dbfe16a700c3b525", "size": "1603", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/org/assertj/core/api/list/ListAssert_usingComparator_Test.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "5558028" }, { "name": "Shell", "bytes": "22656" } ], "symlink_target": "" }
package sk.vx.connectbot.bean; import java.util.Map.Entry; import sk.vx.connectbot.util.XmlBuilder; import android.content.ContentValues; /** * @author Kenny Root * */ abstract class AbstractBean { public abstract ContentValues getValues(); public abstract String getBeanName(); public String toXML() { XmlBuilder xml = new XmlBuilder(); xml.append(String.format("<%s>", getBeanName())); ContentValues values = getValues(); for (Entry<String, Object> entry : values.valueSet()) { Object value = entry.getValue(); if (value != null) xml.append(entry.getKey(), value); } xml.append(String.format("</%s>", getBeanName())); return xml.toString(); } }
{ "content_hash": "d420dfc70f35e09f7ab65cc519aab47c", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 57, "avg_line_length": 20.818181818181817, "alnum_prop": 0.6899563318777293, "repo_name": "0xD34D/connectbot", "id": "d3fd333bd1bb83b1b1614c76e2a48cd5839ce1ae", "size": "1365", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/sk/vx/connectbot/bean/AbstractBean.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#ifndef GRPPI_STENCIL_H #define GRPPI_STENCIL_H #include <tuple> #include <utility> #include "grppi/common/zip_view.h" #include "grppi/common/execution_traits.h" #include "grppi/common/iterator_traits.h" namespace grppi { /** \addtogroup data_patterns @{ \defgroup stencil_pattern Stencil pattern \brief Interface for applyinng the \ref md_stencil. @{ */ /** \brief Invoke \ref md_stencil on a data sequence with sequential execution. \tparam Execution Execution type. \tparam InputRange Range type used for the input sequence. \tparam OutputRange Range type used for the output sequence \tparam Neighbourhood Callable type for obtaining the neighbourhood. \tparam StencilTransformer Callable type for performing the stencil transformation. \param ex Execution policy object. \param rin Range for the input sequence. \param rout Range for the output sequence. \param transform_op Stencil transformation operation. \param neighbour_op Neighbourhood operation. */ template <typename Execution, typename InputRange, typename OutputRange, typename StencilTransformer, typename Neighbourhood, meta::requires_<range_concept,InputRange> = 0, meta::requires_<range_concept,OutputRange> = 0> void stencil( const Execution & ex, InputRange && rin, OutputRange && rout, StencilTransformer && transform_op, Neighbourhood && neighbour_op) { static_assert(supports_stencil<Execution>(), "stencil not supported for execution type"); ex.stencil(std::make_tuple(rin.begin()), rout.begin(), rin.size(), std::forward<StencilTransformer>(transform_op), std::forward<Neighbourhood>(neighbour_op)); } /** \brief Invoke \ref md_stencil on a data sequence with sequential execution. \tparam Execution Execution type. \tparam InputRanges Range types used for the input sequences. \tparam OutputRange Range type used for the output sequence \tparam StencilTransformer Callable type for performing the stencil transformation. \tparam Neighbourhood Callable type for obtaining the neighbourhood. \param ex Execution policy object. \param rins Zip view for the input sequences. \param rout Range for the output sequence. \param transform_op Stencil transformation operation. \param neighbour_op Neighbourhood operation. */ template <typename Execution, typename ... InputRanges, typename OutputRange, typename StencilTransformer, typename Neighbourhood, meta::requires_<range_concept,InputRanges...> = 0, meta::requires_<range_concept,OutputRange> = 0> void stencil( const Execution & ex, zip_view<InputRanges...> rins, OutputRange && rout, StencilTransformer && transform_op, Neighbourhood && neighbour_op) { static_assert(supports_stencil<Execution>(), "stencil not supported for execution type"); ex.stencil(rins.begin(), rout.begin(), rins.size(), std::forward<StencilTransformer>(transform_op), std::forward<Neighbourhood>(neighbour_op)); } /** \brief Invoke \ref md_stencil on a data sequence with sequential execution. \tparam Execution Execution type. \tparam InputIt Iterator type used for the input sequence. \tparam OutputIt Iterator type used for the output sequence \tparam Neighbourhood Callable type for obtaining the neighbourhood. \tparam StencilTransformer Callable type for performing the stencil transformation. \param ex Execution policy object. \param first Iterator to the first element in the input sequence. \param last Iterator to one past the end of the input sequence. \param out Iterator to the first element in the output sequence. \param transform_op Stencil transformation operation. \param neighbour_op Neighbourhood operation. */ template <typename Execution, typename InputIt, typename OutputIt, typename StencilTransformer, typename Neighbourhood, requires_iterator<InputIt> = 0, requires_iterator<OutputIt> = 0> void stencil( const Execution & ex, InputIt first, InputIt last, OutputIt out, StencilTransformer && transform_op, Neighbourhood && neighbour_op) { static_assert(supports_stencil<Execution>(), "stencil not supported for execution type"); ex.stencil(std::make_tuple(first), out, std::distance(first,last), std::forward<StencilTransformer>(transform_op), std::forward<Neighbourhood>(neighbour_op)); } /** \brief Invoke \ref md_stencil on a data sequence with sequential execution. \tparam Execution Execution type. \tparam InputIterators Iterators types used for the input sequences. \tparam InputIt Iterator type used for the input sequence. \tparam OutputIt Iterator type used for the output sequence \tparam StencilTransformer Callable type for performing the stencil transformation. \tparam Neighbourhood Callable type for obtaining the neighbourhood. \param ex Execution policy object. \param firsts Tuple of iterator to the first elements of the input sequences. \param last Iterator to one past the end of the input sequence. \param out Iterator to the first element in the output sequence. \param transform_op Stencil transformation operation. \param neighbour_op Neighbourhood operation. */ template <typename Execution, typename ...InputIterators, typename InputIt, typename OutputIt, typename StencilTransformer, typename Neighbourhood, requires_iterators<InputIterators...> = 0, requires_iterator<InputIt> = 0, requires_iterator<OutputIt> = 0> void stencil( const Execution & ex, std::tuple<InputIterators...> firsts, InputIt last, OutputIt out, StencilTransformer && transform_op, Neighbourhood && neighbour_op) { static_assert(supports_stencil<Execution>(), "stencil not supported for execution type"); ex.stencil(firsts, out, std::distance(std::get<0>(firsts),last), std::forward<StencilTransformer>(transform_op), std::forward<Neighbourhood>(neighbour_op)); } /** \brief Invoke \ref md_stencil on a data sequence with sequential execution. \tparam Execution Execution type. \tparam InputIt Iterator type used for the input sequence. \tparam OutputIt Iterator type used for the output sequence \tparam Neighbourhood Callable type for obtaining the neighbourhood. \tparam StencilTransformer Callable type for performing the stencil transformation. \param ex Execution policy object. \param first Iterator to the first element in the input sequence. \param size Size of the input sequence to be proccessed. \param out Iterator to the first element in the output sequence. \param transform_op Stencil transformation operation. \param neighbour_op Neighbourhood operation. */ template <typename Execution, typename InputIt, typename OutputIt, typename StencilTransformer, typename Neighbourhood, requires_iterator<InputIt> = 0, requires_iterator<OutputIt> = 0> void stencil( const Execution & ex, InputIt first, std::size_t size, OutputIt out, StencilTransformer && transform_op, Neighbourhood && neighbour_op) { static_assert(supports_stencil<Execution>(), "stencil not supported for execution type"); ex.stencil(std::make_tuple(first), out, size, std::forward<StencilTransformer>(transform_op), std::forward<Neighbourhood>(neighbour_op)); } /** \brief Invoke \ref md_stencil on a data sequence with sequential execution. \tparam Execution Execution type. \tparam InputIterators Iterators types used for the input sequences. \tparam OutputIt Iterator type used for the output sequence \tparam StencilTransformer Callable type for performing the stencil transformation. \tparam Neighbourhood Callable type for obtaining the neighbourhood. \param ex Execution policy object. \param firsts Tuple of iterator to the first elements of the input sequences. \param size Size of the input sequence to be proccess. \param out Iterator to the first element in the output sequence. \param transform_op Stencil transformation operation. \param neighbour_op Neighbourhood operation. */ template <typename Execution, typename ...InputIterators, typename OutputIt, typename StencilTransformer, typename Neighbourhood, requires_iterators<InputIterators...> = 0, requires_iterator<OutputIt> = 0> void stencil( const Execution & ex, std::tuple<InputIterators...> firsts, std::size_t size, OutputIt out, StencilTransformer && transform_op, Neighbourhood && neighbour_op) { static_assert(supports_stencil<Execution>(), "stencil not supported for execution type"); ex.stencil(firsts, out, size, std::forward<StencilTransformer>(transform_op), std::forward<Neighbourhood>(neighbour_op)); } /** \brief Invoke \ref md_stencil on multiple data sequences with sequential execution. \tparam Execution Execution type. \tparam InputIt Iterator type used for the input sequence. \tparam OutputIt Iterator type used for the output sequence \tparam Neighbourhood Callable type for obtaining the neighbourhood. \tparam StencilTransformer Callable type for performing the stencil transformation. \tparam OtherInputIts Iterator types for additional input sequences. \param ex Execution policy object. \param first Iterator to the first element in the input sequence. \param last Iterator to one past the end of the input sequence. \param out Iterator to the first element in the output sequence. \param transform_op Stencil transformation operation. \param neighbour_op Neighbourhood operation. \param other_firsts Iterators to the first element of additional input sequences. \deprecated For multiple inputs, use a tuple or zip versions. */ template <typename Execution, typename InputIt, typename OutputIt, typename StencilTransformer, typename Neighbourhood, typename ... OtherInputIts, requires_iterator<InputIt> = 0, requires_iterator<OutputIt> = 0> [[deprecated("This version of the interface is deprecated.\n" "For multiple inputs, use a tuple or zip versions.")]] void stencil( const Execution & ex, InputIt first, InputIt last, OutputIt out, StencilTransformer && transform_op, Neighbourhood && neighbour_op, OtherInputIts ... other_firsts) { static_assert(supports_stencil<Execution>(), "stencil not supported for execution type"); ex.stencil(std::make_tuple(first,other_firsts...), out, std::distance(first,last), std::forward<StencilTransformer>(transform_op), std::forward<Neighbourhood>(neighbour_op)); } /** @} @} */ } #endif
{ "content_hash": "8ce3f341419684caee1c8fe45a7ba2e1", "timestamp": "", "source": "github", "line_count": 266, "max_line_length": 83, "avg_line_length": 39.88345864661654, "alnum_prop": 0.74615892167028, "repo_name": "arcosuc3m/grppi", "id": "65169cee522deda215a0c7e326d90a6aa9ee73d0", "size": "11227", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/grppi/stencil.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1463" }, { "name": "C++", "bytes": "474323" }, { "name": "CMake", "bytes": "10167" } ], "symlink_target": "" }
namespace net { URLRequestFtpJob::URLRequestFtpJob( URLRequest* request, NetworkDelegate* network_delegate, FtpTransactionFactory* ftp_transaction_factory, FtpAuthCache* ftp_auth_cache) : URLRequestJob(request, network_delegate), read_in_progress_(false), ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)), ftp_transaction_factory_(ftp_transaction_factory), ftp_auth_cache_(ftp_auth_cache) { DCHECK(ftp_transaction_factory); DCHECK(ftp_auth_cache); } // static URLRequestJob* URLRequestFtpJob::Factory(URLRequest* request, const std::string& scheme) { DCHECK_EQ(scheme, "ftp"); int port = request->url().IntPort(); if (request->url().has_port() && !IsPortAllowedByFtp(port) && !IsPortAllowedByOverride(port)) { return new URLRequestErrorJob(request, ERR_UNSAFE_PORT); } return new URLRequestFtpJob(request, request->context()->network_delegate(), request->context()->ftp_transaction_factory(), request->context()->ftp_auth_cache()); } bool URLRequestFtpJob::GetMimeType(std::string* mime_type) const { if (transaction_->GetResponseInfo()->is_directory_listing) { *mime_type = "text/vnd.chromium.ftp-dir"; return true; } return false; } HostPortPair URLRequestFtpJob::GetSocketAddress() const { if (!transaction_.get()) { return HostPortPair(); } return transaction_->GetResponseInfo()->socket_address; } URLRequestFtpJob::~URLRequestFtpJob() { } void URLRequestFtpJob::StartTransaction() { // Create a transaction. DCHECK(!transaction_.get()); transaction_.reset(ftp_transaction_factory_->CreateTransaction()); // No matter what, we want to report our status as IO pending since we will // be notifying our consumer asynchronously via OnStartCompleted. SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0)); int rv; if (transaction_.get()) { rv = transaction_->Start( &request_info_, base::Bind(&URLRequestFtpJob::OnStartCompleted, base::Unretained(this)), request_->net_log()); if (rv == ERR_IO_PENDING) return; } else { rv = ERR_FAILED; } // The transaction started synchronously, but we need to notify the // URLRequest delegate via the message loop. MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&URLRequestFtpJob::OnStartCompleted, weak_factory_.GetWeakPtr(), rv)); } void URLRequestFtpJob::OnStartCompleted(int result) { // Clear the IO_PENDING status SetStatus(URLRequestStatus()); // Note that transaction_ may be NULL due to a creation failure. if (transaction_.get()) { // FTP obviously doesn't have HTTP Content-Length header. We have to pass // the content size information manually. set_expected_content_size( transaction_->GetResponseInfo()->expected_content_size); } if (result == OK) { NotifyHeadersComplete(); } else if (transaction_.get() && transaction_->GetResponseInfo()->needs_auth) { GURL origin = request_->url().GetOrigin(); if (server_auth_ && server_auth_->state == AUTH_STATE_HAVE_AUTH) { ftp_auth_cache_->Remove(origin, server_auth_->credentials); } else if (!server_auth_) { server_auth_ = new AuthData(); } server_auth_->state = AUTH_STATE_NEED_AUTH; FtpAuthCache::Entry* cached_auth = ftp_auth_cache_->Lookup(origin); if (cached_auth) { // Retry using cached auth data. SetAuth(cached_auth->credentials); } else { // Prompt for a username/password. NotifyHeadersComplete(); } } else { NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, result)); } } void URLRequestFtpJob::OnReadCompleted(int result) { read_in_progress_ = false; if (result == 0) { NotifyDone(URLRequestStatus()); } else if (result < 0) { NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, result)); } else { // Clear the IO_PENDING status SetStatus(URLRequestStatus()); } NotifyReadComplete(result); } void URLRequestFtpJob::RestartTransactionWithAuth() { DCHECK(server_auth_ && server_auth_->state == AUTH_STATE_HAVE_AUTH); // No matter what, we want to report our status as IO pending since we will // be notifying our consumer asynchronously via OnStartCompleted. SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0)); int rv = transaction_->RestartWithAuth( server_auth_->credentials, base::Bind(&URLRequestFtpJob::OnStartCompleted, base::Unretained(this))); if (rv == ERR_IO_PENDING) return; MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&URLRequestFtpJob::OnStartCompleted, weak_factory_.GetWeakPtr(), rv)); } void URLRequestFtpJob::Start() { DCHECK(!transaction_.get()); request_info_.url = request_->url(); StartTransaction(); } void URLRequestFtpJob::Kill() { if (!transaction_.get()) return; transaction_.reset(); URLRequestJob::Kill(); weak_factory_.InvalidateWeakPtrs(); } LoadState URLRequestFtpJob::GetLoadState() const { return transaction_.get() ? transaction_->GetLoadState() : LOAD_STATE_IDLE; } bool URLRequestFtpJob::NeedsAuth() { // Note that we only have to worry about cases where an actual FTP server // requires auth (and not a proxy), because connecting to FTP via proxy // effectively means the browser communicates via HTTP, and uses HTTP's // Proxy-Authenticate protocol when proxy servers require auth. return server_auth_ && server_auth_->state == AUTH_STATE_NEED_AUTH; } void URLRequestFtpJob::GetAuthChallengeInfo( scoped_refptr<AuthChallengeInfo>* result) { DCHECK((server_auth_ != NULL) && (server_auth_->state == AUTH_STATE_NEED_AUTH)); scoped_refptr<AuthChallengeInfo> auth_info(new AuthChallengeInfo); auth_info->is_proxy = false; auth_info->challenger = HostPortPair::FromURL(request_->url()); // scheme and realm are kept empty. DCHECK(auth_info->scheme.empty()); DCHECK(auth_info->realm.empty()); result->swap(auth_info); } void URLRequestFtpJob::SetAuth(const AuthCredentials& credentials) { DCHECK(NeedsAuth()); server_auth_->state = AUTH_STATE_HAVE_AUTH; server_auth_->credentials = credentials; ftp_auth_cache_->Add(request_->url().GetOrigin(), server_auth_->credentials); RestartTransactionWithAuth(); } void URLRequestFtpJob::CancelAuth() { DCHECK(NeedsAuth()); server_auth_->state = AUTH_STATE_CANCELED; // Once the auth is cancelled, we proceed with the request as though // there were no auth. Schedule this for later so that we don't cause // any recursing into the caller as a result of this call. MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&URLRequestFtpJob::OnStartCompleted, weak_factory_.GetWeakPtr(), OK)); } uint64 URLRequestFtpJob::GetUploadProgress() const { return 0; } bool URLRequestFtpJob::ReadRawData(IOBuffer* buf, int buf_size, int *bytes_read) { DCHECK_NE(buf_size, 0); DCHECK(bytes_read); DCHECK(!read_in_progress_); int rv = transaction_->Read(buf, buf_size, base::Bind(&URLRequestFtpJob::OnReadCompleted, base::Unretained(this))); if (rv >= 0) { *bytes_read = rv; return true; } if (rv == ERR_IO_PENDING) { read_in_progress_ = true; SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0)); } else { NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, rv)); } return false; } } // namespace net
{ "content_hash": "ee120a7b6672883e87b7a7bce339e4c4", "timestamp": "", "source": "github", "line_count": 242, "max_line_length": 79, "avg_line_length": 31.96694214876033, "alnum_prop": 0.6614529472595657, "repo_name": "keishi/chromium", "id": "fb345990386e87a00ec263490966bebb93afef10", "size": "8418", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "net/url_request/url_request_ftp_job.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "1172794" }, { "name": "C", "bytes": "67452317" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "132681259" }, { "name": "F#", "bytes": "381" }, { "name": "Go", "bytes": "19048" }, { "name": "Java", "bytes": "361412" }, { "name": "JavaScript", "bytes": "16603687" }, { "name": "Objective-C", "bytes": "9609581" }, { "name": "PHP", "bytes": "97796" }, { "name": "Perl", "bytes": "918683" }, { "name": "Python", "bytes": "6407891" }, { "name": "R", "bytes": "524" }, { "name": "Shell", "bytes": "4192593" }, { "name": "Tcl", "bytes": "277077" } ], "symlink_target": "" }
package com.seoulmobileplatform.waterlife.MenuActivity; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.Ndef; import android.nfc.tech.NdefFormatable; import android.os.Bundle; import android.provider.Settings; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.seoulmobileplatform.waterlife.R; import com.skyfishjy.library.RippleBackground; import java.io.IOException; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; /*=========================================================== @ Version : v1.0.0 @ Since : 2016-10-17 @ Author : [email protected](엄재웅) ===========================================================*/ public class NFCActivity extends AppCompatActivity { // NFC System boolean mWriteMode = false; private NfcAdapter mNfcAdapter; private PendingIntent mNfcPendingIntent; @Bind(R.id.nfc_sticker) RippleBackground rippleBackground; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_nfc); ButterKnife.bind(this); // Start animation rippleBackground.startRippleAnimation(); // Check NFC isEnabled CheckNFCEnabled(); } // Check NFC isEnabled private void CheckNFCEnabled() { NfcAdapter nfcAdpt = NfcAdapter.getDefaultAdapter(this); if(nfcAdpt!=null) { if (!nfcAdpt.isEnabled()) { Intent setnfc = new Intent(Settings.ACTION_NFC_SETTINGS); startActivity(setnfc); Toast.makeText(this, "NFC 기능과 Android Beam을 켜주세요.", Toast.LENGTH_SHORT).show(); } } } // NFC Write Button @OnClick(R.id.nfc_btn_setnfcdata) void NFCWrite(View v) { mNfcAdapter = NfcAdapter.getDefaultAdapter(this); mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, NFCActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); enableTagWriteMode(); rippleBackground.setVisibility(View.VISIBLE); } // Enable Tag write Mode private void enableTagWriteMode() { mWriteMode = true; IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED); IntentFilter[] mWriteTagFilters = new IntentFilter[] { tagDetected }; mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent, mWriteTagFilters, null); } // Disable Tag write Mode private void disableTagWriteMode() { mWriteMode = false; } @Override protected void onNewIntent(Intent intent) { // TODO skydoves - Auto-generated method stub // Tag writing mode if (mWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) { Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); NdefRecord record = NdefRecord.createMime("waterlife_nfc/NFC", ((TextView)findViewById(R.id.nfc_edt01)).getText().toString().getBytes()); NdefMessage message = new NdefMessage(new NdefRecord[] { record }); // Detected Tag if (writeTag(message, detectedTag)) { disableTagWriteMode(); rippleBackground.setVisibility(View.INVISIBLE); Toast.makeText(this, "NFC 태그에 데이터를 작성했습니다.", Toast.LENGTH_SHORT).show(); } } } // Write NFC Tag Data public boolean writeTag(NdefMessage message, Tag tag) { // TODO skydoves - WRITE NFCDATA TAG int size = message.toByteArray().length; try { Ndef ndef = Ndef.get(tag); if (ndef != null) { ndef.connect(); if (!ndef.isWritable()) { Toast.makeText(getApplicationContext(), "Error: tag not writable", Toast.LENGTH_SHORT).show(); return false; } if (ndef.getMaxSize() < size) { Toast.makeText(getApplicationContext(), "Error: tag too small", Toast.LENGTH_SHORT).show(); return false; } ndef.writeNdefMessage(message); return true; } else { NdefFormatable format = NdefFormatable.get(tag); if (format != null) { try { format.connect(); format.format(message); return true; } catch (IOException e) { return false; } } else { return false; } } } catch (Exception e) { return false; } } }
{ "content_hash": "664e50cf69ff727e877e0c698d2822ae", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 149, "avg_line_length": 34.28378378378378, "alnum_prop": 0.5938115884903429, "repo_name": "MobileSeoul/2016seoul-04", "id": "b83d88b21b6fe85391d8eccf170321041b97fb12", "size": "5122", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "App source/app/src/main/java/com/seoulmobileplatform/waterlife/MenuActivity/NFCActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "171191" } ], "symlink_target": "" }
export function sanitize(slug: string) : string { return slug.replace(/[^a-zA-Z0-9-]+/g, ' ').trim().substring(0, 32).trim().toLowerCase().replace(/ /g, '-') } export function isValid(slug: string): boolean { return slug.length > 3 && slug === sanitize(slug) } const illegalSlugs = [ 'www', 'api', 'mail', 'media', // real sub-domains used by the app 'local', 'dev', 'staging', // sub-domains used by branches 'admin', 'profile', 'app', 'login', 'images', 'email', 'web' // official-looking subdomains ] export function isLegal(slug: string): boolean { return !(slug in illegalSlugs) }
{ "content_hash": "3db30d0506cf6808f57d5732ee422996", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 111, "avg_line_length": 30.65, "alnum_prop": 0.636215334420881, "repo_name": "seanmiddleditch/campman", "id": "96af8849d49688f95d82cf7253a4811ee16dd4d6", "size": "613", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/util/slug-utils.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "499" }, { "name": "HTML", "bytes": "5513" }, { "name": "JavaScript", "bytes": "3482" }, { "name": "TypeScript", "bytes": "262329" } ], "symlink_target": "" }
package insights // Copyright (c) Microsoft and contributors. 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "net/http" ) // ExportConfigurationsClient is the composite Swagger for Application Insights Management Client type ExportConfigurationsClient struct { ManagementClient } // NewExportConfigurationsClient creates an instance of the ExportConfigurationsClient client. func NewExportConfigurationsClient(subscriptionID string) ExportConfigurationsClient { return NewExportConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewExportConfigurationsClientWithBaseURI creates an instance of the ExportConfigurationsClient client. func NewExportConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) ExportConfigurationsClient { return ExportConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)} } // Create create a Continuous Export configuration of an Application Insights component. // // resourceGroupName is the name of the resource group. resourceName is the name of the Application Insights component // resource. exportProperties is properties that need to be specified to create a Continuous Export configuration of a // Application Insights component. func (client ExportConfigurationsClient) Create(resourceGroupName string, resourceName string, exportProperties ApplicationInsightsComponentExportRequest) (result ListApplicationInsightsComponentExportConfiguration, err error) { req, err := client.CreatePreparer(resourceGroupName, resourceName, exportProperties) if err != nil { err = autorest.NewErrorWithError(err, "insights.ExportConfigurationsClient", "Create", nil, "Failure preparing request") return } resp, err := client.CreateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "insights.ExportConfigurationsClient", "Create", resp, "Failure sending request") return } result, err = client.CreateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "insights.ExportConfigurationsClient", "Create", resp, "Failure responding to request") } return } // CreatePreparer prepares the Create request. func (client ExportConfigurationsClient) CreatePreparer(resourceGroupName string, resourceName string, exportProperties ApplicationInsightsComponentExportRequest) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "resourceName": autorest.Encode("path", resourceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-05-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/exportconfiguration", pathParameters), autorest.WithJSON(exportProperties), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare(&http.Request{}) } // CreateSender sends the Create request. The method will close the // http.Response Body if it receives an error. func (client ExportConfigurationsClient) CreateSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // CreateResponder handles the response to the Create request. The method always // closes the http.Response Body. func (client ExportConfigurationsClient) CreateResponder(resp *http.Response) (result ListApplicationInsightsComponentExportConfiguration, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete delete a Continuous Export configuration of an Application Insights component. // // resourceGroupName is the name of the resource group. resourceName is the name of the Application Insights component // resource. exportID is the Continuous Export configuration ID. This is unique within a Application Insights // component. func (client ExportConfigurationsClient) Delete(resourceGroupName string, resourceName string, exportID string) (result ApplicationInsightsComponentExportConfiguration, err error) { req, err := client.DeletePreparer(resourceGroupName, resourceName, exportID) if err != nil { err = autorest.NewErrorWithError(err, "insights.ExportConfigurationsClient", "Delete", nil, "Failure preparing request") return } resp, err := client.DeleteSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "insights.ExportConfigurationsClient", "Delete", resp, "Failure sending request") return } result, err = client.DeleteResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "insights.ExportConfigurationsClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. func (client ExportConfigurationsClient) DeletePreparer(resourceGroupName string, resourceName string, exportID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "exportId": autorest.Encode("path", exportID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "resourceName": autorest.Encode("path", resourceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-05-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/exportconfiguration/{exportId}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare(&http.Request{}) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client ExportConfigurationsClient) DeleteSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client ExportConfigurationsClient) DeleteResponder(resp *http.Response) (result ApplicationInsightsComponentExportConfiguration, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Get get the Continuous Export configuration for this export id. // // resourceGroupName is the name of the resource group. resourceName is the name of the Application Insights component // resource. exportID is the Continuous Export configuration ID. This is unique within a Application Insights // component. func (client ExportConfigurationsClient) Get(resourceGroupName string, resourceName string, exportID string) (result ApplicationInsightsComponentExportConfiguration, err error) { req, err := client.GetPreparer(resourceGroupName, resourceName, exportID) if err != nil { err = autorest.NewErrorWithError(err, "insights.ExportConfigurationsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "insights.ExportConfigurationsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "insights.ExportConfigurationsClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client ExportConfigurationsClient) GetPreparer(resourceGroupName string, resourceName string, exportID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "exportId": autorest.Encode("path", exportID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "resourceName": autorest.Encode("path", resourceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-05-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/exportconfiguration/{exportId}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare(&http.Request{}) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client ExportConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client ExportConfigurationsClient) GetResponder(resp *http.Response) (result ApplicationInsightsComponentExportConfiguration, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List gets a list of Continuous Export configuration of an Application Insights component. // // resourceGroupName is the name of the resource group. resourceName is the name of the Application Insights component // resource. func (client ExportConfigurationsClient) List(resourceGroupName string, resourceName string) (result ListApplicationInsightsComponentExportConfiguration, err error) { req, err := client.ListPreparer(resourceGroupName, resourceName) if err != nil { err = autorest.NewErrorWithError(err, "insights.ExportConfigurationsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "insights.ExportConfigurationsClient", "List", resp, "Failure sending request") return } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "insights.ExportConfigurationsClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. func (client ExportConfigurationsClient) ListPreparer(resourceGroupName string, resourceName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "resourceName": autorest.Encode("path", resourceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-05-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/exportconfiguration", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare(&http.Request{}) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client ExportConfigurationsClient) ListSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client ExportConfigurationsClient) ListResponder(resp *http.Response) (result ListApplicationInsightsComponentExportConfiguration, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Update update the Continuous Export configuration for this export id. // // resourceGroupName is the name of the resource group. resourceName is the name of the Application Insights component // resource. exportID is the Continuous Export configuration ID. This is unique within a Application Insights // component. exportProperties is properties that need to be specified to update the Continuous Export configuration. func (client ExportConfigurationsClient) Update(resourceGroupName string, resourceName string, exportID string, exportProperties ApplicationInsightsComponentExportRequest) (result ApplicationInsightsComponentExportConfiguration, err error) { req, err := client.UpdatePreparer(resourceGroupName, resourceName, exportID, exportProperties) if err != nil { err = autorest.NewErrorWithError(err, "insights.ExportConfigurationsClient", "Update", nil, "Failure preparing request") return } resp, err := client.UpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "insights.ExportConfigurationsClient", "Update", resp, "Failure sending request") return } result, err = client.UpdateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "insights.ExportConfigurationsClient", "Update", resp, "Failure responding to request") } return } // UpdatePreparer prepares the Update request. func (client ExportConfigurationsClient) UpdatePreparer(resourceGroupName string, resourceName string, exportID string, exportProperties ApplicationInsightsComponentExportRequest) (*http.Request, error) { pathParameters := map[string]interface{}{ "exportId": autorest.Encode("path", exportID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "resourceName": autorest.Encode("path", resourceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-05-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/exportconfiguration/{exportId}", pathParameters), autorest.WithJSON(exportProperties), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare(&http.Request{}) } // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client ExportConfigurationsClient) UpdateSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // UpdateResponder handles the response to the Update request. The method always // closes the http.Response Body. func (client ExportConfigurationsClient) UpdateResponder(resp *http.Response) (result ApplicationInsightsComponentExportConfiguration, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
{ "content_hash": "24fbf61ceded48204acacf9cbd9f80ea", "timestamp": "", "source": "github", "line_count": 390, "max_line_length": 241, "avg_line_length": 43.05128205128205, "alnum_prop": 0.7847528290649196, "repo_name": "wojtekzw/imageproxy", "id": "e2736ae624f045b7bdaf27a4ea76d2656fb2954a", "size": "16790", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/github.com/Azure/azure-sdk-for-go/services/appinsights/mgmt/2015-05-01/insights/exportconfigurations.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "118309" }, { "name": "Makefile", "bytes": "439" }, { "name": "Shell", "bytes": "1720" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>Statistics of Polarity in UD_Swedish-Talbanken</title> <link rel="root" href=""/> <!-- for JS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/> <link rel="stylesheet" type="text/css" href="../../css/style.css"/> <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/> <link rel="stylesheet" type="text/css" href="../../css/hint.css"/> <script type="text/javascript" src="../../lib/ext/head.load.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script> <script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script> <!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo --> <!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page. <script> (function() { var cx = '001145188882102106025:dl1mehhcgbo'; var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; gcse.src = 'https://cse.google.com/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); })(); </script> --> <!-- <link rel="shortcut icon" href="favicon.ico"/> --> </head> <body> <div id="main" class="center"> <div id="hp-header"> <table width="100%"><tr><td width="50%"> <span class="header-text"><a href="http://universaldependencies.org/#language-">home</a></span> <span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/treebanks/sv_talbanken/sv_talbanken-feat-Polarity.md" target="#">edit page</a></span> <span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span> </td><td> <gcse:search></gcse:search> </td></tr></table> </div> <hr/> <div class="v2complete"> This page pertains to UD version 2. </div> <div id="content"> <noscript> <div id="noscript"> It appears that you have Javascript disabled. Please consider enabling Javascript for this page to see the visualizations. </div> </noscript> <!-- The content may include scripts and styles, hence we must load the shared libraries before the content. --> <script type="text/javascript"> console.time('loading libraries'); var root = '../../'; // filled in by jekyll head.js( // External libraries // DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all. root + 'lib/ext/jquery.min.js', root + 'lib/ext/jquery.svg.min.js', root + 'lib/ext/jquery.svgdom.min.js', root + 'lib/ext/jquery.timeago.js', root + 'lib/ext/jquery-ui.min.js', root + 'lib/ext/waypoints.min.js', root + 'lib/ext/jquery.address.min.js' ); </script> <h2 id="treebank-statistics-ud_swedish-talbanken-features-polarity">Treebank Statistics: UD_Swedish-Talbanken: Features: <code class="language-plaintext highlighter-rouge">Polarity</code></h2> <p>This feature is universal. It occurs with 1 different values: <code class="language-plaintext highlighter-rouge">Neg</code>.</p> <p>791 tokens (1%) have a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>. 17 types (0%) occur at least once with a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>. 15 lemmas (0%) occur at least once with a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>. The feature is used with 4 part-of-speech tags: <tt><a href="sv_talbanken-pos-PART.html">PART</a></tt> (729; 1% instances), <tt><a href="sv_talbanken-pos-ADV.html">ADV</a></tt> (60; 0% instances), <tt><a href="sv_talbanken-pos-CCONJ.html">CCONJ</a></tt> (1; 0% instances), <tt><a href="sv_talbanken-pos-PRON.html">PRON</a></tt> (1; 0% instances).</p> <h3 id="part"><code class="language-plaintext highlighter-rouge">PART</code></h3> <p>729 <tt><a href="sv_talbanken-pos-PART.html">PART</a></tt> tokens (39% of all <code class="language-plaintext highlighter-rouge">PART</code> tokens) have a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>.</p> <p><code class="language-plaintext highlighter-rouge">PART</code> tokens may have the following values of <code class="language-plaintext highlighter-rouge">Polarity</code>:</p> <ul> <li><code class="language-plaintext highlighter-rouge">Neg</code> (729; 100% of non-empty <code class="language-plaintext highlighter-rouge">Polarity</code>): <em>inte, ej, icke</em></li> <li><code class="language-plaintext highlighter-rouge">EMPTY</code> (1145): <em>att, inte, Icke</em></li> </ul> <h3 id="adv"><code class="language-plaintext highlighter-rouge">ADV</code></h3> <p>60 <tt><a href="sv_talbanken-pos-ADV.html">ADV</a></tt> tokens (1% of all <code class="language-plaintext highlighter-rouge">ADV</code> tokens) have a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>.</p> <p>The most frequent other feature values with which <code class="language-plaintext highlighter-rouge">ADV</code> and <code class="language-plaintext highlighter-rouge">Polarity</code> co-occurred: <tt><a href="sv_talbanken-feat-Degree.html">Degree</a></tt><tt>=EMPTY</tt> (39; 65%).</p> <p><code class="language-plaintext highlighter-rouge">ADV</code> tokens may have the following values of <code class="language-plaintext highlighter-rouge">Polarity</code>:</p> <ul> <li><code class="language-plaintext highlighter-rouge">Neg</code> (60; 100% of non-empty <code class="language-plaintext highlighter-rouge">Polarity</code>): <em>aldrig, knappast, ingalunda, föga, nu, näppeligen, så, knappt, långt, minst</em></li> <li><code class="language-plaintext highlighter-rouge">EMPTY</code> (6978): <em>så, också, hur, där, här, bara, nu, ut, mycket, mer</em></li> </ul> <p><code class="language-plaintext highlighter-rouge">Polarity</code> seems to be <strong>lexical feature</strong> of <code class="language-plaintext highlighter-rouge">ADV</code>. 100% lemmas (10) occur only with one value of <code class="language-plaintext highlighter-rouge">Polarity</code>.</p> <h3 id="cconj"><code class="language-plaintext highlighter-rouge">CCONJ</code></h3> <p>1 <tt><a href="sv_talbanken-pos-CCONJ.html">CCONJ</a></tt> tokens (0% of all <code class="language-plaintext highlighter-rouge">CCONJ</code> tokens) have a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>.</p> <p><code class="language-plaintext highlighter-rouge">CCONJ</code> tokens may have the following values of <code class="language-plaintext highlighter-rouge">Polarity</code>:</p> <ul> <li><code class="language-plaintext highlighter-rouge">Neg</code> (1; 100% of non-empty <code class="language-plaintext highlighter-rouge">Polarity</code>): <em>varken</em></li> <li><code class="language-plaintext highlighter-rouge">EMPTY</code> (3702): <em>och, eller, men, både, utan, som, dels, såväl, samt, varken</em></li> </ul> <h3 id="pron"><code class="language-plaintext highlighter-rouge">PRON</code></h3> <p>1 <tt><a href="sv_talbanken-pos-PRON.html">PRON</a></tt> tokens (0% of all <code class="language-plaintext highlighter-rouge">PRON</code> tokens) have a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>.</p> <p>The most frequent other feature values with which <code class="language-plaintext highlighter-rouge">PRON</code> and <code class="language-plaintext highlighter-rouge">Polarity</code> co-occurred: <tt><a href="sv_talbanken-feat-Case.html">Case</a></tt><tt>=Acc</tt> (1; 100%), <tt><a href="sv_talbanken-feat-Definite.html">Definite</a></tt><tt>=Def</tt> (1; 100%), <tt><a href="sv_talbanken-feat-Gender.html">Gender</a></tt><tt>=EMPTY</tt> (1; 100%), <tt><a href="sv_talbanken-feat-Number.html">Number</a></tt><tt>=EMPTY</tt> (1; 100%), <tt><a href="sv_talbanken-feat-Poss.html">Poss</a></tt><tt>=EMPTY</tt> (1; 100%), <tt><a href="sv_talbanken-feat-PronType.html">PronType</a></tt><tt>=Ind</tt> (1; 100%).</p> <p><code class="language-plaintext highlighter-rouge">PRON</code> tokens may have the following values of <code class="language-plaintext highlighter-rouge">Polarity</code>:</p> <ul> <li><code class="language-plaintext highlighter-rouge">Neg</code> (1; 100% of non-empty <code class="language-plaintext highlighter-rouge">Polarity</code>): <em>sig</em></li> <li><code class="language-plaintext highlighter-rouge">EMPTY</code> (6670): <em>det, som, man, de, sig, vi, den, du, sin, detta</em></li> </ul> </div> <!-- support for embedded visualizations --> <script type="text/javascript"> var root = '../../'; // filled in by jekyll head.js( // We assume that external libraries such as jquery.min.js have already been loaded outside! // (See _layouts/base.html.) // brat helper modules root + 'lib/brat/configuration.js', root + 'lib/brat/util.js', root + 'lib/brat/annotation_log.js', root + 'lib/ext/webfont.js', // brat modules root + 'lib/brat/dispatcher.js', root + 'lib/brat/url_monitor.js', root + 'lib/brat/visualizer.js', // embedding configuration root + 'lib/local/config.js', // project-specific collection data root + 'lib/local/collections.js', // Annodoc root + 'lib/annodoc/annodoc.js', // NOTE: non-local libraries 'https://spyysalo.github.io/conllu.js/conllu.js' ); var webFontURLs = [ // root + 'static/fonts/Astloch-Bold.ttf', root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf', root + 'static/fonts/Liberation_Sans-Regular.ttf' ]; var setupTimeago = function() { jQuery("time.timeago").timeago(); }; head.ready(function() { setupTimeago(); // mark current collection (filled in by Jekyll) Collections.listing['_current'] = ''; // perform all embedding and support functions Annodoc.activate(Config.bratCollData, Collections.listing); }); </script> <!-- google analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-55233688-1', 'auto'); ga('send', 'pageview'); </script> <div id="footer"> <p class="footer-text">&copy; 2014–2021 <a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>. Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>. </div> </div> </body> </html>
{ "content_hash": "db4ce33c3c7e757c0802fa0899561d45", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 713, "avg_line_length": 55.79342723004695, "alnum_prop": 0.6597946819252777, "repo_name": "UniversalDependencies/universaldependencies.github.io", "id": "8ae4f5855a95a4b004d5b3bbe6a61463a1596695", "size": "11897", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "treebanks/sv_talbanken/sv_talbanken-feat-Polarity.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "64420" }, { "name": "HTML", "bytes": "383191916" }, { "name": "JavaScript", "bytes": "687350" }, { "name": "Perl", "bytes": "7788" }, { "name": "Python", "bytes": "21203" }, { "name": "Shell", "bytes": "7253" } ], "symlink_target": "" }
package quotas //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // AlarmHistory is a nested struct in quotas response type AlarmHistory struct { AlarmName string `json:"AlarmName" xml:"AlarmName"` QuotaUsage float64 `json:"QuotaUsage" xml:"QuotaUsage"` ProductCode string `json:"ProductCode" xml:"ProductCode"` CreateTime string `json:"CreateTime" xml:"CreateTime"` NotifyTarget string `json:"NotifyTarget" xml:"NotifyTarget"` Threshold float64 `json:"Threshold" xml:"Threshold"` ThresholdPercent float64 `json:"ThresholdPercent" xml:"ThresholdPercent"` QuotaActionCode string `json:"QuotaActionCode" xml:"QuotaActionCode"` NotifyChannels []string `json:"NotifyChannels" xml:"NotifyChannels"` }
{ "content_hash": "20c6233a18f5ddbc3e3c9e948e196dff", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 84, "avg_line_length": 48.03448275862069, "alnum_prop": 0.7480258435032304, "repo_name": "aliyun/alibaba-cloud-sdk-go", "id": "2f90d748c2421bab38fefa4d674b990a5ffc0493", "size": "1393", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "services/quotas/struct_alarm_history.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "734307" }, { "name": "Makefile", "bytes": "183" } ], "symlink_target": "" }
Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **account_id** | **int** | The account&#39;s ID. | **account_name** | **string** | The account&#39;s name. | **account_email** | **string** | The account&#39;s email. | **active** | **bool** | The account activation flag. | **api_key** | **string** | The account API key. | **users** | [**\Voximplant\Model\ClonedUserType[]**](ClonedUserType.md) | | [optional] **scenarios** | [**\Voximplant\Model\ClonedScenarioType[]**](ClonedScenarioType.md) | | [optional] **applications** | [**\Voximplant\Model\ClonedApplicationType[]**](ClonedApplicationType.md) | | [optional] **acd_queues** | [**\Voximplant\Model\ClonedACDQueueType[]**](ClonedACDQueueType.md) | | [optional] **acd_skills** | [**\Voximplant\Model\ClonedACDSkillType[]**](ClonedACDSkillType.md) | | [optional] **admin_roles** | [**\Voximplant\Model\ClonedAdminRoleType[]**](ClonedAdminRoleType.md) | | [optional] **admin_users** | [**\Voximplant\Model\ClonedAdminUserType[]**](ClonedAdminUserType.md) | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
{ "content_hash": "304f1d66ad0aa8264602a977a5cb1209", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 161, "avg_line_length": 69.61111111111111, "alnum_prop": 0.6304868316041501, "repo_name": "DmitryIvaneychik/phpsdk", "id": "d8878ef8c86d754983602c056ad8aa30d95dae44", "size": "1288", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/Model/ClonedAccountType.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "2710984" }, { "name": "Shell", "bytes": "1629" } ], "symlink_target": "" }
package xorm import ( "gomodules.xyz/secrets/types" ) type SSHKey struct { ID int64 Name string `xorm:"not null 'name'"` ClusterID int64 `xorm:"NOT NULL 'cluster_id'"` ClusterName string `xorm:"not null 'cluster_name'"` UID string `xorm:"not null 'uid'"` PublicKey string `xorm:"text not null 'public_key'"` PrivateKey types.SecureString `xorm:"text not null 'private_key'"` CreatedUnix int64 `xorm:"INDEX created"` UpdatedUnix int64 `xorm:"INDEX updated"` DeletedUnix *int64 `xorm:"null"` } func (SSHKey) TableName() string { return "ac_cluster_ssh" }
{ "content_hash": "cea24736128a46bd3415f0b79e0fe667", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 68, "avg_line_length": 27.583333333333332, "alnum_prop": 0.6148036253776435, "repo_name": "appscode/pharmer", "id": "ecdf36b25458aacfbaa5b9eb02363a088cf26eff", "size": "1223", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "store/providers/xorm/ssh_types.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "1067743" }, { "name": "Makefile", "bytes": "6149" }, { "name": "Python", "bytes": "31934" }, { "name": "Ruby", "bytes": "295" }, { "name": "Shell", "bytes": "31683" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Get-Set-Go Documentation</title> </head> <body> <div id="root-container"></div> <script async defer src="https://buttons.github.io/buttons.js"></script> <script type="text/javascript" src="gsg-site.min.js"></script></body> </html>
{ "content_hash": "c49a80d4b6ac9a64079c036d63f8d9ad", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 76, "avg_line_length": 26.4, "alnum_prop": 0.6388888888888888, "repo_name": "get-set-go/gsg-documentation-site", "id": "a4c30bc55cb22453500b41be364feaf94ec16a2e", "size": "396", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dist/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1114" }, { "name": "HTML", "bytes": "334" }, { "name": "JavaScript", "bytes": "65993" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>V8 API Reference Guide for node.js v6.4.0: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v6.4.0 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">NamedPropertyHandlerConfiguration</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">v8::NamedPropertyHandlerConfiguration Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>data</b> (defined in <a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a>)</td><td class="entry"><a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>deleter</b> (defined in <a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a>)</td><td class="entry"><a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>enumerator</b> (defined in <a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a>)</td><td class="entry"><a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>flags</b> (defined in <a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a>)</td><td class="entry"><a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getter</b> (defined in <a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a>)</td><td class="entry"><a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html#a7304ee88edae7f7342f3a03f7974202d">NamedPropertyHandlerConfiguration</a>(GenericNamedPropertyGetterCallback getter=0, GenericNamedPropertySetterCallback setter=0, GenericNamedPropertyQueryCallback query=0, GenericNamedPropertyDeleterCallback deleter=0, GenericNamedPropertyEnumeratorCallback enumerator=0, Local&lt; Value &gt; data=Local&lt; Value &gt;(), PropertyHandlerFlags flags=PropertyHandlerFlags::kNone)</td><td class="entry"><a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>query</b> (defined in <a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a>)</td><td class="entry"><a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>setter</b> (defined in <a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a>)</td><td class="entry"><a class="el" href="structv8_1_1NamedPropertyHandlerConfiguration.html">v8::NamedPropertyHandlerConfiguration</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html>
{ "content_hash": "0aad768110f7e5d153d7ab5bd620658a", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 709, "avg_line_length": 67.8157894736842, "alnum_prop": 0.7021083947742853, "repo_name": "v8-dox/v8-dox.github.io", "id": "40c1db5c5719a7933ed2ee68e94dc7b98b3c5eee", "size": "7731", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "e6887e2/html/structv8_1_1NamedPropertyHandlerConfiguration-members.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
""" Test QiToolchain SVN Status """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function import os import qitoolchain.toolchain import qitoolchain.svn_package from qitoolchain.test.conftest import qitoolchain_action from qibuild.test.conftest import record_messages from qisrc.test.conftest import svn_server def test_simple(qitoolchain_action, svn_server, feed, record_messages): """ Test Simple """ toolchain = qitoolchain.toolchain.Toolchain("foo") boost_url = svn_server.create_repo("boost") svn_server.commit_file("boost", "version.hpp", "") qt_url = svn_server.create_repo("qt") boost_package = qitoolchain.svn_package.SvnPackage("boost") boost_package.url = boost_url qt_package = qitoolchain.svn_package.SvnPackage("qt") qt_package.url = qt_url feed.add_svn_package(boost_package) feed.add_svn_package(qt_package) toolchain.update(feed.url) record_messages.reset() rc = qitoolchain_action("svn-status", "foo", retcode=True) assert rc == 0 assert not record_messages.find("qt") assert not record_messages.find("boost") assert record_messages.find("All OK") # Now create a problem in the svn repo: boost_path = toolchain.get_package("boost").path version_hpp = os.path.join(boost_path, "version.hpp") os.remove(version_hpp) record_messages.reset() rc = qitoolchain_action("svn-status", "foo", retcode=True) assert rc != 0 assert record_messages.find("boost") assert record_messages.find("version.hpp")
{ "content_hash": "3295105da37f04a958a2ec451740be33", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 71, "avg_line_length": 37.714285714285715, "alnum_prop": 0.711489898989899, "repo_name": "aldebaran/qibuild", "id": "02bf091b461f4585795a64bc4587c3a96d7893df", "size": "1781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "python/qitoolchain/test/test_qitoolchain_svn_status.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "6892" }, { "name": "C++", "bytes": "23130" }, { "name": "CMake", "bytes": "292637" }, { "name": "Makefile", "bytes": "755" }, { "name": "Nix", "bytes": "563" }, { "name": "Python", "bytes": "1581825" }, { "name": "SWIG", "bytes": "306" }, { "name": "Shell", "bytes": "888" } ], "symlink_target": "" }
<?php /* @var $installer Mage_Sales_Model_Entity_Setup */ $installer = $this; $installer->getConnection()->addKey($this->getTable('sales/order'), 'IDX_QUOTE_ID' ,'quote_id');
{ "content_hash": "d5fbae1bd7d9d45a6a284f8e93ae8314", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 96, "avg_line_length": 29.5, "alnum_prop": 0.6779661016949152, "repo_name": "portchris/NaturalRemedyCompany", "id": "82a93110f37f49a469d627e18c7d659ff123d823", "size": "1111", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/code/core/Mage/Sales/sql/sales_setup/mysql4-upgrade-1.4.0.24-1.4.0.25.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "20009" }, { "name": "Batchfile", "bytes": "1036" }, { "name": "CSS", "bytes": "2584823" }, { "name": "Dockerfile", "bytes": "828" }, { "name": "HTML", "bytes": "8762252" }, { "name": "JavaScript", "bytes": "2932806" }, { "name": "PHP", "bytes": "66466458" }, { "name": "PowerShell", "bytes": "1028" }, { "name": "Ruby", "bytes": "576" }, { "name": "Shell", "bytes": "40066" }, { "name": "XSLT", "bytes": "2135" } ], "symlink_target": "" }
import React, { Component, PropTypes } from 'react'; /*** Components ***/ import Board from './Board'; import Settings from './Settings'; import Results from './Results'; /*** AI ***/ import compTurn from '../utils/compTurn'; import boardFull from '../utils/AI/boardFull'; import findResults from '../utils/AI/helpers/findResults'; export default class Main extends Component { static propTypes = { gameBoard: PropTypes.object.isRequired, settings: PropTypes.object.isRequired, actions: PropTypes.object.isRequired, compCanPlay: PropTypes.bool.isRequired, results: PropTypes.object.isRequired } constructor(props, context) { super(props, context); } placeMarker(event) { const { gameBoard, actions, settings } = this.props; const { id: square } = event.target; const { user, comp} = settings; actions.addMarker(square, user); actions.setCompTurn(); } componentDidUpdate() { const { gameBoard, actions, settings, compCanPlay } = this.props; /*** I set it back to the user turn as soon as the component updates or, as soon as there is a change to the state; a marker is placed on the gameBoard either user or comp. This was to prevent the comp from playing first after a tie game. Since the flag was originally after the compturn() call ***/ actions.setUserTurn(); /** found a winning match **/ if (!!findResults(gameBoard)) { actions.clearBoard(); } /*** board full without winning match ***/ if (boardFull(gameBoard) && !findResults(gameBoard)) { // if I delay the call then the Results component calls the tie action // twice... actions.clearBoard(); } /*** normal computer turn ***/ if(compCanPlay && !findResults(gameBoard) && !boardFull(gameBoard)) { let square = compTurn(gameBoard, settings.comp); actions.addMarker(square, settings.comp); } } render() { const { gameBoard, actions, settings, compCanPlay, results } = this.props; return ( <div className="col span_3_of_3"> <header> <h1>Natac's Tic Tac Toe</h1> <a className="source-code" href="https://github.com/natac13/Tic-Tac-Toe-Game" target="_blank" title="Github Repo"> Source Code </a> </header> {/*Can pass the spread version of the state to the component and get all props from it that way in Board.*/} <Settings {...this.props} /> <Board placeMarker={this.placeMarker.bind(this)} gameBoard={gameBoard}/> <Results results={results} gameBoard={gameBoard} actions={actions}/> </div> ); } }
{ "content_hash": "5afe93d45733ed346973446046fec905", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 124, "avg_line_length": 33.142857142857146, "alnum_prop": 0.5686339522546419, "repo_name": "natac13/Tic-Tac-Toe-Game", "id": "de2076b757c93fe6dc5651157c1ef5afc5304cdd", "size": "3016", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "app/components/Main.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11196" }, { "name": "HTML", "bytes": "400" }, { "name": "JavaScript", "bytes": "61881" } ], "symlink_target": "" }
package cashier; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({cashier.CashierTest.class, cashier.resource.ResourceSuite.class, cashier.net.NetSuite.class}) public class CashierSuite { @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } }
{ "content_hash": "c7719478de38903e6d60a40858b34453", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 114, "avg_line_length": 20.866666666666667, "alnum_prop": 0.7523961661341853, "repo_name": "akoerner/cashier.java", "id": "0ad684290475443e43262d3253877a5005ca7c40", "size": "626", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/cashier/CashierSuite.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "268664" } ], "symlink_target": "" }
using TeaLeafed.Domain.Importer.Internal.Helpers.Absract; using umbraco; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Services; namespace TeaLeafed.Domain.Importer.Internal.Helpers { /// <summary> /// Content service for Umbraco /// </summary> internal class MigrationContentService : IMigrationContentService { /// <summary> /// container for the content service /// </summary> private IContentService _content { get; set; } public MigrationContentService() { _content = ApplicationContext.Current.Services.ContentService; } /// <summary> /// Get a IContent by its id /// </summary> /// <param name="id"></param> /// <returns></returns> public IContent GetById(int id) => _content.GetById(id); /// <summary> /// Create content initial /// </summary> /// <param name="name"></param> /// <param name="parentId"></param> /// <param name="documentTypeAlias"></param> /// <returns></returns> public IContent CreateContent(string name, int parentId, string documentTypeAlias) => _content.CreateContent(name, parentId, documentTypeAlias); /// <summary> /// Save an updated content /// </summary> /// <param name="content"></param> public void Save(IContent content) => _content.Save(content); /// <summary> /// Save and publish /// </summary> /// <param name="content"></param> public void SaveAndPublishWithStatus(IContent content) => _content.SaveAndPublishWithStatus(content); /// <summary> /// Gets the nice url from a content model /// </summary> /// <param name="id"></param> /// <returns></returns> public string NiceUrl(int id) { return library.NiceUrl(id); } } }
{ "content_hash": "f42b9489928a519030ef72ef8f735acf", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 152, "avg_line_length": 31.532258064516128, "alnum_prop": 0.579539641943734, "repo_name": "micklaw/TeaLeafed", "id": "ba426fab7a4d0cb3be0dcb59ec91bd25a173725d", "size": "1957", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TeaLeafed.Domain/Importer/Internal/Helpers/MigrationContentService.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "301448" }, { "name": "C#", "bytes": "120164" }, { "name": "CSS", "bytes": "404682" }, { "name": "HTML", "bytes": "598301" }, { "name": "JavaScript", "bytes": "4157724" }, { "name": "XSLT", "bytes": "48541" } ], "symlink_target": "" }
#include <memory> #include <utility> #include <vector> #include "absl/memory/memory.h" #include "tensorflow/compiler/xla/literal.h" #include "tensorflow/compiler/xla/service/cpu/cpu_instruction_fusion.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/tests/hlo_test_base.h" #include "tensorflow/compiler/xla/tests/literal_test_util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/platform/test.h" namespace xla { namespace cpu { namespace { class CpuFusionTest : public HloTestBase { protected: CpuFusionTest() {} ErrorSpec error_spec_{0.0001, 1e-5}; }; TEST_F(CpuFusionTest, FuseTwoElementwiseOps) { auto builder = HloComputation::Builder(TestName()); auto input_literal1 = LiteralUtil::CreateR1<float>({1.0, 2.0, 3.0}); auto input_literal2 = LiteralUtil::CreateR1<float>({-2.0, -42.0, 2.0}); Shape vshape = input_literal1.shape(); auto input1 = builder.AddInstruction( HloInstruction::CreateConstant(std::move(input_literal1))); auto input2 = builder.AddInstruction( HloInstruction::CreateConstant(std::move(input_literal2))); auto add1 = builder.AddInstruction( HloInstruction::CreateBinary(vshape, HloOpcode::kAdd, input1, input2)); builder.AddInstruction( HloInstruction::CreateUnary(vshape, HloOpcode::kNegate, add1)); auto module = CreateNewVerifiedModule(); module->AddEntryComputation(builder.Build()); CpuInstructionFusion fusion; EXPECT_TRUE(fusion.Run(module.get()).ValueOrDie()); // The computation root instruction was fused. Verify the fusion instruction // is now the root. auto computation = module->entry_computation(); auto fusion_instruction = computation->root_instruction(); EXPECT_EQ(HloOpcode::kFusion, fusion_instruction->opcode()); EXPECT_EQ(HloOpcode::kNegate, fusion_instruction->fused_expression_root()->opcode()); // There should be four fused instructions: 2 parameters, the add, and the // negate. EXPECT_EQ(4, fusion_instruction->fused_instruction_count()); // Compile and execute the computation. auto result = ExecuteAndTransfer(module->Clone(), {}); // Check the output correctness. LiteralTestUtil::ExpectR1Near<float>({1.0, 40.0, -5.0}, result, error_spec_); } TEST_F(CpuFusionTest, FuseElementwiseOpChain) { auto builder = HloComputation::Builder(TestName()); auto input_literal = LiteralUtil::CreateR1<float>({-1.5, -2.5, -3.0}); Shape vshape = input_literal.shape(); auto input = builder.AddInstruction( HloInstruction::CreateConstant(std::move(input_literal))); auto negate = builder.AddInstruction( HloInstruction::CreateUnary(vshape, HloOpcode::kNegate, input)); auto ceil = builder.AddInstruction( HloInstruction::CreateUnary(vshape, HloOpcode::kCeil, negate)); auto exp = builder.AddInstruction( HloInstruction::CreateUnary(vshape, HloOpcode::kExp, ceil)); auto floor = builder.AddInstruction( HloInstruction::CreateUnary(vshape, HloOpcode::kFloor, exp)); auto two = builder.AddInstruction(HloInstruction::CreateBroadcast( vshape, builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(2.0))), {})); builder.AddInstruction( HloInstruction::CreateBinary(vshape, HloOpcode::kMultiply, two, floor)); auto module = CreateNewVerifiedModule(); module->AddEntryComputation(builder.Build()); CpuInstructionFusion fusion; EXPECT_TRUE(fusion.Run(module.get()).ValueOrDie()); // The computation root instruction was fused. Verify the fusion instruction // is now the root. auto computation = module->entry_computation(); auto fusion_instruction = computation->root_instruction(); EXPECT_EQ(HloOpcode::kFusion, fusion_instruction->opcode()); EXPECT_EQ(HloOpcode::kMultiply, fusion_instruction->fused_expression_root()->opcode()); // There should be 8 fused instructions: 2 parameters and the fused // operations. EXPECT_EQ(8, fusion_instruction->fused_instruction_count()); // Compile and execute the computation. auto result = ExecuteAndTransfer(module->Clone(), {}); // Check the output correctness. LiteralTestUtil::ExpectR1Near<float>({14.0, 40.0, 40.0}, result, error_spec_); } TEST_F(CpuFusionTest, ElementwiseOpChainWithNonfusibleInstruction) { // Test a chain of fusible ops with a non-fusible op (a reduce) thrown in the // middle. auto module = CreateNewVerifiedModule(); auto builder = HloComputation::Builder(TestName()); auto input_literal = LiteralUtil::CreateR1<float>({-1.5, -2.5, -3.0}); Shape vshape = input_literal.shape(); auto input = builder.AddInstruction( HloInstruction::CreateConstant(std::move(input_literal))); auto negate = builder.AddInstruction( HloInstruction::CreateUnary(vshape, HloOpcode::kNegate, input)); auto ceil = builder.AddInstruction( HloInstruction::CreateUnary(vshape, HloOpcode::kCeil, negate)); auto cshape = ShapeUtil::MakeShape(F32, {6}); auto concatenate = builder.AddInstruction( HloInstruction::CreateConcatenate(cshape, {ceil, ceil}, /*dimension=*/0)); // Build an x+y computation to use in a reduce. Shape r0f32 = ShapeUtil::MakeShape(F32, {}); auto embedded_builder = HloComputation::Builder("f32+f32"); embedded_builder.AddInstruction(HloInstruction::CreateBinary( r0f32, HloOpcode::kAdd, embedded_builder.AddInstruction( HloInstruction::CreateParameter(0, r0f32, "x")), embedded_builder.AddInstruction( HloInstruction::CreateParameter(1, r0f32, "y")))); auto add_f32 = module->AddEmbeddedComputation(embedded_builder.Build()); // This is a nop reduction. auto reduce = builder.AddInstruction(HloInstruction::CreateReduce( cshape, builder.AddInstruction(HloInstruction::CreateReshape( ShapeUtil::MakeShape(F32, {6, 1}), concatenate)), /*init_value=*/ builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(0))), /*dimensions_to_reduce=*/{1}, add_f32)); auto exp = builder.AddInstruction( HloInstruction::CreateUnary(cshape, HloOpcode::kExp, reduce)); auto floor = builder.AddInstruction( HloInstruction::CreateUnary(cshape, HloOpcode::kFloor, exp)); auto two = builder.AddInstruction(HloInstruction::CreateBroadcast( cshape, builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(2.0))), {})); builder.AddInstruction( HloInstruction::CreateBinary(cshape, HloOpcode::kMultiply, two, floor)); module->AddEntryComputation(builder.Build()); CpuInstructionFusion fusion; EXPECT_TRUE(fusion.Run(module.get()).ValueOrDie()); // The computation root instruction was fused. Verify the fusion instruction // is now the root. auto computation = module->entry_computation(); auto fusion_instruction1 = computation->root_instruction(); EXPECT_EQ(HloOpcode::kFusion, fusion_instruction1->opcode()); EXPECT_EQ(HloOpcode::kMultiply, fusion_instruction1->fused_expression_root()->opcode()); // There should be 6 fused instructions in the root fusion instruction: 2 // parameters, multiply, floor, and exp. EXPECT_EQ(6, fusion_instruction1->fused_instruction_count()) << fusion_instruction1->fused_instructions_computation()->ToString(); auto fusion_instruction2 = reduce->operand(0); EXPECT_EQ(HloOpcode::kFusion, fusion_instruction1->opcode()); EXPECT_EQ(HloOpcode::kReshape, fusion_instruction2->fused_expression_root()->opcode()); // There should be 5 fused instructions in the second fusion instruction: 1 // parameter, negate, ceil, concat, and reshape. EXPECT_EQ(5, fusion_instruction2->fused_instruction_count()) << fusion_instruction2->fused_instructions_computation()->ToString(); // Compile and execute the computation. auto result = ExecuteAndTransfer(module->Clone(), {}); // Check the output correctness. LiteralTestUtil::ExpectR1Near<float>({14.0, 40.0, 40.0, 14.0, 40.0, 40.0}, result, error_spec_); } TEST_F(CpuFusionTest, TestOperandOrderToAvoidDuplication) { // Test that the operands of an instruction to be fused are considered in the // proper order to avoid duplication. Test input: // // constant = {...} // negate = neg(constant) // ceil = ceil(negate) // add1 = add(negate, ceil) // add2 = add(ceil, negate) // // In this example, the operands of both add1 and add2 should be fused in the // order {ceil, negate} even though they have different orders in their // operand vectors. Test for this problem by counting the number of nodes in // each fusion instruction to ensure that negate is not duplicated. auto builder = HloComputation::Builder(TestName()); auto input_literal = LiteralUtil::CreateR1<float>({1.0, 2.0, 3.0}); Shape vshape = input_literal.shape(); auto constant = builder.AddInstruction( HloInstruction::CreateConstant(std::move(input_literal))); auto negate = builder.AddInstruction( HloInstruction::CreateUnary(vshape, HloOpcode::kNegate, constant)); auto ceil = builder.AddInstruction( HloInstruction::CreateUnary(vshape, HloOpcode::kCeil, negate)); auto add1 = builder.AddInstruction( HloInstruction::CreateBinary(vshape, HloOpcode::kMultiply, negate, ceil)); auto add2 = builder.AddInstruction( HloInstruction::CreateBinary(vshape, HloOpcode::kMultiply, ceil, negate)); // Tie together the two adds with a tuple to create a single root. auto result = builder.AddInstruction(HloInstruction::CreateTuple({add1, add2})); // Create computation and module. auto module = CreateNewVerifiedModule(); module->AddEntryComputation(builder.Build()); // Run fusion. CpuInstructionFusion fusion; EXPECT_TRUE(fusion.Run(module.get()).ValueOrDie()); auto fusion1 = result->operand(0); auto fusion2 = result->operand(1); EXPECT_EQ(HloOpcode::kFusion, fusion1->opcode()); EXPECT_EQ(HloOpcode::kFusion, fusion2->opcode()); // Each fusion instruction should have 4 fused instruction inside: add, ceil, // negate, and the fused parameter. EXPECT_EQ(4, fusion1->fused_instruction_count()); EXPECT_EQ(4, fusion2->fused_instruction_count()); // The fusion has no parameters, everything is fused including constants. EXPECT_EQ(0, fusion1->operand_count()); EXPECT_EQ(0, fusion2->operand_count()); } TEST_F(CpuFusionTest, DoNotDuplicateExpensiveOps) { // Verify that expensive operations will not be fused if the fusion results in // duplication. Test code: // // constant = 42.0 // exp1 = exp(constant) // negate1 = negate(exp1) // exp2 = exp(constant) // negate2 = negate(exp2) // tuple = tuple(negate1, negate2, exp2) // // exp1 should be fused down into negate1, but exp2 will not be fused into // negate2 because this will result in duplication of the expensive exp // computation. The duplication is caused by the other use of exp2 in the // tuple. auto builder = HloComputation::Builder(TestName()); auto input_literal1 = LiteralUtil::CreateR1<float>({1.0, 2.0, 3.0}); auto input_literal2 = LiteralUtil::CreateR1<float>({-2.0, -42.0, 2.0}); auto constant = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(42.0))); Shape shape = constant->shape(); auto exp1 = builder.AddInstruction( HloInstruction::CreateUnary(shape, HloOpcode::kExp, constant)); auto negate1 = builder.AddInstruction( HloInstruction::CreateUnary(shape, HloOpcode::kNegate, exp1)); auto exp2 = builder.AddInstruction( HloInstruction::CreateUnary(shape, HloOpcode::kExp, constant)); auto negate2 = builder.AddInstruction( HloInstruction::CreateUnary(shape, HloOpcode::kNegate, exp2)); auto tuple = builder.AddInstruction( HloInstruction::CreateTuple({negate1, negate2, exp2})); auto module = CreateNewVerifiedModule(); module->AddEntryComputation(builder.Build()); CpuInstructionFusion fusion; EXPECT_TRUE(fusion.Run(module.get()).ValueOrDie()); // The only fusion instruction should be operand 0 of the tuple (formerly // negate1). EXPECT_EQ(HloOpcode::kFusion, tuple->operand(0)->opcode()); EXPECT_EQ(HloOpcode::kNegate, tuple->operand(1)->opcode()); EXPECT_EQ(HloOpcode::kExp, tuple->operand(2)->opcode()); auto fusion_inst = tuple->operand(0); // There should be three fused instructions: negate2, exp2, and the fused // constant. EXPECT_EQ(3, fusion_inst->fused_instruction_count()); EXPECT_EQ(0, fusion_inst->operand_count()); } } // namespace } // namespace cpu } // namespace xla
{ "content_hash": "7465f157c482720cadda0aa39bdf4879", "timestamp": "", "source": "github", "line_count": 318, "max_line_length": 80, "avg_line_length": 40.698113207547166, "alnum_prop": 0.7154226549219596, "repo_name": "theflofly/tensorflow", "id": "3a26fea9116c0c65892667afbb8a37ee141f7f6e", "size": "13610", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tensorflow/compiler/xla/service/cpu/tests/cpu_fusion_test.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "3560" }, { "name": "Batchfile", "bytes": "14734" }, { "name": "C", "bytes": "644154" }, { "name": "C#", "bytes": "8446" }, { "name": "C++", "bytes": "59546729" }, { "name": "CMake", "bytes": "207169" }, { "name": "Dockerfile", "bytes": "75509" }, { "name": "Go", "bytes": "1507157" }, { "name": "HTML", "bytes": "4680118" }, { "name": "Java", "bytes": "908330" }, { "name": "Jupyter Notebook", "bytes": "2510253" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "94633" }, { "name": "Objective-C", "bytes": "60069" }, { "name": "Objective-C++", "bytes": "118322" }, { "name": "PHP", "bytes": "15108" }, { "name": "Pascal", "bytes": "770" }, { "name": "Perl", "bytes": "7536" }, { "name": "PureBasic", "bytes": "25356" }, { "name": "Python", "bytes": "46310564" }, { "name": "RobotFramework", "bytes": "891" }, { "name": "Ruby", "bytes": "838" }, { "name": "Shell", "bytes": "481712" }, { "name": "Smarty", "bytes": "27249" }, { "name": "Swift", "bytes": "53109" } ], "symlink_target": "" }
package com.linkedin.pinot.broker.routing.builder; import com.linkedin.pinot.broker.routing.RoutingTableLookupRequest; import com.linkedin.pinot.common.config.TableConfig; import com.linkedin.pinot.common.metrics.BrokerMetrics; import com.linkedin.pinot.common.utils.SegmentName; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.configuration.Configuration; import org.apache.helix.ZNRecord; import org.apache.helix.model.ExternalView; import org.apache.helix.model.InstanceConfig; import org.apache.helix.store.zk.ZkHelixPropertyStore; /** * Create a given number of routing tables based on random selections from ExternalView. */ public class DefaultRealtimeRoutingTableBuilder implements RoutingTableBuilder { private RoutingTableBuilder _realtimeHLCRoutingTableBuilder; private RoutingTableBuilder _realtimeLLCRoutingTableBuilder; private boolean _hasHLC; private boolean _hasLLC; @Override public void init(Configuration configuration, TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore, BrokerMetrics brokerMetrics) { _realtimeHLCRoutingTableBuilder = new HighLevelConsumerBasedRoutingTableBuilder(); _realtimeLLCRoutingTableBuilder = new LowLevelConsumerRoutingTableBuilder(); _realtimeHLCRoutingTableBuilder.init(configuration, tableConfig, propertyStore, brokerMetrics); _realtimeLLCRoutingTableBuilder.init(configuration, tableConfig, propertyStore, brokerMetrics); } @Override public void computeOnExternalViewChange(String tableName, ExternalView externalView, List<InstanceConfig> instanceConfigs) { Set<String> segmentSet = externalView.getPartitionSet(); for (String segmentName : segmentSet) { if (SegmentName.isHighLevelConsumerSegmentName(segmentName)) { _hasHLC = true; } if (SegmentName.isLowLevelConsumerSegmentName(segmentName)) { _hasLLC = true; } } if (_hasHLC) { _realtimeHLCRoutingTableBuilder.computeOnExternalViewChange(tableName, externalView, instanceConfigs); } if (_hasLLC) { _realtimeLLCRoutingTableBuilder.computeOnExternalViewChange(tableName, externalView, instanceConfigs); } } @Override public Map<String, List<String>> getRoutingTable(RoutingTableLookupRequest request) { boolean forceLLC = false; boolean forceHLC = false; for (String routingOption : request.getRoutingOptions()) { if (routingOption.equalsIgnoreCase("FORCE_HLC")) { forceHLC = true; } if (routingOption.equalsIgnoreCase("FORCE_LLC")) { forceLLC = true; } } if (forceHLC && forceLLC) { throw new RuntimeException("Trying to force routing to both HLC and LLC at the same time"); } if (forceLLC) { return _realtimeLLCRoutingTableBuilder.getRoutingTable(request); } else if (forceHLC) { return _realtimeHLCRoutingTableBuilder.getRoutingTable(request); } else { if (_hasLLC) { return _realtimeLLCRoutingTableBuilder.getRoutingTable(request); } else if (_hasHLC) { return _realtimeHLCRoutingTableBuilder.getRoutingTable(request); } else { return Collections.emptyMap(); } } } @Override public List<Map<String, List<String>>> getRoutingTables() { if (_hasLLC) { return _realtimeLLCRoutingTableBuilder.getRoutingTables(); } else if (_hasHLC) { return _realtimeHLCRoutingTableBuilder.getRoutingTables(); } else { return Collections.emptyList(); } } }
{ "content_hash": "2092f9745eec9ef7053dabc84b400ebe", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 149, "avg_line_length": 36.40816326530612, "alnum_prop": 0.7446748878923767, "repo_name": "fx19880617/pinot-1", "id": "d78de04b1a1e9909aba251b13328666304c4221c", "size": "4205", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "pinot-broker/src/main/java/com/linkedin/pinot/broker/routing/builder/DefaultRealtimeRoutingTableBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "4620" }, { "name": "Batchfile", "bytes": "7738" }, { "name": "CSS", "bytes": "925082" }, { "name": "FreeMarker", "bytes": "243834" }, { "name": "HTML", "bytes": "275258" }, { "name": "Java", "bytes": "14422749" }, { "name": "JavaScript", "bytes": "5194066" }, { "name": "Makefile", "bytes": "8076" }, { "name": "Python", "bytes": "36574" }, { "name": "Shell", "bytes": "51677" }, { "name": "Thrift", "bytes": "5028" } ], "symlink_target": "" }
import mock import unittest import jujuresources.cli from jujuresources import ALL from jujuresources.backend import ResourceContainer class TestCLI(unittest.TestCase): def setUp(self): self.resources = ResourceContainer('resources') self.resources.add_required('valid', { 'url': 'valid', 'filename': 'valid', 'destination': 'res-defaults.yaml', 'hash': '4f08575d804517cea2265a7d43022771', 'hash_type': 'md5', }) self.resources.add_required('invalid', { 'url': 'invalid', 'filename': 'invalid', 'destination': 'res-defaults.yaml', 'hash': 'deadbeef', 'hash_type': 'md5', }) self.resources.add_optional('opt-invalid', { 'url': 'opt-invalid', 'filename': 'opt-invalid', 'destination': 'res-defaults.yaml', 'hash': 'deadbeef', 'hash_type': 'md5', }) def mep(name, target): m = mock.Mock() m.name = name m.load.return_value = target return m self._piep = mock.patch.object(jujuresources.cli, 'iter_entry_points') self._miep = self._piep.start() self._miep.return_value = [ mep('fetch', jujuresources.cli.fetch), mep('verify', jujuresources.cli.verify), mep('install', jujuresources.cli.install), mep('resource_path', jujuresources.cli.resource_path), mep('resource_spec', jujuresources.cli.resource_spec), mep('serve', jujuresources.cli.serve), ] def tearDown(self): self._piep.stop() @mock.patch('argparse.ArgumentParser._print_message') def test_resources_help(self, mprint_help): jujuresources.cli.resources(['help', 'fetch']) self.assertRegexpMatches(mprint_help.call_args_list[0][0][0], '^usage: [^ ]+ fetch') @mock.patch('jujuresources.cli.print') def test_resources_desc(self, mprint): jujuresources.cli.resources(['--description']) self.assertEqual(mprint.call_args_list[0][0][0], 'Manage and mirror charm resources') @mock.patch('jujuresources.cli._exit') @mock.patch('jujuresources.cli.verify') @mock.patch('jujuresources.cli._fetch') @mock.patch('jujuresources.cli._load') def test_fetch(self, mload, mfetch, mverify, mexit): mload.return_value = self.resources mverify.return_value = -1 jujuresources.cli.resources(['fetch']) mload.assert_called_once_with('resources.yaml', None) mfetch.assert_called_once_with(self.resources, [], None, False, mock.ANY) self.assertIsNotNone(mfetch.call_args_list[0][0][4]) mexit.assert_called_once_with(-1) @mock.patch('jujuresources.cli._exit') @mock.patch('jujuresources.cli.verify') @mock.patch('jujuresources.cli._fetch') @mock.patch('jujuresources.cli._load') def test_fetch_opts(self, mload, mfetch, mverify, mexit): mload.return_value = self.resources mverify.return_value = 1 jujuresources.cli.resources(['fetch', '-r', 'r.y', '-d', 'od', '-u', 'url', '-a', '-q', '-f']) mload.assert_called_once_with('r.y', 'od') mfetch.assert_called_once_with(self.resources, ALL, 'url', True, None) mexit.assert_called_once_with(1) @mock.patch('jujuresources.cli._exit') @mock.patch('jujuresources.cli.verify') @mock.patch('jujuresources.cli._fetch') @mock.patch('jujuresources.cli._load') def test_fetch_names(self, mload, mfetch, mverify, mexit): mload.return_value = self.resources mverify.return_value = 2 jujuresources.cli.resources(['fetch', 'foo', 'bar']) self.assertItemsEqual(mfetch.call_args_list[0][0][1], ['foo', 'bar']) mexit.assert_called_once_with(2) @mock.patch('jujuresources.cli._exit') @mock.patch('jujuresources.cli.print') @mock.patch('jujuresources.cli._invalid') @mock.patch('jujuresources.cli._load') def test_verify(self, mload, minvalid, mprint, mexit): mload.return_value = self.resources minvalid.return_value = ['invalid'] jujuresources.cli.resources(['verify']) mload.assert_called_once_with('resources.yaml', None) minvalid.assert_called_once_with(self.resources, []) mprint.assert_called_once_with('Invalid or missing resources: invalid') mexit.assert_called_once_with(1) @mock.patch('jujuresources.cli._exit') @mock.patch('jujuresources.cli.print') @mock.patch('jujuresources.cli._invalid') @mock.patch('jujuresources.cli._load') def test_verify_opts(self, mload, minvalid, mprint, mexit): mload.return_value = self.resources minvalid.return_value = ['invalid', 'opt-invalid'] jujuresources.cli.resources(['verify', '-r', 'r.y', '-d', 'od', '-a', '-q']) mload.assert_called_once_with('r.y', 'od') minvalid.assert_called_once_with(self.resources, ALL) assert not mprint.called mexit.assert_called_once_with(1) @mock.patch('jujuresources.cli._exit') @mock.patch('jujuresources.cli.print') @mock.patch('jujuresources.cli._invalid') @mock.patch('jujuresources.cli._load') def test_verify_names(self, mload, minvalid, mprint, mexit): mload.return_value = self.resources minvalid.return_value = [] jujuresources.cli.resources(['verify', 'foo', 'bar']) minvalid.assert_called_once_with(self.resources, ['foo', 'bar']) mprint.assert_called_once_with('All resources successfully downloaded') mexit.assert_called_once_with(0) @mock.patch('jujuresources.cli._exit') @mock.patch('jujuresources.cli.print') @mock.patch('jujuresources.cli._load') def test_resource_path(self, mload, mprint, mexit): mload.return_value = self.resources jujuresources.cli.resources(['resource_path', 'valid']) mload.assert_called_once_with('resources.yaml', None) mprint.assert_called_once_with('res-defaults.yaml') mexit.assert_called_once_with(0) @mock.patch('jujuresources.cli._exit') @mock.patch('jujuresources.cli.sys') @mock.patch('jujuresources.cli._load') def test_resource_path_invalid_resource(self, mload, msys, mexit): mload.return_value = self.resources jujuresources.cli.resources(['resource_path', 'foo', '-d', 'od', '-r', 'r.y']) mload.assert_called_once_with('r.y', 'od') msys.stderr.write.assert_called_once_with('Invalid resource name: foo\n') mexit.assert_called_once_with(1) @mock.patch('jujuresources.cli._exit') @mock.patch('jujuresources.cli.print') @mock.patch('jujuresources.cli.HTTPServer') @mock.patch('jujuresources.cli.backend') @mock.patch('jujuresources.cli.os') @mock.patch('jujuresources.cli._load') def test_serve(self, mload, mos, mbackend, mHTTPServer, mprint, mexit): mload.return_value = self.resources mos.path.exists.return_value = True jujuresources.cli.resources(['serve', '-H', 'host', '-p', '9999']) mos.chdir.assert_called_once_with('resources') mbackend.PyPIResource.build_pypi_indexes.assert_called_with('resources') self.assertIs(mHTTPServer.allow_reuse_address, True) mHTTPServer.assert_called_once_with(('host', 9999), jujuresources.cli.SimpleHTTPRequestHandler) @mock.patch('jujuresources.cli._exit') @mock.patch('jujuresources.cli.print') @mock.patch('jujuresources.cli.HTTPServer') @mock.patch('jujuresources.cli.backend') @mock.patch('jujuresources.cli.os') @mock.patch('jujuresources.cli._load') def test_serve_dir(self, mload, mos, mbackend, mHTTPServer, mprint, mexit): mload.return_value = ResourceContainer('od') mos.path.exists.return_value = True jujuresources.cli.resources(['serve', '-d', 'od']) mload.assert_called_once_with('resources.yaml', 'od') mos.path.exists.assert_called_once_with('od') mbackend.PyPIResource.build_pypi_indexes.assert_called_with('od') mos.chdir.assert_called_once_with('od') self.assertIs(mHTTPServer.allow_reuse_address, True) mHTTPServer.assert_called_once_with(('', 8080), jujuresources.cli.SimpleHTTPRequestHandler) @mock.patch('jujuresources.cli._exit') @mock.patch('jujuresources.cli.sys') @mock.patch('jujuresources.cli.os') @mock.patch('jujuresources.cli._load') def test_serve_no_fetch(self, mload, mos, msys, mexit): mload.return_value = ResourceContainer('od') mos.path.exists.return_value = False jujuresources.cli.resources(['serve', '-d', 'od']) msys.stderr.write.assert_called_once_with("Resources dir 'od' not found. Did you fetch?\n") mexit.assert_called_once_with(1) @mock.patch('jujuresources.cli._exit') @mock.patch('jujuresources.cli.print') @mock.patch('jujuresources.cli._install') @mock.patch('jujuresources.cli._load') def test_install(self, mload, minstall, mprint, mexit): mload.return_value = self.resources minstall.return_value = True jujuresources.cli.resources(['install']) mload.assert_called_once_with('resources.yaml', None) minstall.assert_called_once_with(self.resources, [], None, None, False) mprint.assert_called_with('All resources successfully installed') mexit.assert_called_with(0) @mock.patch('jujuresources.cli._exit') @mock.patch('jujuresources.cli.print') @mock.patch('jujuresources.cli._invalid') @mock.patch('jujuresources.cli._install') @mock.patch('jujuresources.cli._load') def test_install_fail(self, mload, minstall, minvalid, mprint, mexit): mload.return_value = self.resources minstall.return_value = False minvalid.return_value = ['foo', 'bar'] jujuresources.cli.resources(['install']) mload.assert_called_once_with('resources.yaml', None) minstall.assert_called_once_with(self.resources, [], None, None, False) mprint.assert_called_with('Unable to install some resources: foo, bar') mexit.assert_called_with(1) @mock.patch('jujuresources.cli._exit') @mock.patch('jujuresources.cli.print') @mock.patch('jujuresources.cli._install') @mock.patch('jujuresources.cli._load') def test_install_opts(self, mload, minstall, mprint, mexit): mload.return_value = self.resources minstall.return_value = False jujuresources.cli.resources(['install', '-r', 'r.y', '-d', 'od', '-u', 'url', '-D', 'dst', '-s', '-q', '-a']) mload.assert_called_once_with('r.y', 'od') minstall.assert_called_once_with(self.resources, ALL, 'url', 'dst', True) assert not mprint.called mexit.assert_called_with(1) if __name__ == '__main__': unittest.main()
{ "content_hash": "b0d8d36933f76a5b015a99cae8600310", "timestamp": "", "source": "github", "line_count": 247, "max_line_length": 103, "avg_line_length": 44.75708502024292, "alnum_prop": 0.6331071913161466, "repo_name": "johnsca/jujuresources", "id": "3ae025bc2e54ecbe2534fa536413ca97431d04fe", "size": "11055", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/test_cli.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "1512" }, { "name": "Python", "bytes": "79856" }, { "name": "Shell", "bytes": "288" } ], "symlink_target": "" }
import * as utils from 'base/utils'; import globals from 'base/globals'; import Component from 'base/component'; /*! * VIZABI INDICATOR PICKER * Reusable indicator picker component */ var IndPicker = Component.extend({ /** * Initializes the Indicator Picker. * Executed once before any template is rendered. * @param config The options passed to the component * @param context The component's parent */ init: function(config, context) { this.name = 'gapminder-indicatorpicker'; this.template = '<span class="vzb-ip-select"></span>'; var _this = this; this.model_expects = [{ name: "marker", type: "model" }, { name: "language", type: "language" }]; this.markerID = config.markerID; if(!config.markerID) utils.warn("indicatorpicker.js complains on 'markerID' property: " + config.markerID); this.model_binds = { "change:language.strings": function(evt) { _this.updateView(); }, "change:marker": function(evt) { _this.updateView(); }, "ready": function(evt) { if(!_this._readyOnce) return; _this.updateView(); } }; //contructor is the same as any component this._super(config, context); }, ready: function() { this.updateView(); }, readyOnce: function() { var _this = this; this.el_select = d3.select(this.element); this.el_select.on("click", function() { _this.root.findChildByName("gapminder-treemenu") .markerID(_this.markerID) .alignX("left") .alignY("top") .updateView() .toggle(); }); }, updateView: function() { var _this = this; this.translator = this.model.language.getTFunction(); this.el_select.text(this.translator("indicator/" + this.model.marker[this.markerID].which)); } }); export default IndPicker;
{ "content_hash": "2077f8756a6f130cda9f32914493a987", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 115, "avg_line_length": 25.783132530120483, "alnum_prop": 0.5392523364485982, "repo_name": "jdk137/vizabi", "id": "9c2fdede7d1c8a5f7836ef70391412440161488b", "size": "2140", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/components/indicatorpicker/indicatorpicker.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "92877" }, { "name": "HTML", "bytes": "28973" }, { "name": "JavaScript", "bytes": "829285" }, { "name": "Shell", "bytes": "1503" } ], "symlink_target": "" }
""" WSGI config for warehouse project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "warehouse.settings.production") application = get_wsgi_application() try: from dj_static import Cling, MediaCling application = Cling(get_wsgi_application()) application = Cling(MediaCling(get_wsgi_application())) except: pass
{ "content_hash": "a8a4ffc1719c05c732254e0138be8718", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 80, "avg_line_length": 24.73913043478261, "alnum_prop": 0.7715289982425307, "repo_name": "z-Wind/warehouse", "id": "ceceb0b7782cb114a978a7e7f095deb884783764", "size": "569", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "warehouse/wsgi.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "46701" }, { "name": "HTML", "bytes": "46119" }, { "name": "JavaScript", "bytes": "149149" }, { "name": "Python", "bytes": "121983" } ], "symlink_target": "" }
package main import ( "bytes" "crypto/sha1" "errors" "fmt" "go/build" "go/scanner" "go/token" "io" "io/ioutil" "os" pathpkg "path" "path/filepath" "runtime" "sort" "strconv" "strings" "unicode" ) // A Package describes a single package found in a directory. type Package struct { // Note: These fields are part of the go command's public API. // See list.go. It is okay to add fields, but not to change or // remove existing ones. Keep in sync with list.go Dir string `json:",omitempty"` // directory containing package sources ImportPath string `json:",omitempty"` // import path of package in dir ImportComment string `json:",omitempty"` // path in import comment on package statement Name string `json:",omitempty"` // package name Doc string `json:",omitempty"` // package documentation string Target string `json:",omitempty"` // install path Shlib string `json:",omitempty"` // the shared library that contains this package (only set when -linkshared) Goroot bool `json:",omitempty"` // is this package found in the Go root? Standard bool `json:",omitempty"` // is this package part of the standard Go library? Stale bool `json:",omitempty"` // would 'go install' do anything for this package? StaleReason string `json:",omitempty"` // why is Stale true? Root string `json:",omitempty"` // Go root or Go path dir containing this package ConflictDir string `json:",omitempty"` // Dir is hidden by this other directory BinaryOnly bool `json:",omitempty"` // package cannot be recompiled // Source files GoFiles []string `json:",omitempty"` // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles) CgoFiles []string `json:",omitempty"` // .go sources files that import "C" IgnoredGoFiles []string `json:",omitempty"` // .go sources ignored due to build constraints CFiles []string `json:",omitempty"` // .c source files CXXFiles []string `json:",omitempty"` // .cc, .cpp and .cxx source files MFiles []string `json:",omitempty"` // .m source files HFiles []string `json:",omitempty"` // .h, .hh, .hpp and .hxx source files FFiles []string `json:",omitempty"` // .f, .F, .for and .f90 Fortran source files SFiles []string `json:",omitempty"` // .s source files SwigFiles []string `json:",omitempty"` // .swig files SwigCXXFiles []string `json:",omitempty"` // .swigcxx files SysoFiles []string `json:",omitempty"` // .syso system object files added to package // Cgo directives CgoCFLAGS []string `json:",omitempty"` // cgo: flags for C compiler CgoCPPFLAGS []string `json:",omitempty"` // cgo: flags for C preprocessor CgoCXXFLAGS []string `json:",omitempty"` // cgo: flags for C++ compiler CgoFFLAGS []string `json:",omitempty"` // cgo: flags for Fortran compiler CgoLDFLAGS []string `json:",omitempty"` // cgo: flags for linker CgoPkgConfig []string `json:",omitempty"` // cgo: pkg-config names // Dependency information Imports []string `json:",omitempty"` // import paths used by this package Deps []string `json:",omitempty"` // all (recursively) imported dependencies // Error information Incomplete bool `json:",omitempty"` // was there an error loading this package or dependencies? Error *PackageError `json:",omitempty"` // error loading this package (not dependencies) DepsErrors []*PackageError `json:",omitempty"` // errors loading dependencies // Test information TestGoFiles []string `json:",omitempty"` // _test.go files in package TestImports []string `json:",omitempty"` // imports from TestGoFiles XTestGoFiles []string `json:",omitempty"` // _test.go files outside package XTestImports []string `json:",omitempty"` // imports from XTestGoFiles // Unexported fields are not part of the public API. build *build.Package pkgdir string // overrides build.PkgDir imports []*Package deps []*Package gofiles []string // GoFiles+CgoFiles+TestGoFiles+XTestGoFiles files, absolute paths sfiles []string allgofiles []string // gofiles + IgnoredGoFiles, absolute paths target string // installed file for this package (may be executable) fake bool // synthesized package external bool // synthesized external test package forceLibrary bool // this package is a library (even if named "main") cmdline bool // defined by files listed on command line local bool // imported via local path (./ or ../) localPrefix string // interpret ./ and ../ imports relative to this prefix exeName string // desired name for temporary executable coverMode string // preprocess Go source files with the coverage tool in this mode coverVars map[string]*CoverVar // variables created by coverage analysis omitDWARF bool // tell linker not to write DWARF information buildID string // expected build ID for generated package gobinSubdir bool // install target would be subdir of GOBIN } // vendored returns the vendor-resolved version of imports, // which should be p.TestImports or p.XTestImports, NOT p.Imports. // The imports in p.TestImports and p.XTestImports are not recursively // loaded during the initial load of p, so they list the imports found in // the source file, but most processing should be over the vendor-resolved // import paths. We do this resolution lazily both to avoid file system work // and because the eventual real load of the test imports (during 'go test') // can produce better error messages if it starts with the original paths. // The initial load of p loads all the non-test imports and rewrites // the vendored paths, so nothing should ever call p.vendored(p.Imports). func (p *Package) vendored(imports []string) []string { if len(imports) > 0 && len(p.Imports) > 0 && &imports[0] == &p.Imports[0] { panic("internal error: p.vendored(p.Imports) called") } seen := make(map[string]bool) var all []string for _, path := range imports { path = vendoredImportPath(p, path) if !seen[path] { seen[path] = true all = append(all, path) } } sort.Strings(all) return all } // CoverVar holds the name of the generated coverage variables targeting the named file. type CoverVar struct { File string // local file name Var string // name of count struct } func (p *Package) copyBuild(pp *build.Package) { p.build = pp if pp.PkgTargetRoot != "" && buildPkgdir != "" { old := pp.PkgTargetRoot pp.PkgRoot = buildPkgdir pp.PkgTargetRoot = buildPkgdir pp.PkgObj = filepath.Join(buildPkgdir, strings.TrimPrefix(pp.PkgObj, old)) } p.Dir = pp.Dir p.ImportPath = pp.ImportPath p.ImportComment = pp.ImportComment p.Name = pp.Name p.Doc = pp.Doc p.Root = pp.Root p.ConflictDir = pp.ConflictDir p.BinaryOnly = pp.BinaryOnly // TODO? Target p.Goroot = pp.Goroot p.Standard = p.Goroot && p.ImportPath != "" && isStandardImportPath(p.ImportPath) p.GoFiles = pp.GoFiles p.CgoFiles = pp.CgoFiles p.IgnoredGoFiles = pp.IgnoredGoFiles p.CFiles = pp.CFiles p.CXXFiles = pp.CXXFiles p.MFiles = pp.MFiles p.HFiles = pp.HFiles p.FFiles = pp.FFiles p.SFiles = pp.SFiles p.SwigFiles = pp.SwigFiles p.SwigCXXFiles = pp.SwigCXXFiles p.SysoFiles = pp.SysoFiles p.CgoCFLAGS = pp.CgoCFLAGS p.CgoCPPFLAGS = pp.CgoCPPFLAGS p.CgoCXXFLAGS = pp.CgoCXXFLAGS p.CgoLDFLAGS = pp.CgoLDFLAGS p.CgoPkgConfig = pp.CgoPkgConfig p.Imports = pp.Imports p.TestGoFiles = pp.TestGoFiles p.TestImports = pp.TestImports p.XTestGoFiles = pp.XTestGoFiles p.XTestImports = pp.XTestImports } // isStandardImportPath reports whether $GOROOT/src/path should be considered // part of the standard distribution. For historical reasons we allow people to add // their own code to $GOROOT instead of using $GOPATH, but we assume that // code will start with a domain name (dot in the first element). func isStandardImportPath(path string) bool { i := strings.Index(path, "/") if i < 0 { i = len(path) } elem := path[:i] return !strings.Contains(elem, ".") } // A PackageError describes an error loading information about a package. type PackageError struct { ImportStack []string // shortest path from package named on command line to this one Pos string // position of error Err string // the error itself isImportCycle bool // the error is an import cycle hard bool // whether the error is soft or hard; soft errors are ignored in some places } func (p *PackageError) Error() string { // Import cycles deserve special treatment. if p.isImportCycle { return fmt.Sprintf("%s\npackage %s\n", p.Err, strings.Join(p.ImportStack, "\n\timports ")) } if p.Pos != "" { // Omit import stack. The full path to the file where the error // is the most important thing. return p.Pos + ": " + p.Err } if len(p.ImportStack) == 0 { return p.Err } return "package " + strings.Join(p.ImportStack, "\n\timports ") + ": " + p.Err } // An importStack is a stack of import paths. type importStack []string func (s *importStack) push(p string) { *s = append(*s, p) } func (s *importStack) pop() { *s = (*s)[0 : len(*s)-1] } func (s *importStack) copy() []string { return append([]string{}, *s...) } // shorterThan reports whether sp is shorter than t. // We use this to record the shortest import sequence // that leads to a particular package. func (sp *importStack) shorterThan(t []string) bool { s := *sp if len(s) != len(t) { return len(s) < len(t) } // If they are the same length, settle ties using string ordering. for i := range s { if s[i] != t[i] { return s[i] < t[i] } } return false // they are equal } // packageCache is a lookup cache for loadPackage, // so that if we look up a package multiple times // we return the same pointer each time. var packageCache = map[string]*Package{} // reloadPackage is like loadPackage but makes sure // not to use the package cache. func reloadPackage(arg string, stk *importStack) *Package { p := packageCache[arg] if p != nil { delete(packageCache, p.Dir) delete(packageCache, p.ImportPath) } return loadPackage(arg, stk) } // dirToImportPath returns the pseudo-import path we use for a package // outside the Go path. It begins with _/ and then contains the full path // to the directory. If the package lives in c:\home\gopher\my\pkg then // the pseudo-import path is _/c_/home/gopher/my/pkg. // Using a pseudo-import path like this makes the ./ imports no longer // a special case, so that all the code to deal with ordinary imports works // automatically. func dirToImportPath(dir string) string { return pathpkg.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir))) } func makeImportValid(r rune) rune { // Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport. const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD" if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) { return '_' } return r } // Mode flags for loadImport and download (in get.go). const ( // useVendor means that loadImport should do vendor expansion // (provided the vendoring experiment is enabled). // That is, useVendor means that the import path came from // a source file and has not been vendor-expanded yet. // Every import path should be loaded initially with useVendor, // and then the expanded version (with the /vendor/ in it) gets // recorded as the canonical import path. At that point, future loads // of that package must not pass useVendor, because // disallowVendor will reject direct use of paths containing /vendor/. useVendor = 1 << iota // getTestDeps is for download (part of "go get") and indicates // that test dependencies should be fetched too. getTestDeps ) // loadImport scans the directory named by path, which must be an import path, // but possibly a local import path (an absolute file system path or one beginning // with ./ or ../). A local relative path is interpreted relative to srcDir. // It returns a *Package describing the package found in that directory. func loadImport(path, srcDir string, parent *Package, stk *importStack, importPos []token.Position, mode int) *Package { stk.push(path) defer stk.pop() // Determine canonical identifier for this package. // For a local import the identifier is the pseudo-import path // we create from the full directory to the package. // Otherwise it is the usual import path. // For vendored imports, it is the expanded form. importPath := path origPath := path isLocal := build.IsLocalImport(path) if isLocal { importPath = dirToImportPath(filepath.Join(srcDir, path)) } else if mode&useVendor != 0 { // We do our own vendor resolution, because we want to // find out the key to use in packageCache without the // overhead of repeated calls to buildContext.Import. // The code is also needed in a few other places anyway. path = vendoredImportPath(parent, path) importPath = path } if p := packageCache[importPath]; p != nil { if perr := disallowInternal(srcDir, p, stk); perr != p { return perr } if mode&useVendor != 0 { if perr := disallowVendor(srcDir, origPath, p, stk); perr != p { return perr } } return reusePackage(p, stk) } p := new(Package) p.local = isLocal p.ImportPath = importPath packageCache[importPath] = p // Load package. // Import always returns bp != nil, even if an error occurs, // in order to return partial information. // // TODO: After Go 1, decide when to pass build.AllowBinary here. // See issue 3268 for mistakes to avoid. buildMode := build.ImportComment if mode&useVendor == 0 || path != origPath { // Not vendoring, or we already found the vendored path. buildMode |= build.IgnoreVendor } bp, err := buildContext.Import(path, srcDir, buildMode) bp.ImportPath = importPath if gobin != "" { bp.BinDir = gobin } if err == nil && !isLocal && bp.ImportComment != "" && bp.ImportComment != path && !strings.Contains(path, "/vendor/") && !strings.HasPrefix(path, "vendor/") { err = fmt.Errorf("code in directory %s expects import %q", bp.Dir, bp.ImportComment) } p.load(stk, bp, err) if p.Error != nil && p.Error.Pos == "" && len(importPos) > 0 { pos := importPos[0] pos.Filename = shortPath(pos.Filename) p.Error.Pos = pos.String() } if perr := disallowInternal(srcDir, p, stk); perr != p { return perr } if mode&useVendor != 0 { if perr := disallowVendor(srcDir, origPath, p, stk); perr != p { return perr } } return p } var isDirCache = map[string]bool{} func isDir(path string) bool { result, ok := isDirCache[path] if ok { return result } fi, err := os.Stat(path) result = err == nil && fi.IsDir() isDirCache[path] = result return result } // vendoredImportPath returns the expansion of path when it appears in parent. // If parent is x/y/z, then path might expand to x/y/z/vendor/path, x/y/vendor/path, // x/vendor/path, vendor/path, or else stay path if none of those exist. // vendoredImportPath returns the expanded path or, if no expansion is found, the original. func vendoredImportPath(parent *Package, path string) (found string) { if parent == nil || parent.Root == "" { return path } dir := filepath.Clean(parent.Dir) root := filepath.Join(parent.Root, "src") if !hasFilePathPrefix(dir, root) { // Look for symlinks before reporting error. dir = expandPath(dir) root = expandPath(root) } if !hasFilePathPrefix(dir, root) || len(dir) <= len(root) || dir[len(root)] != filepath.Separator { fatalf("invalid vendoredImportPath: dir=%q root=%q separator=%q", dir, root, string(filepath.Separator)) } vpath := "vendor/" + path for i := len(dir); i >= len(root); i-- { if i < len(dir) && dir[i] != filepath.Separator { continue } // Note: checking for the vendor directory before checking // for the vendor/path directory helps us hit the // isDir cache more often. It also helps us prepare a more useful // list of places we looked, to report when an import is not found. if !isDir(filepath.Join(dir[:i], "vendor")) { continue } targ := filepath.Join(dir[:i], vpath) if isDir(targ) && hasGoFiles(targ) { importPath := parent.ImportPath if importPath == "command-line-arguments" { // If parent.ImportPath is 'command-line-arguments'. // set to relative directory to root (also chopped root directory) importPath = dir[len(root)+1:] } // We started with parent's dir c:\gopath\src\foo\bar\baz\quux\xyzzy. // We know the import path for parent's dir. // We chopped off some number of path elements and // added vendor\path to produce c:\gopath\src\foo\bar\baz\vendor\path. // Now we want to know the import path for that directory. // Construct it by chopping the same number of path elements // (actually the same number of bytes) from parent's import path // and then append /vendor/path. chopped := len(dir) - i if chopped == len(importPath)+1 { // We walked up from c:\gopath\src\foo\bar // and found c:\gopath\src\vendor\path. // We chopped \foo\bar (length 8) but the import path is "foo/bar" (length 7). // Use "vendor/path" without any prefix. return vpath } return importPath[:len(importPath)-chopped] + "/" + vpath } } return path } // hasGoFiles reports whether dir contains any files with names ending in .go. // For a vendor check we must exclude directories that contain no .go files. // Otherwise it is not possible to vendor just a/b/c and still import the // non-vendored a/b. See golang.org/issue/13832. func hasGoFiles(dir string) bool { fis, _ := ioutil.ReadDir(dir) for _, fi := range fis { if !fi.IsDir() && strings.HasSuffix(fi.Name(), ".go") { return true } } return false } // reusePackage reuses package p to satisfy the import at the top // of the import stack stk. If this use causes an import loop, // reusePackage updates p's error information to record the loop. func reusePackage(p *Package, stk *importStack) *Package { // We use p.imports==nil to detect a package that // is in the midst of its own loadPackage call // (all the recursion below happens before p.imports gets set). if p.imports == nil { if p.Error == nil { p.Error = &PackageError{ ImportStack: stk.copy(), Err: "import cycle not allowed", isImportCycle: true, } } p.Incomplete = true } // Don't rewrite the import stack in the error if we have an import cycle. // If we do, we'll lose the path that describes the cycle. if p.Error != nil && !p.Error.isImportCycle && stk.shorterThan(p.Error.ImportStack) { p.Error.ImportStack = stk.copy() } return p } // disallowInternal checks that srcDir is allowed to import p. // If the import is allowed, disallowInternal returns the original package p. // If not, it returns a new package containing just an appropriate error. func disallowInternal(srcDir string, p *Package, stk *importStack) *Package { // golang.org/s/go14internal: // An import of a path containing the element “internal” // is disallowed if the importing code is outside the tree // rooted at the parent of the “internal” directory. // There was an error loading the package; stop here. if p.Error != nil { return p } // The stack includes p.ImportPath. // If that's the only thing on the stack, we started // with a name given on the command line, not an // import. Anything listed on the command line is fine. if len(*stk) == 1 { return p } // Check for "internal" element: three cases depending on begin of string and/or end of string. i, ok := findInternal(p.ImportPath) if !ok { return p } // Internal is present. // Map import path back to directory corresponding to parent of internal. if i > 0 { i-- // rewind over slash in ".../internal" } parent := p.Dir[:i+len(p.Dir)-len(p.ImportPath)] if hasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) { return p } // Look for symlinks before reporting error. srcDir = expandPath(srcDir) parent = expandPath(parent) if hasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) { return p } // Internal is present, and srcDir is outside parent's tree. Not allowed. perr := *p perr.Error = &PackageError{ ImportStack: stk.copy(), Err: "use of internal package not allowed", } perr.Incomplete = true return &perr } // findInternal looks for the final "internal" path element in the given import path. // If there isn't one, findInternal returns ok=false. // Otherwise, findInternal returns ok=true and the index of the "internal". func findInternal(path string) (index int, ok bool) { // Three cases, depending on internal at start/end of string or not. // The order matters: we must return the index of the final element, // because the final one produces the most restrictive requirement // on the importer. switch { case strings.HasSuffix(path, "/internal"): return len(path) - len("internal"), true case strings.Contains(path, "/internal/"): return strings.LastIndex(path, "/internal/") + 1, true case path == "internal", strings.HasPrefix(path, "internal/"): return 0, true } return 0, false } // disallowVendor checks that srcDir is allowed to import p as path. // If the import is allowed, disallowVendor returns the original package p. // If not, it returns a new package containing just an appropriate error. func disallowVendor(srcDir, path string, p *Package, stk *importStack) *Package { // The stack includes p.ImportPath. // If that's the only thing on the stack, we started // with a name given on the command line, not an // import. Anything listed on the command line is fine. if len(*stk) == 1 { return p } if perr := disallowVendorVisibility(srcDir, p, stk); perr != p { return perr } // Paths like x/vendor/y must be imported as y, never as x/vendor/y. if i, ok := findVendor(path); ok { perr := *p perr.Error = &PackageError{ ImportStack: stk.copy(), Err: "must be imported as " + path[i+len("vendor/"):], } perr.Incomplete = true return &perr } return p } // disallowVendorVisibility checks that srcDir is allowed to import p. // The rules are the same as for /internal/ except that a path ending in /vendor // is not subject to the rules, only subdirectories of vendor. // This allows people to have packages and commands named vendor, // for maximal compatibility with existing source trees. func disallowVendorVisibility(srcDir string, p *Package, stk *importStack) *Package { // The stack includes p.ImportPath. // If that's the only thing on the stack, we started // with a name given on the command line, not an // import. Anything listed on the command line is fine. if len(*stk) == 1 { return p } // Check for "vendor" element. i, ok := findVendor(p.ImportPath) if !ok { return p } // Vendor is present. // Map import path back to directory corresponding to parent of vendor. if i > 0 { i-- // rewind over slash in ".../vendor" } truncateTo := i + len(p.Dir) - len(p.ImportPath) if truncateTo < 0 || len(p.Dir) < truncateTo { return p } parent := p.Dir[:truncateTo] if hasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) { return p } // Look for symlinks before reporting error. srcDir = expandPath(srcDir) parent = expandPath(parent) if hasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) { return p } // Vendor is present, and srcDir is outside parent's tree. Not allowed. perr := *p perr.Error = &PackageError{ ImportStack: stk.copy(), Err: "use of vendored package not allowed", } perr.Incomplete = true return &perr } // findVendor looks for the last non-terminating "vendor" path element in the given import path. // If there isn't one, findVendor returns ok=false. // Otherwise, findVendor returns ok=true and the index of the "vendor". // // Note that terminating "vendor" elements don't count: "x/vendor" is its own package, // not the vendored copy of an import "" (the empty import path). // This will allow people to have packages or commands named vendor. // This may help reduce breakage, or it may just be confusing. We'll see. func findVendor(path string) (index int, ok bool) { // Two cases, depending on internal at start of string or not. // The order matters: we must return the index of the final element, // because the final one is where the effective import path starts. switch { case strings.Contains(path, "/vendor/"): return strings.LastIndex(path, "/vendor/") + 1, true case strings.HasPrefix(path, "vendor/"): return 0, true } return 0, false } type targetDir int const ( toRoot targetDir = iota // to bin dir inside package root (default) toTool // GOROOT/pkg/tool stalePath // the old import path; fail to build ) // goTools is a map of Go program import path to install target directory. var goTools = map[string]targetDir{ "cmd/addr2line": toTool, "cmd/api": toTool, "cmd/asm": toTool, "cmd/compile": toTool, "cmd/cgo": toTool, "cmd/cover": toTool, "cmd/dist": toTool, "cmd/doc": toTool, "cmd/fix": toTool, "cmd/link": toTool, "cmd/newlink": toTool, "cmd/nm": toTool, "cmd/objdump": toTool, "cmd/pack": toTool, "cmd/pprof": toTool, "cmd/trace": toTool, "cmd/vet": toTool, "code.google.com/p/go.tools/cmd/cover": stalePath, "code.google.com/p/go.tools/cmd/godoc": stalePath, "code.google.com/p/go.tools/cmd/vet": stalePath, } // expandScanner expands a scanner.List error into all the errors in the list. // The default Error method only shows the first error. func expandScanner(err error) error { // Look for parser errors. if err, ok := err.(scanner.ErrorList); ok { // Prepare error with \n before each message. // When printed in something like context: %v // this will put the leading file positions each on // its own line. It will also show all the errors // instead of just the first, as err.Error does. var buf bytes.Buffer for _, e := range err { e.Pos.Filename = shortPath(e.Pos.Filename) buf.WriteString("\n") buf.WriteString(e.Error()) } return errors.New(buf.String()) } return err } var raceExclude = map[string]bool{ "runtime/race": true, "runtime/msan": true, "runtime/cgo": true, "cmd/cgo": true, "syscall": true, "errors": true, } var cgoExclude = map[string]bool{ "runtime/cgo": true, } var cgoSyscallExclude = map[string]bool{ "runtime/cgo": true, "runtime/race": true, "runtime/msan": true, } // load populates p using information from bp, err, which should // be the result of calling build.Context.Import. func (p *Package) load(stk *importStack, bp *build.Package, err error) *Package { p.copyBuild(bp) // The localPrefix is the path we interpret ./ imports relative to. // Synthesized main packages sometimes override this. p.localPrefix = dirToImportPath(p.Dir) if err != nil { p.Incomplete = true err = expandScanner(err) p.Error = &PackageError{ ImportStack: stk.copy(), Err: err.Error(), } return p } useBindir := p.Name == "main" if !p.Standard { switch buildBuildmode { case "c-archive", "c-shared", "plugin": useBindir = false } } if useBindir { // Report an error when the old code.google.com/p/go.tools paths are used. if goTools[p.ImportPath] == stalePath { newPath := strings.Replace(p.ImportPath, "code.google.com/p/go.", "golang.org/x/", 1) e := fmt.Sprintf("the %v command has moved; use %v instead.", p.ImportPath, newPath) p.Error = &PackageError{Err: e} return p } _, elem := filepath.Split(p.Dir) full := buildContext.GOOS + "_" + buildContext.GOARCH + "/" + elem if buildContext.GOOS != toolGOOS || buildContext.GOARCH != toolGOARCH { // Install cross-compiled binaries to subdirectories of bin. elem = full } if p.build.BinDir != "" { // Install to GOBIN or bin of GOPATH entry. p.target = filepath.Join(p.build.BinDir, elem) if !p.Goroot && strings.Contains(elem, "/") && gobin != "" { // Do not create $GOBIN/goos_goarch/elem. p.target = "" p.gobinSubdir = true } } if goTools[p.ImportPath] == toTool { // This is for 'go tool'. // Override all the usual logic and force it into the tool directory. p.target = filepath.Join(gorootPkg, "tool", full) } if p.target != "" && buildContext.GOOS == "windows" { p.target += ".exe" } } else if p.local { // Local import turned into absolute path. // No permanent install target. p.target = "" } else { p.target = p.build.PkgObj if buildLinkshared { shlibnamefile := p.target[:len(p.target)-2] + ".shlibname" shlib, err := ioutil.ReadFile(shlibnamefile) if err == nil { libname := strings.TrimSpace(string(shlib)) if buildContext.Compiler == "gccgo" { p.Shlib = filepath.Join(p.build.PkgTargetRoot, "shlibs", libname) } else { p.Shlib = filepath.Join(p.build.PkgTargetRoot, libname) } } else if !os.IsNotExist(err) { fatalf("unexpected error reading %s: %v", shlibnamefile, err) } } } importPaths := p.Imports // Packages that use cgo import runtime/cgo implicitly. // Packages that use cgo also import syscall implicitly, // to wrap errno. // Exclude certain packages to avoid circular dependencies. if len(p.CgoFiles) > 0 && (!p.Standard || !cgoExclude[p.ImportPath]) { importPaths = append(importPaths, "runtime/cgo") } if len(p.CgoFiles) > 0 && (!p.Standard || !cgoSyscallExclude[p.ImportPath]) { importPaths = append(importPaths, "syscall") } // Currently build modes c-shared, pie, plugin, and -linkshared force // external linking mode, and external linking mode forces an // import of runtime/cgo. pieCgo := buildBuildmode == "pie" && (buildContext.GOOS != "linux" || buildContext.GOARCH != "amd64") if p.Name == "main" && !p.Goroot && (buildBuildmode == "c-shared" || buildBuildmode == "plugin" || pieCgo || buildLinkshared) { importPaths = append(importPaths, "runtime/cgo") } // Everything depends on runtime, except runtime, its internal // subpackages, and unsafe. if !p.Standard || (p.ImportPath != "runtime" && !strings.HasPrefix(p.ImportPath, "runtime/internal/") && p.ImportPath != "unsafe") { importPaths = append(importPaths, "runtime") // When race detection enabled everything depends on runtime/race. // Exclude certain packages to avoid circular dependencies. if buildRace && (!p.Standard || !raceExclude[p.ImportPath]) { importPaths = append(importPaths, "runtime/race") } // MSan uses runtime/msan. if buildMSan && (!p.Standard || !raceExclude[p.ImportPath]) { importPaths = append(importPaths, "runtime/msan") } // On ARM with GOARM=5, everything depends on math for the link. if p.Name == "main" && goarch == "arm" { importPaths = append(importPaths, "math") } } // Runtime and its internal packages depend on runtime/internal/sys, // so that they pick up the generated zversion.go file. // This can be an issue particularly for runtime/internal/atomic; // see issue 13655. if p.Standard && (p.ImportPath == "runtime" || strings.HasPrefix(p.ImportPath, "runtime/internal/")) && p.ImportPath != "runtime/internal/sys" { importPaths = append(importPaths, "runtime/internal/sys") } // Build list of full paths to all Go files in the package, // for use by commands like go fmt. p.gofiles = stringList(p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles) for i := range p.gofiles { p.gofiles[i] = filepath.Join(p.Dir, p.gofiles[i]) } sort.Strings(p.gofiles) p.sfiles = stringList(p.SFiles) for i := range p.sfiles { p.sfiles[i] = filepath.Join(p.Dir, p.sfiles[i]) } sort.Strings(p.sfiles) p.allgofiles = stringList(p.IgnoredGoFiles) for i := range p.allgofiles { p.allgofiles[i] = filepath.Join(p.Dir, p.allgofiles[i]) } p.allgofiles = append(p.allgofiles, p.gofiles...) sort.Strings(p.allgofiles) // Check for case-insensitive collision of input files. // To avoid problems on case-insensitive files, we reject any package // where two different input files have equal names under a case-insensitive // comparison. f1, f2 := foldDup(stringList( p.GoFiles, p.CgoFiles, p.IgnoredGoFiles, p.CFiles, p.CXXFiles, p.MFiles, p.HFiles, p.FFiles, p.SFiles, p.SysoFiles, p.SwigFiles, p.SwigCXXFiles, p.TestGoFiles, p.XTestGoFiles, )) if f1 != "" { p.Error = &PackageError{ ImportStack: stk.copy(), Err: fmt.Sprintf("case-insensitive file name collision: %q and %q", f1, f2), } return p } // Build list of imported packages and full dependency list. imports := make([]*Package, 0, len(p.Imports)) deps := make(map[string]*Package) for i, path := range importPaths { if path == "C" { continue } p1 := loadImport(path, p.Dir, p, stk, p.build.ImportPos[path], useVendor) if p1.Name == "main" { p.Error = &PackageError{ ImportStack: stk.copy(), Err: fmt.Sprintf("import %q is a program, not an importable package", path), } pos := p.build.ImportPos[path] if len(pos) > 0 { p.Error.Pos = pos[0].String() } } if p1.local { if !p.local && p.Error == nil { p.Error = &PackageError{ ImportStack: stk.copy(), Err: fmt.Sprintf("local import %q in non-local package", path), } pos := p.build.ImportPos[path] if len(pos) > 0 { p.Error.Pos = pos[0].String() } } } if p.Standard && p.Error == nil && !p1.Standard && p1.Error == nil { p.Error = &PackageError{ ImportStack: stk.copy(), Err: fmt.Sprintf("non-standard import %q in standard package %q", path, p.ImportPath), } pos := p.build.ImportPos[path] if len(pos) > 0 { p.Error.Pos = pos[0].String() } } path = p1.ImportPath importPaths[i] = path if i < len(p.Imports) { p.Imports[i] = path } deps[path] = p1 imports = append(imports, p1) for _, dep := range p1.deps { // The same import path could produce an error or not, // depending on what tries to import it. // Prefer to record entries with errors, so we can report them. if deps[dep.ImportPath] == nil || dep.Error != nil { deps[dep.ImportPath] = dep } } if p1.Incomplete { p.Incomplete = true } } p.imports = imports p.Deps = make([]string, 0, len(deps)) for dep := range deps { p.Deps = append(p.Deps, dep) } sort.Strings(p.Deps) for _, dep := range p.Deps { p1 := deps[dep] if p1 == nil { panic("impossible: missing entry in package cache for " + dep + " imported by " + p.ImportPath) } p.deps = append(p.deps, p1) if p1.Error != nil { p.DepsErrors = append(p.DepsErrors, p1.Error) } } // unsafe is a fake package. if p.Standard && (p.ImportPath == "unsafe" || buildContext.Compiler == "gccgo") { p.target = "" } p.Target = p.target // If cgo is not enabled, ignore cgo supporting sources // just as we ignore go files containing import "C". if !buildContext.CgoEnabled { p.CFiles = nil p.CXXFiles = nil p.MFiles = nil p.SwigFiles = nil p.SwigCXXFiles = nil // Note that SFiles are okay (they go to the Go assembler) // and HFiles are okay (they might be used by the SFiles). // Also Sysofiles are okay (they might not contain object // code; see issue #16050). } // The gc toolchain only permits C source files with cgo. if len(p.CFiles) > 0 && !p.usesCgo() && !p.usesSwig() && buildContext.Compiler == "gc" { p.Error = &PackageError{ ImportStack: stk.copy(), Err: fmt.Sprintf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")), } return p } // In the absence of errors lower in the dependency tree, // check for case-insensitive collisions of import paths. if len(p.DepsErrors) == 0 { dep1, dep2 := foldDup(p.Deps) if dep1 != "" { p.Error = &PackageError{ ImportStack: stk.copy(), Err: fmt.Sprintf("case-insensitive import collision: %q and %q", dep1, dep2), } return p } } if p.BinaryOnly { // For binary-only package, use build ID from supplied package binary. buildID, err := readBuildID(p) if err == nil { p.buildID = buildID } } else { computeBuildID(p) } return p } // usesSwig reports whether the package needs to run SWIG. func (p *Package) usesSwig() bool { return len(p.SwigFiles) > 0 || len(p.SwigCXXFiles) > 0 } // usesCgo reports whether the package needs to run cgo func (p *Package) usesCgo() bool { return len(p.CgoFiles) > 0 } // packageList returns the list of packages in the dag rooted at roots // as visited in a depth-first post-order traversal. func packageList(roots []*Package) []*Package { seen := map[*Package]bool{} all := []*Package{} var walk func(*Package) walk = func(p *Package) { if seen[p] { return } seen[p] = true for _, p1 := range p.imports { walk(p1) } all = append(all, p) } for _, root := range roots { walk(root) } return all } // computeStale computes the Stale flag in the package dag that starts // at the named pkgs (command-line arguments). func computeStale(pkgs ...*Package) { for _, p := range packageList(pkgs) { p.Stale, p.StaleReason = isStale(p) } } // The runtime version string takes one of two forms: // "go1.X[.Y]" for Go releases, and "devel +hash" at tip. // Determine whether we are in a released copy by // inspecting the version. var isGoRelease = strings.HasPrefix(runtime.Version(), "go1") // isStale and computeBuildID // // Theory of Operation // // There is an installed copy of the package (or binary). // Can we reuse the installed copy, or do we need to build a new one? // // We can use the installed copy if it matches what we'd get // by building a new one. The hard part is predicting that without // actually running a build. // // To start, we must know the set of inputs to the build process that can // affect the generated output. At a minimum, that includes the source // files for the package and also any compiled packages imported by those // source files. The *Package has these, and we use them. One might also // argue for including in the input set: the build tags, whether the race // detector is in use, the target operating system and architecture, the // compiler and linker binaries being used, the additional flags being // passed to those, the cgo binary being used, the additional flags cgo // passes to the host C compiler, the host C compiler being used, the set // of host C include files and installed C libraries, and so on. // We include some but not all of this information. // // Once we have decided on a set of inputs, we must next decide how to // tell whether the content of that set has changed since the last build // of p. If there have been no changes, then we assume a new build would // produce the same result and reuse the installed package or binary. // But if there have been changes, then we assume a new build might not // produce the same result, so we rebuild. // // There are two common ways to decide whether the content of the set has // changed: modification times and content hashes. We use a mixture of both. // // The use of modification times (mtimes) was pioneered by make: // assuming that a file's mtime is an accurate record of when that file was last written, // and assuming that the modification time of an installed package or // binary is the time that it was built, if the mtimes of the inputs // predate the mtime of the installed object, then the build of that // object saw those versions of the files, and therefore a rebuild using // those same versions would produce the same object. In contrast, if any // mtime of an input is newer than the mtime of the installed object, a // change has occurred since the build, and the build should be redone. // // Modification times are attractive because the logic is easy to // understand and the file system maintains the mtimes automatically // (less work for us). Unfortunately, there are a variety of ways in // which the mtime approach fails to detect a change and reuses a stale // object file incorrectly. (Making the opposite mistake, rebuilding // unnecessarily, is only a performance problem and not a correctness // problem, so we ignore that one.) // // As a warmup, one problem is that to be perfectly precise, we need to // compare the input mtimes against the time at the beginning of the // build, but the object file time is the time at the end of the build. // If an input file changes after being read but before the object is // written, the next build will see an object newer than the input and // will incorrectly decide that the object is up to date. We make no // attempt to detect or solve this problem. // // Another problem is that due to file system imprecision, an input and // output that are actually ordered in time have the same mtime. // This typically happens on file systems with 1-second (or, worse, // 2-second) mtime granularity and with automated scripts that write an // input and then immediately run a build, or vice versa. If an input and // an output have the same mtime, the conservative behavior is to treat // the output as out-of-date and rebuild. This can cause one or more // spurious rebuilds, but only for 1 second, until the object finally has // an mtime later than the input. // // Another problem is that binary distributions often set the mtime on // all files to the same time. If the distribution includes both inputs // and cached build outputs, the conservative solution to the previous // problem will cause unnecessary rebuilds. Worse, in such a binary // distribution, those rebuilds might not even have permission to update // the cached build output. To avoid these write errors, if an input and // output have the same mtime, we assume the output is up-to-date. // This is the opposite of what the previous problem would have us do, // but binary distributions are more common than instances of the // previous problem. // // A variant of the last problem is that some binary distributions do not // set the mtime on all files to the same time. Instead they let the file // system record mtimes as the distribution is unpacked. If the outputs // are unpacked before the inputs, they'll be older and a build will try // to rebuild them. That rebuild might hit the same write errors as in // the last scenario. We don't make any attempt to solve this, and we // haven't had many reports of it. Perhaps the only time this happens is // when people manually unpack the distribution, and most of the time // that's done as the same user who will be using it, so an initial // rebuild on first use succeeds quietly. // // More generally, people and programs change mtimes on files. The last // few problems were specific examples of this, but it's a general problem. // For example, instead of a binary distribution, copying a home // directory from one directory or machine to another might copy files // but not preserve mtimes. If the inputs are new than the outputs on the // first machine but copied first, they end up older than the outputs on // the second machine. // // Because many other build systems have the same sensitivity to mtimes, // most programs manipulating source code take pains not to break the // mtime assumptions. For example, Git does not set the mtime of files // during a checkout operation, even when checking out an old version of // the code. This decision was made specifically to work well with // mtime-based build systems. // // The killer problem, though, for mtime-based build systems is that the // build only has access to the mtimes of the inputs that still exist. // If it is possible to remove an input without changing any other inputs, // a later build will think the object is up-to-date when it is not. // This happens for Go because a package is made up of all source // files in a directory. If a source file is removed, there is no newer // mtime available recording that fact. The mtime on the directory could // be used, but it also changes when unrelated files are added to or // removed from the directory, so including the directory mtime would // cause unnecessary rebuilds, possibly many. It would also exacerbate // the problems mentioned earlier, since even programs that are careful // to maintain mtimes on files rarely maintain mtimes on directories. // // A variant of the last problem is when the inputs change for other // reasons. For example, Go 1.4 and Go 1.5 both install $GOPATH/src/mypkg // into the same target, $GOPATH/pkg/$GOOS_$GOARCH/mypkg.a. // If Go 1.4 has built mypkg into mypkg.a, a build using Go 1.5 must // rebuild mypkg.a, but from mtimes alone mypkg.a looks up-to-date. // If Go 1.5 has just been installed, perhaps the compiler will have a // newer mtime; since the compiler is considered an input, that would // trigger a rebuild. But only once, and only the last Go 1.4 build of // mypkg.a happened before Go 1.5 was installed. If a user has the two // versions installed in different locations and flips back and forth, // mtimes alone cannot tell what to do. Changing the toolchain is // changing the set of inputs, without affecting any mtimes. // // To detect the set of inputs changing, we turn away from mtimes and to // an explicit data comparison. Specifically, we build a list of the // inputs to the build, compute its SHA1 hash, and record that as the // ``build ID'' in the generated object. At the next build, we can // recompute the build ID and compare it to the one in the generated // object. If they differ, the list of inputs has changed, so the object // is out of date and must be rebuilt. // // Because this build ID is computed before the build begins, the // comparison does not have the race that mtime comparison does. // // Making the build sensitive to changes in other state is // straightforward: include the state in the build ID hash, and if it // changes, so does the build ID, triggering a rebuild. // // To detect changes in toolchain, we include the toolchain version in // the build ID hash for package runtime, and then we include the build // IDs of all imported packages in the build ID for p. // // It is natural to think about including build tags in the build ID, but // the naive approach of just dumping the tags into the hash would cause // spurious rebuilds. For example, 'go install' and 'go install -tags neverusedtag' // produce the same binaries (assuming neverusedtag is never used). // A more precise approach would be to include only tags that have an // effect on the build. But the effect of a tag on the build is to // include or exclude a file from the compilation, and that file list is // already in the build ID hash. So the build ID is already tag-sensitive // in a perfectly precise way. So we do NOT explicitly add build tags to // the build ID hash. // // We do not include as part of the build ID the operating system, // architecture, or whether the race detector is enabled, even though all // three have an effect on the output, because that information is used // to decide the install location. Binaries for linux and binaries for // darwin are written to different directory trees; including that // information in the build ID is unnecessary (although it would be // harmless). // // TODO(rsc): Investigate the cost of putting source file content into // the build ID hash as a replacement for the use of mtimes. Using the // file content would avoid all the mtime problems, but it does require // reading all the source files, something we avoid today (we read the // beginning to find the build tags and the imports, but we stop as soon // as we see the import block is over). If the package is stale, the compiler // is going to read the files anyway. But if the package is up-to-date, the // read is overhead. // // TODO(rsc): Investigate the complexity of making the build more // precise about when individual results are needed. To be fully precise, // there are two results of a compilation: the entire .a file used by the link // and the subpiece used by later compilations (__.PKGDEF only). // If a rebuild is needed but produces the previous __.PKGDEF, then // no more recompilation due to the rebuilt package is needed, only // relinking. To date, there is nothing in the Go command to express this. // // Special Cases // // When the go command makes the wrong build decision and does not // rebuild something it should, users fall back to adding the -a flag. // Any common use of the -a flag should be considered prima facie evidence // that isStale is returning an incorrect false result in some important case. // Bugs reported in the behavior of -a itself should prompt the question // ``Why is -a being used at all? What bug does that indicate?'' // // There is a long history of changes to isStale to try to make -a into a // suitable workaround for bugs in the mtime-based decisions. // It is worth recording that history to inform (and, as much as possible, deter) future changes. // // (1) Before the build IDs were introduced, building with alternate tags // would happily reuse installed objects built without those tags. // For example, "go build -tags netgo myprog.go" would use the installed // copy of package net, even if that copy had been built without netgo. // (The netgo tag controls whether package net uses cgo or pure Go for // functionality such as name resolution.) // Using the installed non-netgo package defeats the purpose. // // Users worked around this with "go build -tags netgo -a myprog.go". // // Build IDs have made that workaround unnecessary: // "go build -tags netgo myprog.go" // cannot use a non-netgo copy of package net. // // (2) Before the build IDs were introduced, building with different toolchains, // especially changing between toolchains, tried to reuse objects stored in // $GOPATH/pkg, resulting in link-time errors about object file mismatches. // // Users worked around this with "go install -a ./...". // // Build IDs have made that workaround unnecessary: // "go install ./..." will rebuild any objects it finds that were built against // a different toolchain. // // (3) The common use of "go install -a ./..." led to reports of problems // when the -a forced the rebuild of the standard library, which for some // users was not writable. Because we didn't understand that the real // problem was the bug -a was working around, we changed -a not to // apply to the standard library. // // (4) The common use of "go build -tags netgo -a myprog.go" broke // when we changed -a not to apply to the standard library, because // if go build doesn't rebuild package net, it uses the non-netgo version. // // Users worked around this with "go build -tags netgo -installsuffix barf myprog.go". // The -installsuffix here is making the go command look for packages // in pkg/$GOOS_$GOARCH_barf instead of pkg/$GOOS_$GOARCH. // Since the former presumably doesn't exist, go build decides to rebuild // everything, including the standard library. Since go build doesn't // install anything it builds, nothing is ever written to pkg/$GOOS_$GOARCH_barf, // so repeated invocations continue to work. // // If the use of -a wasn't a red flag, the use of -installsuffix to point to // a non-existent directory in a command that installs nothing should // have been. // // (5) Now that (1) and (2) no longer need -a, we have removed the kludge // introduced in (3): once again, -a means ``rebuild everything,'' not // ``rebuild everything except the standard library.'' Only Go 1.4 had // the restricted meaning. // // In addition to these cases trying to trigger rebuilds, there are // special cases trying NOT to trigger rebuilds. The main one is that for // a variety of reasons (see above), the install process for a Go release // cannot be relied upon to set the mtimes such that the go command will // think the standard library is up to date. So the mtime evidence is // ignored for the standard library if we find ourselves in a release // version of Go. Build ID-based staleness checks still apply to the // standard library, even in release versions. This makes // 'go build -tags netgo' work, among other things. // isStale reports whether package p needs to be rebuilt, // along with the reason why. func isStale(p *Package) (bool, string) { if p.Standard && (p.ImportPath == "unsafe" || buildContext.Compiler == "gccgo") { // fake, builtin package return false, "builtin package" } if p.Error != nil { return true, "errors loading package" } if p.Stale { return true, p.StaleReason } // If this is a package with no source code, it cannot be rebuilt. // If the binary is missing, we mark the package stale so that // if a rebuild is needed, that rebuild attempt will produce a useful error. // (Some commands, such as 'go list', do not attempt to rebuild.) if p.BinaryOnly { if p.target == "" { // Fail if a build is attempted. return true, "no source code for package, but no install target" } if _, err := os.Stat(p.target); err != nil { // Fail if a build is attempted. return true, "no source code for package, but cannot access install target: " + err.Error() } return false, "no source code for package" } // If the -a flag is given, rebuild everything. if buildA { return true, "build -a flag in use" } // If there's no install target, we have to rebuild. if p.target == "" { return true, "no install target" } // Package is stale if completely unbuilt. fi, err := os.Stat(p.target) if err != nil { return true, "cannot stat install target" } // Package is stale if the expected build ID differs from the // recorded build ID. This catches changes like a source file // being removed from a package directory. See issue 3895. // It also catches changes in build tags that affect the set of // files being compiled. See issue 9369. // It also catches changes in toolchain, like when flipping between // two versions of Go compiling a single GOPATH. // See issue 8290 and issue 10702. targetBuildID, err := readBuildID(p) if err == nil && targetBuildID != p.buildID { return true, "build ID mismatch" } // Package is stale if a dependency is. for _, p1 := range p.deps { if p1.Stale { return true, "stale dependency" } } // The checks above are content-based staleness. // We assume they are always accurate. // // The checks below are mtime-based staleness. // We hope they are accurate, but we know that they fail in the case of // prebuilt Go installations that don't preserve the build mtimes // (for example, if the pkg/ mtimes are before the src/ mtimes). // See the large comment above isStale for details. // If we are running a release copy of Go and didn't find a content-based // reason to rebuild the standard packages, do not rebuild them. // They may not be writable anyway, but they are certainly not changing. // This makes 'go build' skip the standard packages when // using an official release, even when the mtimes have been changed. // See issue 3036, issue 3149, issue 4106, issue 8290. // (If a change to a release tree must be made by hand, the way to force the // install is to run make.bash, which will remove the old package archives // before rebuilding.) if p.Standard && isGoRelease { return false, "standard package in Go release distribution" } // Time-based staleness. built := fi.ModTime() olderThan := func(file string) bool { fi, err := os.Stat(file) return err != nil || fi.ModTime().After(built) } // Package is stale if a dependency is, or if a dependency is newer. for _, p1 := range p.deps { if p1.target != "" && olderThan(p1.target) { return true, "newer dependency" } } // As a courtesy to developers installing new versions of the compiler // frequently, define that packages are stale if they are // older than the compiler, and commands if they are older than // the linker. This heuristic will not work if the binaries are // back-dated, as some binary distributions may do, but it does handle // a very common case. // See issue 3036. // Exclude $GOROOT, under the assumption that people working on // the compiler may want to control when everything gets rebuilt, // and people updating the Go repository will run make.bash or all.bash // and get a full rebuild anyway. // Excluding $GOROOT used to also fix issue 4106, but that's now // taken care of above (at least when the installed Go is a released version). if p.Root != goroot { if olderThan(buildToolchain.compiler()) { return true, "newer compiler" } if p.build.IsCommand() && olderThan(buildToolchain.linker()) { return true, "newer linker" } } // Note: Until Go 1.5, we had an additional shortcut here. // We built a list of the workspace roots ($GOROOT, each $GOPATH) // containing targets directly named on the command line, // and if p were not in any of those, it would be treated as up-to-date // as long as it is built. The goal was to avoid rebuilding a system-installed // $GOROOT, unless something from $GOROOT were explicitly named // on the command line (like go install math). // That's now handled by the isGoRelease clause above. // The other effect of the shortcut was to isolate different entries in // $GOPATH from each other. This had the unfortunate effect that // if you had (say), GOPATH listing two entries, one for commands // and one for libraries, and you did a 'git pull' in the library one // and then tried 'go install commands/...', it would build the new libraries // during the first build (because they wouldn't have been installed at all) // but then subsequent builds would not rebuild the libraries, even if the // mtimes indicate they are stale, because the different GOPATH entries // were treated differently. This behavior was confusing when using // non-trivial GOPATHs, which were particularly common with some // code management conventions, like the original godep. // Since the $GOROOT case (the original motivation) is handled separately, // we no longer put a barrier between the different $GOPATH entries. // // One implication of this is that if there is a system directory for // non-standard Go packages that is included in $GOPATH, the mtimes // on those compiled packages must be no earlier than the mtimes // on the source files. Since most distributions use the same mtime // for all files in a tree, they will be unaffected. People using plain // tar x to extract system-installed packages will need to adjust mtimes, // but it's better to force them to get the mtimes right than to ignore // the mtimes and thereby do the wrong thing in common use cases. // // So there is no GOPATH vs GOPATH shortcut here anymore. // // If something needs to come back here, we could try writing a dummy // file with a random name to the $GOPATH/pkg directory (and removing it) // to test for write access, and then skip GOPATH roots we don't have write // access to. But hopefully we can just use the mtimes always. srcs := stringList(p.GoFiles, p.CFiles, p.CXXFiles, p.MFiles, p.HFiles, p.FFiles, p.SFiles, p.CgoFiles, p.SysoFiles, p.SwigFiles, p.SwigCXXFiles) for _, src := range srcs { if olderThan(filepath.Join(p.Dir, src)) { return true, "newer source file" } } return false, "" } // computeBuildID computes the build ID for p, leaving it in p.buildID. // Build ID is a hash of the information we want to detect changes in. // See the long comment in isStale for details. func computeBuildID(p *Package) { h := sha1.New() // Include the list of files compiled as part of the package. // This lets us detect removed files. See issue 3895. inputFiles := stringList( p.GoFiles, p.CgoFiles, p.CFiles, p.CXXFiles, p.MFiles, p.HFiles, p.SFiles, p.SysoFiles, p.SwigFiles, p.SwigCXXFiles, ) for _, file := range inputFiles { fmt.Fprintf(h, "file %s\n", file) } // Include the content of runtime/internal/sys/zversion.go in the hash // for package runtime. This will give package runtime a // different build ID in each Go release. if p.Standard && p.ImportPath == "runtime/internal/sys" { data, err := ioutil.ReadFile(filepath.Join(p.Dir, "zversion.go")) if err != nil { fatalf("go: %s", err) } fmt.Fprintf(h, "zversion %q\n", string(data)) } // Include the build IDs of any dependencies in the hash. // This, combined with the runtime/zversion content, // will cause packages to have different build IDs when // compiled with different Go releases. // This helps the go command know to recompile when // people use the same GOPATH but switch between // different Go releases. See issue 10702. // This is also a better fix for issue 8290. for _, p1 := range p.deps { fmt.Fprintf(h, "dep %s %s\n", p1.ImportPath, p1.buildID) } p.buildID = fmt.Sprintf("%x", h.Sum(nil)) } var cwd, _ = os.Getwd() var cmdCache = map[string]*Package{} // loadPackage is like loadImport but is used for command-line arguments, // not for paths found in import statements. In addition to ordinary import paths, // loadPackage accepts pseudo-paths beginning with cmd/ to denote commands // in the Go command directory, as well as paths to those directories. func loadPackage(arg string, stk *importStack) *Package { if build.IsLocalImport(arg) { dir := arg if !filepath.IsAbs(dir) { if abs, err := filepath.Abs(dir); err == nil { // interpret relative to current directory dir = abs } } if sub, ok := hasSubdir(gorootSrc, dir); ok && strings.HasPrefix(sub, "cmd/") && !strings.Contains(sub[4:], "/") { arg = sub } } if strings.HasPrefix(arg, "cmd/") && !strings.Contains(arg[4:], "/") { if p := cmdCache[arg]; p != nil { return p } stk.push(arg) defer stk.pop() bp, err := buildContext.ImportDir(filepath.Join(gorootSrc, arg), 0) bp.ImportPath = arg bp.Goroot = true bp.BinDir = gorootBin if gobin != "" { bp.BinDir = gobin } bp.Root = goroot bp.SrcRoot = gorootSrc p := new(Package) cmdCache[arg] = p p.load(stk, bp, err) if p.Error == nil && p.Name != "main" { p.Error = &PackageError{ ImportStack: stk.copy(), Err: fmt.Sprintf("expected package main but found package %s in %s", p.Name, p.Dir), } } return p } // Wasn't a command; must be a package. // If it is a local import path but names a standard package, // we treat it as if the user specified the standard package. // This lets you run go test ./ioutil in package io and be // referring to io/ioutil rather than a hypothetical import of // "./ioutil". if build.IsLocalImport(arg) { bp, _ := buildContext.ImportDir(filepath.Join(cwd, arg), build.FindOnly) if bp.ImportPath != "" && bp.ImportPath != "." { arg = bp.ImportPath } } return loadImport(arg, cwd, nil, stk, nil, 0) } // packages returns the packages named by the // command line arguments 'args'. If a named package // cannot be loaded at all (for example, if the directory does not exist), // then packages prints an error and does not include that // package in the results. However, if errors occur trying // to load dependencies of a named package, the named // package is still returned, with p.Incomplete = true // and details in p.DepsErrors. func packages(args []string) []*Package { var pkgs []*Package for _, pkg := range packagesAndErrors(args) { if pkg.Error != nil { errorf("can't load package: %s", pkg.Error) continue } pkgs = append(pkgs, pkg) } return pkgs } // packagesAndErrors is like 'packages' but returns a // *Package for every argument, even the ones that // cannot be loaded at all. // The packages that fail to load will have p.Error != nil. func packagesAndErrors(args []string) []*Package { if len(args) > 0 && strings.HasSuffix(args[0], ".go") { return []*Package{goFilesPackage(args)} } args = importPaths(args) var ( pkgs []*Package stk importStack seenArg = make(map[string]bool) seenPkg = make(map[*Package]bool) ) for _, arg := range args { if seenArg[arg] { continue } seenArg[arg] = true pkg := loadPackage(arg, &stk) if seenPkg[pkg] { continue } seenPkg[pkg] = true pkgs = append(pkgs, pkg) } computeStale(pkgs...) return pkgs } // packagesForBuild is like 'packages' but fails if any of // the packages or their dependencies have errors // (cannot be built). func packagesForBuild(args []string) []*Package { pkgs := packagesAndErrors(args) printed := map[*PackageError]bool{} for _, pkg := range pkgs { if pkg.Error != nil { errorf("can't load package: %s", pkg.Error) } for _, err := range pkg.DepsErrors { // Since these are errors in dependencies, // the same error might show up multiple times, // once in each package that depends on it. // Only print each once. if !printed[err] { printed[err] = true errorf("%s", err) } } } exitIfErrors() // Check for duplicate loads of the same package. // That should be impossible, but if it does happen then // we end up trying to build the same package twice, // usually in parallel overwriting the same files, // which doesn't work very well. seen := map[string]bool{} reported := map[string]bool{} for _, pkg := range packageList(pkgs) { if seen[pkg.ImportPath] && !reported[pkg.ImportPath] { reported[pkg.ImportPath] = true errorf("internal error: duplicate loads of %s", pkg.ImportPath) } seen[pkg.ImportPath] = true } exitIfErrors() return pkgs } // hasSubdir reports whether dir is a subdirectory of // (possibly multiple levels below) root. // If so, it sets rel to the path fragment that must be // appended to root to reach dir. func hasSubdir(root, dir string) (rel string, ok bool) { if p, err := filepath.EvalSymlinks(root); err == nil { root = p } if p, err := filepath.EvalSymlinks(dir); err == nil { dir = p } const sep = string(filepath.Separator) root = filepath.Clean(root) if !strings.HasSuffix(root, sep) { root += sep } dir = filepath.Clean(dir) if !strings.HasPrefix(dir, root) { return "", false } return filepath.ToSlash(dir[len(root):]), true } var ( errBuildIDToolchain = fmt.Errorf("build ID only supported in gc toolchain") errBuildIDMalformed = fmt.Errorf("malformed object file") errBuildIDUnknown = fmt.Errorf("lost build ID") ) var ( bangArch = []byte("!<arch>") pkgdef = []byte("__.PKGDEF") goobject = []byte("go object ") buildid = []byte("build id ") ) // readBuildID reads the build ID from an archive or binary. // It only supports the gc toolchain. // Other toolchain maintainers should adjust this function. func readBuildID(p *Package) (id string, err error) { if buildToolchain != (gcToolchain{}) { return "", errBuildIDToolchain } // For commands, read build ID directly from binary. if p.Name == "main" { return ReadBuildIDFromBinary(p.Target) } // Otherwise, we expect to have an archive (.a) file, // and we can read the build ID from the Go export data. if !strings.HasSuffix(p.Target, ".a") { return "", &os.PathError{Op: "parse", Path: p.Target, Err: errBuildIDUnknown} } // Read just enough of the target to fetch the build ID. // The archive is expected to look like: // // !<arch> // __.PKGDEF 0 0 0 644 7955 ` // go object darwin amd64 devel X:none // build id "b41e5c45250e25c9fd5e9f9a1de7857ea0d41224" // // The variable-sized strings are GOOS, GOARCH, and the experiment list (X:none). // Reading the first 1024 bytes should be plenty. f, err := os.Open(p.Target) if err != nil { return "", err } data := make([]byte, 1024) n, err := io.ReadFull(f, data) f.Close() if err != nil && n == 0 { return "", err } bad := func() (string, error) { return "", &os.PathError{Op: "parse", Path: p.Target, Err: errBuildIDMalformed} } // Archive header. for i := 0; ; i++ { // returns during i==3 j := bytes.IndexByte(data, '\n') if j < 0 { return bad() } line := data[:j] data = data[j+1:] switch i { case 0: if !bytes.Equal(line, bangArch) { return bad() } case 1: if !bytes.HasPrefix(line, pkgdef) { return bad() } case 2: if !bytes.HasPrefix(line, goobject) { return bad() } case 3: if !bytes.HasPrefix(line, buildid) { // Found the object header, just doesn't have a build id line. // Treat as successful, with empty build id. return "", nil } id, err := strconv.Unquote(string(line[len(buildid):])) if err != nil { return bad() } return id, nil } } } var ( goBuildPrefix = []byte("\xff Go build ID: \"") goBuildEnd = []byte("\"\n \xff") elfPrefix = []byte("\x7fELF") machoPrefixes = [][]byte{ {0xfe, 0xed, 0xfa, 0xce}, {0xfe, 0xed, 0xfa, 0xcf}, {0xce, 0xfa, 0xed, 0xfe}, {0xcf, 0xfa, 0xed, 0xfe}, } ) var BuildIDReadSize = 32 * 1024 // changed for testing // ReadBuildIDFromBinary reads the build ID from a binary. // // ELF binaries store the build ID in a proper PT_NOTE section. // // Other binary formats are not so flexible. For those, the linker // stores the build ID as non-instruction bytes at the very beginning // of the text segment, which should appear near the beginning // of the file. This is clumsy but fairly portable. Custom locations // can be added for other binary types as needed, like we did for ELF. func ReadBuildIDFromBinary(filename string) (id string, err error) { if filename == "" { return "", &os.PathError{Op: "parse", Path: filename, Err: errBuildIDUnknown} } // Read the first 32 kB of the binary file. // That should be enough to find the build ID. // In ELF files, the build ID is in the leading headers, // which are typically less than 4 kB, not to mention 32 kB. // In Mach-O files, there's no limit, so we have to parse the file. // On other systems, we're trying to read enough that // we get the beginning of the text segment in the read. // The offset where the text segment begins in a hello // world compiled for each different object format today: // // Plan 9: 0x20 // Windows: 0x600 // f, err := os.Open(filename) if err != nil { return "", err } defer f.Close() data := make([]byte, BuildIDReadSize) _, err = io.ReadFull(f, data) if err == io.ErrUnexpectedEOF { err = nil } if err != nil { return "", err } if bytes.HasPrefix(data, elfPrefix) { return readELFGoBuildID(filename, f, data) } for _, m := range machoPrefixes { if bytes.HasPrefix(data, m) { return readMachoGoBuildID(filename, f, data) } } return readRawGoBuildID(filename, data) } // readRawGoBuildID finds the raw build ID stored in text segment data. func readRawGoBuildID(filename string, data []byte) (id string, err error) { i := bytes.Index(data, goBuildPrefix) if i < 0 { // Missing. Treat as successful but build ID empty. return "", nil } j := bytes.Index(data[i+len(goBuildPrefix):], goBuildEnd) if j < 0 { return "", &os.PathError{Op: "parse", Path: filename, Err: errBuildIDMalformed} } quoted := data[i+len(goBuildPrefix)-1 : i+len(goBuildPrefix)+j+1] id, err = strconv.Unquote(string(quoted)) if err != nil { return "", &os.PathError{Op: "parse", Path: filename, Err: errBuildIDMalformed} } return id, nil }
{ "content_hash": "77db55f830ecda8aea5e30439f9b6e50", "timestamp": "", "source": "github", "line_count": 1960, "max_line_length": 146, "avg_line_length": 36.4954081632653, "alnum_prop": 0.6941885336427562, "repo_name": "momchil-velikov/go", "id": "69367eefb130bc80dc69fe9c095e09ae47218c52", "size": "71699", "binary": false, "copies": "1", "ref": "refs/heads/dev.chill", "path": "src/cmd/go/pkg.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "1989835" }, { "name": "Awk", "bytes": "450" }, { "name": "Batchfile", "bytes": "7351" }, { "name": "C", "bytes": "187779" }, { "name": "C++", "bytes": "1370" }, { "name": "CSS", "bytes": "8" }, { "name": "FORTRAN", "bytes": "394" }, { "name": "Go", "bytes": "32611699" }, { "name": "HTML", "bytes": "1806598" }, { "name": "JavaScript", "bytes": "2550" }, { "name": "Logos", "bytes": "1248" }, { "name": "Makefile", "bytes": "748" }, { "name": "Perl", "bytes": "34825" }, { "name": "Protocol Buffer", "bytes": "1698" }, { "name": "Python", "bytes": "12446" }, { "name": "Shell", "bytes": "66347" } ], "symlink_target": "" }
/** @jsx jsx */ import { Box, Button, Flex, Heading, Input, Label, Radio, Select, Textarea, } from "@theme-ui/components"; import React, { useCallback, useEffect } from "react"; import { FormattedMessage } from "react-intl"; import { useFormState } from "react-use-form-state"; import { jsx } from "theme-ui"; import { useCountries } from "../../helpers/use-countries"; import { useTranslatedMessage } from "../../helpers/use-translated-message"; import { InputWrapper } from "../input-wrapper"; import { InvoiceInformationState } from "./types"; type Props = { path: string; onNextStep: () => void; onUpdateInformation: (data: InvoiceInformationState) => void; invoiceInformation: InvoiceInformationState; }; const FISCAL_CODE_REGEX = /^[A-Za-z]{6}[0-9]{2}[A-Za-z]{1}[0-9]{2}[A-Za-z]{1}[0-9]{3}[A-Za-z]{1}$/; export const InformationSection: React.SFC<Props> = ({ onNextStep, onUpdateInformation, invoiceInformation, }) => { const countries = useCountries(); const invalidFiscalCodeMessage = useTranslatedMessage( "orderInformation.invalidFiscalCode", ); const [formState, { text, select, textarea, radio }] = useFormState< InvoiceInformationState >({ ...invoiceInformation }); const isBusiness = invoiceInformation.isBusiness; const isItalian = formState.values.country === "IT"; const shouldAskForFiscalCode = !isBusiness && isItalian; const onSubmit = useCallback( (e: React.MouseEvent<HTMLFormElement>) => { e.preventDefault(); if (shouldAskForFiscalCode && formState.validity.fiscalCode === false) { return; } onNextStep(); }, [formState.values], ); useEffect(() => onUpdateInformation(formState.values), [formState.values]); return ( <React.Fragment> <Heading as="h1" sx={{ pb: 5, mb: 5, borderBottom: "primary" }}> <Box sx={{ maxWidth: "container", mx: "auto", px: 3, }} > <FormattedMessage id="orderInformation.heading" /> </Box> </Heading> <Box sx={{ maxWidth: "container", mx: "auto", px: 3, }} > <Box as="form" onSubmit={onSubmit}> {isBusiness && ( <InputWrapper isRequired={true} label={<FormattedMessage id="orderInformation.companyName" />} > <Input {...text("companyName")} required={isBusiness} /> </InputWrapper> )} <InputWrapper isRequired={true} label={<FormattedMessage id="orderInformation.name" />} > <Input {...text("name")} required={true} /> </InputWrapper> {isBusiness && ( <InputWrapper isRequired={true} label={<FormattedMessage id="orderInformation.vatId" />} > <Input {...text("vatId")} required={true} /> </InputWrapper> )} <InputWrapper isRequired={true} label={<FormattedMessage id="orderInformation.address" />} > <Textarea {...textarea("address")} required={true} /> </InputWrapper> <InputWrapper isRequired={true} label={<FormattedMessage id="orderInformation.zipCode" />} > <Input {...text("zipCode")} required={true} /> </InputWrapper> <InputWrapper isRequired={true} label={<FormattedMessage id="orderInformation.city" />} > <Input {...text("city")} required={true} /> </InputWrapper> <InputWrapper isRequired={true} label={<FormattedMessage id="orderInformation.country" />} > <Select {...select("country")} required={true}> {countries.map(c => ( <option key={c.value} value={c.value}> {c.label} </option> ))} </Select> </InputWrapper> {shouldAskForFiscalCode && ( <InputWrapper errors={[formState.errors.fiscalCode || ""]} isRequired={true} label={<FormattedMessage id="orderInformation.fiscalCode" />} > <Input {...text({ name: "fiscalCode", validate: (value, values, e) => { const isValid = FISCAL_CODE_REGEX.test(value); if (!isValid) { return invalidFiscalCodeMessage; } }, validateOnBlur: true, })} required={true} /> </InputWrapper> )} <Button> <FormattedMessage id="order.nextStep" /> </Button> </Box> </Box> </React.Fragment> ); };
{ "content_hash": "b0a8c3d1e5c8b90e255a9bffe48adc34", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 99, "avg_line_length": 29.420118343195266, "alnum_prop": 0.5233306516492358, "repo_name": "patrick91/pycon", "id": "14297adc3db0714ad07559a7825d38514f44456c", "size": "4972", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frontend/src/components/tickets-page/information.tsx", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1456" }, { "name": "Python", "bytes": "13911" } ], "symlink_target": "" }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.11.03 at 06:37:06 PM GMT-08:00 // package org.zstack.test.deployer.schema; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for NetworkServiceConfig complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="NetworkServiceConfig"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="serviceType" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="provider" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "NetworkServiceConfig", propOrder = { "serviceType" }) public class NetworkServiceConfig { protected List<String> serviceType; @XmlAttribute(name = "provider", required = true) protected String provider; /** * Gets the value of the serviceType property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the serviceType property. * * <p> * For example, to add a new item, do as follows: * <pre> * getServiceType().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getServiceType() { if (serviceType == null) { serviceType = new ArrayList<String>(); } return this.serviceType; } /** * Gets the value of the provider property. * * @return * possible object is * {@link String } * */ public String getProvider() { return provider; } /** * Sets the value of the provider property. * * @param value * allowed object is * {@link String } * */ public void setProvider(String value) { this.provider = value; } }
{ "content_hash": "818333aad37cb7299526bec8b537a2b8", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 127, "avg_line_length": 28.205882352941178, "alnum_prop": 0.6280848105665624, "repo_name": "SoftwareKing/zstack", "id": "74e1088ca365573626f6e07baa089c57fa3ac587", "size": "2877", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/src/test/java/org/zstack/test/deployer/schema/NetworkServiceConfig.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "49265" }, { "name": "Groovy", "bytes": "16605" }, { "name": "Java", "bytes": "8041121" }, { "name": "Shell", "bytes": "146403" } ], "symlink_target": "" }
template<int x> class Adds { public: template<typename T> constexpr T operator()(T input) const { return T(input + x); } }; class Increments : public Adds<1> {}; class Decrements : public Adds<-1> {}; auto const incrementing = transducers::mapping(Increments()); auto const decrementing = transducers::mapping(Decrements());
{ "content_hash": "93018f3a088f85e2e46ffd2d924ea71c", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 61, "avg_line_length": 18.473684210526315, "alnum_prop": 0.6723646723646723, "repo_name": "AndrewGaspar/transducers.hpp", "id": "ce96599412090a77a1b4c1ec80dd00e8700a4501", "size": "434", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "unit_tests/common.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "642" }, { "name": "C++", "bytes": "104585" }, { "name": "PowerShell", "bytes": "91" } ], "symlink_target": "" }
module Gitlab module Ci module Ansi2json class Converter def convert(stream, new_state) @lines = [] @state = State.new(new_state, stream.size) append = false truncated = false cur_offset = stream.tell if cur_offset > @state.offset @state.offset = cur_offset truncated = true else stream.seek(@state.offset) append = @state.offset > 0 end start_offset = @state.offset @state.set_current_line!(style: Style.new(@state.inherited_style)) stream.each_line do |line| s = StringScanner.new(line) convert_line(s) end # This must be assigned before flushing the current line # or the @current_line.offset will advance to the very end # of the trace. Instead we want @last_line_offset to always # point to the beginning of last line. @state.set_last_line_offset flush_current_line # TODO: replace OpenStruct with a better type # https://gitlab.com/gitlab-org/gitlab/issues/34305 OpenStruct.new( lines: @lines, state: @state.encode, append: append, truncated: truncated, offset: start_offset, size: stream.tell - start_offset, total: stream.size ) end private def convert_line(scanner) until scanner.eos? if scanner.scan(Gitlab::Regex.build_trace_section_regex) handle_section(scanner) elsif scanner.scan(/\e([@-_])(.*?)([@-~])/) handle_sequence(scanner) elsif scanner.scan(/\e(([@-_])(.*?)?)?$/) break elsif scanner.scan(/</) @state.current_line << '&lt;' elsif scanner.scan(/\r?\n/) # we advance the offset of the next current line # so it does not start from \n flush_current_line(advance_offset: scanner.matched_size) else @state.current_line << scanner.scan(/./m) end @state.offset += scanner.matched_size end end def handle_sequence(scanner) indicator = scanner[1] commands = scanner[2].split ';' terminator = scanner[3] # We are only interested in color and text style changes - triggered by # sequences starting with '\e[' and ending with 'm'. Any other control # sequence gets stripped (including stuff like "delete last line") return unless indicator == '[' && terminator == 'm' @state.update_style(commands) end def handle_section(scanner) action = scanner[1] timestamp = scanner[2] section = scanner[3] section_name = sanitize_section_name(section) if action == "start" handle_section_start(section_name, timestamp) elsif action == "end" handle_section_end(section_name, timestamp) end end def handle_section_start(section, timestamp) flush_current_line unless @state.current_line.empty? @state.open_section(section, timestamp) end def handle_section_end(section, timestamp) return unless @state.section_open?(section) flush_current_line unless @state.current_line.empty? @state.close_section(section, timestamp) # ensure that section end is detached from the last # line in the section flush_current_line end def flush_current_line(advance_offset: 0) @lines << @state.current_line.to_h @state.set_current_line!(advance_offset: advance_offset) end def sanitize_section_name(section) section.to_s.downcase.gsub(/[^a-z0-9]/, '-') end end end end end
{ "content_hash": "5228205fe4edde001c61bd5cbd730404", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 81, "avg_line_length": 30.702290076335878, "alnum_prop": 0.5497265042267528, "repo_name": "stoplightio/gitlabhq", "id": "8d25b66af9c72cf6e152cc75240082345cfc5396", "size": "4053", "binary": false, "copies": "1", "ref": "refs/heads/stoplight/develop", "path": "lib/gitlab/ci/ansi2json/converter.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "632980" }, { "name": "Clojure", "bytes": "79" }, { "name": "Dockerfile", "bytes": "1676" }, { "name": "HTML", "bytes": "1264236" }, { "name": "JavaScript", "bytes": "3425347" }, { "name": "Ruby", "bytes": "16497064" }, { "name": "Shell", "bytes": "34509" }, { "name": "Vue", "bytes": "752795" } ], "symlink_target": "" }
from django import forms from django.contrib import admin from rdmo.core.utils import get_language_fields from .models import Task from .validators import TaskLockedValidator, TaskUniqueURIValidator class TaskAdminForm(forms.ModelForm): key = forms.SlugField(required=True) class Meta: model = Task fields = '__all__' def clean(self): TaskUniqueURIValidator(self.instance)(self.cleaned_data) TaskLockedValidator(self.instance)(self.cleaned_data) class TaskAdmin(admin.ModelAdmin): form = TaskAdminForm search_fields = ['uri'] + get_language_fields('title') + get_language_fields('text') list_display = ('uri', 'title', 'text', 'available') readonly_fields = ('uri', ) list_filter = ('available', ) admin.site.register(Task, TaskAdmin)
{ "content_hash": "8adb43b38b0567be8609f6624ef7887b", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 88, "avg_line_length": 26.129032258064516, "alnum_prop": 0.7, "repo_name": "DMPwerkzeug/DMPwerkzeug", "id": "82884a64ccb7e15996bd1e3b73dc2b09f12c7832", "size": "810", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "rdmo/tasks/admin.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9735" }, { "name": "HTML", "bytes": "126570" }, { "name": "JavaScript", "bytes": "46177" }, { "name": "Python", "bytes": "120676" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "8dd86d990fa627818eea4cdce6d71f3c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "c907724e8aff27a3592e55765c24c21e8e2ce4e4", "size": "195", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Chamaecrista/Chamaecrista duckeana/ Syn. Cassia duckeana/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(259, 117) self.horizontalLayout = QtGui.QHBoxLayout(Form) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.gridLayout_2 = QtGui.QGridLayout() self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 1, 2, 1, 1) self.vcHoldingLabel = QtGui.QLabel(Form) self.vcHoldingLabel.setText(_fromUtf8("")) self.vcHoldingLabel.setObjectName(_fromUtf8("vcHoldingLabel")) self.gridLayout_2.addWidget(self.vcHoldingLabel, 3, 2, 1, 1) self.icHoldingSpin = SpinBox(Form) self.icHoldingSpin.setMaximumSize(QtCore.QSize(150, 16777215)) self.icHoldingSpin.setObjectName(_fromUtf8("icHoldingSpin")) self.gridLayout_2.addWidget(self.icHoldingSpin, 4, 1, 1, 1) self.label_6 = QtGui.QLabel(Form) self.label_6.setObjectName(_fromUtf8("label_6")) self.gridLayout_2.addWidget(self.label_6, 0, 0, 1, 1) self.label = QtGui.QLabel(Form) self.label.setObjectName(_fromUtf8("label")) self.gridLayout_2.addWidget(self.label, 1, 0, 1, 1) self.channelLabel = QtGui.QLabel(Form) self.channelLabel.setText(_fromUtf8("")) self.channelLabel.setObjectName(_fromUtf8("channelLabel")) self.gridLayout_2.addWidget(self.channelLabel, 0, 2, 1, 1) self.label_3 = QtGui.QLabel(Form) self.label_3.setObjectName(_fromUtf8("label_3")) self.gridLayout_2.addWidget(self.label_3, 4, 0, 1, 1) self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) self.vcRadio = QtGui.QRadioButton(Form) self.vcRadio.setObjectName(_fromUtf8("vcRadio")) self.horizontalLayout_2.addWidget(self.vcRadio) self.i0Radio = QtGui.QRadioButton(Form) self.i0Radio.setObjectName(_fromUtf8("i0Radio")) self.horizontalLayout_2.addWidget(self.i0Radio) self.icRadio = QtGui.QRadioButton(Form) self.icRadio.setObjectName(_fromUtf8("icRadio")) self.horizontalLayout_2.addWidget(self.icRadio) self.gridLayout_2.addLayout(self.horizontalLayout_2, 1, 1, 1, 1) self.label_2 = QtGui.QLabel(Form) self.label_2.setObjectName(_fromUtf8("label_2")) self.gridLayout_2.addWidget(self.label_2, 3, 0, 1, 1) self.vcHoldingSpin = SpinBox(Form) self.vcHoldingSpin.setMaximumSize(QtCore.QSize(150, 16777215)) self.vcHoldingSpin.setObjectName(_fromUtf8("vcHoldingSpin")) self.gridLayout_2.addWidget(self.vcHoldingSpin, 3, 1, 1, 1) self.icHoldingLabel = QtGui.QLabel(Form) self.icHoldingLabel.setText(_fromUtf8("")) self.icHoldingLabel.setObjectName(_fromUtf8("icHoldingLabel")) self.gridLayout_2.addWidget(self.icHoldingLabel, 4, 2, 1, 1) spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout_2.addItem(spacerItem1, 5, 0, 1, 1) self.horizontalLayout.addLayout(self.gridLayout_2) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Form", None)) self.label_6.setText(_translate("Form", "MultiClamp Channel:", None)) self.label.setText(_translate("Form", "Mode:", None)) self.label_3.setText(_translate("Form", "IC Holding:", None)) self.vcRadio.setText(_translate("Form", "VC", None)) self.i0Radio.setText(_translate("Form", "I=0", None)) self.icRadio.setText(_translate("Form", "IC", None)) self.label_2.setText(_translate("Form", "VC Holding:", None)) from acq4.pyqtgraph import SpinBox
{ "content_hash": "32b992d167bc0f990e5187b3811c40fe", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 103, "avg_line_length": 50.38636363636363, "alnum_prop": 0.6790708164185837, "repo_name": "mgraupe/acq4", "id": "8c0367746ff9c4ae4c88e0af0a454a12deeabda2", "size": "4668", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "acq4/devices/MultiClamp/RackTemplate.py", "mode": "33188", "license": "mit", "language": [ { "name": "AMPL", "bytes": "3037" }, { "name": "Batchfile", "bytes": "247" }, { "name": "C", "bytes": "757367" }, { "name": "C++", "bytes": "1222891" }, { "name": "CSS", "bytes": "716" }, { "name": "Inno Setup", "bytes": "1606" }, { "name": "MATLAB", "bytes": "1752" }, { "name": "Makefile", "bytes": "30" }, { "name": "Processing", "bytes": "13403" }, { "name": "Python", "bytes": "6110588" }, { "name": "Shell", "bytes": "70" } ], "symlink_target": "" }
package net.liftweb.util import _root_.java.text.SimpleDateFormat import _root_.java.util.{TimeZone, Calendar, Date, Locale} /** * The TimeHelpers object extends the TimeHelpers. It can be imported to access all of the trait functions. */ object TimeHelpers extends TimeHelpers with ControlHelpers with ClassHelpers /** * The TimeHelpers trait provide functions to create TimeSpans (an object representing an amount of time), to manage date formats * or general utility functions (get the date for today, get year/month/day number,...) */ trait TimeHelpers { self: ControlHelpers => /** private variable allowing the access to all TimeHelpers functions from inside the TimeSpan class */ private val outer = this /** transforms a long to a TimeSpanBuilder object. Usage: 3L.seconds returns a TimeSpan of 3000L millis */ implicit def longToTimeSpanBuilder(in: Long): TimeSpanBuilder = TimeSpanBuilder(in) /** transforms an int to a TimeSpanBuilder object. Usage: 3.seconds returns a TimeSpan of 3000L millis */ implicit def intToTimeSpanBuilder(in: Int): TimeSpanBuilder = TimeSpanBuilder(in) /** transforms a long to a TimeSpan object. Usage: 3000L returns a TimeSpan of 3000L millis */ implicit def longToTimeSpan(in: Long): TimeSpan = TimeSpan(in) /** transforms an int to a TimeSpan object. Usage: 3000 returns a TimeSpan of 3000L millis */ implicit def intToTimeSpan(in: Int): TimeSpan = TimeSpan(in) /** class building TimeSpans given an amount (len) and a method specify the time unit */ case class TimeSpanBuilder(val len: Long) { def seconds = TimeSpan(outer.seconds(len)) def second = seconds def minutes = TimeSpan(outer.minutes(len)) def minute = minutes def hours = TimeSpan(outer.hours(len)) def hour = hours def days = TimeSpan(outer.days(len)) def day = days def weeks = TimeSpan(outer.weeks(len)) def week = weeks } /** * transforms a TimeSpan to a date by converting the TimeSpan expressed as millis and creating * a Date lasting that number of millis from the Epoch time (see the documentation for java.util.Date) */ implicit def timeSpanToDate(in: TimeSpan): Date = in.date /** transforms a TimeSpan to its long value as millis */ implicit def timeSpanToLong(in: TimeSpan): Long = in.millis /** * The TimeSpan class represents an amount of time. * It can be translated to a date with the date method. In that case, the number of millis seconds will be used to create a Date * object starting from the Epoch time (see the documentation for java.util.Date) */ class TimeSpan(val millis: Long) { /** @return a Date as the amount of time represented by the TimeSpan after the Epoch date */ def date = new Date(millis) /** @return a Date as the amount of time represented by the TimeSpan after now */ def later = TimeSpan(millis + outer.millis).date /** @return a Date as the amount of time represented by the TimeSpan before now */ def ago = TimeSpan(outer.millis - millis).date /** @return a TimeSpan representing the addition of 2 TimeSpans */ def +(in: TimeSpan) = TimeSpan(this.millis + in.millis) /** @return a TimeSpan representing the substraction of 2 TimeSpans */ def -(in: TimeSpan) = TimeSpan(this.millis - in.millis) /** override the equals method so that TimeSpans can be compared to long, int and TimeSpan */ override def equals(cmp: Any) = { cmp match { case lo: Long => lo == this.millis case i: Int => i == this.millis case ti: TimeSpan => ti.millis == this.millis case _ => false } } /** override the toString method to display a readable amount of time */ override def toString = TimeSpan.format(millis) } /** * The TimeSpan object provides class represents an amount of time. * It can be translated to a date with the date method. In that case, the number of millis seconds will be used to create a Date * object starting from the Epoch time (see the documentation for java.util.Date) */ object TimeSpan { /** time units and values used when converting a total number of millis to those units (see the format function) */ val scales = List((1000L, "milli"), (60L, "second"), (60L, "minute"), (24L, "hour"), (7L, "day"), (10000L, "week")) /** explicit constructor for a TimeSpan */ def apply(in: Long) = new TimeSpan(in) /** * Formats a number of millis to a string representing the number of weeks, days, hours, minutes, seconds, millis */ def format(millis: Long): String = { def divideInUnits(millis: Long) = scales.foldLeft[(Long, List[(Long, String)])]((millis, Nil)){ (total, div) => (total._1 / div._1, (total._1 % div._1, div._2) :: total._2) }._2 def formatAmount(amountUnit: (Long, String)) = amountUnit match { case (amount, unit) if (amount == 1) => amount + " " + unit case (amount, unit) => amount + " " + unit + "s" } divideInUnits(millis).filter(_._1 > 0).map(formatAmount(_)).mkString(", ") } } /** @return the current number of millis: System.currentTimeMillis */ def millis = System.currentTimeMillis /** @return the number of millis corresponding to 'in' seconds */ def seconds(in: Long): Long = in * 1000L /** @return the number of millis corresponding to 'in' minutes */ def minutes(in: Long): Long = seconds(in) * 60L /** @return the number of millis corresponding to 'in' hours */ def hours(in: Long): Long = minutes(in) * 60L /** @return the number of millis corresponding to 'in' days */ def days(in: Long): Long = hours(in) * 24L /** @return the number of millis corresponding to 'in' weeks */ def weeks(in: Long): Long = days(in) * 7L /** implicit def used to add the noTime method to the Date class */ implicit def toDateExtension(d: Date) = new DateExtension(d) /** This class adds a noTime method the Date class, in order to get at Date object starting at 00:00 */ class DateExtension(date: Date) { /** @returns a Date object starting at 00:00 from date */ def noTime = { val calendar = Calendar.getInstance calendar.set(Calendar.HOUR_OF_DAY, 0) calendar.set(Calendar.MINUTE, 0) calendar.set(Calendar.SECOND, 0) calendar.set(Calendar.MILLISECOND, 0) calendar.getTime } } /** implicit def used to add the setXXX methods to the Calendar class */ implicit def toCalendarExtension(c: Calendar) = new CalendarExtension(c) /** This class adds the setXXX methods to the Calendar class. Each setter returns the updated Calendar */ class CalendarExtension(c: Calendar) { /** set the day of the month (1 based) and return the calendar */ def setDay(d: Int) = { c.set(Calendar.DAY_OF_MONTH, d); c } /** set the month (0 based) and return the calendar */ def setMonth(m: Int) = { c.set(Calendar.MONTH, m); c } /** set the year and return the calendar */ def setYear(y: Int) = { c.set(Calendar.YEAR, y); c } /** set the TimeZone and return the calendar */ def setTimezone(tz: TimeZone) = { c.setTimeZone(tz); c } /** set the time to 00:00:00.000 and return the calendar */ def noTime = { c.setTime(c.getTime.noTime); c } } /** @return the date object for now */ def now = new Date /** @return the Calendar object for today (the TimeZone is the local TimeZone). Its time is 00:00:00.000 */ def today = Calendar.getInstance.noTime /** @return the current year */ def currentYear: Int = Calendar.getInstance.get(Calendar.YEAR) /** * @deprecated use now instead * @return the current time as a Date object */ def timeNow = new Date /** * @deprecated use today instead * @return the current Day as a Date object */ def dayNow: Date = 0.seconds.later.noTime /** alias for new Date(millis) */ def time(when: Long) = new Date(when) /** @return the month corresponding to today (0 based, relative to UTC) */ def month(in: Date): Int = { val cal = Calendar.getInstance(utc) cal.setTimeInMillis(in.getTime) cal.get(Calendar.MONTH) } /** @return the year corresponding to today (relative to UTC) */ def year(in: Date): Int = { val cal = Calendar.getInstance(utc) cal.setTimeInMillis(in.getTime) cal.get(Calendar.YEAR) } /** @return the day of month corresponding to the input date (1 based) */ def day(in: Date): Int = { val cal = Calendar.getInstance(utc) cal.setTimeInMillis(in.getTime) cal.get(Calendar.DAY_OF_MONTH) } /** The UTC TimeZone */ val utc = TimeZone.getTimeZone("UTC") /** @return the number of days since epoch converted from millis */ def millisToDays(millis: Long): Long = millis / (1000L * 60L * 60L * 24L) /** @return the number of days since epoch */ def daysSinceEpoch: Long = millisToDays(millis) /** @return the time taken to evaluate f in millis and the result */ def calcTime[T](f: => T): (Long, T) = { val start = millis val result = f (millis - start, result) } /** * Log a message with the time taken in millis to do something and retrun the result * @return the result */ def logTime[T](msg: String)(f: => T): T = { val (time, ret) = calcTime(f) Log.info(msg + " took " + time + " Milliseconds") ret } /** * @return a standard format HH:mm:ss */ val hourFormat = new SimpleDateFormat("HH:mm:ss") /** * @return the formatted time for a given Date */ def hourFormat(in: Date): String = hourFormat.format(in) /** @return a standard format for the date yyyy/MM/dd */ def dateFormatter = new SimpleDateFormat("yyyy/MM/dd") /** @return a format for the time which includes the TimeZone: HH:mm zzz*/ def timeFormatter = new SimpleDateFormat("HH:mm zzz") /** @return today's date formatted as yyyy/MM/dd */ def formattedDateNow = dateFormatter.format(now) /** @return now's time formatted as HH:mm zzz */ def formattedTimeNow = timeFormatter.format(now) /** @return a formatter for internet dates including: the day of week, the month, day of month, time and time zone */ def internetDateFormatter = { val ret = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.US) ret.setTimeZone(utc) ret } /** @return a date from a string using the internet format. Return the Epoch date if the parse is unsuccesfull */ def boxParseInternetDate(dateString: String): Box[Date] = tryo { internetDateFormatter.parse(dateString) } /** @return a date from a string using the internet format. Return the Epoch date if the parse is unsuccesfull */ def parseInternetDate(dateString: String): Date = tryo { internetDateFormatter.parse(dateString) } openOr new Date(0L) /** @return a date formatted with the internet format */ def toInternetDate(in: Date): String = internetDateFormatter.format(in) /** @return a date formatted with the internet format (from a number of millis) */ def toInternetDate(in: Long): String = internetDateFormatter.format(new Date(in)) /** @return the current time as an internet date */ def nowAsInternetDate: String = toInternetDate(millis) /** @return a Full(date) or a failure if the input couldn't be translated to date (or Empty if the input is null)*/ def toDate(in: Any): Box[Date] = { try { in match { case null => Empty case d: Date => Full(d) case lng: Long => Full(new Date(lng)) case lng: Number => Full(new Date(lng.longValue)) case Nil | Empty | None | Failure(_, _, _) => Empty case Full(v) => toDate(v) case Some(v) => toDate(v) case v :: vs => toDate(v) case s : String => tryo(internetDateFormatter.parse(s)) or tryo(dateFormatter.parse(s)) case o => toDate(o.toString) } } catch { case e => Log.debug("Error parsing date "+in, e); Failure("Bad date: "+in, Full(e), Empty) } } }
{ "content_hash": "b080b796cdd07286bde6518b7d0f6665", "timestamp": "", "source": "github", "line_count": 311, "max_line_length": 130, "avg_line_length": 38.437299035369776, "alnum_prop": 0.6695666722436004, "repo_name": "beni55/liftweb", "id": "e4721ff01fa5a04e0bc1c85fe7df5595ac264630", "size": "12556", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lift-util/src/main/scala/net/liftweb/util/TimeHelpers.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13098" }, { "name": "CSS", "bytes": "67047" }, { "name": "HTML", "bytes": "108437" }, { "name": "JavaScript", "bytes": "299266" }, { "name": "Scala", "bytes": "1479897" }, { "name": "Shell", "bytes": "10389" } ], "symlink_target": "" }
define(function(require) { 'use strict'; const __ = require('orotranslation/js/translator'); const $ = require('jquery'); require('jquery.select2'); $.fn.select2.defaults = $.extend($.fn.select2.defaults, { formatNoMatches: function() { return __('No matches found'); }, formatInputTooShort: function(input, min) { const number = min - input.length; return __('oro.ui.select2.input_too_short', {number: number}, number); }, formatInputTooLong: function(input, max) { const number = input.length - max; return __('oro.ui.select2.input_too_long', {number: number}, number); }, formatSelectionTooBig: function(limit) { return __('oro.ui.select2.selection_too_big', {limit: limit}, limit); }, formatLoadMore: function() { return __('oro.ui.select2.load_more'); }, formatSearching: function() { return __('Searching...'); } }); });
{ "content_hash": "38f04cca68935ae31e4d58151be6d74a", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 82, "avg_line_length": 34.833333333333336, "alnum_prop": 0.5483253588516747, "repo_name": "orocrm/platform", "id": "0bf307d363516f739886a41f8bfff302c667a67c", "size": "1045", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Oro/Bundle/UIBundle/Resources/public/js/select2-l10n.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "618485" }, { "name": "Gherkin", "bytes": "158217" }, { "name": "HTML", "bytes": "1648915" }, { "name": "JavaScript", "bytes": "3326127" }, { "name": "PHP", "bytes": "37828618" } ], "symlink_target": "" }
The node.js composer-api library enables access to the RESTful API for [`composer`](https://github.com/nodejitsu/composer). ## Example: ```js var composer = require('composer-api'); var client = composer.createClient({ host: 'api.nodejitsu.com', port: 80, auth: { username: 'charlie', password: 'foobar', } }); client.groups.list(function (err, result) { if (err) { console.log(err); return; } console.log(JSON.stringify(result, null, 2, true)); }); ``` ## Usage: ### api.createClient(options) This method sets up a client for connecting to `composer`. Here's a minimal example for connecting to composer as `charlie`: ``` js var client = composer.createClient({ host: 'api.nodejitsu.com', port: 80, auth: { username: 'charlie', password: 'foobar', } }); ``` The options object contains three required properties: * `auth.username`: The username for your composer account * `auth.password`: The password for your composer account * `host`: The api host (typically http://composer.nodejitsu.com. ### client Method calls are generally structured as `resource` and `action`. ``` js client.resource.action("data", function (err, result) { if (err) { throw err; } // // use the result // }); ``` Most actions take a string argument and a callback, though a few actions only take a callback. The client's methods are reflective of [`composer`](https://github.com/opsmezzo/composer/tree/master/lib/resources) resources. Here's a broad overview: * **client.config**: Manage your composer accounts. Methods include: * `config.create` * `config.get` * `config.list` * `config.update` * `config.destroy` * **client.system**: Manage your composer accounts. Methods include: * `system.create` * `system.get` * `system.list` * `system.update` * `system.destroy` * `system.removeVersion` * `system.addVersion` * `system.addOwner` * `system.removeOwner` * `system.upload` * `system.download` * **client.users**: Manage your composer accounts. Methods include: * `users.create` * `users.get` * `users.list` * `users.update` * `users.destroy` * `users.getKey` * `users.getKeys` * `users.addKey` * `users.updateKey` ## Installation This library may be installed using npm: ``` bash $ npm install composer-api ``` ## Tests All tests are included in [`composer`](https://github.com/opsmezzo/composer/tree/master/tests) to facilitate integration tests and to avoid the need for complex mocking. ## License Proprietary. Copyright (c) 2011 Nodejitsu Inc.
{ "content_hash": "5a8acba0ed4547105a14f2bdfc5ebf39", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 169, "avg_line_length": 23.135135135135137, "alnum_prop": 0.6814641744548287, "repo_name": "opsmezzo/composer-api", "id": "bef6554de9b40bf41ef3d7ca8906ac7893ee6526", "size": "2592", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node.js/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "23673" } ], "symlink_target": "" }
require 'set' require 'uri' class Content < ActiveRecord::Base include Stateful include ContentBase # TODO: Move these calls to ContentBase after_save :invalidates_cache? after_destroy lambda { |c| c.invalidates_cache?(true) } belongs_to :text_filter has_many :redirections has_many :redirects, :through => :redirections, :dependent => :destroy has_many :triggers, :as => :pending_item, :dependent => :delete_all scope :user_id, lambda { |user_id| where('user_id = ?', user_id) } scope :published, lambda { where(published: true, published_at: Time.at(0)..Time.now).order('published_at DESC') } scope :published_at, lambda {|time_params| published.where(published_at: PublifyTime.delta(*time_params)).order('published_at DESC')} scope :not_published, lambda { where('published = ?', false) } scope :draft, lambda { where('state = ?', 'draft') } scope :no_draft, lambda { where('state <> ?', 'draft').order('published_at DESC') } scope :searchstring, lambda { |search_string| tokens = search_string.split(' ').collect {|c| "%#{c.downcase}%"} where('state = ? AND ' + (['(LOWER(body) LIKE ? OR LOWER(extended) LIKE ? OR LOWER(title) LIKE ?)']*tokens.size).join(' AND '), "published", *tokens.collect{ |token| [token] * 3 }.flatten) } scope :already_published, lambda { where('published = ? AND published_at < ?', true, Time.now).order(default_order) } scope :published_at_like, lambda { |date_at| where(:published_at => ( if date_at =~ /\d{4}-\d{2}-\d{2}/ DateTime.strptime(date_at, '%Y-%m-%d').beginning_of_day..DateTime.strptime(date_at, '%Y-%m-%d').end_of_day elsif date_at =~ /\d{4}-\d{2}/ DateTime.strptime(date_at, '%Y-%m').beginning_of_month..DateTime.strptime(date_at, '%Y-%m').end_of_month elsif date_at =~ /\d{4}/ DateTime.strptime(date_at, '%Y').beginning_of_year..DateTime.strptime(date_at, '%Y').end_of_year else date_at end) )} serialize :whiteboard def shorten_url return unless self.published r = Redirect.new r.from_path = r.shorten r.to_path = self.permalink_url # This because updating self.redirects.first raises ActiveRecord::ReadOnlyRecord unless (red = self.redirects.first).nil? return if red.to_path == self.permalink_url r.from_path = red.from_path red.destroy self.redirects.clear # not sure we need this one end self.redirects << r end def self.find_already_published(limit) where('published_at < ?', Time.now).limit(1000).order('created_at DESC') end def self.search_with(params) params ||= {} scoped = self.unscoped if params[:searchstring].present? scoped = scoped.searchstring(params[:searchstring]) end if params[:published_at].present? && %r{(\d\d\d\d)-(\d\d)} =~ params[:published_at] scoped = scoped.published_at_like(params[:published_at]) end if params[:user_id].present? && params[:user_id].to_i > 0 scoped = scoped.user_id(params[:user_id]) end if params[:published].present? scoped = scoped.published if params[:published].to_s == '1' scoped = scoped.not_published if params[:published].to_s == '0' end scoped end def whiteboard self[:whiteboard] ||= Hash.new end def withdraw! self.withdraw self.save! end def link_to_author? !user.email.blank? && blog.link_to_author end def published_at self[:published_at] || self[:created_at] end def get_rss_description return "" unless blog.rss_description return "" unless respond_to?(:user) && self.user && self.user.name rss_desc = blog.rss_description_text rss_desc.gsub!('%author%', self.user.name) rss_desc.gsub!('%blog_url%', blog.base_url) rss_desc.gsub!('%blog_name%', blog.blog_name) rss_desc.gsub!('%permalink_url%', self.permalink_url) return rss_desc end # TODO: Perhaps permalink_url should produce valid URI's instead of IRI's def normalized_permalink_url @normalized_permalink_url ||= Addressable::URI.parse(permalink_url).normalize end def short_url # Double check because of crappy data in my own old database return unless self.published and self.redirects.size > 0 self.redirects.last.to_url end end class Object def to_text_filter TextFilter.find_by_name(self.to_s) || TextFilter.find_by_name('none') end end class ContentTextHelpers include ActionView::Helpers::UrlHelper include ActionView::Helpers::TagHelper include ActionView::Helpers::SanitizeHelper include ActionView::Helpers::TextHelper extend ActionView::Helpers::SanitizeHelper::ClassMethods end
{ "content_hash": "987abe00d1656c82de571ce7c283aaf0", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 135, "avg_line_length": 31.768707482993197, "alnum_prop": 0.6618843683083512, "repo_name": "rubytribe/fitting_room_blog", "id": "70b0595a727ba822cbeb7d11b0d58e3739ecd111", "size": "4670", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/models/content.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "803198" }, { "name": "JavaScript", "bytes": "164677" }, { "name": "Perl", "bytes": "866" }, { "name": "Ruby", "bytes": "1538886" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>toInfo method - KRootingTable class - hetimatorrent library - Dart API</title> <!-- required because all the links are pseudo-absolute --> <base href="../.."> <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="static-assets/prettify.css"> <link rel="stylesheet" href="static-assets/css/bootstrap.min.css"> <link rel="stylesheet" href="static-assets/styles.css"> <meta name="description" content="API docs for the toInfo method from the KRootingTable class, for the Dart programming language."> <link rel="icon" href="static-assets/favicon.png"> <!-- Do not remove placeholder --> <!-- Header Placeholder --> </head> <body> <div id="overlay-under-drawer"></div> <header class="container-fluid" id="title"> <nav class="navbar navbar-fixed-top"> <div class="container"> <button id="sidenav-left-toggle" type="button">&nbsp;</button> <ol class="breadcrumbs gt-separated hidden-xs"> <li><a href="index.html">hetimatorrent</a></li> <li><a href="hetimatorrent/hetimatorrent-library.html">hetimatorrent</a></li> <li><a href="hetimatorrent/KRootingTable-class.html">KRootingTable</a></li> <li class="self-crumb">toInfo</li> </ol> <div class="self-name">toInfo</div> </div> </nav> <div class="container masthead"> <ol class="breadcrumbs gt-separated visible-xs"> <li><a href="index.html">hetimatorrent</a></li> <li><a href="hetimatorrent/hetimatorrent-library.html">hetimatorrent</a></li> <li><a href="hetimatorrent/KRootingTable-class.html">KRootingTable</a></li> <li class="self-crumb">toInfo</li> </ol> <div class="title-description"> <h1 class="title"> <div class="kind">method</div> toInfo </h1> <!-- p class="subtitle"> </p --> </div> <ul class="subnav"> <li><a href="hetimatorrent/KRootingTable/toInfo.html#source">Source</a></li> </ul> </div> </header> <div class="container body"> <div class="col-xs-6 col-sm-3 sidebar sidebar-offcanvas-left"> <h5><a href="index.html">hetimatorrent</a></h5> <h5><a href="hetimatorrent/hetimatorrent-library.html">hetimatorrent</a></h5> <h5><a href="hetimatorrent/KRootingTable-class.html">KRootingTable</a></h5> <ol> <li class="section-title"><a href="hetimatorrent/KRootingTable-class.html#instance-properties">Properties</a></li> <li><a href="hetimatorrent/KRootingTable/ownerKId.html">ownerKId</a> </li> <li class="section-title"><a href="hetimatorrent/KRootingTable-class.html#constructors">Constructors</a></li> <li><a href="hetimatorrent/KRootingTable/KRootingTable.html">KRootingTable</a></li> <li class="section-title"><a href="hetimatorrent/KRootingTable-class.html#methods">Methods</a></li> <li><a href="hetimatorrent/KRootingTable/clear.html">clear</a> </li> <li><a href="hetimatorrent/KRootingTable/findNode.html">findNode</a> </li> <li><a href="hetimatorrent/KRootingTable/getRootingTabkeIndex.html">getRootingTabkeIndex</a> </li> <li><a href="hetimatorrent/KRootingTable/toInfo.html">toInfo</a> </li> <li><a href="hetimatorrent/KRootingTable/update.html">update</a> </li> </ol> </div><!--/.sidebar-offcanvas--> <div class="col-xs-12 col-sm-9 col-md-6 main-content"> <section class="multi-line-signature"> <span class="returntype">String</span> <span class="name ">toInfo</span>( ) </section> <section class="desc markdown"> <p class="no-docs">Not documented.</p> </section> <section class="summary source-code" id="source"> <h2>Source</h2> <pre><code class="prettyprint lang-dart">String toInfo() { StringBuffer buffer = new StringBuffer(); buffer.write(&quot;${ownerKId.toString()}\n&quot;); for (int j = 0; j &lt; _kBuckets.length; j++) { int bucketLength = _kBuckets[j].length; if (bucketLength == 0) { continue; } buffer.write(&quot;[${j}] len:${bucketLength}:## &quot;); for (int i = 0; i &lt; bucketLength; i++) { buffer.write(_kBuckets[j][i].toString()); buffer.write(&quot;(^_^)&quot;); } buffer.write(&quot;\n&quot;); } return buffer.toString(); }</code></pre> </section> </div> <!-- /.main-content --> </div> <!-- container --> <footer> <div class="container-fluid"> <div class="container"> <p class="text-center"> <span class="no-break"> hetimatorrent 0.0.1 api docs </span> &bull; <span class="copyright no-break"> <a href="https://www.dartlang.org"> <img src="static-assets/favicon.png" alt="Dart" title="Dart"width="16" height="16"> </a> </span> &bull; <span class="copyright no-break"> <a href="http://creativecommons.org/licenses/by-sa/4.0/">cc license</a> </span> </p> </div> </div> </footer> <script src="static-assets/prettify.js"></script> <script src="static-assets/script.js"></script> <!-- Do not remove placeholder --> <!-- Footer Placeholder --> </body> </html>
{ "content_hash": "098efe3b1e57ca70a691940087034027", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 135, "avg_line_length": 35.88819875776397, "alnum_prop": 0.5924195223260644, "repo_name": "kyorohiro/dart_hetimatorrent", "id": "232cf4251d8bb7dd02bfaa7d4db17369eb612ed0", "size": "5778", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/api/hetimatorrent/KRootingTable/toInfo.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "165425" }, { "name": "Dart", "bytes": "453550" }, { "name": "HTML", "bytes": "19043" }, { "name": "JavaScript", "bytes": "2312" } ], "symlink_target": "" }
module JumioRock class EmbedNetverifyParams < NetverifyParams attr_reader :merchantIdScanReference, :successUrl, :errorUrl attr_accessor :enabledFields, :authorizationTokenLifetime, :merchantReportingCriteria, :callbackUrl, :locale, :clientIp, :customerId, :firstName, :lastName, :country, :usState, :expiry, :number, :dob, :idType, :personalNumber, :mrzCheck, :additionalInformation, :captureMethod def initialize(scan_reference, success_url, error_url) @merchantIdScanReference = scan_reference @successUrl = success_url @errorUrl = error_url end end end
{ "content_hash": "1d56f4fefd8e7fe12f1ebd9fdd7db7c1", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 115, "avg_line_length": 34.5, "alnum_prop": 0.7246376811594203, "repo_name": "therocktrading/JumioRock", "id": "6fff833be302394aa4c619d4d07ed6e96b31f36f", "size": "621", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/jumio_rock/embed_netverify_params.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "21852" } ], "symlink_target": "" }
package com.antsoft.ant.designer.classdesigner; import java.awt.*; import java.awt.event.*; import java.util.Vector; import java.util.StringTokenizer; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import com.antsoft.ant.browser.packagebrowser.*; import com.antsoft.ant.codecontext.CodeContext; import com.antsoft.ant.manager.projectmanager.ProjectManager; import com.antsoft.ant.util.*; import com.antsoft.ant.pool.librarypool.LibraryPool; import com.antsoft.ant.pool.classpool.ClassPool; /** * @author Kim sang kyun */ public class GeneralPanel extends JPanel{ private JTextField packageTf, classTf, extendsTf, docTf; private String extendsPackageName; private JList importList, implementsList; private JButton importAddBtn, importRemoveBtn, implementsAddBtn, implementsRemoveBtn, extendsFindBtn, packageFindBtn; private JComboBox javaDocCombo; private DefaultListModel importM; private ImplementsListModel implementsM; private JScrollPane importListScrollPane, implementsListScrollPane; private Vector docM; private String see, author, version, since, desc; private JCheckBox publicBtn, abstractBtn, finalBtn; private CDGeneralInfo info; private JavaDocInfo javaDoc = new JavaDocInfo(); public GeneralPanel(CDGeneralInfo cdGeneralInfo) { this.info = cdGeneralInfo; this.info.setJavaDoc(javaDoc); try { jbInit(); } catch (Exception ex) { ex.printStackTrace(); } } void jbInit() throws Exception { setBorder(BorderList.etchedBorder5); ActionEventHandler actionEventHandler = new ActionEventHandler(); ListSelectEventHandler listHandler = new ListSelectEventHandler(); DocumentListener docListener = new DocumentEventHandler(); //package label JLabel pkgLbl = new JLabel(" Package"); pkgLbl.setPreferredSize(new Dimension(84,20)); pkgLbl.setFont(FontList.regularFont); pkgLbl.setForeground(Color.black); packageFindBtn = new JButton(".."); packageFindBtn.setPreferredSize(new Dimension(20,20)); packageFindBtn.setFont(FontList.regularFont); packageFindBtn.setActionCommand("PackageFind"); packageFindBtn.addActionListener(actionEventHandler); //package textfiled, button packageTf = new JTextField(13); //packageTf.setPreferredSize(new Dimension(150,20)); packageTf.getDocument().putProperty("TYPE", "PACKAGE"); packageTf.getDocument().addDocumentListener(docListener); //by lila JPanel p1 = new JPanel(); p1.setLayout(new FlowLayout(FlowLayout.LEFT)); p1.add(pkgLbl); p1.add(packageTf); p1.add(packageFindBtn); //import label JLabel importLbl = new JLabel(" Import"); importLbl.setFont(FontList.regularFont); importLbl.setForeground(Color.black); //import add, remove button importAddBtn = new JButton("Add"); importAddBtn.setFont(FontList.regularFont); importAddBtn.setActionCommand("ImportAdd"); importAddBtn.addActionListener(actionEventHandler); importRemoveBtn = new JButton("Remove"); importRemoveBtn.setFont(FontList.regularFont); importRemoveBtn.setActionCommand("ImportRemove"); importRemoveBtn.addActionListener(actionEventHandler); //by lila JPanel p2 = new JPanel(); p2.setLayout(new GridLayout(3,1)); p2.add(importLbl); p2.add(importAddBtn); p2.add(importRemoveBtn); importM = new DefaultListModel(); importList = new JList(importM); importList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); importList.setSelectedIndex(0); importList.addListSelectionListener(listHandler); importListScrollPane = new JScrollPane(importList); //importList.setPreferredSize(new Dimension(200,150)); importListScrollPane.setPreferredSize(new Dimension(170,150)); JPanel p3 = new JPanel(); p3.setLayout(new BorderLayout()); p3.add(p2,BorderLayout.NORTH); p3.add(new JPanel(),BorderLayout.CENTER); JPanel p4 = new JPanel(); p4.setLayout(new BorderLayout(5,0)); p4.add(p3,BorderLayout.WEST); p4.add(importListScrollPane,BorderLayout.CENTER); JPanel p5 = new JPanel(); p5.setLayout(new BorderLayout()); p5.setBorder(new EtchedBorder()); p5.add(p1,BorderLayout.NORTH); p5.add(p4,BorderLayout.CENTER); p5.add(new JPanel(),BorderLayout.EAST); p5.add(new JPanel(),BorderLayout.WEST); p5.add(new JPanel(),BorderLayout.SOUTH); JPanel leftPanel = new JPanel(); leftPanel.setLayout(new FlowLayout(FlowLayout.CENTER)); leftPanel.add(p5); //extends label JLabel extendsLbl = new JLabel(" Extends"); extendsLbl.setFont(FontList.regularFont); extendsLbl.setForeground(Color.black); extendsLbl.setPreferredSize(new Dimension(84,20)); extendsFindBtn = new JButton(".."); extendsFindBtn.setFont(FontList.regularFont); extendsFindBtn.setPreferredSize(new Dimension(20,20)); extendsFindBtn.setActionCommand("ExtendsFind"); extendsFindBtn.addActionListener(actionEventHandler); //extends textfield, find button extendsTf = new JTextField(13); extendsTf.getDocument().putProperty("TYPE", "EXTENDS"); extendsTf.getDocument().addDocumentListener(docListener); //by lila JPanel p6 = new JPanel(); p6.setLayout(new FlowLayout(FlowLayout.LEFT)); p6.add(extendsLbl); p6.add(extendsTf); p6.add(extendsFindBtn); //implements label JLabel implementsLbl = new JLabel(" Implements "); implementsLbl.setFont(FontList.regularFont); implementsLbl.setForeground(Color.black); implementsLbl.setPreferredSize(new Dimension(74,20)); //implements add, remove button implementsAddBtn = new JButton("Add"); implementsAddBtn.setFont(FontList.regularFont); implementsAddBtn.setActionCommand("ImplementsAdd"); implementsAddBtn.addActionListener(actionEventHandler); implementsRemoveBtn = new JButton("Remove"); implementsRemoveBtn.setFont(FontList.regularFont); implementsRemoveBtn.setActionCommand("ImplementsRemove"); implementsRemoveBtn.addActionListener(actionEventHandler); //by lila JPanel p7 = new JPanel(); p7.setLayout(new GridLayout(3,1)); p7.add(implementsLbl); p7.add(implementsAddBtn); p7.add(implementsRemoveBtn); JPanel p8 = new JPanel(); p8.setLayout(new BorderLayout()); p8.add(p7,BorderLayout.NORTH); p8.add(createDummyPanel(), BorderLayout.CENTER); //implements List implementsM = new ImplementsListModel(); implementsList = new JList(implementsM); implementsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); implementsList.setSelectedIndex(0); implementsList.addListSelectionListener(listHandler); implementsListScrollPane = new JScrollPane(implementsList); implementsListScrollPane.setPreferredSize(new Dimension(170,150)); //by lila JPanel p9 = new JPanel(); p9.setLayout(new BorderLayout(5,0)); p9.add(p8,BorderLayout.WEST); p9.add(implementsListScrollPane,BorderLayout.CENTER); JPanel p10 = new JPanel(); p10.setLayout(new BorderLayout()); p10.setBorder(new EtchedBorder()); p10.add(p6,BorderLayout.NORTH); p10.add(p9,BorderLayout.CENTER); p10.add(createDummyPanel(),BorderLayout.EAST); p10.add(createDummyPanel(),BorderLayout.WEST); p10.add(createDummyPanel(),BorderLayout.SOUTH); JPanel rightPanel = new JPanel(); rightPanel.setLayout(new FlowLayout(FlowLayout.CENTER)); rightPanel.add(p10); //class modifier JLabel classModifierLbl = new JLabel("Class Modifier"); classModifierLbl.setPreferredSize(new Dimension(90,20)); classModifierLbl.setFont(FontList.regularFont); classModifierLbl.setForeground(Color.black); //public, abstract, final Checkbox, RadioButton publicBtn = new JCheckBox("public", true); publicBtn.setPreferredSize(new Dimension(55,20)); publicBtn.setFont(FontList.regularFont); publicBtn.setActionCommand("PUBLIC_BUTTON"); publicBtn.addActionListener(actionEventHandler); abstractBtn = new JCheckBox("abstract", false); abstractBtn.setPreferredSize(new Dimension(70,20)); abstractBtn.setFont(FontList.regularFont); abstractBtn.setActionCommand("ABSTRACT_BUTTON"); abstractBtn.addActionListener(actionEventHandler); finalBtn = new JCheckBox("final", false); finalBtn.setPreferredSize(new Dimension(70,20)); finalBtn.setFont(FontList.regularFont); finalBtn.setActionCommand("FINAL_BUTTON"); finalBtn.addActionListener(actionEventHandler); //class name label, textfield JLabel classLbl = new JLabel("Class Name"); //classLbl.setPreferredSize(new Dimension(60,20)); classLbl.setFont(FontList.regularFont); classLbl.setForeground(Color.black); classTf = new JTextField(15); classTf.getDocument().putProperty("TYPE", "CLASS"); classTf.getDocument().addDocumentListener(docListener); JLabel label = new JLabel(" "); label.setPreferredSize(new Dimension(17,20)); //by lila JPanel p11 = new JPanel(); p11.setLayout(new FlowLayout(FlowLayout.LEFT)); p11.add(classModifierLbl); p11.add(publicBtn); p11.add(abstractBtn); p11.add(finalBtn); //p11.add(label); p11.add(classLbl); p11.add(classTf); //javadoc docM = new Vector(); docM.addElement("JavaDoc"); docM.addElement("See"); docM.addElement("Author"); docM.addElement("Version"); docM.addElement("Since"); javaDocCombo = new JComboBox(docM); javaDocCombo.setFont(FontList.regularFont); javaDocCombo.setSelectedItem(docM.elementAt(0)); javaDocCombo.setActionCommand("JavaDoc"); javaDocCombo.addActionListener(actionEventHandler); docTf = new JTextField(40); docTf.getDocument().putProperty("TYPE", "JAVADOC"); docTf.getDocument().addDocumentListener(docListener); docTf.setText("JavaDoc Comment Setting"); docTf.setEditable(false); //by lila JPanel p12 = new JPanel(); p12.setLayout(new FlowLayout(FlowLayout.LEFT)); p12.add(javaDocCombo); p12.add(new JLabel(" ")); p12.add(docTf); JPanel p13 = new JPanel(); p13.setLayout(new GridLayout(2,1)); p13.add(p11); p13.add(p12); JPanel p14 = new JPanel(); p14.setLayout(new BorderLayout()); p14.setBorder(new EtchedBorder()); p14.add(p13,BorderLayout.CENTER); p14.add(createDummyPanel(),BorderLayout.WEST); p14.add(createDummyPanel(),BorderLayout.EAST); JPanel bottom = new JPanel(); bottom.setLayout(new FlowLayout(FlowLayout.CENTER)); bottom.add(p14); this.setLayout(new FlowLayout(FlowLayout.LEFT)); add(leftPanel); add(rightPanel); add(bottom); /* p1.setBackground(new Color(166, 201, 213)); p2.setBackground(new Color(166, 201, 213)); p3.setBackground(new Color(166, 201, 213)); p4.setBackground(new Color(166, 201, 213)); p5.setBackground(new Color(166, 201, 213)); p6.setBackground(new Color(166, 201, 213)); p7.setBackground(new Color(166, 201, 213)); p8.setBackground(new Color(166, 201, 213)); p9.setBackground(new Color(166, 201, 213)); p10.setBackground(new Color(166, 201, 213)); p11.setBackground(new Color(166, 201, 213)); p12.setBackground(new Color(166, 201, 213)); p13.setBackground(new Color(166, 201, 213)); p14.setBackground(new Color(166, 201, 213)); this.setBackground(new Color(166, 201, 213)); */ } private JPanel createDummyPanel(){ JPanel p = new JPanel(); return p; } /** * packageName TextField¿¡ packageNameÀ» »ðÀÔÇÑ´Ù. * * @param packagename »ðÀ﵃ package name */ public void setPackageName(String packagename){ packageTf.setText(packagename); packageTf.setToolTipText(packagename); } public void removeImportList(int index){ String packageName = null; String removedElement = (String)importM.elementAt(index); info.removeImportAt(index); if(removedElement.endsWith("*")){ packageName = removedElement.substring(0, removedElement.lastIndexOf("*")-1); if(extendsPackageName!=null && extendsPackageName.equals(packageName)){ extendsTf.setText(packageName + "." + extendsTf.getText()); } String interfacePackage = null; for(int i=0; i<implementsM.getSize(); i++){ interfacePackage = (String)implementsM.getPackageName(i); if(interfacePackage.equals(packageName)){ String newName = packageName + "." + implementsM.getElementAt(i); implementsM.setElementAt(newName, i); info.setImplementsAt(newName, i); } } } else{ packageName = removedElement.substring(0, removedElement.lastIndexOf(".")); if(extendsPackageName != null && extendsPackageName.equals(removedElement)){ extendsTf.setText(packageName + "." + extendsTf.getText()); extendsPackageName = ""; } String interfacePackage = null; for(int i=0; i<implementsM.getSize(); i++){ interfacePackage = (String)implementsM.getPackageName(i); if(interfacePackage.equals(removedElement)){ implementsM.setElementAt(packageName + "." + implementsM.getElementAt(i), i); } } } importM.removeElementAt(index); implementsList.repaint(); importListScrollPane.validate(); } /** * ImportList DataModel¿¡ data¸¦ »ðÀÔÇÑ´Ù * * @param importName »ðÀ﵃ package ¶Ç´Â class name */ public void addImportList(String importName, boolean all){ importM.addElement(importName); /* GeneralInfo°´Ã¼¿¡ ÀúÀåÇÑ´Ù */ info.addImport(importName); /** package nameÀ» ±¸Çؼ­ °°Àº package¿¡ ¼ÓÇÑ classµéÀ» extend Çϰųª implementsÇϸé short nameÀ¸·Î ¹Ù²Û´Ù */ String packageName = null; String oldExtends = extendsTf.getText(); if(all){ packageName = importName.substring(0, importName.lastIndexOf("*")-1); if(oldExtends.startsWith(packageName)){ extendsPackageName = packageName; extendsTf.setText(oldExtends.substring(oldExtends.lastIndexOf(".")+1)); } String interfaceName = null; for(int i=0; i<implementsM.getSize(); i++){ interfaceName = (String)implementsM.getElementAt(i); if(interfaceName.startsWith(packageName)){ String newName = interfaceName.substring(interfaceName.lastIndexOf(".")+1); implementsM.setElementAt(newName, i); info.setImplementsAt(newName, i); implementsM.setPackageAt(packageName, i); } } } else{ packageName = importName.substring(0, importName.lastIndexOf(".")); if(oldExtends.equals(importName)){ extendsPackageName = importName; extendsTf.setText(oldExtends.substring(oldExtends.lastIndexOf(".")+1)); } String interfaceName = null; for(int i=0; i<implementsM.getSize(); i++){ interfaceName = (String)implementsM.getElementAt(i); if(interfaceName.equals(importName)){ String newName = interfaceName.substring(interfaceName.lastIndexOf(".")+1); implementsM.setElementAt(newName, i); info.setImplementsAt(newName, i); implementsM.setPackageAt(importName, i); } } } implementsList.repaint(); importListScrollPane.validate(); } /** * ExtendsName TextField¿¡ class nameÀ» »ðÀÔÇÑ´Ù. * * @param extendsName »ðÀ﵃ class name */ public void setExtendsName(String extendsName){ extendsTf.setText(extendsName); extendsTf.setToolTipText(extendsName); } /** * ImplementsList DataModel¿¡ data¸¦ »ðÀÔÇÑ´Ù * * @param implementsName interface name */ public void addImplementsList(String interfaceName){ implementsM.addElement(interfaceName); info.addImplements(interfaceName); implementsListScrollPane.validate(); } public void setSee(String seeData){ see = seeData; } public String getSee(){ return see; } public void setAuthor(String authorData){ author = authorData; } public String getAuthor(){ return author; } public void setVersion(String versionData){ version = versionData; } public String getVersion(){ return version; } public void setSince(String sinceData){ since = sinceData; } public String getSince(){ return since; } public void setDescription(String descData){ desc = descData; } public String getDescription(){ return desc; } public String getClassName(){ return classTf.getText(); } class ImplementsListModel extends AbstractListModel{ private Vector interfaceData, packageData; /** default constructor */ public ImplementsListModel(){ interfaceData = new Vector(); packageData = new Vector(); } public Object getElementAt(int index){ return interfaceData.elementAt(index); } public boolean contains(Object obj){ return interfaceData.contains(obj); } public void setPackageAt(String packageName, int index){ packageData.setElementAt(packageName, index); } public void setElementAt(String interfaceName, int index){ interfaceData.setElementAt(interfaceName, index); } public void removeElementAt(int index){ interfaceData.removeElementAt(index); packageData.removeElementAt(index); } public Object getPackageName(int index){ return packageData.elementAt(index); } public int getSize(){ return interfaceData.size(); } public void removeAllElements(){ interfaceData.removeAllElements(); packageData.removeAllElements(); } public void addElement(String interfaceName){ int index = interfaceData.size(); interfaceData.addElement(interfaceName); packageData.addElement(""); fireIntervalAdded(this, index, index); } } /** * Radio buttonÀÇ »óŰ¡ º¯ÇßÀ»¶§ ó¸®ÇØÁØ´Ù */ class ChangeEventHandler implements ChangeListener{ public void stateChanged(ChangeEvent e){ } } /** * Document Listener. text field³ª textarea»ó¿¡¼­ »ç¿ëÀÚ°¡ º¯È­¸¦ * °¡ÇßÀ»¶§ Áï°¢ Á¤º¸¸¦ º¯°æ½ÃÄÑÁØ´Ù */ class DocumentEventHandler implements DocumentListener{ public void process(DocumentEvent e){ String type = (String)e.getDocument().getProperty("TYPE"); if(type.equals("PACKAGE")){ if(packageTf.getText().equals("")) info.setPackageName(null); else info.setPackageName(packageTf.getText()); } else if(type.equals("EXTENDS")){ if(extendsTf.getText().equals("")) info.setSuperName(null); else info.setSuperName(extendsTf.getText()); } else if(type.equals("CLASS")){ if(classTf.getText().equals("")) info.setClassName(null); else info.setClassName(classTf.getText()); } else if(type.equals("JAVADOC")){ String item = (String)javaDocCombo.getSelectedItem(); if(item.equals("See")){ if(docTf.getText().equals("")){ setSee(null); javaDoc.setSee(null); } else{ setSee(docTf.getText()); javaDoc.setSee(docTf.getText()); } } else if(item.equals("Author")){ if(docTf.getText().equals("")){ setAuthor(null); javaDoc.setAuthor(null); } else{ setAuthor(docTf.getText()); javaDoc.setAuthor(docTf.getText()); } } else if(item.equals("Version")){ if(docTf.getText().equals("")) { setVersion(null); javaDoc.setVersion(null); } else{ setVersion(docTf.getText()); javaDoc.setVersion(docTf.getText()); } } else if(item.equals("Since")){ if(docTf.getText().equals("")) { setSince(null); javaDoc.setSince(null); } else{ setSince(docTf.getText()); javaDoc.setSince(docTf.getText()); } } else if(item.equals("Desc")){ if(docTf.getText().equals("")) { setDescription(null); javaDoc.setDescription(null); } else{ setDescription(docTf.getText()); javaDoc.setDescription(docTf.getText()); } } } } public void insertUpdate(DocumentEvent e){ process(e); } public void changedUpdate(DocumentEvent e){ process(e); } public void removeUpdate(DocumentEvent e){ process(e); } } //List Selection Event Handler class ListSelectEventHandler implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { } } //Action event handler class ActionEventHandler implements ActionListener { private String actionCommand; private final String MESSAGE = "Set Project's JDK Property"; public void actionPerformed(ActionEvent e){ actionCommand = e.getActionCommand(); if(actionCommand.equals("PackageFind")){ PackageBrowser pvf = new PackageBrowser(ClassDesigner.parent, "User Package Browser", true); if(pvf.showUserPackage()) pvf.setVisible(true); else return; if(pvf.isOK()){ String packageName = pvf.getSelectedPackageItem(); //È­¸é¿¡ packagename setting setPackageName(packageName); } } else if(actionCommand.equals("ImportAdd")){ //Jdk°¡ ¼³Á¤µÇ¾î ÀÖ´ÂÁö üũÇÑ´Ù if(LibraryPool.getProjectLibrarys(ProjectManager.getCurrentProject().getProjectName()) == null){ JOptionPane.showMessageDialog(null, MESSAGE, "alert", JOptionPane.ERROR_MESSAGE); return; } final PackageBrowser pvf = new PackageBrowser(ClassDesigner.parent, "User Package Browser", true); pvf.setMultiSelectionListener(new MultiSelectionListener(){ public void selectionPerformed(String selectedItem){ if(selectedItem != null && importM.contains(selectedItem) == false){ addImportList(selectedItem, false); } else{ String packageName = pvf.getSelectedPackageItem(); if(packageName != null){ String importName = packageName + ".*"; if(importM.contains(importName) == false) addImportList(importName, true); }} }}); pvf.setVisible(true); } else if(actionCommand.equals("ImportRemove")){ if(((DefaultListModel)importList.getModel()).getSize() > 0){ int index = importList.getSelectedIndex(); if(index > -1){ removeImportList(index); } } } else if(actionCommand.equals("ExtendsFind")){ //Jdk°¡ ¼³Á¤µÇ¾î ÀÖ´ÂÁö üũÇÑ´Ù if(LibraryPool.getProjectLibrarys(ProjectManager.getCurrentProject().getProjectName()) == null){ JOptionPane.showMessageDialog(null, MESSAGE, "alert", JOptionPane.ERROR_MESSAGE); return; } final PackageBrowser pvf = new PackageBrowser(ClassDesigner.parent, "User Package Browser", true); pvf.setVisible(true); if(pvf.isOK() == true){ String fullClassName = pvf.getSelectedClassItem(); if(fullClassName == null) return; boolean isInterface = false; try{ isInterface = ClassPool.isInterface(fullClassName); } catch(ClassNotFoundException e1){ e1.printStackTrace(); } if( (fullClassName != null) && !isInterface){ String packageAll = fullClassName.substring(0, fullClassName.lastIndexOf(".")+1) + "*"; if(importM.indexOf(fullClassName) != -1 || importM.indexOf(packageAll) != -1){ setExtendsName(fullClassName.substring(fullClassName.lastIndexOf(".")+1)); }else{ setExtendsName(fullClassName); } } else if(fullClassName != null){ JOptionPane.showMessageDialog(null, "You Selected Interface", "Error", JOptionPane.ERROR_MESSAGE, ClassDesigner.errorIcon ); } } } else if(actionCommand.equals("ImplementsAdd")){ //Jdk°¡ ¼³Á¤µÇ¾î ÀÖ´ÂÁö üũÇÑ´Ù if(LibraryPool.getProjectLibrarys(ProjectManager.getCurrentProject().getProjectName()) == null){ JOptionPane.showMessageDialog(null, MESSAGE, "alert", JOptionPane.ERROR_MESSAGE); return; } final PackageBrowser pvf = new PackageBrowser(ClassDesigner.parent, "User Package Browser", true); pvf.setMultiSelectionListener(new MultiSelectionListener(){ public void selectionPerformed(String selectedItem){ if(selectedItem != null){ boolean isInterface = false; try{ isInterface = ClassPool.isInterface(selectedItem); } catch(ClassNotFoundException e1){ e1.printStackTrace(); } if(!isInterface){ JOptionPane.showMessageDialog(null, "It is not Interface", "Error", JOptionPane.ERROR_MESSAGE, ClassDesigner.errorIcon ); return; } String packageAll = selectedItem.substring(0, selectedItem.lastIndexOf(".")+1) + "*"; if(importM.indexOf(selectedItem) != -1 || importM.indexOf(packageAll) != -1){ if(!implementsM.contains(selectedItem.substring(selectedItem.lastIndexOf(".")+1))){ addImplementsList(selectedItem.substring(selectedItem.lastIndexOf(".")+1)); } }else{ if(implementsM.contains(selectedItem) == false) addImplementsList(selectedItem); }}}}); pvf.setVisible(true); } else if(actionCommand.equals("ImplementsRemove")){ if(((ImplementsListModel)implementsList.getModel()).getSize() > 0){ int index = implementsList.getSelectedIndex(); if(index > -1){ implementsM.removeElementAt(index); info.removeImplementsAt(index); } implementsListScrollPane.validate(); implementsListScrollPane.repaint(); } } else if(actionCommand.equals("JavaDoc")){ String item = (String)javaDocCombo.getSelectedItem(); if(item.equals("See")){ docTf.setEditable(true); docTf.setText(getSee()); } else if(item.equals("Author")){ docTf.setEditable(true); docTf.setText(getAuthor()); } else if(item.equals("Version")){ docTf.setEditable(true); docTf.setText(getVersion()); } else if(item.equals("Since")){ docTf.setEditable(true); docTf.setText(getSince()); } else if(item.equals("JavaDoc")){ docTf.setEditable(false); docTf.setText("JavaDoc Comment Setting"); } } else if(actionCommand.equals("PUBLIC_BUTTON")){ info.setPublic(publicBtn.isSelected()); } else if(actionCommand.equals("ABSTRACT_BUTTON")){ info.setAbstract(abstractBtn.isSelected()); } else if(actionCommand.equals("FINAL_BUTTON")){ info.setFinal(finalBtn.isSelected()); } } } }
{ "content_hash": "71e9ab0f0abfb71b631cc688c2bfe24e", "timestamp": "", "source": "github", "line_count": 817, "max_line_length": 142, "avg_line_length": 34.62423500611995, "alnum_prop": 0.636100113122172, "repo_name": "FJplant/AntIDE", "id": "3f32f3e02adbf8a33a955dd7be829f1a5f9e8d51", "size": "31914", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/antsoft/ant/designer/classdesigner/GeneralPanel.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1806" }, { "name": "HTML", "bytes": "27541" }, { "name": "Java", "bytes": "4609672" }, { "name": "Shell", "bytes": "5614" } ], "symlink_target": "" }
"use strict"; module.exports = (sequelize, DataTypes) => { return sequelize.define("User", { id: { type: DataTypes.INTEGER, primaryKey: true }, firstName: DataTypes.STRING, lastName: DataTypes.STRING, email: DataTypes.STRING, password: DataTypes.STRING }, { classMethods: {} }); };
{ "content_hash": "7bdcbc38bf00aa47821f303fe1a93919", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 44, "avg_line_length": 24.866666666666667, "alnum_prop": 0.5442359249329759, "repo_name": "hhimanshu/contactz", "id": "ae7d5998448291a1022d465441c0815f66c0e3b9", "size": "373", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/models/user.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "9502" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace MuteFm.UiPackage { public partial class MusicInfoEditForm : Form { private SoundPlayerInfo _musicInfo = null; Dictionary<string, string> _commands = new Dictionary<string, string>(); public MusicInfoEditForm() { InitializeComponent(); this.Text = Constants.ProgramName + " - " + "Edit Sound Player Info"; } public MusicInfoEditForm(SoundPlayerInfo playerInfo, bool editable) { InitializeComponent(); this.Text = Constants.ProgramName + " - " + "Edit Sound Player Info"; #if NOAWE mWebsiteRadioButton.Text += " (Requires mute.fm+)"; #endif if (playerInfo == null) { this.Text = Constants.ProgramName + " - Add Sound Info"; _musicInfo = new SoundPlayerInfo(); #if !NOAWE _musicInfo.IsWeb = true; mWebsiteRadioButton.Checked = true; mProgramRadioButton.Enabled = true; mWebsiteRadioButton.Enabled = true; #else _musicInfo.IsWeb = false; mWebsiteRadioButton.Enabled = false; mProgramRadioButton.Enabled = true; mProgramRadioButton.Checked = true; mWebsiteRadioButton_CheckedChanged_1(null, null); #endif this.mIgnoreAutomuteCheckbox.Checked = false; this.mIgnoreAutomuteCheckbox.Visible = !_musicInfo.IsWeb; mStopIfMutedTooLongCheckbox.Checked = true; _commands["OnLoad"] = ""; _commands["Play"] = ""; _commands["Pause"] = ""; _commands["PrevTrack"] = ""; _commands["NextTrack"] = ""; _commands["Like"] = ""; _commands["Dislike"] = ""; _commands["Stop"] = ""; } else { _musicInfo = playerInfo; mWebsiteRadioButton.Checked = _musicInfo.IsWeb; mProgramRadioButton.Checked = !_musicInfo.IsWeb; mIgnoreAutomuteCheckbox.Visible = !_musicInfo.IsWeb; mWebsiteRadioButton_CheckedChanged_1(null, null); bool ignoreForAutomute = false; SmartVolManagerPackage.BgMusicManager.IgnoreProcNameForAutomuteDict.TryGetValue(GetProcName(_musicInfo.UrlOrCommandLine), out ignoreForAutomute); this.mIgnoreAutomuteCheckbox.Checked = ignoreForAutomute; mStopIfMutedTooLongCheckbox.Checked = playerInfo.KillAfterAutoMute; _commands["OnLoad"] = _musicInfo.OnLoadCommand; _commands["Play"] = _musicInfo.PlayCommand; _commands["Pause"] = _musicInfo.PauseCommand; _commands["PrevTrack"] = _musicInfo.PrevSongCommand; _commands["NextTrack"] = _musicInfo.NextSongCommand; _commands["Like"] = _musicInfo.LikeCommand; _commands["Dislike"] = _musicInfo.DislikeCommand; _commands["Stop"] = _musicInfo.StopCommand; mIcon.Image = MuteFmConfigUtil.GetImage(_musicInfo.Id, 16); } if (!editable) { foreach (Control control in this.Controls) { if ((string)control.Tag != "+") control.Enabled = false; } } } private void mCancelButton_Click(object sender, EventArgs e) { this.Close(); } private void mOkButton_Click(object sender, EventArgs e) { if (mMusicInfoNameTextBox.Text.Trim() == "") { MessageBox.Show(this, "Error: Name not set."); return; } if ((!mWebsiteRadioButton.Checked) && (!System.IO.File.Exists(mMusicInfoFileNameTextBox.Text.Trim()))) { MessageBox.Show(this, "File not found. Please enter full path and do not include quotes.", Constants.ProgramName); return; } // Update ignoreforautomute if (!mWebsiteRadioButton.Checked) { bool wasIgnoreForAutomute; SmartVolManagerPackage.BgMusicManager.IgnoreProcNameForAutomuteDict.TryGetValue(GetProcName(_musicInfo.UrlOrCommandLine), out wasIgnoreForAutomute); if ((wasIgnoreForAutomute) && (!mIgnoreAutomuteCheckbox.Checked)) { // Remove it string procname = GetProcName(_musicInfo.UrlOrCommandLine); SmartVolManagerPackage.BgMusicManager.IgnoreProcNameForAutomuteDict.Remove(procname); MuteFmConfigUtil.InitIgnoreForAutoMute(SmartVolManagerPackage.BgMusicManager.IgnoreProcNameForAutomuteDict, SmartVolManagerPackage.BgMusicManager.MuteFmConfig); } else if (((!wasIgnoreForAutomute) && (mIgnoreAutomuteCheckbox.Checked)) && (mIgnoreAutomuteCheckbox.Visible = true)) { // Add it string procname = GetProcName(mMusicInfoFileNameTextBox.Text); SmartVolManagerPackage.BgMusicManager.IgnoreProcNameForAutomuteDict[procname] = true; MuteFmConfigUtil.InitIgnoreForAutoMute(SmartVolManagerPackage.BgMusicManager.IgnoreProcNameForAutomuteDict, SmartVolManagerPackage.BgMusicManager.MuteFmConfig); } } _musicInfo.IsWeb = mWebsiteRadioButton.Checked; _musicInfo.Name = this.mMusicInfoNameTextBox.Text; if (_musicInfo.IsWeb) { _musicInfo.UrlOrCommandLine = this.mWebsiteUrlTextBox.Text.Trim(); _musicInfo.CommandLineArgs = ""; } else { _musicInfo.UrlOrCommandLine = this.mMusicInfoFileNameTextBox.Text.Trim(); _musicInfo.CommandLineArgs = this.mProgramArgumentsTextBox.Text; } if (this.Text == Constants.ProgramName + " - Add Sound Info") MuteFmConfigUtil.AddSoundPlayerInfo(_musicInfo, SmartVolManagerPackage.BgMusicManager.MuteFmConfig); _musicInfo.OnLoadCommand = _commands["OnLoad"]; _musicInfo.PlayCommand = _commands["Play"]; _musicInfo.PauseCommand = _commands["Pause"]; _musicInfo.PrevSongCommand = _commands["PrevTrack"]; _musicInfo.NextSongCommand = _commands["NextTrack"]; _musicInfo.LikeCommand = _commands["Like"]; _musicInfo.DislikeCommand = _commands["Dislike"]; _musicInfo.StopCommand = _commands["Stop"]; _musicInfo.KillAfterAutoMute = mStopIfMutedTooLongCheckbox.Checked; MuteFmConfigUtil.Save(SmartVolManagerPackage.BgMusicManager.MuteFmConfig); MuteFmConfigUtil.GenerateIconImage(_musicInfo, true); this.Close(); } private void mWebsiteRadioButton_CheckedChanged_1(object sender, EventArgs e) { mWebsiteGroupBox.Visible = mWebsiteRadioButton.Checked; mProgramGroupBox.Visible = !mWebsiteRadioButton.Checked; mIgnoreAutomuteCheckbox.Visible = !mWebsiteRadioButton.Checked; if (mWebsiteRadioButton.Checked) { mWebsiteUrlTextBox_TextChanged(null, null); } else { mMusicInfoFileNameTextBox_TextChanged(null, null); } this.mCommandsListbox.Items.Clear(); if (mWebsiteRadioButton.Checked == true) this.mCommandsListbox.Items.Add("OnLoad"); this.mCommandsListbox.Items.Add("Play"); this.mCommandsListbox.Items.Add("Pause"); this.mCommandsListbox.Items.Add("PrevTrack"); this.mCommandsListbox.Items.Add("NextTrack"); this.mCommandsListbox.Items.Add("Like"); this.mCommandsListbox.Items.Add("Dislike"); if (mWebsiteRadioButton.Checked == false) this.mCommandsListbox.Items.Add("Stop"); } private void MusicInfoEditForm_Load(object sender, EventArgs e) { if (_musicInfo == null) return; this.mMusicInfoNameTextBox.Text = _musicInfo.GetName(); if (_musicInfo.IsWeb) { mWebsiteRadioButton.Checked = true; mWebsiteUrlTextBox.Text = _musicInfo.UrlOrCommandLine; mMusicInfoFileNameTextBox.Text = ""; mProgramArgumentsTextBox.Text = ""; } else { mProgramRadioButton.Checked = true; mWebsiteUrlTextBox.Text = ""; mMusicInfoFileNameTextBox.Text = _musicInfo.UrlOrCommandLine; mProgramArgumentsTextBox.Text = _musicInfo.CommandLineArgs; } } private void mMusicInfoEditButton_Click(object sender, EventArgs e) { if (this.mCommandsListbox.Text == "") return; string commandText = _commands[this.mCommandsListbox.Text]; bool isChecked = false; string promptText = ""; if (this.mWebsiteRadioButton.Checked) { promptText = "Enter a JavaScript command that should be run when this operation occurs.\n\nYou can most easily debug it by going to the same page in your browser."; } else { promptText = "Enter a process name with args that should be run when this operation occurs.\n\nYou can include the process name by entering '$procname$'."; } DialogResult result = InputBoxWithCheck.Show(this, Constants.ProgramName + " - " + this.mCommandsListbox.Text, promptText, null, ref commandText, ref isChecked); if (result != System.Windows.Forms.DialogResult.Cancel) { _commands[this.mCommandsListbox.Text] = commandText; mCommandsListbox_SelectedIndexChanged(null, null); } } private void mCommandsListbox_SelectedIndexChanged(object sender, EventArgs e) { if (this.mCommandsListbox.Text == "") return; string commandText = _commands[this.mCommandsListbox.Text]; if (commandText.Trim() == "") commandText = "(none)"; mCustomCommandTextBox.Text = "Command: " + commandText; } private void mBrowseButton_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Multiselect = false; dialog.Filter = "Applications (*.exe)|*.exe"; DialogResult result = dialog.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) { this.mMusicInfoFileNameTextBox.Text = dialog.FileName; } } private void mTestButton_Click(object sender, EventArgs e) { if (System.IO.File.Exists(mMusicInfoFileNameTextBox.Text.Trim())) { try { System.Diagnostics.Process.Start(mMusicInfoFileNameTextBox.Text.Trim(), mProgramArgumentsTextBox.Text.Trim()); } catch { } } else { MessageBox.Show(this, "File does not exist. Please include full path and no quotes.", Constants.ProgramName); } } private void mCommandsListbox_DoubleClick(object sender, EventArgs e) { mMusicInfoEditButton_Click(null, null); } private void mTestWebButton_Click(object sender, EventArgs e) { try { System.Diagnostics.Process.Start(mWebsiteUrlTextBox.Text.Trim(), mProgramArgumentsTextBox.Text.Trim()); } catch { } } private static string GetProcName(string fullPath) { string fullPathNotNull = fullPath; if (fullPath == null) fullPathNotNull = ""; string procname = ""; string filename = System.IO.Path.GetFileName(fullPathNotNull).ToLower(); if (filename != "") { string[] parts = filename.Split('.'); procname = parts[0]; } return procname; } private void mDefaultsButton_Click(object sender, EventArgs e) { string procname = ""; if (mWebsiteRadioButton.Checked) procname = this.mWebsiteUrlTextBox.Text.Trim().TrimEnd('/'); else procname = GetProcName(this.mMusicInfoFileNameTextBox.Text); if (MuteFmConfigUtil.hasDefaults(procname)) { SoundPlayerInfo tempMusicInfo = new SoundPlayerInfo(); if (mWebsiteRadioButton.Checked) tempMusicInfo.UrlOrCommandLine = procname; else tempMusicInfo.UrlOrCommandLine = mMusicInfoFileNameTextBox.Text; if (this.mWebsiteRadioButton.Checked) MuteFmConfigUtil.InitDefaultsWeb(tempMusicInfo); else MuteFmConfigUtil.InitDefaultsProcess(tempMusicInfo, procname); _commands["OnLoad"] = tempMusicInfo.OnLoadCommand; _commands["Play"] = tempMusicInfo.PlayCommand; _commands["Pause"] = tempMusicInfo.PauseCommand; _commands["PrevTrack"] = tempMusicInfo.PrevSongCommand; _commands["NextTrack"] = tempMusicInfo.NextSongCommand; _commands["Like"] = tempMusicInfo.LikeCommand; _commands["Dislike"] = tempMusicInfo.DislikeCommand; _commands["Stop"] = tempMusicInfo.StopCommand; MessageBox.Show(this, "Defaults loaded.", Constants.ProgramName); mCommandsListbox_SelectedIndexChanged(null, null); } else { MessageBox.Show(this, "No defaults", Constants.ProgramName); // should never see this } } private void mMusicInfoFileNameTextBox_TextChanged(object sender, EventArgs e) { string procname = GetProcName(this.mMusicInfoFileNameTextBox.Text); mDefaultsButton.Enabled = MuteFmConfigUtil.hasDefaults(procname); //this.mNoIgnoreAutomuteCheckbox.Checked = } private void mWebsiteUrlTextBox_TextChanged(object sender, EventArgs e) { mDefaultsButton.Enabled = MuteFmConfigUtil.hasDefaults(mWebsiteUrlTextBox.Text); } private void mIcon_Click(object sender, EventArgs e) { //MessageBox.Show("TODO: change source for icon here."); } private void mExportButton_Click(object sender, EventArgs e) { SoundExportData data = new SoundExportData(); data.PlayCommand = _commands["Play"]; data.PauseCommand = _commands["Pause"]; data.StopCommand = _commands["Stop"]; data.NextTrackCommand = _commands["NextTrack"]; data.PrevTrackCommand = _commands["PrevTrack"]; data.OnLoadCommand = _commands["OnLoad"]; data.LikeCommand = _commands["Like"]; data.DislikeCommand = _commands["Dislike"]; string jsonText = Newtonsoft.Json.JsonConvert.SerializeObject(data); string tempFileName = System.IO.Path.GetTempFileName(); System.IO.File.WriteAllText(tempFileName, jsonText); MessageBox.Show(this, "To share with the community, please e-mail to [email protected].", Constants.ProgramName); System.Diagnostics.Process.Start("notepad.exe", tempFileName); } [Serializable] private class SoundExportData { public SoundExportData() { } public string PlayCommand = ""; public string PauseCommand = ""; public string StopCommand = ""; public string NextTrackCommand = ""; public string PrevTrackCommand = ""; public string OnLoadCommand = ""; public string LikeCommand = ""; public string DislikeCommand = ""; } } }
{ "content_hash": "896debee76e2fdb83a4971a82c31a881", "timestamp": "", "source": "github", "line_count": 418, "max_line_length": 180, "avg_line_length": 40.11483253588517, "alnum_prop": 0.5766937022900763, "repo_name": "jaredsohn/mutefm", "id": "d9aabb18424c5568a932e4723447bf20577595dc", "size": "16770", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/win/UiPackage/MusicEditForm.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1365" }, { "name": "C#", "bytes": "586256" }, { "name": "HTML", "bytes": "8124" }, { "name": "Inno Setup", "bytes": "19505" }, { "name": "JavaScript", "bytes": "78381" } ], "symlink_target": "" }
Release Process ==================== * * * ###update (commit) version in sources CryptoPowers-qt.pro contrib/verifysfbinaries/verify.sh doc/README* share/setup.nsi src/clientversion.h (change CLIENT_VERSION_IS_RELEASE to true) ###tag version in git git tag -a v0.8.0 ###write release notes. git shortlog helps a lot, for example: git shortlog --no-merges v0.7.2..v0.8.0 * * * ##perform gitian builds From a directory containing the CryptoPowers source, gitian-builder and gitian.sigs export SIGNER=(your gitian key, ie bluematt, sipa, etc) export VERSION=0.8.0 cd ./gitian-builder Fetch and build inputs: (first time, or when dependency versions change) mkdir -p inputs; cd inputs/ wget 'http://miniupnp.free.fr/files/download.php?file=miniupnpc-1.6.tar.gz' -O miniupnpc-1.6.tar.gz wget 'http://www.openssl.org/source/openssl-1.0.1c.tar.gz' wget 'http://download.oracle.com/berkeley-db/db-4.8.30.NC.tar.gz' wget 'http://zlib.net/zlib-1.2.6.tar.gz' wget 'ftp://ftp.simplesystems.org/pub/libpng/png/src/libpng-1.5.9.tar.gz' wget 'http://fukuchi.org/works/qrencode/qrencode-3.2.0.tar.bz2' wget 'http://downloads.sourceforge.net/project/boost/boost/1.50.0/boost_1_50_0.tar.bz2' wget 'http://releases.qt-project.org/qt4/source/qt-everywhere-opensource-src-4.8.3.tar.gz' cd .. ./bin/gbuild ../CryptoPowers/contrib/gitian-descriptors/boost-win32.yml mv build/out/boost-win32-1.50.0-gitian2.zip inputs/ ./bin/gbuild ../CryptoPowers/contrib/gitian-descriptors/qt-win32.yml mv build/out/qt-win32-4.8.3-gitian-r1.zip inputs/ ./bin/gbuild ../CryptoPowers/contrib/gitian-descriptors/deps-win32.yml mv build/out/CryptoPowers-deps-0.0.5.zip inputs/ Build CryptoPowersd and CryptoPowers-qt on Linux32, Linux64, and Win32: ./bin/gbuild --commit CryptoPowers=v${VERSION} ../CryptoPowers/contrib/gitian-descriptors/gitian.yml ./bin/gsign --signer $SIGNER --release ${VERSION} --destination ../gitian.sigs/ ../CryptoPowers/contrib/gitian-descriptors/gitian.yml pushd build/out zip -r CryptoPowers-${VERSION}-linux-gitian.zip * mv CryptoPowers-${VERSION}-linux-gitian.zip ../../ popd ./bin/gbuild --commit CryptoPowers=v${VERSION} ../CryptoPowers/contrib/gitian-descriptors/gitian-win32.yml ./bin/gsign --signer $SIGNER --release ${VERSION}-win32 --destination ../gitian.sigs/ ../CryptoPowers/contrib/gitian-descriptors/gitian-win32.yml pushd build/out zip -r CryptoPowers-${VERSION}-win32-gitian.zip * mv CryptoPowers-${VERSION}-win32-gitian.zip ../../ popd Build output expected: 1. linux 32-bit and 64-bit binaries + source (CryptoPowers-${VERSION}-linux-gitian.zip) 2. windows 32-bit binary, installer + source (CryptoPowers-${VERSION}-win32-gitian.zip) 3. Gitian signatures (in gitian.sigs/${VERSION}[-win32]/(your gitian key)/ repackage gitian builds for release as stand-alone zip/tar/installer exe **Linux .tar.gz:** unzip CryptoPowers-${VERSION}-linux-gitian.zip -d CryptoPowers-${VERSION}-linux tar czvf CryptoPowers-${VERSION}-linux.tar.gz CryptoPowers-${VERSION}-linux rm -rf CryptoPowers-${VERSION}-linux **Windows .zip and setup.exe:** unzip CryptoPowers-${VERSION}-win32-gitian.zip -d CryptoPowers-${VERSION}-win32 mv CryptoPowers-${VERSION}-win32/CryptoPowers-*-setup.exe . zip -r CryptoPowers-${VERSION}-win32.zip bitcoin-${VERSION}-win32 rm -rf CryptoPowers-${VERSION}-win32 **Perform Mac build:** OSX binaries are created by Gavin Andresen on a 32-bit, OSX 10.6 machine. qmake RELEASE=1 USE_UPNP=1 USE_QRCODE=1 CryptoPowers-qt.pro make export QTDIR=/opt/local/share/qt4 # needed to find translations/qt_*.qm files T=$(contrib/qt_translations.py $QTDIR/translations src/qt/locale) python2.7 share/qt/clean_mac_info_plist.py python2.7 contrib/macdeploy/macdeployqtplus Bitcoin-Qt.app -add-qt-tr $T -dmg -fancy contrib/macdeploy/fancy.plist Build output expected: Bitcoin-Qt.dmg ###Next steps: * Code-sign Windows -setup.exe (in a Windows virtual machine) and OSX Bitcoin-Qt.app (Note: only Gavin has the code-signing keys currently) * upload builds to SourceForge * create SHA256SUMS for builds, and PGP-sign it * update CryptoPowers.io version make sure all OS download links go to the right versions * update forum version * update wiki download links * update wiki changelog: [https://en.CryptoPowers.it/wiki/Changelog](https://en.bitcoin.it/wiki/Changelog) Commit your signature to gitian.sigs: pushd gitian.sigs git add ${VERSION}/${SIGNER} git add ${VERSION}-win32/${SIGNER} git commit -a git push # Assuming you can push to the gitian.sigs tree popd ------------------------------------------------------------------------- ### After 3 or more people have gitian-built, repackage gitian-signed zips: From a directory containing CryptoPowers source, gitian.sigs and gitian zips export VERSION=0.5.1 mkdir CryptoPowers-${VERSION}-linux-gitian pushd CryptoPowers-${VERSION}-linux-gitian unzip ../CryptoPowers-${VERSION}-linux-gitian.zip mkdir gitian cp ../CryptoPowers/contrib/gitian-downloader/*.pgp ./gitian/ for signer in $(ls ../gitian.sigs/${VERSION}/); do cp ../gitian.sigs/${VERSION}/${signer}/CryptoPowers-build.assert ./gitian/${signer}-build.assert cp ../gitian.sigs/${VERSION}/${signer}/CryptoPowers-build.assert.sig ./gitian/${signer}-build.assert.sig done zip -r CryptoPowers-${VERSION}-linux-gitian.zip * cp CryptoPowers-${VERSION}-linux-gitian.zip ../ popd mkdir CryptoPowers-${VERSION}-win32-gitian pushd CryptoPowers-${VERSION}-win32-gitian unzip ../CryptoPowers-${VERSION}-win32-gitian.zip mkdir gitian cp ../CryptoPowers/contrib/gitian-downloader/*.pgp ./gitian/ for signer in $(ls ../gitian.sigs/${VERSION}-win32/); do cp ../gitian.sigs/${VERSION}-win32/${signer}/CryptoPowers-build.assert ./gitian/${signer}-build.assert cp ../gitian.sigs/${VERSION}-win32/${signer}/CryptoPowers-build.assert.sig ./gitian/${signer}-build.assert.sig done zip -r CryptoPowers-${VERSION}-win32-gitian.zip * cp CryptoPowers-${VERSION}-win32-gitian.zip ../ popd - Upload gitian zips to SourceForge - Celebrate
{ "content_hash": "50055c9f316f1a96dd91da0b1425f05d", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 146, "avg_line_length": 37.65217391304348, "alnum_prop": 0.7307819201583636, "repo_name": "CryptoPowers/CryptoPowersCoin", "id": "cb202b4150daf019dd3f9a33934fcee78033cfe9", "size": "6062", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/release-process.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "765707" }, { "name": "C++", "bytes": "2530644" }, { "name": "CSS", "bytes": "1127" }, { "name": "IDL", "bytes": "14848" }, { "name": "Objective-C++", "bytes": "5864" }, { "name": "Python", "bytes": "37288" }, { "name": "Shell", "bytes": "2526" }, { "name": "TypeScript", "bytes": "5253215" } ], "symlink_target": "" }
package com.hmmelton.tangential; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.app.FragmentManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.hmmelton.tangential.fragments.CorrelationFragment; import com.hmmelton.tangential.fragments.HomeFragment; import com.hmmelton.tangential.models.StyledQuote; import com.hmmelton.tangential.utils.QuoteHelper; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @SuppressWarnings("unused") private final String TAG = getClass().getSimpleName(); @BindView(R.id.drawer_layout) DrawerLayout drawer; @BindView(R.id.nav_view) NavigationView navigationView; // List of display fields for index values private List<TextView> indexes = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // Change text color of toolbar from main text color toolbar.setTitleTextColor(getResources().getColor(android.R.color.white)); setSupportActionBar(toolbar); ButterKnife.bind(this); // Get header view in order to View headerLayout = navigationView.getHeaderView(0); // Add index display fields to list indexes.add((TextView) headerLayout.findViewById(R.id.index_1)); indexes.add((TextView) headerLayout.findViewById(R.id.index_2)); indexes.add((TextView) headerLayout.findViewById(R.id.index_3)); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.main_fragment_holder, HomeFragment.newInstance()) .commit(); // Set up Navigation Drawer ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); navigationView.setNavigationItemSelectedListener(this); setIndexPrices(); } @Override public void onBackPressed() { if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { FragmentManager fragmentManager = getSupportFragmentManager(); // Handle navigation view item clicks here. int id = item.getItemId(); switch (id) { case R.id.nav_home: fragmentManager.beginTransaction() .replace(R.id.main_fragment_holder, HomeFragment.newInstance()) .commit(); getSupportActionBar().setTitle(getString(R.string.app_name)); break; case R.id.nav_correlation: fragmentManager.beginTransaction() .replace(R.id.main_fragment_holder, CorrelationFragment.newInstance()) .commit(); getSupportActionBar().setTitle(getString(R.string.correlation)); break; case R.id.nav_s_ratio: break; case R.id.nav_tangency: break; case R.id.nav_min_var: break; default: break; } drawer.closeDrawer(GravityCompat.START); return true; } /** * This method finds and displays the current prices of the given indexes. */ private void setIndexPrices() { // Ticker symbols for the indexes final String[] indexTickers = { "^DJI", "^IXIC", "^GSPC" }; for (int i = 0; i < indexes.size(); i++) { final int j = i; new AsyncTask<String, Void, StyledQuote>() { @Override protected StyledQuote doInBackground(String... strings) { return QuoteHelper.getChangeStyledQuote(strings[0], 1); } @Override protected void onPostExecute(StyledQuote quote) { super.onPostExecute(quote); if (quote != null) { indexes.get(j).setText(quote.getValue() + ""); indexes.get(j).setTextColor(getResources().getColor(quote.getColor())); } else indexes.get(j).setText(getString(R.string.error)); } }.execute(indexTickers[i]); } } }
{ "content_hash": "9c762fefaccd403cd498de7dca7f0920", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 106, "avg_line_length": 35.97604790419162, "alnum_prop": 0.6338215712383488, "repo_name": "hmmelton/Tangential", "id": "e7506bb0bb818ddd39f1c11c017d19efe70ab2b7", "size": "6008", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/hmmelton/tangential/MainActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "16693" } ], "symlink_target": "" }
package de.ust.skill.common.java.internal; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.Semaphore; import de.ust.skill.common.java.internal.parts.BulkChunk; import de.ust.skill.common.java.internal.parts.Chunk; import de.ust.skill.common.java.internal.parts.SimpleChunk; import de.ust.skill.common.jvm.streams.FileOutputStream; /** * Implementation of append operation. * * @author Timm Felden */ final public class StateAppender extends SerializationFunctions { public StateAppender(SkillState state, FileOutputStream out) throws IOException, InterruptedException { super(state); // save the index of the first new pool final int newPoolIndex; { int i = 0; for (StoragePool<?, ?> t : state.types) { if (t.blocks.isEmpty()) break; i++; } newPoolIndex = i; } // ensure fast size() operations StoragePool.fixed(state.types); // make lbpsi map, update data map to contain dynamic instances and // create serialization skill IDs for // serialization // index → bpsi final int[] lbpoMap = new int[state.types.size()]; final HashMap<FieldDeclaration<?, ?>, Chunk> chunkMap = new HashMap<>(); final Semaphore barrier = new Semaphore(0, false); { int bases = 0; for (StoragePool<?, ?> p : state.types) { if (p instanceof BasePool<?>) { bases++; SkillState.pool.execute(new Runnable() { @Override public void run() { ((BasePool<?>) p).prepareAppend(lbpoMap, chunkMap); barrier.release(); } }); } } barrier.acquire(bases); } // locate relevant pools final ArrayList<StoragePool<?, ?>> rPools = new ArrayList<>(state.types.size()); for (StoragePool<?, ?> p : state.types) { // new index? if (p.typeID - 32 >= newPoolIndex) rPools.add(p); // new instance or field? else if (p.size() > 0) { boolean exists = false; for (FieldDeclaration<?, ?> f : p.dataFields) { if (chunkMap.containsKey(f)) { exists = true; break; } } if (exists) rPools.add(p); } } /** * **************** PHASE 3: WRITE * **************** */ // write string block state.strings.prepareAndAppend(out, this); // calculate offsets for relevant fields int fieldCount = 0; { for (final FieldDeclaration<?, ?> f : chunkMap.keySet()) { fieldCount++; SkillState.pool.execute(new Runnable() { @Override public void run() { f.offset = 0; Chunk c = f.lastChunk(); if (c instanceof SimpleChunk) { int i = (int) ((SimpleChunk) c).bpo; f.osc(i, i + (int) c.count); } else f.obc((BulkChunk) c); barrier.release(); }; }); } barrier.acquire(fieldCount); } // write count of the type block out.v64(rPools.size()); // write headers final ArrayList<ArrayList<FieldDeclaration<?, ?>>> fieldQueue = new ArrayList<>(fieldCount); final HashMap<String, Integer> stringIDs = state.strings.stringIDs; for (StoragePool<?, ?> p : rPools) { // generic append final boolean newPool = p.typeID - 32 >= newPoolIndex; final ArrayList<FieldDeclaration<?, ?>> fields = new ArrayList<FieldDeclaration<?, ?>>(p.dataFields.size()); for (FieldDeclaration<?, ?> f : p.dataFields) if (chunkMap.containsKey(f)) fields.add(f); if (newPool || (0 != fields.size() && p.size() > 0)) { out.v64(stringIDs.get(p.name)); final long count = p.lastBlock().count; out.v64(count); if (newPool) { restrictions(p, out); if (null == p.superName()) { out.i8((byte) 0); } else { out.v64(p.superPool.typeID - 31); if (0 != count) { // we used absolute BPOs to ease overall // implementation out.v64(lbpoMap[p.typeID - 32] - lbpoMap[p.basePool.typeID - 32]); } } } else if (null != p.superName() && 0 != count) { out.v64(lbpoMap[p.typeID - 32] - lbpoMap[p.basePool.typeID - 32]); } if (newPool && 0 == count) { out.i8((byte) 0); } else { out.v64(fields.size()); fieldQueue.add(fields); } } } // write fields final ArrayList<Task> data = new ArrayList<>(fieldCount); long offset = 0L; for (ArrayList<FieldDeclaration<?, ?>> fields : fieldQueue) { for (FieldDeclaration<?, ?> f : fields) { out.v64(f.index); if (1 == f.dataChunks.size()) { out.v64(stringIDs.get(f.name)); writeType(f.type, out); restrictions(f, out); } // put end offset and enqueue data final long end = offset + f.offset; out.v64(end); data.add(new Task(f, offset, end)); offset = end; } } writeFieldData(state, out, data, (int) offset, barrier); } }
{ "content_hash": "4e0c4ade5848a5590f74990306222652", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 120, "avg_line_length": 35.1, "alnum_prop": 0.45742323520101297, "repo_name": "skill-lang/javaCommon", "id": "9ce455e516db488c2b4da4e1c70b64238c886488", "size": "6320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/de/ust/skill/common/java/internal/StateAppender.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "181815" } ], "symlink_target": "" }
class BrowsingDataCookieHelper; class BrowsingDataServerBoundCertHelper; class CookieSettings; class CookiesTreeModel; class CookieTreeAppCacheNode; class CookieTreeAppCachesNode; class CookieTreeCookieNode; class CookieTreeCookiesNode; class CookieTreeDatabaseNode; class CookieTreeDatabasesNode; class CookieTreeFileSystemNode; class CookieTreeFileSystemsNode; class CookieTreeFlashLSONode; class CookieTreeHostNode; class CookieTreeIndexedDBNode; class CookieTreeIndexedDBsNode; class CookieTreeLocalStorageNode; class CookieTreeLocalStoragesNode; class CookieTreeQuotaNode; class CookieTreeServerBoundCertNode; class CookieTreeServerBoundCertsNode; class CookieTreeSessionStorageNode; class CookieTreeSessionStoragesNode; class ExtensionSpecialStoragePolicy; namespace net { class CanonicalCookie; } // CookieTreeNode ------------------------------------------------------------- // The base node type in the Cookies, Databases, and Local Storage options // view, from which all other types are derived. Specialized from TreeNode in // that it has a notion of deleting objects stored in the profile, and being // able to have its children do the same. class CookieTreeNode : public ui::TreeNode<CookieTreeNode> { public: // Used to pull out information for the InfoView (the details display below // the tree control.) struct DetailedInfo { // NodeType corresponds to the various CookieTreeNode types. enum NodeType { TYPE_NONE, TYPE_ROOT, // This is used for CookieTreeRootNode nodes. TYPE_HOST, // This is used for CookieTreeHostNode nodes. TYPE_COOKIES, // This is used for CookieTreeCookiesNode nodes. TYPE_COOKIE, // This is used for CookieTreeCookieNode nodes. TYPE_DATABASES, // This is used for CookieTreeDatabasesNode. TYPE_DATABASE, // This is used for CookieTreeDatabaseNode. TYPE_LOCAL_STORAGES, // This is used for CookieTreeLocalStoragesNode. TYPE_LOCAL_STORAGE, // This is used for CookieTreeLocalStorageNode. TYPE_SESSION_STORAGES, // This is used for CookieTreeSessionStoragesNode. TYPE_SESSION_STORAGE, // This is used for CookieTreeSessionStorageNode. TYPE_APPCACHES, // This is used for CookieTreeAppCachesNode. TYPE_APPCACHE, // This is used for CookieTreeAppCacheNode. TYPE_INDEXED_DBS, // This is used for CookieTreeIndexedDBsNode. TYPE_INDEXED_DB, // This is used for CookieTreeIndexedDBNode. TYPE_FILE_SYSTEMS, // This is used for CookieTreeFileSystemsNode. TYPE_FILE_SYSTEM, // This is used for CookieTreeFileSystemNode. TYPE_QUOTA, // This is used for CookieTreeQuotaNode. TYPE_SERVER_BOUND_CERTS, // Used for CookieTreeServerBoundCertsNode. TYPE_SERVER_BOUND_CERT, // Used for CookieTreeServerBoundCertNode. TYPE_FLASH_LSO, // This is used for CookieTreeFlashLSONode. }; DetailedInfo(); ~DetailedInfo(); DetailedInfo& Init(NodeType type); DetailedInfo& InitHost(); DetailedInfo& InitCookie(const net::CanonicalCookie* cookie); DetailedInfo& InitDatabase( const BrowsingDataDatabaseHelper::DatabaseInfo* database_info); DetailedInfo& InitLocalStorage( const BrowsingDataLocalStorageHelper::LocalStorageInfo* local_storage_info); DetailedInfo& InitSessionStorage( const BrowsingDataLocalStorageHelper::LocalStorageInfo* session_storage_info); DetailedInfo& InitAppCache(const GURL& origin, const appcache::AppCacheInfo* appcache_info); DetailedInfo& InitIndexedDB( const BrowsingDataIndexedDBHelper::IndexedDBInfo* indexed_db_info); DetailedInfo& InitFileSystem( const BrowsingDataFileSystemHelper::FileSystemInfo* file_system_info); DetailedInfo& InitQuota( const BrowsingDataQuotaHelper::QuotaInfo* quota_info); DetailedInfo& InitServerBoundCert( const net::ServerBoundCertStore::ServerBoundCert* server_bound_cert); DetailedInfo& InitFlashLSO(const std::string& flash_lso_domain); NodeType node_type; GURL origin; const net::CanonicalCookie* cookie; const BrowsingDataDatabaseHelper::DatabaseInfo* database_info; const BrowsingDataLocalStorageHelper::LocalStorageInfo* local_storage_info; const BrowsingDataLocalStorageHelper::LocalStorageInfo* session_storage_info; const appcache::AppCacheInfo* appcache_info; const BrowsingDataIndexedDBHelper::IndexedDBInfo* indexed_db_info; const BrowsingDataFileSystemHelper::FileSystemInfo* file_system_info; const BrowsingDataQuotaHelper::QuotaInfo* quota_info; const net::ServerBoundCertStore::ServerBoundCert* server_bound_cert; std::string flash_lso_domain; }; CookieTreeNode() {} explicit CookieTreeNode(const string16& title) : ui::TreeNode<CookieTreeNode>(title) {} virtual ~CookieTreeNode() {} // Delete backend storage for this node, and any children nodes. (E.g. delete // the cookie from CookieMonster, clear the database, and so forth.) virtual void DeleteStoredObjects(); // Gets a pointer back to the associated model for the tree we are in. virtual CookiesTreeModel* GetModel() const; // Returns a struct with detailed information used to populate the details // part of the view. virtual DetailedInfo GetDetailedInfo() const = 0; protected: void AddChildSortedByTitle(CookieTreeNode* new_child); private: DISALLOW_COPY_AND_ASSIGN(CookieTreeNode); }; // CookieTreeRootNode --------------------------------------------------------- // The node at the root of the CookieTree that gets inserted into the view. class CookieTreeRootNode : public CookieTreeNode { public: explicit CookieTreeRootNode(CookiesTreeModel* model); virtual ~CookieTreeRootNode(); CookieTreeHostNode* GetOrCreateHostNode(const GURL& url); // CookieTreeNode methods: virtual CookiesTreeModel* GetModel() const OVERRIDE; virtual DetailedInfo GetDetailedInfo() const OVERRIDE; private: CookiesTreeModel* model_; DISALLOW_COPY_AND_ASSIGN(CookieTreeRootNode); }; // CookieTreeHostNode ------------------------------------------------------- class CookieTreeHostNode : public CookieTreeNode { public: // Returns the host node's title to use for a given URL. static string16 TitleForUrl(const GURL& url); explicit CookieTreeHostNode(const GURL& url); virtual ~CookieTreeHostNode(); // CookieTreeNode methods: virtual DetailedInfo GetDetailedInfo() const OVERRIDE; // CookieTreeHostNode methods: CookieTreeCookiesNode* GetOrCreateCookiesNode(); CookieTreeDatabasesNode* GetOrCreateDatabasesNode(); CookieTreeLocalStoragesNode* GetOrCreateLocalStoragesNode(); CookieTreeSessionStoragesNode* GetOrCreateSessionStoragesNode(); CookieTreeAppCachesNode* GetOrCreateAppCachesNode(); CookieTreeIndexedDBsNode* GetOrCreateIndexedDBsNode(); CookieTreeFileSystemsNode* GetOrCreateFileSystemsNode(); CookieTreeServerBoundCertsNode* GetOrCreateServerBoundCertsNode(); CookieTreeQuotaNode* UpdateOrCreateQuotaNode( std::list<BrowsingDataQuotaHelper::QuotaInfo>::iterator quota_info); CookieTreeFlashLSONode* GetOrCreateFlashLSONode(const std::string& domain); std::string canonicalized_host() const { return canonicalized_host_; } // Creates an content exception for this origin of type // CONTENT_SETTINGS_TYPE_COOKIES. void CreateContentException(CookieSettings* cookie_settings, ContentSetting setting) const; // True if a content exception can be created for this origin. bool CanCreateContentException() const; const std::string GetHost() const; private: // Pointers to the cookies, databases, local and session storage and appcache // nodes. When we build up the tree we need to quickly get a reference to // the COOKIES node to add children. Checking each child and interrogating // them to see if they are a COOKIES, APPCACHES, DATABASES etc node seems // less preferable than storing an extra pointer per origin. CookieTreeCookiesNode* cookies_child_; CookieTreeDatabasesNode* databases_child_; CookieTreeLocalStoragesNode* local_storages_child_; CookieTreeSessionStoragesNode* session_storages_child_; CookieTreeAppCachesNode* appcaches_child_; CookieTreeIndexedDBsNode* indexed_dbs_child_; CookieTreeFileSystemsNode* file_systems_child_; CookieTreeQuotaNode* quota_child_; CookieTreeServerBoundCertsNode* server_bound_certs_child_; CookieTreeFlashLSONode* flash_lso_child_; // The URL for which this node was initially created. GURL url_; std::string canonicalized_host_; DISALLOW_COPY_AND_ASSIGN(CookieTreeHostNode); }; // CookieTreeCookieNode ------------------------------------------------------ class CookieTreeCookieNode : public CookieTreeNode { public: friend class CookieTreeCookiesNode; // The cookie should remain valid at least as long as the // CookieTreeCookieNode is valid. explicit CookieTreeCookieNode( std::list<net::CanonicalCookie>::iterator cookie); virtual ~CookieTreeCookieNode(); // CookieTreeNode methods: virtual void DeleteStoredObjects() OVERRIDE; virtual DetailedInfo GetDetailedInfo() const OVERRIDE; private: // cookie_ is expected to remain valid as long as the CookieTreeCookieNode is // valid. std::list<net::CanonicalCookie>::iterator cookie_; DISALLOW_COPY_AND_ASSIGN(CookieTreeCookieNode); }; class CookieTreeCookiesNode : public CookieTreeNode { public: CookieTreeCookiesNode(); virtual ~CookieTreeCookiesNode(); virtual DetailedInfo GetDetailedInfo() const OVERRIDE; void AddCookieNode(CookieTreeCookieNode* child) { AddChildSortedByTitle(child); } private: DISALLOW_COPY_AND_ASSIGN(CookieTreeCookiesNode); }; // CookieTreeAppCacheNode ----------------------------------------------------- class CookieTreeAppCacheNode : public CookieTreeNode { public: friend class CookieTreeAppCachesNode; // appcache_info should remain valid at least as long as the // CookieTreeAppCacheNode is valid. explicit CookieTreeAppCacheNode( const GURL& origin_url, std::list<appcache::AppCacheInfo>::iterator appcache_info); virtual ~CookieTreeAppCacheNode(); virtual void DeleteStoredObjects() OVERRIDE; virtual DetailedInfo GetDetailedInfo() const OVERRIDE; private: GURL origin_url_; std::list<appcache::AppCacheInfo>::iterator appcache_info_; DISALLOW_COPY_AND_ASSIGN(CookieTreeAppCacheNode); }; class CookieTreeAppCachesNode : public CookieTreeNode { public: CookieTreeAppCachesNode(); virtual ~CookieTreeAppCachesNode(); virtual DetailedInfo GetDetailedInfo() const OVERRIDE; void AddAppCacheNode(CookieTreeAppCacheNode* child) { AddChildSortedByTitle(child); } private: DISALLOW_COPY_AND_ASSIGN(CookieTreeAppCachesNode); }; // CookieTreeDatabaseNode ----------------------------------------------------- class CookieTreeDatabaseNode : public CookieTreeNode { public: friend class CookieTreeDatabasesNode; // database_info should remain valid at least as long as the // CookieTreeDatabaseNode is valid. explicit CookieTreeDatabaseNode( std::list<BrowsingDataDatabaseHelper::DatabaseInfo>::iterator database_info); virtual ~CookieTreeDatabaseNode(); virtual void DeleteStoredObjects() OVERRIDE; virtual DetailedInfo GetDetailedInfo() const OVERRIDE; private: // database_info_ is expected to remain valid as long as the // CookieTreeDatabaseNode is valid. std::list<BrowsingDataDatabaseHelper::DatabaseInfo>::iterator database_info_; DISALLOW_COPY_AND_ASSIGN(CookieTreeDatabaseNode); }; class CookieTreeDatabasesNode : public CookieTreeNode { public: CookieTreeDatabasesNode(); virtual ~CookieTreeDatabasesNode(); virtual DetailedInfo GetDetailedInfo() const OVERRIDE; void AddDatabaseNode(CookieTreeDatabaseNode* child) { AddChildSortedByTitle(child); } private: DISALLOW_COPY_AND_ASSIGN(CookieTreeDatabasesNode); }; // CookieTreeFileSystemNode -------------------------------------------------- class CookieTreeFileSystemNode : public CookieTreeNode { public: friend class CookieTreeFileSystemsNode; // file_system_info should remain valid at least as long as the // CookieTreeFileSystemNode is valid. explicit CookieTreeFileSystemNode( std::list<BrowsingDataFileSystemHelper::FileSystemInfo>::iterator file_system_info); virtual ~CookieTreeFileSystemNode(); virtual void DeleteStoredObjects() OVERRIDE; virtual DetailedInfo GetDetailedInfo() const OVERRIDE; private: // file_system_info_ expected to remain valid as long as the // CookieTreeFileSystemNode is valid. std::list<BrowsingDataFileSystemHelper::FileSystemInfo>::iterator file_system_info_; DISALLOW_COPY_AND_ASSIGN(CookieTreeFileSystemNode); }; class CookieTreeFileSystemsNode : public CookieTreeNode { public: CookieTreeFileSystemsNode(); virtual ~CookieTreeFileSystemsNode(); virtual DetailedInfo GetDetailedInfo() const OVERRIDE; void AddFileSystemNode(CookieTreeFileSystemNode* child) { AddChildSortedByTitle(child); } private: DISALLOW_COPY_AND_ASSIGN(CookieTreeFileSystemsNode); }; // CookieTreeLocalStorageNode ------------------------------------------------- class CookieTreeLocalStorageNode : public CookieTreeNode { public: // local_storage_info should remain valid at least as long as the // CookieTreeLocalStorageNode is valid. explicit CookieTreeLocalStorageNode( std::list<BrowsingDataLocalStorageHelper::LocalStorageInfo>::iterator local_storage_info); virtual ~CookieTreeLocalStorageNode(); // CookieTreeNode methods: virtual void DeleteStoredObjects() OVERRIDE; virtual DetailedInfo GetDetailedInfo() const OVERRIDE; private: // local_storage_info_ is expected to remain valid as long as the // CookieTreeLocalStorageNode is valid. std::list<BrowsingDataLocalStorageHelper::LocalStorageInfo>::iterator local_storage_info_; DISALLOW_COPY_AND_ASSIGN(CookieTreeLocalStorageNode); }; class CookieTreeLocalStoragesNode : public CookieTreeNode { public: CookieTreeLocalStoragesNode(); virtual ~CookieTreeLocalStoragesNode(); virtual DetailedInfo GetDetailedInfo() const OVERRIDE; void AddLocalStorageNode(CookieTreeLocalStorageNode* child) { AddChildSortedByTitle(child); } private: DISALLOW_COPY_AND_ASSIGN(CookieTreeLocalStoragesNode); }; // CookieTreeSessionStorageNode ----------------------------------------------- class CookieTreeSessionStorageNode : public CookieTreeNode { public: // session_storage_info should remain valid at least as long as the // CookieTreeSessionStorageNode is valid. explicit CookieTreeSessionStorageNode( std::list<BrowsingDataLocalStorageHelper::LocalStorageInfo>::iterator session_storage_info); virtual ~CookieTreeSessionStorageNode(); // CookieTreeNode methods: virtual void DeleteStoredObjects() OVERRIDE; virtual DetailedInfo GetDetailedInfo() const OVERRIDE; private: // session_storage_info_ is expected to remain valid as long as the // CookieTreeSessionStorageNode is valid. std::list<BrowsingDataLocalStorageHelper::LocalStorageInfo>::iterator session_storage_info_; DISALLOW_COPY_AND_ASSIGN(CookieTreeSessionStorageNode); }; class CookieTreeSessionStoragesNode : public CookieTreeNode { public: CookieTreeSessionStoragesNode(); virtual ~CookieTreeSessionStoragesNode(); virtual DetailedInfo GetDetailedInfo() const OVERRIDE; void AddSessionStorageNode(CookieTreeSessionStorageNode* child) { AddChildSortedByTitle(child); } private: DISALLOW_COPY_AND_ASSIGN(CookieTreeSessionStoragesNode); }; // CookieTreeIndexedDBNode ----------------------------------------------- class CookieTreeIndexedDBNode : public CookieTreeNode { public: // indexed_db_info should remain valid at least as long as the // CookieTreeIndexedDBNode is valid. explicit CookieTreeIndexedDBNode( std::list<BrowsingDataIndexedDBHelper::IndexedDBInfo>::iterator indexed_db_info); virtual ~CookieTreeIndexedDBNode(); // CookieTreeNode methods: virtual void DeleteStoredObjects() OVERRIDE; virtual DetailedInfo GetDetailedInfo() const OVERRIDE; private: // indexed_db_info_ is expected to remain valid as long as the // CookieTreeIndexedDBNode is valid. std::list<BrowsingDataIndexedDBHelper::IndexedDBInfo>::iterator indexed_db_info_; DISALLOW_COPY_AND_ASSIGN(CookieTreeIndexedDBNode); }; class CookieTreeIndexedDBsNode : public CookieTreeNode { public: CookieTreeIndexedDBsNode(); virtual ~CookieTreeIndexedDBsNode(); virtual DetailedInfo GetDetailedInfo() const OVERRIDE; void AddIndexedDBNode(CookieTreeIndexedDBNode* child) { AddChildSortedByTitle(child); } private: DISALLOW_COPY_AND_ASSIGN(CookieTreeIndexedDBsNode); }; // CookieTreeQuotaNode -------------------------------------------------- class CookieTreeQuotaNode : public CookieTreeNode { public: // quota_info should remain valid at least as long as the CookieTreeQuotaNode // is valid. explicit CookieTreeQuotaNode( std::list<BrowsingDataQuotaHelper::QuotaInfo>::iterator quota_info); virtual ~CookieTreeQuotaNode(); virtual void DeleteStoredObjects() OVERRIDE; virtual DetailedInfo GetDetailedInfo() const OVERRIDE; private: // quota_info_ is expected to remain valid as long as the CookieTreeQuotaNode // is valid. std::list<BrowsingDataQuotaHelper::QuotaInfo>::iterator quota_info_; DISALLOW_COPY_AND_ASSIGN(CookieTreeQuotaNode); }; // CookieTreeServerBoundCertNode --------------------------------------------- class CookieTreeServerBoundCertNode : public CookieTreeNode { public: friend class CookieTreeServerBoundCertsNode; // The iterator should remain valid at least as long as the // CookieTreeServerBoundCertNode is valid. explicit CookieTreeServerBoundCertNode( net::ServerBoundCertStore::ServerBoundCertList::iterator cert); virtual ~CookieTreeServerBoundCertNode(); // CookieTreeNode methods: virtual void DeleteStoredObjects() OVERRIDE; virtual DetailedInfo GetDetailedInfo() const OVERRIDE; private: // server_bound_cert_ is expected to remain valid as long as the // CookieTreeServerBoundCertNode is valid. net::ServerBoundCertStore::ServerBoundCertList::iterator server_bound_cert_; DISALLOW_COPY_AND_ASSIGN(CookieTreeServerBoundCertNode); }; class CookieTreeServerBoundCertsNode : public CookieTreeNode { public: CookieTreeServerBoundCertsNode(); virtual ~CookieTreeServerBoundCertsNode(); virtual DetailedInfo GetDetailedInfo() const OVERRIDE; void AddServerBoundCertNode(CookieTreeServerBoundCertNode* child) { AddChildSortedByTitle(child); } private: DISALLOW_COPY_AND_ASSIGN(CookieTreeServerBoundCertsNode); }; // CookieTreeFlashLSONode ---------------------------------------------------- class CookieTreeFlashLSONode : public CookieTreeNode { public: explicit CookieTreeFlashLSONode(const std::string& domain); virtual ~CookieTreeFlashLSONode(); // CookieTreeNode methods: virtual void DeleteStoredObjects() OVERRIDE; virtual DetailedInfo GetDetailedInfo() const OVERRIDE; private: std::string domain_; DISALLOW_COPY_AND_ASSIGN(CookieTreeFlashLSONode); }; // CookiesTreeModel ----------------------------------------------------------- class CookiesTreeModel : public ui::TreeNodeModel<CookieTreeNode> { public: CookiesTreeModel(LocalDataContainer* data_container, ExtensionSpecialStoragePolicy* special_storage_policy, bool group_by_cookie_source); virtual ~CookiesTreeModel(); // Because non-cookie nodes are fetched in a background thread, they are not // present at the time the Model is created. The Model then notifies its // observers for every item added from databases, local storage, and // appcache. We extend the Observer interface to add notifications before and // after these batch inserts. class Observer : public ui::TreeModelObserver { public: virtual void TreeModelBeginBatch(CookiesTreeModel* model) {} virtual void TreeModelEndBatch(CookiesTreeModel* model) {} }; // This class defines the scope for batch updates. It can be created as a // local variable and the destructor will terminate the batch update, if one // has been started. class ScopedBatchUpdateNotifier { public: ScopedBatchUpdateNotifier(CookiesTreeModel* model, CookieTreeNode* node); ~ScopedBatchUpdateNotifier(); void StartBatchUpdate(); private: CookiesTreeModel* model_; CookieTreeNode* node_; bool batch_in_progress_; }; // ui::TreeModel methods: // Returns the set of icons for the nodes in the tree. You only need override // this if you don't want to use the default folder icons. virtual void GetIcons(std::vector<gfx::ImageSkia>* icons) OVERRIDE; // Returns the index of the icon to use for |node|. Return -1 to use the // default icon. The index is relative to the list of icons returned from // GetIcons. virtual int GetIconIndex(ui::TreeModelNode* node) OVERRIDE; // CookiesTreeModel methods: void DeleteAllStoredObjects(); // Deletes a specific node in the tree, identified by |cookie_node|, and its // subtree. void DeleteCookieNode(CookieTreeNode* cookie_node); // Filter the origins to only display matched results. void UpdateSearchResults(const string16& filter); // Returns the set of extensions which protect the data item represented by // this node from deletion. // Returns NULL if the node doesn't represent a protected data item or the // special storage policy is NULL. const ExtensionSet* ExtensionsProtectingNode( const CookieTreeNode& cookie_node); // Manages CookiesTreeModel::Observers. This will also call // TreeNodeModel::AddObserver so that it gets all the proper notifications. // Note that the converse is not true: simply adding a TreeModelObserver will // not get CookiesTreeModel::Observer notifications. virtual void AddCookiesTreeObserver(Observer* observer); virtual void RemoveCookiesTreeObserver(Observer* observer); // Methods that update the model based on the data retrieved by the browsing // data helpers. void PopulateAppCacheInfo(LocalDataContainer* container); void PopulateCookieInfo(LocalDataContainer* container); void PopulateDatabaseInfo(LocalDataContainer* container); void PopulateLocalStorageInfo(LocalDataContainer* container); void PopulateSessionStorageInfo(LocalDataContainer* container); void PopulateIndexedDBInfo(LocalDataContainer* container); void PopulateFileSystemInfo(LocalDataContainer* container); void PopulateQuotaInfo(LocalDataContainer* container); void PopulateServerBoundCertInfo(LocalDataContainer* container); void PopulateFlashLSOInfo(LocalDataContainer* container); BrowsingDataCookieHelper* GetCookieHelper(const std::string& app_id); LocalDataContainer* data_container() { return data_container_.get(); } private: enum CookieIconIndex { ORIGIN = 0, COOKIE = 1, DATABASE = 2 }; void NotifyObserverBeginBatch(); void NotifyObserverEndBatch(); void PopulateAppCacheInfoWithFilter(LocalDataContainer* container, ScopedBatchUpdateNotifier* notifier, const string16& filter); void PopulateCookieInfoWithFilter(LocalDataContainer* container, ScopedBatchUpdateNotifier* notifier, const string16& filter); void PopulateDatabaseInfoWithFilter(LocalDataContainer* container, ScopedBatchUpdateNotifier* notifier, const string16& filter); void PopulateLocalStorageInfoWithFilter(LocalDataContainer* container, ScopedBatchUpdateNotifier* notifier, const string16& filter); void PopulateSessionStorageInfoWithFilter(LocalDataContainer* container, ScopedBatchUpdateNotifier* notifier, const string16& filter); void PopulateIndexedDBInfoWithFilter(LocalDataContainer* container, ScopedBatchUpdateNotifier* notifier, const string16& filter); void PopulateFileSystemInfoWithFilter(LocalDataContainer* container, ScopedBatchUpdateNotifier* notifier, const string16& filter); void PopulateQuotaInfoWithFilter(LocalDataContainer* container, ScopedBatchUpdateNotifier* notifier, const string16& filter); void PopulateServerBoundCertInfoWithFilter( LocalDataContainer* container, ScopedBatchUpdateNotifier* notifier, const string16& filter); void PopulateFlashLSOInfoWithFilter(LocalDataContainer* container, ScopedBatchUpdateNotifier* notifier, const string16& filter); // Map of app ids to LocalDataContainer objects to use when retrieving // locally stored data. scoped_ptr<LocalDataContainer> data_container_; // The extension special storage policy; see ExtensionsProtectingNode() above. scoped_refptr<ExtensionSpecialStoragePolicy> special_storage_policy_; // The CookiesTreeModel maintains a separate list of observers that are // specifically of the type CookiesTreeModel::Observer. ObserverList<Observer> cookies_observer_list_; // If true, use the CanonicalCookie::Source attribute to group cookies. // Otherwise, use the CanonicalCookie::Domain attribute. bool group_by_cookie_source_; // If this is non-zero, then this model is batching updates (there's a lot of // notifications coming down the pipe). This is an integer is used to balance // calls to Begin/EndBatch() if they're called in a nested manner. int batch_update_; }; #endif // CHROME_BROWSER_BROWSING_DATA_COOKIES_TREE_MODEL_H_
{ "content_hash": "ea3430ad610d2857050a97610642054a", "timestamp": "", "source": "github", "line_count": 704, "max_line_length": 80, "avg_line_length": 37.25426136363637, "alnum_prop": 0.7318793609638922, "repo_name": "zcbenz/cefode-chromium", "id": "76735f5969b747d99daa1ca900fa725d79d87a44", "size": "27554", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "chrome/browser/browsing_data/cookies_tree_model.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "1174304" }, { "name": "Awk", "bytes": "9519" }, { "name": "C", "bytes": "76026099" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "157904700" }, { "name": "DOT", "bytes": "1559" }, { "name": "F#", "bytes": "381" }, { "name": "Java", "bytes": "3225038" }, { "name": "JavaScript", "bytes": "18180217" }, { "name": "Logos", "bytes": "4517" }, { "name": "Matlab", "bytes": "5234" }, { "name": "Objective-C", "bytes": "7139426" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "932901" }, { "name": "Python", "bytes": "8654916" }, { "name": "R", "bytes": "262" }, { "name": "Ragel in Ruby Host", "bytes": "3621" }, { "name": "Shell", "bytes": "1533012" }, { "name": "Tcl", "bytes": "277077" }, { "name": "XML", "bytes": "13493" } ], "symlink_target": "" }
<?php /** * Smarty plugin * @package Smarty * @subpackage PluginsModifier */ /** * Smarty spacify modifier plugin * * Type: modifier<br> * Name: spacify<br> * Purpose: add spaces between characters in a string * * @link http://smarty.php.net/manual/en/language.modifier.spacify.php spacify (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string $string input string * @param string $spacify_char string to insert between characters. * @return string */ function smarty_modifier_spacify($string, $spacify_char = ' ') { // well… what about charsets besides latin and UTF-8? return implode($spacify_char, preg_split('//' . Smarty::$_UTF8_MODIFIER, $string, -1, PREG_SPLIT_NO_EMPTY)); } ?>
{ "content_hash": "14a67081887a65e37813c0aa0b85e568", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 112, "avg_line_length": 28.14814814814815, "alnum_prop": 0.675, "repo_name": "imaschio/xkvmt", "id": "d5426161822ddf12cd8807ed9c5fa573c195587b", "size": "762", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "includes/smarty/plugins/modifier.spacify.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "1203" }, { "name": "CSS", "bytes": "930652" }, { "name": "HTML", "bytes": "126151" }, { "name": "JavaScript", "bytes": "1759063" }, { "name": "PHP", "bytes": "4783277" }, { "name": "Shell", "bytes": "583" }, { "name": "Smarty", "bytes": "452012" } ], "symlink_target": "" }
package org.vaadin.spring.security.web.authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; /** * Strategy used to handle a failed authentication attempt. * <p> * Typical behaviour might be to redirect the user to the authentication page (in the case of a form login) to * allow them to try again. More sophisticated logic might be implemented depending on the type of the exception. * For example, a {@link CredentialsExpiredException} might cause a redirect to a web controller which allowed the * user to change their password. * <p> * Vaadin Specific Strategy of {@link AuthenticationFailureHandler} */ public interface VaadinAuthenticationFailureHandler { /** * Called when an authentication attempt fails. * @param exception the exception which was thrown to reject the authentication request. */ void onAuthenticationFailure(AuthenticationException exception) throws Exception; }
{ "content_hash": "9a57836a201466444181cb290e4d3e32", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 114, "avg_line_length": 43.208333333333336, "alnum_prop": 0.7868852459016393, "repo_name": "fastnsilver/vaadin4spring", "id": "ad3ef7b47d3d6de683a3fe4a461da6698bce12b9", "size": "1638", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spring-vaadin-security/src/main/java/org/vaadin/spring/security/web/authentication/VaadinAuthenticationFailureHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "665" }, { "name": "Java", "bytes": "383776" } ], "symlink_target": "" }
package org.wso2.carbon.mdm.mobileservices.windows.services.wstep.impl; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.cxf.headers.Header; import org.apache.cxf.helpers.CastUtils; import org.apache.cxf.jaxws.context.WrappedMessageContext; import org.apache.cxf.message.Message; import org.w3c.dom.*; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementServiceImpl; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.mdm.mobileservices.windows.common.PluginConstants; import org.wso2.carbon.mdm.mobileservices.windows.common.beans.CacheEntry; import org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.CertificateGenerationException; import org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.SyncmlMessageFormatException; import org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.WAPProvisioningException; import org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.WindowsDeviceEnrolmentException; import org.wso2.carbon.mdm.mobileservices.windows.common.util.DeviceUtil; import org.wso2.carbon.mdm.mobileservices.windows.common.util.WindowsAPIUtils; import org.wso2.carbon.mdm.mobileservices.windows.operations.util.SyncmlCredentials; import org.wso2.carbon.mdm.mobileservices.windows.services.wstep.CertificateEnrollmentService; import org.wso2.carbon.mdm.mobileservices.windows.services.wstep.beans.AdditionalContext; import org.wso2.carbon.mdm.mobileservices.windows.services.wstep.beans.BinarySecurityToken; import org.wso2.carbon.mdm.mobileservices.windows.services.wstep.beans.RequestSecurityTokenResponse; import org.wso2.carbon.mdm.mobileservices.windows.services.wstep.beans.RequestedSecurityToken; import org.xml.sax.SAXException; import javax.annotation.Resource; import javax.jws.WebService; import javax.servlet.ServletContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.ws.BindingType; import javax.xml.ws.Holder; import javax.xml.ws.WebServiceContext; import javax.xml.ws.handler.MessageContext; import javax.xml.ws.soap.Addressing; import javax.xml.ws.soap.SOAPBinding; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.List; /** * Implementation class of CertificateEnrollmentService interface. This class implements MS-WSTEP * protocol. */ @WebService(endpointInterface = PluginConstants.CERTIFICATE_ENROLLMENT_SERVICE_ENDPOINT, targetNamespace = PluginConstants.DEVICE_ENROLLMENT_SERVICE_TARGET_NAMESPACE) @Addressing(enabled = true, required = true) @BindingType(value = SOAPBinding.SOAP12HTTP_BINDING) public class CertificateEnrollmentServiceImpl implements CertificateEnrollmentService { private static Log log = LogFactory.getLog(CertificateEnrollmentServiceImpl.class); private X509Certificate rootCACertificate; private String pollingFrequency; private String provisioningURL; private String domain; @Resource private WebServiceContext context; /** * This method implements MS-WSTEP for Certificate Enrollment Service. * * @param tokenType - Device Enrolment Token type is received via device * @param requestType - WS-Trust request type * @param binarySecurityToken - CSR from device * @param additionalContext - Device type and OS version is received * @param response - Response will include wap-provisioning xml */ @Override public void requestSecurityToken(String tokenType, String requestType, String binarySecurityToken, AdditionalContext additionalContext, Holder<RequestSecurityTokenResponse> response) throws WindowsDeviceEnrolmentException, UnsupportedEncodingException, WAPProvisioningException { String headerBinarySecurityToken = null; String headerTo = null; List<Header> headers = getHeaders(); for (Header headerElement : headers != null ? headers : null) { String nodeName = headerElement.getName().getLocalPart(); if (nodeName.equals(PluginConstants.SECURITY)) { Element element = (Element) headerElement.getObject(); headerBinarySecurityToken = element.getFirstChild().getNextSibling().getFirstChild().getTextContent(); } if (nodeName.equals(PluginConstants.TO)) { Element toElement = (Element) headerElement.getObject(); headerTo = toElement.getFirstChild().getTextContent(); } } String[] splitEmail = headerTo.split("(/ENROLLMENTSERVER)"); String email = splitEmail[PluginConstants.CertificateEnrolment.EMAIL_SEGMENT]; String[] splitDomain = email.split("(EnterpriseEnrollment.)"); domain = splitDomain[PluginConstants.CertificateEnrolment.DOMAIN_SEGMENT]; provisioningURL = PluginConstants.CertificateEnrolment.ENROLL_SUBDOMAIN + domain + PluginConstants.CertificateEnrolment.SYNCML_PROVISIONING_SERVICE_URL; List<ConfigurationEntry> tenantConfigurations; try { if (WindowsAPIUtils.getTenantConfigurationData() != null) { tenantConfigurations = WindowsAPIUtils.getTenantConfigurationData(); for (ConfigurationEntry configurationEntry : tenantConfigurations) { if ((PluginConstants.TenantConfigProperties.NOTIFIER_FREQUENCY.equals( configurationEntry.getName()))) { pollingFrequency = configurationEntry.getValue().toString(); } else { pollingFrequency = PluginConstants.TenantConfigProperties.DEFAULT_FREQUENCY; } } } else { pollingFrequency = PluginConstants.TenantConfigProperties.DEFAULT_FREQUENCY; String msg = "Tenant configurations are not initialized yet."; log.error(msg); } } catch (DeviceManagementException e) { String msg = "Error occurred in while getting tenant configurations."; log.error(msg); throw new WindowsDeviceEnrolmentException(msg, e); } ServletContext ctx = (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT); File wapProvisioningFile = (File) ctx.getAttribute(PluginConstants.CONTEXT_WAP_PROVISIONING_FILE); if (log.isDebugEnabled()) { log.debug("Received CSR from Device:" + binarySecurityToken); } String wapProvisioningFilePath = wapProvisioningFile.getPath(); RequestSecurityTokenResponse requestSecurityTokenResponse = new RequestSecurityTokenResponse(); requestSecurityTokenResponse.setTokenType(PluginConstants.CertificateEnrolment.TOKEN_TYPE); String encodedWap; try { encodedWap = prepareWapProvisioningXML(binarySecurityToken, wapProvisioningFilePath, headerBinarySecurityToken); RequestedSecurityToken requestedSecurityToken = new RequestedSecurityToken(); BinarySecurityToken binarySecToken = new BinarySecurityToken(); binarySecToken.setValueType(PluginConstants.CertificateEnrolment.VALUE_TYPE); binarySecToken.setEncodingType(PluginConstants.CertificateEnrolment.ENCODING_TYPE); binarySecToken.setToken(encodedWap); requestedSecurityToken.setBinarySecurityToken(binarySecToken); requestSecurityTokenResponse.setRequestedSecurityToken(requestedSecurityToken); requestSecurityTokenResponse.setRequestID(PluginConstants.CertificateEnrolment.REQUEST_ID); response.value = requestSecurityTokenResponse; } catch (CertificateGenerationException e) { String msg = "Problem occurred in generating certificate."; log.error(msg, e); throw new WindowsDeviceEnrolmentException(msg, e); } catch (WAPProvisioningException e) { String msg = "Problem occurred in generating wap-provisioning file."; log.error(msg, e); throw new WAPProvisioningException(msg, e); } finally { PrivilegedCarbonContext.endTenantFlow(); } } /** * Method used to Convert the Document object into a String. * * @param document - Wap provisioning XML document * @return - String representation of wap provisioning XML document * @throws TransformerException */ private String convertDocumentToString(Document document) throws TransformerException { DOMSource DOMSource = new DOMSource(document); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(DOMSource, streamResult); return stringWriter.toString(); } /** * This method prepares the wap-provisioning file by including relevant certificates etc * * @param binarySecurityToken - CSR from device * @param wapProvisioningFilePath - File path of wap-provisioning file * @return - base64 encoded final wap-provisioning file as a String * @throws CertificateGenerationException * @throws org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.WAPProvisioningException */ public String prepareWapProvisioningXML( String binarySecurityToken, String wapProvisioningFilePath, String headerBst) throws CertificateGenerationException, WAPProvisioningException, WindowsDeviceEnrolmentException { String rootCertEncodedString; String signedCertEncodedString; X509Certificate signedCertificate; CertificateManagementServiceImpl impl = CertificateManagementServiceImpl.getInstance(); Base64 base64Encoder = new Base64(); try { rootCACertificate = (X509Certificate) impl.getCACertificate(); rootCertEncodedString = base64Encoder.encodeAsString(rootCACertificate.getEncoded()); } catch (KeystoreException e) { String msg = "CA certificate cannot be generated"; log.error(msg, e); throw new CertificateGenerationException(msg, e); } catch (CertificateEncodingException e) { String msg = "CA certificate cannot be encoded."; log.error(msg, e); throw new CertificateGenerationException(msg, e); } try { signedCertificate = impl.getSignedCertificateFromCSR(binarySecurityToken); signedCertEncodedString = base64Encoder.encodeAsString(signedCertificate.getEncoded()); } catch (CertificateEncodingException e) { String msg = "Singed certificate cannot be encoded."; log.error(msg, e); throw new CertificateGenerationException(msg, e); } catch (KeystoreException e) { String msg = "CA certificate cannot be generated"; log.error(msg, e); throw new CertificateGenerationException(msg, e); } DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; String wapProvisioningString; try { builder = domFactory.newDocumentBuilder(); Document document = builder.parse(wapProvisioningFilePath); NodeList wapParm = document.getElementsByTagName(PluginConstants.CertificateEnrolment.PARM); Node caCertificatePosition = wapParm.item(PluginConstants.CertificateEnrolment.CA_CERTIFICATE_POSITION); //Adding SHA1 CA certificate finger print to wap-provisioning xml. caCertificatePosition.getParentNode().getAttributes().getNamedItem(PluginConstants. CertificateEnrolment.TYPE).setTextContent(String.valueOf( DigestUtils.sha1Hex(rootCACertificate.getEncoded())).toUpperCase()); //Adding encoded CA certificate to wap-provisioning file after removing new line // characters. NamedNodeMap rootCertAttributes = caCertificatePosition.getAttributes(); Node rootCertNode = rootCertAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE); rootCertEncodedString = rootCertEncodedString.replaceAll("\n", ""); rootCertNode.setTextContent(rootCertEncodedString); if (log.isDebugEnabled()) { log.debug("Root certificate: " + rootCertEncodedString); } Node signedCertificatePosition = wapParm.item(PluginConstants.CertificateEnrolment. SIGNED_CERTIFICATE_POSITION); //Adding SHA1 signed certificate finger print to wap-provisioning xml. signedCertificatePosition.getParentNode().getAttributes().getNamedItem(PluginConstants. CertificateEnrolment.TYPE).setTextContent(String.valueOf( DigestUtils.sha1Hex(signedCertificate.getEncoded())).toUpperCase()); //Adding encoded signed certificate to wap-provisioning file after removing new line // characters. NamedNodeMap clientCertAttributes = signedCertificatePosition.getAttributes(); Node clientEncodedNode = clientCertAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE); signedCertEncodedString = signedCertEncodedString.replaceAll("\n", ""); clientEncodedNode.setTextContent(signedCertEncodedString); if (log.isDebugEnabled()) { log.debug("Signed certificate: " + signedCertEncodedString); } //Adding domainName to wap-provisioning xml. Node domainPosition = wapParm.item(PluginConstants.CertificateEnrolment.DOMAIN_POSITION); NamedNodeMap domainAttribute = domainPosition.getAttributes(); Node domainNode = domainAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE); domainNode.setTextContent(domain); //Adding Next provisioning service URL to wap-provisioning xml. Node syncmlServicePosition = wapParm.item(PluginConstants.CertificateEnrolment. SYNCML_PROVISIONING_ADDR_POSITION); NamedNodeMap syncmlServiceAttribute = syncmlServicePosition.getAttributes(); Node syncmlServiceNode = syncmlServiceAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE); syncmlServiceNode.setTextContent(provisioningURL); // Adding user name auth token to wap-provisioning xml. Node userNameAuthPosition = wapParm.item(PluginConstants.CertificateEnrolment.APPAUTH_USERNAME_POSITION); NamedNodeMap appServerAttribute = userNameAuthPosition.getAttributes(); Node authNameNode = appServerAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE); CacheEntry cacheEntry = (CacheEntry) DeviceUtil.getCacheEntry(headerBst); String userName = cacheEntry.getUsername(); authNameNode.setTextContent(cacheEntry.getUsername()); DeviceUtil.removeToken(headerBst); String password = DeviceUtil.generateRandomToken(); Node passwordAuthPosition = wapParm.item(PluginConstants.CertificateEnrolment.APPAUTH_PASSWORD_POSITION); NamedNodeMap appSrvPasswordAttribute = passwordAuthPosition.getAttributes(); Node authPasswordNode = appSrvPasswordAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE); authPasswordNode.setTextContent(password); String requestSecurityTokenResponse = new SyncmlCredentials().generateRST(userName, password); DeviceUtil.persistChallengeToken(requestSecurityTokenResponse, null, userName); // Get device polling frequency from the tenant Configurations. Node numberOfFirstRetries = wapParm.item(PluginConstants.CertificateEnrolment.POLLING_FREQUENCY_POSITION); NamedNodeMap pollingAttributes = numberOfFirstRetries.getAttributes(); Node pollValue = pollingAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE); pollValue.setTextContent(pollingFrequency); if (log.isDebugEnabled()) { log.debug("Username: " + userName + "Password: " + requestSecurityTokenResponse); } wapProvisioningString = convertDocumentToString(document); } catch (ParserConfigurationException e) { String msg = "Problem occurred in parsing wap-provisioning.xml file."; log.error(msg, e); throw new WAPProvisioningException(msg, e); } catch (DeviceManagementException e) { String msg = "Error occurred in while getting CA and Root certificates."; log.error(msg, e); throw new WindowsDeviceEnrolmentException(msg, e); } catch (CertificateEncodingException e) { String msg = "Error occurred in while encoding certificates."; log.error(msg, e); throw new WindowsDeviceEnrolmentException(msg, e); } catch (UnsupportedEncodingException e) { String msg = "Error occurred in while encoding wap-provisioning file."; log.error(msg, e); throw new WindowsDeviceEnrolmentException(msg, e); } catch (SAXException e) { String msg = "Error occurred in while parsing wap-provisioning.xml file."; log.error(msg, e); throw new WAPProvisioningException(msg, e); } catch (TransformerException e) { String msg = "Error occurred in while transforming wap-provisioning.xml file."; log.error(msg, e); throw new WAPProvisioningException(msg, e); } catch (IOException e) { String msg = "Error occurred in while getting wap-provisioning.xml file."; log.error(msg, e); throw new WAPProvisioningException(msg, e); } catch (SyncmlMessageFormatException e) { String msg = "Error occurred in while getting CA and Root certificates."; log.error(msg, e); throw new WindowsDeviceEnrolmentException(msg, e); } return base64Encoder.encodeAsString(wapProvisioningString.getBytes()); } /** * This method get the soap request header contents * * @return Header object type,soap header tag list */ private List<Header> getHeaders() { MessageContext messageContext = context.getMessageContext(); if (messageContext == null || !(messageContext instanceof WrappedMessageContext)) { return null; } Message message = ((WrappedMessageContext) messageContext).getWrappedMessage(); return CastUtils.cast((List<?>) message.get(Header.HEADER_LIST)); } }
{ "content_hash": "aeaed078607113fbc40788f0fe6c46a6", "timestamp": "", "source": "github", "line_count": 371, "max_line_length": 118, "avg_line_length": 53.97035040431267, "alnum_prop": 0.7055386305748389, "repo_name": "jeradrutnam/product-mdm", "id": "cd409c52196918a604b6c8eee571b3f2bb4a3f7c", "size": "20695", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/mobile-agents/windows/jax-rs/src/main/java/org/wso2/carbon/mdm/mobileservices/windows/services/wstep/impl/CertificateEnrollmentServiceImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3319" }, { "name": "CSS", "bytes": "494835" }, { "name": "HTML", "bytes": "1159251" }, { "name": "Java", "bytes": "1869666" }, { "name": "JavaScript", "bytes": "2077396" }, { "name": "PLSQL", "bytes": "85302" }, { "name": "PLpgSQL", "bytes": "34379" }, { "name": "Shell", "bytes": "5635" } ], "symlink_target": "" }
package com.choonster.mcmoddecompiler; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; import com.choonster.mcmoddecompiler.commandline.Arguments; import java.io.IOException; import java.nio.file.Path; import java.util.List; public class Main { public static void main(String[] args) { Arguments arguments = new Arguments(); JCommander jCommander = new JCommander(); jCommander.setProgramName("java -jar MinecraftModDecompiler.jar"); jCommander.addObject(arguments); try { jCommander.parse(args); } catch (ParameterException e) { System.out.printf("Error: %s\n\n", e.getMessage()); jCommander.usage(); exit(); } ModDecompiler decompiler = null; try { decompiler = new ModDecompiler(arguments.modDirectory, arguments.outputDirectory, arguments.mappingsDirectory); } catch (IOException e) { System.err.println("Exception initialising MCP data"); e.printStackTrace(); exit(); } List<Path> errors = decompiler.decompile(); if (errors.size() > 0) { System.err.println("Errored mods:"); System.err.println(errors.toString()); exit(); } } private static void exit() { System.exit(-1); } }
{ "content_hash": "f2b3553ba4baef64a3f20203887b9b79", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 114, "avg_line_length": 24.46938775510204, "alnum_prop": 0.7197664720600501, "repo_name": "Choonster/MinecraftModDecompiler", "id": "96444ccef5cac7f2fd4c4fee4880bb1fc6b2b1bd", "size": "1199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/choonster/mcmoddecompiler/Main.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "7393" }, { "name": "Shell", "bytes": "163" } ], "symlink_target": "" }
export { Movie } from './movie.model'; export { Showtime } from './showtime.model'; export { Cinema } from './cinema'; export { CinemaHall } from './cinema-hall.model'; export { CinemaHallSeat } from './cinema-hall-seat.model'; export { Booking } from './booking.model'; export * from './ticket.model'; export * from './account.model';
{ "content_hash": "28b98fca8c78aa8ad396f13b21c2750a", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 58, "avg_line_length": 41.875, "alnum_prop": 0.6805970149253732, "repo_name": "bkorobeinikov/movieapp-ionic", "id": "aee499728460f4991ee5acb05ba373a56acc5d52", "size": "336", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/store/models/index.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "44167" }, { "name": "HTML", "bytes": "31283" }, { "name": "JavaScript", "bytes": "990" }, { "name": "TypeScript", "bytes": "166185" } ], "symlink_target": "" }
<?php namespace SilverStripe\UserForms\Modifier; use SilverStripe\Forms\SegmentFieldModifier\SlugSegmentFieldModifier; class UnderscoreSegmentFieldModifier extends SlugSegmentFieldModifier { public function getPreview($value) { return str_replace('-', '_', parent::getPreview($value) ?? ''); } public function getSuggestion($value) { return str_replace('-', '_', parent::getSuggestion($value) ?? ''); } }
{ "content_hash": "d6a8965c04abe342711ed86b8f4ceef7", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 74, "avg_line_length": 24.944444444444443, "alnum_prop": 0.688195991091314, "repo_name": "silverstripe/silverstripe-userforms", "id": "d50ea31002db0eef446190ea67d00a671cdaf33d", "size": "449", "binary": false, "copies": "1", "ref": "refs/heads/5", "path": "code/Modifier/UnderscoreSegmentFieldModifier.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Gherkin", "bytes": "10558" }, { "name": "JavaScript", "bytes": "149714" }, { "name": "PHP", "bytes": "423947" }, { "name": "SCSS", "bytes": "5383" }, { "name": "Scheme", "bytes": "8352" } ], "symlink_target": "" }
import React from "react"; import PropTypes from "prop-types"; import styles from "./Document.styl"; import hljs from 'highlight.js' import select from 'select' require('highlight.js/styles/color-brewer.css'); import {getReactCode} from '../../utils' const NodeTypes = { Element: 1, }; function removeIds(o) { if (o.nodeType === NodeTypes.Element) { o.removeAttribute('id'); if (o.nodeName !== 'SVG') { for (let child of o.childNodes) { removeIds(child); } } } } function getOuterHtmlCode(o, depth = 0, jsx = false) { let spaces = ''; for (let i = 0; i < depth; ++i) { spaces += ' '; } let tagName = o.tagName.toLowerCase(); switch (tagName) { case 'img': case 'path': case 'span': return `${spaces}${o.outerHTML}\n`; default: return `${spaces}<${tagName} style="${o.style.cssText}">\n${Array.prototype.map.call(o.childNodes, child => getOuterHtmlCode(child, depth + 1)).join('')}${spaces}</${tagName}>\n` } } export default class LayerInfo extends React.Component { static propTypes = { layer: PropTypes.string, }; componentWillMount() { this.state = {codeMode: 'react'}; } selectCodeMode = (e) => { this.setState({codeMode: e.target.value}); }; render() { let {layer} = this.props; if (!layer) { return <div className={styles['info']}> <div className={styles['empty']}>Select a layer</div> </div> } else { let _o = document.getElementById(layer); let o = _o.cloneNode(); o.innerHTML = _o.innerHTML; removeIds(o); o.style.cssText = o.style.cssText.replace(/top:[^;]*;/, '').replace(/left:[^;]*;/, ''); let ratio = _o.clientWidth > 208 ? 208 / _o.clientWidth : 1; return <div className={styles['info']}> <div className={styles['section']}> <div className={styles['section-header']}>Preview</div> <div className={styles['previewer']}> <div dangerouslySetInnerHTML={{__html: o.outerHTML}} style={{ position: 'relative', width: _o.clientWidth, height: _o.clientHeight * ratio, transformOrigin: 'left top', transform: `scale(${ratio})`, }}/> </div> </div> <div className={styles['section']}> <div className={styles['section-header']}>CSS (outer)</div> <pre className={styles['code']} dangerouslySetInnerHTML={{__html: hljs.highlight('css', o.style.cssText.replace(/;\s+/g, ';\n')).value}}/> </div> <div className={styles['section']}> <div className={styles['section-header']}> <span>Code</span> <select style={{marginLeft: 8}} onChange={this.selectCodeMode} value={this.state.codeMode}> <option value='html'>html</option> <option value='react'>react</option> </select> <a onClick={() => select(document.getElementById('code'))} style={{ float: 'right', fontWeight: 'normal', marginRight: 8, color: '#6e9ee1', cursor: 'pointer', }}>select code</a> </div> {this.state.codeMode === 'html' ? <pre id='code' className={styles['code']} dangerouslySetInnerHTML={{__html: hljs.highlight('xml', getOuterHtmlCode(o)).value}}> </pre> : <pre id='code' className={styles['code']} dangerouslySetInnerHTML={{__html: hljs.highlight('jsx', getReactCode(o)).value}}> </pre> } </div> </div>; } } }
{ "content_hash": "2f9612f76b9dc01719d9f0303321372f", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 184, "avg_line_length": 32.85840707964602, "alnum_prop": 0.540802585510369, "repo_name": "zjuasmn/sketch-react", "id": "58dd702520bb48afedf924d05a72fe6fb26cfb07", "size": "3713", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/Document/LayerInfo.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5628" }, { "name": "HTML", "bytes": "268" }, { "name": "JavaScript", "bytes": "1618991" } ], "symlink_target": "" }
define(['Graft'] , function (Graft) { describe('View' , function () { beforeEach(function () { this.view = new Graft.View(); }); afterEach(function () { this.view.remove(); }); describe('service injection', function () { beforeEach(function () { this.service = {service: true}; Graft.Directives.registerService('service', this.service); }); afterEach(function () { Graft.Directives.unregisterService('service'); }); it('service gets array of items and injects them', function () { var klass = Graft.View.extend({ services: [ 'service' ] }), view = new klass(); chai.expect(view.service).to.equal(this.service); }); }); describe('remove' , function () { it('marks as removed when removed' , function () { chai.expect(this.view._removed).to.not.equal(true); this.view.remove(); chai.expect(this.view._removed).to.equal(true); }); it('fires the remove event' , function (done) { this.view.on('remove' , function () { done(); }); this.view.remove(); }); }); describe('template' , function () { it('renders string as template' , function () { var x = Graft.View.extend({ template: 'eh' }); this.view = new x; chai.expect(this.view.$el.text()).to.equal('eh'); }); it('renders _ templates' , function () { var x = Graft.View.extend({ template: _.template('eh') }); this.view = new x; chai.expect(this.view.$el.text()).to.equal('eh'); }); it('renders templates automatically with options as variable templates' , function () { var x = Graft.View.extend({ template: _.template('eh<%=number%>') }); this.view = new x({ number: 12 }); chai.expect(this.view.$el.text()).to.equal('eh12'); }); it('renders templates with options and extend function as variable templates' , function () { var x = Graft.View.extend({ template: _.template('eh-<%=number%>-<%=alpha%>-<%=beta%>'), getTemplateOptions: function () { return {number: 99, alpha: 'a'}; } }); this.view = new x({ number: 12, beta: 'b' }); chai.expect(this.view.$el.text()).to.equal('eh-99-a-b'); }); it('renders templates automatically with model exposed as variable templates' , function () { var x = Graft.View.extend({ template: _.template('eh<%=model.get("number")%>') }), model = new Backbone.Model({ number: 99 }); this.view = new x({ model: model }); chai.expect(this.view.$el.text()).to.equal('eh99'); }); }); describe('append' , function () { it('appends subview' , function () { var y = new (Graft.View.extend({ template: 'barf' }))(); this.view.append(y); chai.expect(this.view.$el.html()).to.equal('<div>barf</div>'); }); it('appends multiple subview' , function () { var y = new (Graft.View.extend({ template: 'y' }))(), z = new (Graft.View.extend({ template: 'z' }))(); this.view.append(y); this.view.append(z); chai.expect(this.view.$el.html()).to.equal('<div>y</div><div>z</div>'); }); it('appends specific CSS selector' , function () { var y = new (Graft.View.extend({ template: 'y<div class="z"></div>' }))(), z = new (Graft.View.extend({ template: 'z' }))(); y.append('.z' , z); chai.expect(y.$el.html()).to.equal('y<div class="z"><div>z</div></div>'); }); it('registers appended subview' , function () { var y = new (Graft.View.extend({ template: 'barf' }))(); this.view.append(y); chai.expect(this.view._subViews).to.have.property(this.view.getIdForView(y)).to.equal(y); }); }); describe('prepend' , function () { it('prepend subview' , function () { var y = new (Graft.View.extend({ template: 'barf' }))(), z = new (Graft.View.extend({ template: 'z' }))(); this.view.append(y); this.view.prepend(z); chai.expect(this.view.$el.html()).to.equal('<div>z</div><div>barf</div>'); }); it('appends specific CSS selector' , function () { var y = new (Graft.View.extend({ template: 'y<div class="z">hello</div>' }))(), z = new (Graft.View.extend({ template: 'z' }))(); y.prepend('.z' , z); chai.expect(y.$el.html()).to.equal('y<div class="z"><div>z</div>hello</div>'); }); }); describe('replace' , function () { it('replaces content with subviews' , function () { this.view.$el.html('replace me'); chai.expect(this.view.$el.html()).to.equal('replace me'); var y = new (Graft.View.extend({ template: 'barf' }))(); this.view.replace(y); chai.expect(this.view.$el.html()).to.equal('<div>barf</div>'); }); it('replaces content with subview of specfic CSS selector' , function () { this.view.$el.html('<div class="x">replace me</div>'); chai.expect(this.view.$el.find('.x').html()).to.equal('replace me'); var something = new (Graft.View.extend({ template: 'x-content' }))(); this.view.replace('.x' , something); chai.expect(this.view.$el.find('.x').html()).to.equal('<div>x-content</div>'); }); it('registers subview with selector' , function () { this.view.$el.html('<div class="x"></div>'); var something = new (Graft.View.extend({ template: 'x-content' }))(); this.view.replace('.x' , something); chai.expect(this.view._subViews).to.have.property('.x').to.equal(something); }); it('removes previous subview with same selector of new replace' , function () { this.view.$el.html('<div class="x"></div>'); var something = new (Graft.View.extend({ template: 'x-content' }))(); this.view.replace('.x' , something); var newer = new (Graft.View.extend({ template: 'x-content' }))(); this.view.replace('.x' , newer); chai.expect(something._removed).to.equal(true); chai.expect(this.view._subViews).to.have.property('.x').to.equal(newer); }); }); describe('relayEvents', function () { beforeEach(function () { this.view = new Graft.View(); this.relayed = new Graft.View(); }); it('#bindRelayEventsToView should relay event', function (callback) { this.view.bindRelayEventsToView(this.relayed, ['select']); this.view.on('select', function () { callback(); }); this.relayed.trigger('select'); }); it('#unbindRelayEventsFromView should remove event', function () { this.view.bindRelayEventsToView(this.relayed, ['select']); this.view.on('select', function () { throw Error('should not of been called'); }); this.view.unbindRelayEventsFromView(this.relayed, ['select']); this.relayed.trigger('select'); }); }); describe('Element Directives', function () { it('#createElementDirective instantiates the directive class', function (callback) { var directiveKlass = function () { callback(); }; this.view = new Graft.View(); this.view.createElementDirective(directiveKlass, this.view.el, {$parentScope: {}}); }); it('#createElementDirective instantiates the directive class grabbing options from data attributes', function (callback) { var $el = Backbone.$('<div data-attribute="123"></div>'), view = new Graft.View(), directiveKlass = function (o) { chai.expect(o.attribute).to.equal(123); callback(); }; view.createElementDirective(directiveKlass, $el[0], {$parentScope: {}}); }); }); describe('#processDirectives', function () { beforeEach(function () { this.directiveKlass = Backbone.View.extend({ className: 'my-directive', }); Graft.Directives.registerElement('my-directive', this.directiveKlass); this.klass = Graft.View.extend({ template: _.template('<div><my-directive></my-directive></div>') }); }); afterEach(function () { Graft.Directives.unregisterElement('my-directive'); }); it('creates registered directive instance', function (callback) { this.directiveKlass.prototype.initialize = function () { callback(); }; var view = new (this.klass); }); it('creates registered directive class from html and replaces the el', function () { var view = new (this.klass); chai.expect(view.$('.my-directive')).to.have.length(1); chai.expect(view.$('my-directive')).to.have.length(0); }); }); describe('Attribute Directives', function () { it('#createAttributeDirective should instantiate given function with given element', function (callback) { var fakeEl = {}; var fakeVal = {a:1}; var fakeDirective = function (o) { if (o.el != fakeEl) { callback('not the el'); } else if (fakeVal !== o.directiveValue) { callback('not the directive value'); } else { callback(); } }; var x = new Graft.View(); x.createAttributeDirective(fakeDirective, fakeEl, 'blah', fakeVal); }); it('should create attribute directive from nested child', function (callback) { var attrDir = function () { callback(); }; var fake = Graft.View.extend({ template: '<div><div xe-attr class="blah"></div></div>' }); Graft.Directives.registerAttribute('xe-attr', attrDir); new fake(); Graft.Directives.unregisterElement('xe-attr'); }); }); describe('Transclusion', function () { beforeEach(function () { this.transcludableKlass = Graft.View.extend({ transclude: true, template: '<div class="one"></div><div class="two basket" transclude></div>' }); Graft.Directives.registerElement('transcludable', this.transcludableKlass); }); afterEach(function () { Graft.Directives.unregisterElement('transcludable'); }); it('#transcludedElements puts the elements in the basket', function () { var element = $('<span></span>'); var view = new (this.transcludableKlass)({ transcludedElements: element }); chai.expect($.contains(view.$el.find('.basket')[0], element[0])).to.be.true; }); it('#transcludedElements automatically gets provided content', function () { var elementDirective = Graft.View.extend({ template: '<transcludable><span class="find-me"></span></transcludable>' }); var inst = new elementDirective(); chai.expect(inst.$('.find-me').parent().hasClass('basket')).to.be.true; }); }); }); });
{ "content_hash": "cd48a1e249fd3f4c58dc1e89848daa9f", "timestamp": "", "source": "github", "line_count": 343, "max_line_length": 128, "avg_line_length": 33.80758017492711, "alnum_prop": 0.5373404622283546, "repo_name": "inlineblock/graft", "id": "58d52a5c4e4338a19d9537b4f70ed219d1d0a4b0", "size": "11596", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "specs/View_spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1520" }, { "name": "JavaScript", "bytes": "38122" }, { "name": "Ruby", "bytes": "3250" } ], "symlink_target": "" }
/* eslint-disable object-shorthand, func-names, guard-for-in, no-restricted-syntax, comma-dangle, no-param-reassign, max-len */ window.DiscussionMixins = { computed: { discussionCount: function () { return Object.keys(this.discussions).length; }, resolvedDiscussionCount: function () { let resolvedCount = 0; for (const discussionId in this.discussions) { const discussion = this.discussions[discussionId]; if (discussion.isResolved()) { resolvedCount += 1; } } return resolvedCount; }, unresolvedDiscussionCount: function () { let unresolvedCount = 0; for (const discussionId in this.discussions) { const discussion = this.discussions[discussionId]; if (!discussion.isResolved()) { unresolvedCount += 1; } } return unresolvedCount; } } };
{ "content_hash": "621a210dec1217afd7052b24988e61f0", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 127, "avg_line_length": 25.62857142857143, "alnum_prop": 0.6231884057971014, "repo_name": "dplarson/gitlabhq", "id": "36c4abf02cf065e63348bb4dec2718ec2f590529", "size": "897", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "app/assets/javascripts/diff_notes/mixins/discussion.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "536999" }, { "name": "Gherkin", "bytes": "116570" }, { "name": "HTML", "bytes": "1044163" }, { "name": "JavaScript", "bytes": "2193246" }, { "name": "Ruby", "bytes": "11711128" }, { "name": "Shell", "bytes": "27251" }, { "name": "Vue", "bytes": "196242" } ], "symlink_target": "" }
<!DOCTYPE html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="keywords" content=" "> <title>Page Not Found | Statistical Mechanics: A Primer</title> <link rel="stylesheet" href="css/syntax.css"> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <!--<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">--> <link rel="stylesheet" href="css/modern-business.css"> <link rel="stylesheet" href="css/lavish-bootstrap.css"> <link rel="stylesheet" href="css/customstyles.css"> <link rel="stylesheet" href="css/theme-blue.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script> <script src="js/jquery.navgoco.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/2.0.0/anchor.min.js"></script> <script src="js/toc.js"></script> <script src="js/customscripts.js"></script> <link rel="shortcut icon" href="images/favicon.ico"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <link rel="alternate" type="application/rss+xml" title="" href="AmbroseYim.github.iofeed.xml"> <script> $(document).ready(function() { // Initialize navgoco with default options $("#mysidebar").navgoco({ caretHtml: '', accordion: true, openClass: 'active', // open save: false, // leave false or nav highlighting doesn't work right cookie: { name: 'navgoco', expires: false, path: '/' }, slide: { duration: 400, easing: 'swing' } }); $("#collapseAll").click(function(e) { e.preventDefault(); $("#mysidebar").navgoco('toggle', false); }); $("#expandAll").click(function(e) { e.preventDefault(); $("#mysidebar").navgoco('toggle', true); }); }); </script> <script> $(function () { $('[data-toggle="tooltip"]').tooltip() }) </script> </head> <body> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container topnavlinks"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="fa fa-home fa-lg navbar-brand" href="index.html">&nbsp;<span class="projectTitle"> Stat Mech 101</span></a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <!-- entries without drop-downs appear here --> <li><a href="news">News</a></li> <!-- entries with drop-downs appear here --> <!-- conditional logic to control which topnav appears for the audience defined in the configuration file.--> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Jekyll Resources<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="https://github.com/tomjohnson1492/documentation-theme-jekyll" target="_blank">Github Repo</a></li> <li><a href="https://talk.jekyllrb.com" target="_blank">Jekyll Talk</a></li> <li><a href="http://jekyllrb.com/docs/home/" target="_blank">Jekyll documentation</a></li> <li><a href="http://stackoverflow.com/questions/tagged/jekyll" target="_blank">Jekyll on Stack Overflow</a></li> <li><a href="http://idratherbewriting.com/category-jekyll/" target="_blank">Jekyll on my blog</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Products<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="mydoc_introduction.html">Jekyll Documentation Theme</a></li> <li><a href="p1_landing_page.html">Product 1</a></li> </ul> </li> <li><a class="email" title="Submit feedback" href="#" onclick="javascript:window.location='mailto:[email protected]?subject=Stat Mech 101 f eedback&body=I have some feedback about the Page Not Found page: ' + window.location.href;"><i class="fa fa-envelope-o"></i> Feedback</a><li> <!--comment out this block if you want to hide search--> <li> <!--start search--> <div id="search-demo-container"> <input type="text" id="search-input" placeholder="search..."> <ul id="results-container"></ul> </div> <script src="js/jekyll-search.js" type="text/javascript"></script> <script type="text/javascript"> SimpleJekyllSearch.init({ searchInput: document.getElementById('search-input'), resultsContainer: document.getElementById('results-container'), dataSource: 'search.json', searchResultTemplate: '<li><a href="{url}" title="Page Not Found">{title}</a></li>', noResultsText: 'No results found.', limit: 10, fuzzy: true, }) </script> <!--end search--> </li> </ul> </div> </div> <!-- /.container --> </nav> <!-- Page Content --> <div class="container"> <div class="col-lg-12">&nbsp;</div> <!-- Content Row --> <div class="row"> <!-- Sidebar Column --> <div class="col-md-3"> <ul id="mysidebar" class="nav"> <li class="sidebarTitle"> </li> <li> <a href="#">Products</a> <ul> <li><a href="news.html">News</a></li> <li><a href="mydoc_introduction.html">Theme instructions</a></li> <li><a href="p1_landing_page.html">Product 1</a></li> </ul> <!-- if you aren't using the accordion, uncomment this block: <p class="external"> <a href="#" id="collapseAll">Collapse All</a> | <a href="#" id="expandAll">Expand All</a> </p> --> </li> </ul> </div> <!-- this highlights the active parent class in the navgoco sidebar. this is critical so that the parent expands when you're viewing a page. This must appear below the sidebar code above. Otherwise, if placed inside customscripts.js, the script runs before the sidebar code runs and the class never gets inserted.--> <script>$("li.active").parents('li').toggleClass("active");</script> <!-- Content Column --> <div class="col-md-9"> <div class="post-header"> <h1 class="post-title-main">Page Not Found</h1> </div> <div class="post-content"> <!-- this handles the automatic toc. use ## for subheads to auto-generate the on-page minitoc. if you use html tags, you must supply an ID for the heading element in order for it to appear in the minitoc. --> <script> $( document ).ready(function() { // Handler for .ready() called. $('#toc').toc({ minimumHeaders: 0, listType: 'ul', showSpeed: 0, headers: 'h2,h3,h4' }); /* this offset helps account for the space taken up by the floating toolbar. */ $('#toc').on('click', 'a', function() { var target = $(this.getAttribute('href')) , scroll_target = target.offset().top $(window).scrollTop(scroll_target - 10); return false }) }); </script> <div id="toc"></div> <p>Sorry, but the page you were trying to view does not exist. Try searching for it or looking at the URL to see if it looks correct.</p> <div class="tags"> </div> </div> <hr class="shaded"/> <footer> <div class="row"> <div class="col-lg-12 footer"> &copy;2016 . All rights reserved. <br /> Site last generated: Sep 10, 2016 <br /> <p><img src="images/company_logo.png" alt="Company logo"/></p> </div> </div> </footer> </div> <!-- /.row --> </div> <!-- /.container --> </div> </body> </html>
{ "content_hash": "8fa9c77c338e7a730291b1190064d8a0", "timestamp": "", "source": "github", "line_count": 323, "max_line_length": 316, "avg_line_length": 32.702786377708975, "alnum_prop": 0.4938937801760863, "repo_name": "AmbroseYim/Entropy", "id": "c1850fa14b6d2ad8ca1f739fb4dcb8065f509787", "size": "10563", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "_site/404.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "300616" }, { "name": "HTML", "bytes": "2261079" }, { "name": "JavaScript", "bytes": "10070" }, { "name": "Ruby", "bytes": "6980" }, { "name": "Shell", "bytes": "1940" } ], "symlink_target": "" }
require 'aws-sdk' require 'table_print' require_relative "cloud_front_interative_invalidator/version" module CloudFrontInterativeInvalidator def self.start(params={}) tp.set :max_width, 100 if ENV['AWS_ACCESS_KEY_ID'].nil? puts "Input AWS access key id:" ENV['AWS_ACCESS_KEY_ID'] = gets.chomp end if ENV['AWS_SECRET_ACCESS_KEY'].nil? puts "Input AWS secret access key:" ENV['AWS_SECRET_ACCESS_KEY'] = gets.chomp end AWS.config({ :access_key_id => ENV['AWS_ACCESS_KEY_ID'], :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'], }) list_distributions end def self.list_distributions(options={}) distributions = [] AWS::CloudFront::Client.new.list_distributions[:items].each_with_index do |item, index| distributions << { number: index + 1, id: item[:id], domain_name: item[:domain_name], origins: item[:origins][:items].map{|i| i[:domain_name]}.join(',') } end tp distributions begin puts "Input the number of the distribution (or anything else to quit):" distribution_input = gets.chomp return unless distribution_input.match(/^[0-9]+$/) distribution_index = distribution_input.to_i - 1 end until distribution_index < distributions.size && distribution_index > 0 distribution_id = distributions[distribution_index][:id] show_distribution(distribution_id) if distribution_id end def self.show_distribution(distribution_id) #tp AWS::CloudFront::Client.new.get_distribution(id: distribution_id).data puts "Distribution #{distribution_id} selected." puts "l/list: list invalidations" puts "c/create: create invalidations" puts "q/quit: quit current step" actions = { /^(l|list)$/ => :list_invalidations, /^(c|create)$/ => :create_invalidation, /^(q|quit)$/ => :list_distributions, } action = gets.chomp method_name = actions.select{|k,v| k.match(action)}.values.first send(method_name, distribution_id) end def self.list_invalidations(distribution_id=nil) begin invalidations = AWS::CloudFront::Client.new.list_invalidations(distribution_id: distribution_id) tp invalidations[:items] puts "Refresh? (y/n)" end while gets.chomp.downcase == 'y' invalidation_id = nil #get_invalidation(distribution_id, invalidation_id) show_distribution(distribution_id) end def self.create_invalidation(distribution_id) puts "Input the path to be invalidated:" paths = [] paths << gets.chomp options = {distribution_id: distribution_id, invalidation_batch: { paths: { quantity: paths.size, items: paths } , caller_reference: rand.to_s }} tp AWS::CloudFront::Client.new.create_invalidation(options).data show_distribution(distribution_id) end def self.get_invalidation(distribution_id, invalidation_id) tp AWS::CloudFront::Client.new.get_invalidation(distribution_id: distribution_id, id: invalidation_id).data end end
{ "content_hash": "84a53c1ba3d0430acc53e6ae326d6f46", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 160, "avg_line_length": 35.51190476190476, "alnum_prop": 0.6828695943680858, "repo_name": "liuming/cloud_front_interative_invalidator", "id": "3d96ea58e29031a97e1f00113e104289390da977", "size": "2983", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/cloud_front_interative_invalidator.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "4350" } ], "symlink_target": "" }
package com.chaquo.python.utils; import android.content.pm.*; import android.os.*; import android.text.method.*; import android.widget.*; import androidx.appcompat.app.*; import androidx.preference.*; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { String version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName; setTitle(getTitle() + " " + version); } catch (PackageManager.NameNotFoundException ignored) {} setContentView(resId("layout", "activity_menu")); ((TextView)findViewById(resId("id", "tvCaption"))) .setText(resId("string", "main_caption")); getSupportFragmentManager().beginTransaction() .replace(resId("id", "flMenu"), new MenuFragment()) .commit(); ((TextView)findViewById(resId("id", "tvCaption"))).setMovementMethod(LinkMovementMethod.getInstance()); } public static class MenuFragment extends PreferenceFragmentCompat { @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { addPreferencesFromResource(Utils.resId(getContext(), "xml", "activity_main")); } } public int resId(String type, String name) { return Utils.resId(this, type, name); } }
{ "content_hash": "64a5f7ddf7e6aac7bff1834abb15a8c7", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 111, "avg_line_length": 35.55, "alnum_prop": 0.670182841068917, "repo_name": "chaquo/chaquopy", "id": "d47d76299bbd1ce0221f9f386df4754363725697", "size": "1422", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demo/app/src/utils/java/com/chaquo/python/utils/MainActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "30" }, { "name": "C", "bytes": "174108" }, { "name": "CMake", "bytes": "1897" }, { "name": "CSS", "bytes": "991" }, { "name": "Cython", "bytes": "251545" }, { "name": "Dockerfile", "bytes": "6938" }, { "name": "Groovy", "bytes": "42472" }, { "name": "Java", "bytes": "159387" }, { "name": "Kotlin", "bytes": "697" }, { "name": "Python", "bytes": "8043408" }, { "name": "Roff", "bytes": "232" }, { "name": "Shell", "bytes": "53150" }, { "name": "Starlark", "bytes": "2018" } ], "symlink_target": "" }
<?php declare (strict_types = 1); namespace HMLB\DDDBundle\Doctrine\ORM; use Doctrine\Common\EventSubscriber; use Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs; use Doctrine\ORM\Event\OnClassMetadataNotFoundEventArgs; use Doctrine\ORM\Events; /** * MessagesMappingSubscriber. * * @author Hugues Maignol <[email protected]> */ class MessagesMappingSubscriber implements EventSubscriber { public function getSubscribedEvents() { return [ Events::loadClassMetadata, Events::onClassMetadataNotFound, ]; } public function onClassMetadataNotFound(OnClassMetadataNotFoundEventArgs $event) { } /** * @para */ public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs) { } }
{ "content_hash": "93e543f27de4adeab790c0162ea699fb", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 84, "avg_line_length": 21.405405405405407, "alnum_prop": 0.7108585858585859, "repo_name": "hmlb/ddd-bundle", "id": "0ea5fbec3d5ee71e0dd13b9e45878dfd627c4c8b", "size": "792", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Doctrine/ORM/MessagesMappingSubscriber.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "53600" } ], "symlink_target": "" }
import uuid from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from msrest.polling import LROPoller, NoPolling from msrestazure.polling.arm_polling import ARMPolling from .. import models class InboundNatRulesOperations(object): """InboundNatRulesOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. :ivar api_version: Client API version. Constant value: "2018-01-01". """ models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2018-01-01" self.config = config def list( self, resource_group_name, load_balancer_name, custom_headers=None, raw=False, **operation_config): """Gets all the inbound nat rules in a load balancer. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param load_balancer_name: The name of the load balancer. :type load_balancer_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: An iterator like instance of InboundNatRule :rtype: ~azure.mgmt.network.v2018_01_01.models.InboundNatRulePaged[~azure.mgmt.network.v2018_01_01.models.InboundNatRule] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = self.list.metadata['url'] path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.InboundNatRulePaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.InboundNatRulePaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/inboundNatRules'} def _delete_initial( self, resource_group_name, load_balancer_name, inbound_nat_rule_name, custom_headers=None, raw=False, **operation_config): # Construct URL url = self.delete.metadata['url'] path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'), 'inboundNatRuleName': self._serialize.url("inbound_nat_rule_name", inbound_nat_rule_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.delete(url, query_parameters) response = self._client.send(request, header_parameters, stream=False, **operation_config) if response.status_code not in [200, 202, 204]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response def delete( self, resource_group_name, load_balancer_name, inbound_nat_rule_name, custom_headers=None, raw=False, polling=True, **operation_config): """Deletes the specified load balancer inbound nat rule. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param load_balancer_name: The name of the load balancer. :type load_balancer_name: str :param inbound_nat_rule_name: The name of the inbound nat rule. :type inbound_nat_rule_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: The poller return type is ClientRawResponse, the direct response alongside the deserialized response :param polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :return: An instance of LROPoller that returns None or ClientRawResponse<None> if raw==True :rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ raw_result = self._delete_initial( resource_group_name=resource_group_name, load_balancer_name=load_balancer_name, inbound_nat_rule_name=inbound_nat_rule_name, custom_headers=custom_headers, raw=True, **operation_config ) def get_long_running_output(response): if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response lro_delay = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) if polling is True: polling_method = ARMPolling(lro_delay, **operation_config) elif polling is False: polling_method = NoPolling() else: polling_method = polling return LROPoller(self._client, raw_result, get_long_running_output, polling_method) delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/inboundNatRules/{inboundNatRuleName}'} def get( self, resource_group_name, load_balancer_name, inbound_nat_rule_name, expand=None, custom_headers=None, raw=False, **operation_config): """Gets the specified load balancer inbound nat rule. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param load_balancer_name: The name of the load balancer. :type load_balancer_name: str :param inbound_nat_rule_name: The name of the inbound nat rule. :type inbound_nat_rule_name: str :param expand: Expands referenced resources. :type expand: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: InboundNatRule or ClientRawResponse if raw=true :rtype: ~azure.mgmt.network.v2018_01_01.models.InboundNatRule or ~msrest.pipeline.ClientRawResponse :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = self.get.metadata['url'] path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'), 'inboundNatRuleName': self._serialize.url("inbound_nat_rule_name", inbound_nat_rule_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send(request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('InboundNatRule', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/inboundNatRules/{inboundNatRuleName}'} def _create_or_update_initial( self, resource_group_name, load_balancer_name, inbound_nat_rule_name, inbound_nat_rule_parameters, custom_headers=None, raw=False, **operation_config): # Construct URL url = self.create_or_update.metadata['url'] path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'), 'inboundNatRuleName': self._serialize.url("inbound_nat_rule_name", inbound_nat_rule_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(inbound_nat_rule_parameters, 'InboundNatRule') # Construct and send request request = self._client.put(url, query_parameters) response = self._client.send( request, header_parameters, body_content, stream=False, **operation_config) if response.status_code not in [200, 201]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('InboundNatRule', response) if response.status_code == 201: deserialized = self._deserialize('InboundNatRule', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def create_or_update( self, resource_group_name, load_balancer_name, inbound_nat_rule_name, inbound_nat_rule_parameters, custom_headers=None, raw=False, polling=True, **operation_config): """Creates or updates a load balancer inbound nat rule. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param load_balancer_name: The name of the load balancer. :type load_balancer_name: str :param inbound_nat_rule_name: The name of the inbound nat rule. :type inbound_nat_rule_name: str :param inbound_nat_rule_parameters: Parameters supplied to the create or update inbound nat rule operation. :type inbound_nat_rule_parameters: ~azure.mgmt.network.v2018_01_01.models.InboundNatRule :param dict custom_headers: headers that will be added to the request :param bool raw: The poller return type is ClientRawResponse, the direct response alongside the deserialized response :param polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :return: An instance of LROPoller that returns InboundNatRule or ClientRawResponse<InboundNatRule> if raw==True :rtype: ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.network.v2018_01_01.models.InboundNatRule] or ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.network.v2018_01_01.models.InboundNatRule]] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, load_balancer_name=load_balancer_name, inbound_nat_rule_name=inbound_nat_rule_name, inbound_nat_rule_parameters=inbound_nat_rule_parameters, custom_headers=custom_headers, raw=True, **operation_config ) def get_long_running_output(response): deserialized = self._deserialize('InboundNatRule', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized lro_delay = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) if polling is True: polling_method = ARMPolling(lro_delay, **operation_config) elif polling is False: polling_method = NoPolling() else: polling_method = polling return LROPoller(self._client, raw_result, get_long_running_output, polling_method) create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/inboundNatRules/{inboundNatRuleName}'}
{ "content_hash": "8cbe8bd8179e83e7941ca9bc49dffa3f", "timestamp": "", "source": "github", "line_count": 361, "max_line_length": 207, "avg_line_length": 49.013850415512465, "alnum_prop": 0.655815530688369, "repo_name": "lmazuel/azure-sdk-for-python", "id": "201ff22af7055699101e3732980ae0fc27f13c06", "size": "18168", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "azure-mgmt-network/azure/mgmt/network/v2018_01_01/operations/inbound_nat_rules_operations.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "42572767" } ], "symlink_target": "" }
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.1 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property <Global.System.Configuration.UserScopedSettingAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Configuration.DefaultSettingValueAttribute("")> _ Public Property LastPath() As String Get Return CType(Me("LastPath"),String) End Get Set Me("LastPath") = value End Set End Property <Global.System.Configuration.UserScopedSettingAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Configuration.DefaultSettingValueAttribute("")> _ Public Property LastFiles() As String Get Return CType(Me("LastFiles"),String) End Get Set Me("LastFiles") = value End Set End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.FileExistOTron.My.MySettings Get Return Global.FileExistOTron.My.MySettings.Default End Get End Property End Module End Namespace
{ "content_hash": "7e06231c03b240d8e3cdf1b552227e3c", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 179, "avg_line_length": 39.371134020618555, "alnum_prop": 0.6300078554595444, "repo_name": "donatj/File-Exist-O-Tron", "id": "e4539f9155f1f676a605ad530590849d3c3984d8", "size": "3821", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "My Project/Settings.Designer.vb", "mode": "33188", "license": "mit", "language": [ { "name": "Visual Basic", "bytes": "19582" } ], "symlink_target": "" }