text
stringlengths
2
99k
meta
dict
<!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.6"/> <title>libguac: guac_pool_int 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/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </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">libguac &#160;<span id="projectnumber">0.9.6</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.6 --> <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 class="current"><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="files.html"><span>Files</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>Data&#160;Structures</span></a></li> <li><a href="functions.html"><span>Data&#160;Fields</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)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&#160;</span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark">&#160;</span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark">&#160;</span>Macros</a></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><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-attribs">Data Fields</a> </div> <div class="headertitle"> <div class="title">guac_pool_int Struct Reference</div> </div> </div><!--header--> <div class="contents"> <p>Represents a single integer within a larger pool of integers. <a href="structguac__pool__int.html#details">More...</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a> Data Fields</h2></td></tr> <tr class="memitem:af76ff5f21c6e0f69d95cdd1385ea24a4"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af76ff5f21c6e0f69d95cdd1385ea24a4"></a> int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structguac__pool__int.html#af76ff5f21c6e0f69d95cdd1385ea24a4">value</a></td></tr> <tr class="memdesc:af76ff5f21c6e0f69d95cdd1385ea24a4"><td class="mdescLeft">&#160;</td><td class="mdescRight">The integer value of this pool entry. <br/></td></tr> <tr class="separator:af76ff5f21c6e0f69d95cdd1385ea24a4"><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>Represents a single integer within a larger pool of integers. </p> </div><hr/>The documentation for this struct was generated from the following file:<ul> <li>guacamole/<a class="el" href="pool_8h_source.html">pool.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Mar 30 2015 20:22:56 for libguac by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.6 </small></address> <!-- Google Analytics --> <script type="text/javascript"> (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-75289145-1', 'auto'); ga('send', 'pageview'); </script> <!-- End Google Analytics --> </body> </html>
{ "pile_set_name": "Github" }
import { connect } from 'react-redux'; import { mapDispatchToProps } from '../actions'; import { NetworkStatus } from '../../components/NetworkStatus'; import { StateType } from '../reducer'; import { getIntl } from '../selectors/user'; import { hasNetworkDialog } from '../selectors/network'; const mapStateToProps = (state: StateType) => { return { ...state.network, hasNetworkDialog: hasNetworkDialog(state), i18n: getIntl(state), }; }; const smart = connect(mapStateToProps, mapDispatchToProps); export const SmartNetworkStatus = smart(NetworkStatus);
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package v1beta1 import ( v1beta1 "k8s.io/api/scheduling/v1beta1" serializer "k8s.io/apimachinery/pkg/runtime/serializer" "k8s.io/client-go/kubernetes/scheme" rest "k8s.io/client-go/rest" ) type SchedulingV1beta1Interface interface { RESTClient() rest.Interface PriorityClassesGetter } // SchedulingV1beta1Client is used to interact with features provided by the scheduling.k8s.io group. type SchedulingV1beta1Client struct { restClient rest.Interface } func (c *SchedulingV1beta1Client) PriorityClasses() PriorityClassInterface { return newPriorityClasses(c) } // NewForConfig creates a new SchedulingV1beta1Client for the given config. func NewForConfig(c *rest.Config) (*SchedulingV1beta1Client, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err } client, err := rest.RESTClientFor(&config) if err != nil { return nil, err } return &SchedulingV1beta1Client{client}, nil } // NewForConfigOrDie creates a new SchedulingV1beta1Client for the given config and // panics if there is an error in the config. func NewForConfigOrDie(c *rest.Config) *SchedulingV1beta1Client { client, err := NewForConfig(c) if err != nil { panic(err) } return client } // New creates a new SchedulingV1beta1Client for the given RESTClient. func New(c rest.Interface) *SchedulingV1beta1Client { return &SchedulingV1beta1Client{c} } func setConfigDefaults(config *rest.Config) error { gv := v1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs} if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } return nil } // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. func (c *SchedulingV1beta1Client) RESTClient() rest.Interface { if c == nil { return nil } return c.restClient }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 977d3ef0ac8d24da3b326eae7a67894c timeCreated: 1507646114 licenseType: Pro MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright( C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages //(including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort(including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ /* definition of the current version of OpenCV Usefull to test in user programs */ #ifndef __OPENCV_VERSION_HPP__ #define __OPENCV_VERSION_HPP__ #define CV_MAJOR_VERSION 2 #define CV_MINOR_VERSION 4 #define CV_SUBMINOR_VERSION 2 #define CVAUX_STR_EXP(__A) #__A #define CVAUX_STR(__A) CVAUX_STR_EXP(__A) #define CV_VERSION CVAUX_STR(CV_MAJOR_VERSION) "." CVAUX_STR(CV_MINOR_VERSION) "." CVAUX_STR(CV_SUBMINOR_VERSION) #endif
{ "pile_set_name": "Github" }
// // SPUDownloaderDeprecated.h // Sparkle // // Created by Deadpikle on 12/20/17. // Copyright © 2017 Sparkle Project. All rights reserved. // #import "SPUDownloader.h" @interface SPUDownloaderDeprecated : SPUDownloader <SPUDownloaderProtocol> @end
{ "pile_set_name": "Github" }
<?php namespace Oro\Bundle\VisibilityBundle\Tests\Functional\Entity\VisibilityResolved\Repository; use Oro\Bundle\CatalogBundle\Entity\Category; use Oro\Bundle\VisibilityBundle\Entity\Visibility\CategoryVisibility; use Oro\Bundle\VisibilityBundle\Entity\VisibilityResolved\BaseCategoryVisibilityResolved; use Oro\Bundle\VisibilityBundle\Entity\VisibilityResolved\CategoryVisibilityResolved; use Oro\Bundle\VisibilityBundle\Entity\VisibilityResolved\Repository\CategoryRepository; class CategoryRepositoryTest extends AbstractCategoryRepositoryTest { /** * @var CategoryRepository */ protected $repository; /** * @dataProvider isCategoryVisibleDataProvider * @param string $categoryName * @param int $configValue * @param bool $expectedVisibility */ public function testIsCategoryVisible($categoryName, $configValue, $expectedVisibility) { /** @var Category $category */ $category = $this->getReference($categoryName); $actualVisibility = $this->getRepository()->isCategoryVisible($category, $configValue); $this->assertEquals($expectedVisibility, $actualVisibility); } /** * @return array */ public function isCategoryVisibleDataProvider() { return [ [ 'categoryName' => 'category_1', 'configValue' => 1, 'expectedVisibility' => true, ], [ 'categoryName' => 'category_1_2', 'configValue' => 1, 'expectedVisibility' => true, ], [ 'categoryName' => 'category_1_2_3', 'configValue' => 1, 'expectedVisibility' => true, ], ]; } /** * @dataProvider getCategoryIdsByVisibilityDataProvider * @param int $visibility * @param int $configValue * @param array $expected */ public function testGetCategoryIdsByVisibility($visibility, $configValue, array $expected) { $categoryIds = $this->repository->getCategoryIdsByVisibility($visibility, $configValue); $expectedCategoryIds = []; foreach ($expected as $categoryName) { /** @var Category $category */ $category = $this->getReference($categoryName); $expectedCategoryIds[] = $category->getId(); } if ($visibility === BaseCategoryVisibilityResolved::VISIBILITY_VISIBLE) { $masterCatalogId = $this->getMasterCatalog()->getId(); array_unshift($expectedCategoryIds, $masterCatalogId); } $this->assertEquals($expectedCategoryIds, $categoryIds); } /** * @return array */ public function getCategoryIdsByVisibilityDataProvider() { return [ [ 'visibility' => BaseCategoryVisibilityResolved::VISIBILITY_VISIBLE, 'configValue' => 1, 'expected' => [ 'category_1', 'category_1_2', 'category_1_2_3', 'category_1_2_3_4', 'category_1_5', ] ], [ 'visibility' => BaseCategoryVisibilityResolved::VISIBILITY_HIDDEN, 'configValue' => 1, 'expected' => [ 'category_1_5_6', 'category_1_5_6_7', ] ], ]; } public function testClearTable() { $this->assertGreaterThan(0, $this->getEntitiesCount()); $this->repository->clearTable(); $this->assertEquals(0, $this->getEntitiesCount()); } public function testInsertStaticValues() { /** @var CategoryVisibility[] $visibilities */ $visibilities = $this->getManagerRegistry() ->getManagerForClass('OroVisibilityBundle:Visibility\CategoryVisibility') ->getRepository('OroVisibilityBundle:Visibility\CategoryVisibility') ->createQueryBuilder('entity') ->andWhere('entity.visibility IN (:scalarVisibilities)') ->setParameter('scalarVisibilities', [CategoryVisibility::VISIBLE, CategoryVisibility::HIDDEN]) ->getQuery() ->getResult(); $this->assertNotEmpty($visibilities); /** @var CategoryVisibility[] $indexedVisibilities */ $indexedVisibilities = []; foreach ($visibilities as $visibility) { $indexedVisibilities[$visibility->getId()] = $visibility; } $this->repository->clearTable(); $scope = $this->scopeManager->findOrCreate(CategoryVisibility::VISIBILITY_TYPE); $this->repository->insertStaticValues($this->getInsertExecutor(), $scope); $resolvedVisibilities = $this->getResolvedVisibilities(); $this->assertSameSize($indexedVisibilities, $resolvedVisibilities); foreach ($resolvedVisibilities as $resolvedVisibility) { $id = $resolvedVisibility['sourceCategoryVisibility']; $this->assertArrayHasKey($id, $indexedVisibilities); $visibility = $indexedVisibilities[$id]; $this->assertEquals($visibility->getCategory()->getId(), $resolvedVisibility['category']); $this->assertEquals(CategoryVisibilityResolved::SOURCE_STATIC, $resolvedVisibility['source']); if ($visibility->getVisibility() === CategoryVisibility::VISIBLE) { $this->assertEquals(CategoryVisibilityResolved::VISIBILITY_VISIBLE, $resolvedVisibility['visibility']); } else { $this->assertEquals(CategoryVisibilityResolved::VISIBILITY_HIDDEN, $resolvedVisibility['visibility']); } } } public function testInsertParentCategoryValues() { $parentCategoryFallbackCategories = ['category_1_2', 'category_1_2_3_4']; $parentCategoryFallbackCategoryIds = []; foreach ($parentCategoryFallbackCategories as $categoryReference) { /** @var Category $category */ $category = $this->getReference($categoryReference); $parentCategoryFallbackCategoryIds[] = $category->getId(); } /** @var Category $staticCategory */ $staticCategory = $this->getReference('category_1_2_3'); $staticCategoryId = $staticCategory->getId(); $visibility = CategoryVisibilityResolved::VISIBILITY_VISIBLE; $scope = $this->scopeManager->findOrCreate(CategoryVisibility::VISIBILITY_TYPE); $this->repository->clearTable(); $this->repository->insertParentCategoryValues( $this->getInsertExecutor(), array_merge($parentCategoryFallbackCategoryIds, [$staticCategoryId]), $visibility, $scope ); $resolvedVisibilities = $this->getResolvedVisibilities(); // static visibilities should not be inserted $this->assertSameSize($parentCategoryFallbackCategoryIds, $resolvedVisibilities); foreach ($resolvedVisibilities as $resolvedVisibility) { static::assertContainsEquals( $resolvedVisibility['category'], $parentCategoryFallbackCategoryIds, \var_export($parentCategoryFallbackCategoryIds, true) ); $this->assertEquals(CategoryVisibilityResolved::SOURCE_PARENT_CATEGORY, $resolvedVisibility['source']); $this->assertEquals($visibility, $resolvedVisibility['visibility']); } } /** * @param array $a * @param array $b * @return int */ protected function sortByCategoryId(array $a, array $b) { return $a['category_id'] > $b['category_id'] ? 1 : -1; } /** * @param array $categories * @return array */ protected function replaceReferencesWithIds(array $categories) { $rootCategory = $this->getMasterCatalog(); foreach ($categories as $key => $row) { $category = $row['category_id']; /** @var Category $category */ if ($category === self::ROOT_CATEGORY) { $category = $rootCategory; } else { $category = $this->getReference($category); } $categories[$key]['category_id'] = $category->getId(); $parentCategory = $row['parent_category_id']; if ($parentCategory) { /** @var Category $parentCategory */ if ($parentCategory === self::ROOT_CATEGORY) { $parentCategory = $rootCategory; } else { $parentCategory = $this->getReference($parentCategory); } $categories[$key]['parent_category_id'] = $parentCategory->getId(); } } return $categories; } /** * @return CategoryRepository */ protected function getRepository() { return $this->getContainer()->get('oro_visibility.category_repository'); } /** * @return array */ protected function getResolvedVisibilities() { return $this->repository->createQueryBuilder('entity') ->select( 'IDENTITY(entity.sourceCategoryVisibility) as sourceCategoryVisibility', 'IDENTITY(entity.category) as category', 'entity.visibility', 'entity.source' ) ->getQuery() ->getArrayResult(); } }
{ "pile_set_name": "Github" }
# Letters of Credit Network > This network tracks letters of credit from application through to closure. ## Models within this business network ### Participants `Customer`, `Bank Employee` ### Assets `LetterOfCredit` ### Transactions `InitialApplication`, `Approve`, `Reject`, `SuggestChanges`, `ShipProduct`, `ReceiveProduct`, `ReadyForPayment`, `Close`, `CreateDemoParticipants` ### Events `InitialApplicationEvent`, `ApproveEvent`, `RejectEvent`, `SuggestChangesEvent`, `ShipProductEvent`, `ReceiveProductEvent`, `ReadyForPaymentEvent`, `CloseEvent` ## Example use of this Business network Two parties, each a `Customer` of a bank come to an agreement that Party A will import x number of Product Y from Party B. Party A uses their banking application to request a letter of credit using details from the agreement. The banking application submits an `InitialApplication` transaction which creates a new `LetterOfCredit` asset containing details of the two parties, their banks and their agreement. A `BankEmployee` at Party A's bank uses the banks internal application to review the letter of credit. The employee decides they do not like the rules set out in the application and therefore they decide to suggest changes using their application to submit a `SuggestChanges` transaction. Party A is alerted on their banking application that changes have been suggested in the letter of credit. Party A reviews the changes to the rules suggested by their bank and approves the changes using their banking application to submit an `Approve` transaction. The letter is now approved by both Party A and their bank. A `BankEmployee` at Party B's bank uses the banks internal application to review the letter of credit. The employee uses their application to submit an `Approve` transaction to mark that Party B's bank is happy with the issuance of the letter of credit to their customer, Party B. Party B is alerted to the letter of credit in their banking application. They use the application to review the letter and approve it using their application to submit an `Approve` transaction. The letter is now unable to be changed any further. Once Party B has manufactured the goods and sent them for shipping Party B uses their banking application to access the letter of credit and mark the goods relating to it as shipped using a `ShipProduct` transaction, passing with the transaction a hash of the shipping documents to be used as proof of shipping. When the goods arrive at their destination Party A reviews what they have received and checks that the received goods match the rules set out in the letter of credit. Party A is happy that they do and uses the banking application to submit a `ReceiveProduct` transaction. A `BankEmployee` at Party A's bank is alerted that Party A has stated that the goods are received. The employee does their own checks on the goods against the letter of credit rules and then uses their banking application to submit a `ReadyForPayment` transaction. Their own internal system then transfers funds to Party B's bank. A `BankEmployee` at Party B's bank is alerted that the letter of credit is ready to be paid and confirms that Party A has transferred the funds. The employee uses their banking application to close the letter of credit using a `Close` transaction and pay the money into Party B's account. ## Testing this network within playground The steps below will simulate the above scenario within playground. Navigate to the **Test** tab and then submit a `CreateDemoParticipants` transaction: ``` { "$class": "org.example.loc.CreateDemoParticipants" } ``` Navigate to the ID registry and generate IDs for: ``` org.example.loc.Customer#alice org.example.loc.Customer#bob org.example.loc.BankEmployee#matias org.example.loc.BankEmployee#ella ``` Select to Alice to be your identity. Navigate to the **Test** tab and then submit an `InitialApplication` transaction to request a letter of credit. The application will cover Alice and Bob's prior agreement to the following: - Bob will deliver 100 computers - Alice will pay $450 for each computer - The computers will be received in working order - The computers will be received within 30 days ``` { "$class": "org.example.loc.InitialApplication", "letterId": "LETTER-REF-123", "applicant": "resource:org.example.loc.Customer#alice", "beneficiary": "resource:org.example.loc.Customer#bob", "rules": [ { "ruleId": "LETTER-REF-123-RULE-1", "ruleText": "The computers will be received in working order" }, { "ruleId": "LETTER-REF-123-RULE-2", "ruleText": "The computers will be received within 30 days" } ], "productDetails": { "$class": "org.example.loc.ProductDetails", "productType": "Computers", "quantity": 100, "pricePerUnit": 450 } } ``` This creates a `LetterOfCredit` asset and sets the issuingBank to be Alice's bank and exportersBank to be Bob's bank. --- Use the ID registry to select Matias to be your identity. Matias works at Alice's bank. Review the letter of credit by selecting the `LetterOfCredit` asset. Matias decides that the rules are not suitable for the bank and therefore he decides to suggest changes. Submit a `SuggestChanges` transaction to change the rules: ``` { "$class": "org.example.loc.SuggestChanges", "loc": "resource:org.example.loc.LetterOfCredit#LETTER-REF-123", "rules": [ { "ruleId": "LETTER-REF-123-RULE-1", "ruleText": "The computers will be received in working order" }, { "ruleId": "LETTER-REF-123-RULE-2-UPDATED", "ruleText": "The computers will be received within 15 days" } ], "suggestingParty": "resource:org.example.loc.BankEmployee#matias" } ``` This transaction clears the array `LetterOfCredit` asset's `approval` field, updating it contain only the suggesting party and replaces the rules with the updated rules. --- Use the ID registry to select Alice to be your identity. Review the changes made to the letter of credit by selecting the `LetterOfCredit` asset. Alice agrees with the changes and decides she will approve. Approve the letter by submitting an `Approve` transaction: ``` { "$class": "org.example.loc.Approve", "loc": "resource:org.example.loc.LetterOfCredit#LETTER-REF-123", "approvingParty": "resource:org.example.loc.Customer#alice" } ``` This transaction adds Alice to the array of parties in the `approval` field of the `LetterOfCredit` asset. --- Use the ID registry to select Ella to be your identity. **NOTE:** Alice doesn't have permission to see Ella and therefore you must switch via admin first. Ella works at Bob's bank. Review the letter of credit by selecting the `LetterOfCredit` asset. Ella decides that the letter of credit is acceptable to her bank and that she will approve the request. Approve the letter by submitting an `Approve` transaction: ``` { "$class": "org.example.loc.Approve", "loc": "resource:org.example.loc.LetterOfCredit#LETTER-REF-123", "approvingParty": "resource:org.example.loc.BankEmployee#ella" } ``` This transaction adds Ella to the array of parties in the `approval` field of the `LetterOfCredit` asset. --- Use the ID registry to select Bob to be your identity. Bob reviews the letter of credit to ensure that it matches with his and Alice's agreement. He notices that the rules don't quite match the agreement however he still decides to accept the letter of credit and go through with the deal. Approve the letter by submitting an `Approve` transaction: ``` { "$class": "org.example.loc.Approve", "loc": "resource:org.example.loc.LetterOfCredit#LETTER-REF-123", "approvingParty": "resource:org.example.loc.Customer#bob" } ``` This transaction adds Bob to the array of parties in the `approval` field of the `LetterOfCredit` asset. As now all the parties have submitted their approval the `status` field is also updated to be `APPROVED`. At this point no participant may reject or suggest changes to the letter. Further participants (e.g. other bank employees) are also blocked from adding their approval. Bob manufactures the computers and ships them. He updates the `LetterOfCredit` asset to add proof that he has shipped the goods. Submit a `ShipProduct` transaction: ``` { "$class": "org.example.loc.ShipProduct", "loc": "resource:org.example.loc.LetterOfCredit#LETTER-REF-123", "evidence": "337478411cab754ce47fcaa72ec1d0f6" } ``` This transaction updates the `status` field of the `LetterOfCredit` asset to be `SHIPPED` and adds the evidence provided (in this case a hash of the shipping invoice) to the `evidence` array. --- Use the ID registry to select Alice to be your identity. Alice now receives the goods and has inspected them. The goods arrived within 14 days and were in working order and therefore Alice decides to update the letter of credit to show she has accepted delivery. Submit a `ReceiveProduct` transaction: ``` { "$class": "org.example.loc.ReceiveProduct", "loc": "resource:org.example.loc.LetterOfCredit#LETTER-REF-123" } ``` This transaction updates the `LetterOfCredit` asset to have a `status` of `RECEIVED`. --- Use the ID registry to select Matias to be your identity. Matias inspects the goods received by Alice and agrees that they meet the rules set out in the letter. He therefore decides to approve the transfer of funds to Bob's bank and updates the letter of credit to show that these funds are ready. Submit a `ReadyForPayment` transaction: ``` { "$class": "org.example.loc.ReadyForPayment", "loc": "resource:org.example.loc.LetterOfCredit#LETTER-REF-123" } ``` This transaction updates the `status` of the letter of credit to be `READY_FOR_PAYMENT`. The payment is not covered by this network. --- Use the ID registry to select Ella to be your identity. **NOTE:** Matias doesn't have permission to see Ella and therefore you must switch via admin first. Ella having received the funds from Alice's bank can close the letter of credit and deposit the funds in Bob's bank account. Submit a `Close` transaction: ``` { "$class": "org.example.loc.Close", "loc": "resource:org.example.loc.LetterOfCredit#LETTER-REF-123", "closeReason": "Payment made" } ``` This transaction updates the `status` of the letter to be `CLOSED`. The letter is now complete and no further transactions can take place. This business network has been used to create demo application that simulate the scenario above. You can find more detail on these at https://github.com/hyperledger/composer-sample-applications/tree/master/packages/letters-of-credit ## License <a name="license"></a> Hyperledger Project source code files are made available under the Apache License, Version 2.0 (Apache-2.0), located in the LICENSE file. Hyperledger Project documentation files are made available under the Creative Commons Attribution 4.0 International License (CC-BY-4.0), available at http://creativecommons.org/licenses/by/4.0/.
{ "pile_set_name": "Github" }
using System; using System.Collections.Immutable; using Newtonsoft.Json; namespace Microsoft.DotNet.Helix.Client.Models { public partial class BuildAggregationSource { public BuildAggregationSource(IImmutableDictionary<string, AggregatedWorkItemCounts> types) { Types = types; } [JsonProperty("Types")] public IImmutableDictionary<string, AggregatedWorkItemCounts> Types { get; } } }
{ "pile_set_name": "Github" }
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <google/protobuf/util/json_util.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/util/internal/default_value_objectwriter.h> #include <google/protobuf/util/internal/error_listener.h> #include <google/protobuf/util/internal/json_objectwriter.h> #include <google/protobuf/util/internal/json_stream_parser.h> #include <google/protobuf/util/internal/protostream_objectsource.h> #include <google/protobuf/util/internal/protostream_objectwriter.h> #include <google/protobuf/util/type_resolver.h> #include <google/protobuf/util/type_resolver_util.h> #include <google/protobuf/stubs/bytestream.h> #include <google/protobuf/stubs/status_macros.h> namespace google { namespace protobuf { namespace util { namespace internal { ZeroCopyStreamByteSink::~ZeroCopyStreamByteSink() { stream_->BackUp(buffer_size_); } void ZeroCopyStreamByteSink::Append(const char* bytes, size_t len) { while (true) { if (len <= buffer_size_) { memcpy(buffer_, bytes, len); buffer_ = static_cast<char*>(buffer_) + len; buffer_size_ -= len; return; } if (buffer_size_ > 0) { memcpy(buffer_, bytes, buffer_size_); bytes += buffer_size_; len -= buffer_size_; } if (!stream_->Next(&buffer_, &buffer_size_)) { // There isn't a way for ByteSink to report errors. buffer_size_ = 0; return; } } } } // namespace internal util::Status BinaryToJsonStream(TypeResolver* resolver, const string& type_url, io::ZeroCopyInputStream* binary_input, io::ZeroCopyOutputStream* json_output, const JsonPrintOptions& options) { io::CodedInputStream in_stream(binary_input); google::protobuf::Type type; RETURN_IF_ERROR(resolver->ResolveMessageType(type_url, &type)); converter::ProtoStreamObjectSource proto_source(&in_stream, resolver, type); proto_source.set_use_ints_for_enums(options.always_print_enums_as_ints); proto_source.set_preserve_proto_field_names( options.preserve_proto_field_names); io::CodedOutputStream out_stream(json_output); converter::JsonObjectWriter json_writer(options.add_whitespace ? " " : "", &out_stream); if (options.always_print_primitive_fields) { converter::DefaultValueObjectWriter default_value_writer( resolver, type, &json_writer); default_value_writer.set_preserve_proto_field_names( options.preserve_proto_field_names); return proto_source.WriteTo(&default_value_writer); } else { return proto_source.WriteTo(&json_writer); } } util::Status BinaryToJsonString(TypeResolver* resolver, const string& type_url, const string& binary_input, string* json_output, const JsonPrintOptions& options) { io::ArrayInputStream input_stream(binary_input.data(), binary_input.size()); io::StringOutputStream output_stream(json_output); return BinaryToJsonStream(resolver, type_url, &input_stream, &output_stream, options); } namespace { class StatusErrorListener : public converter::ErrorListener { public: StatusErrorListener() {} virtual ~StatusErrorListener() {} util::Status GetStatus() { return status_; } virtual void InvalidName(const converter::LocationTrackerInterface& loc, StringPiece unknown_name, StringPiece message) { status_ = util::Status(util::error::INVALID_ARGUMENT, loc.ToString() + ": " + message.ToString()); } virtual void InvalidValue(const converter::LocationTrackerInterface& loc, StringPiece type_name, StringPiece value) { status_ = util::Status(util::error::INVALID_ARGUMENT, loc.ToString() + ": invalid value " + value.ToString() + " for type " + type_name.ToString()); } virtual void MissingField(const converter::LocationTrackerInterface& loc, StringPiece missing_name) { status_ = util::Status( util::error::INVALID_ARGUMENT, loc.ToString() + ": missing field " + missing_name.ToString()); } private: util::Status status_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StatusErrorListener); }; } // namespace util::Status JsonToBinaryStream(TypeResolver* resolver, const string& type_url, io::ZeroCopyInputStream* json_input, io::ZeroCopyOutputStream* binary_output, const JsonParseOptions& options) { google::protobuf::Type type; RETURN_IF_ERROR(resolver->ResolveMessageType(type_url, &type)); internal::ZeroCopyStreamByteSink sink(binary_output); StatusErrorListener listener; converter::ProtoStreamObjectWriter::Options proto_writer_options; proto_writer_options.ignore_unknown_fields = options.ignore_unknown_fields; converter::ProtoStreamObjectWriter proto_writer(resolver, type, &sink, &listener, proto_writer_options); converter::JsonStreamParser parser(&proto_writer); const void* buffer; int length; while (json_input->Next(&buffer, &length)) { if (length == 0) continue; RETURN_IF_ERROR( parser.Parse(StringPiece(static_cast<const char*>(buffer), length))); } RETURN_IF_ERROR(parser.FinishParse()); return listener.GetStatus(); } util::Status JsonToBinaryString(TypeResolver* resolver, const string& type_url, const string& json_input, string* binary_output, const JsonParseOptions& options) { io::ArrayInputStream input_stream(json_input.data(), json_input.size()); io::StringOutputStream output_stream(binary_output); return JsonToBinaryStream( resolver, type_url, &input_stream, &output_stream, options); } namespace { const char* kTypeUrlPrefix = "type.googleapis.com"; TypeResolver* generated_type_resolver_ = NULL; GOOGLE_PROTOBUF_DECLARE_ONCE(generated_type_resolver_init_); string GetTypeUrl(const Message& message) { return string(kTypeUrlPrefix) + "/" + message.GetDescriptor()->full_name(); } void DeleteGeneratedTypeResolver() { delete generated_type_resolver_; } void InitGeneratedTypeResolver() { generated_type_resolver_ = NewTypeResolverForDescriptorPool( kTypeUrlPrefix, DescriptorPool::generated_pool()); ::google::protobuf::internal::OnShutdown(&DeleteGeneratedTypeResolver); } TypeResolver* GetGeneratedTypeResolver() { ::google::protobuf::GoogleOnceInit(&generated_type_resolver_init_, &InitGeneratedTypeResolver); return generated_type_resolver_; } } // namespace util::Status MessageToJsonString(const Message& message, string* output, const JsonOptions& options) { const DescriptorPool* pool = message.GetDescriptor()->file()->pool(); TypeResolver* resolver = pool == DescriptorPool::generated_pool() ? GetGeneratedTypeResolver() : NewTypeResolverForDescriptorPool(kTypeUrlPrefix, pool); util::Status result = BinaryToJsonString(resolver, GetTypeUrl(message), message.SerializeAsString(), output, options); if (pool != DescriptorPool::generated_pool()) { delete resolver; } return result; } util::Status JsonStringToMessage(const string& input, Message* message, const JsonParseOptions& options) { const DescriptorPool* pool = message->GetDescriptor()->file()->pool(); TypeResolver* resolver = pool == DescriptorPool::generated_pool() ? GetGeneratedTypeResolver() : NewTypeResolverForDescriptorPool(kTypeUrlPrefix, pool); string binary; util::Status result = JsonToBinaryString( resolver, GetTypeUrl(*message), input, &binary, options); if (result.ok() && !message->ParseFromString(binary)) { result = util::Status(util::error::INVALID_ARGUMENT, "JSON transcoder produced invalid protobuf output."); } if (pool != DescriptorPool::generated_pool()) { delete resolver; } return result; } } // namespace util } // namespace protobuf } // namespace google
{ "pile_set_name": "Github" }
/*************************************************************************** Atari Arcade Classics hardware (prototypes) Note: this video hardware has some similarities to Shuuz & company The sprite offset registers are stored to 3EFF80 ****************************************************************************/ #include "driver.h" #include "machine/atarigen.h" #include "vidhrdw/generic.h" #define XCHARS 43 #define YCHARS 30 #define XDIM (XCHARS*8) #define YDIM (YCHARS*8) /************************************* * * Statics * *************************************/ static int *color_usage; /************************************* * * Prototypes * *************************************/ static const UINT8 *update_palette(void); static void mo_color_callback(const UINT16 *data, const struct rectangle *clip, void *param); static void mo_render_callback(const UINT16 *data, const struct rectangle *clip, void *param); /************************************* * * Video system start * *************************************/ int arcadecl_vh_start(void) { static struct atarigen_mo_desc mo_desc = { 256, /* maximum number of MO's */ 8, /* number of bytes per MO entry */ 2, /* number of bytes between MO words */ 0, /* ignore an entry if this word == 0xffff */ 0, 0, 0xff, /* link = (data[linkword] >> linkshift) & linkmask */ 0 /* render in reverse link order */ }; static struct atarigen_pf_desc pf_desc = { 8, 8, /* width/height of each tile */ 64, 64, /* number of tiles in each direction */ 1 /* non-scrolling */ }; /* allocate color usage */ color_usage = (int*)malloc(sizeof(int) * 256); if (!color_usage) return 1; color_usage[0] = XDIM * YDIM; memset(atarigen_playfieldram, 0, 0x20000); /* initialize the playfield */ if (atarigen_pf_init(&pf_desc)) { free(color_usage); return 1; } /* initialize the motion objects */ if (atarigen_mo_init(&mo_desc)) { atarigen_pf_free(); free(color_usage); return 1; } return 0; } /************************************* * * Video system shutdown * *************************************/ void arcadecl_vh_stop(void) { /* free data */ if (color_usage) free(color_usage); color_usage = 0; atarigen_pf_free(); atarigen_mo_free(); } /************************************* * * Playfield RAM write handler * *************************************/ WRITE_HANDLER( arcadecl_playfieldram_w ) { int oldword = READ_WORD(&atarigen_playfieldram[offset]); int newword = COMBINE_WORD(oldword, data); int x, y; if (oldword != newword) { WRITE_WORD(&atarigen_playfieldram[offset], newword); /* track color usage */ x = offset % 512; y = offset / 512; if (x < XDIM && y < YDIM) { color_usage[(oldword >> 8) & 0xff]--; color_usage[oldword & 0xff]--; color_usage[(newword >> 8) & 0xff]++; color_usage[newword & 0xff]++; } /* mark scanlines dirty */ atarigen_pf_dirty[y] = 1; } } /************************************* * * Periodic scanline updater * *************************************/ void arcadecl_scanline_update(int scanline) { /* doesn't appear to use SLIPs */ if (scanline < YDIM) atarigen_mo_update(atarigen_spriteram, 0, scanline); } /************************************* * * Main refresh * *************************************/ void arcadecl_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh) { /* remap if necessary */ if (update_palette()) memset(atarigen_pf_dirty, 1, YDIM); /* update the cached bitmap */ { int x, y; for (y = 0; y < YDIM; y++) if (atarigen_pf_dirty[y]) { int xx = 0; const UINT8 *src = &atarigen_playfieldram[512 * y]; /* regenerate the line */ for (x = 0; x < XDIM/2; x++) { int bits = READ_WORD(src); src += 2; plot_pixel(atarigen_pf_bitmap, xx++, y, Machine->pens[bits >> 8]); plot_pixel(atarigen_pf_bitmap, xx++, y, Machine->pens[bits & 0xff]); } atarigen_pf_dirty[y] = 0; } } /* copy the cached bitmap */ copybitmap(bitmap, atarigen_pf_bitmap, 0, 0, 0, 0, NULL, TRANSPARENCY_NONE, 0); /* render the motion objects */ atarigen_mo_process(mo_render_callback, bitmap); /* update onscreen messages */ atarigen_update_messages(); } /************************************* * * Palette management * *************************************/ static const UINT8 *update_palette(void) { UINT16 mo_map[16]; int i, j; /* reset color tracking */ memset(mo_map, 0, sizeof(mo_map)); palette_init_used_colors(); /* update color usage for the mo's */ atarigen_mo_process(mo_color_callback, mo_map); /* rebuild the playfield palette */ for (i = 0; i < 256; i++) if (color_usage[i]) palette_used_colors[0x000 + i] = PALETTE_COLOR_USED; /* rebuild the motion object palette */ for (i = 0; i < 16; i++) { UINT16 used = mo_map[i]; if (used) { palette_used_colors[0x100 + i * 16 + 0] = PALETTE_COLOR_TRANSPARENT; for (j = 1; j < 16; j++) if (used & (1 << j)) palette_used_colors[0x100 + i * 16 + j] = PALETTE_COLOR_USED; } } return palette_recalc(); } /************************************* * * Motion object palette * *************************************/ static void mo_color_callback(const UINT16 *data, const struct rectangle *clip, void *param) { const UINT32 *usage = Machine->gfx[0]->pen_usage; UINT16 *colormap = (UINT16*)param; int code = data[1] & 0x7fff; int color = data[2] & 0x000f; int hsize = ((data[3] >> 4) & 7) + 1; int vsize = (data[3] & 7) + 1; int tiles = hsize * vsize; UINT16 temp = 0; int i; for (i = 0; i < tiles; i++) temp |= usage[code++]; colormap[color] |= temp; } /************************************* * * Motion object rendering * *************************************/ static void mo_render_callback(const UINT16 *data, const struct rectangle *clip, void *param) { const struct GfxElement *gfx = Machine->gfx[0]; struct osd_bitmap *bitmap = (struct osd_bitmap *)param; struct rectangle pf_clip; /* extract data from the various words */ int hflip = data[1] & 0x8000; int code = data[1] & 0x7fff; int xpos = (data[2] >> 7) + 4; int color = data[2] & 0x000f; /* int priority = (data[2] >> 3) & 1;*/ int ypos = YDIM - (data[3] >> 7); int hsize = ((data[3] >> 4) & 7) + 1; int vsize = (data[3] & 7) + 1; /* adjust for height */ ypos -= vsize * 8; /* adjust the final coordinates */ xpos &= 0x1ff; ypos &= 0x1ff; if (xpos >= XDIM) xpos -= 0x200; if (ypos >= YDIM) ypos -= 0x200; /* determine the bounding box */ atarigen_mo_compute_clip_8x8(pf_clip, xpos, ypos, hsize, vsize, clip); /* draw the motion object */ atarigen_mo_draw_8x8(bitmap, gfx, code, color, hflip, 0, xpos, ypos, hsize, vsize, clip, TRANSPARENCY_PEN, 0); }
{ "pile_set_name": "Github" }
<!DOCTYPE html> {% autoescape true %} <html> <body> <p>Videos: </p> {% for video in videos %} {{ video }}<br> {% endfor %} <p>Channels:</p> {% for channel in channels %} {{ channel }} <br> {% endfor %} <p>Playlists:</p> {% for playlist in playlists %} {{ playlist }} <br> {% endfor %} </body> </html> {% endautoescape %}
{ "pile_set_name": "Github" }
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE OverloadedStrings #-} module Unison.Name ( Name(Name) , fromString , isPrefixOf , joinDot , makeAbsolute , parent , sortNames , sortNamed , sortNamed' , stripNamePrefix , stripPrefixes , segments , segments' , suffixes , toString , toText , toVar , unqualified , unqualified' , unsafeFromText , unsafeFromString , fromSegment , fromVar ) where import Unison.Prelude import qualified Unison.NameSegment as NameSegment import Unison.NameSegment ( NameSegment(NameSegment) , segments' ) import Control.Lens ( unsnoc ) import qualified Control.Lens as Lens import qualified Data.Text as Text import qualified Unison.Hashable as H import Unison.Var ( Var ) import qualified Unison.Var as Var import qualified Data.RFC5051 as RFC5051 import Data.List ( sortBy, tails ) newtype Name = Name { toText :: Text } deriving (Eq, Ord, Monoid, Semigroup) sortNames :: [Name] -> [Name] sortNames = sortNamed id sortNamed :: (a -> Name) -> [a] -> [a] sortNamed by as = let as' = [ (a, Text.unpack (toText (by a))) | a <- as ] comp (_,s) (_,s2) = RFC5051.compareUnicode s s2 in fst <$> sortBy comp as' -- | Like sortNamed, but takes an additional backup comparison function if two -- names are equal. sortNamed' :: (a -> Name) -> (a -> a -> Ordering) -> [a] -> [a] sortNamed' by by2 as = let as' = [ (a, Text.unpack (toText (by a))) | a <- as ] comp (a,s) (a2,s2) = RFC5051.compareUnicode s s2 <> by2 a a2 in fst <$> sortBy comp as' unsafeFromText :: Text -> Name unsafeFromText t = if Text.any (== '#') t then error $ "not a name: " <> show t else Name t unsafeFromString :: String -> Name unsafeFromString = unsafeFromText . Text.pack toVar :: Var v => Name -> v toVar (Name t) = Var.named t fromVar :: Var v => v -> Name fromVar = unsafeFromText . Var.name toString :: Name -> String toString = Text.unpack . toText isPrefixOf :: Name -> Name -> Bool a `isPrefixOf` b = toText a `Text.isPrefixOf` toText b -- stripTextPrefix a.b. a.b.c = Just c -- stripTextPrefix a.b a.b.c = Just .c; you probably don't want to do this -- stripTextPrefix x.y. a.b.c = Nothing -- stripTextPrefix "" a.b.c = undefined _stripTextPrefix :: Text -> Name -> Maybe Name _stripTextPrefix prefix name = Name <$> Text.stripPrefix prefix (toText name) -- stripNamePrefix a.b a.b.c = Just c -- stripNamePrefix a.b. a.b.c = undefined, "a.b." isn't a valid name IMO -- stripNamePrefix x.y a.b.c = Nothing, x.y isn't a prefix of a.b.c -- stripNamePrefix "" a.b.c = undefined, "" isn't a valid name IMO -- stripNamePrefix . .Nat = Just Nat stripNamePrefix :: Name -> Name -> Maybe Name stripNamePrefix prefix name = Name <$> Text.stripPrefix (toText prefix <> mid) (toText name) where mid = if toText prefix == "." then "" else "." -- a.b.c.d -> d stripPrefixes :: Name -> Name stripPrefixes = fromSegment . last . segments joinDot :: Name -> Name -> Name joinDot prefix suffix = if toText prefix == "." then Name (toText prefix <> toText suffix) else Name (toText prefix <> "." <> toText suffix) unqualified :: Name -> Name unqualified = unsafeFromText . unqualified' . toText -- parent . -> Nothing -- parent + -> Nothing -- parent foo -> Nothing -- parent foo.bar -> foo -- parent foo.bar.+ -> foo.bar parent :: Name -> Maybe Name parent n = case unsnoc (NameSegment.toText <$> segments n) of Nothing -> Nothing Just ([] , _) -> Nothing Just (init, _) -> Just $ Name (Text.intercalate "." init) -- suffixes "" -> [] -- suffixes bar -> [bar] -- suffixes foo.bar -> [foo.bar, bar] -- suffixes foo.bar.baz -> [foo.bar.baz, bar.baz, baz] -- suffixes ".base.." -> [base.., .] suffixes :: Name -> [Name] suffixes (Name "") = [] suffixes (Name n ) = fmap up . filter (not . null) . tails $ segments' n where up ns = Name (Text.intercalate "." ns) unqualified' :: Text -> Text unqualified' = last . segments' makeAbsolute :: Name -> Name makeAbsolute n | toText n == "." = Name ".." | Text.isPrefixOf "." (toText n) = n | otherwise = Name ("." <> toText n) instance Show Name where show = toString instance IsString Name where fromString = unsafeFromText . Text.pack instance H.Hashable Name where tokens s = [H.Text (toText s)] fromSegment :: NameSegment -> Name fromSegment = unsafeFromText . NameSegment.toText -- Smarter segmentation than `text.splitOn "."` -- e.g. split `base..` into `[base,.]` segments :: Name -> [NameSegment] segments (Name n) = NameSegment <$> segments' n instance Lens.Snoc Name Name NameSegment NameSegment where _Snoc = Lens.prism snoc unsnoc where snoc :: (Name, NameSegment) -> Name snoc (n, s) = joinDot n (fromSegment s) unsnoc :: Name -> Either Name (Name, NameSegment) unsnoc n@(segments -> ns) = case Lens.unsnoc (NameSegment.toText <$> ns) of Nothing -> Left n Just ([], _) -> Left n Just (init, last) -> Right (Name (Text.intercalate "." init), NameSegment last)
{ "pile_set_name": "Github" }
{ "_from": "pify@^2.3.0", "_id": "pify@2.3.0", "_inBundle": false, "_integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", "_location": "/update-notifier/configstore/make-dir/pify", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, "raw": "pify@^2.3.0", "name": "pify", "escapedName": "pify", "rawSpec": "^2.3.0", "saveSpec": null, "fetchSpec": "^2.3.0" }, "_requiredBy": [ "/update-notifier/configstore/make-dir" ], "_resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", "_shasum": "ed141a6ac043a849ea588498e7dca8b15330e90c", "_spec": "pify@^2.3.0", "_where": "/Users/rebecca/code/npm/node_modules/update-notifier/node_modules/configstore/node_modules/make-dir", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/sindresorhus/pify/issues" }, "bundleDependencies": false, "deprecated": false, "description": "Promisify a callback-style function", "devDependencies": { "ava": "*", "pinkie-promise": "^1.0.0", "v8-natives": "0.0.2", "xo": "*" }, "engines": { "node": ">=0.10.0" }, "files": [ "index.js" ], "homepage": "https://github.com/sindresorhus/pify#readme", "keywords": [ "promise", "promises", "promisify", "denodify", "denodeify", "callback", "cb", "node", "then", "thenify", "convert", "transform", "wrap", "wrapper", "bind", "to", "async", "es2015" ], "license": "MIT", "name": "pify", "repository": { "type": "git", "url": "git+https://github.com/sindresorhus/pify.git" }, "scripts": { "optimization-test": "node --allow-natives-syntax optimization-test.js", "test": "xo && ava && npm run optimization-test" }, "version": "2.3.0" }
{ "pile_set_name": "Github" }
#pragma once #include "AfxInterfaces.h" #include "SourceInterfaces.h" #include <set> #include <map> #include <atomic> #include <mutex> #include <shared_mutex> #include <Windows.h> // CAfxMaterialKey ///////////////////////////////////////////////////////////// class CAfxMaterialKey { public: CAfxMaterialKey(SOURCESDK::IMaterial_csgo * material); CAfxMaterialKey::CAfxMaterialKey(const CAfxMaterialKey & x); virtual ~CAfxMaterialKey(); private: /// <remarks> /// This is internal material object pointer based, meaning different references on the same material can have different keys /// </remarks> bool operator < (const CAfxMaterialKey & y) const; public: SOURCESDK::IMaterial_csgo * GetMaterial() const; protected: SOURCESDK::IMaterial_csgo * m_Material; }; // CAfxOwnedMaterial //////////////////////////////////////////////////////////// class CAfxOwnedMaterial : public CAfxMaterialKey { public: CAfxOwnedMaterial(SOURCESDK::IMaterial_csgo * material); virtual ~CAfxOwnedMaterial(); private: static std::map<SOURCESDK::IMaterial_csgo *, std::atomic_int> m_OwnedMaterials; static std::shared_timed_mutex m_OwnedMaterialsMutex; static void AddRef(SOURCESDK::IMaterial_csgo * material); static void Release(SOURCESDK::IMaterial_csgo * material); }; // CAfxTrackedMaterial ///////////////////////////////////////////////////////// class CAfxTrackedMaterial; class IAfxMaterialFree abstract { public: virtual void AfxMaterialFree(CAfxTrackedMaterial * material) abstract = 0; }; class CAfxTrackedMaterial : public CAfxMaterialKey { public: //:192 typedef void (__fastcall * MaterialHook_Free_t)(void* This, void* Edx); struct CMaterialDetours { //:034 MaterialHook_Free_t InterlockedDecrement; }; /// <remarks>On Drawing thread only.</remarks> static CAfxTrackedMaterial * TrackMaterial(SOURCESDK::IMaterial_csgo * material); /// <remarks>Threadsafe.</remarks> void AddRef(); /// <remarks>Threadsafe.</remarks> void Release(); /// <remarks>On Drawing thread only.</remarks> void AddNotifyee(IAfxMaterialFree * notifyee); /// <remarks>Threadsafe.</remarks> void RemoveNotifyee(IAfxMaterialFree * notifyee); // TODO: move this elsewhere /// <remarks>On Drawing thread only.</remarks> SOURCESDK::IMaterial_csgo * GetReplacement(void) { return m_Replacement; } // TODO: move this elsewhere /// <remarks>On Drawing thread only.</remarks> void SetReplacement(SOURCESDK::IMaterial_csgo * value) { m_Replacement = value; } protected: CAfxTrackedMaterial(SOURCESDK::IMaterial_csgo * material); virtual ~CAfxTrackedMaterial(); private: static std::map<SOURCESDK::IMaterial_csgo *, CAfxTrackedMaterial *> m_Trackeds; static std::shared_timed_mutex m_TrackedsMutex; static std::map<int *, CMaterialDetours> m_VtableMap; static std::shared_timed_mutex m_VtableMapMutex; static void HooKVtable(SOURCESDK::IMaterial_csgo * orgMaterial); static void __fastcall CAfxTrackedMaterial::Material_InterlockedDecrement(void* This, void* Edx); static void OnMaterialInterlockedDecrement(SOURCESDK::IMaterial_csgo * material); std::atomic_int m_RefCount = 1; std::mutex m_ThisNotifyeesMutex; std::set<IAfxMaterialFree *> m_ThisNotifyees; bool m_Deleting = false; SOURCESDK::IMaterial_csgo * m_Replacement = 0; void Delete(); }; class CAfxTrackedMaterialRef { public: CAfxTrackedMaterialRef(CAfxTrackedMaterial* trackedMaterial) : m_TrackedMaterial(trackedMaterial) { m_TrackedMaterial->AddRef(); } CAfxTrackedMaterialRef(const CAfxTrackedMaterialRef& trackedMaterialRef) : m_TrackedMaterial(trackedMaterialRef.m_TrackedMaterial) { m_TrackedMaterial->AddRef(); } ~CAfxTrackedMaterialRef() { m_TrackedMaterial->Release(); } bool operator < (const CAfxTrackedMaterialRef& y) const { return m_TrackedMaterial < y.m_TrackedMaterial; } CAfxTrackedMaterial* Get() const { return m_TrackedMaterial; } private: CAfxTrackedMaterial* m_TrackedMaterial; };
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Generated by Elektra API. Total of 9 keys. --> <keyset xmlns="https://www.libelektra.org" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.libelektra.org elektra.xsd" parent = "user/tests/filesys" > <key type="43" basename="0-27042916" value="0 216905227"><comment>2551516588474823843</comment></key> <key type="253" basename="1-2449524622" value="1 1679328197"><comment>3246436893195629244</comment></key> <key type="string" isdir="true" basename="dir-1-0"> <key type="114" basename="0-294164813" value="0 216245011"><comment>18454108762891828026</comment></key> <key type="135" basename="1-1479930365" value="1 2732423037"><comment>24597295372375238</comment></key> <key type="string" isdir="true" basename="dir-2-0"> <key type="144" basename="0-215571059" value="0 264857705"><comment>2188631490667217086</comment></key> <key type="217" basename="1-172696863" value="1 1413010492"><comment>2009260691056619998</comment></key> </key> <key type="string" isdir="true" basename="dir-2-1"> <key type="173" basename="0-2000814607" value="0 1955026514"><comment>634720937883220825</comment></key> <key type="20" basename="1-1242717281" value="1 1279621809"><comment>10835219082633423494</comment></key> </key> <key type="string" isdir="true" basename="dir-2-2"> <key type="28" basename="0-215623221" value="0 2615831169"><comment>439048222054330242</comment></key> <key type="239" basename="1-268626445" value="1 211926272"><comment>2671264801133512045</comment></key> </key> <key type="string" isdir="true" basename="dir-2-3"> <key type="145" basename="0-72095994" value="0 3082914659"><comment>2462099381906519637</comment></key> <key type="26" basename="1-1112526887" value="1 13790397"><comment>29552250853230432415</comment></key> </key> <key type="string" isdir="true" basename="dir-2-4"> <key type="242" basename="0-43814952" value="0 245627749"><comment>287081235381626635</comment></key> <key type="223" basename="1-312568090" value="1 36219472"><comment>2056467162314026779</comment></key> </key> </key> <key type="string" isdir="true" basename="dir-1-1"> <key type="88" basename="0-2993514317" value="0 3007016338"><comment>6513136152238131569</comment></key> <key type="161" basename="1-2673925626" value="1 3085029208"><comment>595310088267681325</comment></key> <key type="string" isdir="true" basename="dir-2-0"> <key type="247" basename="0-164223741" value="0 64307894"><comment>22531187641857031662</comment></key> <key type="190" basename="1-3182527006" value="1 152121106"><comment>6050128332068515722</comment></key> </key> <key type="string" isdir="true" basename="dir-2-1"> <key type="229" basename="0-3219021027" value="0 240036888"><comment>16238284472997719576</comment></key> <key type="159" basename="1-2486914396" value="1 145207467"><comment>3883281333052412037</comment></key> </key> <key type="string" isdir="true" basename="dir-2-2"> <key type="82" basename="0-46903647" value="0 2268621888"><comment>32753327232797919976</comment></key> <key type="115" basename="1-905011462" value="1 1273310721"><comment>14800138803221317405</comment></key> </key> <key type="string" isdir="true" basename="dir-2-3"> <key type="197" basename="0-3208912452" value="0 1169512568"><comment>2676924538788523596</comment></key> <key type="186" basename="1-1091331377" value="1 199987266"><comment>4522262551362712874</comment></key> </key> <key type="string" isdir="true" basename="dir-2-4"> <key type="202" basename="0-294181683" value="0 3146316501"><comment>2101827480127277145</comment></key> <key type="179" basename="1-175659776" value="1 2334131443"><comment>198753828813576</comment></key> </key> </key> <key type="string" isdir="true" basename="dir-1-2"> <key type="100" basename="0-972431067" value="0 133203847"><comment>1347011419147246413</comment></key> <key type="129" basename="1-75222444" value="1 1867917733"><comment>31620169261048613078</comment></key> <key type="string" isdir="true" basename="dir-2-0"> <key type="92" basename="0-315168369" value="0 1810024091"><comment>17609274262950321182</comment></key> <key type="110" basename="1-18334792" value="1 355327020"><comment>26036252041174319415</comment></key> </key> <key type="string" isdir="true" basename="dir-2-1"> <key type="167" basename="0-43779371" value="0 2717329532"><comment>1847528778209268968</comment></key> <key type="33" basename="1-211724603" value="1 1274718100"><comment>16075148982907919368</comment></key> </key> <key type="string" isdir="true" basename="dir-2-2"> <key type="93" basename="0-23186501" value="0 162585077"><comment>1823923665139346176</comment></key> <key type="238" basename="1-117112769" value="1 124652661"><comment>15563326831112072</comment></key> </key> <key type="string" isdir="true" basename="dir-2-3"> <key type="20" basename="0-1045212001" value="0 2042429548"><comment>2095516044228183782</comment></key> <key type="35" basename="1-2201810163" value="1 121814102"><comment>2139722875720320817</comment></key> </key> <key type="string" isdir="true" basename="dir-2-4"> <key type="33" basename="0-1913626837" value="0 2913127539"><comment>776043343146721534</comment></key> <key type="187" basename="1-2016421284" value="1 753117627"><comment>255613898214632040</comment></key> </key> </key> <key type="string" isdir="true" basename="dir-1-3"> <key type="176" basename="0-3155020840" value="0 990825763"><comment>21852226343272631185</comment></key> <key type="200" basename="1-874922" value="1 1759916191"><comment>2623735621954316926</comment></key> <key type="string" isdir="true" basename="dir-2-0"> <key type="223" basename="0-630724305" value="0 2995613338"><comment>1964917880248812636</comment></key> <key type="157" basename="1-169830617" value="1 2619012633"><comment>6277190786814312</comment></key> </key> <key type="string" isdir="true" basename="dir-2-1"> <key type="20" basename="0-1313819824" value="0 1076430387"><comment>143682467514357045</comment></key> <key type="78" basename="1-1642029463" value="1 1695720003"><comment>165992136954451860</comment></key> </key> <key type="string" isdir="true" basename="dir-2-2"> <key type="176" basename="0-153568349" value="0 802220498"><comment>2544318414240793465</comment></key> <key type="220" basename="1-203925831" value="1 1773615811"><comment>326122332660329661</comment></key> </key> <key type="string" isdir="true" basename="dir-2-3"> <key type="205" basename="0-132335709" value="0 753610877"><comment>194216610785116060</comment></key> <key type="203" basename="1-267732539" value="1 29164318"><comment>990832569759630797</comment></key> </key> <key type="string" isdir="true" basename="dir-2-4"> <key type="209" basename="0-3199312703" value="0 1001316339"><comment>21741123163068723187</comment></key> <key type="93" basename="1-1790727245" value="1 289129416"><comment>53059801514130705</comment></key> </key> </key> <key type="string" isdir="true" basename="dir-1-4"> <key type="133" basename="0-387126160" value="0 204394545"><comment>21188322531851320535</comment></key> <key type="137" basename="1-151647309" value="1 2842511711"><comment>9883314882767419206</comment></key> <key type="string" isdir="true" basename="dir-2-0"> <key type="53" basename="0-526230536" value="0 1181112782"><comment>1065225830188249547</comment></key> <key type="132" basename="1-203866829" value="1 21315999"><comment>30944117441110710316</comment></key> </key> <key type="string" isdir="true" basename="dir-2-1"> <key type="162" basename="0-232282487" value="0 28204903"><comment>14723134441057028108</comment></key> <key type="80" basename="1-2551523896" value="1 140713945"><comment>5891315043040223589</comment></key> </key> <key type="string" isdir="true" basename="dir-2-2"> <key type="198" basename="0-2408724547" value="0 293399851"><comment>11915196071822725798</comment></key> <key type="136" basename="1-2609326364" value="1 240967228"><comment>2183621105162112017</comment></key> </key> <key type="string" isdir="true" basename="dir-2-3"> <key type="204" basename="0-563328213" value="0 1680912618"><comment>76214949230088786</comment></key> <key type="64" basename="1-1453831796" value="1 245126793"><comment>15761313992127631931</comment></key> </key> <key type="string" isdir="true" basename="dir-2-4"> <key type="145" basename="0-257736880" value="0 867028967"><comment>319532359220727161</comment></key> <key type="20" basename="1-2918914282" value="1 311082578"><comment>1104442372487923737</comment></key> </key> </key> <!-- 92 keys generated --> </keyset>
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package fake import ( core_v1 "k8s.io/api/core/v1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" testing "k8s.io/client-go/testing" ) // FakePodTemplates implements PodTemplateInterface type FakePodTemplates struct { Fake *FakeCoreV1 ns string } var podtemplatesResource = schema.GroupVersionResource{Group: "", Version: "v1", Resource: "podtemplates"} var podtemplatesKind = schema.GroupVersionKind{Group: "", Version: "v1", Kind: "PodTemplate"} // Get takes name of the podTemplate, and returns the corresponding podTemplate object, and an error if there is any. func (c *FakePodTemplates) Get(name string, options v1.GetOptions) (result *core_v1.PodTemplate, err error) { obj, err := c.Fake. Invokes(testing.NewGetAction(podtemplatesResource, c.ns, name), &core_v1.PodTemplate{}) if obj == nil { return nil, err } return obj.(*core_v1.PodTemplate), err } // List takes label and field selectors, and returns the list of PodTemplates that match those selectors. func (c *FakePodTemplates) List(opts v1.ListOptions) (result *core_v1.PodTemplateList, err error) { obj, err := c.Fake. Invokes(testing.NewListAction(podtemplatesResource, podtemplatesKind, c.ns, opts), &core_v1.PodTemplateList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOptions(opts) if label == nil { label = labels.Everything() } list := &core_v1.PodTemplateList{ListMeta: obj.(*core_v1.PodTemplateList).ListMeta} for _, item := range obj.(*core_v1.PodTemplateList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } } return list, err } // Watch returns a watch.Interface that watches the requested podTemplates. func (c *FakePodTemplates) Watch(opts v1.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(testing.NewWatchAction(podtemplatesResource, c.ns, opts)) } // Create takes the representation of a podTemplate and creates it. Returns the server's representation of the podTemplate, and an error, if there is any. func (c *FakePodTemplates) Create(podTemplate *core_v1.PodTemplate) (result *core_v1.PodTemplate, err error) { obj, err := c.Fake. Invokes(testing.NewCreateAction(podtemplatesResource, c.ns, podTemplate), &core_v1.PodTemplate{}) if obj == nil { return nil, err } return obj.(*core_v1.PodTemplate), err } // Update takes the representation of a podTemplate and updates it. Returns the server's representation of the podTemplate, and an error, if there is any. func (c *FakePodTemplates) Update(podTemplate *core_v1.PodTemplate) (result *core_v1.PodTemplate, err error) { obj, err := c.Fake. Invokes(testing.NewUpdateAction(podtemplatesResource, c.ns, podTemplate), &core_v1.PodTemplate{}) if obj == nil { return nil, err } return obj.(*core_v1.PodTemplate), err } // Delete takes name of the podTemplate and deletes it. Returns an error if one occurs. func (c *FakePodTemplates) Delete(name string, options *v1.DeleteOptions) error { _, err := c.Fake. Invokes(testing.NewDeleteAction(podtemplatesResource, c.ns, name), &core_v1.PodTemplate{}) return err } // DeleteCollection deletes a collection of objects. func (c *FakePodTemplates) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { action := testing.NewDeleteCollectionAction(podtemplatesResource, c.ns, listOptions) _, err := c.Fake.Invokes(action, &core_v1.PodTemplateList{}) return err } // Patch applies the patch and returns the patched podTemplate. func (c *FakePodTemplates) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *core_v1.PodTemplate, err error) { obj, err := c.Fake. Invokes(testing.NewPatchSubresourceAction(podtemplatesResource, c.ns, name, data, subresources...), &core_v1.PodTemplate{}) if obj == nil { return nil, err } return obj.(*core_v1.PodTemplate), err }
{ "pile_set_name": "Github" }
export default { get (key) { try { return JSON.parse(localStorage.getItem(key)) } catch (e) {} }, set (key, val) { try { localStorage.setItem(key, JSON.stringify(val)) } catch (e) {} }, remove (key) { try { localStorage.removeItem(key) } catch (e) {} }, clear () { try { localStorage.clear() } catch (e) {} } }
{ "pile_set_name": "Github" }
#' @include geom-.r NULL #' Annotation: Custom grob #' #' This is a special geom intended for use as static annotations #' that are the same in every panel. These annotations will not #' affect scales (i.e. the x and y axes will not grow to cover the range #' of the grob, and the grob will not be modified by any ggplot settings #' or mappings). #' #' Most useful for adding tables, inset plots, and other grid-based decorations. #' #' @param grob grob to display #' @param xmin,xmax x location (in data coordinates) giving horizontal #' location of raster #' @param ymin,ymax y location (in data coordinates) giving vertical #' location of raster #' @export #' @note `annotation_custom()` expects the grob to fill the entire viewport #' defined by xmin, xmax, ymin, ymax. Grobs with a different (absolute) size #' will be center-justified in that region. #' Inf values can be used to fill the full plot panel (see examples). #' @examples #' # Dummy plot #' df <- data.frame(x = 1:10, y = 1:10) #' base <- ggplot(df, aes(x, y)) + #' geom_blank() + #' theme_bw() #' #' # Full panel annotation #' base + annotation_custom( #' grob = grid::roundrectGrob(), #' xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf #' ) #' #' # Inset plot #' df2 <- data.frame(x = 1 , y = 1) #' g <- ggplotGrob(ggplot(df2, aes(x, y)) + #' geom_point() + #' theme(plot.background = element_rect(colour = "black"))) #' base + #' annotation_custom(grob = g, xmin = 1, xmax = 10, ymin = 8, ymax = 10) annotation_custom <- function(grob, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf) { layer( data = dummy_data(), stat = StatIdentity, position = PositionIdentity, geom = GeomCustomAnn, inherit.aes = FALSE, params = list( grob = grob, xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax ) ) } #' @rdname ggplot2-ggproto #' @format NULL #' @usage NULL #' @export GeomCustomAnn <- ggproto("GeomCustomAnn", Geom, extra_params = "", handle_na = function(data, params) { data }, draw_panel = function(data, panel_params, coord, grob, xmin, xmax, ymin, ymax) { if (!inherits(coord, "CoordCartesian")) { abort("annotation_custom only works with Cartesian coordinates") } corners <- new_data_frame(list(x = c(xmin, xmax), y = c(ymin, ymax)), n = 2) data <- coord$transform(corners, panel_params) x_rng <- range(data$x, na.rm = TRUE) y_rng <- range(data$y, na.rm = TRUE) vp <- viewport(x = mean(x_rng), y = mean(y_rng), width = diff(x_rng), height = diff(y_rng), just = c("center","center")) editGrob(grob, vp = vp, name = paste(grob$name, annotation_id())) }, default_aes = aes_(xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf) ) annotation_id <- local({ i <- 1 function() { i <<- i + 1 i } })
{ "pile_set_name": "Github" }
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class BaselinesOperations(object): """BaselinesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~$(python-base-namespace).v2019_03_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, resource_uri, # type: str metricnames=None, # type: Optional[str] metricnamespace=None, # type: Optional[str] timespan=None, # type: Optional[str] interval=None, # type: Optional[datetime.timedelta] aggregation=None, # type: Optional[str] sensitivities=None, # type: Optional[str] filter=None, # type: Optional[str] result_type=None, # type: Optional[Union[str, "models.ResultType"]] **kwargs # type: Any ): # type: (...) -> Iterable["models.MetricBaselinesResponse"] """**Lists the metric baseline values for a resource**. :param resource_uri: The identifier of the resource. :type resource_uri: str :param metricnames: The names of the metrics (comma separated) to retrieve. :type metricnames: str :param metricnamespace: Metric namespace to query metric definitions for. :type metricnamespace: str :param timespan: The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. :type timespan: str :param interval: The interval (i.e. timegrain) of the query. :type interval: ~datetime.timedelta :param aggregation: The list of aggregation types (comma separated) to retrieve. :type aggregation: str :param sensitivities: The list of sensitivities (comma separated) to retrieve. :type sensitivities: str :param filter: The **$filter** is used to reduce the set of metric data returned.:code:`<br>`Example::code:`<br>`Metric contains metadata A, B and C.:code:`<br>`- Return all time series of C where A = a1 and B = b1 or b2:code:`<br>`\ **$filter=A eq ‘a1’ and B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\ :code:`<br>`- Invalid variant::code:`<br>`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\ :code:`<br>`This is invalid because the logical or operator cannot separate two different metadata names.:code:`<br>`- Return all time series where A = a1, B = b1 and C = c1::code:`<br>`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘c1’**\ :code:`<br>`- Return all time series where A = a1:code:`<br>`\ **$filter=A eq ‘a1’ and B eq ‘\ *’ and C eq ‘*\ ’**. :type filter: str :param result_type: Allows retrieving only metadata of the baseline. On data request all information is retrieved. :type result_type: str or ~$(python-base-namespace).v2019_03_01.models.ResultType :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricBaselinesResponse or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~$(python-base-namespace).v2019_03_01.models.MetricBaselinesResponse] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.MetricBaselinesResponse"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-03-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'resourceUri': self._serialize.url("resource_uri", resource_uri, 'str', skip_quote=True), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] if metricnames is not None: query_parameters['metricnames'] = self._serialize.query("metricnames", metricnames, 'str') if metricnamespace is not None: query_parameters['metricnamespace'] = self._serialize.query("metricnamespace", metricnamespace, 'str') if timespan is not None: query_parameters['timespan'] = self._serialize.query("timespan", timespan, 'str') if interval is not None: query_parameters['interval'] = self._serialize.query("interval", interval, 'duration') if aggregation is not None: query_parameters['aggregation'] = self._serialize.query("aggregation", aggregation, 'str') if sensitivities is not None: query_parameters['sensitivities'] = self._serialize.query("sensitivities", sensitivities, 'str') if filter is not None: query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') if result_type is not None: query_parameters['resultType'] = self._serialize.query("result_type", result_type, 'str') query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('MetricBaselinesResponse', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: error = self._deserialize(models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list.metadata = {'url': '/{resourceUri}/providers/microsoft.insights/metricBaselines'} # type: ignore
{ "pile_set_name": "Github" }
/* algebra3.cpp, algebra3.h - C++ Vector and Matrix Algebra routines GLUI User Interface Toolkit (LGPL) Copyright (c) 1998 Paul Rademacher WWW: http://sourceforge.net/projects/glui/ Forums: http://sourceforge.net/forum/?group_id=92496 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /************************************************************************** There are three vector classes and two matrix classes: vec2, vec3, vec4, mat3, and mat4. All the standard arithmetic operations are defined, with '*' for dot product of two vectors and multiplication of two matrices, and '^' for cross product of two vectors. Additional functions include length(), normalize(), homogenize for vectors, and print(), set(), apply() for all classes. There is a function transpose() for matrices, but note that it does not actually change the matrix, When multiplied with a matrix, a vector is treated as a row vector if it precedes the matrix (v*M), and as a column vector if it follows the matrix (M*v). Matrices are stored in row-major form. A vector of one dimension (2d, 3d, or 4d) can be cast to a vector of a higher or lower dimension. If casting to a higher dimension, the new component is set by default to 1.0, unless a value is specified: vec3 a(1.0, 2.0, 3.0 ); vec4 b( a, 4.0 ); // now b == {1.0, 2.0, 3.0, 4.0}; When casting to a lower dimension, the vector is homogenized in the lower dimension. E.g., if a 4d {X,Y,Z,W} is cast to 3d, the resulting vector is {X/W, Y/W, Z/W}. It is up to the user to insure the fourth component is not zero before casting. There are also the following function for building matrices: identity2D(), translation2D(), rotation2D(), scaling2D(), identity3D(), translation3D(), rotation3D(), rotation3Drad(), scaling3D(), perspective3D() --------------------------------------------------------------------- Author: Jean-Francois DOUEg Revised: Paul Rademacher Version 3.2 - Feb 1998 Revised: Nigel Stewart (GLUI Code Cleaning) **************************************************************************/ #include "algebra3.h" #include "glui_internal.h" #include <cmath> #ifdef VEC_ERROR_FATAL #ifndef VEC_ERROR #define VEC_ERROR(E) { printf( "VERROR %s\n", E ); exit(1); } #endif #else #ifndef VEC_ERROR #define VEC_ERROR(E) { printf( "VERROR %s\n", E ); } #endif #endif /**************************************************************** * * * vec2 Member functions * * * ****************************************************************/ /******************** vec2 CONSTRUCTORS ********************/ vec2::vec2() { n[VX] = n[VY] = 0.0; } vec2::vec2(float x, float y) { n[VX] = x; n[VY] = y; } vec2::vec2(const vec2 &v) { n[VX] = v.n[VX]; n[VY] = v.n[VY]; } vec2::vec2(const vec3 &v) // it is up to caller to avoid divide-by-zero { n[VX] = v.n[VX]/v.n[VZ]; n[VY] = v.n[VY]/v.n[VZ]; } vec2::vec2(const vec3 &v, int dropAxis) { switch (dropAxis) { case VX: n[VX] = v.n[VY]; n[VY] = v.n[VZ]; break; case VY: n[VX] = v.n[VX]; n[VY] = v.n[VZ]; break; default: n[VX] = v.n[VX]; n[VY] = v.n[VY]; break; } } /******************** vec2 ASSIGNMENT OPERATORS ******************/ vec2 & vec2::operator=(const vec2 &v) { n[VX] = v.n[VX]; n[VY] = v.n[VY]; return *this; } vec2 & vec2::operator+=(const vec2 &v) { n[VX] += v.n[VX]; n[VY] += v.n[VY]; return *this; } vec2 & vec2::operator-=(const vec2 &v) { n[VX] -= v.n[VX]; n[VY] -= v.n[VY]; return *this; } vec2 &vec2::operator*=(float d) { n[VX] *= d; n[VY] *= d; return *this; } vec2 &vec2::operator/=(float d) { float d_inv = 1.0f/d; n[VX] *= d_inv; n[VY] *= d_inv; return *this; } float &vec2::operator[](int i) { if (i < VX || i > VY) //VEC_ERROR("vec2 [] operator: illegal access; index = " << i << '\n') VEC_ERROR("vec2 [] operator: illegal access" ); return n[i]; } const float &vec2::operator[](int i) const { if (i < VX || i > VY) //VEC_ERROR("vec2 [] operator: illegal access; index = " << i << '\n') VEC_ERROR("vec2 [] operator: illegal access" ); return n[i]; } /******************** vec2 SPECIAL FUNCTIONS ********************/ float vec2::length() const { return (float) sqrt(length2()); } float vec2::length2() const { return n[VX]*n[VX] + n[VY]*n[VY]; } vec2 &vec2::normalize() // it is up to caller to avoid divide-by-zero { *this /= length(); return *this; } vec2 &vec2::apply(V_FCT_PTR fct) { n[VX] = (*fct)(n[VX]); n[VY] = (*fct)(n[VY]); return *this; } void vec2::set( float x, float y ) { n[VX] = x; n[VY] = y; } /******************** vec2 FRIENDS *****************************/ vec2 operator-(const vec2 &a) { return vec2(-a.n[VX],-a.n[VY]); } vec2 operator+(const vec2 &a, const vec2& b) { return vec2(a.n[VX]+b.n[VX], a.n[VY]+b.n[VY]); } vec2 operator-(const vec2 &a, const vec2& b) { return vec2(a.n[VX]-b.n[VX], a.n[VY]-b.n[VY]); } vec2 operator*(const vec2 &a, float d) { return vec2(d*a.n[VX], d*a.n[VY]); } vec2 operator*(float d, const vec2 &a) { return a*d; } vec2 operator*(const mat3 &a, const vec2 &v) { vec3 av; av.n[VX] = a.v[0].n[VX]*v.n[VX] + a.v[0].n[VY]*v.n[VY] + a.v[0].n[VZ]; av.n[VY] = a.v[1].n[VX]*v.n[VX] + a.v[1].n[VY]*v.n[VY] + a.v[1].n[VZ]; av.n[VZ] = a.v[2].n[VX]*v.n[VX] + a.v[2].n[VY]*v.n[VY] + a.v[2].n[VZ]; return av; } vec2 operator*(const vec2 &v, const mat3 &a) { return a.transpose() * v; } vec3 operator*(const mat3 &a, const vec3 &v) { vec3 av; av.n[VX] = a.v[0].n[VX]*v.n[VX] + a.v[0].n[VY]*v.n[VY] + a.v[0].n[VZ]*v.n[VZ]; av.n[VY] = a.v[1].n[VX]*v.n[VX] + a.v[1].n[VY]*v.n[VY] + a.v[1].n[VZ]*v.n[VZ]; av.n[VZ] = a.v[2].n[VX]*v.n[VX] + a.v[2].n[VY]*v.n[VY] + a.v[2].n[VZ]*v.n[VZ]; return av; } vec3 operator*(const vec3 &v, const mat3 &a) { return a.transpose() * v; } float operator*(const vec2 &a, const vec2 &b) { return a.n[VX]*b.n[VX] + a.n[VY]*b.n[VY]; } vec2 operator/(const vec2 &a, float d) { float d_inv = 1.0f/d; return vec2(a.n[VX]*d_inv, a.n[VY]*d_inv); } vec3 operator^(const vec2 &a, const vec2 &b) { return vec3(0.0, 0.0, a.n[VX] * b.n[VY] - b.n[VX] * a.n[VY]); } int operator==(const vec2 &a, const vec2 &b) { return (a.n[VX] == b.n[VX]) && (a.n[VY] == b.n[VY]); } int operator!=(const vec2 &a, const vec2 &b) { return !(a == b); } /*ostream& operator << (ostream& s, vec2& v) { return s << "| " << v.n[VX] << ' ' << v.n[VY] << " |"; } */ /*istream& operator >> (istream& s, vec2& v) { vec2 v_tmp; char c = ' '; while (isspace(c)) s >> c; // The vectors can be formatted either as x y or | x y | if (c == '|') { s >> v_tmp[VX] >> v_tmp[VY]; while (s >> c && isspace(c)) ; if (c != '|') ;//s.set(_bad); } else { s.putback(c); s >> v_tmp[VX] >> v_tmp[VY]; } if (s) v = v_tmp; return s; } */ void swap(vec2 &a, vec2 &b) { vec2 tmp(a); a = b; b = tmp; } vec2 min_vec(const vec2 &a, const vec2 &b) { return vec2(MIN(a.n[VX], b.n[VX]), MIN(a.n[VY], b.n[VY])); } vec2 max_vec(const vec2 &a, const vec2 &b) { return vec2(MAX(a.n[VX], b.n[VX]), MAX(a.n[VY], b.n[VY])); } vec2 prod(const vec2 &a, const vec2 &b) { return vec2(a.n[VX] * b.n[VX], a.n[VY] * b.n[VY]); } /**************************************************************** * * * vec3 Member functions * * * ****************************************************************/ // CONSTRUCTORS vec3::vec3() { n[VX] = n[VY] = n[VZ] = 0.0; } vec3::vec3(float x, float y, float z) { n[VX] = x; n[VY] = y; n[VZ] = z; } vec3::vec3(const vec3 &v) { n[VX] = v.n[VX]; n[VY] = v.n[VY]; n[VZ] = v.n[VZ]; } vec3::vec3(const vec2 &v) { n[VX] = v.n[VX]; n[VY] = v.n[VY]; n[VZ] = 1.0; } vec3::vec3(const vec2 &v, float d) { n[VX] = v.n[VX]; n[VY] = v.n[VY]; n[VZ] = d; } vec3::vec3(const vec4 &v) // it is up to caller to avoid divide-by-zero { n[VX] = v.n[VX] / v.n[VW]; n[VY] = v.n[VY] / v.n[VW]; n[VZ] = v.n[VZ] / v.n[VW]; } vec3::vec3(const vec4 &v, int dropAxis) { switch (dropAxis) { case VX: n[VX] = v.n[VY]; n[VY] = v.n[VZ]; n[VZ] = v.n[VW]; break; case VY: n[VX] = v.n[VX]; n[VY] = v.n[VZ]; n[VZ] = v.n[VW]; break; case VZ: n[VX] = v.n[VX]; n[VY] = v.n[VY]; n[VZ] = v.n[VW]; break; default: n[VX] = v.n[VX]; n[VY] = v.n[VY]; n[VZ] = v.n[VZ]; break; } } // ASSIGNMENT OPERATORS vec3 &vec3::operator=(const vec3 &v) { n[VX] = v.n[VX]; n[VY] = v.n[VY]; n[VZ] = v.n[VZ]; return *this; } vec3 &vec3::operator+=(const vec3 &v) { n[VX] += v.n[VX]; n[VY] += v.n[VY]; n[VZ] += v.n[VZ]; return *this; } vec3 &vec3::operator-=(const vec3& v) { n[VX] -= v.n[VX]; n[VY] -= v.n[VY]; n[VZ] -= v.n[VZ]; return *this; } vec3 &vec3::operator*=(float d) { n[VX] *= d; n[VY] *= d; n[VZ] *= d; return *this; } vec3 &vec3::operator/=(float d) { float d_inv = 1.0f/d; n[VX] *= d_inv; n[VY] *= d_inv; n[VZ] *= d_inv; return *this; } float &vec3::operator[](int i) { if (i < VX || i > VZ) //VEC_ERROR("vec3 [] operator: illegal access; index = " << i << '\n') VEC_ERROR("vec3 [] operator: illegal access" ); return n[i]; } const float &vec3::operator[](int i) const { if (i < VX || i > VZ) //VEC_ERROR("vec3 [] operator: illegal access; index = " << i << '\n') VEC_ERROR("vec3 [] operator: illegal access" ); return n[i]; } // SPECIAL FUNCTIONS float vec3::length() const { return (float) sqrt(length2()); } float vec3::length2() const { return n[VX]*n[VX] + n[VY]*n[VY] + n[VZ]*n[VZ]; } vec3 &vec3::normalize() // it is up to caller to avoid divide-by-zero { *this /= length(); return *this; } vec3 &vec3::homogenize(void) // it is up to caller to avoid divide-by-zero { n[VX] /= n[VZ]; n[VY] /= n[VZ]; n[VZ] = 1.0; return *this; } vec3 &vec3::apply(V_FCT_PTR fct) { n[VX] = (*fct)(n[VX]); n[VY] = (*fct)(n[VY]); n[VZ] = (*fct)(n[VZ]); return *this; } void vec3::set(float x, float y, float z) // set vector { n[VX] = x; n[VY] = y; n[VZ] = z; } void vec3::print(FILE *file, const char *name) const // print vector to a file { fprintf( file, "%s: <%f, %f, %f>\n", name, n[VX], n[VY], n[VZ] ); } // FRIENDS vec3 operator-(const vec3 &a) { return vec3(-a.n[VX],-a.n[VY],-a.n[VZ]); } vec3 operator+(const vec3 &a, const vec3 &b) { return vec3(a.n[VX]+ b.n[VX], a.n[VY] + b.n[VY], a.n[VZ] + b.n[VZ]); } vec3 operator-(const vec3 &a, const vec3 &b) { return vec3(a.n[VX]-b.n[VX], a.n[VY]-b.n[VY], a.n[VZ]-b.n[VZ]); } vec3 operator*(const vec3 &a, float d) { return vec3(d*a.n[VX], d*a.n[VY], d*a.n[VZ]); } vec3 operator*(float d, const vec3 &a) { return a*d; } vec3 operator*(const mat4 &a, const vec3 &v) { return a*vec4(v); } vec3 operator*(const vec3 &v, mat4 &a) { return a.transpose()*v; } float operator*(const vec3 &a, const vec3 &b) { return a.n[VX]*b.n[VX] + a.n[VY]*b.n[VY] + a.n[VZ]*b.n[VZ]; } vec3 operator/(const vec3 &a, float d) { float d_inv = 1.0f/d; return vec3(a.n[VX]*d_inv, a.n[VY]*d_inv, a.n[VZ]*d_inv); } vec3 operator^(const vec3 &a, const vec3 &b) { return vec3(a.n[VY]*b.n[VZ] - a.n[VZ]*b.n[VY], a.n[VZ]*b.n[VX] - a.n[VX]*b.n[VZ], a.n[VX]*b.n[VY] - a.n[VY]*b.n[VX]); } int operator==(const vec3 &a, const vec3 &b) { return (a.n[VX] == b.n[VX]) && (a.n[VY] == b.n[VY]) && (a.n[VZ] == b.n[VZ]); } int operator!=(const vec3 &a, const vec3 &b) { return !(a == b); } /*ostream& operator << (ostream& s, vec3& v) { return s << "| " << v.n[VX] << ' ' << v.n[VY] << ' ' << v.n[VZ] << " |"; } istream& operator >> (istream& s, vec3& v) { vec3 v_tmp; char c = ' '; while (isspace(c)) s >> c; // The vectors can be formatted either as x y z or | x y z | if (c == '|') { s >> v_tmp[VX] >> v_tmp[VY] >> v_tmp[VZ]; while (s >> c && isspace(c)) ; if (c != '|') ;//s.set(_bad); } else { s.putback(c); s >> v_tmp[VX] >> v_tmp[VY] >> v_tmp[VZ]; } if (s) v = v_tmp; return s; } */ void swap(vec3 &a, vec3 &b) { vec3 tmp(a); a = b; b = tmp; } vec3 min_vec(const vec3 &a, const vec3 &b) { return vec3( MIN(a.n[VX], b.n[VX]), MIN(a.n[VY], b.n[VY]), MIN(a.n[VZ], b.n[VZ])); } vec3 max_vec(const vec3 &a, const vec3 &b) { return vec3( MAX(a.n[VX], b.n[VX]), MAX(a.n[VY], b.n[VY]), MAX(a.n[VZ], b.n[VZ])); } vec3 prod(const vec3 &a, const vec3 &b) { return vec3(a.n[VX]*b.n[VX], a.n[VY]*b.n[VY], a.n[VZ]*b.n[VZ]); } /**************************************************************** * * * vec4 Member functions * * * ****************************************************************/ // CONSTRUCTORS vec4::vec4() { n[VX] = n[VY] = n[VZ] = 0.0; n[VW] = 1.0; } vec4::vec4(float x, float y, float z, float w) { n[VX] = x; n[VY] = y; n[VZ] = z; n[VW] = w; } vec4::vec4(const vec4 &v) { n[VX] = v.n[VX]; n[VY] = v.n[VY]; n[VZ] = v.n[VZ]; n[VW] = v.n[VW]; } vec4::vec4(const vec3 &v) { n[VX] = v.n[VX]; n[VY] = v.n[VY]; n[VZ] = v.n[VZ]; n[VW] = 1.0; } vec4::vec4(const vec3 &v, float d) { n[VX] = v.n[VX]; n[VY] = v.n[VY]; n[VZ] = v.n[VZ]; n[VW] = d; } // ASSIGNMENT OPERATORS vec4 &vec4::operator=(const vec4 &v) { n[VX] = v.n[VX]; n[VY] = v.n[VY]; n[VZ] = v.n[VZ]; n[VW] = v.n[VW]; return *this; } vec4 &vec4::operator+=(const vec4 &v) { n[VX] += v.n[VX]; n[VY] += v.n[VY]; n[VZ] += v.n[VZ]; n[VW] += v.n[VW]; return *this; } vec4 &vec4::operator-=(const vec4 &v) { n[VX] -= v.n[VX]; n[VY] -= v.n[VY]; n[VZ] -= v.n[VZ]; n[VW] -= v.n[VW]; return *this; } vec4 &vec4::operator*=(float d) { n[VX] *= d; n[VY] *= d; n[VZ] *= d; n[VW] *= d; return *this; } vec4 &vec4::operator/=(float d) { float d_inv = 1.0f/d; n[VX] *= d_inv; n[VY] *= d_inv; n[VZ] *= d_inv; n[VW] *= d_inv; return *this; } float &vec4::operator[](int i) { if (i < VX || i > VW) //VEC_ERROR("vec4 [] operator: illegal access; index = " << i << '\n') VEC_ERROR("vec4 [] operator: illegal access" ); return n[i]; } const float &vec4::operator[](int i) const { if (i < VX || i > VW) //VEC_ERROR("vec4 [] operator: illegal access; index = " << i << '\n') VEC_ERROR("vec4 [] operator: illegal access" ); return n[i]; } // SPECIAL FUNCTIONS float vec4::length() const { return (float) sqrt(length2()); } float vec4::length2() const { return n[VX]*n[VX] + n[VY]*n[VY] + n[VZ]*n[VZ] + n[VW]*n[VW]; } vec4 &vec4::normalize() // it is up to caller to avoid divide-by-zero { *this /= length(); return *this; } vec4 &vec4::homogenize() // it is up to caller to avoid divide-by-zero { n[VX] /= n[VW]; n[VY] /= n[VW]; n[VZ] /= n[VW]; n[VW] = 1.0; return *this; } vec4 &vec4::apply(V_FCT_PTR fct) { n[VX] = (*fct)(n[VX]); n[VY] = (*fct)(n[VY]); n[VZ] = (*fct)(n[VZ]); n[VW] = (*fct)(n[VW]); return *this; } void vec4::print(FILE *file, const char *name) const // print vector to a file { fprintf( file, "%s: <%f, %f, %f, %f>\n", name, n[VX], n[VY], n[VZ], n[VW]); } void vec4::set(float x, float y, float z, float a) { n[0] = x; n[1] = y; n[2] = z; n[3] = a; } // FRIENDS vec4 operator-(const vec4 &a) { return vec4(-a.n[VX],-a.n[VY],-a.n[VZ],-a.n[VW]); } vec4 operator+(const vec4 &a, const vec4 &b) { return vec4( a.n[VX] + b.n[VX], a.n[VY] + b.n[VY], a.n[VZ] + b.n[VZ], a.n[VW] + b.n[VW]); } vec4 operator-(const vec4 &a, const vec4 &b) { return vec4( a.n[VX] - b.n[VX], a.n[VY] - b.n[VY], a.n[VZ] - b.n[VZ], a.n[VW] - b.n[VW]); } vec4 operator*(const vec4 &a, float d) { return vec4(d*a.n[VX], d*a.n[VY], d*a.n[VZ], d*a.n[VW]); } vec4 operator*(float d, const vec4 &a) { return a*d; } vec4 operator*(const mat4 &a, const vec4 &v) { #define ROWCOL(i) \ a.v[i].n[0]*v.n[VX] + \ a.v[i].n[1]*v.n[VY] + \ a.v[i].n[2]*v.n[VZ] + \ a.v[i].n[3]*v.n[VW] return vec4(ROWCOL(0), ROWCOL(1), ROWCOL(2), ROWCOL(3)); #undef ROWCOL } vec4 operator*(const vec4 &v, const mat4 &a) { return a.transpose()*v; } float operator*(const vec4 &a, const vec4 &b) { return a.n[VX]*b.n[VX] + a.n[VY]*b.n[VY] + a.n[VZ]*b.n[VZ] + a.n[VW]*b.n[VW]; } vec4 operator/(const vec4 &a, float d) { float d_inv = 1.0f/d; return vec4( a.n[VX]*d_inv, a.n[VY]*d_inv, a.n[VZ]*d_inv, a.n[VW]*d_inv); } int operator==(const vec4 &a, const vec4 &b) { return (a.n[VX] == b.n[VX]) && (a.n[VY] == b.n[VY]) && (a.n[VZ] == b.n[VZ]) && (a.n[VW] == b.n[VW]); } int operator!=(const vec4 &a, const vec4 &b) { return !(a == b); } /*ostream& operator << (ostream& s, vec4& v) { return s << "| " << v.n[VX] << ' ' << v.n[VY] << ' ' << v.n[VZ] << ' ' << v.n[VW] << " |"; } istream& operator >> (istream& s, vec4& v) { vec4 v_tmp; char c = ' '; while (isspace(c)) s >> c; // The vectors can be formatted either as x y z w or | x y z w | if (c == '|') { s >> v_tmp[VX] >> v_tmp[VY] >> v_tmp[VZ] >> v_tmp[VW]; while (s >> c && isspace(c)) ; if (c != '|') ;//s.set(_bad); } else { s.putback(c); s >> v_tmp[VX] >> v_tmp[VY] >> v_tmp[VZ] >> v_tmp[VW]; } if (s) v = v_tmp; return s; } */ void swap(vec4 &a, vec4 &b) { vec4 tmp(a); a = b; b = tmp; } vec4 min_vec(const vec4 &a, const vec4 &b) { return vec4( MIN(a.n[VX], b.n[VX]), MIN(a.n[VY], b.n[VY]), MIN(a.n[VZ], b.n[VZ]), MIN(a.n[VW], b.n[VW])); } vec4 max_vec(const vec4 &a, const vec4 &b) { return vec4( MAX(a.n[VX], b.n[VX]), MAX(a.n[VY], b.n[VY]), MAX(a.n[VZ], b.n[VZ]), MAX(a.n[VW], b.n[VW])); } vec4 prod(const vec4 &a, const vec4 &b) { return vec4( a.n[VX] * b.n[VX], a.n[VY] * b.n[VY], a.n[VZ] * b.n[VZ], a.n[VW] * b.n[VW]); } /**************************************************************** * * * mat3 member functions * * * ****************************************************************/ // CONSTRUCTORS mat3::mat3() { *this = identity2D(); } mat3::mat3(const vec3 &v0, const vec3 &v1, const vec3 &v2) { set(v0, v1, v2); } mat3::mat3(const mat3 &m) { v[0] = m.v[0]; v[1] = m.v[1]; v[2] = m.v[2]; } // ASSIGNMENT OPERATORS mat3 &mat3::operator=(const mat3 &m) { v[0] = m.v[0]; v[1] = m.v[1]; v[2] = m.v[2]; return *this; } mat3 &mat3::operator+=(const mat3& m) { v[0] += m.v[0]; v[1] += m.v[1]; v[2] += m.v[2]; return *this; } mat3 &mat3::operator-=(const mat3& m) { v[0] -= m.v[0]; v[1] -= m.v[1]; v[2] -= m.v[2]; return *this; } mat3 &mat3::operator*=(float d) { v[0] *= d; v[1] *= d; v[2] *= d; return *this; } mat3 &mat3::operator/=(float d) { v[0] /= d; v[1] /= d; v[2] /= d; return *this; } vec3 &mat3::operator[](int i) { if (i < VX || i > VZ) //VEC_ERROR("mat3 [] operator: illegal access; index = " << i << '\n') VEC_ERROR("mat3 [] operator: illegal access" ); return v[i]; } const vec3 &mat3::operator[](int i) const { if (i < VX || i > VZ) //VEC_ERROR("mat3 [] operator: illegal access; index = " << i << '\n') VEC_ERROR("mat3 [] operator: illegal access" ); return v[i]; } void mat3::set(const vec3 &v0, const vec3 &v1, const vec3 &v2) { v[0] = v0; v[1] = v1; v[2] = v2; } // SPECIAL FUNCTIONS mat3 mat3::transpose() const { return mat3( vec3(v[0][0], v[1][0], v[2][0]), vec3(v[0][1], v[1][1], v[2][1]), vec3(v[0][2], v[1][2], v[2][2])); } mat3 mat3::inverse() const // Gauss-Jordan elimination with partial pivoting { mat3 a(*this); // As a evolves from original mat into identity mat3 b(identity2D()); // b evolves from identity into inverse(a) int i, j, i1; // Loop over cols of a from left to right, eliminating above and below diag for (j=0; j<3; j++) // Find largest pivot in column j among rows j..2 { i1 = j; // Row with largest pivot candidate for (i=j+1; i<3; i++) if (fabs(a.v[i].n[j]) > fabs(a.v[i1].n[j])) i1 = i; // Swap rows i1 and j in a and b to put pivot on diagonal swap(a.v[i1], a.v[j]); swap(b.v[i1], b.v[j]); // Scale row j to have a unit diagonal if (a.v[j].n[j]==0.) VEC_ERROR("mat3::inverse: singular matrix; can't invert\n"); b.v[j] /= a.v[j].n[j]; a.v[j] /= a.v[j].n[j]; // Eliminate off-diagonal elems in col j of a, doing identical ops to b for (i=0; i<3; i++) if (i!=j) { b.v[i] -= a.v[i].n[j]*b.v[j]; a.v[i] -= a.v[i].n[j]*a.v[j]; } } return b; } mat3 &mat3::apply(V_FCT_PTR fct) { v[VX].apply(fct); v[VY].apply(fct); v[VZ].apply(fct); return *this; } // FRIENDS mat3 operator-(const mat3 &a) { return mat3(-a.v[0], -a.v[1], -a.v[2]); } mat3 operator+(const mat3 &a, const mat3 &b) { return mat3(a.v[0]+b.v[0], a.v[1]+b.v[1], a.v[2]+b.v[2]); } mat3 operator-(const mat3 &a, const mat3 &b) { return mat3(a.v[0]-b.v[0], a.v[1]-b.v[1], a.v[2]-b.v[2]); } mat3 operator*(const mat3 &a, const mat3 &b) { #define ROWCOL(i, j) \ a.v[i].n[0]*b.v[0][j] + a.v[i].n[1]*b.v[1][j] + a.v[i].n[2]*b.v[2][j] return mat3( vec3(ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2)), vec3(ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2)), vec3(ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2))); #undef ROWCOL } mat3 operator*(const mat3 &a, float d) { return mat3(a.v[0]*d, a.v[1]*d, a.v[2]*d); } mat3 operator*(float d, const mat3 &a) { return a*d; } mat3 operator/(const mat3 &a, float d) { return mat3(a.v[0]/d, a.v[1]/d, a.v[2]/d); } int operator==(const mat3 &a, const mat3 &b) { return (a.v[0] == b.v[0]) && (a.v[1] == b.v[1]) && (a.v[2] == b.v[2]); } int operator!=(const mat3 &a, const mat3 &b) { return !(a == b); } /*ostream& operator << (ostream& s, mat3& m) { return s << m.v[VX] << '\n' << m.v[VY] << '\n' << m.v[VZ]; } istream& operator >> (istream& s, mat3& m) { mat3 m_tmp; s >> m_tmp[VX] >> m_tmp[VY] >> m_tmp[VZ]; if (s) m = m_tmp; return s; } */ void swap(mat3 &a, mat3 &b) { mat3 tmp(a); a = b; b = tmp; } void mat3::print(FILE *file, const char *name) const { int i, j; fprintf( stderr, "%s:\n", name ); for( i = 0; i < 3; i++ ) { fprintf( stderr, " " ); for( j = 0; j < 3; j++ ) { fprintf( stderr, "%f ", v[i][j] ); } fprintf( stderr, "\n" ); } } /**************************************************************** * * * mat4 member functions * * * ****************************************************************/ // CONSTRUCTORS mat4::mat4() { *this = identity3D(); } mat4::mat4(const vec4& v0, const vec4& v1, const vec4& v2, const vec4& v3) { v[0] = v0; v[1] = v1; v[2] = v2; v[3] = v3; } mat4::mat4(const mat4 &m) { v[0] = m.v[0]; v[1] = m.v[1]; v[2] = m.v[2]; v[3] = m.v[3]; } mat4::mat4( float a00, float a01, float a02, float a03, float a10, float a11, float a12, float a13, float a20, float a21, float a22, float a23, float a30, float a31, float a32, float a33 ) { v[0][0] = a00; v[0][1] = a01; v[0][2] = a02; v[0][3] = a03; v[1][0] = a10; v[1][1] = a11; v[1][2] = a12; v[1][3] = a13; v[2][0] = a20; v[2][1] = a21; v[2][2] = a22; v[2][3] = a23; v[3][0] = a30; v[3][1] = a31; v[3][2] = a32; v[3][3] = a33; } // ASSIGNMENT OPERATORS mat4 &mat4::operator=(const mat4 &m) { v[0] = m.v[0]; v[1] = m.v[1]; v[2] = m.v[2]; v[3] = m.v[3]; return *this; } mat4 &mat4::operator+=(const mat4 &m) { v[0] += m.v[0]; v[1] += m.v[1]; v[2] += m.v[2]; v[3] += m.v[3]; return *this; } mat4 &mat4::operator-=(const mat4 &m) { v[0] -= m.v[0]; v[1] -= m.v[1]; v[2] -= m.v[2]; v[3] -= m.v[3]; return *this; } mat4 &mat4::operator*=(float d) { v[0] *= d; v[1] *= d; v[2] *= d; v[3] *= d; return *this; } mat4 &mat4::operator/=(float d) { v[0] /= d; v[1] /= d; v[2] /= d; v[3] /= d; return *this; } vec4 &mat4::operator[](int i) { if (i < VX || i > VW) //VEC_ERROR("mat4 [] operator: illegal access; index = " << i << '\n') VEC_ERROR("mat4 [] operator: illegal access" ); return v[i]; } const vec4 &mat4::operator[](int i) const { if (i < VX || i > VW) //VEC_ERROR("mat4 [] operator: illegal access; index = " << i << '\n') VEC_ERROR("mat4 [] operator: illegal access" ); return v[i]; } // SPECIAL FUNCTIONS; mat4 mat4::transpose() const { return mat4( vec4(v[0][0], v[1][0], v[2][0], v[3][0]), vec4(v[0][1], v[1][1], v[2][1], v[3][1]), vec4(v[0][2], v[1][2], v[2][2], v[3][2]), vec4(v[0][3], v[1][3], v[2][3], v[3][3])); } mat4 mat4::inverse() const // Gauss-Jordan elimination with partial pivoting { mat4 a(*this); // As a evolves from original mat into identity mat4 b(identity3D()); // b evolves from identity into inverse(a) int i, j, i1; // Loop over cols of a from left to right, eliminating above and below diag for (j=0; j<4; j++) // Find largest pivot in column j among rows j..3 { i1 = j; // Row with largest pivot candidate for (i=j+1; i<4; i++) if (fabs(a.v[i].n[j]) > fabs(a.v[i1].n[j])) i1 = i; // Swap rows i1 and j in a and b to put pivot on diagonal swap(a.v[i1], a.v[j]); swap(b.v[i1], b.v[j]); // Scale row j to have a unit diagonal if (a.v[j].n[j]==0.) VEC_ERROR("mat4::inverse: singular matrix; can't invert\n"); b.v[j] /= a.v[j].n[j]; a.v[j] /= a.v[j].n[j]; // Eliminate off-diagonal elems in col j of a, doing identical ops to b for (i=0; i<4; i++) if (i!=j) { b.v[i] -= a.v[i].n[j]*b.v[j]; a.v[i] -= a.v[i].n[j]*a.v[j]; } } return b; } mat4 &mat4::apply(V_FCT_PTR fct) { v[VX].apply(fct); v[VY].apply(fct); v[VZ].apply(fct); v[VW].apply(fct); return *this; } void mat4::print(FILE *file, const char *name) const { int i, j; fprintf( stderr, "%s:\n", name ); for( i = 0; i < 4; i++ ) { fprintf( stderr, " " ); for( j = 0; j < 4; j++ ) { fprintf( stderr, "%f ", v[i][j] ); } fprintf( stderr, "\n" ); } } void mat4::swap_rows(int i, int j) { vec4 t; t = v[i]; v[i] = v[j]; v[j] = t; } void mat4::swap_cols(int i, int j) { float t; int k; for (k=0; k<4; k++) { t = v[k][i]; v[k][i] = v[k][j]; v[k][j] = t; } } // FRIENDS mat4 operator-(const mat4 &a) { return mat4(-a.v[0],-a.v[1],-a.v[2],-a.v[3]); } mat4 operator+(const mat4 &a, const mat4 &b) { return mat4( a.v[0] + b.v[0], a.v[1] + b.v[1], a.v[2] + b.v[2], a.v[3] + b.v[3]); } mat4 operator-(const mat4 &a, const mat4 &b) { return mat4( a.v[0] - b.v[0], a.v[1] - b.v[1], a.v[2] - b.v[2], a.v[3] - b.v[3]); } mat4 operator*(const mat4 &a, const mat4 &b) { #define ROWCOL(i, j) \ a.v[i].n[0]*b.v[0][j] + \ a.v[i].n[1]*b.v[1][j] + \ a.v[i].n[2]*b.v[2][j] + \ a.v[i].n[3]*b.v[3][j] return mat4( vec4(ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2), ROWCOL(0,3)), vec4(ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2), ROWCOL(1,3)), vec4(ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2), ROWCOL(2,3)), vec4(ROWCOL(3,0), ROWCOL(3,1), ROWCOL(3,2), ROWCOL(3,3)) ); #undef ROWCOL } mat4 operator*(const mat4 &a, float d) { return mat4(a.v[0]*d, a.v[1]*d, a.v[2]*d, a.v[3]*d); } mat4 operator*(float d, const mat4 &a) { return a*d; } mat4 operator/(const mat4 &a, float d) { return mat4(a.v[0]/d, a.v[1]/d, a.v[2]/d, a.v[3]/d); } int operator==(const mat4 &a, const mat4 &b) { return (a.v[0] == b.v[0]) && (a.v[1] == b.v[1]) && (a.v[2] == b.v[2]) && (a.v[3] == b.v[3]); } int operator!=(const mat4 &a, const mat4 &b) { return !(a == b); } /*ostream& operator << (ostream& s, mat4& m) { return s << m.v[VX] << '\n' << m.v[VY] << '\n' << m.v[VZ] << '\n' << m.v[VW]; } istream& operator >> (istream& s, mat4& m) { mat4 m_tmp; s >> m_tmp[VX] >> m_tmp[VY] >> m_tmp[VZ] >> m_tmp[VW]; if (s) m = m_tmp; return s; } */ void swap(mat4 &a, mat4 &b) { mat4 tmp(a); a = b; b = tmp; } /**************************************************************** * * * 2D functions and 3D functions * * * ****************************************************************/ mat3 identity2D() { return mat3( vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0)); } mat3 translation2D(const vec2 &v) { return mat3( vec3(1.0, 0.0, v[VX]), vec3(0.0, 1.0, v[VY]), vec3(0.0, 0.0, 1.0)); } mat3 rotation2D(const vec2 &Center, float angleDeg) { float angleRad = (float) (angleDeg * M_PI / 180.0); float c = (float) cos(angleRad); float s = (float) sin(angleRad); return mat3( vec3(c, -s, Center[VX] * (1.0f-c) + Center[VY] * s), vec3(s, c, Center[VY] * (1.0f-c) - Center[VX] * s), vec3(0.0, 0.0, 1.0)); } mat3 scaling2D(const vec2 &scaleVector) { return mat3( vec3(scaleVector[VX], 0.0, 0.0), vec3(0.0, scaleVector[VY], 0.0), vec3(0.0, 0.0, 1.0)); } mat4 identity3D() { return mat4( vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); } mat4 translation3D(const vec3 &v) { return mat4( vec4(1.0, 0.0, 0.0, v[VX]), vec4(0.0, 1.0, 0.0, v[VY]), vec4(0.0, 0.0, 1.0, v[VZ]), vec4(0.0, 0.0, 0.0, 1.0)); } mat4 rotation3D(const vec3 &Axis, float angleDeg) { float angleRad = (float) (angleDeg * M_PI / 180.0); float c = (float) cos(angleRad); float s = (float) sin(angleRad); float t = 1.0f - c; vec3 axis(Axis); axis.normalize(); return mat4( vec4(t * axis[VX] * axis[VX] + c, t * axis[VX] * axis[VY] - s * axis[VZ], t * axis[VX] * axis[VZ] + s * axis[VY], 0.0), vec4(t * axis[VX] * axis[VY] + s * axis[VZ], t * axis[VY] * axis[VY] + c, t * axis[VY] * axis[VZ] - s * axis[VX], 0.0), vec4(t * axis[VX] * axis[VZ] - s * axis[VY], t * axis[VY] * axis[VZ] + s * axis[VX], t * axis[VZ] * axis[VZ] + c, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); } mat4 rotation3Drad(const vec3 &Axis, float angleRad) { float c = (float) cos(angleRad); float s = (float) sin(angleRad); float t = 1.0f - c; vec3 axis(Axis); axis.normalize(); return mat4( vec4(t * axis[VX] * axis[VX] + c, t * axis[VX] * axis[VY] - s * axis[VZ], t * axis[VX] * axis[VZ] + s * axis[VY], 0.0), vec4(t * axis[VX] * axis[VY] + s * axis[VZ], t * axis[VY] * axis[VY] + c, t * axis[VY] * axis[VZ] - s * axis[VX], 0.0), vec4(t * axis[VX] * axis[VZ] - s * axis[VY], t * axis[VY] * axis[VZ] + s * axis[VX], t * axis[VZ] * axis[VZ] + c, 0.0), vec4(0.0, 0.0, 0.0, 1.0)); } mat4 scaling3D(const vec3 &scaleVector) { return mat4( vec4(scaleVector[VX], 0.0, 0.0, 0.0), vec4(0.0, scaleVector[VY], 0.0, 0.0), vec4(0.0, 0.0, scaleVector[VZ], 0.0), vec4(0.0, 0.0, 0.0, 1.0)); } mat4 perspective3D(float d) { return mat4( vec4(1.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 1.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 1.0f, 0.0f), vec4(0.0f, 0.0f, 1.0f/d, 0.0f)); }
{ "pile_set_name": "Github" }
{ "name": "0-dns", "version": "1.0.0", "description": "create certificate for 0-dns test", "main": "createCert.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "SEE LICENSE IN ../../../LICENSE", "private": true, "dependencies": { "asn1.js": "^4.9.1", "asn1.js-rfc5280": "^1.2.2" } }
{ "pile_set_name": "Github" }
/** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Request; import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class NotificationFetcher extends Fetcher<Notification> { private String pathAccountSid; private final String pathSid; /** * Construct a new NotificationFetcher. * * @param pathSid The unique string that identifies the resource */ public NotificationFetcher(final String pathSid) { this.pathSid = pathSid; } /** * Construct a new NotificationFetcher. * * @param pathAccountSid The SID of the Account that created the resource to * fetch * @param pathSid The unique string that identifies the resource */ public NotificationFetcher(final String pathAccountSid, final String pathSid) { this.pathAccountSid = pathAccountSid; this.pathSid = pathSid; } /** * Make the request to the Twilio API to perform the fetch. * * @param client TwilioRestClient with which to make the request * @return Fetched Notification */ @Override @SuppressWarnings("checkstyle:linelength") public Notification fetch(final TwilioRestClient client) { this.pathAccountSid = this.pathAccountSid == null ? client.getAccountSid() : this.pathAccountSid; Request request = new Request( HttpMethod.GET, Domains.API.toString(), "/2010-04-01/Accounts/" + this.pathAccountSid + "/Notifications/" + this.pathSid + ".json" ); Response response = client.request(request); if (response == null) { throw new ApiConnectionException("Notification fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); if (restException == null) { throw new ApiException("Server Error, no content"); } throw new ApiException(restException); } return Notification.fromJson(response.getStream(), client.getObjectMapper()); } }
{ "pile_set_name": "Github" }
package com.google.gwt.maps.client.events.position; /* * #%L * GWT Maps API V3 - Core API * %% * Copyright (C) 2011 - 2012 GWT Maps API V3 * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.google.gwt.ajaxloader.client.Properties; import com.google.gwt.maps.client.events.MapEvent; public class PositionChangeMapEvent extends MapEvent<PositionChangeMapHandler, PositionChangeMapEvent> { public static Type<PositionChangeMapHandler> TYPE = new Type<PositionChangeMapHandler>(); public PositionChangeMapEvent(Properties properties) { super(properties); } @Override public com.google.gwt.event.shared.GwtEvent.Type<PositionChangeMapHandler> getAssociatedType() { return TYPE; } @Override protected void dispatch(PositionChangeMapHandler handler) { handler.onEvent(this); } }
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0+ /* * Copyright (C) 2015-2019 Stefan Roese <sr@denx.de> */ #include <common.h> #include <console.h> #include <i2c.h> #include <init.h> #include <pci.h> #if !defined(CONFIG_SPL_BUILD) #include <bootcount.h> #endif #include <asm/gpio.h> #include <asm/io.h> #include <asm/arch/cpu.h> #include <asm/arch/soc.h> #include <linux/mbus.h> #ifdef CONFIG_NET #include <netdev.h> #endif #include <u-boot/crc.h> #include "theadorable.h" #include "../drivers/ddr/marvell/axp/ddr3_hw_training.h" #include "../arch/arm/mach-mvebu/serdes/axp/high_speed_env_spec.h" DECLARE_GLOBAL_DATA_PTR; #define MV_USB_PHY_BASE (MVEBU_AXP_USB_BASE + 0x800) #define PHY_CHANNEL_RX_CTRL0_REG(port, chan) \ (MV_USB_PHY_BASE + ((port) << 12) + ((chan) << 6) + 0x8) #define THEADORABLE_GPP_OUT_ENA_LOW 0x00336780 #define THEADORABLE_GPP_OUT_ENA_MID 0x00003cf0 #define THEADORABLE_GPP_OUT_ENA_HIGH (~(0x0)) #define THEADORABLE_GPP_OUT_VAL_LOW 0x2c0c983f #define THEADORABLE_GPP_OUT_VAL_MID 0x0007000c #define THEADORABLE_GPP_OUT_VAL_HIGH 0x00000000 #define GPIO_USB0_PWR_ON 18 #define GPIO_USB1_PWR_ON 19 #define PEX_SWITCH_NOT_FOUNT_LIMIT 3 #define STM_I2C_BUS 1 #define STM_I2C_ADDR 0x27 #define REBOOT_DELAY 1000 /* reboot-delay in ms */ #define ABORT_TIMEOUT 3000 /* 3 seconds reboot abort timeout */ /* DDR3 static configuration */ static MV_DRAM_MC_INIT ddr3_theadorable[MV_MAX_DDR3_STATIC_SIZE] = { {0x00001400, 0x7301ca28}, /* DDR SDRAM Configuration Register */ {0x00001404, 0x30000800}, /* Dunit Control Low Register */ {0x00001408, 0x44149887}, /* DDR SDRAM Timing (Low) Register */ {0x0000140C, 0x38d93fc7}, /* DDR SDRAM Timing (High) Register */ {0x00001410, 0x1b100001}, /* DDR SDRAM Address Control Register */ {0x00001424, 0x0000f3ff}, /* Dunit Control High Register */ {0x00001428, 0x000f8830}, /* ODT Timing (Low) Register */ {0x0000142C, 0x014c50f4}, /* DDR3 Timing Register */ {0x0000147C, 0x0000c671}, /* ODT Timing (High) Register */ {0x00001494, 0x00010000}, /* DDR SDRAM ODT Control (Low) Reg */ {0x0000149C, 0x00000001}, /* DDR Dunit ODT Control Register */ {0x000014A0, 0x00000001}, /* DRAM FIFO Control Register */ {0x000014A8, 0x00000101}, /* AXI Control Register */ /* * DO NOT Modify - Open Mbus Window - 2G - Mbus is required for the * training sequence */ {0x000200e8, 0x3fff0e01}, {0x00020184, 0x3fffffe0}, /* Close fast path Window to - 2G */ {0x0001504, 0x7fffffe1}, /* CS0 Size */ {0x000150C, 0x00000000}, /* CS1 Size */ {0x0001514, 0x00000000}, /* CS2 Size */ {0x000151C, 0x00000000}, /* CS3 Size */ {0x00020220, 0x00000007}, /* Reserved */ {0x00001538, 0x00000009}, /* Read Data Sample Delays Register */ {0x0000153C, 0x00000009}, /* Read Data Ready Delay Register */ {0x000015D0, 0x00000650}, /* MR0 */ {0x000015D4, 0x00000044}, /* MR1 */ {0x000015D8, 0x00000010}, /* MR2 */ {0x000015DC, 0x00000000}, /* MR3 */ {0x000015E0, 0x00000001}, {0x000015E4, 0x00203c18}, /* ZQDS Configuration Register */ {0x000015EC, 0xf800a225}, /* DDR PHY */ /* Recommended Settings from Marvell for 4 x 16 bit devices: */ {0x000014C0, 0x192424c9}, /* DRAM addr and Ctrl Driving Strenght*/ {0x000014C4, 0x0aaa24c9}, /* DRAM Data and DQS Driving Strenght */ {0x0, 0x0} }; static MV_DRAM_MODES board_ddr_modes[MV_DDR3_MODES_NUMBER] = { {"theadorable_1333-667", 0x3, 0x5, 0x0, A0, ddr3_theadorable, NULL}, }; extern MV_SERDES_CHANGE_M_PHY serdes_change_m_phy[]; /* * Lane0 - PCIE0.0 X1 (to WIFI Module) * Lane5 - SATA0 * Lane6 - SATA1 * Lane7 - SGMII0 (to Ethernet Phy) * Lane8-11 - PCIE2.0 X4 (to PEX Switch) * all other lanes are disabled */ MV_BIN_SERDES_CFG theadorable_serdes_cfg[] = { { MV_PEX_ROOT_COMPLEX, 0x22200001, 0x00001111, { PEX_BUS_MODE_X1, PEX_BUS_DISABLED, PEX_BUS_MODE_X4, PEX_BUS_DISABLED }, 0x0060, serdes_change_m_phy }, }; /* * Define a board-specific detection pulse-width array for the SerDes PCIe * interfaces. If not defined in the board code, the default of currently 2 * is used. Values from 0...3 are possible (2 bits). */ u8 serdes_pex_pulse_width[4] = { 0, 2, 2, 2 }; MV_DRAM_MODES *ddr3_get_static_ddr_mode(void) { /* Only one mode supported for this board */ return &board_ddr_modes[0]; } MV_BIN_SERDES_CFG *board_serdes_cfg_get(void) { return &theadorable_serdes_cfg[0]; } u8 board_sat_r_get(u8 dev_num, u8 reg) { /* Bit x enables PCI 2.0 link capabilities instead of PCI 1.x */ return 0xe; /* PEX port 0 is PCIe Gen1, PEX port 1..3 PCIe Gen2 */ } int board_early_init_f(void) { /* Configure MPP */ writel(0x00000000, MVEBU_MPP_BASE + 0x00); writel(0x03300000, MVEBU_MPP_BASE + 0x04); writel(0x00000033, MVEBU_MPP_BASE + 0x08); writel(0x00000000, MVEBU_MPP_BASE + 0x0c); writel(0x11110000, MVEBU_MPP_BASE + 0x10); writel(0x00221100, MVEBU_MPP_BASE + 0x14); writel(0x00000000, MVEBU_MPP_BASE + 0x18); writel(0x00000000, MVEBU_MPP_BASE + 0x1c); writel(0x00000000, MVEBU_MPP_BASE + 0x20); /* Configure GPIO */ writel(THEADORABLE_GPP_OUT_VAL_LOW, MVEBU_GPIO0_BASE + 0x00); writel(THEADORABLE_GPP_OUT_ENA_LOW, MVEBU_GPIO0_BASE + 0x04); writel(THEADORABLE_GPP_OUT_VAL_MID, MVEBU_GPIO1_BASE + 0x00); writel(THEADORABLE_GPP_OUT_ENA_MID, MVEBU_GPIO1_BASE + 0x04); writel(THEADORABLE_GPP_OUT_VAL_HIGH, MVEBU_GPIO2_BASE + 0x00); writel(THEADORABLE_GPP_OUT_ENA_HIGH, MVEBU_GPIO2_BASE + 0x04); return 0; } int board_init(void) { int ret; /* adress of boot parameters */ gd->bd->bi_boot_params = mvebu_sdram_bar(0) + 0x100; /* * Map SPI devices via MBUS so that they can be accessed via * the SPI direct access mode */ mbus_dt_setup_win(&mbus_state, SPI_BUS0_DEV1_BASE, SPI_BUS0_DEV1_SIZE, CPU_TARGET_DEVICEBUS_BOOTROM_SPI, CPU_ATTR_SPI0_CS1); mbus_dt_setup_win(&mbus_state, SPI_BUS1_DEV2_BASE, SPI_BUS0_DEV1_SIZE, CPU_TARGET_DEVICEBUS_BOOTROM_SPI, CPU_ATTR_SPI1_CS2); /* * Set RX Channel Control 0 Register: * Tests have shown, that setting the LPF_COEF from 0 (1/8) * to 3 (1/1) results in a more stable USB connection. */ setbits_le32(PHY_CHANNEL_RX_CTRL0_REG(0, 1), 0xc); setbits_le32(PHY_CHANNEL_RX_CTRL0_REG(0, 2), 0xc); setbits_le32(PHY_CHANNEL_RX_CTRL0_REG(0, 3), 0xc); /* Toggle USB power */ ret = gpio_request(GPIO_USB0_PWR_ON, "USB0_PWR_ON"); if (ret < 0) return ret; gpio_direction_output(GPIO_USB0_PWR_ON, 0); ret = gpio_request(GPIO_USB1_PWR_ON, "USB1_PWR_ON"); if (ret < 0) return ret; gpio_direction_output(GPIO_USB1_PWR_ON, 0); mdelay(1); gpio_set_value(GPIO_USB0_PWR_ON, 1); gpio_set_value(GPIO_USB1_PWR_ON, 1); return 0; } int checkboard(void) { board_fpga_add(); return 0; } #ifdef CONFIG_NET int board_eth_init(bd_t *bis) { cpu_eth_init(bis); /* Built in controller(s) come first */ return pci_eth_init(bis); } #endif #if !defined(CONFIG_SPL_BUILD) && defined(CONFIG_BOARD_LATE_INIT) int board_late_init(void) { pci_dev_t bdf; ulong bootcount; /* * Check if the PEX switch is detected (somtimes its not available * on the PCIe bus). In this case, try to recover by issuing a * soft-reset or even a power-cycle, depending on the bootcounter * value. */ bdf = pci_find_device(PCI_VENDOR_ID_PLX, 0x8619, 0); if (bdf == -1) { unsigned long start_time = get_timer(0); u8 i2c_buf[8]; int ret; /* PEX switch not found! */ bootcount = bootcount_load(); printf("Failed to find PLX PEX-switch (bootcount=%ld)\n", bootcount); /* * The user can exit this boot-loop in the error case by * hitting Ctrl-C. So wait some time for this key here. */ printf("Continue booting with Ctrl-C, otherwise rebooting\n"); do { /* Handle control-c and timeouts */ if (ctrlc()) { printf("PEX error boot-loop aborted!\n"); return 0; } } while (get_timer(start_time) < ABORT_TIMEOUT); /* * At this stage the bootcounter has not been incremented * yet. We need to do this manually here to get an actually * working bootcounter in this error case. */ bootcount_inc(); if (bootcount > PEX_SWITCH_NOT_FOUNT_LIMIT) { printf("Issuing power-switch via uC!\n"); printf("Issuing power-switch via uC!\n"); i2c_set_bus_num(STM_I2C_BUS); i2c_buf[0] = STM_I2C_ADDR << 1; i2c_buf[1] = 0xc5; /* cmd */ i2c_buf[2] = 0x01; /* enable */ /* Delay before reboot */ i2c_buf[3] = REBOOT_DELAY & 0x00ff; i2c_buf[4] = (REBOOT_DELAY & 0xff00) >> 8; /* Delay before shutdown */ i2c_buf[5] = 0x00; i2c_buf[6] = 0x00; i2c_buf[7] = crc8(0x72, &i2c_buf[0], 7); ret = i2c_write(STM_I2C_ADDR, 0, 0, &i2c_buf[1], 7); if (ret) { printf("I2C write error (ret=%d)\n", ret); printf("Issuing soft-reset...\n"); /* default handling: SOFT reset */ do_reset(NULL, 0, 0, NULL); } /* Wait for power-cycle to occur... */ printf("Waiting for power-cycle via uC...\n"); while (1) ; } else { printf("Issuing soft-reset...\n"); /* default handling: SOFT reset */ do_reset(NULL, 0, 0, NULL); } } return 0; } #endif #if !defined(CONFIG_SPL_BUILD) && defined(CONFIG_PCI) int do_pcie_test(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) { pci_dev_t bdf; u16 ven_id, dev_id; if (argc != 3) return cmd_usage(cmdtp); ven_id = simple_strtoul(argv[1], NULL, 16); dev_id = simple_strtoul(argv[2], NULL, 16); printf("Checking for PCIe device: VendorID 0x%04x, DeviceId 0x%04x\n", ven_id, dev_id); /* * Check if the PCIe device is detected (somtimes its not available * on the PCIe bus) */ bdf = pci_find_device(ven_id, dev_id, 0); if (bdf == -1) { /* PCIe device not found! */ printf("Failed to find PCIe device\n"); } else { /* PCIe device found! */ printf("PCIe device found, resetting board...\n"); /* default handling: SOFT reset */ do_reset(NULL, 0, 0, NULL); } return 0; } U_BOOT_CMD( pcie, 3, 0, do_pcie_test, "Test for presence of a PCIe device", "<VendorID> <DeviceID>" ); #endif
{ "pile_set_name": "Github" }
// *************************************************************************** // * // * Copyright (C) 2010 International Business Machines // * Corporation and others. All Rights Reserved. // * Tool: com.ibm.icu.dev.tool.cldr.LDML2ICUConverter.java // * Source File:<path>/common/main/az.xml // * // *************************************************************************** /** * ICU <specials> source: <path>/xml/main/az.xml */ az{ AuxExemplarCharacters{"[w]"} ExemplarCharacters{"[a b c ç d e ə f g ğ h x ı i {i\u0307} j k q l m n o ö p r s ş t u ü v y z]"} ExemplarCharactersIndex{"[A B C Ç D E Ə F G Ğ H X I İ J K Q L M N O Ö P R S Ş T U Ü V W Y Z]"} LocaleScript{ "Latn", } NumberElements{ latn{ patterns{ currencyFormat{"¤ #,##0.00"} } symbols{ decimal{","} exponential{"E"} group{"."} infinity{"∞"} list{";"} minusSign{"-"} nan{"NaN"} perMille{"‰"} percentSign{"%"} plusSign{"+"} } } } Version{"2.0.47.53"} calendar{ gregorian{ DateTimePatterns{ "HH:mm:ss zzzz", "HH:mm:ss z", "HH:mm:ss", "HH:mm", "EEEE, d, MMMM, y", "d MMMM , y", "d MMM, y", "yyyy-MM-dd", "{1} {0}", "{1} {0}", "{1} {0}", "{1} {0}", "{1} {0}", } dayNames{ format{ abbreviated{ "B.", "B.E.", "Ç.A.", "Ç.", "C.A.", "C", "Ş.", } wide{ "bazar", "bazar ertəsi", "çərşənbə axşamı", "çərşənbə", "cümə axşamı", "cümə", "şənbə", } } stand-alone{ narrow{ "7", "1", "2", "3", "4", "5", "6", } } } eras{ abbreviated{ "e.ə.", "b.e.", } wide{ "eramızdan əvvəl", "bizim eramızın", } } fields{ day{ dn{"bu gün"} relative{ "-1"{"dünən"} "-3"{"üç gün əvvəl"} "0"{"bu gün"} "1"{"sabah"} "3"{"üç gün sonra"} } } era{ dn{"era"} } hour{ dn{"saat"} } minute{ dn{"dəqiqə"} } month{ dn{"ay"} } second{ dn{"saniyə"} } week{ dn{"həftə"} } weekday{ dn{"həftə günü"} } year{ dn{"il"} } zone{ dn{"zona"} } } monthNames{ format{ abbreviated{ "yan", "fev", "mar", "apr", "may", "iyn", "iyl", "avq", "sen", "okt", "noy", "dek", } wide{ "Yanvar", "Fevral", "Mart", "Aprel", "May", "İyun", "İyul", "Avqust", "Sentyabr", "Oktyabr", "Noyabr", "Dekabr", } } } quarters{ format{ abbreviated{ "1-ci kv.", "2-ci kv.", "3-cü kv.", "4-cü kv.", } wide{ "1-ci kvartal", "2-ci kvartal", "3-cü kvartal", "4-cü kvartal", } } } } } delimiters{ alternateQuotationEnd{"’"} alternateQuotationStart{"‘"} quotationEnd{"”"} quotationStart{"“"} } measurementSystemNames{ US{"ABŞ"} metric{"metr"} } units{ day{ other{"{0} gün"} } hour{ other{"{0} saat"} } minute{ other{"{0} dəqiqə"} } month{ other{"{0} ay"} } second{ other{"{0} saniyə"} } week{ other{"{0} həftə"} } year{ other{"{0} il"} } } }
{ "pile_set_name": "Github" }
<?php /* * This file is part of SwiftMailer. * (c) 2018 Christian Schmidt * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * An IDN email address encoder. * * Encodes the domain part of an address using IDN. This is compatible will all * SMTP servers. * * This encoder does not support email addresses with non-ASCII characters in * local-part (the substring before @). To send to such addresses, use * Swift_AddressEncoder_Utf8AddressEncoder together with * Swift_Transport_Esmtp_SmtpUtf8Handler. Your outbound SMTP server must support * the SMTPUTF8 extension. * * @author Christian Schmidt */ class Swift_AddressEncoder_IdnAddressEncoder implements Swift_AddressEncoder { /** * Encodes the domain part of an address using IDN. * * @throws Swift_AddressEncoderException If local-part contains non-ASCII characters */ public function encodeString(string $address): string { $i = strrpos($address, '@'); if (false !== $i) { $local = substr($address, 0, $i); $domain = substr($address, $i + 1); if (preg_match('/[^\x00-\x7F]/', $local)) { throw new Swift_AddressEncoderException('Non-ASCII characters not supported in local-part', $address); } if (preg_match('/[^\x00-\x7F]/', $domain)) { $address = sprintf('%s@%s', $local, idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46)); } } return $address; } }
{ "pile_set_name": "Github" }
<?php /** * This file is part of the Propel package. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @license MIT License */ /** * Simple class that serves as a container for any information about a failed validation. * * Currently this class stores the qualified column name (e.g. tablename.COLUMN_NAME) and * the message that should be displayed to the user. * * An array of these objects will be returned by BasePeer::doValidate() if validation * failed. * * @author Hans Lellelid <hans@xmpl.org> * @version $Revision$ * @package propel.runtime.validator * @see BasePeer::doValidate() */ class ValidationFailed { /** Column name in tablename.COLUMN_NAME format */ private $colname; /** Message to display to user. */ private $message; /** Validator object that caused this to fail. */ private $validator; /** * Construct a new ValidationFailed object. * * @param string $colname Column name. * @param string $message Message to display to user. * @param object $validator The Validator that caused this column to fail. */ public function __construct($colname, $message, $validator = null) { $this->colname = $colname; $this->message = $message; $this->validator = $validator; } /** * Set the column name. * * @param string $v */ public function setColumn($v) { $this->colname = $v; } /** * Gets the column name. * * @return string Qualified column name (tablename.COLUMN_NAME) */ public function getColumn() { return $this->colname; } /** * Set the message for the validation failure. * * @param string $v */ public function setMessage($v) { $this->message = $v; } /** * Gets the message for the validation failure. * * @return string */ public function getMessage() { return $this->message; } /** * Set the validator object that caused this to fail. * * @param object $v */ public function setValidator($v) { $this->validator = $v; } /** * Gets the validator object that caused this to fail. * * @return object */ public function getValidator() { return $this->validator; } /** * "magic" method to get string represenation of object. * Maybe someday PHP5 will support the invoking this method automatically * on (string) cast. Until then it's pretty useless. * * @return string */ public function __toString() { return $this->getMessage(); } }
{ "pile_set_name": "Github" }
/* * e-mail-send-account-override.c * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. * * * Copyright (C) 2013 Red Hat, Inc. (www.redhat.com) * */ #include "evolution-config.h" #include <string.h> #include <libedataserver/libedataserver.h> #include "e-mail-send-account-override.h" #define E_MAIL_SEND_ACCOUNT_OVERRIDE_GET_PRIVATE(obj) \ (G_TYPE_INSTANCE_GET_PRIVATE \ ((obj), E_TYPE_MAIL_SEND_ACCOUNT_OVERRIDE, EMailSendAccountOverridePrivate)) #define FOLDERS_SECTION "Folders" #define FOLDERS_ALIAS_NAME_SECTION "Folders-Alias-Name" #define FOLDERS_ALIAS_ADDRESS_SECTION "Folders-Alias-Address" #define RECIPIENTS_SECTION "Recipients" #define RECIPIENTS_ALIAS_NAME_SECTION "Recipients-Alias-Name" #define RECIPIENTS_ALIAS_ADDRESS_SECTION "Recipients-Alias-Address" #define OPTIONS_SECTION "Options" #define OPTION_PREFER_FOLDER "PreferFolder" struct _EMailSendAccountOverridePrivate { GKeyFile *key_file; gchar *config_filename; gboolean prefer_folder; gboolean need_save; guint save_frozen; GMutex property_lock; }; enum { PROP_0, PROP_PREFER_FOLDER }; enum { CHANGED, LAST_SIGNAL }; static guint signals[LAST_SIGNAL]; G_DEFINE_TYPE ( EMailSendAccountOverride, e_mail_send_account_override, G_TYPE_OBJECT) static gboolean e_mail_send_account_override_save_locked (EMailSendAccountOverride *override) { gchar *contents; GError *error = NULL; g_return_val_if_fail (override->priv->key_file != NULL, FALSE); override->priv->need_save = FALSE; if (override->priv->config_filename == NULL) return FALSE; contents = g_key_file_to_data (override->priv->key_file, NULL, NULL); if (contents == NULL) return FALSE; g_file_set_contents ( override->priv->config_filename, contents, -1, &error); if (error != NULL) { g_warning ("%s: %s", G_STRFUNC, error->message); g_clear_error (&error); } g_free (contents); return TRUE; } static gboolean e_mail_send_account_override_maybe_save_locked (EMailSendAccountOverride *override) { if (override->priv->save_frozen > 0) { override->priv->need_save = TRUE; return FALSE; } return e_mail_send_account_override_save_locked (override); } static void read_alias_info_locked (EMailSendAccountOverride *override, const gchar *alias_name_section, const gchar *alias_address_section, const gchar *key, gchar **out_alias_name, gchar **out_alias_address) { if (out_alias_name) { gchar *alias_name; alias_name = g_key_file_get_string ( override->priv->key_file, alias_name_section, key, NULL); if (alias_name) g_strchomp (alias_name); if (alias_name && !*alias_name) { g_free (alias_name); alias_name = NULL; } *out_alias_name = alias_name; } if (out_alias_address) { gchar *alias_address; alias_address = g_key_file_get_string ( override->priv->key_file, alias_address_section, key, NULL); if (alias_address) g_strchomp (alias_address); if (alias_address && !*alias_address) { g_free (alias_address); alias_address = NULL; } *out_alias_address = alias_address; } } static void write_alias_info_locked (EMailSendAccountOverride *override, const gchar *alias_name_section, const gchar *alias_address_section, const gchar *key, const gchar *alias_name, const gchar *alias_address) { if (alias_name && *alias_name) { g_key_file_set_string (override->priv->key_file, alias_name_section, key, alias_name); } else { g_key_file_remove_key (override->priv->key_file, alias_name_section, key, NULL); } if (alias_address && *alias_address) { g_key_file_set_string (override->priv->key_file, alias_address_section, key, alias_address); } else { g_key_file_remove_key (override->priv->key_file, alias_address_section, key, NULL); } } static gchar * get_override_for_folder_uri_locked (EMailSendAccountOverride *override, const gchar *folder_uri, gchar **out_alias_name, gchar **out_alias_address) { gchar *account_uid; if (folder_uri == NULL || *folder_uri == '\0') return NULL; account_uid = g_key_file_get_string ( override->priv->key_file, FOLDERS_SECTION, folder_uri, NULL); if (account_uid != NULL) g_strchomp (account_uid); if (account_uid != NULL && *account_uid == '\0') { g_free (account_uid); account_uid = NULL; } if (account_uid) { read_alias_info_locked (override, FOLDERS_ALIAS_NAME_SECTION, FOLDERS_ALIAS_ADDRESS_SECTION, folder_uri, out_alias_name, out_alias_address); } return account_uid; } static gchar * test_one_recipient (gchar **keys, GPtrArray *values, const gchar *name, const gchar *address, gint *out_keys_index) { gint ii; g_return_val_if_fail (keys != NULL, NULL); g_return_val_if_fail (values != NULL, NULL); g_return_val_if_fail (out_keys_index != NULL, NULL); if (name != NULL && *name == '\0') name = NULL; if (address != NULL && *address == '\0') address = NULL; if (name == NULL && address == NULL) return NULL; for (ii = 0; keys[ii] && ii < values->len; ii++) { if (name != NULL && e_util_utf8_strstrcase (name, keys[ii]) != NULL) { *out_keys_index = ii; return g_strdup (values->pdata[ii]); } if (address != NULL && e_util_utf8_strstrcase (address, keys[ii]) != NULL) { *out_keys_index = ii; return g_strdup (values->pdata[ii]); } } return NULL; } static gchar * get_override_for_recipients_locked (EMailSendAccountOverride *override, CamelAddress *recipients, gchar **out_alias_name, gchar **out_alias_address) { CamelInternetAddress *iaddress; gchar *account_uid = NULL; GPtrArray *values; gchar **keys; gint ii, len; if (!CAMEL_IS_INTERNET_ADDRESS (recipients)) return NULL; keys = g_key_file_get_keys ( override->priv->key_file, RECIPIENTS_SECTION, NULL, NULL); if (keys == NULL) return NULL; values = g_ptr_array_new_full (g_strv_length (keys), g_free); for (ii = 0; keys[ii]; ii++) { g_ptr_array_add ( values, g_key_file_get_string ( override->priv->key_file, RECIPIENTS_SECTION, keys[ii], NULL)); } iaddress = CAMEL_INTERNET_ADDRESS (recipients); len = camel_address_length (recipients); for (ii = 0; ii < len; ii++) { const gchar *name, *address; if (camel_internet_address_get (iaddress, ii, &name, &address)) { gint keys_index = -1; account_uid = test_one_recipient (keys, values, name, address, &keys_index); if (account_uid != NULL) g_strchomp (account_uid); if (account_uid != NULL && *account_uid == '\0') { g_free (account_uid); account_uid = NULL; } if (account_uid != NULL) { g_warn_if_fail (keys_index >= 0 && keys_index < g_strv_length (keys)); read_alias_info_locked (override, RECIPIENTS_ALIAS_NAME_SECTION, RECIPIENTS_ALIAS_ADDRESS_SECTION, keys[keys_index], out_alias_name, out_alias_address); break; } } } g_ptr_array_free (values, TRUE); g_strfreev (keys); return account_uid; } static void list_overrides_section_for_account_locked (EMailSendAccountOverride *override, const gchar *account_uid, const gchar *alias_name, const gchar *alias_address, const gchar *section, const gchar *alias_name_section, const gchar *alias_address_section, GList **overrides) { gchar **keys; g_return_if_fail (account_uid != NULL); g_return_if_fail (section != NULL); if (overrides == NULL) return; *overrides = NULL; keys = g_key_file_get_keys ( override->priv->key_file, section, NULL, NULL); if (keys != NULL) { gint ii; for (ii = 0; keys[ii]; ii++) { const gchar *key = keys[ii]; gchar *value; value = g_key_file_get_string ( override->priv->key_file, section, key, NULL); if (g_strcmp0 (value, account_uid) == 0) { gchar *stored_alias_name = NULL, *stored_alias_address = NULL; read_alias_info_locked (override, alias_name_section, alias_address_section, key, &stored_alias_name, &stored_alias_address); if (g_strcmp0 (stored_alias_name, alias_name) == 0 && g_strcmp0 (stored_alias_address, alias_address) == 0) { *overrides = g_list_prepend (*overrides, g_strdup (key)); } g_free (stored_alias_name); g_free (stored_alias_address); } g_free (value); } } g_strfreev (keys); *overrides = g_list_reverse (*overrides); } static void list_overrides_for_account_locked (EMailSendAccountOverride *override, const gchar *account_uid, const gchar *alias_name, const gchar *alias_address, GList **folder_overrides, GList **recipient_overrides) { if (account_uid == NULL) return; list_overrides_section_for_account_locked ( override, account_uid, alias_name, alias_address, FOLDERS_SECTION, FOLDERS_ALIAS_NAME_SECTION, FOLDERS_ALIAS_ADDRESS_SECTION, folder_overrides); list_overrides_section_for_account_locked ( override, account_uid, alias_name, alias_address, RECIPIENTS_SECTION, RECIPIENTS_ALIAS_NAME_SECTION, RECIPIENTS_ALIAS_ADDRESS_SECTION, recipient_overrides); } static void mail_send_account_override_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { switch (property_id) { case PROP_PREFER_FOLDER: e_mail_send_account_override_set_prefer_folder ( E_MAIL_SEND_ACCOUNT_OVERRIDE (object), g_value_get_boolean (value)); return; } G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } static void mail_send_account_override_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { switch (property_id) { case PROP_PREFER_FOLDER: g_value_set_boolean ( value, e_mail_send_account_override_get_prefer_folder ( E_MAIL_SEND_ACCOUNT_OVERRIDE (object))); return; } G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } static void mail_send_account_override_finalize (GObject *object) { EMailSendAccountOverridePrivate *priv; priv = E_MAIL_SEND_ACCOUNT_OVERRIDE_GET_PRIVATE (object); g_key_file_free (priv->key_file); g_free (priv->config_filename); g_mutex_clear (&priv->property_lock); /* Chain up to parent's finalize() method. */ G_OBJECT_CLASS (e_mail_send_account_override_parent_class)-> finalize (object); } static void e_mail_send_account_override_class_init (EMailSendAccountOverrideClass *class) { GObjectClass *object_class; g_type_class_add_private ( class, sizeof (EMailSendAccountOverridePrivate)); object_class = G_OBJECT_CLASS (class); object_class->set_property = mail_send_account_override_set_property; object_class->get_property = mail_send_account_override_get_property; object_class->finalize = mail_send_account_override_finalize; g_object_class_install_property ( object_class, PROP_PREFER_FOLDER, g_param_spec_boolean ( "prefer-folder", "Prefer Folder", NULL, TRUE, G_PARAM_READWRITE)); signals[CHANGED] = g_signal_new ( "changed", G_OBJECT_CLASS_TYPE (object_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET (EMailSendAccountOverrideClass, changed), NULL, NULL, NULL, G_TYPE_NONE, 0); } static void e_mail_send_account_override_init (EMailSendAccountOverride *override) { override->priv = E_MAIL_SEND_ACCOUNT_OVERRIDE_GET_PRIVATE (override); g_mutex_init (&override->priv->property_lock); override->priv->key_file = g_key_file_new (); override->priv->prefer_folder = TRUE; } EMailSendAccountOverride * e_mail_send_account_override_new (const gchar *config_filename) { EMailSendAccountOverride *override; override = g_object_new (E_TYPE_MAIL_SEND_ACCOUNT_OVERRIDE, NULL); if (config_filename != NULL) e_mail_send_account_override_set_config_filename ( override, config_filename); return override; } void e_mail_send_account_override_set_config_filename (EMailSendAccountOverride *override, const gchar *config_filename) { GError *error = NULL; gboolean old_prefer_folder, prefer_folder_changed; g_return_if_fail (E_IS_MAIL_SEND_ACCOUNT_OVERRIDE (override)); g_return_if_fail (config_filename != NULL); g_return_if_fail (*config_filename != '\0'); g_mutex_lock (&override->priv->property_lock); if (g_strcmp0 (config_filename, override->priv->config_filename) == 0) { g_mutex_unlock (&override->priv->property_lock); return; } g_free (override->priv->config_filename); override->priv->config_filename = g_strdup (config_filename); g_key_file_load_from_file ( override->priv->key_file, override->priv->config_filename, G_KEY_FILE_NONE, NULL); old_prefer_folder = override->priv->prefer_folder; override->priv->prefer_folder = g_key_file_get_boolean ( override->priv->key_file, OPTIONS_SECTION, OPTION_PREFER_FOLDER, &error); if (error != NULL) { /* default value is to prefer the folder override over the recipients */ override->priv->prefer_folder = TRUE; g_clear_error (&error); } prefer_folder_changed = (override->priv->prefer_folder != old_prefer_folder); g_mutex_unlock (&override->priv->property_lock); if (prefer_folder_changed) g_object_notify (G_OBJECT (override), "prefer-folder"); } gchar * e_mail_send_account_override_dup_config_filename (EMailSendAccountOverride *override) { gchar *config_filename; g_return_val_if_fail (E_IS_MAIL_SEND_ACCOUNT_OVERRIDE (override), NULL); g_mutex_lock (&override->priv->property_lock); config_filename = g_strdup (override->priv->config_filename); g_mutex_unlock (&override->priv->property_lock); return config_filename; } void e_mail_send_account_override_set_prefer_folder (EMailSendAccountOverride *override, gboolean prefer_folder) { gboolean changed, saved = FALSE; g_return_if_fail (E_IS_MAIL_SEND_ACCOUNT_OVERRIDE (override)); g_mutex_lock (&override->priv->property_lock); changed = (prefer_folder != override->priv->prefer_folder); if (changed) { override->priv->prefer_folder = prefer_folder; g_key_file_set_boolean ( override->priv->key_file, OPTIONS_SECTION, OPTION_PREFER_FOLDER, prefer_folder); saved = e_mail_send_account_override_maybe_save_locked (override); } g_mutex_unlock (&override->priv->property_lock); if (changed) g_object_notify (G_OBJECT (override), "prefer-folder"); if (saved) g_signal_emit (override, signals[CHANGED], 0); } gboolean e_mail_send_account_override_get_prefer_folder (EMailSendAccountOverride *override) { g_return_val_if_fail (E_IS_MAIL_SEND_ACCOUNT_OVERRIDE (override), FALSE); return override->priv->prefer_folder; } /* free returned pointers with g_free() */ gchar * e_mail_send_account_override_get_account_uid (EMailSendAccountOverride *override, const gchar *folder_uri, CamelInternetAddress *recipients_to, CamelInternetAddress *recipients_cc, CamelInternetAddress *recipients_bcc, gchar **out_alias_name, gchar **out_alias_address) { gchar *account_uid = NULL; g_return_val_if_fail (E_IS_MAIL_SEND_ACCOUNT_OVERRIDE (override), NULL); g_return_val_if_fail (override->priv->config_filename != NULL, NULL); g_mutex_lock (&override->priv->property_lock); if (override->priv->prefer_folder) account_uid = get_override_for_folder_uri_locked ( override, folder_uri, out_alias_name, out_alias_address); if (account_uid == NULL) account_uid = get_override_for_recipients_locked ( override, CAMEL_ADDRESS (recipients_to), out_alias_name, out_alias_address); if (account_uid == NULL) account_uid = get_override_for_recipients_locked ( override, CAMEL_ADDRESS (recipients_cc), out_alias_name, out_alias_address); if (account_uid == NULL) account_uid = get_override_for_recipients_locked ( override, CAMEL_ADDRESS (recipients_bcc), out_alias_name, out_alias_address); if (account_uid == NULL && !override->priv->prefer_folder) account_uid = get_override_for_folder_uri_locked ( override, folder_uri, out_alias_name, out_alias_address); g_mutex_unlock (&override->priv->property_lock); return account_uid; } void e_mail_send_account_override_remove_for_account_uid (EMailSendAccountOverride *override, const gchar *account_uid, const gchar *alias_name, const gchar *alias_address) { GList *folders = NULL, *recipients = NULL; gboolean saved = FALSE; g_return_if_fail (E_IS_MAIL_SEND_ACCOUNT_OVERRIDE (override)); g_return_if_fail (account_uid != NULL); g_mutex_lock (&override->priv->property_lock); list_overrides_for_account_locked ( override, account_uid, alias_name, alias_address, &folders, &recipients); if (folders != NULL || recipients != NULL) { GList *link; for (link = folders; link != NULL; link = g_list_next (link)) { const gchar *key = link->data; g_key_file_remove_key ( override->priv->key_file, FOLDERS_SECTION, key, NULL); write_alias_info_locked (override, FOLDERS_ALIAS_NAME_SECTION, FOLDERS_ALIAS_ADDRESS_SECTION, key, NULL, NULL); } for (link = recipients; link != NULL; link = g_list_next (link)) { const gchar *key = link->data; g_key_file_remove_key ( override->priv->key_file, RECIPIENTS_SECTION, key, NULL); write_alias_info_locked (override, RECIPIENTS_ALIAS_NAME_SECTION, RECIPIENTS_ALIAS_ADDRESS_SECTION, key, NULL, NULL); } saved = e_mail_send_account_override_maybe_save_locked (override); } g_list_free_full (folders, g_free); g_list_free_full (recipients, g_free); g_mutex_unlock (&override->priv->property_lock); if (saved) g_signal_emit (override, signals[CHANGED], 0); } gchar * e_mail_send_account_override_get_for_folder (EMailSendAccountOverride *override, const gchar *folder_uri, gchar **out_alias_name, gchar **out_alias_address) { gchar *account_uid = NULL; g_return_val_if_fail (E_IS_MAIL_SEND_ACCOUNT_OVERRIDE (override), NULL); g_mutex_lock (&override->priv->property_lock); account_uid = get_override_for_folder_uri_locked (override, folder_uri, out_alias_name, out_alias_address); g_mutex_unlock (&override->priv->property_lock); return account_uid; } void e_mail_send_account_override_set_for_folder (EMailSendAccountOverride *override, const gchar *folder_uri, const gchar *account_uid, const gchar *alias_name, const gchar *alias_address) { gboolean saved; g_return_if_fail (E_IS_MAIL_SEND_ACCOUNT_OVERRIDE (override)); g_return_if_fail (folder_uri != NULL); g_return_if_fail (account_uid != NULL); g_mutex_lock (&override->priv->property_lock); g_key_file_set_string ( override->priv->key_file, FOLDERS_SECTION, folder_uri, account_uid); write_alias_info_locked (override, FOLDERS_ALIAS_NAME_SECTION, FOLDERS_ALIAS_ADDRESS_SECTION, folder_uri, alias_name, alias_address); saved = e_mail_send_account_override_maybe_save_locked (override); g_mutex_unlock (&override->priv->property_lock); if (saved) g_signal_emit (override, signals[CHANGED], 0); } void e_mail_send_account_override_remove_for_folder (EMailSendAccountOverride *override, const gchar *folder_uri) { gboolean saved; g_return_if_fail (E_IS_MAIL_SEND_ACCOUNT_OVERRIDE (override)); g_return_if_fail (folder_uri != NULL); g_mutex_lock (&override->priv->property_lock); g_key_file_remove_key ( override->priv->key_file, FOLDERS_SECTION, folder_uri, NULL); write_alias_info_locked (override, FOLDERS_ALIAS_NAME_SECTION, FOLDERS_ALIAS_ADDRESS_SECTION, folder_uri, NULL, NULL); saved = e_mail_send_account_override_maybe_save_locked (override); g_mutex_unlock (&override->priv->property_lock); if (saved) g_signal_emit (override, signals[CHANGED], 0); } gchar * e_mail_send_account_override_get_for_recipient (EMailSendAccountOverride *override, CamelInternetAddress *recipients, gchar **out_alias_name, gchar **out_alias_address) { gchar *account_uid; g_return_val_if_fail (E_IS_MAIL_SEND_ACCOUNT_OVERRIDE (override), NULL); g_return_val_if_fail (recipients != NULL, NULL); g_mutex_lock (&override->priv->property_lock); account_uid = get_override_for_recipients_locked ( override, CAMEL_ADDRESS (recipients), out_alias_name, out_alias_address); g_mutex_unlock (&override->priv->property_lock); return account_uid; } void e_mail_send_account_override_set_for_recipient (EMailSendAccountOverride *override, const gchar *recipient, const gchar *account_uid, const gchar *alias_name, const gchar *alias_address) { gboolean saved; g_return_if_fail (E_IS_MAIL_SEND_ACCOUNT_OVERRIDE (override)); g_return_if_fail (recipient != NULL); g_return_if_fail (account_uid != NULL); g_mutex_lock (&override->priv->property_lock); g_key_file_set_string ( override->priv->key_file, RECIPIENTS_SECTION, recipient, account_uid); write_alias_info_locked (override, RECIPIENTS_ALIAS_NAME_SECTION, RECIPIENTS_ALIAS_ADDRESS_SECTION, recipient, alias_name, alias_address); saved = e_mail_send_account_override_maybe_save_locked (override); g_mutex_unlock (&override->priv->property_lock); if (saved) g_signal_emit (override, signals[CHANGED], 0); } void e_mail_send_account_override_remove_for_recipient (EMailSendAccountOverride *override, const gchar *recipient) { gboolean saved; g_return_if_fail (E_IS_MAIL_SEND_ACCOUNT_OVERRIDE (override)); g_return_if_fail (recipient != NULL); g_mutex_lock (&override->priv->property_lock); g_key_file_remove_key ( override->priv->key_file, RECIPIENTS_SECTION, recipient, NULL); write_alias_info_locked (override, RECIPIENTS_ALIAS_NAME_SECTION, RECIPIENTS_ALIAS_ADDRESS_SECTION, recipient, NULL, NULL); saved = e_mail_send_account_override_maybe_save_locked (override); g_mutex_unlock (&override->priv->property_lock); if (saved) g_signal_emit (override, signals[CHANGED], 0); } void e_mail_send_account_override_list_for_account (EMailSendAccountOverride *override, const gchar *account_uid, const gchar *alias_name, const gchar *alias_address, GList **folder_overrides, GList **recipient_overrides) { g_return_if_fail (E_IS_MAIL_SEND_ACCOUNT_OVERRIDE (override)); g_return_if_fail (account_uid != NULL); g_mutex_lock (&override->priv->property_lock); list_overrides_for_account_locked ( override, account_uid, alias_name, alias_address, folder_overrides, recipient_overrides); g_mutex_unlock (&override->priv->property_lock); } void e_mail_send_account_override_freeze_save (EMailSendAccountOverride *override) { g_return_if_fail (E_IS_MAIL_SEND_ACCOUNT_OVERRIDE (override)); g_mutex_lock (&override->priv->property_lock); override->priv->save_frozen++; if (!override->priv->save_frozen) { g_warn_if_reached (); } g_mutex_unlock (&override->priv->property_lock); } void e_mail_send_account_override_thaw_save (EMailSendAccountOverride *override) { gboolean saved = FALSE; g_return_if_fail (E_IS_MAIL_SEND_ACCOUNT_OVERRIDE (override)); g_mutex_lock (&override->priv->property_lock); if (!override->priv->save_frozen) { g_warn_if_reached (); } else { override->priv->save_frozen--; if (!override->priv->save_frozen && override->priv->need_save) saved = e_mail_send_account_override_save_locked (override); } g_mutex_unlock (&override->priv->property_lock); if (saved) g_signal_emit (override, signals[CHANGED], 0); }
{ "pile_set_name": "Github" }
{ "created_at": "2015-02-27T22:28:06.644610", "description": "\u6536\u96c6\u6574\u7406Android\u5f00\u53d1\u6240\u9700\u7684Android SDK\u3001\u5f00\u53d1\u4e2d\u7528\u5230\u7684\u5de5\u5177\u3001Android\u5f00\u53d1\u6559\u7a0b\u3001Android\u8bbe\u8ba1\u89c4\u8303\uff0c\u514d\u8d39\u7684\u8bbe\u8ba1\u7d20\u6750\u7b49\u3002", "fork": false, "full_name": "inferjay/AndroidDevTools", "updated_at": "2015-02-27T23:42:09.934053" }
{ "pile_set_name": "Github" }
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2014 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2011-03-05 // Updated : 2011-03-05 // Licence : This source is under MIT License // File : glm/gtx/matrix_interpolation.inl /////////////////////////////////////////////////////////////////////////////////////////////////// namespace glm { template <typename T, precision P> GLM_FUNC_QUALIFIER void axisAngle ( detail::tmat4x4<T, P> const & mat, detail::tvec3<T, P> & axis, T & angle ) { T epsilon = (T)0.01; T epsilon2 = (T)0.1; if((abs(mat[1][0] - mat[0][1]) < epsilon) && (abs(mat[2][0] - mat[0][2]) < epsilon) && (abs(mat[2][1] - mat[1][2]) < epsilon)) { if ((abs(mat[1][0] + mat[0][1]) < epsilon2) && (abs(mat[2][0] + mat[0][2]) < epsilon2) && (abs(mat[2][1] + mat[1][2]) < epsilon2) && (abs(mat[0][0] + mat[1][1] + mat[2][2] - (T)3.0) < epsilon2)) { angle = (T)0.0; axis.x = (T)1.0; axis.y = (T)0.0; axis.z = (T)0.0; return; } angle = static_cast<T>(3.1415926535897932384626433832795); T xx = (mat[0][0] + (T)1.0) / (T)2.0; T yy = (mat[1][1] + (T)1.0) / (T)2.0; T zz = (mat[2][2] + (T)1.0) / (T)2.0; T xy = (mat[1][0] + mat[0][1]) / (T)4.0; T xz = (mat[2][0] + mat[0][2]) / (T)4.0; T yz = (mat[2][1] + mat[1][2]) / (T)4.0; if((xx > yy) && (xx > zz)) { if (xx < epsilon) { axis.x = (T)0.0; axis.y = (T)0.7071; axis.z = (T)0.7071; } else { axis.x = sqrt(xx); axis.y = xy / axis.x; axis.z = xz / axis.x; } } else if (yy > zz) { if (yy < epsilon) { axis.x = (T)0.7071; axis.y = (T)0.0; axis.z = (T)0.7071; } else { axis.y = sqrt(yy); axis.x = xy / axis.y; axis.z = yz / axis.y; } } else { if (zz < epsilon) { axis.x = (T)0.7071; axis.y = (T)0.7071; axis.z = (T)0.0; } else { axis.z = sqrt(zz); axis.x = xz / axis.z; axis.y = yz / axis.z; } } return; } T s = sqrt((mat[2][1] - mat[1][2]) * (mat[2][1] - mat[1][2]) + (mat[2][0] - mat[0][2]) * (mat[2][0] - mat[0][2]) + (mat[1][0] - mat[0][1]) * (mat[1][0] - mat[0][1])); if (glm::abs(s) < T(0.001)) s = (T)1.0; angle = acos((mat[0][0] + mat[1][1] + mat[2][2] - (T)1.0) / (T)2.0); axis.x = (mat[1][2] - mat[2][1]) / s; axis.y = (mat[2][0] - mat[0][2]) / s; axis.z = (mat[0][1] - mat[1][0]) / s; } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tmat4x4<T, P> axisAngleMatrix ( detail::tvec3<T, P> const & axis, T const angle ) { T c = cos(angle); T s = sin(angle); T t = static_cast<T>(1) - c; detail::tvec3<T, P> n = normalize(axis); return detail::tmat4x4<T, P>( t * n.x * n.x + c, t * n.x * n.y + n.z * s, t * n.x * n.z - n.y * s, T(0), t * n.x * n.y - n.z * s, t * n.y * n.y + c, t * n.y * n.z + n.x * s, T(0), t * n.x * n.z + n.y * s, t * n.y * n.z - n.x * s, t * n.z * n.z + c, T(0), T(0), T(0), T(0), T(1) ); } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tmat4x4<T, P> extractMatrixRotation ( detail::tmat4x4<T, P> const & mat ) { return detail::tmat4x4<T, P>( mat[0][0], mat[0][1], mat[0][2], 0.0, mat[1][0], mat[1][1], mat[1][2], 0.0, mat[2][0], mat[2][1], mat[2][2], 0.0, 0.0, 0.0, 0.0, 1.0 ); } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tmat4x4<T, P> interpolate ( detail::tmat4x4<T, P> const & m1, detail::tmat4x4<T, P> const & m2, T const delta ) { detail::tmat4x4<T, P> m1rot = extractMatrixRotation(m1); detail::tmat4x4<T, P> dltRotation = m2 * transpose(m1rot); detail::tvec3<T, P> dltAxis; T dltAngle; axisAngle(dltRotation, dltAxis, dltAngle); detail::tmat4x4<T, P> out = axisAngleMatrix(dltAxis, dltAngle * delta) * m1rot; out[3][0] = m1[3][0] + delta * (m2[3][0] - m1[3][0]); out[3][1] = m1[3][1] + delta * (m2[3][1] - m1[3][1]); out[3][2] = m1[3][2] + delta * (m2[3][2] - m1[3][2]); return out; } }//namespace glm
{ "pile_set_name": "Github" }
/* * XML wrapper for libxml2 * Copyright (c) 2012-2013, Qualcomm Atheros, Inc. * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include "includes.h" #define LIBXML_VALID_ENABLED #include <libxml/tree.h> #include <libxml/xmlschemastypes.h> #include "common.h" #include "base64.h" #include "xml-utils.h" struct xml_node_ctx { void *ctx; }; struct str_buf { char *buf; size_t len; }; #define MAX_STR 1000 static void add_str(void *ctx_ptr, const char *fmt, ...) { struct str_buf *str = ctx_ptr; va_list ap; char *n; int len; n = os_realloc(str->buf, str->len + MAX_STR + 2); if (n == NULL) return; str->buf = n; va_start(ap, fmt); len = vsnprintf(str->buf + str->len, MAX_STR, fmt, ap); va_end(ap); if (len >= MAX_STR) len = MAX_STR - 1; str->len += len; str->buf[str->len] = '\0'; } int xml_validate(struct xml_node_ctx *ctx, xml_node_t *node, const char *xml_schema_fname, char **ret_err) { xmlDocPtr doc; xmlNodePtr n; xmlSchemaParserCtxtPtr pctx; xmlSchemaValidCtxtPtr vctx; xmlSchemaPtr schema; int ret; struct str_buf errors; if (ret_err) *ret_err = NULL; doc = xmlNewDoc((xmlChar *) "1.0"); if (doc == NULL) return -1; n = xmlDocCopyNode((xmlNodePtr) node, doc, 1); if (n == NULL) { xmlFreeDoc(doc); return -1; } xmlDocSetRootElement(doc, n); os_memset(&errors, 0, sizeof(errors)); pctx = xmlSchemaNewParserCtxt(xml_schema_fname); xmlSchemaSetParserErrors(pctx, (xmlSchemaValidityErrorFunc) add_str, (xmlSchemaValidityWarningFunc) add_str, &errors); schema = xmlSchemaParse(pctx); xmlSchemaFreeParserCtxt(pctx); vctx = xmlSchemaNewValidCtxt(schema); xmlSchemaSetValidErrors(vctx, (xmlSchemaValidityErrorFunc) add_str, (xmlSchemaValidityWarningFunc) add_str, &errors); ret = xmlSchemaValidateDoc(vctx, doc); xmlSchemaFreeValidCtxt(vctx); xmlFreeDoc(doc); xmlSchemaFree(schema); if (ret == 0) { os_free(errors.buf); return 0; } else if (ret > 0) { if (ret_err) *ret_err = errors.buf; else os_free(errors.buf); return -1; } else { if (ret_err) *ret_err = errors.buf; else os_free(errors.buf); return -1; } } int xml_validate_dtd(struct xml_node_ctx *ctx, xml_node_t *node, const char *dtd_fname, char **ret_err) { xmlDocPtr doc; xmlNodePtr n; xmlValidCtxt vctx; xmlDtdPtr dtd; int ret; struct str_buf errors; if (ret_err) *ret_err = NULL; doc = xmlNewDoc((xmlChar *) "1.0"); if (doc == NULL) return -1; n = xmlDocCopyNode((xmlNodePtr) node, doc, 1); if (n == NULL) { xmlFreeDoc(doc); return -1; } xmlDocSetRootElement(doc, n); os_memset(&errors, 0, sizeof(errors)); dtd = xmlParseDTD(NULL, (const xmlChar *) dtd_fname); if (dtd == NULL) { xmlFreeDoc(doc); return -1; } os_memset(&vctx, 0, sizeof(vctx)); vctx.userData = &errors; vctx.error = add_str; vctx.warning = add_str; ret = xmlValidateDtd(&vctx, doc, dtd); xmlFreeDoc(doc); xmlFreeDtd(dtd); if (ret == 1) { os_free(errors.buf); return 0; } else { if (ret_err) *ret_err = errors.buf; else os_free(errors.buf); return -1; } } void xml_node_free(struct xml_node_ctx *ctx, xml_node_t *node) { xmlFreeNode((xmlNodePtr) node); } xml_node_t * xml_node_get_parent(struct xml_node_ctx *ctx, xml_node_t *node) { return (xml_node_t *) ((xmlNodePtr) node)->parent; } xml_node_t * xml_node_from_buf(struct xml_node_ctx *ctx, const char *buf) { xmlDocPtr doc; xmlNodePtr node; doc = xmlParseMemory(buf, strlen(buf)); if (doc == NULL) return NULL; node = xmlDocGetRootElement(doc); node = xmlCopyNode(node, 1); xmlFreeDoc(doc); return (xml_node_t *) node; } const char * xml_node_get_localname(struct xml_node_ctx *ctx, xml_node_t *node) { return (const char *) ((xmlNodePtr) node)->name; } char * xml_node_to_str(struct xml_node_ctx *ctx, xml_node_t *node) { xmlChar *buf; int bufsiz; char *ret, *pos; xmlNodePtr n = (xmlNodePtr) node; xmlDocPtr doc; doc = xmlNewDoc((xmlChar *) "1.0"); n = xmlDocCopyNode(n, doc, 1); xmlDocSetRootElement(doc, n); xmlDocDumpFormatMemory(doc, &buf, &bufsiz, 0); xmlFreeDoc(doc); if (!buf) return NULL; pos = (char *) buf; if (strncmp(pos, "<?xml", 5) == 0) { pos = strchr(pos, '>'); if (pos) pos++; while (pos && (*pos == '\r' || *pos == '\n')) pos++; } if (pos) ret = os_strdup(pos); else ret = NULL; xmlFree(buf); if (ret) { pos = ret; if (pos[0]) { while (pos[1]) pos++; } while (pos >= ret && *pos == '\n') *pos-- = '\0'; } return ret; } void xml_node_detach(struct xml_node_ctx *ctx, xml_node_t *node) { xmlUnlinkNode((xmlNodePtr) node); } void xml_node_add_child(struct xml_node_ctx *ctx, xml_node_t *parent, xml_node_t *child) { xmlAddChild((xmlNodePtr) parent, (xmlNodePtr) child); } xml_node_t * xml_node_create_root(struct xml_node_ctx *ctx, const char *ns_uri, const char *ns_prefix, xml_namespace_t **ret_ns, const char *name) { xmlNodePtr node; xmlNsPtr ns = NULL; node = xmlNewNode(NULL, (const xmlChar *) name); if (node == NULL) return NULL; if (ns_uri) { ns = xmlNewNs(node, (const xmlChar *) ns_uri, (const xmlChar *) ns_prefix); xmlSetNs(node, ns); } if (ret_ns) *ret_ns = (xml_namespace_t *) ns; return (xml_node_t *) node; } xml_node_t * xml_node_create(struct xml_node_ctx *ctx, xml_node_t *parent, xml_namespace_t *ns, const char *name) { xmlNodePtr node; node = xmlNewChild((xmlNodePtr) parent, (xmlNsPtr) ns, (const xmlChar *) name, NULL); return (xml_node_t *) node; } xml_node_t * xml_node_create_text(struct xml_node_ctx *ctx, xml_node_t *parent, xml_namespace_t *ns, const char *name, const char *value) { xmlNodePtr node; node = xmlNewTextChild((xmlNodePtr) parent, (xmlNsPtr) ns, (const xmlChar *) name, (const xmlChar *) value); return (xml_node_t *) node; } xml_node_t * xml_node_create_text_ns(struct xml_node_ctx *ctx, xml_node_t *parent, const char *ns_uri, const char *name, const char *value) { xmlNodePtr node; xmlNsPtr ns; node = xmlNewTextChild((xmlNodePtr) parent, NULL, (const xmlChar *) name, (const xmlChar *) value); ns = xmlNewNs(node, (const xmlChar *) ns_uri, NULL); xmlSetNs(node, ns); return (xml_node_t *) node; } void xml_node_set_text(struct xml_node_ctx *ctx, xml_node_t *node, const char *value) { /* TODO: escape XML special chars in value */ xmlNodeSetContent((xmlNodePtr) node, (xmlChar *) value); } int xml_node_add_attr(struct xml_node_ctx *ctx, xml_node_t *node, xml_namespace_t *ns, const char *name, const char *value) { xmlAttrPtr attr; if (ns) { attr = xmlNewNsProp((xmlNodePtr) node, (xmlNsPtr) ns, (const xmlChar *) name, (const xmlChar *) value); } else { attr = xmlNewProp((xmlNodePtr) node, (const xmlChar *) name, (const xmlChar *) value); } return attr ? 0 : -1; } char * xml_node_get_attr_value(struct xml_node_ctx *ctx, xml_node_t *node, char *name) { return (char *) xmlGetNoNsProp((xmlNodePtr) node, (const xmlChar *) name); } char * xml_node_get_attr_value_ns(struct xml_node_ctx *ctx, xml_node_t *node, const char *ns_uri, char *name) { return (char *) xmlGetNsProp((xmlNodePtr) node, (const xmlChar *) name, (const xmlChar *) ns_uri); } void xml_node_get_attr_value_free(struct xml_node_ctx *ctx, char *val) { if (val) xmlFree((xmlChar *) val); } xml_node_t * xml_node_first_child(struct xml_node_ctx *ctx, xml_node_t *parent) { return (xml_node_t *) ((xmlNodePtr) parent)->children; } xml_node_t * xml_node_next_sibling(struct xml_node_ctx *ctx, xml_node_t *node) { return (xml_node_t *) ((xmlNodePtr) node)->next; } int xml_node_is_element(struct xml_node_ctx *ctx, xml_node_t *node) { return ((xmlNodePtr) node)->type == XML_ELEMENT_NODE; } char * xml_node_get_text(struct xml_node_ctx *ctx, xml_node_t *node) { if (xmlChildElementCount((xmlNodePtr) node) > 0) return NULL; return (char *) xmlNodeGetContent((xmlNodePtr) node); } void xml_node_get_text_free(struct xml_node_ctx *ctx, char *val) { if (val) xmlFree((xmlChar *) val); } char * xml_node_get_base64_text(struct xml_node_ctx *ctx, xml_node_t *node, int *ret_len) { char *txt; unsigned char *ret; size_t len; txt = xml_node_get_text(ctx, node); if (txt == NULL) return NULL; ret = base64_decode((unsigned char *) txt, strlen(txt), &len); if (ret_len) *ret_len = len; xml_node_get_text_free(ctx, txt); if (ret == NULL) return NULL; txt = os_malloc(len + 1); if (txt == NULL) { os_free(ret); return NULL; } os_memcpy(txt, ret, len); txt[len] = '\0'; return txt; } xml_node_t * xml_node_copy(struct xml_node_ctx *ctx, xml_node_t *node) { if (node == NULL) return NULL; return (xml_node_t *) xmlCopyNode((xmlNodePtr) node, 1); } struct xml_node_ctx * xml_node_init_ctx(void *upper_ctx, const void *env) { struct xml_node_ctx *xctx; xctx = os_zalloc(sizeof(*xctx)); if (xctx == NULL) return NULL; xctx->ctx = upper_ctx; LIBXML_TEST_VERSION return xctx; } void xml_node_deinit_ctx(struct xml_node_ctx *ctx) { xmlSchemaCleanupTypes(); xmlCleanupParser(); xmlMemoryDump(); os_free(ctx); }
{ "pile_set_name": "Github" }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v201911; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for BasisType. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="BasisType"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="UNKNOWN"/> * &lt;enumeration value="ABSOLUTE"/> * &lt;enumeration value="HISTORICAL"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "BasisType") @XmlEnum public enum BasisType { /** * * The value returned if the actual value is not exposed by the requested API version. * * */ UNKNOWN, /** * * The adjustment segment has no basis to reference and is manually defined for the future dates. * * */ ABSOLUTE, /** * * The adjustment segment has a historical basis to reference for its forecast adjustment. * * */ HISTORICAL; public String value() { return name(); } public static BasisType fromValue(String v) { return valueOf(v); } }
{ "pile_set_name": "Github" }
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // 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. #ifndef RAPIDJSON_CURSORSTREAMWRAPPER_H_ #define RAPIDJSON_CURSORSTREAMWRAPPER_H_ #include "stream.h" #if defined(__GNUC__) RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(effc++) #endif #if defined(_MSC_VER) && _MSC_VER <= 1800 RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(4702) // unreachable code RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated #endif RAPIDJSON_NAMESPACE_BEGIN //! Cursor stream wrapper for counting line and column number if error exists. /*! \tparam InputStream Any stream that implements Stream Concept */ template <typename InputStream, typename Encoding = UTF8<> > class CursorStreamWrapper : public GenericStreamWrapper<InputStream, Encoding> { public: typedef typename Encoding::Ch Ch; CursorStreamWrapper(InputStream& is): GenericStreamWrapper<InputStream, Encoding>(is), line_(1), col_(0) {} // counting line and column number Ch Take() { Ch ch = this->is_.Take(); if(ch == '\n') { line_ ++; col_ = 0; } else { col_ ++; } return ch; } //! Get the error line number, if error exists. size_t GetLine() const { return line_; } //! Get the error column number, if error exists. size_t GetColumn() const { return col_; } private: size_t line_; //!< Current Line size_t col_; //!< Current Column }; #if defined(_MSC_VER) && _MSC_VER <= 1800 RAPIDJSON_DIAG_POP #endif #if defined(__GNUC__) RAPIDJSON_DIAG_POP #endif RAPIDJSON_NAMESPACE_END #endif // RAPIDJSON_CURSORSTREAMWRAPPER_H_
{ "pile_set_name": "Github" }
Device Tree Clock bindings for ZTE zx296718 This binding uses the common clock binding[1]. [1] Documentation/devicetree/bindings/clock/clock-bindings.txt Required properties: - compatible : shall be one of the following: "zte,zx296718-topcrm": zx296718 top clock selection, divider and gating "zte,zx296718-lsp0crm" and "zte,zx296718-lsp1crm": zx296718 device level clock selection and gating "zte,zx296718-audiocrm": zx296718 audio clock selection, divider and gating - reg: Address and length of the register set The clock consumer should specify the desired clock by having the clock ID in its "clocks" phandle cell. See include/dt-bindings/clock/zx296718-clock.h for the full list of zx296718 clock IDs. topclk: topcrm@1461000 { compatible = "zte,zx296718-topcrm-clk"; reg = <0x01461000 0x1000>; #clock-cells = <1>; }; usbphy0:usb-phy0 { compatible = "zte,zx296718-usb-phy"; #phy-cells = <0>; clocks = <&topclk USB20_PHY_CLK>; clock-names = "phyclk"; };
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package fake import ( rest "k8s.io/client-go/rest" testing "k8s.io/client-go/testing" internalversion "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/internalversion" ) type FakeBatch struct { *testing.Fake } func (c *FakeBatch) CronJobs(namespace string) internalversion.CronJobInterface { return &FakeCronJobs{c, namespace} } func (c *FakeBatch) Jobs(namespace string) internalversion.JobInterface { return &FakeJobs{c, namespace} } // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. func (c *FakeBatch) RESTClient() rest.Interface { var ret *rest.RESTClient return ret }
{ "pile_set_name": "Github" }
package web import ( "encoding/json" "net/http" ) // Respond converts a Go value to JSON and sends it to the client. func Respond(w http.ResponseWriter, data interface{}, statusCode int) error { // Convert the response value to JSON. res, err := json.Marshal(data) if err != nil { return err } // Respond with the provided JSON. w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(statusCode) if _, err := w.Write(res); err != nil { return err } return nil }
{ "pile_set_name": "Github" }
'so that default templates can be assigned to the issue.': 'tato defoltně nastavená šablona může být přiřazena k tomuto tématu.' 'Once this is done, the issue can be published': 'Jakmile je to hotovo, může být téma zveřejněno' 'This issue cannot be previewed. Please make sure the publication has a theme assigned.': 'Toto vydání nemůže být zobrazeno. Prosím ujistěte se, že publikace má přiděleno téma.' 'This issue cannot be previewed. Please make sure it has the front template selected.': 'Toto vydání nemůže být zobrazeno. Prosím ujistěte se, že je vybrána přední šablona.' 'Publish all articles:': 'Publikovat všechny články:' 'Publish all articles': 'Publikovat všechny články' 'Force publishing of all articles. If set to No, only articles with Publish with Issue status will be published.': 'Nucené publikování všech článků. Pokud nastaveno Ne, pouze články se statusem Publikovat s vydáním budou uveřejněny.' default: default 'The publishing/unpublishing can not be set the same time': 'Publikování/nepublikování nemůže být nastaveno najednou' 'The publishing schedule can not be set in the past': 'Publikační harmonogram nemůže být nastaven v minulosti' 'Please assign at least one theme to the publication': 'Prosím zadejte alespoň jeden námět do publikace' 'Issue Theme': 'Téma vydání' 'The values you are trying to set conflict with issue $1$2. $3 ($4)$5.': 'Hodnoty, které se snažíte nastavit, jsou v rozporu s vydáním $1$2. $3 ($4)$5.' 'The number must be unique for each issue in this publication of the same language.': 'Číslo musí být jedinečné pro každé vydání v této publikaci stejného jazyka.' 'The language and URL name must be unique for each issue in this publication.': 'Jazyk a URL musí být jedinečné pro každé vydání v této publikaci.' 'Issue created.': 'Vydání vytvořeno.' 'Issue updated': 'Vydání aktualizováno' 'Could not save the changes to the issue.': 'Nezdařilo se uložit změny ve vydání.' 'Unpublish on: $1': 'Nepublikovat v: $1' 'There are $1 articles in this issue.': 'V tomto vydání je $1 článků.' 'The issue $1 has been deleted.': 'Vydání $1 bylo odstraněno.' Schedule: Rozvrh 'Publish on: $1': 'Publikovat v: $1' 'Publish Date $1': 'Datum Publikování $1' 'Deleted issue': 'Odstraněné vydání' 'Delete issue': 'Odstranit vydání' 'Click here to publish this issue': 'Klikněte zde pro publikaci vydání' 'A total of $1 articles were deleted.': 'Celkem $1 článků odstraněno.' 'Name<BR><SMALL>(click to see sections)</SMALL>': 'Název publikace<BR><SMALL>(klikněte pro zobrazení rubrik)</SMALL> ' 'Delete issue $1': 'Odstranit vydání $1' 'You do not have the right to change issues.': 'Nemáte právo měnit vydání' 'Are you sure you want to change the issue $1 status from $2 to $3?': 'Určitě chcete změnit stav vydání $1 z $2 na $3?' 'Add new translation': 'Přidat překlad' 'You do not have the right to add issues.': 'Nemáte právo přidat vydání' 'The issue $1 has been successfuly added.': 'Vydání $1 bylo úspěšně přidáno' 'The issue could not be added.': 'Vydání nemohlo být přidáno' 'Change issue details': 'Změnit detaily vydání' 'You do not have the right to change issue details.': 'Nemáte právo změnit detaily vydání' 'Publication date<BR><SMALL>(yyyy-mm-dd)</SMALL>': 'Datum publikování <BR><SMALL>(rrrr-mm-dd)</SMALL>' 'Front Page Template': 'Šablona Hlavní Stránky' 'You do not have the right to delete issues.': 'Nemáte právo mazat vydání' 'Are you sure you want to delete the issue $1?': 'Určitě chcete smazat vydání $1?' 'Use the structure of the previous issue': 'Použít strukturu předchozího vydání' 'Copy the entire structure in all languages from the previous issue except for content.': 'Kopírovat celou strukturu ve všech jazycích z předchozího vydání kromě obsahu' 'You may modify it later if you wish.': 'Můžete to upravit později' 'Create a new structure': 'Vytvořit novou strukturu' 'Create a complete new structure.': 'Vytvořit kopletně novou strukturu' 'You must define an issue type for each language and then sections for them.': 'Definovat typ vydání pro každý jazyk a rubriky' 'Copy previous issue': 'Kopírovat předchozí vydání' 'No previous issue.': 'Žádné předchozí vydání' 'Copy structure from issue number $1': 'Kopírovat strukturu z vydání č. $1' 'Delete entry': 'Odstranit vztup' 'Issue Publishing Schedule': 'Rozvrh Publikování Vydání' 'Invalid Input: $1': 'Neplatný vztup: $1' 'Issue Number': 'Číslo Vydání' 'Go To Sections': 'Jít na Rubriky' 'There was an error reading the language parameter.': 'Vyskytla se chyba při čtení jazkového parametru.' 'There was an error reading the publication parameter.': 'Vyskytla se chyba při čtení parametru publikace.' 'There was an error reading the issue parameter.': 'Vyskytla se chyba při čtení parametru vydání.' 'There was an error scheduling the $1 action on $2': 'Nebylo možné naplánovat činnost $1 na $2' 'The action scheduled on $1 could not be deleted.': 'Činnost naplánovaná na $1 nemohla být zrušena' 'Click to open': null
{ "pile_set_name": "Github" }
66 1 98 2 128 3 146 2 150 1 213 2 224 2 238 2 255 2 273 3 278 2 311 3 369 3 401 5 406 4
{ "pile_set_name": "Github" }
subject= CN = LibreSSL Test Server 1 issuer= CN = LibreSSL Test Intermediate CA 2 subject= CN = LibreSSL Test Intermediate CA 2 issuer= CN = LibreSSL Test Intermediate CA 1 subject= CN = LibreSSL Test Intermediate CA 2 issuer= CN = LibreSSL Test Root CA 2 subject= CN = LibreSSL Test Intermediate CA 1 issuer= CN = LibreSSL Test Root CA 1 -----BEGIN CERTIFICATE----- MIIDLjCCAhagAwIBAgIJAIZjiC92oa9fMA0GCSqGSIb3DQEBCwUAMCoxKDAmBgNV BAMMH0xpYnJlU1NMIFRlc3QgSW50ZXJtZWRpYXRlIENBIDIwHhcNMjAwNzE0MTgy MTA0WhcNMzAwNzEyMTgyMTA0WjAhMR8wHQYDVQQDDBZMaWJyZVNTTCBUZXN0IFNl cnZlciAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwqXhw2gULhNs Z7sBIqh/TciOMIFpsWU6JDES663BQ7BhVD3uHwsBRGV80+dNz8zi070t+5eoX00O 9GWwIuC4wjhjM0VVid+NJgRdDvjHBpnbdtY8DFh4X7wsXqyHb5Zmbda+f81JiXEF m1E8FtNnw5wdhzaZdN2quZsIDq4cnldVoolFbKDuhRBgYXujv64Yh4SkPEzOGiUv YQW7kkSVepwchwy2baGYEsZSNQhPasuCCGsjRi1piYJ0mx3FpSO/gtcTwF2DsLtw rAFms/HtHIuGOgPROfVllemTTnj+OqutNoYFbpw5qPvDk1b8ciSJOXuzu42hDmkH smqlTIz36wIDAQABo2AwXjAdBgNVHQ4EFgQU0lC+eXXjL7i1nIpo28/iBVuyqM4w HwYDVR0jBBgwFoAUxwNMYQTwWSAmTGX9yKxo/zsaciIwDAYDVR0TAQH/BAIwADAO BgNVHQ8BAf8EBAMCB4AwDQYJKoZIhvcNAQELBQADggEBAIq1+kpJ23wZNmttl1dY vecnxNYQbztAfblXLofzrNWcjcuFjMA+r6r6ACninGUmaqdzwAWE9kTg2MvEJ/Gi +FgXhZRHDozDKkX6LZ5r+KKrUI5IRKXH8yuVTWgL8NJhvYQeG1lJ+NYwiIDDbO1b mfR7HJOSM1wY6OmWl+ac72PUdN5h7q6HVIcIFlMVwPQ+Xz5DgDLmh1iglcq8/i1/ wJRLVN8Wg/Ava3o8PwE7Lp0flfrURTuZqP3RNa+YRy6xCl7kokx2BxygzM/zBHhJ 7EMkJxPVEi28+51iL2COtXgbL3HWPUubM8fUwbv5ftuEE4DhXMRI1o2Tv9WoWcEx 9yM= -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIDOjCCAiKgAwIBAgIJAIZjiC92oa9dMA0GCSqGSIb3DQEBCwUAMCoxKDAmBgNV BAMMH0xpYnJlU1NMIFRlc3QgSW50ZXJtZWRpYXRlIENBIDEwHhcNMjAwNzE0MTgy MTAzWhcNMzAwNzEyMTgyMTAzWjAqMSgwJgYDVQQDDB9MaWJyZVNTTCBUZXN0IElu dGVybWVkaWF0ZSBDQSAyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA 1bCCdCJL6+v+rzJaS6nrDfElt4ktbb4zrKvIIaB0TwImSbiHxrSYiiylXCTZbehJ iXogu41LOMMrwTyXvt8yNs2K0JAE6Rk7cO0Goq5GmT7Dgbd6kfdBUXgdldOA0xel z/dJ9ZH4jgyQK1x5zdr+FM63FYKaEguLiLa74DWWG7xBczmmy7C7pn+4VXaIpeIh xVgF86F4yRiOCtoEFv5R4ohsysW+bnEJpF/E4/FcAAMP0OevGQZrZJhkVx5Zhrp5 Xru4PUt4jn7TGBD3XlNPbGt3YvCM0fos70/+YEn9/7mue8l8w/ccZCNkHlc6rhoV VhjP+RYJZzeK7jk5viqZ+QIDAQABo2MwYTAdBgNVHQ4EFgQUxwNMYQTwWSAmTGX9 yKxo/zsaciIwHwYDVR0jBBgwFoAUZ48rls6iM5jYKv5fad8uGlZBR4YwDwYDVR0T AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQELBQADggEBAAHt H9FaBdHkCIIBaG3L3eQms3roh5AElb1PlOD8q3gm1WL5P6ZoC73zXjYJeIu65mAt +/KSLu5mhj8CO8VQBWVxMSwTOpVadT9XR+nb23NwbhedQ88ef6df9dy9oN/gJx+f lzdH3sFkuNkirTYKd6V/eHwXP2a+vxc+bJNmafeE/2BF+g6CDvi38bO3gBAfNg0x U6pSiLaWRgljH4klWlzL6G+JiFCZug5aacZnvMtQrqfGDDblAKPYG/xe4ARQIPhz 6D/aY29gNIhYARDG6E1fD54/PT1YxZGj/Y8mskppoxiNVvEPoxfqwzvlyqL1olh6 vKcYy30m72E6Esrbev8= -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIDMjCCAhqgAwIBAgIJAIZjiC92oa9eMA0GCSqGSIb3DQEBCwUAMCIxIDAeBgNV BAMMF0xpYnJlU1NMIFRlc3QgUm9vdCBDQSAyMB4XDTIwMDcxNDE4MjEwNFoXDTMw MDcxMjE4MjEwNFowKjEoMCYGA1UEAwwfTGlicmVTU0wgVGVzdCBJbnRlcm1lZGlh dGUgQ0EgMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANWwgnQiS+vr /q8yWkup6w3xJbeJLW2+M6yryCGgdE8CJkm4h8a0mIospVwk2W3oSYl6ILuNSzjD K8E8l77fMjbNitCQBOkZO3DtBqKuRpk+w4G3epH3QVF4HZXTgNMXpc/3SfWR+I4M kCtcec3a/hTOtxWCmhILi4i2u+A1lhu8QXM5psuwu6Z/uFV2iKXiIcVYBfOheMkY jgraBBb+UeKIbMrFvm5xCaRfxOPxXAADD9DnrxkGa2SYZFceWYa6eV67uD1LeI5+ 0xgQ915TT2xrd2LwjNH6LO9P/mBJ/f+5rnvJfMP3HGQjZB5XOq4aFVYYz/kWCWc3 iu45Ob4qmfkCAwEAAaNjMGEwHQYDVR0OBBYEFMcDTGEE8FkgJkxl/cisaP87GnIi MB8GA1UdIwQYMBaAFLwyUPdO1PqOOYNMNxrqJ61rjZ+1MA8GA1UdEwEB/wQFMAMB Af8wDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4IBAQAJuKJAJeVbo1dg YojKwWikaIedSVHgzrGY360EIb31oO5Jb+WECw+9x6k8Q3SmRvuRLHFMbcIK/dqc qgeqlMh5pePsyaomwLAIz2n2OMRzjW0B0evENUvuqunC1T4Bp1RGTMdiHt46EScy 79XP3tw/BdCYO5kPYAcBJ4qI0Mf1ofPcuBFufv53UGZ1UVytoKIlGfgcoWmeR9+p ZeE7F6bpzC9OE5589ytwCUh61rruDKKK38B4rUaITKKQiyCfH1cilz+HEeyal1vx mh2BfMVYYJQowCy8oIcJrNeq9SKb2naPV/fMEGrBbnPrkz/GFsYCYWW/vBVL2XSf z3eka+T2 -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIDMjCCAhqgAwIBAgIJAIZjiC92oa9cMA0GCSqGSIb3DQEBCwUAMCIxIDAeBgNV BAMMF0xpYnJlU1NMIFRlc3QgUm9vdCBDQSAxMB4XDTIwMDcxNDE4MjEwM1oXDTMw MDcxMjE4MjEwM1owKjEoMCYGA1UEAwwfTGlicmVTU0wgVGVzdCBJbnRlcm1lZGlh dGUgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMFY/+WkYwrm HyQHqjzssWWvPY69ryOukIz8vSxIsKBvC8lWVBBYf+P7KEErr8XWsCJWId7b3ETX 0FKxFvthOqZ7Xgotp7b0Rt5Nl0nJsymPMCWIdiFAli9d9T4rY6DTg0ulsvnZKMg1 bjW5yZef8TlUsO5jyyPL7ePlVa18/Tg73lmoKwbAfmQwL8yEjI3a9gjDzBs6J0Nx GwSUz0XtIMJ2OuDGV1f3yX1eeOOFOLSPKK31oCMVN/U2m64pU0TYsqp52KPP2OKQ NADWOUY8hH/iMKcwErB8hJIP5uNcMZcNL/3Fx5fMzB0dYY4qMXWbhNamhrMwaA76 nDqV03c4aOsCAwEAAaNjMGEwHQYDVR0OBBYEFGePK5bOojOY2Cr+X2nfLhpWQUeG MB8GA1UdIwQYMBaAFJb654HjhVrD+wQKAvmil5cqWOAGMA8GA1UdEwEB/wQFMAMB Af8wDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4IBAQChewj1lVVYl7OR nqZh4vsKT6/da5ppfxUuTKeaBFumPjxmQEM7swOGCAFL8VIYP7Px4NlC4DihNHox M7y1H63ZBI12vePjLOcqxjPXK59v3ECZOz7RjT18QoIJmAB8KeDI/hLJf83PGD4e MauFsx3XCxJkHLU22v8k5Sn3n0pWvPCQ+uA8qF+MDhNZq6BuTFyAUHwWZvJGK9PX Tj/fh9LskZV3HsNLM1WF0jVMOtxV6nTI2e5RlqqOSlrlyZr/lmXy13r+wVpuyUmR R1c/av6G7SGa+F9YbKzLYZx/80kO7AO4RWG5AgjgRcCz+fWyE3W0Yaa8LQjXspGo KO4leRha -----END CERTIFICATE-----
{ "pile_set_name": "Github" }
/* * Copyright 2018 Andrea Bresolin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package andreabresolin.kotlincoroutinesexamples.app.network.model import com.google.gson.annotations.SerializedName data class CurrentWeather( @SerializedName("coord") val coord: Coord?, @SerializedName("weather") val weather: List<Weather>?, @SerializedName("base") val base: String?, @SerializedName("main") val main: Main?, @SerializedName("wind") val wind: Wind?, @SerializedName("clouds") val clouds: Clouds?, @SerializedName("rain") val rain: Rain?, @SerializedName("dt") val dt: Int?, @SerializedName("sys") val sys: Sys?, @SerializedName("id") val id: Int?, @SerializedName("name") val name: String?, @SerializedName("cod") val cod: Int?)
{ "pile_set_name": "Github" }
-- This file will be generated at release time. Don't edit it manually. ndless_revision="0"
{ "pile_set_name": "Github" }
CSharpCodeBlock - [0..10)::10 - [@val?[more] CSharpImplicitExpression - [0..10)::10 CSharpTransition - [0..1)::1 - Gen<None> - SpanEditHandler;Accepts:None Transition;[@]; CSharpImplicitExpressionBody - [1..10)::9 CSharpCodeBlock - [1..10)::9 CSharpExpressionLiteral - [1..10)::9 - [val?[more] - Gen<Expr> - ImplicitExpressionEditHandler;Accepts:Any;ImplicitExpression[RTD];K14 Identifier;[val]; QuestionMark;[?]; LeftBracket;[[]; Identifier;[more];
{ "pile_set_name": "Github" }
<?php /** * Test App Comment Model * * CakePHP : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakefoundation.org/projects/info/cakephp CakePHP Project * @package Cake.Test.TestApp.Plugin.TestPlugin.Model * @since CakePHP v 1.2.0.7726 * @version $Revision$ * @modifiedby $LastChangedBy$ * @lastmodified $Date$ * @license http://www.opensource.org/licenses/mit-license.php MIT License */ /** * Class TestPluginComment * * @package Cake.Test.TestApp.Plugin.TestPlugin.Model */ class TestPluginComment extends TestPluginAppModel { public $useTable = 'test_plugin_comments'; public $name = 'TestPluginComment'; }
{ "pile_set_name": "Github" }
// Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License") // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package compatibility import ( "github.com/hazelcast/hazelcast-go-client/serialization" ) type aPortable struct { bool bool b byte c uint16 d float64 s int16 f float32 i int32 l int64 str string p serialization.Portable booleans []bool bytes []byte chars []uint16 doubles []float64 shorts []int16 floats []float32 ints []int32 longs []int64 strings []string portables []serialization.Portable booleansNull []bool bytesNull []byte charsNull []uint16 doublesNull []float64 shortsNull []int16 floatsNull []float32 intsNull []int32 longsNull []int64 stringsNull []string } func (*aPortable) ClassID() int32 { return portableClassID } func (*aPortable) FactoryID() int32 { return portableFactoryID } func (p *aPortable) WritePortable(writer serialization.PortableWriter) error { writer.WriteBool("bool", p.bool) writer.WriteByte("b", p.b) writer.WriteUInt16("c", p.c) writer.WriteFloat64("d", p.d) writer.WriteInt16("s", p.s) writer.WriteFloat32("f", p.f) writer.WriteInt32("i", p.i) writer.WriteInt64("l", p.l) writer.WriteUTF("str", p.str) if p != nil { writer.WritePortable("p", p) } else { writer.WriteNilPortable("p", portableFactoryID, portableClassID) } writer.WriteBoolArray("booleans", p.booleans) writer.WriteByteArray("bs", p.bytes) writer.WriteUInt16Array("cs", p.chars) writer.WriteFloat64Array("ds", p.doubles) writer.WriteInt16Array("ss", p.shorts) writer.WriteFloat32Array("fs", p.floats) writer.WriteInt32Array("is", p.ints) writer.WriteInt64Array("ls", p.longs) writer.WriteUTFArray("strs", p.strings) writer.WritePortableArray("ps", p.portables) writer.WriteBoolArray("booleansNull", p.booleansNull) writer.WriteByteArray("bsNull", p.bytesNull) writer.WriteUInt16Array("csNull", p.charsNull) writer.WriteFloat64Array("dsNull", p.doublesNull) writer.WriteInt16Array("ssNull", p.shortsNull) writer.WriteFloat32Array("fsNull", p.floatsNull) writer.WriteInt32Array("isNull", p.intsNull) writer.WriteInt64Array("lsNull", p.longsNull) writer.WriteUTFArray("strsNull", p.stringsNull) return nil } func (p *aPortable) ReadPortable(reader serialization.PortableReader) error { p.bool = reader.ReadBool("bool") p.b = reader.ReadByte("b") p.c = reader.ReadUInt16("c") p.d = reader.ReadFloat64("d") p.s = reader.ReadInt16("s") p.f = reader.ReadFloat32("f") p.i = reader.ReadInt32("i") p.l = reader.ReadInt64("l") p.str = reader.ReadUTF("str") p.p = reader.ReadPortable("p") p.booleans = reader.ReadBoolArray("booleans") p.bytes = reader.ReadByteArray("bs") p.chars = reader.ReadUInt16Array("cs") p.doubles = reader.ReadFloat64Array("ds") p.shorts = reader.ReadInt16Array("ss") p.floats = reader.ReadFloat32Array("fs") p.ints = reader.ReadInt32Array("is") p.longs = reader.ReadInt64Array("ls") p.strings = reader.ReadUTFArray("strs") p.portables = reader.ReadPortableArray("ps") p.booleansNull = reader.ReadBoolArray("booleansNull") p.bytesNull = reader.ReadByteArray("bsNull") p.charsNull = reader.ReadUInt16Array("csNull") p.doublesNull = reader.ReadFloat64Array("dsNull") p.shortsNull = reader.ReadInt16Array("ssNull") p.floatsNull = reader.ReadFloat32Array("fsNull") p.intsNull = reader.ReadInt32Array("isNull") p.longsNull = reader.ReadInt64Array("lsNull") p.stringsNull = reader.ReadUTFArray("strsNull") return nil }
{ "pile_set_name": "Github" }
package models // TCP_BUFFER_SIZE is the maximum packet size const TCP_BUFFER_SIZE = 1024 * 64 // DEFAULT_RELAY is the default relay used (can be set using --relay) const DEFAULT_RELAY = "142.93.177.120:9009" const DEFAULT_RELAY6 = "[2604:a880:800:c1::14c:1]:9009"
{ "pile_set_name": "Github" }
/* * Copyright 2016 NXP Semiconductor. * Author: Wang Dongsheng <dongsheng.wang@freescale.com> * * SPDX-License-Identifier: GPL-2.0+ */ #include <config.h> #include <linux/linkage.h> #include <asm/armv7.h> #include <asm/psci.h> .pushsection ._secure.text, "ax" .arch_extension sec .align 5 .globl psci_system_off psci_system_off: @ Get QIXIS base address movw r1, #(QIXIS_BASE & 0xffff) movt r1, #(QIXIS_BASE >> 16) ldrb r2, [r1, #QIXIS_PWR_CTL] orr r2, r2, #QIXIS_PWR_CTL_POWEROFF strb r2, [r1, #QIXIS_PWR_CTL] 1: wfi b 1b .popsection
{ "pile_set_name": "Github" }
import java.util.LinkedList; import java.util.List; import java.util.TreeMap; class Solution { private class Freq implements Comparable<Freq> { // 元素的值和频率 public int e, freq; public Freq () {} public Freq (int e, int freq) { this.e = e; this.freq = freq; } @Override public int compareTo(Freq another) { // 最大堆,取出优先级最高的那个元素, // 频次最低的那个元素才是优先级最高的 // 频次低的话优先级才高 if (this.freq < another.freq) return 1; else if (this.freq > another.freq) return -1; else return 0; } } public List<Integer> topKFrequent(int[] nums, int k) { // 先将数组中的元素放入 TreeMap中,统计每个数字出现的次数 TreeMap<Integer, Integer> treeMap = new TreeMap<Integer, Integer>(); for (int num: nums) { if (treeMap.containsKey(num)) treeMap.put(num, treeMap.get(num) + 1); else treeMap.put(num, 1); } // 使用自定义的优先队列 MyPriorityQueue<Freq> priorityQueue = new MyPriorityQueue<Freq>(); // 这样的一个算法就是nlogk这样一个级别的算法 for (int key: treeMap.keySet()) { // 如果还没有存够k个元素 if (priorityQueue.getSize() < k) priorityQueue.enqueue(new Freq(key, treeMap.get(key))); else if (treeMap.get(key) > priorityQueue.getFront().freq) { priorityQueue.dequeue(); priorityQueue.enqueue(new Freq(key, treeMap.get(key))); } } LinkedList<Integer> result = new LinkedList<Integer>(); while (!priorityQueue.isEmpty()) result.add(priorityQueue.dequeue().e); return result; } public static void main(String[] args) { int[] testData = {4,1,-1,2,-1,2,3};//{3,0,1,0}; Solution solution = new Solution(); System.out.println(solution.topKFrequent(testData, 2)); } }
{ "pile_set_name": "Github" }
/************************************************************************** * * Copyright 2008-2010 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #include "pipe/p_compiler.h" #include "util/u_memory.h" #include "util/u_string.h" #include "util/format/u_format.h" #include "tgsi/tgsi_dump.h" #include <inttypes.h> #include "u_dump.h" /* * Dump primitives */ static inline void util_stream_writef(FILE *stream, const char *format, ...) { static char buf[1024]; unsigned len; va_list ap; va_start(ap, format); len = vsnprintf(buf, sizeof(buf), format, ap); va_end(ap); fwrite(buf, len, 1, stream); } static void util_dump_bool(FILE *stream, int value) { util_stream_writef(stream, "%c", value ? '1' : '0'); } static void util_dump_int(FILE *stream, long long int value) { util_stream_writef(stream, "%lli", value); } static void util_dump_uint(FILE *stream, long long unsigned value) { util_stream_writef(stream, "%llu", value); } static void util_dump_float(FILE *stream, double value) { util_stream_writef(stream, "%g", value); } void util_dump_ns(FILE *f, uint64_t time) { uint64_t secs = time / (1000*1000*1000); unsigned usecs = (time % (1000*1000*1000)) / 1000; fprintf(f, "%"PRIu64".%06us", secs, usecs); } static void util_dump_string(FILE *stream, const char *str) { fputs("\"", stream); fputs(str, stream); fputs("\"", stream); } static void util_dump_enum(FILE *stream, const char *value) { fputs(value, stream); } static void util_dump_array_begin(FILE *stream) { fputs("{", stream); } static void util_dump_array_end(FILE *stream) { fputs("}", stream); } static void util_dump_elem_begin(UNUSED FILE *stream) { } static void util_dump_elem_end(FILE *stream) { fputs(", ", stream); } static void util_dump_struct_begin(FILE *stream, UNUSED const char *name) { fputs("{", stream); } static void util_dump_struct_end(FILE *stream) { fputs("}", stream); } static void util_dump_member_begin(FILE *stream, const char *name) { util_stream_writef(stream, "%s = ", name); } static void util_dump_member_end(FILE *stream) { fputs(", ", stream); } static void util_dump_null(FILE *stream) { fputs("NULL", stream); } void util_dump_ptr(FILE *stream, const void *value) { if(value) util_stream_writef(stream, "%p", value); else util_dump_null(stream); } /* * Code saving macros. */ #define util_dump_arg(_stream, _type, _arg) \ do { \ util_dump_arg_begin(_stream, #_arg); \ util_dump_##_type(_stream, _arg); \ util_dump_arg_end(_stream); \ } while(0) #define util_dump_ret(_stream, _type, _arg) \ do { \ util_dump_ret_begin(_stream); \ util_dump_##_type(_stream, _arg); \ util_dump_ret_end(_stream); \ } while(0) #define util_dump_array(_stream, _type, _obj, _size) \ do { \ size_t idx; \ util_dump_array_begin(_stream); \ for(idx = 0; idx < (_size); ++idx) { \ util_dump_elem_begin(_stream); \ util_dump_##_type(_stream, (_obj)[idx]); \ util_dump_elem_end(_stream); \ } \ util_dump_array_end(_stream); \ } while(0) #define util_dump_struct_array(_stream, _type, _obj, _size) \ do { \ size_t idx; \ util_dump_array_begin(_stream); \ for(idx = 0; idx < (_size); ++idx) { \ util_dump_elem_begin(_stream); \ util_dump_##_type(_stream, &(_obj)[idx]); \ util_dump_elem_end(_stream); \ } \ util_dump_array_end(_stream); \ } while(0) #define util_dump_member(_stream, _type, _obj, _member) \ do { \ util_dump_member_begin(_stream, #_member); \ util_dump_##_type(_stream, (_obj)->_member); \ util_dump_member_end(_stream); \ } while(0) #define util_dump_arg_array(_stream, _type, _arg, _size) \ do { \ util_dump_arg_begin(_stream, #_arg); \ util_dump_array(_stream, _type, _arg, _size); \ util_dump_arg_end(_stream); \ } while(0) #define util_dump_member_array(_stream, _type, _obj, _member) \ do { \ util_dump_member_begin(_stream, #_member); \ util_dump_array(_stream, _type, (_obj)->_member, sizeof((_obj)->_member)/sizeof((_obj)->_member[0])); \ util_dump_member_end(_stream); \ } while(0) /* * Wrappers for enum -> string dumpers. */ static void util_dump_format(FILE *stream, enum pipe_format format) { util_dump_enum(stream, util_format_name(format)); } static void util_dump_enum_blend_factor(FILE *stream, unsigned value) { util_dump_enum(stream, util_str_blend_factor(value, TRUE)); } static void util_dump_enum_blend_func(FILE *stream, unsigned value) { util_dump_enum(stream, util_str_blend_func(value, TRUE)); } static void util_dump_enum_func(FILE *stream, unsigned value) { util_dump_enum(stream, util_str_func(value, TRUE)); } static void util_dump_enum_prim_mode(FILE *stream, unsigned value) { util_dump_enum(stream, util_str_prim_mode(value, TRUE)); } static void util_dump_enum_tex_target(FILE *stream, unsigned value) { util_dump_enum(stream, util_str_tex_target(value, TRUE)); } static void util_dump_enum_tex_filter(FILE *stream, unsigned value) { util_dump_enum(stream, util_str_tex_filter(value, TRUE)); } static void util_dump_enum_tex_mipfilter(FILE *stream, unsigned value) { util_dump_enum(stream, util_str_tex_mipfilter(value, TRUE)); } static void util_dump_enum_tex_wrap(FILE *stream, unsigned value) { util_dump_enum(stream, util_str_tex_wrap(value, TRUE)); } static void util_dump_enum_stencil_op(FILE *stream, unsigned value) { util_dump_enum(stream, util_str_stencil_op(value, TRUE)); } /* * Public functions */ void util_dump_resource(FILE *stream, const struct pipe_resource *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_resource"); util_dump_member(stream, enum_tex_target, state, target); util_dump_member(stream, format, state, format); util_dump_member(stream, uint, state, width0); util_dump_member(stream, uint, state, height0); util_dump_member(stream, uint, state, depth0); util_dump_member(stream, uint, state, array_size); util_dump_member(stream, uint, state, last_level); util_dump_member(stream, uint, state, nr_samples); util_dump_member(stream, uint, state, nr_storage_samples); util_dump_member(stream, uint, state, usage); util_dump_member(stream, uint, state, bind); util_dump_member(stream, uint, state, flags); util_dump_struct_end(stream); } void util_dump_rasterizer_state(FILE *stream, const struct pipe_rasterizer_state *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_rasterizer_state"); util_dump_member(stream, bool, state, flatshade); util_dump_member(stream, bool, state, light_twoside); util_dump_member(stream, bool, state, clamp_vertex_color); util_dump_member(stream, bool, state, clamp_fragment_color); util_dump_member(stream, uint, state, front_ccw); util_dump_member(stream, uint, state, cull_face); util_dump_member(stream, uint, state, fill_front); util_dump_member(stream, uint, state, fill_back); util_dump_member(stream, bool, state, offset_point); util_dump_member(stream, bool, state, offset_line); util_dump_member(stream, bool, state, offset_tri); util_dump_member(stream, bool, state, scissor); util_dump_member(stream, bool, state, poly_smooth); util_dump_member(stream, bool, state, poly_stipple_enable); util_dump_member(stream, bool, state, point_smooth); util_dump_member(stream, uint, state, sprite_coord_enable); util_dump_member(stream, bool, state, sprite_coord_mode); util_dump_member(stream, bool, state, point_quad_rasterization); util_dump_member(stream, bool, state, point_tri_clip); util_dump_member(stream, bool, state, point_size_per_vertex); util_dump_member(stream, bool, state, multisample); util_dump_member(stream, bool, state, line_smooth); util_dump_member(stream, bool, state, line_stipple_enable); util_dump_member(stream, uint, state, line_stipple_factor); util_dump_member(stream, uint, state, line_stipple_pattern); util_dump_member(stream, bool, state, line_last_pixel); util_dump_member(stream, bool, state, flatshade_first); util_dump_member(stream, bool, state, half_pixel_center); util_dump_member(stream, bool, state, bottom_edge_rule); util_dump_member(stream, bool, state, rasterizer_discard); util_dump_member(stream, bool, state, depth_clip_near); util_dump_member(stream, bool, state, depth_clip_far); util_dump_member(stream, bool, state, clip_halfz); util_dump_member(stream, uint, state, clip_plane_enable); util_dump_member(stream, float, state, line_width); util_dump_member(stream, float, state, point_size); util_dump_member(stream, float, state, offset_units); util_dump_member(stream, float, state, offset_scale); util_dump_member(stream, float, state, offset_clamp); util_dump_struct_end(stream); } void util_dump_poly_stipple(FILE *stream, const struct pipe_poly_stipple *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_poly_stipple"); util_dump_member_begin(stream, "stipple"); util_dump_member_array(stream, uint, state, stipple); util_dump_member_end(stream); util_dump_struct_end(stream); } void util_dump_viewport_state(FILE *stream, const struct pipe_viewport_state *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_viewport_state"); util_dump_member_array(stream, float, state, scale); util_dump_member_array(stream, float, state, translate); util_dump_struct_end(stream); } void util_dump_scissor_state(FILE *stream, const struct pipe_scissor_state *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_scissor_state"); util_dump_member(stream, uint, state, minx); util_dump_member(stream, uint, state, miny); util_dump_member(stream, uint, state, maxx); util_dump_member(stream, uint, state, maxy); util_dump_struct_end(stream); } void util_dump_clip_state(FILE *stream, const struct pipe_clip_state *state) { unsigned i; if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_clip_state"); util_dump_member_begin(stream, "ucp"); util_dump_array_begin(stream); for(i = 0; i < PIPE_MAX_CLIP_PLANES; ++i) { util_dump_elem_begin(stream); util_dump_array(stream, float, state->ucp[i], 4); util_dump_elem_end(stream); } util_dump_array_end(stream); util_dump_member_end(stream); util_dump_struct_end(stream); } void util_dump_shader_state(FILE *stream, const struct pipe_shader_state *state) { unsigned i; if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_shader_state"); if (state->type == PIPE_SHADER_IR_TGSI) { util_dump_member_begin(stream, "tokens"); fprintf(stream, "\"\n"); tgsi_dump_to_file(state->tokens, 0, stream); fprintf(stream, "\""); util_dump_member_end(stream); } if (state->stream_output.num_outputs) { util_dump_member_begin(stream, "stream_output"); util_dump_struct_begin(stream, "pipe_stream_output_info"); util_dump_member(stream, uint, &state->stream_output, num_outputs); util_dump_array(stream, uint, state->stream_output.stride, ARRAY_SIZE(state->stream_output.stride)); util_dump_array_begin(stream); for(i = 0; i < state->stream_output.num_outputs; ++i) { util_dump_elem_begin(stream); util_dump_struct_begin(stream, ""); /* anonymous */ util_dump_member(stream, uint, &state->stream_output.output[i], register_index); util_dump_member(stream, uint, &state->stream_output.output[i], start_component); util_dump_member(stream, uint, &state->stream_output.output[i], num_components); util_dump_member(stream, uint, &state->stream_output.output[i], output_buffer); util_dump_struct_end(stream); util_dump_elem_end(stream); } util_dump_array_end(stream); util_dump_struct_end(stream); util_dump_member_end(stream); } util_dump_struct_end(stream); } void util_dump_depth_stencil_alpha_state(FILE *stream, const struct pipe_depth_stencil_alpha_state *state) { unsigned i; if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_depth_stencil_alpha_state"); util_dump_member_begin(stream, "depth"); util_dump_struct_begin(stream, "pipe_depth_state"); util_dump_member(stream, bool, &state->depth, enabled); if (state->depth.enabled) { util_dump_member(stream, bool, &state->depth, writemask); util_dump_member(stream, enum_func, &state->depth, func); } util_dump_struct_end(stream); util_dump_member_end(stream); util_dump_member_begin(stream, "stencil"); util_dump_array_begin(stream); for(i = 0; i < ARRAY_SIZE(state->stencil); ++i) { util_dump_elem_begin(stream); util_dump_struct_begin(stream, "pipe_stencil_state"); util_dump_member(stream, bool, &state->stencil[i], enabled); if (state->stencil[i].enabled) { util_dump_member(stream, enum_func, &state->stencil[i], func); util_dump_member(stream, enum_stencil_op, &state->stencil[i], fail_op); util_dump_member(stream, enum_stencil_op, &state->stencil[i], zpass_op); util_dump_member(stream, enum_stencil_op, &state->stencil[i], zfail_op); util_dump_member(stream, uint, &state->stencil[i], valuemask); util_dump_member(stream, uint, &state->stencil[i], writemask); } util_dump_struct_end(stream); util_dump_elem_end(stream); } util_dump_array_end(stream); util_dump_member_end(stream); util_dump_member_begin(stream, "alpha"); util_dump_struct_begin(stream, "pipe_alpha_state"); util_dump_member(stream, bool, &state->alpha, enabled); if (state->alpha.enabled) { util_dump_member(stream, enum_func, &state->alpha, func); util_dump_member(stream, float, &state->alpha, ref_value); } util_dump_struct_end(stream); util_dump_member_end(stream); util_dump_struct_end(stream); } void util_dump_rt_blend_state(FILE *stream, const struct pipe_rt_blend_state *state) { util_dump_struct_begin(stream, "pipe_rt_blend_state"); util_dump_member(stream, uint, state, blend_enable); if (state->blend_enable) { util_dump_member(stream, enum_blend_func, state, rgb_func); util_dump_member(stream, enum_blend_factor, state, rgb_src_factor); util_dump_member(stream, enum_blend_factor, state, rgb_dst_factor); util_dump_member(stream, enum_blend_func, state, alpha_func); util_dump_member(stream, enum_blend_factor, state, alpha_src_factor); util_dump_member(stream, enum_blend_factor, state, alpha_dst_factor); } util_dump_member(stream, uint, state, colormask); util_dump_struct_end(stream); } void util_dump_blend_state(FILE *stream, const struct pipe_blend_state *state) { unsigned valid_entries = 1; if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_blend_state"); util_dump_member(stream, bool, state, dither); util_dump_member(stream, bool, state, alpha_to_coverage); util_dump_member(stream, bool, state, alpha_to_one); util_dump_member(stream, uint, state, max_rt); util_dump_member(stream, bool, state, logicop_enable); if (state->logicop_enable) { util_dump_member(stream, enum_func, state, logicop_func); } else { util_dump_member(stream, bool, state, independent_blend_enable); util_dump_member_begin(stream, "rt"); if (state->independent_blend_enable) valid_entries = state->max_rt + 1; util_dump_struct_array(stream, rt_blend_state, state->rt, valid_entries); util_dump_member_end(stream); } util_dump_struct_end(stream); } void util_dump_blend_color(FILE *stream, const struct pipe_blend_color *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_blend_color"); util_dump_member_array(stream, float, state, color); util_dump_struct_end(stream); } void util_dump_stencil_ref(FILE *stream, const struct pipe_stencil_ref *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_stencil_ref"); util_dump_member_array(stream, uint, state, ref_value); util_dump_struct_end(stream); } void util_dump_framebuffer_state(FILE *stream, const struct pipe_framebuffer_state *state) { util_dump_struct_begin(stream, "pipe_framebuffer_state"); util_dump_member(stream, uint, state, width); util_dump_member(stream, uint, state, height); util_dump_member(stream, uint, state, samples); util_dump_member(stream, uint, state, layers); util_dump_member(stream, uint, state, nr_cbufs); util_dump_member_array(stream, ptr, state, cbufs); util_dump_member(stream, ptr, state, zsbuf); util_dump_struct_end(stream); } void util_dump_sampler_state(FILE *stream, const struct pipe_sampler_state *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_sampler_state"); util_dump_member(stream, enum_tex_wrap, state, wrap_s); util_dump_member(stream, enum_tex_wrap, state, wrap_t); util_dump_member(stream, enum_tex_wrap, state, wrap_r); util_dump_member(stream, enum_tex_filter, state, min_img_filter); util_dump_member(stream, enum_tex_mipfilter, state, min_mip_filter); util_dump_member(stream, enum_tex_filter, state, mag_img_filter); util_dump_member(stream, uint, state, compare_mode); util_dump_member(stream, enum_func, state, compare_func); util_dump_member(stream, bool, state, normalized_coords); util_dump_member(stream, uint, state, max_anisotropy); util_dump_member(stream, bool, state, seamless_cube_map); util_dump_member(stream, float, state, lod_bias); util_dump_member(stream, float, state, min_lod); util_dump_member(stream, float, state, max_lod); util_dump_member_array(stream, float, state, border_color.f); util_dump_struct_end(stream); } void util_dump_surface(FILE *stream, const struct pipe_surface *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_surface"); util_dump_member(stream, format, state, format); util_dump_member(stream, uint, state, width); util_dump_member(stream, uint, state, height); util_dump_member(stream, ptr, state, texture); util_dump_member(stream, uint, state, u.tex.level); util_dump_member(stream, uint, state, u.tex.first_layer); util_dump_member(stream, uint, state, u.tex.last_layer); util_dump_struct_end(stream); } void util_dump_image_view(FILE *stream, const struct pipe_image_view *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_image_view"); util_dump_member(stream, ptr, state, resource); util_dump_member(stream, format, state, format); if (state->resource->target == PIPE_BUFFER) { util_dump_member(stream, uint, state, u.buf.offset); util_dump_member(stream, uint, state, u.buf.size); } else { util_dump_member(stream, uint, state, u.tex.first_layer); util_dump_member(stream, uint, state, u.tex.last_layer); util_dump_member(stream, uint, state, u.tex.level); } util_dump_struct_end(stream); } void util_dump_shader_buffer(FILE *stream, const struct pipe_shader_buffer *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_shader_buffer"); util_dump_member(stream, ptr, state, buffer); util_dump_member(stream, uint, state, buffer_offset); util_dump_member(stream, uint, state, buffer_size); util_dump_struct_end(stream); } void util_dump_sampler_view(FILE *stream, const struct pipe_sampler_view *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_sampler_view"); util_dump_member(stream, enum_tex_target, state, target); util_dump_member(stream, format, state, format); util_dump_member(stream, ptr, state, texture); if (state->target == PIPE_BUFFER) { util_dump_member(stream, uint, state, u.buf.offset); util_dump_member(stream, uint, state, u.buf.size); } else { util_dump_member(stream, uint, state, u.tex.first_layer); util_dump_member(stream, uint, state, u.tex.last_layer); util_dump_member(stream, uint, state, u.tex.first_level); util_dump_member(stream, uint, state, u.tex.last_level); } util_dump_member(stream, uint, state, swizzle_r); util_dump_member(stream, uint, state, swizzle_g); util_dump_member(stream, uint, state, swizzle_b); util_dump_member(stream, uint, state, swizzle_a); util_dump_struct_end(stream); } void util_dump_transfer(FILE *stream, const struct pipe_transfer *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_transfer"); util_dump_member(stream, ptr, state, resource); util_dump_member(stream, uint, state, level); util_dump_member(stream, transfer_usage, state, usage); util_dump_member_begin(stream, "box"); util_dump_box(stream, &state->box); util_dump_member_end(stream); util_dump_member(stream, uint, state, stride); util_dump_member(stream, uint, state, layer_stride); util_dump_struct_end(stream); } void util_dump_constant_buffer(FILE *stream, const struct pipe_constant_buffer *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_constant_buffer"); util_dump_member(stream, ptr, state, buffer); util_dump_member(stream, uint, state, buffer_offset); util_dump_member(stream, uint, state, buffer_size); util_dump_member(stream, ptr, state, user_buffer); util_dump_struct_end(stream); } void util_dump_vertex_buffer(FILE *stream, const struct pipe_vertex_buffer *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_vertex_buffer"); util_dump_member(stream, uint, state, stride); util_dump_member(stream, bool, state, is_user_buffer); util_dump_member(stream, uint, state, buffer_offset); util_dump_member(stream, ptr, state, buffer.resource); util_dump_struct_end(stream); } void util_dump_vertex_element(FILE *stream, const struct pipe_vertex_element *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_vertex_element"); util_dump_member(stream, uint, state, src_offset); util_dump_member(stream, uint, state, instance_divisor); util_dump_member(stream, uint, state, vertex_buffer_index); util_dump_member(stream, format, state, src_format); util_dump_struct_end(stream); } void util_dump_stream_output_target(FILE *stream, const struct pipe_stream_output_target *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_stream_output_target"); util_dump_member(stream, ptr, state, buffer); util_dump_member(stream, uint, state, buffer_offset); util_dump_member(stream, uint, state, buffer_size); util_dump_struct_end(stream); } void util_dump_draw_info(FILE *stream, const struct pipe_draw_info *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_draw_info"); util_dump_member(stream, uint, state, index_size); util_dump_member(stream, uint, state, has_user_indices); util_dump_member(stream, enum_prim_mode, state, mode); util_dump_member(stream, uint, state, start); util_dump_member(stream, uint, state, count); util_dump_member(stream, uint, state, start_instance); util_dump_member(stream, uint, state, instance_count); util_dump_member(stream, uint, state, drawid); util_dump_member(stream, uint, state, vertices_per_patch); util_dump_member(stream, int, state, index_bias); util_dump_member(stream, uint, state, min_index); util_dump_member(stream, uint, state, max_index); util_dump_member(stream, bool, state, primitive_restart); if (state->primitive_restart) util_dump_member(stream, uint, state, restart_index); if (state->index_size) { if (state->has_user_indices) util_dump_member(stream, ptr, state, index.user); else util_dump_member(stream, ptr, state, index.resource); } util_dump_member(stream, ptr, state, count_from_stream_output); if (!state->indirect) { util_dump_member(stream, ptr, state, indirect); } else { util_dump_member(stream, uint, state, indirect->offset); util_dump_member(stream, uint, state, indirect->stride); util_dump_member(stream, uint, state, indirect->draw_count); util_dump_member(stream, uint, state, indirect->indirect_draw_count_offset); util_dump_member(stream, ptr, state, indirect->buffer); util_dump_member(stream, ptr, state, indirect->indirect_draw_count); } util_dump_struct_end(stream); } void util_dump_grid_info(FILE *stream, const struct pipe_grid_info *state) { if (!state) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_grid_info"); util_dump_member(stream, uint, state, pc); util_dump_member(stream, ptr, state, input); util_dump_member(stream, uint, state, work_dim); util_dump_member_begin(stream, "block"); util_dump_array(stream, uint, state->block, ARRAY_SIZE(state->block)); util_dump_member_end(stream); util_dump_member_begin(stream, "grid"); util_dump_array(stream, uint, state->grid, ARRAY_SIZE(state->grid)); util_dump_member_end(stream); util_dump_member(stream, ptr, state, indirect); util_dump_member(stream, uint, state, indirect_offset); util_dump_struct_end(stream); } void util_dump_box(FILE *stream, const struct pipe_box *box) { if (!box) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_box"); util_dump_member(stream, int, box, x); util_dump_member(stream, int, box, y); util_dump_member(stream, int, box, z); util_dump_member(stream, int, box, width); util_dump_member(stream, int, box, height); util_dump_member(stream, int, box, depth); util_dump_struct_end(stream); } void util_dump_blit_info(FILE *stream, const struct pipe_blit_info *info) { char mask[7]; if (!info) { util_dump_null(stream); return; } util_dump_struct_begin(stream, "pipe_blit_info"); util_dump_member_begin(stream, "dst"); util_dump_struct_begin(stream, "dst"); util_dump_member(stream, ptr, &info->dst, resource); util_dump_member(stream, uint, &info->dst, level); util_dump_member(stream, format, &info->dst, format); util_dump_member_begin(stream, "box"); util_dump_box(stream, &info->dst.box); util_dump_member_end(stream); util_dump_struct_end(stream); util_dump_member_end(stream); util_dump_member_begin(stream, "src"); util_dump_struct_begin(stream, "src"); util_dump_member(stream, ptr, &info->src, resource); util_dump_member(stream, uint, &info->src, level); util_dump_member(stream, format, &info->src, format); util_dump_member_begin(stream, "box"); util_dump_box(stream, &info->src.box); util_dump_member_end(stream); util_dump_struct_end(stream); util_dump_member_end(stream); mask[0] = (info->mask & PIPE_MASK_R) ? 'R' : '-'; mask[1] = (info->mask & PIPE_MASK_G) ? 'G' : '-'; mask[2] = (info->mask & PIPE_MASK_B) ? 'B' : '-'; mask[3] = (info->mask & PIPE_MASK_A) ? 'A' : '-'; mask[4] = (info->mask & PIPE_MASK_Z) ? 'Z' : '-'; mask[5] = (info->mask & PIPE_MASK_S) ? 'S' : '-'; mask[6] = 0; util_dump_member_begin(stream, "mask"); util_dump_string(stream, mask); util_dump_member_end(stream); util_dump_member(stream, enum_tex_filter, info, filter); util_dump_member(stream, bool, info, scissor_enable); util_dump_member_begin(stream, "scissor"); util_dump_scissor_state(stream, &info->scissor); util_dump_member_end(stream); util_dump_member(stream, bool, info, render_condition_enable); util_dump_struct_end(stream); }
{ "pile_set_name": "Github" }
((output (((f.ml (1 0) (1 25)) (paragraph (((f.ml (1 0) (1 25)) (reference (field baz (type bar (root Foo unknown))) ()))))))) (warnings ()))
{ "pile_set_name": "Github" }
# -*- coding:utf-8 -*- from flask import request, render_template, json import config import os, requests, re from app import MysqlDB, MongoDB from app import decorators from app.admin import admin from ..drive import models from ..drive import logic from ..task import models as taskModels from ..menu import models as menuModels from app import common @admin.route('/drive/list', methods=['GET']) @admin.route('/drive/list/') # 设置分页 @decorators.login_require def list(): isRunning = common.isRunning("cuteTask") # 检测是否有更新任务 if request.args.get('page'): data_list = models.drive.all() json_data = {"code": 0, "msg": "", "count": 0, "data": []} if data_list: for result in data_list: json_data["count"] = json_data["count"]+1 drive_number = len(models.drive_list.all(result.id)) syn_task_status = logic.isSynTask(result.id) if syn_task_status: syn_task_status = "<button class='layui-btn layui-btn-normal layui-btn-xs' lay-event='syn_detail' data-id='1'>正在运行同步</button>" else: syn_task_status = "<button class='layui-btn layui-btn-primary layui-btn-xs'>暂无同步进程</button>" json_data["data"].append( {"id": result.id, "title": result.title, "description": result.description, "drive_number":drive_number, "syn_task_status":syn_task_status, "update_time":str(result.update_time), "create_time": str(result.create_time)}) return json.dumps(json_data) else: return render_template('admin/drive/list.html', top_nav='drive', activity_nav='list', isRunning=isRunning) @admin.route('/drive/syn_detail/<int:id>', methods=['GET', 'POST']) @decorators.login_require def syn_detail(id): collection = MongoDB.db["log"] data = collection.find({"drive_id": str(id), "type":"syn"}) return render_template('admin/drive/syn_detail.html', top_nav='drive', activity_nav='list', dirve_id=id, data=data) @admin.route('/drive/edit/<int:id>', methods=['GET', 'POST']) # 新增/编辑 @decorators.login_require def edit(id): if request.method == 'GET': if id: data_list = models.drive.find_by_id(id) result = {} result["id"] = data_list.id result["title"] = data_list.title result["description"] = data_list.description else: result = { 'id': '0' , 'title': '' , 'description': '' } return render_template('admin/drive/edit.html', top_nav='drive', activity_nav='edit', data=result) else: id = request.form['id'] title = request.form['title'] description = request.form['description'] if id != '0': models.drive.update({"id": id, "title": title, "description": description}) else: # 初始化role 并插入数据库 role = models.drive(title=title, description=description) MysqlDB.session.add(role) MysqlDB.session.flush() role_id = role.id MysqlDB.session.commit() menu_role = menuModels.menu(title=title, url='/drive/?drive='+str(role_id), pid=0, postion=0, type=1, type_name=role_id, activate=0, sort=0, status=1) MysqlDB.session.add(menu_role) MysqlDB.session.flush() MysqlDB.session.commit() return json.dumps({"code": 0, "msg": "完成!"}) @admin.route('/drive/drive_del/<int:id>', methods=['GET', 'POST']) # 新增/编辑 @decorators.login_require def drive_del(id): res = models.drive.find_by_id(id) models.drive.deldata(id) models.drive_list.deldata_by_drive_id(id) menuModels.menu.deldata_by_title_type(res.title, 1) return json.dumps({"code": 0, "msg": "完成!"}) @admin.route('/drive/disk_list/<int:id>', methods=['GET']) @admin.route('/drive/disk_list/<int:id>/') # 设置分页 @decorators.login_require def disk_list(id): if request.args.get('page'): data_list = models.drive_list.all(id) json_data = {"code": 0, "msg": "", "count": 0, "data": []} if data_list: for result in data_list: json_data["count"] = json_data["count"]+1 if result.chief == "1": result.chief = "主盘" else: result.chief = "从盘" cache_count = models.mongodb_count(result.id) json_data["data"].append( {"id": result.id, "title": result.title, "chief":result.chief, "client_id": result.client_id, "client_secret": result.client_secret, "count": cache_count, "update_time":str(result.update_time), "create_time": str(result.create_time)}) return json.dumps(json_data) else: data = models.drive.find_by_id(id) ifSynTask = logic.ifSynTask(id) isSynTask = logic.isSynTask(id) return render_template('admin/drive/disk_list.html', top_nav='drive', activity_nav='list', data=data, isSynTask=isSynTask, ifSynTask=ifSynTask) @admin.route('/drive/disk_edit/<int:drive_id>/<int:id>', methods=['GET', 'POST']) # 新增/编辑 @decorators.login_require def disk_edit(drive_id, id): if request.method == 'GET': if id: data_list = models.drive_list.find_by_id(id) result = {} result["drive_id"] = data_list.drive_id result["id"] = data_list.id result["title"] = data_list.title result["client_id"] = data_list.client_id result["client_secret"] = data_list.client_secret result["chief"] = data_list.chief else: result = { 'drive_id': drive_id ,'id': '0' , 'title': '' , 'client_id': '' , 'client_secret': '' , 'code': '' , 'chief': '0' } return render_template('admin/drive/disk_edit.html', top_nav='drive', activity_nav='edit', data=result) else: drive_id = request.form['drive_id'] id = request.form['id'] title = request.form['title'] client_id = request.form['client_id'] client_secret = request.form['client_secret'] code = request.form['code'] chief = request.form['chief'] if id != '0': if code: url = config.BaseAuthUrl + '/common/oauth2/v2.0/token' redirect_url = "http://127.0.0.1/" AuthData = 'client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}&code={code}&grant_type=authorization_code' data = AuthData.format(client_id=client_id, redirect_uri=redirect_url, client_secret=client_secret, code=code) headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'ISV|CuteOne|CuteOne/1.0' } res = requests.post(url, data=data, headers=headers) get_res = json.loads(res.text) if 'error' in get_res.keys(): return json.dumps({"code": 1, "msg": "Error!"}) else: token = json.dumps(res.text) models.drive_list.update({"id": id, "title": title, "client_id": client_id, "client_secret": client_secret, "chief":chief, "token":token}) return json.dumps({"code": 0, "msg": "完成!"}) else: models.drive_list.update( {"id": id, "title": title, "client_id": client_id, "client_secret": client_secret, "chief": chief}) return json.dumps({"code": 0, "msg": "完成!"}) else: url = config.BaseAuthUrl + '/common/oauth2/v2.0/token' redirect_url = "http://127.0.0.1/" AuthData = 'client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}&code={code}&grant_type=authorization_code' data = AuthData.format(client_id=client_id, redirect_uri=redirect_url, client_secret=client_secret, code=code) headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'ISV|CuteOne|CuteOne/1.0' } res = requests.post(url,data=data,headers=headers) get_res = json.loads(res.text) if 'error' in get_res.keys(): return json.dumps({"code": 1, "msg": "Error!"}) else: token = json.dumps(res.text) # 初始化role 并插入数据库 role = models.drive_list(title=title, drive_id=drive_id, client_id=client_id, client_secret=client_secret, token=token, chief=chief) MysqlDB.session.add(role) MysqlDB.session.flush() MysqlDB.session.commit() return json.dumps({"code": 0, "msg": "完成!"}) @admin.route('/drive/file_uploads_big/<int:drive_id>', methods=['GET']) # 大文件上传 @admin.route('/drive/file_uploads_big/<int:drive_id>/', methods=['GET']) @decorators.login_require def file_uploads_big(drive_id): path = request.args.get('path') return render_template('admin/drive/file_uploads_big.html', top_nav='drive', activity_nav='file_uploads', drive_id=drive_id, path=path) @admin.route('/drive/file_uploads_small/<int:drive_id>', methods=['GET']) # 小文件上传 @admin.route('/drive/file_uploads_small/<int:drive_id>/', methods=['GET']) @decorators.login_require def file_uploads_small(drive_id): path = request.args.get('path') return render_template('admin/drive/file_uploads_small.html', top_nav='drive', activity_nav='file_uploads', drive_id=drive_id, path=path) @admin.route('/drive/file_uploads', methods=['POST']) @decorators.login_require def file_uploads(): md5value = request.form['md5value'] chunk = request.form['chunk'] file = request.files['file'] file_path = os.getcwd()+"/temp_uploads/"+ md5value isExists = os.path.exists(file_path) if not isExists: # 如果不存在则创建目录 os.makedirs(file_path) file.save(file_path + "/" + chunk) return json.dumps({}) @admin.route('/drive/file_uploads_check', methods=['GET', 'POST']) @decorators.login_require def file_uploads_check(): md5 = request.form['md5'] # 通过MD5唯一标识找到缓存文件 file_path = os.getcwd()+"/temp_uploads/" + md5 if os.path.exists(file_path): block_info = os.listdir(file_path) return json.dumps({'block_info': block_info}) else: return json.dumps({}) @admin.route('/drive/file_uploads_success', methods=['GET', 'POST']) @decorators.login_require def file_uploads_success(): drive_id = request.form['drive_id'] path = request.form['path'] md5 = request.form['md5'] fileName = request.form['fileName'] target_filename = os.getcwd()+"/temp_uploads/" + md5 # 获取上传文件的文件名 ok_file = os.getcwd()+"/temp_uploads/" + drive_id + "/" + fileName if not os.path.exists(os.getcwd()+"/temp_uploads/" + drive_id): # 如果不存在则创建目录 os.makedirs(os.getcwd()+"/temp_uploads/" + drive_id) chunk = 0 with open(ok_file, 'wb') as target_file: # 创建新文件 while True: try: filename = target_filename + "/" + str(chunk) source_file = open(filename, 'rb') # 按序打开每个分片 target_file.write(source_file.read()) # 读取分片内容写入新文件 source_file.close() except IOError: break chunk += 1 os.remove(filename) # 删除该分片 if os.path.exists(target_filename): os.rmdir(target_filename) # 删除文件夹 # # 初始化role 并插入数据库 role = taskModels.uploads_list(drive_id=drive_id, file_name=fileName,path=path, type='uploads', status=0) MysqlDB.session.add(role) MysqlDB.session.flush() MysqlDB.session.commit() # 推送到上传任务 logic.pull_uploads(role.id, drive_id, fileName, path) return json.dumps({"code": 0, "msg": "完成!"}) @admin.route('/drive/disk_del/<int:id>', methods=['GET', 'POST']) # 新增/编辑 @decorators.login_require def disk_del(id): models.drive_list.deldata_by_id(id) return json.dumps({"code": 0, "msg": "完成!"}) @admin.route('/drive/update_cache', methods=['POST']) # 更新MongoDB缓存 @decorators.login_require def update_cache(): drive_id = request.form['id'] type = request.form['type'] logic.update_cache(drive_id, type) return json.dumps({"code": 0, "msg": "完成!"}) @admin.route('/drive/files/<int:id>', methods=['GET']) @admin.route('/drive/files/<int:id>/', methods=['GET']) @decorators.login_require def files(id): drive_info = models.drive_list.find_by_id(id) drive_id = drive_info.drive_id chief = int(drive_info.chief) uploads_path = request.args.get('path') if request.args.get('path'): path = request.args.get("path") current_url = '/admin/drive/files/' + str(id) + '/?path=' + path else: path = '' current_url = '/admin/drive/files/' + str(id) + '/?path=' data = logic.get_one_file_list(id, path) for i in data["data"]: i["lastModifiedDateTime"] = common.utc_to_local(i["lastModifiedDateTime"]) i["size"] = common.size_cov(i["size"]) data = data["data"] return render_template('admin/drive/files.html', top_nav='drive', activity_nav='edit', chief=chief, id=id, current_url=current_url, drive_id=drive_id, uploads_path=uploads_path, data=data) @admin.route('/drive/folder_create', methods=['POST']) @decorators.login_require def folder_create(): id = request.form['id'] path = request.form['path'] fileName = request.form['fileName'] path = re.findall('\?path=(.*?)', path)[0] logic.folder_create(id, path, fileName) return json.dumps({"code": 0, "msg": "成功!"}) @admin.route('/drive/rename_files', methods=['POST']) @decorators.login_require def rename_files(): id = request.form['id'] fileid = request.form['fileid'] new_name = request.form['new_name'] logic.rename_files(id, fileid, new_name) return json.dumps({"code": 0, "msg": "成功!"}) @admin.route('/drive/delete_files', methods=['POST']) @decorators.login_require def delete_files(): id = request.form['id'] fileid = request.form['fileid'] logic.delete_files(id, fileid) return json.dumps({"code": 0, "msg": "成功!"}) @admin.route('/drive/synStart/<int:id>') @decorators.login_require def synStart(id): drive_id = id collection = MongoDB.db["log"] collection.delete_many({"drive_id": str(drive_id), "type":"syn"}) logic.startSynTask(drive_id) return json.dumps({"code": 0, "msg": "成功!"}) @admin.route('/drive/synContinue/<int:id>') @decorators.login_require def synContinue(id): drive_id = id logic.startSynTask(drive_id) return json.dumps({"code": 0, "msg": "成功!"}) @admin.route('/drive/synReStart/<int:id>') @decorators.login_require def synReStart(id): drive_id = id logic.reStartSynTask(drive_id) return json.dumps({"code": 0, "msg": "成功!"}) @admin.route('/drive/synStop/<int:id>') @decorators.login_require def synStop(id): drive_id = id logic.stopSynTask(drive_id) return json.dumps({"code": 0, "msg": "成功!"})
{ "pile_set_name": "Github" }
#ifndef __ACPI_ACPI_THERMAL_H #define __ACPI_ACPI_THERMAL_H #include <asm/ioctl.h> #define ACPI_THERMAL_MAGIC 's' #define ACPI_THERMAL_GET_TRT_LEN _IOR(ACPI_THERMAL_MAGIC, 1, unsigned long) #define ACPI_THERMAL_GET_ART_LEN _IOR(ACPI_THERMAL_MAGIC, 2, unsigned long) #define ACPI_THERMAL_GET_TRT_COUNT _IOR(ACPI_THERMAL_MAGIC, 3, unsigned long) #define ACPI_THERMAL_GET_ART_COUNT _IOR(ACPI_THERMAL_MAGIC, 4, unsigned long) #define ACPI_THERMAL_GET_TRT _IOR(ACPI_THERMAL_MAGIC, 5, unsigned long) #define ACPI_THERMAL_GET_ART _IOR(ACPI_THERMAL_MAGIC, 6, unsigned long) struct art { acpi_handle source; acpi_handle target; u64 weight; u64 ac0_max; u64 ac1_max; u64 ac2_max; u64 ac3_max; u64 ac4_max; u64 ac5_max; u64 ac6_max; u64 ac7_max; u64 ac8_max; u64 ac9_max; } __packed; struct trt { acpi_handle source; acpi_handle target; u64 influence; u64 sample_period; u64 reverved1; u64 reverved2; u64 reverved3; u64 reverved4; } __packed; #define ACPI_NR_ART_ELEMENTS 13 /* for usrspace */ union art_object { struct { char source_device[8]; /* ACPI single name */ char target_device[8]; /* ACPI single name */ u64 weight; u64 ac0_max_level; u64 ac1_max_level; u64 ac2_max_level; u64 ac3_max_level; u64 ac4_max_level; u64 ac5_max_level; u64 ac6_max_level; u64 ac7_max_level; u64 ac8_max_level; u64 ac9_max_level; }; u64 __data[ACPI_NR_ART_ELEMENTS]; }; union trt_object { struct { char source_device[8]; /* ACPI single name */ char target_device[8]; /* ACPI single name */ u64 influence; u64 sample_period; u64 reserved[4]; }; u64 __data[8]; }; #ifdef __KERNEL__ int acpi_thermal_rel_misc_device_add(acpi_handle handle); int acpi_thermal_rel_misc_device_remove(acpi_handle handle); int acpi_parse_art(acpi_handle handle, int *art_count, struct art **arts, bool create_dev); int acpi_parse_trt(acpi_handle handle, int *trt_count, struct trt **trts, bool create_dev); #endif #endif /* __ACPI_ACPI_THERMAL_H */
{ "pile_set_name": "Github" }
/*! @file Defines `boost::hana::cartesian_product`. @copyright Louis Dionne 2013-2017 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_CARTESIAN_PRODUCT_HPP #define BOOST_HANA_CARTESIAN_PRODUCT_HPP #include <boost/hana/fwd/cartesian_product.hpp> #include <boost/hana/at.hpp> #include <boost/hana/concept/sequence.hpp> #include <boost/hana/config.hpp> #include <boost/hana/core/dispatch.hpp> #include <boost/hana/core/make.hpp> #include <boost/hana/detail/array.hpp> #include <boost/hana/integral_constant.hpp> #include <boost/hana/length.hpp> #include <boost/hana/unpack.hpp> #include <cstddef> #include <utility> BOOST_HANA_NAMESPACE_BEGIN //! @cond template <typename Xs> constexpr auto cartesian_product_t::operator()(Xs&& xs) const { using S = typename hana::tag_of<Xs>::type; using CartesianProduct = BOOST_HANA_DISPATCH_IF( cartesian_product_impl<S>, hana::Sequence<S>::value ); #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS static_assert(hana::Sequence<S>::value, "hana::cartesian_product(xs) requires 'xs' to be a Sequence"); #endif return CartesianProduct::apply(static_cast<Xs&&>(xs)); } //! @endcond namespace detail { template <std::size_t ...Lengths> struct cartesian_product_indices { static constexpr std::size_t total_length() { std::size_t lengths[sizeof...(Lengths)] = {Lengths...}; std::size_t r = 1; for (std::size_t len: lengths) r *= len; return r; } static constexpr std::size_t length = total_length(); static constexpr auto indices_of(std::size_t i) { constexpr std::size_t lengths[sizeof...(Lengths)] = {Lengths...}; constexpr std::size_t n = sizeof...(Lengths); detail::array<std::size_t, n> result{}; for (std::size_t j = n; j--;) { result[j] = i % lengths[j]; i /= lengths[j]; } return result; } template <typename S, std::size_t n, std::size_t ...k, typename ...Xs> static constexpr auto product_element(std::index_sequence<k...>, Xs&& ...xs) { constexpr auto indices = indices_of(n); return hana::make<S>(hana::at_c<indices[k]>(xs)...); } template <typename S, std::size_t ...n, typename ...Xs> static constexpr auto create_product(std::index_sequence<n...>, Xs&& ...xs) { return hana::make<S>(product_element<S, n>( std::make_index_sequence<sizeof...(Xs)>{}, xs... )...); } }; } // Credits: implementation adapted from http://github.com/alexk7/hel. template <typename S, bool condition> struct cartesian_product_impl<S, when<condition>> : default_ { template <typename Xs> static constexpr auto apply(Xs&& xs) { return hana::unpack(static_cast<Xs&&>(xs), cartesian_product_impl{}); } template <typename ...Xs> constexpr auto operator()(Xs&& ...xs) const { using indices = detail::cartesian_product_indices< decltype(hana::length(xs))::value... >; return indices::template create_product<S>( std::make_index_sequence<indices::length>{}, static_cast<Xs&&>(xs)...); } constexpr auto operator()() const { return hana::make<S>(); } }; BOOST_HANA_NAMESPACE_END #endif // !BOOST_HANA_CARTESIAN_PRODUCT_HPP
{ "pile_set_name": "Github" }
/* ioapi.h -- IO base function header for compress/uncompress .zip part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) Modifications for Zip64 support Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) For more info read MiniZip_info.txt */ #include "ioapi.h" namespace cocos2d { voidpf call_zopen64 (const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode) { if (pfilefunc->zfile_func64.zopen64_file != NULL) return (*(pfilefunc->zfile_func64.zopen64_file)) (pfilefunc->zfile_func64.opaque,filename,mode); else { return (*(pfilefunc->zopen32_file))(pfilefunc->zfile_func64.opaque,(const char*)filename,mode); } } long call_zseek64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin) { if (pfilefunc->zfile_func64.zseek64_file != NULL) return (*(pfilefunc->zfile_func64.zseek64_file)) (pfilefunc->zfile_func64.opaque,filestream,offset,origin); else { uLong offsetTruncated = (uLong)offset; if (offsetTruncated != offset) return -1; else return (*(pfilefunc->zseek32_file))(pfilefunc->zfile_func64.opaque,filestream,offsetTruncated,origin); } } ZPOS64_T call_ztell64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream) { if (pfilefunc->zfile_func64.zseek64_file != NULL) return (*(pfilefunc->zfile_func64.ztell64_file)) (pfilefunc->zfile_func64.opaque,filestream); else { uLong tell_uLong = (*(pfilefunc->ztell32_file))(pfilefunc->zfile_func64.opaque,filestream); if ((tell_uLong) == ((uLong)-1)) return (ZPOS64_T)-1; else return tell_uLong; } } void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32) { p_filefunc64_32->zfile_func64.zopen64_file = NULL; p_filefunc64_32->zopen32_file = p_filefunc32->zopen_file; p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file; p_filefunc64_32->zfile_func64.zread_file = p_filefunc32->zread_file; p_filefunc64_32->zfile_func64.zwrite_file = p_filefunc32->zwrite_file; p_filefunc64_32->zfile_func64.ztell64_file = NULL; p_filefunc64_32->zfile_func64.zseek64_file = NULL; p_filefunc64_32->zfile_func64.zclose_file = p_filefunc32->zclose_file; p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file; p_filefunc64_32->zfile_func64.opaque = p_filefunc32->opaque; p_filefunc64_32->zseek32_file = p_filefunc32->zseek_file; p_filefunc64_32->ztell32_file = p_filefunc32->ztell_file; } static voidpf ZCALLBACK fopen_file_func OF((voidpf opaque, const char* filename, int mode)); static uLong ZCALLBACK fread_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size)); static uLong ZCALLBACK fwrite_file_func OF((voidpf opaque, voidpf stream, const void* buf,uLong size)); static ZPOS64_T ZCALLBACK ftell64_file_func OF((voidpf opaque, voidpf stream)); static long ZCALLBACK fseek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)); static int ZCALLBACK fclose_file_func OF((voidpf opaque, voidpf stream)); static int ZCALLBACK ferror_file_func OF((voidpf opaque, voidpf stream)); static voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode) { FILE* file = NULL; const char* mode_fopen = NULL; if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) mode_fopen = "rb"; else if (mode & ZLIB_FILEFUNC_MODE_EXISTING) mode_fopen = "r+b"; else if (mode & ZLIB_FILEFUNC_MODE_CREATE) mode_fopen = "wb"; if ((filename!=NULL) && (mode_fopen != NULL)) file = fopen(filename, mode_fopen); return file; } static voidpf ZCALLBACK fopen64_file_func (voidpf opaque, const void* filename, int mode) { FILE* file = NULL; const char* mode_fopen = NULL; if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) mode_fopen = "rb"; else if (mode & ZLIB_FILEFUNC_MODE_EXISTING) mode_fopen = "r+b"; else if (mode & ZLIB_FILEFUNC_MODE_CREATE) mode_fopen = "wb"; if ((filename!=NULL) && (mode_fopen != NULL)) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE || CC_TARGET_PLATFORM == CC_PLATFORM_BADA) || (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) file = NULL; #else file = fopen64((const char*)filename, mode_fopen); #endif } return file; } static uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size) { uLong ret; ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream); return ret; } static uLong ZCALLBACK fwrite_file_func (voidpf opaque, voidpf stream, const void* buf, uLong size) { uLong ret; ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream); return ret; } static long ZCALLBACK ftell_file_func (voidpf opaque, voidpf stream) { long ret; ret = ftell((FILE *)stream); return ret; } static ZPOS64_T ZCALLBACK ftell64_file_func (voidpf opaque, voidpf stream) { ZPOS64_T ret; #if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE || CC_TARGET_PLATFORM == CC_PLATFORM_BADA) || (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) ret = NULL; #else ret = ftello64((FILE *)stream); #endif return ret; } static long ZCALLBACK fseek_file_func (voidpf opaque, voidpf stream, uLong offset, int origin) { int fseek_origin=0; long ret; switch (origin) { case ZLIB_FILEFUNC_SEEK_CUR : fseek_origin = SEEK_CUR; break; case ZLIB_FILEFUNC_SEEK_END : fseek_origin = SEEK_END; break; case ZLIB_FILEFUNC_SEEK_SET : fseek_origin = SEEK_SET; break; default: return -1; } ret = 0; if (fseek((FILE *)stream, offset, fseek_origin) != 0) ret = -1; return ret; } static long ZCALLBACK fseek64_file_func (voidpf opaque, voidpf stream, ZPOS64_T offset, int origin) { int fseek_origin=0; long ret; switch (origin) { case ZLIB_FILEFUNC_SEEK_CUR : fseek_origin = SEEK_CUR; break; case ZLIB_FILEFUNC_SEEK_END : fseek_origin = SEEK_END; break; case ZLIB_FILEFUNC_SEEK_SET : fseek_origin = SEEK_SET; break; default: return -1; } ret = 0; #if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE || CC_TARGET_PLATFORM == CC_PLATFORM_BADA) || (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) ret = -1; #else if(fseeko64((FILE *)stream, offset, fseek_origin) != 0) ret = -1; #endif return ret; } static int ZCALLBACK fclose_file_func (voidpf opaque, voidpf stream) { int ret; ret = fclose((FILE *)stream); return ret; } static int ZCALLBACK ferror_file_func (voidpf opaque, voidpf stream) { int ret; ret = ferror((FILE *)stream); return ret; } void fill_fopen_filefunc (zlib_filefunc_def* pzlib_filefunc_def) { pzlib_filefunc_def->zopen_file = fopen_file_func; pzlib_filefunc_def->zread_file = fread_file_func; pzlib_filefunc_def->zwrite_file = fwrite_file_func; pzlib_filefunc_def->ztell_file = ftell_file_func; pzlib_filefunc_def->zseek_file = fseek_file_func; pzlib_filefunc_def->zclose_file = fclose_file_func; pzlib_filefunc_def->zerror_file = ferror_file_func; pzlib_filefunc_def->opaque = NULL; } void fill_fopen64_filefunc (zlib_filefunc64_def* pzlib_filefunc_def) { pzlib_filefunc_def->zopen64_file = fopen64_file_func; pzlib_filefunc_def->zread_file = fread_file_func; pzlib_filefunc_def->zwrite_file = fwrite_file_func; pzlib_filefunc_def->ztell64_file = ftell64_file_func; pzlib_filefunc_def->zseek64_file = fseek64_file_func; pzlib_filefunc_def->zclose_file = fclose_file_func; pzlib_filefunc_def->zerror_file = ferror_file_func; pzlib_filefunc_def->opaque = NULL; } } // end of namespace cocos2d
{ "pile_set_name": "Github" }
""" WSGI config for webapp project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'treeherder.config.settings') application = get_wsgi_application()
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <Filter Include="Source Files"> <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> </Filter> <Filter Include="Header Files"> <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> <Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions> </Filter> <Filter Include="Resource Files"> <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions> </Filter> </ItemGroup> <ItemGroup> <ClInclude Include="pch.h"> <Filter>Header Files</Filter> </ClInclude> </ItemGroup> <ItemGroup> <ClCompile Include="pch.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="HandleHijackingMaster.cpp"> <Filter>Source Files</Filter> </ClCompile> </ItemGroup> <ItemGroup> <None Include="README.md" /> </ItemGroup> </Project>
{ "pile_set_name": "Github" }
.set-tag { display: inline-block; .edit-name { width: 276px; .input { width: 258px; } } .add-tag { height: 38px; line-height: 38px; font-size: 14px; display: inline-block; color: #fff; background-color: #008EDC; border: 1px solid #008EDC; padding: 0 16px; } } .set-tag-icon { color: #6f6f6f; } .icon-tag-list { padding: 0 10px; width: 318px; height: 96px; border: 1px solid #dfdfdf; border-top: 0; margin-left: 5px; .icon-tag { float: left; padding: 6px; margin: 12px 8px 0 0; font-size: 12px; border-radius: 4px; background: #f1f3f6; color: #787979; .delete { cursor: pointer; } } }
{ "pile_set_name": "Github" }
import Alert from './Alert' import AlertLink from './AlertLink' export { Alert, AlertLink }
{ "pile_set_name": "Github" }
namespace Machine.Specifications.Sdk { public class ActDelegateAttributeFullName : DelegateAttributeFullName { static readonly string actDelegateAttributeName = typeof(ActDelegateAttribute).FullName; public static implicit operator string(ActDelegateAttributeFullName fullName) { return actDelegateAttributeName; } public override string FullName { get { return this; } } } }
{ "pile_set_name": "Github" }
// Copyright Daniel Wallin, David Abrahams 2005. Use, modification and // distribution is subject to the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef YESNO_050328_HPP #define YESNO_050328_HPP #include <boost/mpl/bool.hpp> namespace boost { namespace parameter { namespace aux { // types used with the "sizeof trick" to capture the results of // overload resolution at compile-time. typedef char yes_tag; typedef char (&no_tag)[2]; // mpl::true_ and mpl::false_ are not distinguishable by sizeof(), // so we pass them through these functions to get a type that is. yes_tag to_yesno(mpl::true_); no_tag to_yesno(mpl::false_); }}} // namespace boost::parameter::aux #endif // YESNO_050328_HPP
{ "pile_set_name": "Github" }
# Event 28 - Provider ###### Version: 0 ## Description None ## Data Dictionary |Standard Name|Field Name|Type|Description|Sample Value| |---|---|---|---|---| |TBD|ProviderGuid|GUID|None|`None`| |TBD|ErrorCode|UInt32|None|`None`| ## Tags * etw_level_Error * etw_keywords_ETW_KEYWORD_PROVIDER ETW_KEYWORD_REGISTRATION ETW_KEYWORD_GROUP * etw_opcode_SetProviderTraits * etw_task_Provider
{ "pile_set_name": "Github" }
/*- * Copyright (c) 2014-2019 MongoDB, Inc. * Copyright (c) 2008-2014 WiredTiger, Inc. * All rights reserved. * * See the file LICENSE for redistribution information. */ #include "util.h" static int usage(void); int util_salvage(WT_SESSION *session, int argc, char *argv[]) { WT_DECL_RET; int ch; char *uri; const char *force; force = NULL; uri = NULL; while ((ch = __wt_getopt(progname, argc, argv, "F")) != EOF) switch (ch) { case 'F': force = "force"; break; case '?': default: return (usage()); } argc -= __wt_optind; argv += __wt_optind; /* The remaining argument is the file name. */ if (argc != 1) return (usage()); if ((uri = util_uri(session, *argv, "file")) == NULL) return (1); if ((ret = session->salvage(session, uri, force)) != 0) (void)util_err(session, ret, "session.salvage: %s", uri); else { /* * Verbose configures a progress counter, move to the next line. */ if (verbose) printf("\n"); } free(uri); return (ret); } static int usage(void) { (void)fprintf(stderr, "usage: %s %s " "salvage [-F] uri\n", progname, usage_prefix); return (1); }
{ "pile_set_name": "Github" }
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/kernels/arm/group_norm_compute.h" #include "lite/backends/arm/math/funcs.h" #include "lite/core/op_registry.h" #include "lite/core/type_system.h" namespace paddle { namespace lite { namespace kernels { namespace arm { void GroupNormCompute::PrepareForRun() {} void GroupNormCompute::Run() { auto& param = this->Param<param_t>(); const float* in = param.x->data<float>(); const float* scale = param.scale->data<float>(); const float* bias = param.bias->data<float>(); float* out = param.out->mutable_data<float>(); float* saved_mean = param.saved_mean->mutable_data<float>(); float* saved_variance = param.saved_variance->mutable_data<float>(); float epsilon = param.epsilon; int groups = param.groups; int channels = param.channels; int n = param.x->dims()[0]; int c = param.x->dims()[1]; int ch_per_group = channels / groups; int height = param.x->dims()[2]; int width = param.x->dims()[3]; int spatial_size = ch_per_group * height * width; int ngroup = n * groups; int cnt = spatial_size >> 4; int remain = spatial_size % 16; // compute saved_mean and saved_variance #pragma omp parallel for for (int n = 0; n < ngroup; ++n) { const float* in_p = in + n * spatial_size; float sum_spatial = 0.f; float summ_spatial = 0.f; float32x4_t sum0 = vdupq_n_f32(0.f); float32x4_t sum1 = vdupq_n_f32(0.f); float32x4_t sum2 = vdupq_n_f32(0.f); float32x4_t sum3 = vdupq_n_f32(0.f); float32x4_t summ0 = vdupq_n_f32(0.f); float32x4_t summ1 = vdupq_n_f32(0.f); float32x4_t summ2 = vdupq_n_f32(0.f); float32x4_t summ3 = vdupq_n_f32(0.f); for (int i = 0; i < cnt; i++) { float32x4_t in0 = vld1q_f32(in_p); float32x4_t in1 = vld1q_f32(in_p + 4); float32x4_t in2 = vld1q_f32(in_p + 8); float32x4_t in3 = vld1q_f32(in_p + 12); sum0 = vaddq_f32(sum0, in0); summ0 = vmlaq_f32(summ0, in0, in0); sum1 = vaddq_f32(sum1, in1); summ1 = vmlaq_f32(summ1, in1, in1); sum2 = vaddq_f32(sum2, in2); summ2 = vmlaq_f32(summ2, in2, in2); sum3 = vaddq_f32(sum3, in3); summ3 = vmlaq_f32(summ3, in3, in3); in_p += 16; } for (int i = 0; i < remain - 3; i += 4) { float32x4_t in0 = vld1q_f32(in_p); sum1 = vaddq_f32(sum1, in0); summ1 = vmlaq_f32(summ1, in0, in0); in_p += 4; } float sum = 0.0; float summ = 0.0; sum0 = vaddq_f32(sum0, sum1); sum2 = vaddq_f32(sum2, sum3); summ0 = vaddq_f32(summ0, summ1); summ2 = vaddq_f32(summ2, summ3); for (int i = 0; i < remain % 4; i++) { sum += *in_p; summ += (*in_p) * (*in_p); in_p++; } sum0 = vaddq_f32(sum0, sum2); summ0 = vaddq_f32(summ0, summ2); float32x2_t sum_low = vpadd_f32(vget_low_f32(sum0), vget_high_f32(sum0)); float32x2_t sum_high = vpadd_f32(vget_low_f32(summ0), vget_high_f32(summ0)); float32x2_t sum_mix = vpadd_f32(sum_low, sum_high); sum += vget_lane_f32(sum_mix, 0); summ += vget_lane_f32(sum_mix, 1); float mean = sum / spatial_size; // float variance = summ / spatial_size - mean * mean; // the flolowing code has higher precision than above comment code float variance = (summ - mean * mean * spatial_size) / spatial_size; float std = 1.f / sqrtf(variance + epsilon); saved_mean[n] = mean; saved_variance[n] = std; } int in_size = height * width; cnt = in_size >> 4; remain = in_size % 16; // compute Group_norm result: out = scale * (in - mean) / std + bias #pragma omp parallel for for (int i = 0; i < ngroup; ++i) { const float* in_p = in + i * spatial_size; float* out_p = out + i * spatial_size; int numc = i % groups; numc *= ch_per_group; for (int c = 0; c < ch_per_group; c++) { int chin = numc + c; const float sstd_val = scale[chin] * saved_variance[i]; const float bias_val = bias[chin]; const float mean_val = saved_mean[i]; const float32x4_t vsstd = vdupq_n_f32(sstd_val); const float32x4_t vbias = vdupq_n_f32(bias_val); const float32x4_t vmean = vdupq_n_f32(mean_val); for (int k = 0; k < cnt; k++) { float32x4_t in0 = vld1q_f32(in_p); float32x4_t in1 = vld1q_f32(in_p + 4); float32x4_t in2 = vld1q_f32(in_p + 8); float32x4_t in3 = vld1q_f32(in_p + 12); float32x4_t submean0 = vsubq_f32(in0, vmean); float32x4_t submean1 = vsubq_f32(in1, vmean); float32x4_t submean2 = vsubq_f32(in2, vmean); float32x4_t submean3 = vsubq_f32(in3, vmean); float32x4_t out0 = vmlaq_f32(vbias, submean0, vsstd); float32x4_t out1 = vmlaq_f32(vbias, submean1, vsstd); float32x4_t out2 = vmlaq_f32(vbias, submean2, vsstd); float32x4_t out3 = vmlaq_f32(vbias, submean3, vsstd); vst1q_f32(out_p, out0); vst1q_f32(out_p + 4, out1); vst1q_f32(out_p + 8, out2); vst1q_f32(out_p + 12, out3); in_p += 16; out_p += 16; } for (int k = 0; k < remain - 3; k += 4) { float32x4_t in0 = vld1q_f32(in_p); in_p += 4; float32x4_t submean0 = vsubq_f32(in0, vmean); float32x4_t out0 = vmlaq_f32(vbias, submean0, vsstd); vst1q_f32(out_p, out0); out_p += 4; } for (int k = 0; k < remain % 4; k++) { *out_p = (*in_p - mean_val) * sstd_val + bias_val; in_p++; out_p++; } } } } } // namespace arm } // namespace kernels } // namespace lite } // namespace paddle REGISTER_LITE_KERNEL(group_norm, kARM, kFloat, kNCHW, paddle::lite::kernels::arm::GroupNormCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kARM))}) .BindInput("Scale", {LiteType::GetTensorTy(TARGET(kARM))}) .BindInput("Bias", {LiteType::GetTensorTy(TARGET(kARM))}) .BindOutput("Y", {LiteType::GetTensorTy(TARGET(kARM))}) .BindOutput("SavedMean", {LiteType::GetTensorTy(TARGET(kARM))}) .BindOutput("SavedVariance", {LiteType::GetTensorTy(TARGET(kARM))}) .Finalize();
{ "pile_set_name": "Github" }
#include <eosio/chain/abi_serializer.hpp> #include <eosio/testing/tester.hpp> #include <Runtime/Runtime.h> #include <fc/variant_object.hpp> #include <boost/test/unit_test.hpp> #include <contracts.hpp> #ifdef NON_VALIDATING_TEST #define TESTER tester #else #define TESTER validating_tester #endif using namespace eosio; using namespace eosio::chain; using namespace eosio::testing; using namespace fc; using mvo = fc::mutable_variant_object; struct genesis_account { account_name aname; uint64_t initial_balance; }; std::vector<genesis_account> test_genesis( { {N(b1), 100'000'000'0000ll}, {N(whale4), 40'000'000'0000ll}, {N(whale3), 30'000'000'0000ll}, {N(whale2), 20'000'000'0000ll}, {N(proda), 1'000'000'0000ll}, {N(prodb), 1'000'000'0000ll}, {N(prodc), 1'000'000'0000ll}, {N(prodd), 1'000'000'0000ll}, {N(prode), 1'000'000'0000ll}, {N(prodf), 1'000'000'0000ll}, {N(prodg), 1'000'000'0000ll}, {N(prodh), 1'000'000'0000ll}, {N(prodi), 1'000'000'0000ll}, {N(prodj), 1'000'000'0000ll}, {N(prodk), 1'000'000'0000ll}, {N(prodl), 1'000'000'0000ll}, {N(prodm), 1'000'000'0000ll}, {N(prodn), 1'000'000'0000ll}, {N(prodo), 1'000'000'0000ll}, {N(prodp), 1'000'000'0000ll}, {N(prodq), 1'000'000'0000ll}, {N(prodr), 1'000'000'0000ll}, {N(prods), 1'000'000'0000ll}, {N(prodt), 1'000'000'0000ll}, {N(produ), 1'000'000'0000ll}, {N(runnerup1), 1'000'000'0000ll}, {N(runnerup2), 1'000'000'0000ll}, {N(runnerup3), 1'000'000'0000ll}, {N(minow1), 100'0000ll}, {N(minow2), 1'0000ll}, {N(minow3), 1'0000ll}, {N(masses), 800'000'000'0000ll} }); class bootseq_tester : public TESTER { public: void deploy_contract( bool call_init = true ) { set_code( config::system_account_name, contracts::eosio_system_wasm() ); set_abi( config::system_account_name, contracts::eosio_system_abi().data() ); if( call_init ) { base_tester::push_action(config::system_account_name, N(init), config::system_account_name, mutable_variant_object() ("version", 0) ("core", CORE_SYM_STR) ); } const auto& accnt = control->db().get<account_object,by_name>( config::system_account_name ); abi_def abi; BOOST_REQUIRE_EQUAL(abi_serializer::to_abi(accnt.abi, abi), true); abi_ser.set_abi(abi, abi_serializer::create_yield_function( abi_serializer_max_time )); } fc::variant get_global_state() { vector<char> data = get_row_by_account( config::system_account_name, config::system_account_name, N(global), N(global) ); if (data.empty()) std::cout << "\nData is empty\n" << std::endl; return data.empty() ? fc::variant() : abi_ser.binary_to_variant( "eosio_global_state", data, abi_serializer::create_yield_function( abi_serializer_max_time ) ); } auto buyram( name payer, name receiver, asset ram ) { auto r = base_tester::push_action(config::system_account_name, N(buyram), payer, mvo() ("payer", payer) ("receiver", receiver) ("quant", ram) ); produce_block(); return r; } auto delegate_bandwidth( name from, name receiver, asset net, asset cpu, uint8_t transfer = 1) { auto r = base_tester::push_action(config::system_account_name, N(delegatebw), from, mvo() ("from", from ) ("receiver", receiver) ("stake_net_quantity", net) ("stake_cpu_quantity", cpu) ("transfer", transfer) ); produce_block(); return r; } void create_currency( name contract, name manager, asset maxsupply, const private_key_type* signer = nullptr ) { auto act = mutable_variant_object() ("issuer", manager ) ("maximum_supply", maxsupply ); base_tester::push_action(contract, N(create), contract, act ); } auto issue( name contract, name manager, name to, asset amount ) { auto r = base_tester::push_action( contract, N(issue), manager, mutable_variant_object() ("to", to ) ("quantity", amount ) ("memo", "") ); produce_block(); return r; } auto claim_rewards( name owner ) { auto r = base_tester::push_action( config::system_account_name, N(claimrewards), owner, mvo()("owner", owner )); produce_block(); return r; } auto set_privileged( name account ) { auto r = base_tester::push_action(config::system_account_name, N(setpriv), config::system_account_name, mvo()("account", account)("is_priv", 1)); produce_block(); return r; } auto register_producer(name producer) { auto r = base_tester::push_action(config::system_account_name, N(regproducer), producer, mvo() ("producer", name(producer)) ("producer_key", get_public_key( producer, "active" ) ) ("url", "" ) ("location", 0 ) ); produce_block(); return r; } auto undelegate_bandwidth( name from, name receiver, asset net, asset cpu ) { auto r = base_tester::push_action(config::system_account_name, N(undelegatebw), from, mvo() ("from", from ) ("receiver", receiver) ("unstake_net_quantity", net) ("unstake_cpu_quantity", cpu) ); produce_block(); return r; } asset get_balance( const account_name& act ) { return get_currency_balance(N(eosio.token), symbol(CORE_SYMBOL), act); } void set_code_abi(const account_name& account, const vector<uint8_t>& wasm, const char* abi, const private_key_type* signer = nullptr) { wdump((account)); set_code(account, wasm, signer); set_abi(account, abi, signer); if (account == config::system_account_name) { const auto& accnt = control->db().get<account_object,by_name>( account ); abi_def abi_definition; BOOST_REQUIRE_EQUAL(abi_serializer::to_abi(accnt.abi, abi_definition), true); abi_ser.set_abi(abi_definition, abi_serializer::create_yield_function( abi_serializer_max_time )); } produce_blocks(); } abi_serializer abi_ser; }; BOOST_AUTO_TEST_SUITE(bootseq_tests) BOOST_FIXTURE_TEST_CASE( bootseq_test, bootseq_tester ) { try { // Create eosio.msig and eosio.token create_accounts({N(eosio.msig), N(eosio.token), N(eosio.ram), N(eosio.ramfee), N(eosio.stake), N(eosio.vpay), N(eosio.bpay), N(eosio.saving) }); // Set code for the following accounts: // - eosio (code: eosio.bios) (already set by tester constructor) // - eosio.msig (code: eosio.msig) // - eosio.token (code: eosio.token) // set_code_abi(N(eosio.msig), contracts::eosio_msig_wasm(), contracts::eosio_msig_abi().data());//, &eosio_active_pk); // set_code_abi(N(eosio.token), contracts::eosio_token_wasm(), contracts::eosio_token_abi().data()); //, &eosio_active_pk); set_code_abi(N(eosio.msig), contracts::eosio_msig_wasm(), contracts::eosio_msig_abi().data());//, &eosio_active_pk); set_code_abi(N(eosio.token), contracts::eosio_token_wasm(), contracts::eosio_token_abi().data()); //, &eosio_active_pk); // Set privileged for eosio.msig and eosio.token set_privileged(N(eosio.msig)); set_privileged(N(eosio.token)); // Verify eosio.msig and eosio.token is privileged const auto& eosio_msig_acc = get<account_metadata_object, by_name>(N(eosio.msig)); BOOST_TEST(eosio_msig_acc.is_privileged() == true); const auto& eosio_token_acc = get<account_metadata_object, by_name>(N(eosio.token)); BOOST_TEST(eosio_token_acc.is_privileged() == true); // Create SYS tokens in eosio.token, set its manager as eosio auto max_supply = core_from_string("10000000000.0000"); /// 1x larger than 1B initial tokens auto initial_supply = core_from_string("1000000000.0000"); /// 1x larger than 1B initial tokens create_currency(N(eosio.token), config::system_account_name, max_supply); // Issue the genesis supply of 1 billion SYS tokens to eosio.system issue(N(eosio.token), config::system_account_name, config::system_account_name, initial_supply); auto actual = get_balance(config::system_account_name); BOOST_REQUIRE_EQUAL(initial_supply, actual); // Create genesis accounts for( const auto& a : test_genesis ) { create_account( a.aname, config::system_account_name ); } deploy_contract(); // Buy ram and stake cpu and net for each genesis accounts for( const auto& a : test_genesis ) { auto ib = a.initial_balance; auto ram = 1000; auto net = (ib - ram) / 2; auto cpu = ib - net - ram; auto r = buyram(config::system_account_name, a.aname, asset(ram)); BOOST_REQUIRE( !r->except_ptr ); r = delegate_bandwidth(N(eosio.stake), a.aname, asset(net), asset(cpu)); BOOST_REQUIRE( !r->except_ptr ); } auto producer_candidates = { N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg), N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn), N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(produ), N(runnerup1), N(runnerup2), N(runnerup3) }; // Register producers for( auto pro : producer_candidates ) { register_producer(pro); } // Vote for producers auto votepro = [&]( account_name voter, vector<account_name> producers ) { std::sort( producers.begin(), producers.end() ); base_tester::push_action(config::system_account_name, N(voteproducer), voter, mvo() ("voter", name(voter)) ("proxy", name(0) ) ("producers", producers) ); }; votepro( N(b1), { N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg), N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn), N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(produ)} ); votepro( N(whale2), {N(runnerup1), N(runnerup2), N(runnerup3)} ); votepro( N(whale3), {N(proda), N(prodb), N(prodc), N(prodd), N(prode)} ); // Total Stakes = b1 + whale2 + whale3 stake = (100,000,000 - 1,000) + (20,000,000 - 1,000) + (30,000,000 - 1,000) vector<char> data = get_row_by_account( config::system_account_name, config::system_account_name, N(global), N(global) ); BOOST_TEST(get_global_state()["total_activated_stake"].as<int64_t>() == 1499999997000); // No producers will be set, since the total activated stake is less than 150,000,000 produce_blocks_for_n_rounds(2); // 2 rounds since new producer schedule is set when the first block of next round is irreversible auto active_schedule = control->head_block_state()->active_schedule; BOOST_TEST(active_schedule.producers.size() == 1u); BOOST_TEST(active_schedule.producers.front().producer_name == name("eosio")); // Spend some time so the producer pay pool is filled by the inflation rate produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(fc::seconds(30 * 24 * 3600)); // 30 days // Since the total activated stake is less than 150,000,000, it shouldn't be possible to claim rewards BOOST_REQUIRE_THROW(claim_rewards(N(runnerup1)), eosio_assert_message_exception); // This will increase the total vote stake by (40,000,000 - 1,000) votepro( N(whale4), {N(prodq), N(prodr), N(prods), N(prodt), N(produ)} ); BOOST_TEST(get_global_state()["total_activated_stake"].as<int64_t>() == 1899999996000); // Since the total vote stake is more than 150,000,000, the new producer set will be set produce_blocks_for_n_rounds(2); // 2 rounds since new producer schedule is set when the first block of next round is irreversible active_schedule = control->head_block_state()->active_schedule; BOOST_REQUIRE(active_schedule.producers.size() == 21); BOOST_TEST(active_schedule.producers.at( 0).producer_name == name("proda")); BOOST_TEST(active_schedule.producers.at( 1).producer_name == name("prodb")); BOOST_TEST(active_schedule.producers.at( 2).producer_name == name("prodc")); BOOST_TEST(active_schedule.producers.at( 3).producer_name == name("prodd")); BOOST_TEST(active_schedule.producers.at( 4).producer_name == name("prode")); BOOST_TEST(active_schedule.producers.at( 5).producer_name == name("prodf")); BOOST_TEST(active_schedule.producers.at( 6).producer_name == name("prodg")); BOOST_TEST(active_schedule.producers.at( 7).producer_name == name("prodh")); BOOST_TEST(active_schedule.producers.at( 8).producer_name == name("prodi")); BOOST_TEST(active_schedule.producers.at( 9).producer_name == name("prodj")); BOOST_TEST(active_schedule.producers.at(10).producer_name == name("prodk")); BOOST_TEST(active_schedule.producers.at(11).producer_name == name("prodl")); BOOST_TEST(active_schedule.producers.at(12).producer_name == name("prodm")); BOOST_TEST(active_schedule.producers.at(13).producer_name == name("prodn")); BOOST_TEST(active_schedule.producers.at(14).producer_name == name("prodo")); BOOST_TEST(active_schedule.producers.at(15).producer_name == name("prodp")); BOOST_TEST(active_schedule.producers.at(16).producer_name == name("prodq")); BOOST_TEST(active_schedule.producers.at(17).producer_name == name("prodr")); BOOST_TEST(active_schedule.producers.at(18).producer_name == name("prods")); BOOST_TEST(active_schedule.producers.at(19).producer_name == name("prodt")); BOOST_TEST(active_schedule.producers.at(20).producer_name == name("produ")); // Spend some time so the producer pay pool is filled by the inflation rate produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(fc::seconds(30 * 24 * 3600)); // 30 days // Since the total activated stake is larger than 150,000,000, pool should be filled reward should be bigger than zero claim_rewards(N(runnerup1)); BOOST_TEST(get_balance(N(runnerup1)).get_amount() > 0); const auto first_june_2018 = fc::seconds(1527811200); // 2018-06-01 const auto first_june_2028 = fc::seconds(1843430400); // 2028-06-01 // Ensure that now is yet 10 years after 2018-06-01 yet BOOST_REQUIRE(control->head_block_time().time_since_epoch() < first_june_2028); // This should thrown an error, since block one can only unstake all his stake after 10 years BOOST_REQUIRE_THROW(undelegate_bandwidth(N(b1), N(b1), core_from_string("49999500.0000"), core_from_string("49999500.0000")), eosio_assert_message_exception); // Skip 10 years produce_block(first_june_2028 - control->head_block_time().time_since_epoch()); // Block one should be able to unstake all his stake now undelegate_bandwidth(N(b1), N(b1), core_from_string("49999500.0000"), core_from_string("49999500.0000")); return; produce_blocks(7000); /// produce blocks until virutal bandwidth can acomadate a small user wlog("minow" ); votepro( N(minow1), {N(p1), N(p2)} ); // TODO: Complete this test } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_SUITE_END()
{ "pile_set_name": "Github" }
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /* * $Id$ * Copyright (C) 1997, 1998, 1999, 2000 Free Software Foundation * All rights reserved. * * This file is part of the Gnome Library. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * published by the Free Software Foundation; either the * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * License along with the Gnome Library; see the file COPYING.LIB. If not, */ /* @NOTATION@ */ /* Text item type for GnomeCanvas widget * * GnomeCanvas is basically a port of the Tk toolkit's most excellent canvas * widget. Tk is copyrighted by the Regents of the University of California, * Sun Microsystems, and other parties. * * * Author: Federico Mena <federico@nuclecu.unam.mx> * Port to Pango co-done by Gergõ Érdi <cactus@cactus.rulez.org> */ #include "evolution-config.h" #include <math.h> #include <string.h> #include "gnome-canvas-text.h" #include "gnome-canvas-util.h" #include "gnome-canvas-i18n.h" /* Object argument IDs */ enum { PROP_0, /* Text contents */ PROP_TEXT, PROP_MARKUP, /* Position */ PROP_X, PROP_Y, /* Font */ PROP_FONT, PROP_FONT_DESC, PROP_FAMILY, PROP_FAMILY_SET, /* Style */ PROP_ATTRIBUTES, PROP_STYLE, PROP_STYLE_SET, PROP_VARIANT, PROP_VARIANT_SET, PROP_WEIGHT, PROP_WEIGHT_SET, PROP_STRETCH, PROP_STRETCH_SET, PROP_SIZE, PROP_SIZE_SET, PROP_SIZE_POINTS, PROP_STRIKETHROUGH, PROP_STRIKETHROUGH_SET, PROP_UNDERLINE, PROP_UNDERLINE_SET, PROP_RISE, PROP_RISE_SET, PROP_SCALE, PROP_SCALE_SET, /* Clipping */ PROP_JUSTIFICATION, PROP_CLIP_WIDTH, PROP_CLIP_HEIGHT, PROP_CLIP, PROP_X_OFFSET, PROP_Y_OFFSET, /* Coloring */ PROP_FILL_COLOR, PROP_FILL_COLOR_GDK, PROP_FILL_COLOR_RGBA, /* Rendered size accessors */ PROP_TEXT_WIDTH, PROP_TEXT_HEIGHT }; static void gnome_canvas_text_dispose (GnomeCanvasItem *object); static void gnome_canvas_text_set_property (GObject *object, guint param_id, const GValue *value, GParamSpec *pspec); static void gnome_canvas_text_get_property (GObject *object, guint param_id, GValue *value, GParamSpec *pspec); static void gnome_canvas_text_update (GnomeCanvasItem *item, const cairo_matrix_t *matrix, gint flags); static void gnome_canvas_text_draw (GnomeCanvasItem *item, cairo_t *cr, gint x, gint y, gint width, gint height); static GnomeCanvasItem *gnome_canvas_text_point (GnomeCanvasItem *item, gdouble x, gdouble y, gint cx, gint cy); static void gnome_canvas_text_bounds (GnomeCanvasItem *item, gdouble *x1, gdouble *y1, gdouble *x2, gdouble *y2); static void gnome_canvas_text_set_markup (GnomeCanvasText *textitem, const gchar *markup); static void gnome_canvas_text_set_font_desc (GnomeCanvasText *textitem, PangoFontDescription *font_desc); static void gnome_canvas_text_apply_font_desc (GnomeCanvasText *textitem); static void gnome_canvas_text_apply_attributes (GnomeCanvasText *textitem); static void add_attr (PangoAttrList *attr_list, PangoAttribute *attr); G_DEFINE_TYPE ( GnomeCanvasText, gnome_canvas_text, GNOME_TYPE_CANVAS_ITEM) /* Class initialization function for the text item */ static void gnome_canvas_text_class_init (GnomeCanvasTextClass *class) { GObjectClass *gobject_class; GnomeCanvasItemClass *item_class; gobject_class = (GObjectClass *) class; item_class = (GnomeCanvasItemClass *) class; gobject_class->set_property = gnome_canvas_text_set_property; gobject_class->get_property = gnome_canvas_text_get_property; /* Text */ g_object_class_install_property ( gobject_class, PROP_TEXT, g_param_spec_string ( "text", "Text", "Text to render", NULL, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_MARKUP, g_param_spec_string ( "markup", "Markup", "Marked up text to render", NULL, G_PARAM_WRITABLE)); /* Position */ g_object_class_install_property ( gobject_class, PROP_X, g_param_spec_double ( "x", NULL, NULL, -G_MAXDOUBLE, G_MAXDOUBLE, 0.0, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_Y, g_param_spec_double ( "y", NULL, NULL, -G_MAXDOUBLE, G_MAXDOUBLE, 0.0, G_PARAM_READABLE | G_PARAM_WRITABLE)); /* Font */ g_object_class_install_property ( gobject_class, PROP_FONT, g_param_spec_string ( "font", "Font", "Font description as a string", NULL, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_FONT_DESC, g_param_spec_boxed ( "font_desc", "Font description", "Font description as a PangoFontDescription struct", PANGO_TYPE_FONT_DESCRIPTION, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_FAMILY, g_param_spec_string ( "family", "Font family", "Name of the font family, e.g. " "Sans, Helvetica, Times, Monospace", NULL, G_PARAM_READABLE | G_PARAM_WRITABLE)); /* Style */ g_object_class_install_property ( gobject_class, PROP_ATTRIBUTES, g_param_spec_boxed ( "attributes", NULL, NULL, PANGO_TYPE_ATTR_LIST, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_STYLE, g_param_spec_enum ( "style", "Font style", "Font style", PANGO_TYPE_STYLE, PANGO_STYLE_NORMAL, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_VARIANT, g_param_spec_enum ( "variant", "Font variant", "Font variant", PANGO_TYPE_VARIANT, PANGO_VARIANT_NORMAL, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_WEIGHT, g_param_spec_int ( "weight", "Font weight", "Font weight", 0, G_MAXINT, PANGO_WEIGHT_NORMAL, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_STRETCH, g_param_spec_enum ( "stretch", "Font stretch", "Font stretch", PANGO_TYPE_STRETCH, PANGO_STRETCH_NORMAL, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_SIZE, g_param_spec_int ( "size", "Font size", "Font size (as a multiple of PANGO_SCALE, " "eg. 12*PANGO_SCALE for a 12pt font size)", 0, G_MAXINT, 0, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_SIZE_POINTS, g_param_spec_double ( "size_points", "Font points", "Font size in points (eg. 12 for a 12pt font size)", 0.0, G_MAXDOUBLE, 0.0, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_RISE, g_param_spec_int ( "rise", "Rise", "Offset of text above the baseline " "(below the baseline if rise is negative)", -G_MAXINT, G_MAXINT, 0, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_STRIKETHROUGH, g_param_spec_boolean ( "strikethrough", "Strikethrough", "Whether to strike through the text", FALSE, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_UNDERLINE, g_param_spec_enum ( "underline", "Underline", "Style of underline for this text", PANGO_TYPE_UNDERLINE, PANGO_UNDERLINE_NONE, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_SCALE, g_param_spec_double ( "scale", "Scale", "Size of font, relative to default size", 0.0, G_MAXDOUBLE, 1.0, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_JUSTIFICATION, g_param_spec_enum ( "justification", NULL, NULL, GTK_TYPE_JUSTIFICATION, GTK_JUSTIFY_LEFT, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_CLIP_WIDTH, g_param_spec_double ( "clip_width", NULL, NULL, -G_MAXDOUBLE, G_MAXDOUBLE, 0.0, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_CLIP_HEIGHT, g_param_spec_double ( "clip_height", NULL, NULL, -G_MAXDOUBLE, G_MAXDOUBLE, 0.0, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_CLIP, g_param_spec_boolean ( "clip", NULL, NULL, FALSE, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_X_OFFSET, g_param_spec_double ( "x_offset", NULL, NULL, -G_MAXDOUBLE, G_MAXDOUBLE, 0.0, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_Y_OFFSET, g_param_spec_double ( "y_offset", NULL, NULL, -G_MAXDOUBLE, G_MAXDOUBLE, 0.0, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_FILL_COLOR, g_param_spec_string ( "fill_color", "Color", "Text color, as string", NULL, G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_FILL_COLOR_GDK, g_param_spec_boxed ( "fill_color_gdk", "Color", "Text color, as a GdkColor", GDK_TYPE_COLOR, G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_FILL_COLOR_RGBA, g_param_spec_uint ( "fill_color_rgba", "Color", "Text color, as an R/G/B/A combined integer", 0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property ( gobject_class, PROP_TEXT_WIDTH, g_param_spec_double ( "text_width", "Text width", "Width of the rendered text", 0.0, G_MAXDOUBLE, 0.0, G_PARAM_READABLE)); g_object_class_install_property ( gobject_class, PROP_TEXT_HEIGHT, g_param_spec_double ( "text_height", "Text height", "Height of the rendered text", 0.0, G_MAXDOUBLE, 0.0, G_PARAM_READABLE)); /* Style props are set (explicitly applied) or not */ #define ADD_SET_PROP(propname, propval, nick, blurb) \ g_object_class_install_property ( \ gobject_class, propval, \ g_param_spec_boolean ( \ propname, nick, blurb, FALSE, \ G_PARAM_READABLE | G_PARAM_WRITABLE)) ADD_SET_PROP ( "family_set", PROP_FAMILY_SET, "Font family set", "Whether this tag affects the font family"); ADD_SET_PROP ( "style_set", PROP_STYLE_SET, "Font style set", "Whether this tag affects the font style"); ADD_SET_PROP ( "variant_set", PROP_VARIANT_SET, "Font variant set", "Whether this tag affects the font variant"); ADD_SET_PROP ( "weight_set", PROP_WEIGHT_SET, "Font weight set", "Whether this tag affects the font weight"); ADD_SET_PROP ( "stretch_set", PROP_STRETCH_SET, "Font stretch set", "Whether this tag affects the font stretch"); ADD_SET_PROP ( "size_set", PROP_SIZE_SET, "Font size set", "Whether this tag affects the font size"); ADD_SET_PROP ( "rise_set", PROP_RISE_SET, "Rise set", "Whether this tag affects the rise"); ADD_SET_PROP ( "strikethrough_set", PROP_STRIKETHROUGH_SET, "Strikethrough set", "Whether this tag affects strikethrough"); ADD_SET_PROP ( "underline_set", PROP_UNDERLINE_SET, "Underline set", "Whether this tag affects underlining"); ADD_SET_PROP ( "scale_set", PROP_SCALE_SET, "Scale set", "Whether this tag affects font scaling"); #undef ADD_SET_PROP item_class->dispose = gnome_canvas_text_dispose; item_class->update = gnome_canvas_text_update; item_class->draw = gnome_canvas_text_draw; item_class->point = gnome_canvas_text_point; item_class->bounds = gnome_canvas_text_bounds; } /* Object initialization function for the text item */ static void gnome_canvas_text_init (GnomeCanvasText *text) { text->x = 0.0; text->y = 0.0; text->justification = GTK_JUSTIFY_LEFT; text->clip_width = 0.0; text->clip_height = 0.0; text->xofs = 0.0; text->yofs = 0.0; text->layout = NULL; text->font_desc = NULL; text->underline = PANGO_UNDERLINE_NONE; text->strikethrough = FALSE; text->rise = 0; text->underline_set = FALSE; text->strike_set = FALSE; text->rise_set = FALSE; } /* Dispose handler for the text item */ static void gnome_canvas_text_dispose (GnomeCanvasItem *object) { GnomeCanvasText *text; g_return_if_fail (GNOME_IS_CANVAS_TEXT (object)); text = GNOME_CANVAS_TEXT (object); g_free (text->text); text->text = NULL; if (text->layout != NULL) { g_object_unref (text->layout); text->layout = NULL; } if (text->font_desc != NULL) { pango_font_description_free (text->font_desc); text->font_desc = NULL; } if (text->attr_list != NULL) { pango_attr_list_unref (text->attr_list); text->attr_list = NULL; } GNOME_CANVAS_ITEM_CLASS (gnome_canvas_text_parent_class)-> dispose (object); } static void get_bounds (GnomeCanvasText *text, gdouble *px1, gdouble *py1, gdouble *px2, gdouble *py2) { GnomeCanvasItem *item; gdouble wx, wy; item = GNOME_CANVAS_ITEM (text); /* Get canvas pixel coordinates for text position */ wx = text->x; wy = text->y; gnome_canvas_item_i2w (item, &wx, &wy); gnome_canvas_w2c ( item->canvas, wx + text->xofs, wy + text->yofs, &text->cx, &text->cy); /* Get canvas pixel coordinates for clip rectangle position */ gnome_canvas_w2c (item->canvas, wx, wy, &text->clip_cx, &text->clip_cy); text->clip_cwidth = text->clip_width; text->clip_cheight = text->clip_height; /* Bounds */ if (text->clip) { *px1 = text->clip_cx; *py1 = text->clip_cy; *px2 = text->clip_cx + text->clip_cwidth; *py2 = text->clip_cy + text->clip_cheight; } else { *px1 = text->cx; *py1 = text->cy; *px2 = text->cx + text->max_width; *py2 = text->cy + text->height; } } static PangoFontMask get_property_font_set_mask (guint property_id) { switch (property_id) { case PROP_FAMILY_SET: return PANGO_FONT_MASK_FAMILY; case PROP_STYLE_SET: return PANGO_FONT_MASK_STYLE; case PROP_VARIANT_SET: return PANGO_FONT_MASK_VARIANT; case PROP_WEIGHT_SET: return PANGO_FONT_MASK_WEIGHT; case PROP_STRETCH_SET: return PANGO_FONT_MASK_STRETCH; case PROP_SIZE_SET: return PANGO_FONT_MASK_SIZE; } return 0; } static void ensure_font (GnomeCanvasText *text) { if (!text->font_desc) text->font_desc = pango_font_description_new (); } /* Set_arg handler for the text item */ static void gnome_canvas_text_set_property (GObject *object, guint param_id, const GValue *value, GParamSpec *pspec) { GnomeCanvasItem *item; GnomeCanvasText *text; GdkColor *pcolor; PangoAlignment align; g_return_if_fail (object != NULL); g_return_if_fail (GNOME_IS_CANVAS_TEXT (object)); item = GNOME_CANVAS_ITEM (object); text = GNOME_CANVAS_TEXT (object); if (!text->layout) text->layout = pango_layout_new ( gtk_widget_get_pango_context ( GTK_WIDGET (item->canvas))); switch (param_id) { case PROP_TEXT: g_free (text->text); text->text = g_value_dup_string (value); pango_layout_set_text (text->layout, text->text, -1); break; case PROP_MARKUP: gnome_canvas_text_set_markup ( text, g_value_get_string (value)); break; case PROP_X: text->x = g_value_get_double (value); break; case PROP_Y: text->y = g_value_get_double (value); break; case PROP_FONT: { const gchar *font_name; PangoFontDescription *font_desc; font_name = g_value_get_string (value); if (font_name) font_desc = pango_font_description_from_string (font_name); else font_desc = NULL; gnome_canvas_text_set_font_desc (text, font_desc); if (font_desc) pango_font_description_free (font_desc); break; } case PROP_FONT_DESC: gnome_canvas_text_set_font_desc (text, g_value_peek_pointer (value)); break; case PROP_FAMILY: case PROP_STYLE: case PROP_VARIANT: case PROP_WEIGHT: case PROP_STRETCH: case PROP_SIZE: case PROP_SIZE_POINTS: ensure_font (text); switch (param_id) { case PROP_FAMILY: pango_font_description_set_family ( text->font_desc, g_value_get_string (value)); break; case PROP_STYLE: pango_font_description_set_style ( text->font_desc, g_value_get_enum (value)); break; case PROP_VARIANT: pango_font_description_set_variant ( text->font_desc, g_value_get_enum (value)); break; case PROP_WEIGHT: pango_font_description_set_weight ( text->font_desc, g_value_get_int (value)); break; case PROP_STRETCH: pango_font_description_set_stretch ( text->font_desc, g_value_get_enum (value)); break; case PROP_SIZE: /* FIXME: This is bogus! It should be pixels, not points/PANGO_SCALE! */ pango_font_description_set_size ( text->font_desc, g_value_get_int (value)); break; case PROP_SIZE_POINTS: pango_font_description_set_size ( text->font_desc, g_value_get_double (value) * PANGO_SCALE); break; } gnome_canvas_text_apply_font_desc (text); break; case PROP_FAMILY_SET: case PROP_STYLE_SET: case PROP_VARIANT_SET: case PROP_WEIGHT_SET: case PROP_STRETCH_SET: case PROP_SIZE_SET: if (!g_value_get_boolean (value) && text->font_desc) pango_font_description_unset_fields ( text->font_desc, get_property_font_set_mask (param_id)); break; case PROP_SCALE: text->scale = g_value_get_double (value); text->scale_set = TRUE; gnome_canvas_text_apply_font_desc (text); break; case PROP_SCALE_SET: text->scale_set = g_value_get_boolean (value); gnome_canvas_text_apply_font_desc (text); break; case PROP_UNDERLINE: text->underline = g_value_get_enum (value); text->underline_set = TRUE; gnome_canvas_text_apply_attributes (text); break; case PROP_UNDERLINE_SET: text->underline_set = g_value_get_boolean (value); gnome_canvas_text_apply_attributes (text); break; case PROP_STRIKETHROUGH: text->strikethrough = g_value_get_boolean (value); text->strike_set = TRUE; gnome_canvas_text_apply_attributes (text); break; case PROP_STRIKETHROUGH_SET: text->strike_set = g_value_get_boolean (value); gnome_canvas_text_apply_attributes (text); break; case PROP_RISE: text->rise = g_value_get_int (value); text->rise_set = TRUE; gnome_canvas_text_apply_attributes (text); break; case PROP_RISE_SET: text->rise_set = TRUE; gnome_canvas_text_apply_attributes (text); break; case PROP_ATTRIBUTES: if (text->attr_list) pango_attr_list_unref (text->attr_list); text->attr_list = g_value_peek_pointer (value); pango_attr_list_ref (text->attr_list); gnome_canvas_text_apply_attributes (text); break; case PROP_JUSTIFICATION: text->justification = g_value_get_enum (value); switch (text->justification) { case GTK_JUSTIFY_LEFT: align = PANGO_ALIGN_LEFT; break; case GTK_JUSTIFY_CENTER: align = PANGO_ALIGN_CENTER; break; case GTK_JUSTIFY_RIGHT: align = PANGO_ALIGN_RIGHT; break; default: /* GTK_JUSTIFY_FILL isn't supported yet. */ align = PANGO_ALIGN_LEFT; break; } pango_layout_set_alignment (text->layout, align); break; case PROP_CLIP_WIDTH: text->clip_width = fabs (g_value_get_double (value)); break; case PROP_CLIP_HEIGHT: text->clip_height = fabs (g_value_get_double (value)); break; case PROP_CLIP: text->clip = g_value_get_boolean (value); break; case PROP_X_OFFSET: text->xofs = g_value_get_double (value); break; case PROP_Y_OFFSET: text->yofs = g_value_get_double (value); break; case PROP_FILL_COLOR: { const gchar *color_name; color_name = g_value_get_string (value); if (color_name) { GdkColor color; if (gdk_color_parse (color_name, &color)) { text->rgba = GNOME_CANVAS_COLOR (color.red, color.green, color.blue); } else { g_warning ( "%s: Failed to parse color form string '%s'", G_STRFUNC, color_name); } } break; } case PROP_FILL_COLOR_GDK: pcolor = g_value_get_boxed (value); if (pcolor) { text->rgba = GNOME_CANVAS_COLOR (pcolor->red, pcolor->green, pcolor->blue); } else { text->rgba = 0; } break; case PROP_FILL_COLOR_RGBA: text->rgba = g_value_get_uint (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); break; } /* Calculate text dimensions */ if (text->layout) pango_layout_get_pixel_size ( text->layout, &text->max_width, &text->height); else { text->max_width = 0; text->height = 0; } gnome_canvas_item_request_update (item); } /* Get_arg handler for the text item */ static void gnome_canvas_text_get_property (GObject *object, guint param_id, GValue *value, GParamSpec *pspec) { GnomeCanvasText *text; g_return_if_fail (object != NULL); g_return_if_fail (GNOME_IS_CANVAS_TEXT (object)); text = GNOME_CANVAS_TEXT (object); switch (param_id) { case PROP_TEXT: g_value_set_string (value, text->text); break; case PROP_X: g_value_set_double (value, text->x); break; case PROP_Y: g_value_set_double (value, text->y); break; case PROP_FONT: case PROP_FONT_DESC: case PROP_FAMILY: case PROP_STYLE: case PROP_VARIANT: case PROP_WEIGHT: case PROP_STRETCH: case PROP_SIZE: case PROP_SIZE_POINTS: ensure_font (text); switch (param_id) { case PROP_FONT: { /* FIXME GValue imposes a totally gratuitous string * copy here, we could just hand off string * ownership. */ gchar *str; str = pango_font_description_to_string (text->font_desc); g_value_set_string (value, str); g_free (str); break; } case PROP_FONT_DESC: g_value_set_boxed (value, text->font_desc); break; case PROP_FAMILY: g_value_set_string ( value, pango_font_description_get_family ( text->font_desc)); break; case PROP_STYLE: g_value_set_enum ( value, pango_font_description_get_style ( text->font_desc)); break; case PROP_VARIANT: g_value_set_enum ( value, pango_font_description_get_variant ( text->font_desc)); break; case PROP_WEIGHT: g_value_set_int ( value, pango_font_description_get_weight ( text->font_desc)); break; case PROP_STRETCH: g_value_set_enum ( value, pango_font_description_get_stretch ( text->font_desc)); break; case PROP_SIZE: g_value_set_int ( value, pango_font_description_get_size ( text->font_desc)); break; case PROP_SIZE_POINTS: g_value_set_double ( value, ((gdouble) pango_font_description_get_size ( text->font_desc)) / (gdouble) PANGO_SCALE); break; } break; case PROP_FAMILY_SET: case PROP_STYLE_SET: case PROP_VARIANT_SET: case PROP_WEIGHT_SET: case PROP_STRETCH_SET: case PROP_SIZE_SET: { PangoFontMask set_mask = text->font_desc ? pango_font_description_get_set_fields (text->font_desc) : 0; PangoFontMask test_mask = get_property_font_set_mask (param_id); g_value_set_boolean (value, (set_mask & test_mask) != 0); break; } case PROP_SCALE: g_value_set_double (value, text->scale); break; case PROP_SCALE_SET: g_value_set_boolean (value, text->scale_set); break; case PROP_UNDERLINE: g_value_set_enum (value, text->underline); break; case PROP_UNDERLINE_SET: g_value_set_boolean (value, text->underline_set); break; case PROP_STRIKETHROUGH: g_value_set_boolean (value, text->strikethrough); break; case PROP_STRIKETHROUGH_SET: g_value_set_boolean (value, text->strike_set); break; case PROP_RISE: g_value_set_int (value, text->rise); break; case PROP_RISE_SET: g_value_set_boolean (value, text->rise_set); break; case PROP_ATTRIBUTES: g_value_set_boxed (value, text->attr_list); break; case PROP_JUSTIFICATION: g_value_set_enum (value, text->justification); break; case PROP_CLIP_WIDTH: g_value_set_double (value, text->clip_width); break; case PROP_CLIP_HEIGHT: g_value_set_double (value, text->clip_height); break; case PROP_CLIP: g_value_set_boolean (value, text->clip); break; case PROP_X_OFFSET: g_value_set_double (value, text->xofs); break; case PROP_Y_OFFSET: g_value_set_double (value, text->yofs); break; case PROP_FILL_COLOR_RGBA: g_value_set_uint (value, text->rgba); break; case PROP_TEXT_WIDTH: g_value_set_double (value, text->max_width); break; case PROP_TEXT_HEIGHT: g_value_set_double (value, text->height); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); break; } } /* */ static void gnome_canvas_text_apply_font_desc (GnomeCanvasText *text) { PangoFontDescription *font_desc; PangoContext *pango_context; GtkWidget *widget; widget = GTK_WIDGET (GNOME_CANVAS_ITEM (text)->canvas); pango_context = gtk_widget_create_pango_context (widget); font_desc = pango_font_description_copy (pango_context_get_font_description (pango_context)); g_object_unref (pango_context); if (text->font_desc) pango_font_description_merge (font_desc, text->font_desc, TRUE); pango_layout_set_font_description (text->layout, font_desc); pango_font_description_free (font_desc); } static void add_attr (PangoAttrList *attr_list, PangoAttribute *attr) { attr->start_index = 0; attr->end_index = G_MAXINT; pango_attr_list_insert (attr_list, attr); } /* */ static void gnome_canvas_text_apply_attributes (GnomeCanvasText *text) { PangoAttrList *attr_list; if (text->attr_list) attr_list = pango_attr_list_copy (text->attr_list); else attr_list = pango_attr_list_new (); if (text->underline_set) add_attr (attr_list, pango_attr_underline_new (text->underline)); if (text->strike_set) add_attr (attr_list, pango_attr_strikethrough_new (text->strikethrough)); if (text->rise_set) add_attr (attr_list, pango_attr_rise_new (text->rise)); pango_layout_set_attributes (text->layout, attr_list); pango_attr_list_unref (attr_list); } static void gnome_canvas_text_set_font_desc (GnomeCanvasText *text, PangoFontDescription *font_desc) { if (text->font_desc) pango_font_description_free (text->font_desc); if (font_desc) text->font_desc = pango_font_description_copy (font_desc); else text->font_desc = NULL; gnome_canvas_text_apply_font_desc (text); } /* Setting the text from a Pango markup string */ static void gnome_canvas_text_set_markup (GnomeCanvasText *textitem, const gchar *markup) { PangoAttrList *attr_list = NULL; gchar *text = NULL; GError *error = NULL; if (markup && !pango_parse_markup (markup, -1, 0, &attr_list, &text, NULL, &error)) { g_warning ( "Failed to set cell text from markup due to " "error parsing markup: %s", error->message); g_error_free (error); return; } g_free (textitem->text); if (textitem->attr_list) pango_attr_list_unref (textitem->attr_list); textitem->text = text; textitem->attr_list = attr_list; pango_layout_set_text (textitem->layout, text, -1); gnome_canvas_text_apply_attributes (textitem); } /* Update handler for the text item */ static void gnome_canvas_text_update (GnomeCanvasItem *item, const cairo_matrix_t *matrix, gint flags) { GnomeCanvasText *text; gdouble x1, y1, x2, y2; text = GNOME_CANVAS_TEXT (item); GNOME_CANVAS_ITEM_CLASS (gnome_canvas_text_parent_class)-> update (item, matrix, flags); get_bounds (text, &x1, &y1, &x2, &y2); gnome_canvas_update_bbox ( item, floor (x1), floor (y1), ceil (x2), ceil (y2)); } /* Draw handler for the text item */ static void gnome_canvas_text_draw (GnomeCanvasItem *item, cairo_t *cr, gint x, gint y, gint width, gint height) { GnomeCanvasText *text = GNOME_CANVAS_TEXT (item); if (!text->text) return; cairo_save (cr); if (text->clip) { cairo_rectangle ( cr, text->clip_cx - x, text->clip_cy - y, text->clip_cwidth, text->clip_cheight); cairo_clip (cr); } cairo_set_source_rgba ( cr, ((text->rgba >> 24) & 0xff) / 255.0, ((text->rgba >> 16) & 0xff) / 255.0, ((text->rgba >> 8) & 0xff) / 255.0, ( text->rgba & 0xff) / 255.0); cairo_move_to (cr, text->cx - x, text->cy - y); pango_cairo_show_layout (cr, text->layout); cairo_restore (cr); } /* Point handler for the text item */ static GnomeCanvasItem * gnome_canvas_text_point (GnomeCanvasItem *item, gdouble x, gdouble y, gint cx, gint cy) { GnomeCanvasText *text; PangoLayoutIter *iter; gint x1, y1, x2, y2; text = GNOME_CANVAS_TEXT (item); /* The idea is to build bounding rectangles for each of the lines of * text (clipped by the clipping rectangle, if it is activated) and see * whether the point is inside any of these. If it is, we are done. * Otherwise, calculate the distance to the nearest rectangle. */ iter = pango_layout_get_iter (text->layout); do { PangoRectangle log_rect; pango_layout_iter_get_line_extents (iter, NULL, &log_rect); x1 = text->cx + PANGO_PIXELS (log_rect.x); y1 = text->cy + PANGO_PIXELS (log_rect.y); x2 = x1 + PANGO_PIXELS (log_rect.width); y2 = y1 + PANGO_PIXELS (log_rect.height); if (text->clip) { if (x1 < text->clip_cx) x1 = text->clip_cx; if (y1 < text->clip_cy) y1 = text->clip_cy; if (x2 > (text->clip_cx + text->clip_width)) x2 = text->clip_cx + text->clip_width; if (y2 > (text->clip_cy + text->clip_height)) y2 = text->clip_cy + text->clip_height; if ((x1 >= x2) || (y1 >= y2)) continue; } /* Calculate distance from point to rectangle */ if (cx >= x1 && cx < x2 && cy >= y1 && cy < y2) { pango_layout_iter_free (iter); return item; } } while (pango_layout_iter_next_line (iter)); pango_layout_iter_free (iter); return NULL; } /* Bounds handler for the text item */ static void gnome_canvas_text_bounds (GnomeCanvasItem *item, gdouble *x1, gdouble *y1, gdouble *x2, gdouble *y2) { GnomeCanvasText *text; gdouble width, height; text = GNOME_CANVAS_TEXT (item); *x1 = text->x; *y1 = text->y; if (text->clip) { width = text->clip_width; height = text->clip_height; } else { width = text->max_width; height = text->height; } *x2 = *x1 + width; *y2 = *y1 + height; }
{ "pile_set_name": "Github" }
// Copyright 2019-present Facebook Inc. All rights reserved. // This source code is licensed under the Apache 2.0 license found // in the LICENSE file in the root directory of this source tree. // Code generated by entc, DO NOT EDIT. package migrate import ( "context" "fmt" "io" "github.com/facebook/ent/dialect" "github.com/facebook/ent/dialect/sql/schema" ) var ( // WithGlobalUniqueID sets the universal ids options to the migration. // If this option is enabled, ent migration will allocate a 1<<32 range // for the ids of each entity (table). // Note that this option cannot be applied on tables that already exist. WithGlobalUniqueID = schema.WithGlobalUniqueID // WithDropColumn sets the drop column option to the migration. // If this option is enabled, ent migration will drop old columns // that were used for both fields and edges. This defaults to false. WithDropColumn = schema.WithDropColumn // WithDropIndex sets the drop index option to the migration. // If this option is enabled, ent migration will drop old indexes // that were defined in the schema. This defaults to false. // Note that unique constraints are defined using `UNIQUE INDEX`, // and therefore, it's recommended to enable this option to get more // flexibility in the schema changes. WithDropIndex = schema.WithDropIndex // WithFixture sets the foreign-key renaming option to the migration when upgrading // ent from v0.1.0 (issue-#285). Defaults to false. WithFixture = schema.WithFixture ) // Schema is the API for creating, migrating and dropping a schema. type Schema struct { drv dialect.Driver universalID bool } // NewSchema creates a new schema client. func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } // Create creates all schema resources. func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { migrate, err := schema.NewMigrate(s.drv, opts...) if err != nil { return fmt.Errorf("ent/migrate: %v", err) } return migrate.Create(ctx, Tables...) } // WriteTo writes the schema changes to w instead of running them against the database. // // if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { // log.Fatal(err) // } // func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { drv := &schema.WriteDriver{ Writer: w, Driver: s.drv, } migrate, err := schema.NewMigrate(drv, opts...) if err != nil { return fmt.Errorf("ent/migrate: %v", err) } return migrate.Create(ctx, Tables...) }
{ "pile_set_name": "Github" }
# created by tools/tclZIC.tcl - do not edit if {![info exists TZData(America/Denver)]} { LoadTimeZoneFile America/Denver } set TZData(:Navajo) $TZData(:America/Denver)
{ "pile_set_name": "Github" }
#!/bin/sh # Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB # This file is public domain and comes with NO WARRANTY of any kind # MySQL daemon start/stop script. # Usually this is put in /etc/init.d (at least on machines SYSV R4 based # systems) and linked to /etc/rc3.d/S99mysql and /etc/rc0.d/K01mysql. # When this is done the mysql server will be started when the machine is # started and shut down when the systems goes down. # Comments to support chkconfig on RedHat Linux # chkconfig: 2345 64 36 # description: A very fast and reliable SQL database engine. # Comments to support LSB init script conventions ### BEGIN INIT INFO # Provides: mysql # Required-Start: $local_fs $network $remote_fs # Should-Start: ypbind nscd ldap ntpd xntpd # Required-Stop: $local_fs $network $remote_fs # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: start and stop MySQL # Description: MySQL is a very fast and reliable SQL database engine. ### END INIT INFO # If you install MySQL on some other places than /usr/local/mysql, then you # have to do one of the following things for this script to work: # # - Run this script from within the MySQL installation directory # - Create a /etc/my.cnf file with the following information: # [mysqld] # basedir=<path-to-mysql-installation-directory> # - Add the above to any other configuration file (for example ~/.my.ini) # and copy my_print_defaults to /usr/bin # - Add the path to the mysql-installation-directory to the basedir variable # below. # # If you want to affect other MySQL variables, you should make your changes # in the /etc/my.cnf, ~/.my.cnf or other MySQL configuration files. # If you change base dir, you must also change datadir. These may get # overwritten by settings in the MySQL configuration files. basedir= datadir= # Default value, in seconds, afterwhich the script should timeout waiting # for server start. # Value here is overriden by value in my.cnf. # 0 means don't wait at all # Negative numbers mean to wait indefinitely service_startup_timeout=900 # Lock directory for RedHat / SuSE. lockdir='/var/lock/subsys' lock_file_path="$lockdir/mysql" # The following variables are only set for letting mysql.server find things. # Set some defaults mysqld_pid_file_path= if test -z "$basedir" then basedir=/usr/local/mysql bindir=/usr/local/mysql/bin if test -z "$datadir" then datadir=/mydata/mysql/data fi sbindir=/usr/local/mysql/bin libexecdir=/usr/local/mysql/bin else bindir="$basedir/bin" if test -z "$datadir" then datadir="$basedir/data" fi sbindir="$basedir/sbin" libexecdir="$basedir/libexec" fi # datadir_set is used to determine if datadir was set (and so should be # *not* set inside of the --basedir= handler.) datadir_set= # # Use LSB init script functions for printing messages, if possible # lsb_functions="/lib/lsb/init-functions" if test -f $lsb_functions ; then . $lsb_functions else log_success_msg() { echo " SUCCESS! $@" } log_failure_msg() { echo " ERROR! $@" } fi PATH="/sbin:/usr/sbin:/bin:/usr/bin:$basedir/bin" export PATH mode=$1 # start or stop [ $# -ge 1 ] && shift other_args="$*" # uncommon, but needed when called from an RPM upgrade action # Expected: "--skip-networking --skip-grant-tables" # They are not checked here, intentionally, as it is the resposibility # of the "spec" file author to give correct arguments only. case `echo "testing\c"`,`echo -n testing` in *c*,-n*) echo_n= echo_c= ;; *c*,*) echo_n=-n echo_c= ;; *) echo_n= echo_c='\c' ;; esac parse_server_arguments() { for arg do case "$arg" in --basedir=*) basedir=`echo "$arg" | sed -e 's/^[^=]*=//'` bindir="$basedir/bin" if test -z "$datadir_set"; then datadir="$basedir/data" fi sbindir="$basedir/sbin" libexecdir="$basedir/libexec" ;; --datadir=*) datadir=`echo "$arg" | sed -e 's/^[^=]*=//'` datadir_set=1 ;; --pid-file=*) mysqld_pid_file_path=`echo "$arg" | sed -e 's/^[^=]*=//'` ;; --service-startup-timeout=*) service_startup_timeout=`echo "$arg" | sed -e 's/^[^=]*=//'` ;; esac done } wait_for_pid () { verb="$1" # created | removed pid="$2" # process ID of the program operating on the pid-file pid_file_path="$3" # path to the PID file. i=0 avoid_race_condition="by checking again" while test $i -ne $service_startup_timeout ; do case "$verb" in 'created') # wait for a PID-file to pop into existence. test -s "$pid_file_path" && i='' && break ;; 'removed') # wait for this PID-file to disappear test ! -s "$pid_file_path" && i='' && break ;; *) echo "wait_for_pid () usage: wait_for_pid created|removed pid pid_file_path" exit 1 ;; esac # if server isn't running, then pid-file will never be updated if test -n "$pid"; then if kill -0 "$pid" 2>/dev/null; then : # the server still runs else # The server may have exited between the last pid-file check and now. if test -n "$avoid_race_condition"; then avoid_race_condition="" continue # Check again. fi # there's nothing that will affect the file. log_failure_msg "The server quit without updating PID file ($pid_file_path)." return 1 # not waiting any more. fi fi echo $echo_n ".$echo_c" i=`expr $i + 1` sleep 1 done if test -z "$i" ; then log_success_msg return 0 else log_failure_msg return 1 fi } # Get arguments from the my.cnf file, # the only group, which is read from now on is [mysqld] if test -x ./bin/my_print_defaults then print_defaults="./bin/my_print_defaults" elif test -x $bindir/my_print_defaults then print_defaults="$bindir/my_print_defaults" elif test -x $bindir/mysql_print_defaults then print_defaults="$bindir/mysql_print_defaults" else # Try to find basedir in /etc/my.cnf conf=/etc/my.cnf print_defaults= if test -r $conf then subpat='^[^=]*basedir[^=]*=\(.*\)$' dirs=`sed -e "/$subpat/!d" -e 's//\1/' $conf` for d in $dirs do d=`echo $d | sed -e 's/[ ]//g'` if test -x "$d/bin/my_print_defaults" then print_defaults="$d/bin/my_print_defaults" break fi if test -x "$d/bin/mysql_print_defaults" then print_defaults="$d/bin/mysql_print_defaults" break fi done fi # Hope it's in the PATH ... but I doubt it test -z "$print_defaults" && print_defaults="my_print_defaults" fi # # Read defaults file from 'basedir'. If there is no defaults file there # check if it's in the old (depricated) place (datadir) and read it from there # extra_args="" if test -r "$basedir/my.cnf" then extra_args="-e $basedir/my.cnf" else if test -r "$datadir/my.cnf" then extra_args="-e $datadir/my.cnf" fi fi parse_server_arguments `$print_defaults $extra_args mysqld server mysql_server mysql.server` # # Set pid file if not given # if test -z "$mysqld_pid_file_path" then mysqld_pid_file_path=$datadir/`hostname`.pid else case "$mysqld_pid_file_path" in /* ) ;; * ) mysqld_pid_file_path="$datadir/$mysqld_pid_file_path" ;; esac fi case "$mode" in 'start') # Start daemon # Safeguard (relative paths, core dumps..) cd $basedir echo $echo_n "Starting MySQL" if test -x $bindir/mysqld_safe then # Give extra arguments to mysqld with the my.cnf file. This script # may be overwritten at next upgrade. $bindir/mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path" $other_args >/dev/null 2>&1 & wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$? # Make lock for RedHat / SuSE if test -w "$lockdir" then touch "$lock_file_path" fi exit $return_value else log_failure_msg "Couldn't find MySQL server ($bindir/mysqld_safe)" fi ;; 'stop') # Stop daemon. We use a signal here to avoid having to know the # root password. if test -s "$mysqld_pid_file_path" then # signal mysqld_safe that it needs to stop touch "$mysqld_pid_file_path.shutdown" mysqld_pid=`cat "$mysqld_pid_file_path"` if (kill -0 $mysqld_pid 2>/dev/null) then echo $echo_n "Shutting down MySQL" kill $mysqld_pid # mysqld should remove the pid file when it exits, so wait for it. wait_for_pid removed "$mysqld_pid" "$mysqld_pid_file_path"; return_value=$? else log_failure_msg "MySQL server process #$mysqld_pid is not running!" rm "$mysqld_pid_file_path" fi # Delete lock for RedHat / SuSE if test -f "$lock_file_path" then rm -f "$lock_file_path" fi exit $return_value else log_failure_msg "MySQL server PID file could not be found!" fi ;; 'restart') # Stop the service and regardless of whether it was # running or not, start it again. if $0 stop $other_args; then $0 start $other_args else log_failure_msg "Failed to stop running server, so refusing to try to start." exit 1 fi ;; 'reload'|'force-reload') if test -s "$mysqld_pid_file_path" ; then read mysqld_pid < "$mysqld_pid_file_path" kill -HUP $mysqld_pid && log_success_msg "Reloading service MySQL" touch "$mysqld_pid_file_path" else log_failure_msg "MySQL PID file could not be found!" exit 1 fi ;; 'status') # First, check to see if pid file exists if test -s "$mysqld_pid_file_path" ; then read mysqld_pid < "$mysqld_pid_file_path" if kill -0 $mysqld_pid 2>/dev/null ; then log_success_msg "MySQL running ($mysqld_pid)" exit 0 else log_failure_msg "MySQL is not running, but PID file exists" exit 1 fi else # Try to find appropriate mysqld process mysqld_pid=`pidof $libexecdir/mysqld` # test if multiple pids exist pid_count=`echo $mysqld_pid | wc -w` if test $pid_count -gt 1 ; then log_failure_msg "Multiple MySQL running but PID file could not be found ($mysqld_pid)" exit 5 elif test -z $mysqld_pid ; then if test -f "$lock_file_path" ; then log_failure_msg "MySQL is not running, but lock file ($lock_file_path) exists" exit 2 fi log_failure_msg "MySQL is not running" exit 3 else log_failure_msg "MySQL is running but PID file could not be found" exit 4 fi fi ;; *) # usage basename=`basename "$0"` echo "Usage: $basename {start|stop|restart|reload|force-reload|status} [ MySQL server options ]" exit 1 ;; esac exit 0
{ "pile_set_name": "Github" }
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* internal.h: ramfs internal definitions * * Copyright (C) 2005 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) */ extern const struct inode_operations ramfs_file_inode_operations;
{ "pile_set_name": "Github" }
require('../../../modules/es7.array.flat-map'); module.exports = require('../../../modules/_entry-virtual')('Array').flatMap;
{ "pile_set_name": "Github" }
import Parser from './htmlparser2/lib/Parser' // monkey patching Parser.prototype.ondeclaration = function(value){ if(this._cbs.ondeclaration){ this._cbs.ondeclaration(value); } else if(this._cbs.onprocessinginstruction){ var name = this._getInstructionName(value); this._cbs.onprocessinginstruction("!" + name, "!" + value); } } Parser.prototype.oncdata = function(value){ this._updatePosition(1); if(this._options.xmlMode || this._options.recognizeCDATA){ if(this._cbs.oncdatastart) this._cbs.oncdatastart(value) // we don't want `ontext` getting called here if(this._cbs.oncdataend) this._cbs.oncdataend() } else { this.oncomment("[CDATA[" + value + "]]") } } export default Parser
{ "pile_set_name": "Github" }
Port from Fedora20 Upstream-Status: Pending Signed-off-by: Qian Lei <qianl.fnst@cn.fujitsu.com> diff -up cmpi-bindings-0.9.5/swig/python/CMakeLists.txt.old cmpi-bindings-0.9.5/swig/python/CMakeLists.txt --- cmpi-bindings-0.9.5/swig/python/CMakeLists.txt.old 2013-08-06 15:57:03.576285764 +0200 +++ cmpi-bindings-0.9.5/swig/python/CMakeLists.txt 2013-08-06 15:57:14.891345941 +0200 @@ -9,7 +9,7 @@ SET (BUILD_SHARED_LIBS ON) FIND_PACKAGE(PythonInterp REQUIRED) -EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} -c "from sys import stdout; from distutils import sysconfig; stdout.write(sysconfig.get_python_lib())" OUTPUT_VARIABLE PYTHON_LIB_DIR) +EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} -c "from sys import stdout; from distutils import sysconfig; stdout.write(sysconfig.get_python_lib(1))" OUTPUT_VARIABLE PYTHON_LIB_DIR) IF (NOT PYTHON_SITE_DIR) SET (PYTHON_SITE_DIR ${PYTHON_LIB_DIR})
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: de67d260a82e87742b9c3c297379ffb3 timeCreated: 1474948268 licenseType: Pro PluginImporter: serializedVersion: 1 iconMap: {} executionOrder: {} isPreloaded: 0 platformData: Any: enabled: 1 settings: {} Editor: enabled: 0 settings: CPU: AnyCPU DefaultValueInitialized: true OS: AnyOS Linux: enabled: 0 settings: CPU: x86 Linux64: enabled: 0 settings: CPU: x86_64 LinuxUniversal: enabled: 0 settings: CPU: None OSXIntel: enabled: 0 settings: CPU: AnyCPU OSXIntel64: enabled: 0 settings: CPU: AnyCPU OSXUniversal: enabled: 0 settings: CPU: None Win: enabled: 1 settings: CPU: AnyCPU Win64: enabled: 1 settings: CPU: AnyCPU WindowsStoreApps: enabled: 0 settings: CPU: AnyCPU userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
local mType = Game.createMonsterType("Orc Cult Minion") local monster = {} monster.description = "an orc cult minion" monster.experience = 850 monster.outfit = { lookType = 50, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookAddons = 0, lookMount = 0 } monster.health = 1000 monster.maxHealth = 1000 monster.race = "blood" monster.corpse = 5996 monster.speed = 105 monster.summonCost = 310 monster.maxSummons = 0 monster.changeTarget = { interval = 4000, chance = 10 } monster.strategiesTarget = { nearest = 70, health = 10, damage = 10, random = 10, } monster.flags = { summonable = true, attackable = true, hostile = true, convinceable = true, pushable = false, rewardBoss = false, illusionable = false, canPushItems = true, canPushCreatures = false, staticAttackChance = 95, targetDistance = 1, runHealth = 0, healthHidden = false, canWalkOnEnergy = false, canWalkOnFire = false, canWalkOnPoison = false } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, {text = "Orc powaaa!", yell = false} } monster.loot = { {id = "gold coin", chance = 100000, maxCount = 166}, {id = "strong health potion", chance = 15930}, {id = "small topaz", chance = 1238, maxCount = 3}, {id = "orcish axe", chance = 9190}, {id = "cultish robe", chance = 19360}, {id = "red mushroom", chance = 6250, maxCount = 3}, {id = "berserk potion", chance = 860, maxCount = 2}, {id = "meat", chance = 4780} } monster.attacks = { {name ="combat", type = COMBAT_PHYSICALDAMAGE, interval = 2000, chance = 100, minDamage = 0, maxDamage = -230, effect = CONST_ME_DRAWBLOOD}, {name ="combat", interval = 2000, chance = 20, minDamage = -120, maxDamage = -170, type = COMBAT_PHYSICALDAMAGE, range = 7, shootEffect = CONST_ANI_SPEAR, target = false} } monster.defenses = { defense = 30, armor = 30 } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 0}, {type = COMBAT_ENERGYDAMAGE, percent = 0}, {type = COMBAT_EARTHDAMAGE, percent = 0}, {type = COMBAT_FIREDAMAGE, percent = 0}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = 0}, {type = COMBAT_HOLYDAMAGE , percent = 0}, {type = COMBAT_DEATHDAMAGE , percent = 10} } monster.immunities = { {type = "paralyze", condition = false}, {type = "outfit", condition = false}, {type = "invisible", condition = true}, {type = "bleed", condition = false} } mType:register(monster)
{ "pile_set_name": "Github" }
7--Cheering/7_Cheering_Cheering_7_687.jpg 2 569.361022949 81.1764297485 54.0473022461 75.7154769897 0.999118864536 818.185546875 212.29486084 34.9154052734 42.137802124 0.979305565357
{ "pile_set_name": "Github" }
<!doctype html> <html lang="en-us"> <head> <title>prepend</title> <link rel="stylesheet" href="assets/css/screen.css" /> </head> <body> <div class="site"> <div class="site-hd" role="banner"> <h2>Goodnight Moon</h2> <h1>prepend</h1> </div> <div class="site-bd" role="main"> <p>Dolor sit amet.</p> <p>Lorem ipsum.</p> </div> <div class="site-ft" role="contentinfo"> <p>MIT License</p> <small>&copy; 1984</small> </div> </div> <script src="assets/js/controllers/home.js"></script> </body> </html>
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); namespace Shopware\Core\Framework\DataAbstractionLayer\Search\AggregationResult\Metric; use Shopware\Core\Framework\DataAbstractionLayer\Search\AggregationResult\AggregationResult; class StatsResult extends AggregationResult { /** * @var mixed|null */ protected $min; /** * @var mixed|null */ protected $max; /** * @var float|null */ protected $avg; /** * @var float|null */ protected $sum; public function __construct(string $name, $min, $max, ?float $avg, ?float $sum) { parent::__construct($name); $this->min = $min; $this->max = $max; $this->avg = $avg; $this->sum = $sum; } public function getMin() { return $this->min; } public function getMax() { return $this->max; } public function getAvg(): ?float { return $this->avg; } public function getSum(): ?float { return $this->sum; } }
{ "pile_set_name": "Github" }
import pytest from jupytext.compare import compare import jupytext from .utils import skip_if_dict_is_not_ordered HEADER = { ".py": """# --- # jupyter: # jupytext: # main_language: python # --- """, ".R": """# --- # jupyter: # jupytext: # main_language: python # --- """, ".md": """--- jupyter: jupytext: main_language: python --- """, ".Rmd": """--- jupyter: jupytext: main_language: python --- """, } ACTIVE_ALL = { ".py": """# + active="ipynb,py,R,Rmd" # This cell is active in all extensions """, ".Rmd": """```{python active="ipynb,py,R,Rmd"} # This cell is active in all extensions ``` """, ".md": """```python active="ipynb,py,R,Rmd" # This cell is active in all extensions ``` """, ".R": """# + active="ipynb,py,R,Rmd" # This cell is active in all extensions """, ".ipynb": { "cell_type": "code", "source": "# This cell is active in all extensions", "metadata": {"active": "ipynb,py,R,Rmd"}, "execution_count": None, "outputs": [], }, } def check_active_cell(ext, active_dict): text = ("" if ext == ".py" else HEADER[ext]) + active_dict[ext] nb = jupytext.reads(text, ext) assert len(nb.cells) == 1 compare(jupytext.writes(nb, ext), text) compare(nb.cells[0], active_dict[".ipynb"]) @pytest.mark.parametrize("ext", [".Rmd", ".md", ".py", ".R"]) def test_active_all(ext, no_jupytext_version_number): check_active_cell(ext, ACTIVE_ALL) ACTIVE_IPYNB = { ".py": """# + active="ipynb" # # This cell is active only in ipynb # %matplotlib inline """, ".Rmd": """```{python active="ipynb", eval=FALSE} # This cell is active only in ipynb %matplotlib inline ``` """, ".md": """```python active="ipynb" # This cell is active only in ipynb %matplotlib inline ``` """, ".R": """# + active="ipynb" # # This cell is active only in ipynb # %matplotlib inline """, ".ipynb": { "cell_type": "code", "source": "# This cell is active only in ipynb\n" "%matplotlib inline", "metadata": {"active": "ipynb"}, "execution_count": None, "outputs": [], }, } @skip_if_dict_is_not_ordered @pytest.mark.parametrize("ext", [".Rmd", ".md", ".py", ".R"]) def test_active_ipynb(ext, no_jupytext_version_number): check_active_cell(ext, ACTIVE_IPYNB) ACTIVE_IPYNB_RMD_USING_TAG = { ".py": """# + tags=["active-ipynb-Rmd"] # # This cell is active only in ipynb and Rmd # %matplotlib inline """, ".Rmd": """```{python tags=c("active-ipynb-Rmd")} # This cell is active only in ipynb and Rmd # %matplotlib inline ``` """, ".md": """```python tags=["active-ipynb-Rmd"] # This cell is active only in ipynb and Rmd %matplotlib inline ``` """, ".R": """# + tags=["active-ipynb-Rmd"] # # This cell is active only in ipynb and Rmd # %matplotlib inline """, ".ipynb": { "cell_type": "code", "source": "# This cell is active only in ipynb and Rmd\n" "%matplotlib inline", "metadata": {"tags": ["active-ipynb-Rmd"]}, "execution_count": None, "outputs": [], }, } @skip_if_dict_is_not_ordered @pytest.mark.parametrize("ext", [".Rmd", ".md", ".py", ".R"]) def test_active_ipynb_rmd_using_tags(ext, no_jupytext_version_number): check_active_cell(ext, ACTIVE_IPYNB_RMD_USING_TAG) ACTIVE_IPYNB_RSPIN = { ".R": """#+ active="ipynb", eval=FALSE # # This cell is active only in ipynb # 1 + 1 """, ".ipynb": { "cell_type": "code", "source": "# This cell is active only in ipynb\n" "1 + 1", "metadata": {"active": "ipynb"}, "execution_count": None, "outputs": [], }, } @skip_if_dict_is_not_ordered def test_active_ipynb_rspin(no_jupytext_version_number): nb = jupytext.reads(ACTIVE_IPYNB_RSPIN[".R"], "R:spin") assert len(nb.cells) == 1 compare(jupytext.writes(nb, "R:spin"), ACTIVE_IPYNB_RSPIN[".R"]) compare(nb.cells[0], ACTIVE_IPYNB_RSPIN[".ipynb"]) ACTIVE_PY_IPYNB = { ".py": """# + active="ipynb,py" # This cell is active in py and ipynb extensions """, ".Rmd": """```{python active="ipynb,py", eval=FALSE} # This cell is active in py and ipynb extensions ``` """, ".md": """```python active="ipynb,py" # This cell is active in py and ipynb extensions ``` """, ".R": """# + active="ipynb,py" # # This cell is active in py and ipynb extensions """, ".ipynb": { "cell_type": "code", "source": "# This cell is active in py and " "ipynb extensions", "metadata": {"active": "ipynb,py"}, "execution_count": None, "outputs": [], }, } @skip_if_dict_is_not_ordered @pytest.mark.parametrize("ext", [".Rmd", ".md", ".py", ".R"]) def test_active_py_ipynb(ext, no_jupytext_version_number): check_active_cell(ext, ACTIVE_PY_IPYNB) ACTIVE_PY_R_IPYNB = { ".py": """# + active="ipynb,py,R" # This cell is active in py, R and ipynb extensions """, ".Rmd": """```{python active="ipynb,py,R", eval=FALSE} # This cell is active in py, R and ipynb extensions ``` """, ".R": """# + active="ipynb,py,R" # This cell is active in py, R and ipynb extensions """, ".ipynb": { "cell_type": "code", "source": "# This cell is active in py, R and " "ipynb extensions", "metadata": {"active": "ipynb,py,R"}, "execution_count": None, "outputs": [], }, } @skip_if_dict_is_not_ordered @pytest.mark.parametrize("ext", [".Rmd", ".py", ".R"]) def test_active_py_r_ipynb(ext, no_jupytext_version_number): check_active_cell(ext, ACTIVE_PY_R_IPYNB) ACTIVE_RMD = { ".py": """# + active="Rmd" # # This cell is active in Rmd only """, ".Rmd": """```{python active="Rmd"} # This cell is active in Rmd only ``` """, ".R": """# + active="Rmd" # # This cell is active in Rmd only """, ".ipynb": { "cell_type": "raw", "source": "# This cell is active in Rmd only", "metadata": {"active": "Rmd"}, }, } @skip_if_dict_is_not_ordered @pytest.mark.parametrize("ext", [".Rmd", ".py", ".R"]) def test_active_rmd(ext, no_jupytext_version_number): check_active_cell(ext, ACTIVE_RMD) ACTIVE_NOT_INCLUDE_RMD = { ".py": """# + tags=["remove_cell"] active="Rmd" # # This cell is active in Rmd only """, ".Rmd": """```{python include=FALSE, active="Rmd"} # This cell is active in Rmd only ``` """, ".R": """# + tags=["remove_cell"] active="Rmd" # # This cell is active in Rmd only """, ".ipynb": { "cell_type": "raw", "source": "# This cell is active in Rmd only", "metadata": {"active": "Rmd", "tags": ["remove_cell"]}, }, } @skip_if_dict_is_not_ordered @pytest.mark.parametrize("ext", [".Rmd", ".py", ".R"]) def test_active_not_include_rmd(ext, no_jupytext_version_number): check_active_cell(ext, ACTIVE_NOT_INCLUDE_RMD) def test_active_cells_from_py_percent( text="""# %% active="py" print('should only be displayed in py file') # %% tags=["active-py"] print('should only be displayed in py file') # %% active="ipynb" # print('only in jupyter') """, ): """Example taken from https://github.com/mwouts/jupytext/issues/477""" nb = jupytext.reads(text, "py:percent") assert nb.cells[0].cell_type == "raw" assert nb.cells[1].cell_type == "raw" assert nb.cells[2].cell_type == "code" assert nb.cells[2].source == "print('only in jupyter')" text2 = jupytext.writes(nb, "py:percent") compare(text2, text) def test_active_cells_from_py_light( text="""# + active="py" print('should only be displayed in py file') # + tags=["active-py"] print('should only be displayed in py file') # + active="ipynb" # print('only in jupyter') """, ): """Example adapted from https://github.com/mwouts/jupytext/issues/477""" nb = jupytext.reads(text, "py") assert nb.cells[0].cell_type == "raw" assert nb.cells[1].cell_type == "raw" assert nb.cells[2].cell_type == "code" assert nb.cells[2].source == "print('only in jupyter')" text2 = jupytext.writes(nb, "py") compare(text2, text)
{ "pile_set_name": "Github" }
/* * Copyright (c) 2013-2016 Dave Collins <dave@davec.name> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "encoding/hex" "fmt" "io" "os" "reflect" "regexp" "strconv" "strings" ) var ( // uint8Type is a reflect.Type representing a uint8. It is used to // convert cgo types to uint8 slices for hexdumping. uint8Type = reflect.TypeOf(uint8(0)) // cCharRE is a regular expression that matches a cgo char. // It is used to detect character arrays to hexdump them. cCharRE = regexp.MustCompile(`^.*\._Ctype_char$`) // cUnsignedCharRE is a regular expression that matches a cgo unsigned // char. It is used to detect unsigned character arrays to hexdump // them. cUnsignedCharRE = regexp.MustCompile(`^.*\._Ctype_unsignedchar$`) // cUint8tCharRE is a regular expression that matches a cgo uint8_t. // It is used to detect uint8_t arrays to hexdump them. cUint8tCharRE = regexp.MustCompile(`^.*\._Ctype_uint8_t$`) ) // dumpState contains information about the state of a dump operation. type dumpState struct { w io.Writer depth int pointers map[uintptr]int ignoreNextType bool ignoreNextIndent bool cs *ConfigState } // indent performs indentation according to the depth level and cs.Indent // option. func (d *dumpState) indent() { if d.ignoreNextIndent { d.ignoreNextIndent = false return } d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) } // unpackValue returns values inside of non-nil interfaces when possible. // This is useful for data types like structs, arrays, slices, and maps which // can contain varying types packed inside an interface. func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { if v.Kind() == reflect.Interface && !v.IsNil() { v = v.Elem() } return v } // dumpPtr handles formatting of pointers by indirecting them as necessary. func (d *dumpState) dumpPtr(v reflect.Value) { // Remove pointers at or below the current depth from map used to detect // circular refs. for k, depth := range d.pointers { if depth >= d.depth { delete(d.pointers, k) } } // Keep list of all dereferenced pointers to show later. pointerChain := make([]uintptr, 0) // Figure out how many levels of indirection there are by dereferencing // pointers and unpacking interfaces down the chain while detecting circular // references. nilFound := false cycleFound := false indirects := 0 ve := v for ve.Kind() == reflect.Ptr { if ve.IsNil() { nilFound = true break } indirects++ addr := ve.Pointer() pointerChain = append(pointerChain, addr) if pd, ok := d.pointers[addr]; ok && pd < d.depth { cycleFound = true indirects-- break } d.pointers[addr] = d.depth ve = ve.Elem() if ve.Kind() == reflect.Interface { if ve.IsNil() { nilFound = true break } ve = ve.Elem() } } // Display type information. d.w.Write(openParenBytes) d.w.Write(bytes.Repeat(asteriskBytes, indirects)) d.w.Write([]byte(ve.Type().String())) d.w.Write(closeParenBytes) // Display pointer information. if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 { d.w.Write(openParenBytes) for i, addr := range pointerChain { if i > 0 { d.w.Write(pointerChainBytes) } printHexPtr(d.w, addr) } d.w.Write(closeParenBytes) } // Display dereferenced value. d.w.Write(openParenBytes) switch { case nilFound: d.w.Write(nilAngleBytes) case cycleFound: d.w.Write(circularBytes) default: d.ignoreNextType = true d.dump(ve) } d.w.Write(closeParenBytes) } // dumpSlice handles formatting of arrays and slices. Byte (uint8 under // reflection) arrays and slices are dumped in hexdump -C fashion. func (d *dumpState) dumpSlice(v reflect.Value) { // Determine whether this type should be hex dumped or not. Also, // for types which should be hexdumped, try to use the underlying data // first, then fall back to trying to convert them to a uint8 slice. var buf []uint8 doConvert := false doHexDump := false numEntries := v.Len() if numEntries > 0 { vt := v.Index(0).Type() vts := vt.String() switch { // C types that need to be converted. case cCharRE.MatchString(vts): fallthrough case cUnsignedCharRE.MatchString(vts): fallthrough case cUint8tCharRE.MatchString(vts): doConvert = true // Try to use existing uint8 slices and fall back to converting // and copying if that fails. case vt.Kind() == reflect.Uint8: // We need an addressable interface to convert the type // to a byte slice. However, the reflect package won't // give us an interface on certain things like // unexported struct fields in order to enforce // visibility rules. We use unsafe, when available, to // bypass these restrictions since this package does not // mutate the values. vs := v if !vs.CanInterface() || !vs.CanAddr() { vs = unsafeReflectValue(vs) } if !UnsafeDisabled { vs = vs.Slice(0, numEntries) // Use the existing uint8 slice if it can be // type asserted. iface := vs.Interface() if slice, ok := iface.([]uint8); ok { buf = slice doHexDump = true break } } // The underlying data needs to be converted if it can't // be type asserted to a uint8 slice. doConvert = true } // Copy and convert the underlying type if needed. if doConvert && vt.ConvertibleTo(uint8Type) { // Convert and copy each element into a uint8 byte // slice. buf = make([]uint8, numEntries) for i := 0; i < numEntries; i++ { vv := v.Index(i) buf[i] = uint8(vv.Convert(uint8Type).Uint()) } doHexDump = true } } // Hexdump the entire slice as needed. if doHexDump { indent := strings.Repeat(d.cs.Indent, d.depth) str := indent + hex.Dump(buf) str = strings.Replace(str, "\n", "\n"+indent, -1) str = strings.TrimRight(str, d.cs.Indent) d.w.Write([]byte(str)) return } // Recursively call dump for each item. for i := 0; i < numEntries; i++ { d.dump(d.unpackValue(v.Index(i))) if i < (numEntries - 1) { d.w.Write(commaNewlineBytes) } else { d.w.Write(newlineBytes) } } } // dump is the main workhorse for dumping a value. It uses the passed reflect // value to figure out what kind of object we are dealing with and formats it // appropriately. It is a recursive function, however circular data structures // are detected and handled properly. func (d *dumpState) dump(v reflect.Value) { // Handle invalid reflect values immediately. kind := v.Kind() if kind == reflect.Invalid { d.w.Write(invalidAngleBytes) return } // Handle pointers specially. if kind == reflect.Ptr { d.indent() d.dumpPtr(v) return } // Print type information unless already handled elsewhere. if !d.ignoreNextType { d.indent() d.w.Write(openParenBytes) d.w.Write([]byte(v.Type().String())) d.w.Write(closeParenBytes) d.w.Write(spaceBytes) } d.ignoreNextType = false // Display length and capacity if the built-in len and cap functions // work with the value's kind and the len/cap itself is non-zero. valueLen, valueCap := 0, 0 switch v.Kind() { case reflect.Array, reflect.Slice, reflect.Chan: valueLen, valueCap = v.Len(), v.Cap() case reflect.Map, reflect.String: valueLen = v.Len() } if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 { d.w.Write(openParenBytes) if valueLen != 0 { d.w.Write(lenEqualsBytes) printInt(d.w, int64(valueLen), 10) } if !d.cs.DisableCapacities && valueCap != 0 { if valueLen != 0 { d.w.Write(spaceBytes) } d.w.Write(capEqualsBytes) printInt(d.w, int64(valueCap), 10) } d.w.Write(closeParenBytes) d.w.Write(spaceBytes) } // Call Stringer/error interfaces if they exist and the handle methods flag // is enabled if !d.cs.DisableMethods { if (kind != reflect.Invalid) && (kind != reflect.Interface) { if handled := handleMethods(d.cs, d.w, v); handled { return } } } switch kind { case reflect.Invalid: // Do nothing. We should never get here since invalid has already // been handled above. case reflect.Bool: printBool(d.w, v.Bool()) case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: printInt(d.w, v.Int(), 10) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: printUint(d.w, v.Uint(), 10) case reflect.Float32: printFloat(d.w, v.Float(), 32) case reflect.Float64: printFloat(d.w, v.Float(), 64) case reflect.Complex64: printComplex(d.w, v.Complex(), 32) case reflect.Complex128: printComplex(d.w, v.Complex(), 64) case reflect.Slice: if v.IsNil() { d.w.Write(nilAngleBytes) break } fallthrough case reflect.Array: d.w.Write(openBraceNewlineBytes) d.depth++ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { d.indent() d.w.Write(maxNewlineBytes) } else { d.dumpSlice(v) } d.depth-- d.indent() d.w.Write(closeBraceBytes) case reflect.String: d.w.Write([]byte(strconv.Quote(v.String()))) case reflect.Interface: // The only time we should get here is for nil interfaces due to // unpackValue calls. if v.IsNil() { d.w.Write(nilAngleBytes) } case reflect.Ptr: // Do nothing. We should never get here since pointers have already // been handled above. case reflect.Map: // nil maps should be indicated as different than empty maps if v.IsNil() { d.w.Write(nilAngleBytes) break } d.w.Write(openBraceNewlineBytes) d.depth++ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { d.indent() d.w.Write(maxNewlineBytes) } else { numEntries := v.Len() keys := v.MapKeys() if d.cs.SortKeys { sortValues(keys, d.cs) } for i, key := range keys { d.dump(d.unpackValue(key)) d.w.Write(colonSpaceBytes) d.ignoreNextIndent = true d.dump(d.unpackValue(v.MapIndex(key))) if i < (numEntries - 1) { d.w.Write(commaNewlineBytes) } else { d.w.Write(newlineBytes) } } } d.depth-- d.indent() d.w.Write(closeBraceBytes) case reflect.Struct: d.w.Write(openBraceNewlineBytes) d.depth++ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { d.indent() d.w.Write(maxNewlineBytes) } else { vt := v.Type() numFields := v.NumField() for i := 0; i < numFields; i++ { d.indent() vtf := vt.Field(i) d.w.Write([]byte(vtf.Name)) d.w.Write(colonSpaceBytes) d.ignoreNextIndent = true d.dump(d.unpackValue(v.Field(i))) if i < (numFields - 1) { d.w.Write(commaNewlineBytes) } else { d.w.Write(newlineBytes) } } } d.depth-- d.indent() d.w.Write(closeBraceBytes) case reflect.Uintptr: printHexPtr(d.w, uintptr(v.Uint())) case reflect.UnsafePointer, reflect.Chan, reflect.Func: printHexPtr(d.w, v.Pointer()) // There were not any other types at the time this code was written, but // fall back to letting the default fmt package handle it in case any new // types are added. default: if v.CanInterface() { fmt.Fprintf(d.w, "%v", v.Interface()) } else { fmt.Fprintf(d.w, "%v", v.String()) } } } // fdump is a helper function to consolidate the logic from the various public // methods which take varying writers and config states. func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { for _, arg := range a { if arg == nil { w.Write(interfaceBytes) w.Write(spaceBytes) w.Write(nilAngleBytes) w.Write(newlineBytes) continue } d := dumpState{w: w, cs: cs} d.pointers = make(map[uintptr]int) d.dump(reflect.ValueOf(arg)) d.w.Write(newlineBytes) } } // Fdump formats and displays the passed arguments to io.Writer w. It formats // exactly the same as Dump. func Fdump(w io.Writer, a ...interface{}) { fdump(&Config, w, a...) } // Sdump returns a string with the passed arguments formatted exactly the same // as Dump. func Sdump(a ...interface{}) string { var buf bytes.Buffer fdump(&Config, &buf, a...) return buf.String() } /* Dump displays the passed parameters to standard out with newlines, customizable indentation, and additional debug information such as complete types and all pointer addresses used to indirect to the final value. It provides the following features over the built-in printing facilities provided by the fmt package: * Pointers are dereferenced and followed * Circular data structures are detected and handled properly * Custom Stringer/error interfaces are optionally invoked, including on unexported types * Custom types which only implement the Stringer/error interfaces via a pointer receiver are optionally invoked when passing non-pointer variables * Byte arrays and slices are dumped like the hexdump -C command which includes offsets, byte values in hex, and ASCII output The configuration options are controlled by an exported package global, spew.Config. See ConfigState for options documentation. See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to get the formatted result as a string. */ func Dump(a ...interface{}) { fdump(&Config, os.Stdout, a...) }
{ "pile_set_name": "Github" }
# frama-c -wp -wp-steps 300 [...] [kernel] Parsing tests/wp_typed/user_init.i (no preprocessing) [wp] Running WP plugin... [wp] Loading driver 'share/wp.driver' [wp] [CFG] Goal init_exits : Valid (Unreachable) [wp] [CFG] Goal init_t1_exits : Valid (Unreachable) [wp] [CFG] Goal init_t2_v1_exits : Valid (Unreachable) [wp] [CFG] Goal init_t2_v2_exits : Valid (Unreachable) [wp] [CFG] Goal init_t2_v3_exits : Valid (Unreachable) [wp] Warning: Missing RTE guards [wp] 16 goals scheduled [wp] [Qed] Goal typed_init_t2_bis_v1_loop_assigns_part1 : Valid [wp] [Alt-Ergo 2.0.0] Goal typed_init_t2_bis_v1_loop_assigns_part2 : Unsuccess [wp] [Alt-Ergo 2.0.0] Goal typed_init_t2_bis_v1_loop_assigns_part3 : Unsuccess [wp] [Qed] Goal typed_init_t2_bis_v1_assigns_exit_part1 : Valid [wp] [Alt-Ergo 2.0.0] Goal typed_init_t2_bis_v1_assigns_exit_part2 : Unsuccess [wp] [Qed] Goal typed_init_t2_bis_v1_assigns_exit_part3 : Valid [wp] [Qed] Goal typed_init_t2_bis_v1_assigns_normal_part1 : Valid [wp] [Alt-Ergo 2.0.0] Goal typed_init_t2_bis_v1_assigns_normal_part2 : Unsuccess [wp] [Qed] Goal typed_init_t2_v1_loop_assigns_part1 : Valid [wp] [Alt-Ergo 2.0.0] Goal typed_init_t2_v1_loop_assigns_part2 : Unsuccess [wp] [Alt-Ergo 2.0.0] Goal typed_init_t2_v1_loop_assigns_part3 : Unsuccess [wp] [Qed] Goal typed_init_t2_v1_loop_assigns_2_part1 : Valid [wp] [Alt-Ergo 2.0.0] Goal typed_init_t2_v1_loop_assigns_2_part2 : Unsuccess [wp] [Alt-Ergo 2.0.0] Goal typed_init_t2_v1_loop_assigns_2_part3 : Unsuccess [wp] [Qed] Goal typed_init_t2_v1_assigns_part1 : Valid [wp] [Alt-Ergo 2.0.0] Goal typed_init_t2_v1_assigns_part2 : Unsuccess [wp] Proved goals: 7 / 16 Qed: 7 Alt-Ergo 2.0.0: 0 (unsuccess: 9) [wp] Report in: 'tests/wp_typed/oracle_qualif/user_init.2.report.json' [wp] Report out: 'tests/wp_typed/result_qualif/user_init.2.report.json' ------------------------------------------------------------- Functions WP Alt-Ergo Total Success init_t2_v1 3 - 8 37.5% init_t2_bis_v1 4 - 8 50.0% -------------------------------------------------------------
{ "pile_set_name": "Github" }
;; -*- mode:lisp -*- (defsystem "browser-repl" :serial t :components ((:file "main")) :depends-on ("react-utilities"))
{ "pile_set_name": "Github" }
var invokePath = require('../internal/invokePath'), restParam = require('../function/restParam'); /** * Creates a function which invokes the method at `path` on a given object. * * @static * @memberOf _ * @category Utility * @param {Array|string} path The path of the method to invoke. * @returns {Function} Returns the new function. * @example * * var objects = [ * { 'a': { 'b': { 'c': _.constant(2) } } }, * { 'a': { 'b': { 'c': _.constant(1) } } } * ]; * * _.map(objects, _.method('a.b.c')); * // => [2, 1] * * _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c'); * // => [1, 2] */ var method = restParam(function(path, args) { return function(object) { return invokePath(object, path, args); } }); module.exports = method;
{ "pile_set_name": "Github" }
package it.niedermann.nextcloud.deck.ui.card; import android.content.Context; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.CallSuper; import androidx.annotation.ColorInt; import androidx.annotation.MenuRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.PopupMenu; import androidx.core.graphics.drawable.DrawableCompat; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.card.MaterialCardView; import org.jetbrains.annotations.Contract; import java.util.List; import it.niedermann.nextcloud.deck.R; import it.niedermann.nextcloud.deck.model.Account; import it.niedermann.nextcloud.deck.model.Card; import it.niedermann.nextcloud.deck.model.User; import it.niedermann.nextcloud.deck.model.enums.DBStatus; import it.niedermann.nextcloud.deck.model.full.FullCard; import it.niedermann.nextcloud.deck.util.DateUtil; import it.niedermann.nextcloud.deck.util.ViewUtil; public abstract class AbstractCardViewHolder extends RecyclerView.ViewHolder { public AbstractCardViewHolder(@NonNull View itemView) { super(itemView); } /** * Removes all {@link OnClickListener} and {@link OnLongClickListener} */ @CallSuper public void bind(@NonNull FullCard fullCard, @NonNull Account account, @Nullable Long boardRemoteId, boolean hasEditPermission, @MenuRes int optionsMenu, @NonNull CardOptionsItemSelectedListener optionsItemsSelectedListener, @NonNull String counterMaxValue, @ColorInt int mainColor) { final Context context = itemView.getContext(); bindCardClickListener(null); bindCardLongClickListener(null); getCardMenu().setVisibility(hasEditPermission ? View.VISIBLE : View.GONE); getCardTitle().setText(fullCard.getCard().getTitle().trim()); DrawableCompat.setTint(getNotSyncedYet().getDrawable(), mainColor); getNotSyncedYet().setVisibility(DBStatus.LOCAL_EDITED.equals(fullCard.getStatusEnum()) ? View.VISIBLE : View.GONE); if (fullCard.getCard().getDueDate() != null) { setupDueDate(getCardDueDate(), fullCard.getCard()); getCardDueDate().setVisibility(View.VISIBLE); } else { getCardDueDate().setVisibility(View.GONE); } getCardMenu().setOnClickListener(view -> { final PopupMenu popup = new PopupMenu(context, view); popup.inflate(optionsMenu); final Menu menu = popup.getMenu(); if (containsUser(fullCard.getAssignedUsers(), account.getUserName())) { menu.removeItem(menu.findItem(R.id.action_card_assign).getItemId()); } else { menu.removeItem(menu.findItem(R.id.action_card_unassign).getItemId()); } if (boardRemoteId == null || fullCard.getCard().getId() == null) { menu.removeItem(R.id.share_link); } popup.setOnMenuItemClickListener(item -> optionsItemsSelectedListener.onCardOptionsItemSelected(item, fullCard)); popup.show(); }); } protected abstract TextView getCardDueDate(); protected abstract ImageView getNotSyncedYet(); protected abstract TextView getCardTitle(); protected abstract View getCardMenu(); protected abstract MaterialCardView getCard(); public void bindCardClickListener(@Nullable OnClickListener l) { getCard().setOnClickListener(l); } public void bindCardLongClickListener(@Nullable OnLongClickListener l) { getCard().setOnLongClickListener(l); } public MaterialCardView getDraggable() { return getCard(); } private static void setupDueDate(@NonNull TextView cardDueDate, @NonNull Card card) { final Context context = cardDueDate.getContext(); cardDueDate.setText(DateUtil.getRelativeDateTimeString(context, card.getDueDate().getTime())); ViewUtil.themeDueDate(context, cardDueDate, card.getDueDate()); } @Contract("null, _ -> false") private static boolean containsUser(List<User> userList, String username) { if (userList != null) { for (User user : userList) { if (user.getPrimaryKey().equals(username)) { return true; } } } return false; } }
{ "pile_set_name": "Github" }
################################################################################ # This test is to test if group replication can be started with needed variables # persisted into mysqld-auto.cnf file. # Test: # 1. Persist configuration on server1. # 2. Restart server1, it must bootstrap the group. # 3. Persist configuration on server2. # 4. Restart server2, it must join the group. # 5. Clean up. ################################################################################ --source include/big_test.inc --source include/have_group_replication_plugin.inc --let $rpl_skip_group_replication_start= 1 --source include/group_replication.inc --echo --echo ############################################################ --echo # 1. Persist configuration on server1. --let $rpl_connection_name= server1 --source include/rpl_connection.inc --replace_result $group_replication_group_name GROUP_REPLICATION_GROUP_NAME --eval SET PERSIST group_replication_group_name= "$group_replication_group_name" --eval SET PERSIST group_replication_group_seeds= @@GLOBAL.group_replication_group_seeds --eval SET PERSIST group_replication_local_address= @@GLOBAL.group_replication_local_address SET PERSIST group_replication_start_on_boot= ON; SET PERSIST group_replication_bootstrap_group= ON; SET PERSIST group_replication_recovery_get_public_key= ON; --echo --echo ############################################################ --echo # 2. Restart server1, it must bootstrap the group. --let $allow_rpl_inited= 1 --source include/restart_mysqld.inc --let $rpl_server_number= 1 --source include/rpl_reconnect.inc --let $group_replication_member_state= ONLINE --source include/gr_wait_for_member_state.inc SELECT variable_name, variable_source FROM performance_schema.variables_info WHERE variable_source IN ('PERSISTED'); --echo --echo ############################################################ --echo # 3. Persist configuration on server2. --let $rpl_connection_name= server2 --source include/rpl_connection.inc --replace_result $group_replication_group_name GROUP_REPLICATION_GROUP_NAME --eval SET PERSIST group_replication_group_name= "$group_replication_group_name" --eval SET PERSIST group_replication_group_seeds= @@GLOBAL.group_replication_group_seeds --eval SET PERSIST group_replication_local_address= @@GLOBAL.group_replication_local_address SET PERSIST group_replication_start_on_boot= ON; SET PERSIST group_replication_recovery_get_public_key= ON; --echo --echo ############################################################ --echo # 4. Restart server2, it must join the group. --let $allow_rpl_inited= 1 --source include/restart_mysqld.inc --let $rpl_server_number= 2 --source include/rpl_reconnect.inc --let $group_replication_member_state= ONLINE --source include/gr_wait_for_member_state.inc --let $group_replication_number_of_members= 2 --source include/gr_wait_for_number_of_members.inc SELECT variable_name, variable_source FROM performance_schema.variables_info WHERE variable_source IN ('PERSISTED'); --echo --echo ############################################################ --echo # 5. Clean up. --let $rpl_connection_name= server1 --source include/rpl_connection.inc RESET PERSIST; SET GLOBAL group_replication_start_on_boot= OFF; --let $rpl_connection_name= server2 --source include/rpl_connection.inc RESET PERSIST; SET GLOBAL group_replication_start_on_boot= OFF; --source include/group_replication_end.inc
{ "pile_set_name": "Github" }
package squidpony.squidgrid.gui.gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.MathUtils; import squidpony.IFilter; import squidpony.squidmath.MathExtras; import squidpony.squidmath.ThrustAltRNG; import java.util.ArrayList; import java.util.Collection; /** * Implementations of {@link IFilter}, that all are meant to perform different changes to colors before they are * created. They should usually be passed to SquidColorCenter's constructor, which can use them. * <br> * Created by Tommy Ettinger on 10/31/2015. */ public final class Filters { private Filters() { /* You should not build me */ } /** * An IFilter that does nothing to the colors it is given but pass them along unchanged. */ public static class IdentityFilter implements IFilter<Color> { public IdentityFilter() { /* Nothing to do */ } @Override public Color alter(float r, float g, float b, float a) { return new Color(r, g, b, a); } } public static class ChainFilter implements IFilter<Color> { public ArrayList<IFilter<Color>> chains; public ChainFilter(IFilter<Color> firstFilter, IFilter<Color> secondFilter) { chains = new ArrayList<>(2); chains.add(firstFilter); chains.add(secondFilter); } public ChainFilter(IFilter<Color> firstFilter, IFilter<Color> secondFilter, IFilter<Color> thirdFilter) { chains = new ArrayList<>(2); chains.add(firstFilter); chains.add(secondFilter); chains.add(thirdFilter); } public ChainFilter(Collection<IFilter<Color>> filters) { if(filters == null || filters.isEmpty()) { chains = new ArrayList<>(); chains.add(new IdentityFilter()); } else chains = new ArrayList<>(filters); } @Override public Color alter(float r, float g, float b, float a) { Color c = chains.get(0).alter(r, g, b, a); for (int i = 1; i < chains.size(); i++) { c = chains.get(i).alter(c.r, c.g, c.b, c.a); } return c; } } /** * An IFilter that converts all colors passed to it to grayscale, like a black and white film. */ public static class GrayscaleFilter implements IFilter<Color> { public GrayscaleFilter() { /* Nothing to do */ } @Override public Color alter(float r, float g, float b, float a) { float v = (r + g + b) / 3f; return new Color(v, v, v, a); } } /** * An IFilter that tracks the highest brightness for any component it was assigned and stores it in its {@link #state} * field. You probably want to set state to 0f before filtering a bunch of colors, if this is being used to find * the brightest color on the screen. */ public static class MaxValueFilter implements IFilter<Color> { public float state; public MaxValueFilter() { state = 0f; } @Override public Color alter(float r, float g, float b, float a) { state = Math.max(state, Math.max(r, Math.max(g, b))); return new Color(r, g, b, a); } } /** * An IFilter that performs a brightness adjustment to make dark areas lighter and light areas not much less bright. */ public static class GammaCorrectFilter implements IFilter<Color> { public float gamma; public float maxValue; /** * Sets up a GammaCorrectFilter with the desired gamma adjustment. * * @param gamma should be 1.0 or less, and must be greater than 0. Typical values are between 0.4 to 0.8. * @param maxValue the maximum brightness in the colors this will be passed; use MaxValueFilter for this */ public GammaCorrectFilter(float gamma, float maxValue) { this.gamma = gamma; this.maxValue = 1f / (float) Math.pow(maxValue, gamma); } @Override public Color alter(float r, float g, float b, float a) { return new Color(maxValue * (float) Math.pow(r, gamma), maxValue * (float) Math.pow(g, gamma), maxValue * (float) Math.pow(b, gamma), a); } } /** * An IFilter that is constructed with a color and linear-interpolates any color it is told to alter toward the color * it was constructed with. */ public static class LerpFilter implements IFilter<Color> { public float r, g, b, a, amount; /** * Sets up a LerpFilter with the desired color to linearly interpolate towards. * * @param r the red component to lerp towards * @param g the green component to lerp towards * @param b the blue component to lerp towards * @param a the opacity component to lerp towards * @param amount the amount to lerp by, should be between 0.0 and 1.0 */ public LerpFilter(float r, float g, float b, float a, float amount) { this.r = r; this.g = g; this.b = b; this.a = a; this.amount = amount; } /** * Sets up a LerpFilter with the desired color to linearly interpolate towards. * * @param color the Color to lerp towards * @param amount the amount to lerp by, should be between 0.0 and 1.0 */ public LerpFilter(Color color, float amount) { this.r = color.r; this.g = color.g; this.b = color.b; this.a = color.a; this.amount = amount; } @Override public Color alter(float r, float g, float b, float a) { return new Color(r, g, b, a).lerp(this.r, this.g, this.b, this.a, this.amount); } } /** * An IFilter that is constructed with a group of colors and linear-interpolates any color it is told to alter toward * the color it was constructed with that has the closest hue. */ public static class MultiLerpFilter implements IFilter<Color> { private SquidColorCenter globalSCC; public float[] state; /** * Sets up a MultiLerpFilter with the desired colors to linearly interpolate towards; the lengths of each given * array should be identical. * * @param r the red components to lerp towards * @param g the green components to lerp towards * @param b the blue components to lerp towards * @param a the opacity components to lerp towards * @param amount the amounts to lerp by, should each be between 0.0 and 1.0 */ public MultiLerpFilter(float[] r, float[] g, float[] b, float[] a, float[] amount) { state = new float[Math.min(r.length, Math.min(g.length, Math.min(b.length, Math.min(a.length, amount.length)))) * 6]; globalSCC = DefaultResources.getSCC(); for (int i = 0; i < state.length / 6; i++) { state[i * 6] = r[i]; state[i * 6 + 1] = g[i]; state[i * 6 + 2] = b[i]; state[i * 6 + 3] = a[i]; state[i * 6 + 4] = amount[i]; state[i * 6 + 5] = globalSCC.getHue(r[i], g[i], b[i]); } }/** * Sets up a MultiLerpFilter with the desired colors to linearly interpolate towards and their amounts. * * @param colors the Colors to lerp towards * @param amount the amounts to lerp by, should each be between 0.0 and 1.0 */ public MultiLerpFilter(Color[] colors, float[] amount) { state = new float[Math.min(colors.length, amount.length) * 6]; globalSCC = DefaultResources.getSCC(); for (int i = 0; i < state.length / 6; i++) { state[i * 6] = colors[i].r; state[i * 6 + 1] = colors[i].g; state[i * 6 + 2] = colors[i].b; state[i * 6 + 3] = colors[i].a; state[i * 6 + 4] = amount[i]; state[i * 6 + 5] = globalSCC.getHue(colors[i]); } } @Override public Color alter(float r, float g, float b, float a) { float givenH = globalSCC.getHue(r, g, b), givenS = globalSCC.getSaturation(r, g, b), minDiff = 999.0f, temp; if(givenS < 0.05) return new Color(r, g, b, a); int choice = 0; for (int i = 5; i < state.length; i += 6) { temp = state[i] - givenH; temp = (temp >= 0.5f) ? Math.abs(temp - 1f) % 1f : Math.abs(temp); if(temp < minDiff) { minDiff = temp; choice = i; } } choice /= 6; // rounds down return new Color(r, g, b, a).lerp(state[choice * 6], state[choice * 6 + 1], state[choice * 6 + 2], state[choice * 6 + 3], state[choice * 6 + 4]); } } /** * An IFilter that is constructed with a color and makes any color it is told to alter have the same hue as the given * color, have saturation that is somewhere between the given color's and the altered colors, and chiefly is * distinguishable from other colors by value. Useful for sepia effects, which can be created satisfactorily with * {@code new Filters.ColorizeFilter(SColor.CLOVE_BROWN, 0.6f, 0.0f)}. */ public static class ColorizeFilter implements IFilter<Color> { private SquidColorCenter globalSCC; public float targetHue, targetSaturation, saturationMultiplier, valueModifier; /** * Sets up a ColorizeFilter with the desired color to colorize towards. * * @param r the red component to colorize towards * @param g the green component to colorize towards * @param b the blue component to colorize towards */ public ColorizeFilter(float r, float g, float b) { globalSCC = DefaultResources.getSCC(); targetHue = globalSCC.getHue(r, g, b); targetSaturation = globalSCC.getSaturation(r, g, b); saturationMultiplier = 1f; valueModifier = 0f; } /** * Sets up a ColorizeFilter with the desired color to colorize towards. * * @param color the Color to colorize towards */ public ColorizeFilter(Color color) { globalSCC = DefaultResources.getSCC(); targetHue = globalSCC.getHue(color); targetSaturation = globalSCC.getSaturation(color); saturationMultiplier = 1f; valueModifier = 0f; } /** * Sets up a ColorizeFilter with the desired color to colorize towards. * * @param r the red component to colorize towards * @param g the green component to colorize towards * @param b the blue component to colorize towards * @param saturationMultiplier a multiplier to apply to the final color's saturation; may be greater than 1 * @param valueModifier a modifier that affects the final brightness value of any color this alters; * typically very small, such as in the -0.2f to 0.2f range */ public ColorizeFilter(float r, float g, float b, float saturationMultiplier, float valueModifier) { globalSCC = DefaultResources.getSCC(); targetHue = globalSCC.getHue(r, g, b); targetSaturation = globalSCC.getSaturation(r, g, b); this.saturationMultiplier = saturationMultiplier; this.valueModifier = valueModifier; } /** * Sets up a ColorizeFilter with the desired color to colorize towards. * * @param color the Color to colorize towards * @param saturationMultiplier a multiplier to apply to the final color's saturation; may be greater than 1 * @param valueModifier a modifier that affects the final brightness value of any color this alters; * typically very small, such as in the -0.2f to 0.2f range */ public ColorizeFilter(Color color, float saturationMultiplier, float valueModifier) { globalSCC = DefaultResources.getSCC(); targetHue = globalSCC.getHue(color); targetSaturation = globalSCC.getSaturation(color); this.saturationMultiplier = saturationMultiplier; this.valueModifier = valueModifier; } @Override public Color alter(float r, float g, float b, float a) { return globalSCC.getHSV( targetHue, Math.max(0f, Math.min((globalSCC.getSaturation(r, g, b) + targetSaturation) * 0.5f * saturationMultiplier, 1f)), globalSCC.getValue(r, g, b) * (1f - valueModifier) + valueModifier, a); } } /** * An IFilter that makes the colors requested from it highly saturated, with the original hue, value and a timer that * increments very slowly altering hue, with hue, value and the timer altering saturation, and the original hue, * saturation, and value all altering value. It should look like a hallucination. * <br> * A short (poorly recorded) video can be seen here http://i.imgur.com/SEw2LXe.gifv ; performance should be smoother * during actual gameplay. */ public static class HallucinateFilter implements IFilter<Color> { private SquidColorCenter globalSCC; /** * Sets up a HallucinateFilter with the timer at 0.. */ public HallucinateFilter() { globalSCC = DefaultResources.getSCC(); } @Override public Color alter(float r, float g, float b, float a) { float t = (System.currentTimeMillis() & 0xfff) * 0x1p-12f, h = globalSCC.getHue(r, g, b), s = globalSCC.getSaturation(r, g, b), v = globalSCC.getValue(r, g, b); return globalSCC.getHSV( (v * 4f + h + t) % 1.0f, Math.max(0f, Math.min((h + v) * 0.65f + t * 0.4f, 1f)), MathExtras.clamp((h + v + s) * 0.35f + 0.7f, 0f, 1f), a); } } /** * An IFilter that multiplies the saturation of any color requested from it by a number given during construction. * When desaturating, you may want to prefer {@link SaturationValueFilter}, because reducing saturation increases * perceived brightness (value), and desaturating an ocean-blue color will make it look like ice if the value * isn't decreased as well. This class is perfectly fine for increasing saturation, in general. */ public static class SaturationFilter implements IFilter<Color> { private SquidColorCenter globalSCC; public float multiplier; /** * Sets up a SaturationFilter with the desired saturation multiplier. Using a multiplier of 0f, as you would * expect, makes the image grayscale. Using a multiplier of 0.5 make the image "muted", with no truly bright * colors, while 1.0f makes no change, and and any numbers higher than 1.0f will make the image more saturated, * with the exception of colors that were already grayscale or close to it. This clamps the result, so there's * no need to worry about using too high of a saturation multiplier. * * @param multiplier the amount to multiply each requested color's saturation by; 1.0f means "no change" */ public SaturationFilter(float multiplier) { globalSCC = DefaultResources.getSCC(); this.multiplier = multiplier; } @Override public Color alter(float r, float g, float b, float a) { return globalSCC.getHSV( globalSCC.getHue(r, g, b), Math.max(0f, Math.min((globalSCC.getSaturation(r, g, b) * multiplier), 1f)), globalSCC.getValue(r, g, b), a); } } /** * An IFilter that multiplies the saturation and the value of any color requested from it by different numbers given * during construction. */ public static class SaturationValueFilter implements IFilter<Color> { private SquidColorCenter globalSCC; public float saturationMultiplier, valueMultiplier; /** * Sets up a SaturationValueFilter with the desired saturation and value multipliers. Using a multiplier of 0f for * saturation, as you would expect, makes the image grayscale. Using a multiplier of 0f for value makes all * colors identicaly black; this is probably not a good idea. Using a multiplier of 0.5 for saturation will * make the image "muted", with no truly bright colors, while 1.0f for saturation makes no change, and and any * numbers higher than 1.0f for saturation will make the image more saturated, with the exception of colors that * were already grayscale or close to it. Using 0.5f for value will darken the image significantly, 1.0f for * value will keep it the same for brightness, and higher than 1.0f will lighten it. This clamps the result, so * there's no need to worry about using too high of a saturation or value multiplier. * * @param saturation the amount to multiply each requested color's saturation by; 1.0f means "no change" * @param value the amount to multiply each requested color's value (lightness) by; 1.0f means "no change" */ public SaturationValueFilter(float saturation, float value) { globalSCC = DefaultResources.getSCC(); saturationMultiplier = saturation; valueMultiplier = value; } @Override public Color alter(float r, float g, float b, float a) { return globalSCC.getHSV( globalSCC.getHue(r, g, b), Math.max(0f, Math.min((globalSCC.getSaturation(r, g, b) * saturationMultiplier), 1f)), Math.max(0f, Math.min((globalSCC.getValue(r, g, b) * valueMultiplier), 1f)), a); } } /** * An IFilter that is constructed with a palette of colors and randomly increases or decreases the red, green, and * blue components of any color it is told to alter. Good for a "glitchy screen" effect. */ public static class WiggleFilter implements IFilter<Color> { long rngState; public WiggleFilter() { rngState = (long) ((Math.random() - 0.5) * 0x10000000000000L) ^ (long) (((Math.random() - 0.5) * 2.0) * 0x8000000000000000L); } @Override public Color alter(float r, float g, float b, float a) { return new Color(r - 0.1f + ThrustAltRNG.determineFloat(++rngState) * 0.2f, g - 0.1f + ThrustAltRNG.determineFloat(++rngState) * 0.2f, b - 0.1f + ThrustAltRNG.determineFloat(++rngState) * 0.2f, a); } } /** * An IFilter that is constructed with a group of colors and forces any color it is told to alter to exactly * the color it was constructed with that has the closest red, green, and blue components. A convenient way to * use this is to pass in one of the color series from SColor, such as {@link SColor#RED_SERIES} or * {@link SColor#ACHROMATIC_SERIES}. This can also be used to enforce usage of a limited color palette such as * one of DawnBringer's popular pixel art palettes, {@link SColor#DAWNBRINGER_16} and * {@link SColor#DAWNBRINGER_32}. Beyond 32 colors, the palettes {@link SColor#VARIED_PALETTE} with 56 colors * and {@link SColor#COLOR_WHEEL_PALETTE} with 198 colors can be used. * * Preview using BLUE_GREEN_SERIES foreground, ACHROMATIC_SERIES background: http://i.imgur.com/2HdZpC9.png */ public static class PaletteFilter implements IFilter<Color> { /** * The array of Color objects this will use as a palette. */ public Color[] colorStore; /** * Sets up a PaletteFilter with the exact colors to use as individual components; the lengths of each given * array should be identical. * * @param r the red components to use * @param g the green components to use * @param b the blue components to use */ public PaletteFilter(float[] r, float[] g, float[] b) { colorStore = new Color[Math.min(r.length, Math.min(g.length, b.length))]; // state = new float[colorStore.length * 3]; for (int i = 0; i < colorStore.length; i++) { colorStore[i] = new Color( MathUtils.clamp(r[i], 0f, 1f), MathUtils.clamp(g[i], 0f, 1f), MathUtils.clamp(b[i], 0f, 1f), 1f); } }/** * Sets up a PaletteFilter with the exact colors to use as Colors. A convenient way to * use this is to pass in one of the color series from SColor, such as RED_SERIES or ACHROMATIC_SERIES. * The alpha component of each color in the palette is ignored, since when a color is requested for * filtering, its alpha is respected and only its red, green, and blue components are changed. * The {@code colors} array is used verbatim (as a reference, not a copy), so changes to the Color values inside * it will change how this PaletteFilter works (possibly badly). If you expect to edit the array you give as a * parameter to this, it may be optimal to give a temporary copy. * @param colors the Colors to use as an array; will be referenced in the PaletteFilter, so changing items in * this array will change what Colors will be used */ public PaletteFilter(Color[] colors) { colorStore = colors; // state = new float[colors.length * 3]; // for (int i = 0; i < colors.length; i++) { // state[i * 3] = colors[i].r; // state[i * 3 + 1] = colors[i].g; // state[i * 3 + 2] = colors[i].b; // } } @Override public Color alter(float r, float g, float b, float a) { int diff = 0x7fffffff, temp; int choice = 0; r = SColor.floatGet(r, g, b, a); for (int i = 0; i < colorStore.length; i++) { temp = SColor.difference2(r, colorStore[i]); if(temp < diff) { diff = temp; choice = i; } } if(a >= 1f) return colorStore[choice]; Color ret = colorStore[choice].cpy(); ret.a = a; return ret; } } /** * An IFilter that alters primarily-red and primarily-green colors so they can be more easily be distinguished by * people with at least some forms of red-green color-blindness (deuteranopia should be handled well, protanopia * very well, and tritanopia may not benefit at all). Causes reds to be darkened and greens to be lightened if the * other of the pair is not present in similar quantities (which is the case for yellows and blues). */ public static class DistinctRedGreenFilter implements IFilter<Color> { /** * Constructs a DistinctRedGreenFilter. This class is a simple wrapper around a function that doesn't need * member variables, so there should be little overhead with this filter. */ public DistinctRedGreenFilter() { } @Override public Color alter(float r, float g, float b, float a) { float diff = g - r; if(diff > 0.4f) return new Color(Math.min(1f, r * (0.8f + diff * 0.5f)), Math.min(1f, g * (0.9f + diff * 0.5f)), Math.min(1f, b * (0.8f + diff * 0.5f)), a); else if(diff < -0.3f) return new Color(r * (0.6f - diff), g * (0.7f - diff), b * (0.7f - diff), a); else return new Color(r, g, b, a); } } }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.apache.sysds.hops.codegen.opt (SystemDS 2.0.0-SNAPSHOT API)</title> <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="org.apache.sysds.hops.codegen.opt (SystemDS 2.0.0-SNAPSHOT API)"; } } 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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/sysds/hops/codegen/cplan/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../../org/apache/sysds/hops/codegen/template/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/sysds/hops/codegen/opt/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.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"> <h1 title="Package" class="title">Package&nbsp;org.apache.sysds.hops.codegen.opt</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../org/apache/sysds/hops/codegen/opt/InterestingPoint.html" title="class in org.apache.sysds.hops.codegen.opt">InterestingPoint</a></td> <td class="colLast"> <div class="block">Interesting decision point with regard to materialization of intermediates.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../org/apache/sysds/hops/codegen/opt/PlanAnalyzer.html" title="class in org.apache.sysds.hops.codegen.opt">PlanAnalyzer</a></td> <td class="colLast"> <div class="block">Utility functions to extract structural information from the memo table, including connected components (aka partitions) of partial fusion plans, materialization points of partitions, and root nodes of partitions.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../org/apache/sysds/hops/codegen/opt/PlanPartition.html" title="class in org.apache.sysds.hops.codegen.opt">PlanPartition</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../org/apache/sysds/hops/codegen/opt/PlanSelection.html" title="class in org.apache.sysds.hops.codegen.opt">PlanSelection</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../org/apache/sysds/hops/codegen/opt/PlanSelection.VisitMarkCost.html" title="class in org.apache.sysds.hops.codegen.opt">PlanSelection.VisitMarkCost</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../org/apache/sysds/hops/codegen/opt/PlanSelectionFuseAll.html" title="class in org.apache.sysds.hops.codegen.opt">PlanSelectionFuseAll</a></td> <td class="colLast"> <div class="block">This plan selection heuristic aims for maximal fusion, which potentially leads to overlapping fused operators and thus, redundant computation but with a minimal number of materialized intermediate results.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../org/apache/sysds/hops/codegen/opt/PlanSelectionFuseCostBased.html" title="class in org.apache.sysds.hops.codegen.opt">PlanSelectionFuseCostBased</a></td> <td class="colLast"> <div class="block">This cost-based plan selection algorithm chooses fused operators based on the DAG structure and resulting overall costs.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../org/apache/sysds/hops/codegen/opt/PlanSelectionFuseCostBasedV2.html" title="class in org.apache.sysds.hops.codegen.opt">PlanSelectionFuseCostBasedV2</a></td> <td class="colLast"> <div class="block">This cost-based plan selection algorithm chooses fused operators based on the DAG structure and resulting overall costs.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../org/apache/sysds/hops/codegen/opt/PlanSelectionFuseNoRedundancy.html" title="class in org.apache.sysds.hops.codegen.opt">PlanSelectionFuseNoRedundancy</a></td> <td class="colLast"> <div class="block">This plan selection heuristic aims for fusion without any redundant computation, which, however, potentially leads to more materialized intermediates than the fuse all heuristic.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../org/apache/sysds/hops/codegen/opt/ReachabilityGraph.html" title="class in org.apache.sysds.hops.codegen.opt">ReachabilityGraph</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../org/apache/sysds/hops/codegen/opt/ReachabilityGraph.SubProblem.html" title="class in org.apache.sysds.hops.codegen.opt">ReachabilityGraph.SubProblem</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation"> <caption><span>Enum Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Enum</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../org/apache/sysds/hops/codegen/opt/InterestingPoint.DecisionType.html" title="enum in org.apache.sysds.hops.codegen.opt">InterestingPoint.DecisionType</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/sysds/hops/codegen/cplan/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../../org/apache/sysds/hops/codegen/template/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/sysds/hops/codegen/opt/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.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 ======= --> <p class="legalCopy"><small>Copyright &#169; 2020 <a href="https://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <DelphiIDETheme modified="2013-04-24 20:49:06" author="Delphi IDE Theme Editor" versionapp="1.1.18.1"> <AdditionalSearchMatchHighlight> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>True</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00999999</ForegroundColorNew> <BackgroundColorNew>$00775555</BackgroundColorNew> </AdditionalSearchMatchHighlight> <Assembler> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$000066FF</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </Assembler> <AttributeNames> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$0077AAAA</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </AttributeNames> <AttributeValues> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$0000FF66</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </AttributeValues> <BraceHighlight> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00999999</ForegroundColorNew> <BackgroundColorNew>$00CCE0DB</BackgroundColorNew> </BraceHighlight> <Character> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$0000FF66</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </Character> <CodeFoldingTree> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00999999</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </CodeFoldingTree> <Comment> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00CC3399</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </Comment> <DiffAddition> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>True</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clBlack</ForegroundColorNew> <BackgroundColorNew>$00CCFFCC</BackgroundColorNew> </DiffAddition> <DiffDeletion> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>True</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clBlack</ForegroundColorNew> <BackgroundColorNew>$00FFC7C7</BackgroundColorNew> </DiffDeletion> <DiffMove> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>True</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clBlack</ForegroundColorNew> <BackgroundColorNew>$00AAFFFF</BackgroundColorNew> </DiffMove> <DisabledBreak> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clGray</ForegroundColorNew> <BackgroundColorNew>$00FFC7C7</BackgroundColorNew> </DisabledBreak> <EnabledBreak> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clBlack</ForegroundColorNew> <BackgroundColorNew>$00FFC7C7</BackgroundColorNew> </EnabledBreak> <ErrorLine> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clWhite</ForegroundColorNew> <BackgroundColorNew>clRed</BackgroundColorNew> </ErrorLine> <ExecutionPoint> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clBlack</ForegroundColorNew> <BackgroundColorNew>$009999CC</BackgroundColorNew> </ExecutionPoint> <Float> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00997217</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </Float> <FoldedCode> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00CC9999</ForegroundColorNew> <BackgroundColorNew>clWhite</BackgroundColorNew> </FoldedCode> <Hex> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00997217</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </Hex> <HotLink> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00FF6666</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </HotLink> <Identifier> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00999999</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </Identifier> <IllegalChar> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$001100AA</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </IllegalChar> <InvalidBreak> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clWhite</ForegroundColorNew> <BackgroundColorNew>clGreen</BackgroundColorNew> </InvalidBreak> <LineHighlight> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>True</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00999999</ForegroundColorNew> <BackgroundColorNew>$00775555</BackgroundColorNew> </LineHighlight> <LineNumber> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00999999</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </LineNumber> <MarkedBlock> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>True</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00999999</ForegroundColorNew> <BackgroundColorNew>$00775555</BackgroundColorNew> </MarkedBlock> <ModifiedLine> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clLime</ForegroundColorNew> <BackgroundColorNew>clYellow</BackgroundColorNew> </ModifiedLine> <Number> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00997217</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </Number> <Octal> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00997217</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </Octal> <PlainText> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00999999</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </PlainText> <Preprocessor> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$0077AAAA</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </Preprocessor> <ReservedWord> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00003FDF</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </ReservedWord> <RightMargin> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00999999</ForegroundColorNew> <BackgroundColorNew>$00F0F0F0</BackgroundColorNew> </RightMargin> <Scripts> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>True</DefaultBackground> <ForegroundColorNew>clPurple</ForegroundColorNew> <BackgroundColorNew>clWhite</BackgroundColorNew> </Scripts> <SearchMatch> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00999999</ForegroundColorNew> <BackgroundColorNew>$00775555</BackgroundColorNew> </SearchMatch> <String> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$0000FF66</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </String> <Symbol> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00999999</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </Symbol> <SyncEditBackground> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>True</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clBlack</ForegroundColorNew> <BackgroundColorNew>$00FAFFE6</BackgroundColorNew> </SyncEditBackground> <SyncEditHighlight> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clBlue</ForegroundColorNew> <BackgroundColorNew>clWhite</BackgroundColorNew> </SyncEditHighlight> <Tags> <Bold>True</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>True</DefaultBackground> <ForegroundColorNew>clNavy</ForegroundColorNew> <BackgroundColorNew>clWhite</BackgroundColorNew> </Tags> <Whitespace> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00999999</ForegroundColorNew> <BackgroundColorNew>$00000000</BackgroundColorNew> </Whitespace> </DelphiIDETheme>
{ "pile_set_name": "Github" }
--- layout: text/textblock hidden: false --- Understand the skills involved in creating content. ### [2] Subject matter expert, legal, media advisor, policy author - subject expertise - legal risk or considerations ### [2] Communications/marketing writer, web writer, web editor, content lead - understanding of digital ecosystem - content writing guidance and compliance - editing, writing, proofreading - understanding user needs - accessibility - understanding and writing metadata - Web graphic designer, external consultant - accessible design - accessibility compliance with WCAG 2.0 AA - Information architect, content strategist - content goals - digital ecosystem ### [2] Web graphic designer, external consultant - accessible design - accessibility compliance with WCAG 2.0 AA ### [2] Information architect, content strategist - content goals - digital ecosystem
{ "pile_set_name": "Github" }
<resources> <string name="app_name">PatchTool</string> <string name="cancel">取消</string> <string name="ok">确定</string> </resources>
{ "pile_set_name": "Github" }
 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.27130.2036 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MessageAnalyzerLibrary", "MessageAnalyzerLibrary.csproj", "{E3B08663-C752-41CC-B2B7-43C69B8C1292}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {E3B08663-C752-41CC-B2B7-43C69B8C1292}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E3B08663-C752-41CC-B2B7-43C69B8C1292}.Debug|Any CPU.Build.0 = Debug|Any CPU {E3B08663-C752-41CC-B2B7-43C69B8C1292}.Debug|x64.ActiveCfg = Debug|Any CPU {E3B08663-C752-41CC-B2B7-43C69B8C1292}.Release|Any CPU.ActiveCfg = Release|Any CPU {E3B08663-C752-41CC-B2B7-43C69B8C1292}.Release|Any CPU.Build.0 = Release|Any CPU {E3B08663-C752-41CC-B2B7-43C69B8C1292}.Release|x64.ActiveCfg = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
{ "pile_set_name": "Github" }
/***************************************************************************/ /* */ /* pspic.c */ /* */ /* The FreeType position independent code services for psnames module. */ /* */ /* Copyright 2009-2018 by */ /* Oran Agra and Mickey Gabel. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_FREETYPE_H #include FT_INTERNAL_OBJECTS_H #include "pspic.h" #include "psnamerr.h" #ifdef FT_CONFIG_OPTION_PIC /* forward declaration of PIC init functions from psmodule.c */ FT_Error FT_Create_Class_pscmaps_services( FT_Library library, FT_ServiceDescRec** output_class ); void FT_Destroy_Class_pscmaps_services( FT_Library library, FT_ServiceDescRec* clazz ); void FT_Init_Class_pscmaps_interface( FT_Library library, FT_Service_PsCMapsRec* clazz ); void psnames_module_class_pic_free( FT_Library library ) { FT_PIC_Container* pic_container = &library->pic_container; FT_Memory memory = library->memory; if ( pic_container->psnames ) { PSModulePIC* container = (PSModulePIC*)pic_container->psnames; if ( container->pscmaps_services ) FT_Destroy_Class_pscmaps_services( library, container->pscmaps_services ); container->pscmaps_services = NULL; FT_FREE( container ); pic_container->psnames = NULL; } } FT_Error psnames_module_class_pic_init( FT_Library library ) { FT_PIC_Container* pic_container = &library->pic_container; FT_Error error = FT_Err_Ok; PSModulePIC* container = NULL; FT_Memory memory = library->memory; /* allocate pointer, clear and set global container pointer */ if ( FT_ALLOC( container, sizeof ( *container ) ) ) return error; FT_MEM_SET( container, 0, sizeof ( *container ) ); pic_container->psnames = container; /* initialize pointer table - */ /* this is how the module usually expects this data */ error = FT_Create_Class_pscmaps_services( library, &container->pscmaps_services ); if ( error ) goto Exit; FT_Init_Class_pscmaps_interface( library, &container->pscmaps_interface ); Exit: if ( error ) psnames_module_class_pic_free( library ); return error; } #endif /* FT_CONFIG_OPTION_PIC */ /* END */
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/favicon.ico"> <meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0"> <title>ColVis example - Custom button text</title> <link rel="stylesheet" type="text/css" href="../../../media/css/jquery.dataTables.css"> <link rel="stylesheet" type="text/css" href="../css/dataTables.colVis.css"> <link rel="stylesheet" type="text/css" href="../../../examples/resources/syntax/shCore.css"> <link rel="stylesheet" type="text/css" href="../../../examples/resources/demo.css"> <style type="text/css" class="init"> </style> <script type="text/javascript" language="javascript" src="../../../media/js/jquery.js"></script> <script type="text/javascript" language="javascript" src="../../../media/js/jquery.dataTables.js"></script> <script type="text/javascript" language="javascript" src="../js/dataTables.colVis.js"></script> <script type="text/javascript" language="javascript" src="../../../examples/resources/syntax/shCore.js"></script> <script type="text/javascript" language="javascript" src="../../../examples/resources/demo.js"></script> <script type="text/javascript" language="javascript" class="init"> $(document).ready(function() { $('#example').DataTable( { "dom": 'C<"clear">lfrtip', "colVis": { "buttonText": "Change columns" } } ); } ); </script> </head> <body class="dt-example"> <div class="container"> <section> <h1>ColVis example <span>Custom button text</span></h1> <div class="info"> <p>You may wish to use your own text in the ColVis button - this is done by making use of the <code>buttonText</code> initialisation option, as shown in this example.</p> <p>For full information about the ColVis options, please refer to the <a href="//datatables.net/extensions/colvis/options">ColVis options documentation</a>.</p> </div> <table id="example" class="display" cellspacing="0" width="100%"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </thead> <tfoot> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </tfoot> <tbody> <tr> <td>Tiger Nixon</td> <td>System Architect</td> <td>Edinburgh</td> <td>61</td> <td>2011/04/25</td> <td>$320,800</td> </tr> <tr> <td>Garrett Winters</td> <td>Accountant</td> <td>Tokyo</td> <td>63</td> <td>2011/07/25</td> <td>$170,750</td> </tr> <tr> <td>Ashton Cox</td> <td>Junior Technical Author</td> <td>San Francisco</td> <td>66</td> <td>2009/01/12</td> <td>$86,000</td> </tr> <tr> <td>Cedric Kelly</td> <td>Senior Javascript Developer</td> <td>Edinburgh</td> <td>22</td> <td>2012/03/29</td> <td>$433,060</td> </tr> <tr> <td>Airi Satou</td> <td>Accountant</td> <td>Tokyo</td> <td>33</td> <td>2008/11/28</td> <td>$162,700</td> </tr> <tr> <td>Brielle Williamson</td> <td>Integration Specialist</td> <td>New York</td> <td>61</td> <td>2012/12/02</td> <td>$372,000</td> </tr> <tr> <td>Herrod Chandler</td> <td>Sales Assistant</td> <td>San Francisco</td> <td>59</td> <td>2012/08/06</td> <td>$137,500</td> </tr> <tr> <td>Rhona Davidson</td> <td>Integration Specialist</td> <td>Tokyo</td> <td>55</td> <td>2010/10/14</td> <td>$327,900</td> </tr> <tr> <td>Colleen Hurst</td> <td>Javascript Developer</td> <td>San Francisco</td> <td>39</td> <td>2009/09/15</td> <td>$205,500</td> </tr> <tr> <td>Sonya Frost</td> <td>Software Engineer</td> <td>Edinburgh</td> <td>23</td> <td>2008/12/13</td> <td>$103,600</td> </tr> <tr> <td>Jena Gaines</td> <td>Office Manager</td> <td>London</td> <td>30</td> <td>2008/12/19</td> <td>$90,560</td> </tr> <tr> <td>Quinn Flynn</td> <td>Support Lead</td> <td>Edinburgh</td> <td>22</td> <td>2013/03/03</td> <td>$342,000</td> </tr> <tr> <td>Charde Marshall</td> <td>Regional Director</td> <td>San Francisco</td> <td>36</td> <td>2008/10/16</td> <td>$470,600</td> </tr> <tr> <td>Haley Kennedy</td> <td>Senior Marketing Designer</td> <td>London</td> <td>43</td> <td>2012/12/18</td> <td>$313,500</td> </tr> <tr> <td>Tatyana Fitzpatrick</td> <td>Regional Director</td> <td>London</td> <td>19</td> <td>2010/03/17</td> <td>$385,750</td> </tr> <tr> <td>Michael Silva</td> <td>Marketing Designer</td> <td>London</td> <td>66</td> <td>2012/11/27</td> <td>$198,500</td> </tr> <tr> <td>Paul Byrd</td> <td>Chief Financial Officer (CFO)</td> <td>New York</td> <td>64</td> <td>2010/06/09</td> <td>$725,000</td> </tr> <tr> <td>Gloria Little</td> <td>Systems Administrator</td> <td>New York</td> <td>59</td> <td>2009/04/10</td> <td>$237,500</td> </tr> <tr> <td>Bradley Greer</td> <td>Software Engineer</td> <td>London</td> <td>41</td> <td>2012/10/13</td> <td>$132,000</td> </tr> <tr> <td>Dai Rios</td> <td>Personnel Lead</td> <td>Edinburgh</td> <td>35</td> <td>2012/09/26</td> <td>$217,500</td> </tr> <tr> <td>Jenette Caldwell</td> <td>Development Lead</td> <td>New York</td> <td>30</td> <td>2011/09/03</td> <td>$345,000</td> </tr> <tr> <td>Yuri Berry</td> <td>Chief Marketing Officer (CMO)</td> <td>New York</td> <td>40</td> <td>2009/06/25</td> <td>$675,000</td> </tr> <tr> <td>Caesar Vance</td> <td>Pre-Sales Support</td> <td>New York</td> <td>21</td> <td>2011/12/12</td> <td>$106,450</td> </tr> <tr> <td>Doris Wilder</td> <td>Sales Assistant</td> <td>Sidney</td> <td>23</td> <td>2010/09/20</td> <td>$85,600</td> </tr> <tr> <td>Angelica Ramos</td> <td>Chief Executive Officer (CEO)</td> <td>London</td> <td>47</td> <td>2009/10/09</td> <td>$1,200,000</td> </tr> <tr> <td>Gavin Joyce</td> <td>Developer</td> <td>Edinburgh</td> <td>42</td> <td>2010/12/22</td> <td>$92,575</td> </tr> <tr> <td>Jennifer Chang</td> <td>Regional Director</td> <td>Singapore</td> <td>28</td> <td>2010/11/14</td> <td>$357,650</td> </tr> <tr> <td>Brenden Wagner</td> <td>Software Engineer</td> <td>San Francisco</td> <td>28</td> <td>2011/06/07</td> <td>$206,850</td> </tr> <tr> <td>Fiona Green</td> <td>Chief Operating Officer (COO)</td> <td>San Francisco</td> <td>48</td> <td>2010/03/11</td> <td>$850,000</td> </tr> <tr> <td>Shou Itou</td> <td>Regional Marketing</td> <td>Tokyo</td> <td>20</td> <td>2011/08/14</td> <td>$163,000</td> </tr> <tr> <td>Michelle House</td> <td>Integration Specialist</td> <td>Sidney</td> <td>37</td> <td>2011/06/02</td> <td>$95,400</td> </tr> <tr> <td>Suki Burks</td> <td>Developer</td> <td>London</td> <td>53</td> <td>2009/10/22</td> <td>$114,500</td> </tr> <tr> <td>Prescott Bartlett</td> <td>Technical Author</td> <td>London</td> <td>27</td> <td>2011/05/07</td> <td>$145,000</td> </tr> <tr> <td>Gavin Cortez</td> <td>Team Leader</td> <td>San Francisco</td> <td>22</td> <td>2008/10/26</td> <td>$235,500</td> </tr> <tr> <td>Martena Mccray</td> <td>Post-Sales support</td> <td>Edinburgh</td> <td>46</td> <td>2011/03/09</td> <td>$324,050</td> </tr> <tr> <td>Unity Butler</td> <td>Marketing Designer</td> <td>San Francisco</td> <td>47</td> <td>2009/12/09</td> <td>$85,675</td> </tr> <tr> <td>Howard Hatfield</td> <td>Office Manager</td> <td>San Francisco</td> <td>51</td> <td>2008/12/16</td> <td>$164,500</td> </tr> <tr> <td>Hope Fuentes</td> <td>Secretary</td> <td>San Francisco</td> <td>41</td> <td>2010/02/12</td> <td>$109,850</td> </tr> <tr> <td>Vivian Harrell</td> <td>Financial Controller</td> <td>San Francisco</td> <td>62</td> <td>2009/02/14</td> <td>$452,500</td> </tr> <tr> <td>Timothy Mooney</td> <td>Office Manager</td> <td>London</td> <td>37</td> <td>2008/12/11</td> <td>$136,200</td> </tr> <tr> <td>Jackson Bradshaw</td> <td>Director</td> <td>New York</td> <td>65</td> <td>2008/09/26</td> <td>$645,750</td> </tr> <tr> <td>Olivia Liang</td> <td>Support Engineer</td> <td>Singapore</td> <td>64</td> <td>2011/02/03</td> <td>$234,500</td> </tr> <tr> <td>Bruno Nash</td> <td>Software Engineer</td> <td>London</td> <td>38</td> <td>2011/05/03</td> <td>$163,500</td> </tr> <tr> <td>Sakura Yamamoto</td> <td>Support Engineer</td> <td>Tokyo</td> <td>37</td> <td>2009/08/19</td> <td>$139,575</td> </tr> <tr> <td>Thor Walton</td> <td>Developer</td> <td>New York</td> <td>61</td> <td>2013/08/11</td> <td>$98,540</td> </tr> <tr> <td>Finn Camacho</td> <td>Support Engineer</td> <td>San Francisco</td> <td>47</td> <td>2009/07/07</td> <td>$87,500</td> </tr> <tr> <td>Serge Baldwin</td> <td>Data Coordinator</td> <td>Singapore</td> <td>64</td> <td>2012/04/09</td> <td>$138,575</td> </tr> <tr> <td>Zenaida Frank</td> <td>Software Engineer</td> <td>New York</td> <td>63</td> <td>2010/01/04</td> <td>$125,250</td> </tr> <tr> <td>Zorita Serrano</td> <td>Software Engineer</td> <td>San Francisco</td> <td>56</td> <td>2012/06/01</td> <td>$115,000</td> </tr> <tr> <td>Jennifer Acosta</td> <td>Junior Javascript Developer</td> <td>Edinburgh</td> <td>43</td> <td>2013/02/01</td> <td>$75,650</td> </tr> <tr> <td>Cara Stevens</td> <td>Sales Assistant</td> <td>New York</td> <td>46</td> <td>2011/12/06</td> <td>$145,600</td> </tr> <tr> <td>Hermione Butler</td> <td>Regional Director</td> <td>London</td> <td>47</td> <td>2011/03/21</td> <td>$356,250</td> </tr> <tr> <td>Lael Greer</td> <td>Systems Administrator</td> <td>London</td> <td>21</td> <td>2009/02/27</td> <td>$103,500</td> </tr> <tr> <td>Jonas Alexander</td> <td>Developer</td> <td>San Francisco</td> <td>30</td> <td>2010/07/14</td> <td>$86,500</td> </tr> <tr> <td>Shad Decker</td> <td>Regional Director</td> <td>Edinburgh</td> <td>51</td> <td>2008/11/13</td> <td>$183,000</td> </tr> <tr> <td>Michael Bruce</td> <td>Javascript Developer</td> <td>Singapore</td> <td>29</td> <td>2011/06/27</td> <td>$183,000</td> </tr> <tr> <td>Donna Snider</td> <td>Customer Support</td> <td>New York</td> <td>27</td> <td>2011/01/25</td> <td>$112,000</td> </tr> </tbody> </table> <ul class="tabs"> <li class="active">Javascript</li> <li>HTML</li> <li>CSS</li> <li>Ajax</li> <li>Server-side script</li> </ul> <div class="tabs"> <div class="js"> <p>The Javascript shown below is used to initialise the table shown in this example:</p><code class="multiline language-js">$(document).ready(function() { $('#example').DataTable( { &quot;dom&quot;: 'C&lt;&quot;clear&quot;&gt;lfrtip', &quot;colVis&quot;: { &quot;buttonText&quot;: &quot;Change columns&quot; } } ); } );</code> <p>In addition to the above code, the following Javascript library files are loaded for use in this example:</p> <ul> <li><a href="../../../media/js/jquery.js">../../../media/js/jquery.js</a></li> <li><a href="../../../media/js/jquery.dataTables.js">../../../media/js/jquery.dataTables.js</a></li> <li><a href="../js/dataTables.colVis.js">../js/dataTables.colVis.js</a></li> </ul> </div> <div class="table"> <p>The HTML shown below is the raw HTML table element, before it has been enhanced by DataTables:</p> </div> <div class="css"> <div> <p>This example uses a little bit of additional CSS beyond what is loaded from the library files (below), in order to correctly display the table. The additional CSS used is shown below:</p><code class="multiline language-css"></code> </div> <p>The following CSS library files are loaded for use in this example to provide the styling of the table:</p> <ul> <li><a href="../../../media/css/jquery.dataTables.css">../../../media/css/jquery.dataTables.css</a></li> <li><a href="../css/dataTables.colVis.css">../css/dataTables.colVis.css</a></li> </ul> </div> <div class="ajax"> <p>This table loads data by Ajax. The latest data that has been loaded is shown below. This data will update automatically as any additional data is loaded.</p> </div> <div class="php"> <p>The script used to perform the server-side processing for this table is shown below. Please note that this is just an example script using PHP. Server-side processing scripts can be written in any language, using <a href="//datatables.net/manual/server-side">the protocol described in the DataTables documentation</a>.</p> </div> </div> </section> </div> <section> <div class="footer"> <div class="gradient"></div> <div class="liner"> <h2>Other examples</h2> <div class="toc"> <div class="toc-group"> <h3><a href="index.html">Examples</a></h3> <ul class="toc active"> <li><a href="simple.html">Basic initialisation</a></li> <li><a href="new_init.html">`new` initialisation</a></li> <li class="active"><a href="./text.html">Custom button text</a></li> <li><a href="exclude_columns.html">Exclude columns from list</a></li> <li><a href="title_callback.html">Column button callback</a></li> <li><a href="button_order.html">Button ordering</a></li> <li><a href="mouseover.html">Mouseover activation</a></li> <li><a href="group_columns.html">Group columns</a></li> <li><a href="two_tables.html">Two tables with individual controls</a></li> <li><a href="two_tables_identical.html">Two tables with shared controls</a></li> <li><a href="restore.html">Restore / show all</a></li> <li><a href="jqueryui.html">jQuery UI styling</a></li> </ul> </div> </div> <div class="epilogue"> <p>Please refer to the <a href="http://www.datatables.net">DataTables documentation</a> for full information about its API properties and methods.<br> Additionally, there are a wide range of <a href="http://www.datatables.net/extras">extras</a> and <a href="http://www.datatables.net/plug-ins">plug-ins</a> which extend the capabilities of DataTables.</p> <p class="copyright">DataTables designed and created by <a href="http://www.sprymedia.co.uk">SpryMedia Ltd</a> &#169; 2007-2015<br> DataTables is licensed under the <a href="http://www.datatables.net/mit">MIT license</a>.</p> </div> </div> </div> </section> </body> </html>
{ "pile_set_name": "Github" }
// Copyright ©2016 The Gonum Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !noasm,!appengine,!safe package c128 // AxpyUnitary is // for i, v := range x { // y[i] += alpha * v // } func AxpyUnitary(alpha complex128, x, y []complex128) // AxpyUnitaryTo is // for i, v := range x { // dst[i] = alpha*v + y[i] // } func AxpyUnitaryTo(dst []complex128, alpha complex128, x, y []complex128) // AxpyInc is // for i := 0; i < int(n); i++ { // y[iy] += alpha * x[ix] // ix += incX // iy += incY // } func AxpyInc(alpha complex128, x, y []complex128, n, incX, incY, ix, iy uintptr) // AxpyIncTo is // for i := 0; i < int(n); i++ { // dst[idst] = alpha*x[ix] + y[iy] // ix += incX // iy += incY // idst += incDst // } func AxpyIncTo(dst []complex128, incDst, idst uintptr, alpha complex128, x, y []complex128, n, incX, incY, ix, iy uintptr) // DscalUnitary is // for i, v := range x { // x[i] = complex(real(v)*alpha, imag(v)*alpha) // } func DscalUnitary(alpha float64, x []complex128) // DscalInc is // var ix uintptr // for i := 0; i < int(n); i++ { // x[ix] = complex(real(x[ix])*alpha, imag(x[ix])*alpha) // ix += inc // } func DscalInc(alpha float64, x []complex128, n, inc uintptr) // ScalInc is // var ix uintptr // for i := 0; i < int(n); i++ { // x[ix] *= alpha // ix += incX // } func ScalInc(alpha complex128, x []complex128, n, inc uintptr) // ScalUnitary is // for i := range x { // x[i] *= alpha // } func ScalUnitary(alpha complex128, x []complex128) // DotcUnitary is // for i, v := range x { // sum += y[i] * cmplx.Conj(v) // } // return sum func DotcUnitary(x, y []complex128) (sum complex128) // DotcInc is // for i := 0; i < int(n); i++ { // sum += y[iy] * cmplx.Conj(x[ix]) // ix += incX // iy += incY // } // return sum func DotcInc(x, y []complex128, n, incX, incY, ix, iy uintptr) (sum complex128) // DotuUnitary is // for i, v := range x { // sum += y[i] * v // } // return sum func DotuUnitary(x, y []complex128) (sum complex128) // DotuInc is // for i := 0; i < int(n); i++ { // sum += y[iy] * x[ix] // ix += incX // iy += incY // } // return sum func DotuInc(x, y []complex128, n, incX, incY, ix, iy uintptr) (sum complex128)
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2010 Benoit Jacob <jacob.benoit.1@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_INVERSE_H #define EIGEN_INVERSE_H namespace Eigen { namespace internal { /********************************** *** General case implementation *** **********************************/ template<typename MatrixType, typename ResultType, int Size = MatrixType::RowsAtCompileTime> struct compute_inverse { static inline void run(const MatrixType& matrix, ResultType& result) { result = matrix.partialPivLu().inverse(); } }; template<typename MatrixType, typename ResultType, int Size = MatrixType::RowsAtCompileTime> struct compute_inverse_and_det_with_check { /* nothing! general case not supported. */ }; /**************************** *** Size 1 implementation *** ****************************/ template<typename MatrixType, typename ResultType> struct compute_inverse<MatrixType, ResultType, 1> { static inline void run(const MatrixType& matrix, ResultType& result) { typedef typename MatrixType::Scalar Scalar; result.coeffRef(0,0) = Scalar(1) / matrix.coeff(0,0); } }; template<typename MatrixType, typename ResultType> struct compute_inverse_and_det_with_check<MatrixType, ResultType, 1> { static inline void run( const MatrixType& matrix, const typename MatrixType::RealScalar& absDeterminantThreshold, ResultType& result, typename ResultType::Scalar& determinant, bool& invertible ) { using std::abs; determinant = matrix.coeff(0,0); invertible = abs(determinant) > absDeterminantThreshold; if(invertible) result.coeffRef(0,0) = typename ResultType::Scalar(1) / determinant; } }; /**************************** *** Size 2 implementation *** ****************************/ template<typename MatrixType, typename ResultType> inline void compute_inverse_size2_helper( const MatrixType& matrix, const typename ResultType::Scalar& invdet, ResultType& result) { result.coeffRef(0,0) = matrix.coeff(1,1) * invdet; result.coeffRef(1,0) = -matrix.coeff(1,0) * invdet; result.coeffRef(0,1) = -matrix.coeff(0,1) * invdet; result.coeffRef(1,1) = matrix.coeff(0,0) * invdet; } template<typename MatrixType, typename ResultType> struct compute_inverse<MatrixType, ResultType, 2> { static inline void run(const MatrixType& matrix, ResultType& result) { typedef typename ResultType::Scalar Scalar; const Scalar invdet = typename MatrixType::Scalar(1) / matrix.determinant(); compute_inverse_size2_helper(matrix, invdet, result); } }; template<typename MatrixType, typename ResultType> struct compute_inverse_and_det_with_check<MatrixType, ResultType, 2> { static inline void run( const MatrixType& matrix, const typename MatrixType::RealScalar& absDeterminantThreshold, ResultType& inverse, typename ResultType::Scalar& determinant, bool& invertible ) { using std::abs; typedef typename ResultType::Scalar Scalar; determinant = matrix.determinant(); invertible = abs(determinant) > absDeterminantThreshold; if(!invertible) return; const Scalar invdet = Scalar(1) / determinant; compute_inverse_size2_helper(matrix, invdet, inverse); } }; /**************************** *** Size 3 implementation *** ****************************/ template<typename MatrixType, int i, int j> inline typename MatrixType::Scalar cofactor_3x3(const MatrixType& m) { enum { i1 = (i+1) % 3, i2 = (i+2) % 3, j1 = (j+1) % 3, j2 = (j+2) % 3 }; return m.coeff(i1, j1) * m.coeff(i2, j2) - m.coeff(i1, j2) * m.coeff(i2, j1); } template<typename MatrixType, typename ResultType> inline void compute_inverse_size3_helper( const MatrixType& matrix, const typename ResultType::Scalar& invdet, const Matrix<typename ResultType::Scalar,3,1>& cofactors_col0, ResultType& result) { result.row(0) = cofactors_col0 * invdet; result.coeffRef(1,0) = cofactor_3x3<MatrixType,0,1>(matrix) * invdet; result.coeffRef(1,1) = cofactor_3x3<MatrixType,1,1>(matrix) * invdet; result.coeffRef(1,2) = cofactor_3x3<MatrixType,2,1>(matrix) * invdet; result.coeffRef(2,0) = cofactor_3x3<MatrixType,0,2>(matrix) * invdet; result.coeffRef(2,1) = cofactor_3x3<MatrixType,1,2>(matrix) * invdet; result.coeffRef(2,2) = cofactor_3x3<MatrixType,2,2>(matrix) * invdet; } template<typename MatrixType, typename ResultType> struct compute_inverse<MatrixType, ResultType, 3> { static inline void run(const MatrixType& matrix, ResultType& result) { typedef typename ResultType::Scalar Scalar; Matrix<typename MatrixType::Scalar,3,1> cofactors_col0; cofactors_col0.coeffRef(0) = cofactor_3x3<MatrixType,0,0>(matrix); cofactors_col0.coeffRef(1) = cofactor_3x3<MatrixType,1,0>(matrix); cofactors_col0.coeffRef(2) = cofactor_3x3<MatrixType,2,0>(matrix); const Scalar det = (cofactors_col0.cwiseProduct(matrix.col(0))).sum(); const Scalar invdet = Scalar(1) / det; compute_inverse_size3_helper(matrix, invdet, cofactors_col0, result); } }; template<typename MatrixType, typename ResultType> struct compute_inverse_and_det_with_check<MatrixType, ResultType, 3> { static inline void run( const MatrixType& matrix, const typename MatrixType::RealScalar& absDeterminantThreshold, ResultType& inverse, typename ResultType::Scalar& determinant, bool& invertible ) { using std::abs; typedef typename ResultType::Scalar Scalar; Matrix<Scalar,3,1> cofactors_col0; cofactors_col0.coeffRef(0) = cofactor_3x3<MatrixType,0,0>(matrix); cofactors_col0.coeffRef(1) = cofactor_3x3<MatrixType,1,0>(matrix); cofactors_col0.coeffRef(2) = cofactor_3x3<MatrixType,2,0>(matrix); determinant = (cofactors_col0.cwiseProduct(matrix.col(0))).sum(); invertible = abs(determinant) > absDeterminantThreshold; if(!invertible) return; const Scalar invdet = Scalar(1) / determinant; compute_inverse_size3_helper(matrix, invdet, cofactors_col0, inverse); } }; /**************************** *** Size 4 implementation *** ****************************/ template<typename Derived> inline const typename Derived::Scalar general_det3_helper (const MatrixBase<Derived>& matrix, int i1, int i2, int i3, int j1, int j2, int j3) { return matrix.coeff(i1,j1) * (matrix.coeff(i2,j2) * matrix.coeff(i3,j3) - matrix.coeff(i2,j3) * matrix.coeff(i3,j2)); } template<typename MatrixType, int i, int j> inline typename MatrixType::Scalar cofactor_4x4(const MatrixType& matrix) { enum { i1 = (i+1) % 4, i2 = (i+2) % 4, i3 = (i+3) % 4, j1 = (j+1) % 4, j2 = (j+2) % 4, j3 = (j+3) % 4 }; return general_det3_helper(matrix, i1, i2, i3, j1, j2, j3) + general_det3_helper(matrix, i2, i3, i1, j1, j2, j3) + general_det3_helper(matrix, i3, i1, i2, j1, j2, j3); } template<int Arch, typename Scalar, typename MatrixType, typename ResultType> struct compute_inverse_size4 { static void run(const MatrixType& matrix, ResultType& result) { result.coeffRef(0,0) = cofactor_4x4<MatrixType,0,0>(matrix); result.coeffRef(1,0) = -cofactor_4x4<MatrixType,0,1>(matrix); result.coeffRef(2,0) = cofactor_4x4<MatrixType,0,2>(matrix); result.coeffRef(3,0) = -cofactor_4x4<MatrixType,0,3>(matrix); result.coeffRef(0,2) = cofactor_4x4<MatrixType,2,0>(matrix); result.coeffRef(1,2) = -cofactor_4x4<MatrixType,2,1>(matrix); result.coeffRef(2,2) = cofactor_4x4<MatrixType,2,2>(matrix); result.coeffRef(3,2) = -cofactor_4x4<MatrixType,2,3>(matrix); result.coeffRef(0,1) = -cofactor_4x4<MatrixType,1,0>(matrix); result.coeffRef(1,1) = cofactor_4x4<MatrixType,1,1>(matrix); result.coeffRef(2,1) = -cofactor_4x4<MatrixType,1,2>(matrix); result.coeffRef(3,1) = cofactor_4x4<MatrixType,1,3>(matrix); result.coeffRef(0,3) = -cofactor_4x4<MatrixType,3,0>(matrix); result.coeffRef(1,3) = cofactor_4x4<MatrixType,3,1>(matrix); result.coeffRef(2,3) = -cofactor_4x4<MatrixType,3,2>(matrix); result.coeffRef(3,3) = cofactor_4x4<MatrixType,3,3>(matrix); result /= (matrix.col(0).cwiseProduct(result.row(0).transpose())).sum(); } }; template<typename MatrixType, typename ResultType> struct compute_inverse<MatrixType, ResultType, 4> : compute_inverse_size4<Architecture::Target, typename MatrixType::Scalar, MatrixType, ResultType> { }; template<typename MatrixType, typename ResultType> struct compute_inverse_and_det_with_check<MatrixType, ResultType, 4> { static inline void run( const MatrixType& matrix, const typename MatrixType::RealScalar& absDeterminantThreshold, ResultType& inverse, typename ResultType::Scalar& determinant, bool& invertible ) { using std::abs; determinant = matrix.determinant(); invertible = abs(determinant) > absDeterminantThreshold; if(invertible) compute_inverse<MatrixType, ResultType>::run(matrix, inverse); } }; /************************* *** MatrixBase methods *** *************************/ template<typename MatrixType> struct traits<inverse_impl<MatrixType> > { typedef typename MatrixType::PlainObject ReturnType; }; template<typename MatrixType> struct inverse_impl : public ReturnByValue<inverse_impl<MatrixType> > { typedef typename MatrixType::Index Index; typedef typename internal::eval<MatrixType>::type MatrixTypeNested; typedef typename remove_all<MatrixTypeNested>::type MatrixTypeNestedCleaned; MatrixTypeNested m_matrix; inverse_impl(const MatrixType& matrix) : m_matrix(matrix) {} inline Index rows() const { return m_matrix.rows(); } inline Index cols() const { return m_matrix.cols(); } template<typename Dest> inline void evalTo(Dest& dst) const { const int Size = EIGEN_PLAIN_ENUM_MIN(MatrixType::ColsAtCompileTime,Dest::ColsAtCompileTime); EIGEN_ONLY_USED_FOR_DEBUG(Size); eigen_assert(( (Size<=1) || (Size>4) || (extract_data(m_matrix)!=0 && extract_data(m_matrix)!=extract_data(dst))) && "Aliasing problem detected in inverse(), you need to do inverse().eval() here."); compute_inverse<MatrixTypeNestedCleaned, Dest>::run(m_matrix, dst); } }; } // end namespace internal /** \lu_module * * \returns the matrix inverse of this matrix. * * For small fixed sizes up to 4x4, this method uses cofactors. * In the general case, this method uses class PartialPivLU. * * \note This matrix must be invertible, otherwise the result is undefined. If you need an * invertibility check, do the following: * \li for fixed sizes up to 4x4, use computeInverseAndDetWithCheck(). * \li for the general case, use class FullPivLU. * * Example: \include MatrixBase_inverse.cpp * Output: \verbinclude MatrixBase_inverse.out * * \sa computeInverseAndDetWithCheck() */ template<typename Derived> inline const internal::inverse_impl<Derived> MatrixBase<Derived>::inverse() const { EIGEN_STATIC_ASSERT(!NumTraits<Scalar>::IsInteger,THIS_FUNCTION_IS_NOT_FOR_INTEGER_NUMERIC_TYPES) eigen_assert(rows() == cols()); return internal::inverse_impl<Derived>(derived()); } /** \lu_module * * Computation of matrix inverse and determinant, with invertibility check. * * This is only for fixed-size square matrices of size up to 4x4. * * \param inverse Reference to the matrix in which to store the inverse. * \param determinant Reference to the variable in which to store the determinant. * \param invertible Reference to the bool variable in which to store whether the matrix is invertible. * \param absDeterminantThreshold Optional parameter controlling the invertibility check. * The matrix will be declared invertible if the absolute value of its * determinant is greater than this threshold. * * Example: \include MatrixBase_computeInverseAndDetWithCheck.cpp * Output: \verbinclude MatrixBase_computeInverseAndDetWithCheck.out * * \sa inverse(), computeInverseWithCheck() */ template<typename Derived> template<typename ResultType> inline void MatrixBase<Derived>::computeInverseAndDetWithCheck( ResultType& inverse, typename ResultType::Scalar& determinant, bool& invertible, const RealScalar& absDeterminantThreshold ) const { // i'd love to put some static assertions there, but SFINAE means that they have no effect... eigen_assert(rows() == cols()); // for 2x2, it's worth giving a chance to avoid evaluating. // for larger sizes, evaluating has negligible cost and limits code size. typedef typename internal::conditional< RowsAtCompileTime == 2, typename internal::remove_all<typename internal::nested<Derived, 2>::type>::type, PlainObject >::type MatrixType; internal::compute_inverse_and_det_with_check<MatrixType, ResultType>::run (derived(), absDeterminantThreshold, inverse, determinant, invertible); } /** \lu_module * * Computation of matrix inverse, with invertibility check. * * This is only for fixed-size square matrices of size up to 4x4. * * \param inverse Reference to the matrix in which to store the inverse. * \param invertible Reference to the bool variable in which to store whether the matrix is invertible. * \param absDeterminantThreshold Optional parameter controlling the invertibility check. * The matrix will be declared invertible if the absolute value of its * determinant is greater than this threshold. * * Example: \include MatrixBase_computeInverseWithCheck.cpp * Output: \verbinclude MatrixBase_computeInverseWithCheck.out * * \sa inverse(), computeInverseAndDetWithCheck() */ template<typename Derived> template<typename ResultType> inline void MatrixBase<Derived>::computeInverseWithCheck( ResultType& inverse, bool& invertible, const RealScalar& absDeterminantThreshold ) const { RealScalar determinant; // i'd love to put some static assertions there, but SFINAE means that they have no effect... eigen_assert(rows() == cols()); computeInverseAndDetWithCheck(inverse,determinant,invertible,absDeterminantThreshold); } } // end namespace Eigen #endif // EIGEN_INVERSE_H
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.network.server; import io.netty.channel.Channel; import org.apache.spark.network.buffer.ManagedBuffer; import org.apache.spark.network.client.TransportClient; /** * The StreamManager is used to fetch individual chunks from a stream. This is used in * {@link TransportRequestHandler} in order to respond to fetchChunk() requests. Creation of the * stream is outside the scope of the transport layer, but a given stream is guaranteed to be read * by only one client connection, meaning that getChunk() for a particular stream will be called * serially and that once the connection associated with the stream is closed, that stream will * never be used again. */ public abstract class StreamManager { /** * Called in response to a fetchChunk() request. The returned buffer will be passed as-is to the * client. A single stream will be associated with a single TCP connection, so this method * will not be called in parallel for a particular stream. * * Chunks may be requested in any order, and requests may be repeated, but it is not required * that implementations support this behavior. * * The returned ManagedBuffer will be release()'d after being written to the network. * * @param streamId id of a stream that has been previously registered with the StreamManager. * @param chunkIndex 0-indexed chunk of the stream that's requested */ public abstract ManagedBuffer getChunk(long streamId, int chunkIndex); /** * Called in response to a stream() request. The returned data is streamed to the client * through a single TCP connection. * * Note the <code>streamId</code> argument is not related to the similarly named argument in the * {@link #getChunk(long, int)} method. * * @param streamId id of a stream that has been previously registered with the StreamManager. * @return A managed buffer for the stream, or null if the stream was not found. */ public ManagedBuffer openStream(String streamId) { throw new UnsupportedOperationException(); } /** * Associates a stream with a single client connection, which is guaranteed to be the only reader * of the stream. The getChunk() method will be called serially on this connection and once the * connection is closed, the stream will never be used again, enabling cleanup. * * This must be called before the first getChunk() on the stream, but it may be invoked multiple * times with the same channel and stream id. */ public void registerChannel(Channel channel, long streamId) { } /** * Indicates that the given channel has been terminated. After this occurs, we are guaranteed not * to read from the associated streams again, so any state can be cleaned up. */ public void connectionTerminated(Channel channel) { } /** * Verify that the client is authorized to read from the given stream. * * @throws SecurityException If client is not authorized. */ public void checkAuthorization(TransportClient client, long streamId) { } }
{ "pile_set_name": "Github" }
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({SomeTest.class}) public class SomeTestSuite { }
{ "pile_set_name": "Github" }
/** * */ package com.zx.sms.codec.cmpp.msg; import com.zx.sms.codec.cmpp.packet.CmppPacketType; import com.zx.sms.common.util.MsgId; /** * @author huzorro(huzorro@gmail.com) * @author Lihuanghe(18852780@qq.com) * */ public class CmppDeliverResponseMessage extends DefaultMessage { private static final long serialVersionUID = -8362723084094916290L; private MsgId msgId = new MsgId(); private long result = 0; public CmppDeliverResponseMessage(int sequenceId) { super(CmppPacketType.CMPPDELIVERRESPONSE, sequenceId); } public CmppDeliverResponseMessage(Header header) { super(CmppPacketType.CMPPDELIVERRESPONSE, header); } /** * @return the msgId */ public MsgId getMsgId() { return msgId; } /** * @param msgId * the msgId to set */ public void setMsgId(MsgId msgId) { this.msgId = msgId; } /** * @return the result */ public long getResult() { return result; } /** * @param result * the result to set */ public void setResult(long result) { this.result = result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("CmppDeliverResponseMessage [msgId=").append(msgId).append(", result=").append(result).append(", sequenceId=") .append(getHeader().getSequenceId()).append( "]"); return sb.toString(); } }
{ "pile_set_name": "Github" }
/* * Copyright 2018 Meituan Dianping. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.meituan.dorado.mock; import com.meituan.dorado.rpc.meta.RpcInvocation; import com.meituan.dorado.trace.InvokeTrace; import com.meituan.dorado.trace.meta.TraceParam; public class MockInvokeTrace implements InvokeTrace { @Override public String getName() { return getClass().getName(); } @Override public void init(String appkey) { } @Override public void clientSend(TraceParam param, RpcInvocation invocation) {} @Override public void clientRecv(TraceParam param, RpcInvocation invocation) {} @Override public void serverRecv(TraceParam param, RpcInvocation invocation) {} @Override public void serverSend(TraceParam param, RpcInvocation invocation) {} }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. --> <xwikidoc> <web>ReleaseCode</web> <name>ReleaseSheet</name> <language/> <defaultLanguage/> <translation>0</translation> <parent>ReleaseCode.WebHome</parent> <creator>xwiki:XWiki.Admin</creator> <author>xwiki:XWiki.Admin</author> <customClass/> <contentAuthor>xwiki:XWiki.Admin</contentAuthor> <version>1.1</version> <title>#set($version=$doc.getObject("ReleaseCode.ReleaseClass").getProperty("version").getValue())#if("$!version" != "")Release for version $version#{else}New Release for version $request.version#end</title> <template/> <defaultTemplate/> <validationScript/> <comment/> <minorEdit>false</minorEdit> <syntaxId>xwiki/2.1</syntaxId> <hidden>true</hidden> <content>{{velocity output="false"}} #if ($request.version) $doc.set('version', $request.version) #end #if ("$!{doc.getValue('releaseManagers')}" == '') $doc.set('releaseManagers', $services.model.serialize($xcontext.userReference, 'default')) #end {{/velocity}} {{velocity}} #if ($xcontext.action == "edit" || $xcontext.action == "inline") $doc.use("ReleaseCode.ReleaseClass") Version: $doc.display("version") Release Managers: $doc.display("releaseManagers") Release Date: $doc.display("releaseDate") #else ## Note: We use the include macro below to circumvent the "nested script" execution issue... {{include reference="ReleaseCode.ReleaseSheetHeader"/}} {{include reference=""/}} #end {{/velocity}}</content> </xwikidoc>
{ "pile_set_name": "Github" }
#import "ARCity+GeospatialAdditions.h" #import "ARCity.h" @implementation ARCity (GeospatialAdditions) + (nullable ARCity *)cityNearLocation:(CLLocation *)location; { static const NSInteger CITY_RADIUS_M = 100 * 1000; // 100km ARCity *closestCity = [[[ARCity cities] sortedArrayUsingComparator:^NSComparisonResult(ARCity *_Nonnull lhs, ARCity *_Nonnull rhs) { if ([lhs.epicenter distanceFromLocation:location] < [rhs.epicenter distanceFromLocation:location]) { return NSOrderedAscending; } else { return NSOrderedDescending; } }] firstObject]; if ([closestCity.epicenter distanceFromLocation:location] < CITY_RADIUS_M) { return closestCity; } else { // User is too far away from any city. return nil; } } @end
{ "pile_set_name": "Github" }