text
stringlengths
2
97.5k
meta
dict
/* * 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.stanbol.entityhub.yard.solr.model; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.stanbol.entityhub.servicesapi.defaults.SpecialFieldEnum; /** * Represents a logical field within the index. * <p> * A logical field consists of the following parts: * <ul> * <li>The path, a list of path elements (URIs parsed as String) * <li>The {@link IndexDataType} * <li>The language * </ul> * <p> * Logical fields are than mapped with an 1..n mapping to actual fields in the Index Documents. This * functionality is provided by the {@link FieldMapper} * * @author Rupert Westenthaler * */ public class IndexField { private final List<String> path; private final SpecialFieldEnum specialField; private final IndexDataType indexType; private final Set<String> languages; private final int hash; /** * Constructs a new IndexField * @param path * @param languages * @throws IllegalArgumentException */ public IndexField(List<String> path, String... languages) throws IllegalArgumentException { this(path,null,languages); } /** * Constructs a new IndexField * * @param path * @param indexType * @param language * @throws IllegalArgumentException */ public IndexField(List<String> path, IndexDataType indexType, String... languages) throws IllegalArgumentException { this(path,indexType,languages != null ? Arrays.asList(languages) : null); } /** * Constructs a new IndexField * @param path * @param indexType * @param languages * @throws IllegalArgumentException */ public IndexField(List<String> path, IndexDataType indexType, Collection<String> languages) throws IllegalArgumentException { this.specialField = getSpecialField(path); // we need to create a new list, to ensure, that no one can change this member! this.path = Collections.unmodifiableList(new ArrayList<String>(path)); //NOTE: no data types for special fields if (indexType == null || specialField != null) { this.indexType = IndexDataType.DEFAULT; // the type representing no pre- nor suffix } else { this.indexType = indexType; } //NOTE: no languages for special fields if (specialField != null || languages == null || languages.isEmpty() ) { this.languages = Collections.emptySet(); } else { Set<String> languageSet = new HashSet<String>(); for (String language : languages) { if (language == null || language.isEmpty()) { languageSet.add(null); // interpret empty as default language } else { languageSet.add(language); } } this.languages = Collections.unmodifiableSet(languageSet); } // calculate the hash of is immutable class only once hash = this.path.hashCode() + this.indexType.hashCode() + this.languages.hashCode(); //we do not need to use specialField for the has as those do have an //unique hash by {special path, no type, no language}. } /** * Checks if this {@link IndexField} represents a field registered with the * {@link SpecialFieldEnum}. * @return the state */ public boolean isSpecialField(){ return specialField != null; } /** * If this path represents a special field registered with the * {@link SpecialFieldEnum} than it will return the according entry of this * enumeration. Otherwise <code>null</code> is returned * @return the {@link SpecialFieldEnum} or <code>null</code> if this * {@link IndexField} is not a special one. */ public SpecialFieldEnum getSpecialField(){ return specialField; } /** * Checks if the path is not <code>null</code>, empty and does not contain a <code>null</code> or empty * element. * * @param path * the path to validate * @throws IllegalArgumentException * if the parsed path in not valid */ public static void validatePath(List<String> path) throws IllegalArgumentException { checkPathElements(path); } private static SpecialFieldEnum checkPathElements(List<String> path) throws IllegalArgumentException { if (path == null || path.isEmpty()) { throw new IllegalArgumentException("Parameter path MUST NOT be NULL nor empty!"); } for(String field : path){ if(field == null || field.isEmpty()){ throw new IllegalArgumentException(String.format( "The parsed path MUST NOT contain a NULL value or an empty element (path=%s)!", path)); } SpecialFieldEnum specialField = SpecialFieldEnum.getSpecialField(field); if(specialField != null){ if(path.size() > 1){ throw new IllegalArgumentException(String.format( "Special Fields MUST NOT be used on path with a length > 1 " + "(path='%s' | specialField='%s')!", path, specialField.getUri())); } return specialField; } } return null; } /** * Checks if the parsed path represents a special field. This also validates * the parsed path with the same rules as applied by {@link #validatePath(List)} * @param path the path * @return the {@link SpecialFieldEnum special field} or <code>null</code>. * @throws IllegalArgumentException if the parsed path is not valid */ public static SpecialFieldEnum getSpecialField(List<String> path){ return checkPathElements(path); } /** * Getter for the Path * * @return the path. Unmodifiable list, guaranteed to contain at lest one element. All elements are * guaranteed NOT <code>null</code> and NOT empty. */ public final List<String> getPath() { return path; } /** * Getter for the index data type * * @return the index data type. Guaranteed to be NOT <code>null</code> */ public final IndexDataType getDataType() { return indexType; } /** * Checks if this field defines any language * * @return <code>true</code> if a language is defined for this field. Note that <code>true</code> is * returned if the language is <code>null</code>. */ public final boolean hasLanguage() { return !languages.isEmpty(); } /** * Getter for the Languages. * * @return the languages. Unmodifiable collection, guaranteed to contain at least one element. May contain * the <code>null</code> value (used for the default language). */ public final Collection<String> getLanguages() { return languages; } @Override public boolean equals(Object obj) { return obj instanceof IndexField && ((IndexField) obj).path.equals(path) && ((IndexField) obj).indexType.equals(indexType) && ((IndexField) obj).languages.equals(languages); } @Override public int hashCode() { return hash; } @Override public String toString() { return String.format("IndexField[path: %s|type: %s", path, indexType) + (hasLanguage() ? String.format("|languages: %s]", languages) : "]"); } }
{ "pile_set_name": "Github" }
<?php /** * li₃: the most RAD framework for PHP (http://li3.me) * * Copyright 2016, Union of RAD. All rights reserved. This source * code is distributed under the terms of the BSD 3-Clause License. * The full license text can be found in the LICENSE.txt file. */ namespace lithium\tests\integration\data; use lithium\tests\fixture\model\gallery\Galleries; class DocumentTest extends \lithium\tests\integration\data\Base { /** * Skip the test if no allowed database connection available. */ public function skip() { parent::connect($this->_connection); $this->skipIf(!$this->with(['MongoDb', 'CouchDb'])); } public function setUp() { Galleries::config(['meta' => ['connection' => 'test']]); } public function tearDown() { Galleries::remove(); Galleries::reset(); } /** * Tests that a successful find on an empty collection doesn't error out * when using count on the resulting collection returned. See issue #1042. */ public function testFindOnEmptyCollection() { $result = Galleries::find('all'); $expected = 0; $result = $result->count(); $this->assertIdentical($expected, $result); } public function testUpdateWithNewArray() { $new = Galleries::create(['name' => 'Poneys', 'active' => true]); $expected = ['name' => 'Poneys', 'active' => true]; $result = $new->data(); $this->assertEqual($expected, $result); $new->foo = ['bar']; $expected = ['name' => 'Poneys', 'active' => true, 'foo' => ['bar']]; $result = $new->data(); $this->assertEqual($expected, $result); $this->assertTrue($new->save()); $updated = Galleries::find((string) $new->_id); $expected = 'bar'; $result = $updated->foo[0]; $this->assertEqual($expected, $result); $updated->foo[1] = 'baz'; $this->assertTrue($updated->save()); $updated = Galleries::find((string) $updated->_id); $expected = 'baz'; $result = $updated->foo[1]; $this->assertEqual($expected, $result); } } ?>
{ "pile_set_name": "Github" }
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> /** Our old friend die from ex17. */ void die(const char *message) { if (errno) { perror(message); } else { printf("ERROR: %s\n", message); } exit(1); } // a typedef creates a fake type, in this // case for a function pointer typedef int (*compare_cb) (int a, int b); /** * A classic bubble sort function that uses the * compare_cb to do the sorting. */ int *bubble_sort(int *numbers, int count, compare_cb cmp) { int temp = 0; int i = 0; int j = 0; int *target = malloc(count * sizeof(int)); if (!target) die("Memory error."); memcpy(target, numbers, count * sizeof(int)); for (i = 0; i < count; i++) { for (j = 0; j < count - 1; j++) { if (cmp(target[j], target[j + 1]) > 0) { temp = target[j + 1]; target[j + 1] = target[j]; target[j] = temp; } } } return target; } int sorted_order(int a, int b) { return a - b; } int reverse_order(int a, int b) { return b - a; } int strange_order(int a, int b) { if (a == 0 || b == 0) { return 0; } else { return a % b; } } /** * Used to test that we are sorting things correctly * by doing the sort and printing it out. */ void test_sorting(int *numbers, int count, compare_cb cmp) { int i = 0; int *sorted = bubble_sort(numbers, count, cmp); if (!sorted) die("Failed to sort as requested."); for (i = 0; i < count; i++) { printf("%d ", sorted[i]); } printf("\n"); free(sorted); } int main(int argc, char *argv[]) { if (argc < 2) die("USAGE: ex18 4 3 1 5 6"); int count = argc - 1; int i = 0; char **inputs = argv + 1; int *numbers = malloc(count * sizeof(int)); if (!numbers) die("Memory error."); for (i = 0; i < count; i++) { numbers[i] = atoi(inputs[i]); } test_sorting(numbers, count, sorted_order); test_sorting(numbers, count, reverse_order); test_sorting(numbers, count, strange_order); free(numbers); return 0; }
{ "pile_set_name": "Github" }
import Notify from 'heyui/src/plugins/notify'; import utils from 'heyui/src/utils/utils'; import locale from 'heyui/src/locale'; const prefixCls = 'h-modal'; let Default = { middle: false }; function Confirm(content, title) { return new Promise((resolve, reject) => { let param = { type: prefixCls, content: `<div><i class="h-icon-warn yellow-color" style="font-size:28px;vertical-align: -8px;"></i>&nbsp;&nbsp;${content}</div>`, buttons: ['cancel', 'ok'], events: { ok: (n) => { n.close(); resolve(); }, cancel: (n) => { n.close(); reject(new Error('cancel')); } }, title, className: 'h-modal-comfirm h-modal-type-default', hasMask: true, closeOnMask: true, hasCloseIcon: false, timeout: 0 }; param = utils.extend({}, Default, param, true); return Notify(param); }); } function confirm(content, title) { if (!title) { title = locale.t('h.confirm.title'); } return Confirm(content, title); } confirm.config = (options) => { if (options.middle) { Default.middle = true; } }; export default confirm;
{ "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.datasketches.quantiles; import static org.apache.datasketches.quantiles.PreambleUtil.COMPACT_FLAG_MASK; import static org.apache.datasketches.quantiles.PreambleUtil.EMPTY_FLAG_MASK; import static org.apache.datasketches.quantiles.PreambleUtil.ORDERED_FLAG_MASK; import static org.apache.datasketches.quantiles.PreambleUtil.READ_ONLY_FLAG_MASK; import static org.apache.datasketches.quantiles.PreambleUtil.insertFamilyID; import static org.apache.datasketches.quantiles.PreambleUtil.insertFlags; import static org.apache.datasketches.quantiles.PreambleUtil.insertK; import static org.apache.datasketches.quantiles.PreambleUtil.insertMaxDouble; import static org.apache.datasketches.quantiles.PreambleUtil.insertMinDouble; import static org.apache.datasketches.quantiles.PreambleUtil.insertN; import static org.apache.datasketches.quantiles.PreambleUtil.insertPreLongs; import static org.apache.datasketches.quantiles.PreambleUtil.insertSerVer; import java.util.Arrays; import org.apache.datasketches.Family; import org.apache.datasketches.memory.WritableMemory; /** * The doubles to byte array algorithms. * * @author Lee Rhodes * @author Jon Malkin */ final class DoublesByteArrayImpl { private DoublesByteArrayImpl() {} static byte[] toByteArray(final DoublesSketch sketch, final boolean ordered, final boolean compact) { final boolean empty = sketch.isEmpty(); //create the flags byte final int flags = (empty ? EMPTY_FLAG_MASK : 0) | (ordered ? ORDERED_FLAG_MASK : 0) | (compact ? (COMPACT_FLAG_MASK | READ_ONLY_FLAG_MASK) : 0); if (empty && !sketch.isDirect()) { //empty & on-heap final byte[] outByteArr = new byte[Long.BYTES]; final WritableMemory memOut = WritableMemory.wrap(outByteArr); final int preLongs = 1; insertPre0(memOut, preLongs, flags, sketch.getK()); return outByteArr; } //not empty || direct; flags passed for convenience return convertToByteArray(sketch, flags, ordered, compact); } /** * Returns a byte array, including preamble, min, max and data extracted from the sketch. * @param sketch the given DoublesSketch * @param flags the Flags field * @param ordered true if the desired form of the resulting array has the base buffer sorted. * @param compact true if the desired form of the resulting array is in compact form. * @return a byte array, including preamble, min, max and data extracted from the Combined Buffer. */ private static byte[] convertToByteArray(final DoublesSketch sketch, final int flags, final boolean ordered, final boolean compact) { final int preLongs = 2; final int extra = 2; // extra space for min and max values final int prePlusExtraBytes = (preLongs + extra) << 3; final int k = sketch.getK(); final long n = sketch.getN(); // If not-compact, have accessor always report full levels. Then use level size to determine // whether to copy data out. final DoublesSketchAccessor dsa = DoublesSketchAccessor.wrap(sketch, !compact); final int outBytes = (compact ? sketch.getCompactStorageBytes() : sketch.getUpdatableStorageBytes()); final byte[] outByteArr = new byte[outBytes]; final WritableMemory memOut = WritableMemory.wrap(outByteArr); //insert preamble-0, N, min, max insertPre0(memOut, preLongs, flags, k); if (sketch.isEmpty()) { return outByteArr; } insertN(memOut, n); insertMinDouble(memOut, sketch.getMinValue()); insertMaxDouble(memOut, sketch.getMaxValue()); long memOffsetBytes = prePlusExtraBytes; // might need to sort base buffer but don't want to change input sketch final int bbCnt = Util.computeBaseBufferItems(k, n); if (bbCnt > 0) { //Base buffer items only final double[] bbItemsArr = dsa.getArray(0, bbCnt); if (ordered) { Arrays.sort(bbItemsArr); } memOut.putDoubleArray(memOffsetBytes, bbItemsArr, 0, bbCnt); } // If n < 2k, totalLevels == 0 so ok to overshoot the offset update memOffsetBytes += (compact ? bbCnt : 2 * k) << 3; // If serializing from a compact sketch to a non-compact form, we may end up copying data for a // higher level one or more times into an unused level. A bit wasteful, but not incorrect. final int totalLevels = Util.computeTotalLevels(sketch.getBitPattern()); for (int lvl = 0; lvl < totalLevels; ++lvl) { dsa.setLevel(lvl); if (dsa.numItems() > 0) { assert dsa.numItems() == k; memOut.putDoubleArray(memOffsetBytes, dsa.getArray(0, k), 0, k); memOffsetBytes += (k << 3); } } return outByteArr; } private static void insertPre0(final WritableMemory wmem, final int preLongs, final int flags, final int k) { insertPreLongs(wmem, preLongs); insertSerVer(wmem, DoublesSketch.DOUBLES_SER_VER); insertFamilyID(wmem, Family.QUANTILES.getID()); insertFlags(wmem, flags); insertK(wmem, k); } }
{ "pile_set_name": "Github" }
package context import ( "os" "strconv" "time" "github.com/spf13/viper" ) // ExternalCalls is the extruct that performs exernal calls. type ExternalCalls struct{} // SetConfigFile will set a configfile into a path. func (eC *ExternalCalls) SetConfigFile(configName, configPath string) error { viper.SetConfigName(configName) viper.AddConfigPath(configPath) return viper.ReadInConfig() } // GetEnvironmentVariable will return the value of an env var. func (eC *ExternalCalls) GetEnvironmentVariable(envName string) string { return os.Getenv(envName) } // ConvertStrToInt converts a string into int. func (eC *ExternalCalls) ConvertStrToInt(str string) (int, error) { return strconv.Atoi(str) } // GetTimeDurationInSeconds returnin the number of seconds of a duration. func (eC *ExternalCalls) GetTimeDurationInSeconds(duration int) time.Duration { return time.Duration(duration) * time.Second } // GetStringFromConfigFile returns a string from a config file. func (eC *ExternalCalls) GetStringFromConfigFile(value string) string { return viper.GetString(value) } // GetBoolFromConfigFile returns a bool from a config file. func (eC *ExternalCalls) GetBoolFromConfigFile(value string) bool { return viper.GetBool(value) } // GetIntFromConfigFile returns a int from a config file. func (eC *ExternalCalls) GetIntFromConfigFile(value string) int { return viper.GetInt(value) } // CallerInterface is the interface that stores all external call functions. type CallerInterface interface { SetConfigFile(configName, configPath string) error GetStringFromConfigFile(value string) string GetBoolFromConfigFile(value string) bool GetIntFromConfigFile(value string) int GetEnvironmentVariable(envName string) string ConvertStrToInt(str string) (int, error) GetTimeDurationInSeconds(duration int) time.Duration }
{ "pile_set_name": "Github" }
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Infrastructure.Filters { using AspNetCore.Mvc; using global::Ordering.Domain.Exceptions; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.eShopOnContainers.Services.Ordering.API.Infrastructure.ActionResults; using Microsoft.Extensions.Logging; using System.Net; public class HttpGlobalExceptionFilter : IExceptionFilter { private readonly IHostingEnvironment env; private readonly ILogger<HttpGlobalExceptionFilter> logger; public HttpGlobalExceptionFilter(IHostingEnvironment env, ILogger<HttpGlobalExceptionFilter> logger) { this.env = env; this.logger = logger; } public void OnException(ExceptionContext context) { logger.LogError(new EventId(context.Exception.HResult), context.Exception, context.Exception.Message); if (context.Exception.GetType() == typeof(OrderingDomainException)) { var json = new JsonErrorResponse { Messages = new[] { context.Exception.Message } }; // Result asigned to a result object but in destiny the response is empty. This is a known bug of .net core 1.1 //It will be fixed in .net core 1.1.2. See https://github.com/aspnet/Mvc/issues/5594 for more information context.Result = new BadRequestObjectResult(json); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; } else { var json = new JsonErrorResponse { Messages = new[] { "An error occur.Try it again." } }; if (env.IsDevelopment()) { json.DeveloperMessage = context.Exception; } // Result asigned to a result object but in destiny the response is empty. This is a known bug of .net core 1.1 // It will be fixed in .net core 1.1.2. See https://github.com/aspnet/Mvc/issues/5594 for more information context.Result = new InternalServerErrorObjectResult(json); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; } context.ExceptionHandled = true; } private class JsonErrorResponse { public string[] Messages { get; set; } public object DeveloperMessage { get; set; } } } }
{ "pile_set_name": "Github" }
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_IMAGE_FETCHER_CORE_CACHE_IMAGE_METADATA_STORE_H_ #define COMPONENTS_IMAGE_FETCHER_CORE_CACHE_IMAGE_METADATA_STORE_H_ #include <string> #include "base/time/time.h" #include "components/image_fetcher/core/cache/image_store_types.h" namespace image_fetcher { // Interface for an object capable of saving/loading image metadata. class ImageMetadataStore { public: virtual ~ImageMetadataStore() = default; // Initialize this store. If calls are made to the class before the // initialization has completed, they are ignored. Ignored requests won't do // any meaningful work. It's the responsibility of the caller to check for // initialization before calling. virtual void Initialize(base::OnceClosure callback) = 0; // Returns true if initialization has finished successfully, else false. // While this is false, initialization may have already started. virtual bool IsInitialized() = 0; // Loads the image metadata for the |key|. virtual void LoadImageMetadata(const std::string& key, ImageMetadataCallback) = 0; // Adds or updates the image metadata for the |key|. If metadata exists for an // image and the |needs_transcoding| is still true, we don't need to update // the existing metadata. virtual void SaveImageMetadata(const std::string& key, const size_t data_size, bool needs_transcoding, ExpirationInterval expiration_interval) = 0; // Deletes the image metadata for the |key|. virtual void DeleteImageMetadata(const std::string& key) = 0; // Updates |last_used_time| for the given |key| if it exists. virtual void UpdateImageMetadata(const std::string& key) = 0; // Returns all the keys this store has. virtual void GetAllKeys(KeysCallback callback) = 0; // Returns the total size of what's in metadata for a given cache option, // possibly incorrect. virtual int64_t GetEstimatedSize(CacheOption cache_option) = 0; // Deletes all metadata that's been cached before the boundary given as // |expiration_time|. void EvictImageMetadata(base::Time expiration_time, KeysCallback callback) { EvictImageMetadata(expiration_time, /* Max size_t */ -1, std::move(callback)); } // Deletes all metadata that's been cached before the boundary given as // |expiration_time|. Evicts other metadata until there are |bytes_left| // in storage. virtual void EvictImageMetadata(base::Time expiration_time, const size_t bytes_left, KeysCallback callback) = 0; }; } // namespace image_fetcher #endif // COMPONENTS_IMAGE_FETCHER_CORE_CACHE_IMAGE_METADATA_STORE_H_
{ "pile_set_name": "Github" }
//======================================================================= // Copyright 1997, 1998, 1999, 2000 University of Notre Dame. // Copyright 2006 The Trustees of Indiana University. // Copyright (C) 2001 Vladimir Prus <ghost@cs.msu.su> // Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek, Douglas Gregor // // Distributed under 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) //======================================================================= // The mutating functions (add_edge, etc.) were added by Vladimir Prus. #ifndef BOOST_VECTOR_AS_GRAPH_HPP #define BOOST_VECTOR_AS_GRAPH_HPP #include <cassert> #include <utility> #include <vector> #include <cstddef> #include <iterator> #include <boost/iterator/counting_iterator.hpp> #include <boost/range/irange.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/property_map/property_map.hpp> #include <boost/graph/properties.hpp> #include <algorithm> /* This module implements the VertexListGraph concept using a std::vector as the "back-bone" of the graph (the vector *is* the graph object). The edge-lists type of the graph is templated, so the user can choose any STL container, so long as the value_type of the container is convertible to the size_type of the vector. For now any graph properties must be stored seperately. This module requires the C++ compiler to support partial specialization for the graph_traits class, so this is not portable to VC++. */ namespace boost { namespace detail { template < class EdgeList > struct val_out_edge_ret; template < class EdgeList > struct val_out_edge_iter; template < class EdgeList > struct val_edge; } } namespace boost { struct vector_as_graph_traversal_tag : public vertex_list_graph_tag, public adjacency_graph_tag, public incidence_graph_tag { }; template < class EdgeList > struct graph_traits< std::vector< EdgeList > > { typedef typename EdgeList::value_type V; typedef V vertex_descriptor; typedef typename detail::val_edge< EdgeList >::type edge_descriptor; typedef typename EdgeList::const_iterator adjacency_iterator; typedef typename detail::val_out_edge_iter< EdgeList >::type out_edge_iterator; typedef void in_edge_iterator; typedef void edge_iterator; typedef counting_iterator< V > vertex_iterator; typedef directed_tag directed_category; typedef allow_parallel_edge_tag edge_parallel_category; typedef vector_as_graph_traversal_tag traversal_category; typedef typename std::vector< EdgeList >::size_type vertices_size_type; typedef void edges_size_type; typedef typename EdgeList::size_type degree_size_type; static V null_vertex() { return V(-1); } }; template < class EdgeList > struct edge_property_type< std::vector< EdgeList > > { typedef void type; }; template < class EdgeList > struct vertex_property_type< std::vector< EdgeList > > { typedef void type; }; template < class EdgeList > struct graph_property_type< std::vector< EdgeList > > { typedef void type; }; } namespace boost { namespace detail { // "val" is short for Vector Adjacency List template < class EdgeList > struct val_edge { typedef typename EdgeList::value_type V; typedef std::pair< V, V > type; }; // need rewrite this using boost::iterator_adaptor template < class V, class Iter > class val_out_edge_iterator { typedef val_out_edge_iterator self; typedef std::pair< V, V > Edge; public: typedef std::input_iterator_tag iterator_category; typedef std::pair< V, V > value_type; typedef std::ptrdiff_t difference_type; typedef std::pair< V, V >* pointer; typedef const std::pair< V, V > reference; val_out_edge_iterator() {} val_out_edge_iterator(V s, Iter i) : _source(s), _iter(i) {} Edge operator*() const { return Edge(_source, *_iter); } self& operator++() { ++_iter; return *this; } self operator++(int) { self t = *this; ++_iter; return t; } bool operator==(const self& x) const { return _iter == x._iter; } bool operator!=(const self& x) const { return _iter != x._iter; } protected: V _source; Iter _iter; }; template < class EdgeList > struct val_out_edge_iter { typedef typename EdgeList::value_type V; typedef typename EdgeList::const_iterator Iter; typedef val_out_edge_iterator< V, Iter > type; }; template < class EdgeList > struct val_out_edge_ret { typedef typename val_out_edge_iter< EdgeList >::type IncIter; typedef std::pair< IncIter, IncIter > type; }; } // namesapce detail template < class EdgeList, class Alloc > typename detail::val_out_edge_ret< EdgeList >::type out_edges( typename EdgeList::value_type v, const std::vector< EdgeList, Alloc >& g) { typedef typename detail::val_out_edge_iter< EdgeList >::type Iter; typedef typename detail::val_out_edge_ret< EdgeList >::type return_type; return return_type(Iter(v, g[v].begin()), Iter(v, g[v].end())); } template < class EdgeList, class Alloc > typename EdgeList::size_type out_degree( typename EdgeList::value_type v, const std::vector< EdgeList, Alloc >& g) { return g[v].size(); } template < class EdgeList, class Alloc > std::pair< typename EdgeList::const_iterator, typename EdgeList::const_iterator > adjacent_vertices( typename EdgeList::value_type v, const std::vector< EdgeList, Alloc >& g) { return std::make_pair(g[v].begin(), g[v].end()); } // source() and target() already provided for pairs in graph_traits.hpp template < class EdgeList, class Alloc > std::pair< boost::counting_iterator< typename EdgeList::value_type >, boost::counting_iterator< typename EdgeList::value_type > > vertices(const std::vector< EdgeList, Alloc >& v) { typedef boost::counting_iterator< typename EdgeList::value_type > Iter; return std::make_pair(Iter(0), Iter(v.size())); } template < class EdgeList, class Alloc > typename std::vector< EdgeList, Alloc >::size_type num_vertices( const std::vector< EdgeList, Alloc >& v) { return v.size(); } template < class EdgeList, class Allocator > typename std::pair< typename detail::val_edge< EdgeList >::type, bool > add_edge(typename EdgeList::value_type u, typename EdgeList::value_type v, std::vector< EdgeList, Allocator >& g) { typedef typename detail::val_edge< EdgeList >::type edge_type; g[u].insert(g[u].end(), v); return std::make_pair(edge_type(u, v), true); } template < class EdgeList, class Allocator > typename std::pair< typename detail::val_edge< EdgeList >::type, bool > edge( typename EdgeList::value_type u, typename EdgeList::value_type v, std::vector< EdgeList, Allocator >& g) { typedef typename detail::val_edge< EdgeList >::type edge_type; typename EdgeList::iterator i = g[u].begin(), end = g[u].end(); for (; i != end; ++i) if (*i == v) return std::make_pair(edge_type(u, v), true); return std::make_pair(edge_type(), false); } template < class EdgeList, class Allocator > void remove_edge(typename EdgeList::value_type u, typename EdgeList::value_type v, std::vector< EdgeList, Allocator >& g) { typename EdgeList::iterator i = std::remove(g[u].begin(), g[u].end(), v); if (i != g[u].end()) g[u].erase(i, g[u].end()); } template < class EdgeList, class Allocator > void remove_edge(typename detail::val_edge< EdgeList >::type e, std::vector< EdgeList, Allocator >& g) { typename EdgeList::value_type u, v; u = e.first; v = e.second; // FIXME: edge type does not fully specify the edge to be deleted typename EdgeList::iterator i = std::remove(g[u].begin(), g[u].end(), v); if (i != g[u].end()) g[u].erase(i, g[u].end()); } template < class EdgeList, class Allocator, class Predicate > void remove_edge_if(Predicate p, std::vector< EdgeList, Allocator >& g) { for (std::size_t u = 0; u < g.size(); ++u) { // Oops! gcc gets internal compiler error on compose_....... typedef typename EdgeList::iterator iterator; iterator b = g[u].begin(), e = g[u].end(); if (!g[u].empty()) { for (; b != e;) { if (p(std::make_pair(u, *b))) { --e; if (b == e) break; else iter_swap(b, e); } else { ++b; } } } if (e != g[u].end()) g[u].erase(e, g[u].end()); } } template < class EdgeList, class Allocator > typename EdgeList::value_type add_vertex(std::vector< EdgeList, Allocator >& g) { g.resize(g.size() + 1); return g.size() - 1; } template < class EdgeList, class Allocator > void clear_vertex( typename EdgeList::value_type u, std::vector< EdgeList, Allocator >& g) { g[u].clear(); for (std::size_t i = 0; i < g.size(); ++i) remove_edge(i, u, g); } template < class EdgeList, class Allocator > void remove_vertex( typename EdgeList::value_type u, std::vector< EdgeList, Allocator >& g) { typedef typename EdgeList::iterator iterator; clear_vertex(u, g); g.erase(g.begin() + u); for (std::size_t i = 0; i < g.size(); ++i) for (iterator it = g[i].begin(); it != g[i].end(); ++it) // after clear_vertex *it is never equal to u if (*it > u) --*it; } template < typename EdgeList, typename Allocator > struct property_map< std::vector< EdgeList, Allocator >, vertex_index_t > { typedef identity_property_map type; typedef type const_type; }; template < typename EdgeList, typename Allocator > identity_property_map get( vertex_index_t, const std::vector< EdgeList, Allocator >&) { return identity_property_map(); } template < typename EdgeList, typename Allocator > identity_property_map get(vertex_index_t, std::vector< EdgeList, Allocator >&) { return identity_property_map(); } } // namespace boost #endif // BOOST_VECTOR_AS_GRAPH_HPP
{ "pile_set_name": "Github" }
package com.huawei.security.conscrypt; import android.util.Log; import com.huawei.security.HwKeystoreManager; import com.huawei.security.keymaster.HwKeymasterCertificateChain; import java.io.ByteArrayInputStream; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SignatureException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.List; import javax.security.auth.x500.X500Principal; public class HwTrustCertificateStore { private static final String TAG = "HwTrustCertificateStore"; private HwKeystoreManager mKeyStore = HwKeystoreManager.getInstance(); /* access modifiers changed from: private */ public interface CertSelector { boolean match(X509Certificate x509Certificate, X509Certificate x509Certificate2); } public HwTrustCertificateStore(HwKeystoreManager keystore) { this.mKeyStore = keystore; } private static X509Certificate[] toCertificates(List<byte[]> bytes) { if (bytes == null || bytes.size() == 0) { Log.e(TAG, "Invalid param."); return null; } try { Log.d(TAG, "toCertificates bytes.size:" + bytes.size()); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); X509Certificate[] certs = new X509Certificate[bytes.size()]; int i = 0; do { byte[] data = bytes.get(i); if (data != null) { if (data.length != 0) { certs[i] = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(data)); i++; } } Log.e(TAG, "data is null"); return null; } while (i < bytes.size()); return certs; } catch (CertificateException e) { Log.w(TAG, "Couldn't parse certificates in keystore CertificateException", e); return null; } } public X509Certificate getTrustAnchor(X509Certificate c) { X509Certificate trustCert = (X509Certificate) findCert(c, c.getSubjectX500Principal(), new GetTrustAnchorCertSelector(), X509Certificate.class); if (trustCert != null) { return trustCert; } return null; } public X509Certificate findIssuer(X509Certificate c) { X509Certificate cert = (X509Certificate) findCert(c, c.getIssuerX500Principal(), new FindIssuerCertSelector(), X509Certificate.class); if (cert != null) { return cert; } return null; } private <T> T findCert(X509Certificate c, X500Principal subject, CertSelector selector, Class<T> desiredReturnType) { if (this.mKeyStore == null) { Log.e(TAG, "mKeyStore is null!"); return null; } HwKeymasterCertificateChain outChain = new HwKeymasterCertificateChain(); if (this.mKeyStore.exportTrustCert(outChain) != 1) { Log.e(TAG, "exportTrustCert failed!"); return null; } List<byte[]> certsByte = outChain.getCertificates(); if (certsByte == null) { Log.e(TAG, "findCert failed!"); return null; } X509Certificate[] certList = toCertificates(certsByte); if (certList == null) { Log.e(TAG, "findCert toCertificates failed!"); return null; } for (X509Certificate x509Certificate : certList) { T t = (T) x509Certificate; boolean match = selector.match(t, c); boolean equals = subject != null ? subject.getName().equals(t.getSubjectX500Principal().getName()) : false; if (!match || !equals) { Log.d(TAG, "exportTrustCert match:" + match + " equals:" + equals); } if (match && equals) { Log.d(TAG, "findCert find the trust cert!"); if (desiredReturnType == X509Certificate.class) { return t; } if (desiredReturnType == Boolean.class) { return (T) Boolean.TRUE; } throw new AssertionError(); } } return null; } static class GetTrustAnchorCertSelector implements CertSelector { GetTrustAnchorCertSelector() { } @Override // com.huawei.security.conscrypt.HwTrustCertificateStore.CertSelector public boolean match(X509Certificate ca, X509Certificate c) { return ca.getPublicKey().equals(c.getPublicKey()); } } static class FindIssuerCertSelector implements CertSelector { FindIssuerCertSelector() { } @Override // com.huawei.security.conscrypt.HwTrustCertificateStore.CertSelector public boolean match(X509Certificate ca, X509Certificate c) { try { c.verify(ca.getPublicKey()); return true; } catch (CertificateException e) { Log.e(HwTrustCertificateStore.TAG, "FindIssuerCertSelector match fail CertificateException!"); return false; } catch (NoSuchAlgorithmException e2) { Log.e(HwTrustCertificateStore.TAG, "FindIssuerCertSelector match fail NoSuchAlgorithmException!"); return false; } catch (InvalidKeyException e3) { Log.e(HwTrustCertificateStore.TAG, "FindIssuerCertSelector match fail InvalidKeyException!"); return false; } catch (NoSuchProviderException e4) { Log.e(HwTrustCertificateStore.TAG, "FindIssuerCertSelector match fail NoSuchProviderException!"); return false; } catch (SignatureException e5) { Log.e(HwTrustCertificateStore.TAG, "FindIssuerCertSelector match fail SignatureException!"); return false; } } } }
{ "pile_set_name": "Github" }
PKIX1Algorithms88 { iso(1) identified-organization(3) dod(6) internet(1) security(5) mechanisms(5) pkix(7) id-mod(0) id-mod-pkix1-algorithms(17) } DEFINITIONS EXPLICIT TAGS ::= BEGIN -- EXPORTS All; -- IMPORTS NONE; -- -- One-way Hash Functions -- md2 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 2 } md5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 5 } id-sha1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 26 } -- -- DSA Keys and Signatures -- -- OID for DSA public key id-dsa OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) x9-57(10040) x9algorithm(4) 1 } -- encoding for DSA public key DSAPublicKey ::= INTEGER -- public key, y Dss-Parms ::= SEQUENCE { p INTEGER, q INTEGER, g INTEGER } -- OID for DSA signature generated with SHA-1 hash id-dsa-with-sha1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) x9-57 (10040) x9algorithm(4) 3 } -- encoding for DSA signature generated with SHA-1 hash Dss-Sig-Value ::= SEQUENCE { r INTEGER, s INTEGER } -- -- RSA Keys and Signatures -- -- arc for RSA public key and RSA signature OIDs pkcs-1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } -- OID for RSA public keys rsaEncryption OBJECT IDENTIFIER ::= { pkcs-1 1 } -- OID for RSA signature generated with MD2 hash md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 } -- OID for RSA signature generated with MD5 hash md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 } -- OID for RSA signature generated with SHA-1 hash sha1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 } -- encoding for RSA public key RSAPublicKey ::= SEQUENCE { modulus INTEGER, -- n publicExponent INTEGER } -- e -- -- Diffie-Hellman Keys -- dhpublicnumber OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) ansi-x942(10046) number-type(2) 1 } -- encoding for DSA public key DHPublicKey ::= INTEGER -- public key, y = g^x mod p DomainParameters ::= SEQUENCE { p INTEGER, -- odd prime, p=jq +1 g INTEGER, -- generator, g q INTEGER, -- factor of p-1 j INTEGER OPTIONAL, -- subgroup factor, j>= 2 validationParms ValidationParms OPTIONAL } ValidationParms ::= SEQUENCE { seed BIT STRING, pgenCounter INTEGER } -- -- KEA Keys -- id-keyExchangeAlgorithm OBJECT IDENTIFIER ::= { 2 16 840 1 101 2 1 1 22 } KEA-Parms-Id ::= OCTET STRING -- -- Elliptic Curve Keys, Signatures, and Curves -- ansi-X9-62 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) 10045 } FieldID ::= SEQUENCE { -- Finite field fieldType OBJECT IDENTIFIER, parameters ANY DEFINED BY fieldType } -- Arc for ECDSA signature OIDS id-ecSigType OBJECT IDENTIFIER ::= { ansi-X9-62 signatures(4) } -- OID for ECDSA signatures with SHA-1 ecdsa-with-SHA1 OBJECT IDENTIFIER ::= { id-ecSigType 1 } -- OID for an elliptic curve signature -- format for the value of an ECDSA signature value ECDSA-Sig-Value ::= SEQUENCE { r INTEGER, s INTEGER } -- recognized field type OIDs are defined in the following arc id-fieldType OBJECT IDENTIFIER ::= { ansi-X9-62 fieldType(1) } -- where fieldType is prime-field, the parameters are of type Prime-p prime-field OBJECT IDENTIFIER ::= { id-fieldType 1 } Prime-p ::= INTEGER -- Finite field F(p), where p is an odd prime -- where fieldType is characteristic-two-field, the parameters are -- of type Characteristic-two characteristic-two-field OBJECT IDENTIFIER ::= { id-fieldType 2 } Characteristic-two ::= SEQUENCE { m INTEGER, -- Field size 2^m basis OBJECT IDENTIFIER, parameters ANY DEFINED BY basis } -- recognized basis type OIDs are defined in the following arc id-characteristic-two-basis OBJECT IDENTIFIER ::= { characteristic-two-field basisType(3) } -- gnbasis is identified by OID gnBasis and indicates -- parameters are NULL gnBasis OBJECT IDENTIFIER ::= { id-characteristic-two-basis 1 } -- parameters for this basis are NULL -- trinomial basis is identified by OID tpBasis and indicates -- parameters of type Pentanomial tpBasis OBJECT IDENTIFIER ::= { id-characteristic-two-basis 2 } -- Trinomial basis representation of F2^m -- Integer k for reduction polynomial xm + xk + 1 Trinomial ::= INTEGER -- for pentanomial basis is identified by OID ppBasis and indicates -- parameters of type Pentanomial ppBasis OBJECT IDENTIFIER ::= { id-characteristic-two-basis 3 } -- Pentanomial basis representation of F2^m -- reduction polynomial integers k1, k2, k3 -- f(x) = x**m + x**k3 + x**k2 + x**k1 + 1 Pentanomial ::= SEQUENCE { k1 INTEGER, k2 INTEGER, k3 INTEGER } -- The object identifiers gnBasis, tpBasis and ppBasis name -- three kinds of basis for characteristic-two finite fields FieldElement ::= OCTET STRING -- Finite field element ECPoint ::= OCTET STRING -- Elliptic curve point -- Elliptic Curve parameters may be specified explicitly, -- specified implicitly through a "named curve", or -- inherited from the CA EcpkParameters ::= CHOICE { ecParameters ECParameters, namedCurve OBJECT IDENTIFIER, implicitlyCA NULL } ECParameters ::= SEQUENCE { -- Elliptic curve parameters version ECPVer, fieldID FieldID, curve Curve, base ECPoint, -- Base point G order INTEGER, -- Order n of the base point cofactor INTEGER OPTIONAL } -- The integer h = #E(Fq)/n ECPVer ::= INTEGER {ecpVer1(1)} Curve ::= SEQUENCE { a FieldElement, -- Elliptic curve coefficient a b FieldElement, -- Elliptic curve coefficient b seed BIT STRING OPTIONAL } id-publicKeyType OBJECT IDENTIFIER ::= { ansi-X9-62 keyType(2) } id-ecPublicKey OBJECT IDENTIFIER ::= { id-publicKeyType 1 } -- Named Elliptic Curves in ANSI X9.62. ellipticCurve OBJECT IDENTIFIER ::= { ansi-X9-62 curves(3) } c-TwoCurve OBJECT IDENTIFIER ::= { ellipticCurve characteristicTwo(0) } c2pnb163v1 OBJECT IDENTIFIER ::= { c-TwoCurve 1 } c2pnb163v2 OBJECT IDENTIFIER ::= { c-TwoCurve 2 } c2pnb163v3 OBJECT IDENTIFIER ::= { c-TwoCurve 3 } c2pnb176w1 OBJECT IDENTIFIER ::= { c-TwoCurve 4 } c2tnb191v1 OBJECT IDENTIFIER ::= { c-TwoCurve 5 } c2tnb191v2 OBJECT IDENTIFIER ::= { c-TwoCurve 6 } c2tnb191v3 OBJECT IDENTIFIER ::= { c-TwoCurve 7 } c2onb191v4 OBJECT IDENTIFIER ::= { c-TwoCurve 8 } c2onb191v5 OBJECT IDENTIFIER ::= { c-TwoCurve 9 } c2pnb208w1 OBJECT IDENTIFIER ::= { c-TwoCurve 10 } c2tnb239v1 OBJECT IDENTIFIER ::= { c-TwoCurve 11 } c2tnb239v2 OBJECT IDENTIFIER ::= { c-TwoCurve 12 } c2tnb239v3 OBJECT IDENTIFIER ::= { c-TwoCurve 13 } c2onb239v4 OBJECT IDENTIFIER ::= { c-TwoCurve 14 } c2onb239v5 OBJECT IDENTIFIER ::= { c-TwoCurve 15 } c2pnb272w1 OBJECT IDENTIFIER ::= { c-TwoCurve 16 } c2pnb304w1 OBJECT IDENTIFIER ::= { c-TwoCurve 17 } c2tnb359v1 OBJECT IDENTIFIER ::= { c-TwoCurve 18 } c2pnb368w1 OBJECT IDENTIFIER ::= { c-TwoCurve 19 } c2tnb431r1 OBJECT IDENTIFIER ::= { c-TwoCurve 20 } primeCurve OBJECT IDENTIFIER ::= { ellipticCurve prime(1) } prime192v1 OBJECT IDENTIFIER ::= { primeCurve 1 } prime192v2 OBJECT IDENTIFIER ::= { primeCurve 2 } prime192v3 OBJECT IDENTIFIER ::= { primeCurve 3 } prime239v1 OBJECT IDENTIFIER ::= { primeCurve 4 } prime239v2 OBJECT IDENTIFIER ::= { primeCurve 5 } prime239v3 OBJECT IDENTIFIER ::= { primeCurve 6 } prime256v1 OBJECT IDENTIFIER ::= { primeCurve 7 } END
{ "pile_set_name": "Github" }
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
{ "pile_set_name": "Github" }
{ "status_code": 200, "data": { "PaginationToken": "", "ResourceTagMappingList": [ ], "ResponseMetadata": {} } }
{ "pile_set_name": "Github" }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // // Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services // // Microsoft Cognitive Services (formerly Project Oxford) GitHub: // https://github.com/Microsoft/Cognitive-Speech-TTS // // Copyright (c) Microsoft Corporation // All rights reserved. // // MIT License: // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { override func viewDidLoad() { super.viewDidLoad() } func textFieldDidBeginEditing(_ textField: UITextField) { textField.becomeFirstResponder() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() if let text = textField.text { DispatchQueue.global().async { TTSVocalizer.sharedInstance.vocalize(text) } } return false } }
{ "pile_set_name": "Github" }
version https://git-lfs.github.com/spec/v1 oid sha256:e3bae3afdb8853e7a104d47e408c9c76538ad9fc938ad382363fc9fbaa9bb12c size 1460
{ "pile_set_name": "Github" }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`RadioButton by default renders correctly 1`] = ` <label class="vnt-radio"> <input type="radio" name="radio" class="vnt-radio__input"> <span class="vnt-radio__icon"></span> <span class="vnt-radio__text">Radio</span></label> `; exports[`RadioButton can be checked and disabled renders correctly 1`] = ` <label class="vnt-radio" checked="checked"> <input type="radio" disabled="disabled" name="radio" class="vnt-radio__input"> <span class="vnt-radio__icon"></span> <span class="vnt-radio__text">Radio</span></label> `; exports[`RadioButton can be checked renders correctly 1`] = ` <label class="vnt-radio" checked="checked"> <input type="radio" name="radio" class="vnt-radio__input"> <span class="vnt-radio__icon"></span> <span class="vnt-radio__text">Radio</span></label> `; exports[`RadioButton can be disabled renders correctly 1`] = ` <label class="vnt-radio"> <input type="radio" disabled="disabled" name="radio" class="vnt-radio__input"> <span class="vnt-radio__icon"></span> <span class="vnt-radio__text">Radio</span></label> `; exports[`RadioButton can have content set using slot 1`] = ` <label class="vnt-radio"> <input type="radio" name="radio" class="vnt-radio__input"> <span class="vnt-radio__icon"></span> <span class="vnt-radio__text"><span>Custom content</span></span> </label> `; exports[`RadioButton can have name attribute rendered correctly 1`] = ` <label class="vnt-radio"> <input type="radio" name="groupedRadios" class="vnt-radio__input"> <span class="vnt-radio__icon"></span> <span class="vnt-radio__text">Radio</span></label> `;
{ "pile_set_name": "Github" }
This directory contains the implementations of lower-level forms of the bulk invocation functions: * `bulk_invoke_executor` * `bulk_async_executor` * `bulk_then_executor` These work like the regular `bulk_invoke` etc. functions, but take an executor as a parameter rather than an execution policy. The implementation of higher-level forms of `bulk_invoke` and friends lower onto these functions.
{ "pile_set_name": "Github" }
<?php namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2; /** * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2 * @xmlType TaxExclusiveAmountType * @xmlName TaxExclusiveAmount * @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\TaxExclusiveAmount */ class TaxExclusiveAmount extends TaxExclusiveAmountType { } // end class TaxExclusiveAmount
{ "pile_set_name": "Github" }
%YAML 1.2 --- | # Copyright 2015 gRPC 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. FROM debian:jessie <%include file="../../apt_get_basic.include"/> <%include file="../../gcp_api_libraries.include"/> <%include file="../../python_deps.include"/> <%include file="../../ruby_deps.include"/> <%include file="../../run_tests_addons.include"/> # Define the default command. CMD ["bash"]
{ "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. --> # Apache Hadoop Changelog ## Release 1.0.1 - 2012-02-22 ### INCOMPATIBLE CHANGES: | JIRA | Summary | Priority | Component | Reporter | Contributor | |:---- |:---- | :--- |:---- |:---- |:---- | | [HADOOP-7470](https://issues.apache.org/jira/browse/HADOOP-7470) | move up to Jackson 1.8.8 | Minor | util | Steve Loughran | Enis Soztutar | | [HADOOP-8037](https://issues.apache.org/jira/browse/HADOOP-8037) | Binary tarball does not preserve platform info for native builds, and RPMs fail to provide needed symlinks for libhadoop.so | Blocker | build | Matt Foley | Matt Foley | ### IMPROVEMENTS: | JIRA | Summary | Priority | Component | Reporter | Contributor | |:---- |:---- | :--- |:---- |:---- |:---- | | [MAPREDUCE-3184](https://issues.apache.org/jira/browse/MAPREDUCE-3184) | Improve handling of fetch failures when a tasktracker is not responding on HTTP | Major | jobtracker | Todd Lipcon | Todd Lipcon | | [MAPREDUCE-3607](https://issues.apache.org/jira/browse/MAPREDUCE-3607) | Port missing new API mapreduce lib classes to 1.x | Major | client | Tom White | Tom White | | [HADOOP-7987](https://issues.apache.org/jira/browse/HADOOP-7987) | Support setting the run-as user in unsecure mode | Major | security | Devaraj Das | Jitendra Nath Pandey | | [HDFS-2814](https://issues.apache.org/jira/browse/HDFS-2814) | NamenodeMXBean does not account for svn revision in the version information | Minor | . | Hitesh Shah | Hitesh Shah | | [HADOOP-8009](https://issues.apache.org/jira/browse/HADOOP-8009) | Create hadoop-client and hadoop-minicluster artifacts for downstream projects | Critical | build | Alejandro Abdelnur | Alejandro Abdelnur | ### BUG FIXES: | JIRA | Summary | Priority | Component | Reporter | Contributor | |:---- |:---- | :--- |:---- |:---- |:---- | | [MAPREDUCE-3343](https://issues.apache.org/jira/browse/MAPREDUCE-3343) | TaskTracker Out of Memory because of distributed cache | Major | mrv1 | Ahmed Radwan | yunjiong zhao | | [HADOOP-7960](https://issues.apache.org/jira/browse/HADOOP-7960) | Port HADOOP-5203 to branch-1, build version comparison is too restrictive | Major | . | Giridharan Kesavan | Matt Foley | | [HADOOP-7964](https://issues.apache.org/jira/browse/HADOOP-7964) | Deadlock in class init. | Blocker | security, util | Kihwal Lee | Daryn Sharp | | [HADOOP-7988](https://issues.apache.org/jira/browse/HADOOP-7988) | Upper case in hostname part of the principals doesn't work with kerberos. | Major | . | Jitendra Nath Pandey | Jitendra Nath Pandey | | [HADOOP-8010](https://issues.apache.org/jira/browse/HADOOP-8010) | hadoop-config.sh spews error message when HADOOP\_HOME\_WARN\_SUPPRESS is set to true and HADOOP\_HOME is present | Minor | scripts | Roman Shaposhnik | Roman Shaposhnik | | [HDFS-2379](https://issues.apache.org/jira/browse/HDFS-2379) | 0.20: Allow block reports to proceed without holding FSDataset lock | Critical | datanode | Todd Lipcon | Todd Lipcon | | [HADOOP-8052](https://issues.apache.org/jira/browse/HADOOP-8052) | Hadoop Metrics2 should emit Float.MAX\_VALUE (instead of Double.MAX\_VALUE) to avoid making Ganglia's gmetad core | Major | metrics | Varun Kapoor | Varun Kapoor |
{ "pile_set_name": "Github" }
{ "paths": { "customizerJs": [ "../assets/js/vendor/autoprefixer.js", "../assets/js/vendor/less.min.js", "../assets/js/vendor/jszip.min.js", "../assets/js/vendor/uglify.min.js", "../assets/js/vendor/Blob.js", "../assets/js/vendor/FileSaver.js", "../assets/js/raw-files.min.js", "../assets/js/src/customizer.js" ], "docsJs": [ "../assets/js/vendor/holder.min.js", "../assets/js/vendor/ZeroClipboard.min.js", "../assets/js/vendor/anchor.min.js", "../assets/js/src/application.js" ] }, "config": { "autoprefixerBrowsers": [ "Android 2.3", "Android >= 4", "Chrome >= 20", "Firefox >= 24", "Explorer >= 8", "iOS >= 6", "Opera >= 12", "Safari >= 6" ], "jqueryCheck": [ "if (typeof jQuery === 'undefined') {", " throw new Error('Bootstrap\\'s JavaScript requires jQuery')", "}\n" ], "jqueryVersionCheck": [ "+function ($) {", " 'use strict';", " var version = $.fn.jquery.split(' ')[0].split('.')", " if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 3)) {", " throw new Error('Bootstrap\\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4')", " }", "}(jQuery);\n\n" ] } }
{ "pile_set_name": "Github" }
<?php /** * Top Menu English lexicon topic * * @language en * @package modx * @subpackage lexicon */ $_lang['about'] = 'About'; $_lang['about_desc'] = 'Learn more and get help with MODX'; $_lang['access_permissions'] = 'Права доступу'; $_lang['access_permissions_desc'] = 'Manage user group access to Resources and Contexts'; $_lang['acls'] = 'Списки управління доступом'; $_lang['acls_desc'] = 'Управління дозволами через групи, ролі та політики доступу'; $_lang['admin'] = 'Admin'; $_lang['api_docs'] = 'Документація по API'; $_lang['api_docs_desc'] = 'Complete API documentation for MODX Revolution'; $_lang['bespoke_manager'] = 'Налаштування Менеджера'; $_lang['bespoke_manager_desc'] = 'Управління користувацькими налаштуваннями адміністративної панелі'; $_lang['components'] = 'Додатки'; $_lang['content_types'] = 'Типи вмісту'; $_lang['content_types_desc'] = 'Додавання нових типів вмісту для ресурсів, таких як .html, .js тощо.'; $_lang['contexts'] = 'Контексти'; $_lang['contexts_desc'] = 'Управління контекстами сайту та їх налаштуваннями'; $_lang['custom'] = 'Custom'; $_lang['custom_desc'] = 'Користувацькі елементи меню'; $_lang['dashboard'] = 'Панель управління'; $_lang['dashboards'] = 'Панелі'; $_lang['dashboards_desc'] = 'Управління панелями та віджетами Менеджера'; $_lang['edit_menu'] = 'Меню'; $_lang['edit_menu_desc'] = 'Управління діями та структурою верхнього меню Менеджера'; $_lang['eventlog_viewer'] = 'Журнал помилок'; $_lang['eventlog_viewer_desc'] = 'View the MODX error log'; $_lang['export_site'] = 'Export Static HTML'; $_lang['export_site_desc'] = 'Export the current site into static HTML pages'; $_lang['file_browser'] = 'Браузер медіа'; $_lang['file_browser_desc'] = 'Перегляд, завантаження і керування медіа-файлами'; $_lang['flush_access'] = 'Скинути Ваші права доступу'; $_lang['flush_access_confirm'] = 'Ви впевнені, що хочете перезавантажити Ваші права доступу? УВАГА: це не вплине на сеанси інших користувачів.'; $_lang['flush_access_desc'] = 'Перезавантажити усі права доступу у поточному сеансі і очистити кеш'; $_lang['flush_sessions'] = 'Розлогінити усіх користувачів'; $_lang['flush_sessions_confirm'] = 'Ви впевнені, що хочете завершити сеанси усіх користувачів? Завершаться сеанси усіх користувачів, включаючи Ваш сеанс, після цього усім необхідно буде входити в систему заново.'; $_lang['flush_sessions_desc'] = 'Негайно завершити усі сеанси роботи'; $_lang['flush_sessions_err'] = 'Сталася помилка при спробі завершення поточних сеансів користувачів.'; $_lang['flush_sessions_not_supported'] = 'Завершення сеансів роботи користувачів не підтримується у Вашій конфігурації.'; $_lang['form_customization'] = 'Налаштування форм'; $_lang['form_customization_desc'] = 'Налаштування зовнішнього вигляду Менеджера'; $_lang['forums'] = 'Форуми'; $_lang['forums_desc'] = 'View the MODX Forums'; $_lang['help'] = 'Допомога'; $_lang['import_resources'] = 'Імпорт статичних ресурсів'; $_lang['import_resources_desc'] = 'Import any Content Type based on file extension to Static Resources'; $_lang['import_site'] = 'Імпорт HTML'; $_lang['import_site_desc'] = 'Імпортування ресурсів з HTML-файлів'; $_lang['installer'] = 'Встановник додатків'; $_lang['installer_desc'] = 'Управління доповненнями та репозитаріями'; $_lang['lexicon_management'] = 'Словники'; $_lang['lexicon_management_desc'] = 'Редагування мовних рядків у Менеджері'; $_lang['logout'] = 'Вийти'; $_lang['logout_desc'] = 'Вийти з Менеджера'; $_lang['manage'] = 'Управління'; $_lang['media'] = 'Медіа'; $_lang['media_desc'] = 'Update Media and Media Sources'; $_lang['messages'] = 'Повідомлення'; $_lang['messages_desc'] = 'Перегляд та надсилання повідомлень'; $_lang['namespaces'] = 'Простори імен'; $_lang['namespaces_desc'] = 'Distinguish between Add-on settings'; $_lang['new_document'] = 'Новий документ'; $_lang['new_document_desc'] = 'Створити новий документ'; $_lang['new_resource'] = 'Новий ресурс'; $_lang['new_resource_desc'] = 'Створення ресурсу - зазвичай, веб-сторінки'; $_lang['new_static_resource'] = 'Новий статичний ресурс'; $_lang['new_static_resource_desc'] = 'Create a file-based Resource'; $_lang['new_symlink'] = 'Нове символічне посилання'; $_lang['new_symlink_desc'] = 'Mirror Resource content without redirecting'; $_lang['new_weblink'] = 'Нове посилання'; $_lang['new_weblink_desc'] = 'Redirect to an existing URL'; $_lang['policy_management'] = 'Політики доступу'; $_lang['policy_management_desc'] = 'Create and edit security policies'; $_lang['powered_by'] = 'is powered by'; $_lang['preview'] = 'Перегляд сайту'; $_lang['preview_desc'] = 'Перегляд сайту у новій вкладці браузера'; $_lang['profile'] = 'Профіль'; $_lang['profile_desc'] = 'Зміна адреси email, паролю тощо'; $_lang['propertysets'] = 'Набори параметрів'; $_lang['propertysets_desc'] = 'Управління наборами параметрів'; $_lang['refresh_site'] = 'Очистити кеш'; $_lang['refresh_site_desc'] = 'Видалити файли кешу для всіх контекстів'; $_lang['refreshuris'] = 'Оновити URI'; $_lang['refreshuris_desc'] = 'Regenerate system Resource URIs'; $_lang['remove_locks'] = 'Зняти блокування'; $_lang['remove_locks_desc'] = 'Зняття усіх блокувань, які виникли при редагуванні іншими користувачами'; $_lang['remove_locks_error'] = 'Сталася помилка при спробі видалення блокувань.'; $_lang['reports'] = 'Звіти'; $_lang['reports_desc'] = 'Звіти щодо Вашої установки MODX для адміністратора'; $_lang['resource_groups'] = 'Групи ресурсів'; $_lang['resource_groups_desc'] = 'Управління приналежністю ресурсів до груп ресурсів'; $_lang['search'] = 'Пошук'; $_lang['search_desc'] = 'Search for resources'; $_lang['search_resulttype_actions'] = 'Дії'; $_lang['search_resulttype_chunks'] = 'Чанки'; $_lang['search_resulttype_plugins'] = 'Плагіни'; $_lang['search_resulttype_resources'] = 'Ресурси'; $_lang['search_resulttype_snippets'] = 'Сніпети'; $_lang['search_resulttype_templates'] = 'Шаблони'; $_lang['search_resulttype_tvs'] = 'TVs'; $_lang['search_resulttype_users'] = 'Користувачі'; $_lang['security'] = 'Безпека'; $_lang['settings'] = 'Налаштування'; $_lang['site'] = 'Вміст'; $_lang['sources'] = 'Джерела медіа'; $_lang['sources_desc'] = 'Управління джерелами медіа-файлів'; $_lang['support'] = 'Підтримка'; $_lang['support_desc'] = ''; $_lang['site_schedule'] = 'Розклад сайту'; $_lang['site_schedule_desc'] = 'View Resources with upcoming publish or unpublish dates'; $_lang['system'] = 'Система'; $_lang['system_settings'] = 'System Settings'; $_lang['system_settings_desc'] = 'Налаштування усіх параметрів системи'; $_lang['tools'] = 'Tools'; $_lang['tools_desc'] = 'Utilities to keep your site sorted'; $_lang['topnav'] = 'Top Navigation'; $_lang['topnav_desc'] = ''; $_lang['user'] = 'Користувач'; $_lang['usernav'] = 'User Navigation'; $_lang['usernav_desc'] = ''; $_lang['users'] = 'Користувачі'; $_lang['user_management'] = 'Управління користувачами'; $_lang['user_management_desc'] = 'Управління користувачами та їх правами доступу'; $_lang['user_group_management'] = 'Списки управління доступом'; $_lang['user_group_management_desc'] = 'Manage user permissions through groups, roles and access policies'; $_lang['view_logging'] = 'Manager log'; $_lang['view_logging_desc'] = 'View the recent manager activity'; $_lang['view_sysinfo'] = 'Інформація про систему'; $_lang['view_sysinfo_desc'] = 'View server information, such as phpinfo, database info, and more'; $_lang['wiki'] = 'Wiki'; $_lang['wiki_desc'] = 'Launch the official MODX documentation';
{ "pile_set_name": "Github" }
/*------------------------------------------------------------------------------ Interim login dialog ------------------------------------------------------------------------------*/ #wp-auth-check-wrap.hidden { display: none; } #wp-auth-check-wrap #wp-auth-check-bg { position: fixed; top: 0; bottom: 0; left: 0; right: 0; background: #000; opacity: 0.7; filter: alpha(opacity=70); z-index: 1000010; /* needs to appear above .notification-dialog */ } #wp-auth-check-wrap #wp-auth-check { position: fixed; left: 50%; overflow: hidden; top: 40px; bottom: 20px; max-height: 415px; width: 380px; margin: 0 0 0 -190px; padding: 30px 0 0; background-color: #f1f1f1; z-index: 1000011; /* needs to appear above #wp-auth-check-bg */ -webkit-box-shadow: 0 3px 6px rgba( 0, 0, 0, 0.3 ); box-shadow: 0 3px 6px rgba( 0, 0, 0, 0.3 ); } @media screen and ( max-width: 380px ) { #wp-auth-check-wrap #wp-auth-check { left: 0; width: 100%; margin: 0; } } #wp-auth-check-wrap.fallback #wp-auth-check { max-height: 180px; overflow: auto; } #wp-auth-check-wrap #wp-auth-check-form { height: 100%; position: relative; overflow: auto; -webkit-overflow-scrolling: touch; } #wp-auth-check-form.loading:before { content: ""; display: block; width: 20px; height: 20px; position: absolute; left: 50%; top: 50%; margin: -10px 0 0 -10px; background: url(../images/spinner.gif) no-repeat center; -webkit-background-size: 20px 20px; background-size: 20px 20px; -webkit-transform: translateZ(0); transform: translateZ(0); } @media print, (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { #wp-auth-check-form.loading:before { background-image: url(../images/spinner-2x.gif); } } #wp-auth-check-wrap #wp-auth-check-form iframe { height: 98%; /* Scrollbar fix */ width: 100%; } #wp-auth-check-wrap .wp-auth-check-close { position: absolute; top: 5px; right: 5px; height: 22px; width: 22px; color: #72777c; } #wp-auth-check-wrap .wp-auth-check-close:before { content: "\f158"; font: normal 20px/22px dashicons; speak: none; -webkit-font-smoothing: antialiased !important; -moz-osx-font-smoothing: grayscale; } #wp-auth-check-wrap .wp-auth-check-close:hover, #wp-auth-check-wrap .wp-auth-check-close:focus { color: #0073aa; } #wp-auth-check-wrap .wp-auth-fallback-expired { outline: 0; } #wp-auth-check-wrap .wp-auth-fallback { font-size: 14px; line-height: 21px; padding: 0 25px; display: none; } #wp-auth-check-wrap.fallback .wp-auth-fallback, #wp-auth-check-wrap.fallback .wp-auth-check-close { display: block; }
{ "pile_set_name": "Github" }
/* Copyright (c) 2019 The Brave Authors. All rights reserved. * 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 BRAVE_COMPONENTS_L10N_COMMON_LOCALE_UTIL_H_ #define BRAVE_COMPONENTS_L10N_COMMON_LOCALE_UTIL_H_ #include <string> namespace brave_l10n { std::string GetLanguageCode( const std::string& locale); std::string GetCountryCode( const std::string& locale); } // namespace brave_l10n #endif // BRAVE_COMPONENTS_L10N_COMMON_LOCALE_UTIL_H_
{ "pile_set_name": "Github" }
/* Cancel */ "picker.navigation.cancel-button" = "Cancelar"; /* Done */ "picker.navigation.done-button" = "OK"; /* Navigation bar default title */ "picker.navigation.title" = "GMImagePicker"; /* %@ Items Selected */ "picker.selection.multiple-items" = "%@ ítems selec."; /* %@ Photos Selected */ "picker.selection.multiple-photos" = "%@ fotos selec."; /* %@ Videos Selected */ "picker.selection.multiple-videos" = "%@ vídeos selec."; /* 1 Photo Selected */ "picker.selection.single-photo" = "1 foto selec."; /* 1 Video Selected */ "picker.selection.single-video" = "1 vídeo selec."; /* All photos */ "picker.table.all-photos-label" = "Carrete"; /* Smart Albums */ "picker.table.smart-albums-header" = "COLECCIONES INTELIGENTES"; /* Albums */ "picker.table.user-albums-header" = "COLECCIONES";
{ "pile_set_name": "Github" }
{ "@type" : "g:Edge", "@value" : { "id" : { "@type" : "g:Int32", "@value" : 13 }, "label" : "develops", "inVLabel" : "software", "outVLabel" : "person", "inV" : { "@type" : "g:Int32", "@value" : 10 }, "outV" : { "@type" : "g:Int32", "@value" : 1 }, "properties" : { "since" : { "@type" : "g:Property", "@value" : { "key" : "since", "value" : { "@type" : "g:Int32", "@value" : 2009 } } } } } }
{ "pile_set_name": "Github" }
# Contributor: Bart Ribbers <bribbers@disroot.org> # Maintainer: Bart Ribbers <bribbers@disroot.org> pkgname=libksane pkgver=20.08.1 pkgrel=0 arch="all !armhf" # armhf blocked by extra-cmake-modules url="https://www.kde.org/applications/graphics/" pkgdesc="An image scanning library" license="LGPL-2.1-only OR LGPL-3.0-only" makedepends="extra-cmake-modules qt5-qtbase-dev ki18n-dev kwidgetsaddons-dev ktextwidgets-dev kwallet-dev sane-dev" source="https://download.kde.org/stable/release-service/$pkgver/src/libksane-$pkgver.tar.xz" subpackages="$pkgname-dev $pkgname-lang" build() { cmake -B build \ -DCMAKE_BUILD_TYPE=None \ -DCMAKE_INSTALL_PREFIX=/usr \ -DCMAKE_INSTALL_LIBDIR=lib cmake --build build } check() { cd build CTEST_OUTPUT_ON_FAILURE=TRUE ctest } package() { DESTDIR="$pkgdir" cmake --build build --target install } sha512sums="7ee4c83a28194f964b2b15f6d7a00d1b8f301e46a32522e9df99ded1ded8e47e11ca574f8199473060668dfd5e4208fdc80d028e0d413e25ffd98c439fb383f7 libksane-20.08.1.tar.xz"
{ "pile_set_name": "Github" }
PriceInput: type: input-object inherits: - 'PriceInputDecorator'
{ "pile_set_name": "Github" }
use super::{error::TomlHelper, parsable::Parse}; use log::error; use toml::Value; #[derive(Clone, Debug)] pub struct ChildProperty { pub name: String, pub type_name: String, pub doc_hidden: bool, } impl Parse for ChildProperty { fn parse(toml: &Value, object_name: &str) -> Option<ChildProperty> { let name = toml .lookup("name") .and_then(Value::as_str) .map(ToOwned::to_owned); let name = if let Some(name) = name { name } else { error!("No child property name for `{}`", object_name); return None; }; toml.check_unwanted( &["name", "type", "doc_hidden"], &format!("child property {}", object_name), ); let type_name = toml .lookup("type") .and_then(Value::as_str) .map(ToOwned::to_owned); let type_name = if let Some(type_name) = type_name { type_name } else { error!( "No type for child property `{}` for `{}`", name, object_name ); return None; }; let doc_hidden = toml .lookup("doc_hidden") .and_then(Value::as_bool) .unwrap_or(false); Some(ChildProperty { name, type_name, doc_hidden, }) } } #[derive(Clone, Debug)] pub struct ChildProperties { pub child_name: Option<String>, pub child_type: Option<String>, pub properties: Vec<ChildProperty>, } impl Parse for ChildProperties { fn parse(toml_object: &Value, object_name: &str) -> Option<ChildProperties> { let child_name = toml_object .lookup("child_name") .and_then(Value::as_str) .map(ToOwned::to_owned); let child_type = toml_object .lookup("child_type") .and_then(Value::as_str) .map(ToOwned::to_owned); let mut properties: Vec<ChildProperty> = Vec::new(); if let Some(configs) = toml_object.lookup("child_prop").and_then(Value::as_array) { for config in configs { if let Some(item) = ChildProperty::parse(config, object_name) { properties.push(item); } } } if !properties.is_empty() { Some(ChildProperties { child_name, child_type, properties, }) } else { if child_name.is_some() { error!("`{}` has child_name but no child_prop's", object_name); } if child_type.is_some() { error!("`{}` has child_type but no child_prop's", object_name); } None } } } #[cfg(test)] mod tests { use super::{super::parsable::Parse, *}; fn toml(input: &str) -> ::toml::Value { let value = ::toml::from_str(&input); assert!(value.is_ok()); value.unwrap() } #[test] fn child_property_parse() { let toml = toml( r#" name = "prop" type = "prop_type" "#, ); let child = ChildProperty::parse(&toml, "a").unwrap(); assert_eq!("prop", child.name); assert_eq!("prop_type", child.type_name); } #[test] fn child_property_parse_not_all() { let tml = toml( r#" name = "prop" "#, ); assert!(ChildProperty::parse(&tml, "a").is_none()); let tml = toml( r#" type_name = "prop_type" "#, ); assert!(ChildProperty::parse(&tml, "a").is_none()); } #[test] fn child_properties_parse() { let toml = toml( r#" child_name = "child_name" child_type = "child_type" [[child_prop]] name = "prop" type = "prop_type" [[child_prop]] name = "prop2" type = "prop_type2" "#, ); let props = ChildProperties::parse(&toml, "a").unwrap(); assert_eq!(Some("child_name".into()), props.child_name); assert_eq!(Some("child_type".into()), props.child_type); assert_eq!(2, props.properties.len()); assert_eq!("prop", props.properties[0].name); assert_eq!("prop_type", props.properties[0].type_name); assert_eq!("prop2", props.properties[1].name); assert_eq!("prop_type2", props.properties[1].type_name); } #[test] fn child_property_no_parse_without_children() { let toml = toml( r#" child_name = "child_name" child_type = "child_type" "#, ); let props = ChildProperties::parse(&toml, "a"); assert!(props.is_none()); } #[test] fn child_properties_parse_without_child_type_name() { let toml = toml( r#" [[child_prop]] name = "prop" type = "prop_type" "#, ); let props = ChildProperties::parse(&toml, "a").unwrap(); assert_eq!(None, props.child_name); assert_eq!(None, props.child_type); assert_eq!(1, props.properties.len()); } #[test] fn child_properties_parse_without_child_type() { let toml = toml( r#" child_name = "child_name" [[child_prop]] name = "prop" type = "prop_type" "#, ); let props = ChildProperties::parse(&toml, "a").unwrap(); assert_eq!(Some("child_name".into()), props.child_name); assert_eq!(None, props.child_type); assert_eq!(1, props.properties.len()); } #[test] fn child_properties_parse_without_child_name() { let toml = toml( r#" child_type = "child_type" [[child_prop]] name = "prop" type = "prop_type" "#, ); let props = ChildProperties::parse(&toml, "a").unwrap(); assert_eq!(None, props.child_name); assert_eq!(Some("child_type".into()), props.child_type); assert_eq!(1, props.properties.len()); } }
{ "pile_set_name": "Github" }
/* Copyright The Kubeform 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 Kubeform. DO NOT EDIT. package v1alpha1 import ( base "kubeform.dev/kubeform/apis/base/v1alpha1" core "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // +genclient // +k8s:openapi-gen=true // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +kubebuilder:object:root=true // +kubebuilder:subresource:status // +kubebuilder:printcolumn:name="Phase",type=string,JSONPath=`.status.phase` type DefaultNetworkACL struct { metav1.TypeMeta `json:",inline,omitempty"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec DefaultNetworkACLSpec `json:"spec,omitempty"` Status DefaultNetworkACLStatus `json:"status,omitempty"` } type DefaultNetworkACLSpecEgress struct { Action string `json:"action" tf:"action"` // +optional CidrBlock string `json:"cidrBlock,omitempty" tf:"cidr_block,omitempty"` FromPort int64 `json:"fromPort" tf:"from_port"` // +optional IcmpCode int64 `json:"icmpCode,omitempty" tf:"icmp_code,omitempty"` // +optional IcmpType int64 `json:"icmpType,omitempty" tf:"icmp_type,omitempty"` // +optional Ipv6CIDRBlock string `json:"ipv6CIDRBlock,omitempty" tf:"ipv6_cidr_block,omitempty"` Protocol string `json:"protocol" tf:"protocol"` RuleNo int64 `json:"ruleNo" tf:"rule_no"` ToPort int64 `json:"toPort" tf:"to_port"` } type DefaultNetworkACLSpecIngress struct { Action string `json:"action" tf:"action"` // +optional CidrBlock string `json:"cidrBlock,omitempty" tf:"cidr_block,omitempty"` FromPort int64 `json:"fromPort" tf:"from_port"` // +optional IcmpCode int64 `json:"icmpCode,omitempty" tf:"icmp_code,omitempty"` // +optional IcmpType int64 `json:"icmpType,omitempty" tf:"icmp_type,omitempty"` // +optional Ipv6CIDRBlock string `json:"ipv6CIDRBlock,omitempty" tf:"ipv6_cidr_block,omitempty"` Protocol string `json:"protocol" tf:"protocol"` RuleNo int64 `json:"ruleNo" tf:"rule_no"` ToPort int64 `json:"toPort" tf:"to_port"` } type DefaultNetworkACLSpec struct { ProviderRef core.LocalObjectReference `json:"providerRef" tf:"-"` ID string `json:"id,omitempty" tf:"id,omitempty"` DefaultNetworkACLID string `json:"defaultNetworkACLID" tf:"default_network_acl_id"` // +optional Egress []DefaultNetworkACLSpecEgress `json:"egress,omitempty" tf:"egress,omitempty"` // +optional Ingress []DefaultNetworkACLSpecIngress `json:"ingress,omitempty" tf:"ingress,omitempty"` // +optional OwnerID string `json:"ownerID,omitempty" tf:"owner_id,omitempty"` // +optional SubnetIDS []string `json:"subnetIDS,omitempty" tf:"subnet_ids,omitempty"` // +optional Tags map[string]string `json:"tags,omitempty" tf:"tags,omitempty"` // +optional VpcID string `json:"vpcID,omitempty" tf:"vpc_id,omitempty"` } type DefaultNetworkACLStatus struct { // Resource generation, which is updated on mutation by the API Server. // +optional ObservedGeneration int64 `json:"observedGeneration,omitempty"` // +optional Output *DefaultNetworkACLSpec `json:"output,omitempty"` // +optional State *base.State `json:"state,omitempty"` // +optional Phase base.Phase `json:"phase,omitempty"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +kubebuilder:object:root=true // DefaultNetworkACLList is a list of DefaultNetworkACLs type DefaultNetworkACLList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` // Items is a list of DefaultNetworkACL CRD objects Items []DefaultNetworkACL `json:"items,omitempty"` }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 5f3e9480f969348ed98b8577aac34056 timeCreated: 1492759317 licenseType: Pro MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
{ "name": "UP! Plus 2", "description": "A 3D printer.", "url": "https://www.amazon.com/Assembled-Printer-Maximum-Dimensions-Resolution/dp/B00TOOHY0M" }
{ "pile_set_name": "Github" }
// Boost.Bimap // // Copyright (c) 2006-2007 Matias Capeletto // // Distributed under 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) /// \file container_adaptor/vector_adaptor.hpp /// \brief Container adaptor to easily build a std::vector signature compatible container. #ifndef BOOST_BIMAP_CONTAINER_ADAPTOR_VECTOR_ADAPTOR_HPP #define BOOST_BIMAP_CONTAINER_ADAPTOR_VECTOR_ADAPTOR_HPP #if defined(_MSC_VER) && (_MSC_VER>=1200) #pragma once #endif #include <boost/config.hpp> #include <boost/bimap/container_adaptor/sequence_container_adaptor.hpp> #include <boost/mpl/aux_/na.hpp> #include <boost/mpl/vector.hpp> namespace boost { namespace bimaps { namespace container_adaptor { /// \brief Container adaptor to easily build a std::vector signature compatible container. template < class Base, class Iterator, class ConstIterator, class ReverseIterator, class ConstReverseIterator, class IteratorToBaseConverter = ::boost::mpl::na, class IteratorFromBaseConverter = ::boost::mpl::na, class ReverseIteratorFromBaseConverter = ::boost::mpl::na, class ValueToBaseConverter = ::boost::mpl::na, class ValueFromBaseConverter = ::boost::mpl::na, class FunctorsFromDerivedClasses = mpl::vector<> > class vector_adaptor : public ::boost::bimaps::container_adaptor::sequence_container_adaptor < Base, Iterator, ConstIterator, ReverseIterator, ConstReverseIterator, IteratorToBaseConverter, IteratorFromBaseConverter, ReverseIteratorFromBaseConverter, ValueToBaseConverter, ValueFromBaseConverter, FunctorsFromDerivedClasses > { typedef ::boost::bimaps::container_adaptor::sequence_container_adaptor < Base, Iterator, ConstIterator, ReverseIterator, ConstReverseIterator, IteratorToBaseConverter, IteratorFromBaseConverter, ReverseIteratorFromBaseConverter, ValueToBaseConverter, ValueFromBaseConverter, FunctorsFromDerivedClasses > base_; // Access ----------------------------------------------------------------- public: vector_adaptor() {} explicit vector_adaptor(Base & c) : base_(c) {} protected: typedef vector_adaptor vector_adaptor_; // Interface -------------------------------------------------------------- public: BOOST_DEDUCED_TYPENAME base_::size_type capacity() const { return this->base().capacity(); } void reserve(BOOST_DEDUCED_TYPENAME base_::size_type m) { this->base().resize(m); } void resize(BOOST_DEDUCED_TYPENAME base_::size_type n, BOOST_DEDUCED_TYPENAME ::boost::call_traits< BOOST_DEDUCED_TYPENAME base_::value_type >::param_type x = BOOST_DEDUCED_TYPENAME base_::value_type()) { this->base().resize(n, this->template functor<BOOST_DEDUCED_TYPENAME base_::value_to_base>()(x) ); } BOOST_DEDUCED_TYPENAME base_::const_reference operator[](BOOST_DEDUCED_TYPENAME base_::size_type n) const { return this->base().operator[](n); } BOOST_DEDUCED_TYPENAME base_::const_reference at(BOOST_DEDUCED_TYPENAME base_::size_type n) const { return this->base().at(n); } BOOST_DEDUCED_TYPENAME base_::reference operator[](BOOST_DEDUCED_TYPENAME base_::size_type n) { return this->base().operator[](n); } BOOST_DEDUCED_TYPENAME base_::reference at(BOOST_DEDUCED_TYPENAME base_::size_type n) { return this->base().at(n); } }; } // namespace container_adaptor } // namespace bimaps } // namespace boost #endif // BOOST_BIMAP_CONTAINER_ADAPTOR_VECTOR_ADAPTOR_HPP
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <ContactsUI/CNPropertyGroupItem.h> __attribute__((visibility("hidden"))) @interface CNPropertyGroupDateItem : CNPropertyGroupItem { } + (id)emptyValueForLabel:(id)arg1; + (void)initialize; - (id)displayStringForValue:(id)arg1; - (id)bestValue:(id)arg1; - (_Bool)isEquivalentToItem:(id)arg1; - (id)defaultActionURL; - (id)normalizedValue; - (_Bool)isValidValue:(id)arg1; @end
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!--Generated by crowdin.com--> <resources> <string name="available">זמין</string> <string name="away">נעדר</string> <string name="chat">מוכן לשיחה!</string> <string name="dnd">נא לא להפריע</string> <string name="edit_status">ערוך מצב</string> <string name="empty_status">&lt; מצב ריק &gt;</string> <string name="invisible">בלתי נראה</string> <string name="remove_status">מחק מצב</string> <string name="status_editor">קבע מצב</string> <string name="status_text_hint">הזן הודעת מצב</string> <string name="unavailable">לא מחובר</string> <string name="unsubscribed">לא מורשה</string> <string name="xa">נעדר למשך זמן ארוך</string> <string name="new_status">מצב חדש</string> <string name="saved_statuses">הודעות מצב שנשמרו</string> <string name="clear_status_history">נקה היסטוריית הודעות מצב</string> <string name="status_message">הודעת מצב</string> </resources>
{ "pile_set_name": "Github" }
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ package java.util.concurrent; import java.security.AccessControlContext; import java.security.AccessControlException; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import sun.security.util.SecurityConstants; import static java.lang.ref.Reference.reachabilityFence; /** * Factory and utility methods for {@link Executor}, {@link * ExecutorService}, {@link ScheduledExecutorService}, {@link * ThreadFactory}, and {@link Callable} classes defined in this * package. This class supports the following kinds of methods: * * <ul> * <li>Methods that create and return an {@link ExecutorService} * set up with commonly useful configuration settings. * <li>Methods that create and return a {@link ScheduledExecutorService} * set up with commonly useful configuration settings. * <li>Methods that create and return a "wrapped" ExecutorService, that * disables reconfiguration by making implementation-specific methods * inaccessible. * <li>Methods that create and return a {@link ThreadFactory} * that sets newly created threads to a known state. * <li>Methods that create and return a {@link Callable} * out of other closure-like forms, so they can be used * in execution methods requiring {@code Callable}. * </ul> * * @author Doug Lea * @since 1.5 */ // 【任务执行框架】的工厂,该类负责生成:【任务执行框架】对象、Callable类型的任务对象、线程工厂对象 public class Executors { /** Cannot instantiate. */ private Executors() { } /*▼ 【工作池】 ████████████████████████████████████████████████████████████████████████████████┓ */ /** * Creates a work-stealing thread pool using the number of * {@linkplain Runtime#availableProcessors available processors} * as its target parallelism level. * * @return the newly created thread pool * * @see #newWorkStealingPool(int) * @since 1.8 */ // 并行度与处理器数量相同的【工作池】 public static ExecutorService newWorkStealingPool() { return new ForkJoinPool(Runtime.getRuntime().availableProcessors(), ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true); } /** * Creates a thread pool that maintains enough threads to support * the given parallelism level, and may use multiple queues to * reduce contention. The parallelism level corresponds to the * maximum number of threads actively engaged in, or available to * engage in, task processing. The actual number of threads may * grow and shrink dynamically. A work-stealing pool makes no * guarantees about the order in which submitted tasks are * executed. * * @param parallelism the targeted parallelism level * * @return the newly created thread pool * * @throws IllegalArgumentException if {@code parallelism <= 0} * @since 1.8 */ // 并行度为parallelism的【工作池】 public static ExecutorService newWorkStealingPool(int parallelism) { return new ForkJoinPool(parallelism, ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true); } /*▲ 【工作池】 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ 【任务执行框架代理】 ████████████████████████████████████████████████████████████████████████████████┓ */ /** * Returns an object that delegates all defined {@link * ExecutorService} methods to the given executor, but not any * other methods that might otherwise be accessible using * casts. This provides a way to safely "freeze" configuration and * disallow tuning of a given concrete implementation. * * @param executor the underlying implementation * * @return an {@code ExecutorService} instance * * @throws NullPointerException if executor null */ // 不可配置 public static ExecutorService unconfigurableExecutorService(ExecutorService executor) { if(executor == null) { throw new NullPointerException(); } return new DelegatedExecutorService(executor); } /*▲ 【任务执行框架代理】 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ 【线程池】 ████████████████████████████████████████████████████████████████████████████████┓ */ /** * Creates a thread pool that creates new threads as needed, but * will reuse previously constructed threads when they are * available. These pools will typically improve the performance * of programs that execute many short-lived asynchronous tasks. * Calls to {@code execute} will reuse previously constructed * threads if available. If no existing thread is available, a new * thread will be created and added to the pool. Threads that have * not been used for sixty seconds are terminated and removed from * the cache. Thus, a pool that remains idle for long enough will * not consume any resources. Note that pools with similar * properties but different details (for example, timeout parameters) * may be created using {@link ThreadPoolExecutor} constructors. * * @return the newly created thread pool */ /* *【缓冲线程池】 * * 提交新任务之后,会创建一个新线程执行它,该新线程在空闲期的存活时长为60秒。 * 换句话说,每个线程在空闲60秒之后就被销毁了,所以适合做缓冲(不是缓存)。 * * 配置: * - 阻塞队列 : SynchronousQueue * -【核心阙值】: 0 * -【最大阙值】: 无限 */ public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); } /** * Creates a thread pool that creates new threads as needed, but * will reuse previously constructed threads when they are * available, and uses the provided * ThreadFactory to create new threads when needed. * * @param threadFactory the factory to use when creating new threads * * @return the newly created thread pool * * @throws NullPointerException if threadFactory is null */ /* *【缓冲线程池】,允许自行指定线程工厂 * * 提交新任务之后,会创建一个新线程执行它,该新线程在空闲期的存活时长为60秒。 * 换句话说,每个线程在空闲60秒之后就被销毁了,所以适合做缓冲(不是缓存)。 * * 配置: * - 阻塞队列 : SynchronousQueue * -【核心阙值】: 0 * -【最大阙值】: 无限 */ public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory); } /** * Creates a thread pool that reuses a fixed number of threads * operating off a shared unbounded queue. At any point, at most * {@code nThreads} threads will be active processing tasks. * If additional tasks are submitted when all threads are active, * they will wait in the queue until a thread is available. * If any thread terminates due to a failure during execution * prior to shutdown, a new one will take its place if needed to * execute subsequent tasks. The threads in the pool will exist * until it is explicitly {@link ExecutorService#shutdown shutdown}. * * @param nThreads the number of threads in the pool * * @return the newly created thread pool * * @throws IllegalArgumentException if {@code nThreads <= 0} */ /* *【固定容量线程池】 * * 线程池中常驻线程数量为nThreads * * 配置: * - 阻塞队列 : LinkedBlockingQueue * -【核心阙值】: nThreads * -【最大阙值】: nThreads */ public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } /** * Creates a thread pool that reuses a fixed number of threads * operating off a shared unbounded queue, using the provided * ThreadFactory to create new threads when needed. At any point, * at most {@code nThreads} threads will be active processing * tasks. If additional tasks are submitted when all threads are * active, they will wait in the queue until a thread is * available. If any thread terminates due to a failure during * execution prior to shutdown, a new one will take its place if * needed to execute subsequent tasks. The threads in the pool will * exist until it is explicitly {@link ExecutorService#shutdown * shutdown}. * * @param nThreads the number of threads in the pool * @param threadFactory the factory to use when creating new threads * * @return the newly created thread pool * * @throws NullPointerException if threadFactory is null * @throws IllegalArgumentException if {@code nThreads <= 0} */ /* *【固定容量线程池】,允许自行指定线程工厂 * * 线程池中常驻线程数量为nThreads * * 配置: * - 阻塞队列 : LinkedBlockingQueue * -【核心阙值】: nThreads * -【最大阙值】: nThreads */ public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); } /** * Creates a thread pool that can schedule commands to run after a * given delay, or to execute periodically. * * @param corePoolSize the number of threads to keep in the pool, * even if they are idle * * @return the newly created scheduled thread pool * * @throws IllegalArgumentException if {@code corePoolSize < 0} */ /* *【定时任务线程池】 * * 用于执行一次性或周期性的定时任务 * * 配置: * - 阻塞队列 : DelayedWorkQueue * -【核心阙值】: corePoolSize * -【最大阙值】: 无限 */ public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); } /** * Creates a thread pool that can schedule commands to run after a * given delay, or to execute periodically. * * @param corePoolSize the number of threads to keep in the pool, * even if they are idle * @param threadFactory the factory to use when the executor * creates a new thread * * @return the newly created scheduled thread pool * * @throws IllegalArgumentException if {@code corePoolSize < 0} * @throws NullPointerException if threadFactory is null */ /* *【定时任务线程池】,允许自行指定线程工厂 * * 用于执行一次性或周期性的定时任务 * * 配置: * - 阻塞队列 : DelayedWorkQueue * -【核心阙值】: corePoolSize * -【最大阙值】: 无限 */ public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) { return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory); } /** * Creates a single-threaded executor that can schedule commands * to run after a given delay, or to execute periodically. * (Note however that if this single * thread terminates due to a failure during execution prior to * shutdown, a new one will take its place if needed to execute * subsequent tasks.) Tasks are guaranteed to execute * sequentially, and no more than one task will be active at any * given time. Unlike the otherwise equivalent * {@code newScheduledThreadPool(1)} the returned executor is * guaranteed not to be reconfigurable to use additional threads. * * @return the newly created scheduled executor */ /* *【定时任务线程池代理】 * * 用于执行一次性或周期性的定时任务,线程池中只有一个常驻线程。 * * 配置: * - 阻塞队列 : DelayedWorkQueue * -【核心阙值】: 1 * -【最大阙值】: 无限 */ public static ScheduledExecutorService newSingleThreadScheduledExecutor() { return new DelegatedScheduledExecutorService(new ScheduledThreadPoolExecutor(1)); } /** * Creates a single-threaded executor that can schedule commands * to run after a given delay, or to execute periodically. (Note * however that if this single thread terminates due to a failure * during execution prior to shutdown, a new one will take its * place if needed to execute subsequent tasks.) Tasks are * guaranteed to execute sequentially, and no more than one task * will be active at any given time. Unlike the otherwise * equivalent {@code newScheduledThreadPool(1, threadFactory)} * the returned executor is guaranteed not to be reconfigurable to * use additional threads. * * @param threadFactory the factory to use when creating new threads * * @return the newly created scheduled executor * * @throws NullPointerException if threadFactory is null */ /* *【定时任务线程池代理】,允许自行指定线程工厂 * * 用于执行一次性或周期性的定时任务,线程池中只有一个常驻线程。 * * 配置: * - 阻塞队列 : DelayedWorkQueue * -【核心阙值】: 1 * -【最大阙值】: 无限 */ public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) { return new DelegatedScheduledExecutorService(new ScheduledThreadPoolExecutor(1, threadFactory)); } /** * Returns an object that delegates all defined {@link * ScheduledExecutorService} methods to the given executor, but * not any other methods that might otherwise be accessible using * casts. This provides a way to safely "freeze" configuration and * disallow tuning of a given concrete implementation. * * @param executor the underlying implementation * * @return a {@code ScheduledExecutorService} instance * * @throws NullPointerException if executor null */ /* *【定时任务线程池代理】 * * 不可自定义配置,只是对指定的【定时任务执行框架】的简单代理 */ public static ScheduledExecutorService unconfigurableScheduledExecutorService(ScheduledExecutorService executor) { if(executor == null) { throw new NullPointerException(); } return new DelegatedScheduledExecutorService(executor); } /** * Creates an Executor that uses a single worker thread operating * off an unbounded queue. (Note however that if this single * thread terminates due to a failure during execution prior to * shutdown, a new one will take its place if needed to execute * subsequent tasks.) Tasks are guaranteed to execute * sequentially, and no more than one task will be active at any * given time. Unlike the otherwise equivalent * {@code newFixedThreadPool(1)} the returned executor is * guaranteed not to be reconfigurable to use additional threads. * * @return the newly created single-threaded Executor */ /* *【Finalizable线程池】 * * 顺序执行普通任务,线程池中最多只有一个线程。 * * 配置: * - 阻塞队列 : LinkedBlockingQueue * -【核心阙值】: 1 * -【最大阙值】: 1 */ public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); } /** * Creates an Executor that uses a single worker thread operating * off an unbounded queue, and uses the provided ThreadFactory to * create a new thread when needed. Unlike the otherwise * equivalent {@code newFixedThreadPool(1, threadFactory)} the * returned executor is guaranteed not to be reconfigurable to use * additional threads. * * @param threadFactory the factory to use when creating new threads * * @return the newly created single-threaded Executor * * @throws NullPointerException if threadFactory is null */ /* *【Finalizable线程池】,允许自行指定线程工厂 * * 顺序执行普通任务,线程池中最多只有一个线程。 * * 配置: * - 阻塞队列 : LinkedBlockingQueue * -【核心阙值】: 1 * -【最大阙值】: 1 */ public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) { return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory)); } /*▲ 【线程池】 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ 任务对象 ████████████████████████████████████████████████████████████████████████████████┓ */ /** * Returns a {@link Callable} object that, when * called, runs the given task and returns {@code null}. * * @param task the task to run * * @return a callable object * * @throws NullPointerException if task null */ // 包装Runnable任务,无返回值 public static Callable<Object> callable(Runnable task) { if(task == null) { throw new NullPointerException(); } return new RunnableAdapter<Object>(task, null); } /** * Returns a {@link Callable} object that, when * called, runs the given task and returns the given result. This * can be useful when applying methods requiring a * {@code Callable} to an otherwise resultless action. * * @param task the task to run * @param result the result to return * @param <T> the type of the result * * @return a callable object * * @throws NullPointerException if task null */ // 包装Runnable任务,有返回值 public static <T> Callable<T> callable(Runnable task, T result) { if(task == null) { throw new NullPointerException(); } return new RunnableAdapter<T>(task, result); } /** * Returns a {@link Callable} object that will, when called, * execute the given {@code callable} under the current access * control context. This method should normally be invoked within * an {@link AccessController#doPrivileged AccessController.doPrivileged} * action to create callables that will, if possible, execute * under the selected permission settings holding within that * action; or if not possible, throw an associated {@link * AccessControlException}. * * @param callable the underlying task * @param <T> the type of the callable's result * * @return a callable object * * @throws NullPointerException if callable null */ // 包装Callable任务,使用上下文访问权限控制器 public static <T> Callable<T> privilegedCallable(Callable<T> callable) { if(callable == null) { throw new NullPointerException(); } return new PrivilegedCallable<T>(callable); } /** * Returns a {@link Callable} object that will, when called, * execute the given {@code callable} under the current access * control context, with the current context class loader as the * context class loader. This method should normally be invoked * within an * {@link AccessController#doPrivileged AccessController.doPrivileged} * action to create callables that will, if possible, execute * under the selected permission settings holding within that * action; or if not possible, throw an associated {@link * AccessControlException}. * * @param callable the underlying task * @param <T> the type of the callable's result * * @return a callable object * * @throws NullPointerException if callable null * @throws AccessControlException if the current access control * context does not have permission to both set and get context * class loader */ // 包装Callable任务,使用上下文访问权限控制器和当前线程的类加载器 public static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) { if(callable == null) { throw new NullPointerException(); } return new PrivilegedCallableUsingCurrentClassLoader<T>(callable); } /** * Returns a {@link Callable} object that, when * called, runs the given privileged action and returns its result. * * @param action the privileged action to run * * @return a callable object * * @throws NullPointerException if action null */ // 包装PrivilegedAction任务 public static Callable<Object> callable(final PrivilegedAction<?> action) { if(action == null) { throw new NullPointerException(); } return new Callable<Object>() { public Object call() { return action.run(); } }; } /** * Returns a {@link Callable} object that, when * called, runs the given privileged exception action and returns * its result. * * @param action the privileged exception action to run * * @return a callable object * * @throws NullPointerException if action null */ // 包装PrivilegedExceptionAction任务 public static Callable<Object> callable(final PrivilegedExceptionAction<?> action) { if(action == null) { throw new NullPointerException(); } return new Callable<Object>() { public Object call() throws Exception { return action.run(); } }; } /*▲ 任务对象 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ 线程工厂 ████████████████████████████████████████████████████████████████████████████████┓ */ /** * Returns a default thread factory used to create new threads. * This factory creates all new threads used by an Executor in the * same {@link ThreadGroup}. If there is a {@link * java.lang.SecurityManager}, it uses the group of {@link * System#getSecurityManager}, else the group of the thread * invoking this {@code defaultThreadFactory} method. Each new * thread is created as a non-daemon thread with priority set to * the smaller of {@code Thread.NORM_PRIORITY} and the maximum * priority permitted in the thread group. New threads have names * accessible via {@link Thread#getName} of * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence * number of this factory, and <em>M</em> is the sequence number * of the thread created by this factory. * * @return a thread factory */ // 默认线程工厂,创建默认线程优先级的非守护线程 public static ThreadFactory defaultThreadFactory() { return new DefaultThreadFactory(); } /** * Returns a thread factory used to create new threads that * have the same permissions as the current thread. * This factory creates threads with the same settings as {@link * Executors#defaultThreadFactory}, additionally setting the * AccessControlContext and contextClassLoader of new threads to * be the same as the thread invoking this * {@code privilegedThreadFactory} method. A new * {@code privilegedThreadFactory} can be created within an * {@link AccessController#doPrivileged AccessController.doPrivileged} * action setting the current thread's access control context to * create threads with the selected permission settings holding * within that action. * * <p>Note that while tasks running within such threads will have * the same access control and class loader settings as the * current thread, they need not have the same {@link * java.lang.ThreadLocal} or {@link * java.lang.InheritableThreadLocal} values. If necessary, * particular values of thread locals can be set or reset before * any task runs in {@link ThreadPoolExecutor} subclasses using * {@link ThreadPoolExecutor#beforeExecute(Thread, Runnable)}. * Also, if it is necessary to initialize worker threads to have * the same InheritableThreadLocal settings as some other * designated thread, you can create a custom ThreadFactory in * which that thread waits for and services requests to create * others that will inherit its values. * * @return a thread factory * * @throws AccessControlException if the current access control * context does not have permission to both get and set context * class loader */ // 特权线程工厂 public static ThreadFactory privilegedThreadFactory() { return new PrivilegedThreadFactory(); } /*▲ 线程工厂 ████████████████████████████████████████████████████████████████████████████████┛ */ /* * 以下定义了各种类型的: * * - 任务执行框架 * - 任务 * - 线程工厂 */ /** * A wrapper class that exposes only the ExecutorService methods of an ExecutorService implementation. */ // 【任务执行框架代理】,限制只能执行ExecutorService接口内的方法 private static class DelegatedExecutorService implements ExecutorService { private final ExecutorService e; DelegatedExecutorService(ExecutorService executor) { e = executor; } public void execute(Runnable command) { try { e.execute(command); } finally { reachabilityFence(this); } } public void shutdown() { e.shutdown(); } public List<Runnable> shutdownNow() { try { return e.shutdownNow(); } finally { reachabilityFence(this); } } public boolean isShutdown() { try { return e.isShutdown(); } finally { reachabilityFence(this); } } public boolean isTerminated() { try { return e.isTerminated(); } finally { reachabilityFence(this); } } public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { try { return e.awaitTermination(timeout, unit); } finally { reachabilityFence(this); } } public Future<?> submit(Runnable task) { try { return e.submit(task); } finally { reachabilityFence(this); } } public <T> Future<T> submit(Callable<T> task) { try { return e.submit(task); } finally { reachabilityFence(this); } } public <T> Future<T> submit(Runnable task, T result) { try { return e.submit(task, result); } finally { reachabilityFence(this); } } public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { try { return e.invokeAll(tasks); } finally { reachabilityFence(this); } } public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { try { return e.invokeAll(tasks, timeout, unit); } finally { reachabilityFence(this); } } public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { try { return e.invokeAny(tasks); } finally { reachabilityFence(this); } } public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { try { return e.invokeAny(tasks, timeout, unit); } finally { reachabilityFence(this); } } } /** * A wrapper class that exposes only the ScheduledExecutorService * methods of a ScheduledExecutorService implementation. */ // 【定时任务执行框架代理】,限制只能执行ExecutorService接口与ScheduledExecutorService接口内的方法 private static class DelegatedScheduledExecutorService extends DelegatedExecutorService implements ScheduledExecutorService { private final ScheduledExecutorService e; DelegatedScheduledExecutorService(ScheduledExecutorService executor) { super(executor); e = executor; } public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return e.schedule(command, delay, unit); } public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) { return e.schedule(callable, delay, unit); } public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { return e.scheduleAtFixedRate(command, initialDelay, period, unit); } public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { return e.scheduleWithFixedDelay(command, initialDelay, delay, unit); } } // 【Finalizable任务执行框架代理】 private static class FinalizableDelegatedExecutorService extends DelegatedExecutorService { FinalizableDelegatedExecutorService(ExecutorService executor) { super(executor); } @SuppressWarnings("deprecation") protected void finalize() { super.shutdown(); } } /** * A callable that runs given task and returns given result. */ // 包装Runnable任务 private static final class RunnableAdapter<T> implements Callable<T> { private final Runnable task; private final T result; RunnableAdapter(Runnable task, T result) { this.task = task; this.result = result; } public T call() { task.run(); return result; } public String toString() { return super.toString() + "[Wrapped task = " + task + "]"; } } /** * A callable that runs under established access control settings. */ // 包装Callable任务,使用上下文访问权限控制器 private static final class PrivilegedCallable<T> implements Callable<T> { final Callable<T> task; final AccessControlContext acc; PrivilegedCallable(Callable<T> task) { this.task = task; this.acc = AccessController.getContext(); } public T call() throws Exception { try { return AccessController.doPrivileged(new PrivilegedExceptionAction<T>() { public T run() throws Exception { return task.call(); } }, acc); } catch(PrivilegedActionException e) { throw e.getException(); } } public String toString() { return super.toString() + "[Wrapped task = " + task + "]"; } } /** * A callable that runs under established access control settings and * current ClassLoader. */ // 包装Callable任务,使用上下文访问权限控制器和当前线程的类加载器 private static final class PrivilegedCallableUsingCurrentClassLoader<T> implements Callable<T> { final Callable<T> task; final AccessControlContext acc; final ClassLoader ccl; PrivilegedCallableUsingCurrentClassLoader(Callable<T> task) { SecurityManager sm = System.getSecurityManager(); if(sm != null) { // Calls to getContextClassLoader from this class // never trigger a security check, but we check // whether our callers have this permission anyways. sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); // Whether setContextClassLoader turns out to be necessary // or not, we fail fast if permission is not available. sm.checkPermission(new RuntimePermission("setContextClassLoader")); } this.task = task; this.acc = AccessController.getContext(); this.ccl = Thread.currentThread().getContextClassLoader(); } public T call() throws Exception { try { return AccessController.doPrivileged(new PrivilegedExceptionAction<T>() { public T run() throws Exception { Thread t = Thread.currentThread(); ClassLoader cl = t.getContextClassLoader(); if(ccl == cl) { return task.call(); } else { t.setContextClassLoader(ccl); try { return task.call(); } finally { t.setContextClassLoader(cl); } } } }, acc); } catch(PrivilegedActionException e) { throw e.getException(); } } public String toString() { return super.toString() + "[Wrapped task = " + task + "]"; } } /** * The default thread factory. */ // 默认线程工厂,创建默认线程优先级的非守护线程 private static class DefaultThreadFactory implements ThreadFactory { private static final AtomicInteger poolNumber = new AtomicInteger(1); private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; private final ThreadGroup group; DefaultThreadFactory() { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-"; } public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if(t.isDaemon()) { t.setDaemon(false); } if(t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; } } /** * Thread factory capturing access control context and class loader. */ // 特权线程工厂 private static class PrivilegedThreadFactory extends DefaultThreadFactory { final AccessControlContext acc; final ClassLoader ccl; PrivilegedThreadFactory() { super(); SecurityManager sm = System.getSecurityManager(); if(sm != null) { /* * Calls to getContextClassLoader from this class never trigger a security check, * but we check whether our callers have this permission anyways. */ sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); // Fail fast sm.checkPermission(new RuntimePermission("setContextClassLoader")); } this.acc = AccessController.getContext(); this.ccl = Thread.currentThread().getContextClassLoader(); } public Thread newThread(final Runnable r) { return super.newThread(new Runnable() { public void run() { AccessController.doPrivileged(new PrivilegedAction<>() { public Void run() { Thread.currentThread().setContextClassLoader(ccl); r.run(); return null; } }, acc); } }); } } }
{ "pile_set_name": "Github" }
/****************************************************************** MIT License http://www.opensource.org/licenses/mit-license.php Author Mora <qiuzhongleiabc@126.com> (https://github.com/qiu8310) *******************************************************************/ import {execSync} from 'child_process' import * as fs from 'fs-extra' import * as path from 'path' import * as JSON5 from 'json5' import * as clog from 'mora-scripts/libs/sys/clog' import {JSON_REGEXP} from '@minapp/common/dist/dev/config' export {JSON_REGEXP} export function code(str: string) { return clog.format('%c' + str, 'yellow') } export function walkDirectory(dir: string, cb: (dir: string, name: string, file: string, stat: fs.Stats) => boolean | void | undefined) { fs.readdirSync(dir).forEach(name => { let file = path.join(dir, name) let stat = fs.statSync(file) if (false !== cb(dir, name, file, stat)) { if (stat.isDirectory()) { walkDirectory(file, cb) } } }) } export function getGitUser() { let name = tryExecCmdSync('git config --get user.name', '').trim() let email = tryExecCmdSync('git config --get user.email', '').trim() if (email) email = `<${email}>` return `${name}${email}` } function tryExecCmdSync(cmd: string, fallback: string): string function tryExecCmdSync(cmd: string, fallback?: string): undefined | string { try { return execSync(cmd).toString() } catch (e) { return fallback } } /** * 从指定的目录中获取指定名称的 json 文件的路径 */ export function getJsonFilePath(fromDirectory: string, baseName: string) { let file = fs.readdirSync(fromDirectory).find(n => n.startsWith(baseName) && JSON_REGEXP.test(n) && n.replace(JSON_REGEXP, '') === baseName) return file ? path.join(fromDirectory, file) : undefined } /** * 获取文件不带路径和后缀的名称 */ export function getFileBaseName(file: string) { return path.basename(file, path.extname(file)) } export function getFilePath(fromDirectory: string, baseName: string, extensions: string[]) { let exts = extensions.map(e => e.toLowerCase()) let file = fs.readdirSync(fromDirectory).find(n => n.startsWith(baseName) && exts.includes(n.substr(baseName.length + 1).toLowerCase())) return file ? path.join(fromDirectory, file) : undefined } export function getComponentJson(refFile: string) { let dir = path.dirname(refFile) let name = path.basename(refFile.replace(/\.\w+$/, '')) let foundjson = fs.readdirSync(dir).find(n => n.replace(JSON_REGEXP, '__') === name + '__') let foundjs = fs.readdirSync(dir).find(n => n === name + '.js' || n === name + '.ts') if (foundjson && foundjs) { let jsonFile = path.join(dir, foundjson) let jsFile = path.join(dir, foundjs) let content = fs.readFileSync(path.join(dir, foundjson)).toString() return { jsonFile, jsFile, jsContent: fs.readFileSync(jsFile).toString(), json: JSON5.parse(content) } } return {} }
{ "pile_set_name": "Github" }
#! /bin/sh [ -f /usr/bin/input-event ] || exit 0 start() { printf "Starting input-event: " input-event echo "done" } stop() { printf "Stopping input-event: " killall input-event echo "done" } restart() { stop start } # See how we were called. case "$1" in start) start ;; stop) stop ;; restart|reload) restart ;; *) echo "Usage: $0 {start|stop|reload|restart}" exit 1 esac exit $?
{ "pile_set_name": "Github" }
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import <WebCore/DOMBlob.h> @class NSString; @interface DOMFile : DOMBlob { } - (double)lastModifiedDate; @property(readonly) NSString *name; @end
{ "pile_set_name": "Github" }
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables __all__ = ['TargetGroupAttachment'] class TargetGroupAttachment(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, availability_zone: Optional[pulumi.Input[str]] = None, port: Optional[pulumi.Input[int]] = None, target_group_arn: Optional[pulumi.Input[str]] = None, target_id: Optional[pulumi.Input[str]] = None, __props__=None, __name__=None, __opts__=None): """ Provides the ability to register instances and containers with an Application Load Balancer (ALB) or Network Load Balancer (NLB) target group. For attaching resources with Elastic Load Balancer (ELB), see the `elb.Attachment` resource. > **Note:** `alb.TargetGroupAttachment` is known as `lb.TargetGroupAttachment`. The functionality is identical. ## Example Usage ```python import pulumi import pulumi_aws as aws test_target_group = aws.lb.TargetGroup("testTargetGroup") # ... other configuration ... test_instance = aws.ec2.Instance("testInstance") # ... other configuration ... test_target_group_attachment = aws.lb.TargetGroupAttachment("testTargetGroupAttachment", target_group_arn=test_target_group.arn, target_id=test_instance.id, port=80) ``` ## Usage with lambda ```python import pulumi import pulumi_aws as aws test_target_group = aws.lb.TargetGroup("testTargetGroup", target_type="lambda") test_function = aws.lambda_.Function("testFunction") # ... other configuration ... with_lb = aws.lambda_.Permission("withLb", action="lambda:InvokeFunction", function=test_function.arn, principal="elasticloadbalancing.amazonaws.com", source_arn=test_target_group.arn) test_target_group_attachment = aws.lb.TargetGroupAttachment("testTargetGroupAttachment", target_group_arn=test_target_group.arn, target_id=test_function.arn, opts=ResourceOptions(depends_on=[with_lb])) ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] availability_zone: The Availability Zone where the IP address of the target is to be registered. If the private ip address is outside of the VPC scope, this value must be set to 'all'. :param pulumi.Input[int] port: The port on which targets receive traffic. :param pulumi.Input[str] target_group_arn: The ARN of the target group with which to register targets :param pulumi.Input[str] target_id: The ID of the target. This is the Instance ID for an instance, or the container ID for an ECS container. If the target type is ip, specify an IP address. If the target type is lambda, specify the arn of lambda. """ if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['availability_zone'] = availability_zone __props__['port'] = port if target_group_arn is None: raise TypeError("Missing required property 'target_group_arn'") __props__['target_group_arn'] = target_group_arn if target_id is None: raise TypeError("Missing required property 'target_id'") __props__['target_id'] = target_id alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="aws:elasticloadbalancingv2/targetGroupAttachment:TargetGroupAttachment")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(TargetGroupAttachment, __self__).__init__( 'aws:lb/targetGroupAttachment:TargetGroupAttachment', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, availability_zone: Optional[pulumi.Input[str]] = None, port: Optional[pulumi.Input[int]] = None, target_group_arn: Optional[pulumi.Input[str]] = None, target_id: Optional[pulumi.Input[str]] = None) -> 'TargetGroupAttachment': """ Get an existing TargetGroupAttachment resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] availability_zone: The Availability Zone where the IP address of the target is to be registered. If the private ip address is outside of the VPC scope, this value must be set to 'all'. :param pulumi.Input[int] port: The port on which targets receive traffic. :param pulumi.Input[str] target_group_arn: The ARN of the target group with which to register targets :param pulumi.Input[str] target_id: The ID of the target. This is the Instance ID for an instance, or the container ID for an ECS container. If the target type is ip, specify an IP address. If the target type is lambda, specify the arn of lambda. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() __props__["availability_zone"] = availability_zone __props__["port"] = port __props__["target_group_arn"] = target_group_arn __props__["target_id"] = target_id return TargetGroupAttachment(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="availabilityZone") def availability_zone(self) -> pulumi.Output[Optional[str]]: """ The Availability Zone where the IP address of the target is to be registered. If the private ip address is outside of the VPC scope, this value must be set to 'all'. """ return pulumi.get(self, "availability_zone") @property @pulumi.getter def port(self) -> pulumi.Output[Optional[int]]: """ The port on which targets receive traffic. """ return pulumi.get(self, "port") @property @pulumi.getter(name="targetGroupArn") def target_group_arn(self) -> pulumi.Output[str]: """ The ARN of the target group with which to register targets """ return pulumi.get(self, "target_group_arn") @property @pulumi.getter(name="targetId") def target_id(self) -> pulumi.Output[str]: """ The ID of the target. This is the Instance ID for an instance, or the container ID for an ECS container. If the target type is ip, specify an IP address. If the target type is lambda, specify the arn of lambda. """ return pulumi.get(self, "target_id") def translate_output_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
{ "pile_set_name": "Github" }
# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # # Translators: # Mingcong Bai <jeffbai@aosc.xyz>, 2017 # plantman <weihanlin@live.com>, 2017 # Feng Chao <chaofeng111@qq.com>, 2020 # Bobby Rong <rjl931189261@126.com>, 2020 # 玉堂白鹤 <yjwork@qq.com>, 2020 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2020-09-03 21:19+0200\n" "PO-Revision-Date: 2017-08-09 10:34+0000\n" "Last-Translator: 玉堂白鹤 <yjwork@qq.com>, 2020\n" "Language-Team: Chinese (China) (https://www.transifex.com/calamares/teams/20061/zh_CN/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: zh_CN\n" "Plural-Forms: nplurals=1; plural=0;\n" #: src/modules/grubcfg/main.py:28 msgid "Configure GRUB." msgstr "配置 GRUB." #: src/modules/mount/main.py:29 msgid "Mounting partitions." msgstr "挂载分区。" #: src/modules/mount/main.py:141 src/modules/initcpiocfg/main.py:196 #: src/modules/initcpiocfg/main.py:200 #: src/modules/luksopenswaphookcfg/main.py:86 #: src/modules/luksopenswaphookcfg/main.py:90 src/modules/rawfs/main.py:164 #: src/modules/initramfscfg/main.py:85 src/modules/initramfscfg/main.py:89 #: src/modules/openrcdmcryptcfg/main.py:69 #: src/modules/openrcdmcryptcfg/main.py:73 src/modules/fstab/main.py:323 #: src/modules/fstab/main.py:329 src/modules/localecfg/main.py:135 #: src/modules/networkcfg/main.py:39 msgid "Configuration Error" msgstr "配置错误" #: src/modules/mount/main.py:142 src/modules/initcpiocfg/main.py:197 #: src/modules/luksopenswaphookcfg/main.py:87 src/modules/rawfs/main.py:165 #: src/modules/initramfscfg/main.py:86 src/modules/openrcdmcryptcfg/main.py:70 #: src/modules/fstab/main.py:324 msgid "No partitions are defined for <pre>{!s}</pre> to use." msgstr "没有分配分区给 <pre>{!s}</pre>。" #: src/modules/services-systemd/main.py:26 msgid "Configure systemd services" msgstr "配置 systemd 服务" #: src/modules/services-systemd/main.py:59 #: src/modules/services-openrc/main.py:93 msgid "Cannot modify service" msgstr "无法修改服务" #: src/modules/services-systemd/main.py:60 msgid "" "<code>systemctl {arg!s}</code> call in chroot returned error code {num!s}." msgstr "chroot 中的 <code>systemctl {arg!s}</code> 命令返回错误 {num!s}." #: src/modules/services-systemd/main.py:63 #: src/modules/services-systemd/main.py:67 msgid "Cannot enable systemd service <code>{name!s}</code>." msgstr "无法启用 systemd 服务 <code>{name!s}</code>." #: src/modules/services-systemd/main.py:65 msgid "Cannot enable systemd target <code>{name!s}</code>." msgstr "无法启用 systemd 目标 <code>{name!s}</code>." #: src/modules/services-systemd/main.py:69 msgid "Cannot disable systemd target <code>{name!s}</code>." msgstr "无法禁用 systemd 目标 <code>{name!s}</code>." #: src/modules/services-systemd/main.py:71 msgid "Cannot mask systemd unit <code>{name!s}</code>." msgstr "无法屏蔽 systemd 单元 <code>{name!s}</code>." #: src/modules/services-systemd/main.py:73 msgid "" "Unknown systemd commands <code>{command!s}</code> and " "<code>{suffix!s}</code> for unit {name!s}." msgstr "" "未知的 systemd 命令 <code>{command!s}</code> 和 {name!s} 单元前缀 " "<code>{suffix!s}</code>." #: src/modules/umount/main.py:31 msgid "Unmount file systems." msgstr "卸载文件系统。" #: src/modules/unpackfs/main.py:35 msgid "Filling up filesystems." msgstr "写入文件系统。" #: src/modules/unpackfs/main.py:248 msgid "rsync failed with error code {}." msgstr "rsync 报错,错误码 {}." #: src/modules/unpackfs/main.py:293 msgid "Unpacking image {}/{}, file {}/{}" msgstr "解压镜像 {}/{},文件{}/{}" #: src/modules/unpackfs/main.py:308 msgid "Starting to unpack {}" msgstr "开始解压 {}" #: src/modules/unpackfs/main.py:317 src/modules/unpackfs/main.py:439 msgid "Failed to unpack image \"{}\"" msgstr "解压镜像失败 \"{}\"" #: src/modules/unpackfs/main.py:406 msgid "No mount point for root partition" msgstr "无 root 分区挂载点" #: src/modules/unpackfs/main.py:407 msgid "globalstorage does not contain a \"rootMountPoint\" key, doing nothing" msgstr "globalstorage 未包含 \"rootMountPoint\",跳过" #: src/modules/unpackfs/main.py:412 msgid "Bad mount point for root partition" msgstr "错误的 root 分区挂载点" #: src/modules/unpackfs/main.py:413 msgid "rootMountPoint is \"{}\", which does not exist, doing nothing" msgstr "rootMountPoint 是 \"{}\",不存在此位置,跳过" #: src/modules/unpackfs/main.py:429 src/modules/unpackfs/main.py:433 #: src/modules/unpackfs/main.py:453 msgid "Bad unsquash configuration" msgstr "错误的 unsquash 配置" #: src/modules/unpackfs/main.py:430 msgid "The filesystem for \"{}\" ({}) is not supported by your current kernel" msgstr "你当前的内核不支持文件系统 \"{}\" ({})" #: src/modules/unpackfs/main.py:434 msgid "The source filesystem \"{}\" does not exist" msgstr "源文件系统 \"{}\" 不存在" #: src/modules/unpackfs/main.py:440 msgid "" "Failed to find unsquashfs, make sure you have the squashfs-tools package " "installed" msgstr "未找到 unsquashfs,请确保安装了 squashfs-tools 软件包" #: src/modules/unpackfs/main.py:454 msgid "The destination \"{}\" in the target system is not a directory" msgstr "目标系统中的 \"{}\" 不是一个目录" #: src/modules/displaymanager/main.py:514 msgid "Cannot write KDM configuration file" msgstr "无法写入 KDM 配置文件" #: src/modules/displaymanager/main.py:515 msgid "KDM config file {!s} does not exist" msgstr "KDM 配置文件 {!s} 不存在" #: src/modules/displaymanager/main.py:576 msgid "Cannot write LXDM configuration file" msgstr "无法写入 LXDM 配置文件" #: src/modules/displaymanager/main.py:577 msgid "LXDM config file {!s} does not exist" msgstr "LXDM 配置文件 {!s} 不存在" #: src/modules/displaymanager/main.py:660 msgid "Cannot write LightDM configuration file" msgstr "无法写入 LightDM 配置文件" #: src/modules/displaymanager/main.py:661 msgid "LightDM config file {!s} does not exist" msgstr "LightDM 配置文件 {!s} 不存在" #: src/modules/displaymanager/main.py:735 msgid "Cannot configure LightDM" msgstr "无法配置 LightDM" #: src/modules/displaymanager/main.py:736 msgid "No LightDM greeter installed." msgstr "未安装 LightDM 欢迎程序。" #: src/modules/displaymanager/main.py:767 msgid "Cannot write SLIM configuration file" msgstr "无法写入 SLIM 配置文件" #: src/modules/displaymanager/main.py:768 msgid "SLIM config file {!s} does not exist" msgstr "SLIM 配置文件 {!s} 不存在" #: src/modules/displaymanager/main.py:894 msgid "No display managers selected for the displaymanager module." msgstr "显示管理器模块中未选择显示管理器。" #: src/modules/displaymanager/main.py:895 msgid "" "The displaymanagers list is empty or undefined in bothglobalstorage and " "displaymanager.conf." msgstr "globalstorage 和 displaymanager.conf 配置文件中都没有配置显示管理器。" #: src/modules/displaymanager/main.py:977 msgid "Display manager configuration was incomplete" msgstr "显示管理器配置不完全" #: src/modules/initcpiocfg/main.py:28 msgid "Configuring mkinitcpio." msgstr "配置 mkinitcpio." #: src/modules/initcpiocfg/main.py:201 #: src/modules/luksopenswaphookcfg/main.py:91 #: src/modules/initramfscfg/main.py:90 src/modules/openrcdmcryptcfg/main.py:74 #: src/modules/fstab/main.py:330 src/modules/localecfg/main.py:136 #: src/modules/networkcfg/main.py:40 msgid "No root mount point is given for <pre>{!s}</pre> to use." msgstr " 未设置 <pre>{!s}</pre> 要使用的根挂载点。" #: src/modules/luksopenswaphookcfg/main.py:26 msgid "Configuring encrypted swap." msgstr "配置加密交换分区。" #: src/modules/rawfs/main.py:26 msgid "Installing data." msgstr "安装数据." #: src/modules/services-openrc/main.py:29 msgid "Configure OpenRC services" msgstr "配置 OpenRC 服务。" #: src/modules/services-openrc/main.py:57 msgid "Cannot add service {name!s} to run-level {level!s}." msgstr "无法将服务 {name!s} 加入 {level!s} 运行级别." #: src/modules/services-openrc/main.py:59 msgid "Cannot remove service {name!s} from run-level {level!s}." msgstr "无法从 {level!s} 运行级别中删除服务 {name!s}。" #: src/modules/services-openrc/main.py:61 msgid "" "Unknown service-action <code>{arg!s}</code> for service {name!s} in run-" "level {level!s}." msgstr "未知的服务动作 <code>{arg!s}</code>,服务名: {name!s},运行级别: {level!s}." #: src/modules/services-openrc/main.py:94 msgid "" "<code>rc-update {arg!s}</code> call in chroot returned error code {num!s}." msgstr "chroot 中运行的 <code>rc-update {arg!s}</code> 返回错误 {num!s}." #: src/modules/services-openrc/main.py:101 msgid "Target runlevel does not exist" msgstr "目标运行级别不存在。" #: src/modules/services-openrc/main.py:102 msgid "" "The path for runlevel {level!s} is <code>{path!s}</code>, which does not " "exist." msgstr "运行级别 {level!s} 所在目录 <code>{path!s}</code> 不存在。" #: src/modules/services-openrc/main.py:110 msgid "Target service does not exist" msgstr "目标服务不存在" #: src/modules/services-openrc/main.py:111 msgid "" "The path for service {name!s} is <code>{path!s}</code>, which does not " "exist." msgstr "服务 {name!s} 的路径 <code>{path!s}</code> 不存在。" #: src/modules/plymouthcfg/main.py:27 msgid "Configure Plymouth theme" msgstr "配置 Plymouth 主题" #: src/modules/packages/main.py:50 src/modules/packages/main.py:59 #: src/modules/packages/main.py:69 msgid "Install packages." msgstr "安装软件包。" #: src/modules/packages/main.py:57 #, python-format msgid "Processing packages (%(count)d / %(total)d)" msgstr "软件包处理中(%(count)d/%(total)d)" #: src/modules/packages/main.py:62 #, python-format msgid "Installing one package." msgid_plural "Installing %(num)d packages." msgstr[0] "安装%(num)d软件包。" #: src/modules/packages/main.py:65 #, python-format msgid "Removing one package." msgid_plural "Removing %(num)d packages." msgstr[0] "移除%(num)d软件包。" #: src/modules/bootloader/main.py:42 msgid "Install bootloader." msgstr "安装启动加载器。" #: src/modules/hwclock/main.py:26 msgid "Setting hardware clock." msgstr "设置硬件时钟。" #: src/modules/mkinitfs/main.py:27 msgid "Creating initramfs with mkinitfs." msgstr "" #: src/modules/mkinitfs/main.py:49 msgid "Failed to run mkinitfs on the target" msgstr "" #: src/modules/mkinitfs/main.py:50 src/modules/dracut/main.py:50 msgid "The exit code was {}" msgstr "退出码是 {}" #: src/modules/dracut/main.py:27 msgid "Creating initramfs with dracut." msgstr "用 dracut 创建 initramfs." #: src/modules/dracut/main.py:49 msgid "Failed to run dracut on the target" msgstr "无法在目标中运行 dracut " #: src/modules/initramfscfg/main.py:32 msgid "Configuring initramfs." msgstr "正在配置初始内存文件系统。" #: src/modules/openrcdmcryptcfg/main.py:25 msgid "Configuring OpenRC dmcrypt service." msgstr "配置 OpenRC dmcrypt 服务。" #: src/modules/fstab/main.py:29 msgid "Writing fstab." msgstr "正在写入 fstab。" #: src/modules/dummypython/main.py:35 msgid "Dummy python job." msgstr "占位 Python 任务。" #: src/modules/dummypython/main.py:37 src/modules/dummypython/main.py:93 #: src/modules/dummypython/main.py:94 msgid "Dummy python step {}" msgstr "占位 Python 步骤 {}" #: src/modules/localecfg/main.py:30 msgid "Configuring locales." msgstr "正在进行本地化配置。" #: src/modules/networkcfg/main.py:28 msgid "Saving network configuration." msgstr "正在保存网络配置。"
{ "pile_set_name": "Github" }
====== Lähetä uusi salasana ====== Täytä käyttäjätunnuksesi kaavakkeeseen pyytääksesi uutta salasanaa wikin käyttäjätilillesi. Vahvistuslinkki lähetetään kirjautumisen yhteydessä antamaan sähköpostiosoitteeseen.
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- """ Document Library - Controllers """ module = request.controller if not settings.has_module(module): raise HTTP(404, body="Module disabled: %s" % module) # ============================================================================= def index(): "Module's Home Page" module_name = settings.modules[module].get("name_nice") response.title = module_name return dict(module_name=module_name) # ============================================================================= def document(): """ RESTful CRUD controller """ # Pre-processor def prep(r): # Location Filter s3db.gis_location_filter(r) if r.method in ("create", "create.popup"): doc_id = get_vars.get("~.doc_id", None) if doc_id: # Coming from Profile page s3db.doc_document.doc_id.default = doc_id return True s3.prep = prep output = s3_rest_controller(rheader = document_rheader, ) return output # ----------------------------------------------------------------------------- def document_rheader(r): if r.representation == "html": doc_document = r.record if doc_document: #rheader_tabs = s3_rheader_tabs(r, document_tabs(r)) table = db.doc_document rheader = DIV(B("%s: " % T("Name")), doc_document.name, TABLE(TR( TH("%s: " % T("File")), table.file.represent(doc_document.file), TH("%s: " % T("URL")), table.url.represent(doc_document.url), ), TR( TH("%s: " % ORGANISATION), table.organisation_id.represent(doc_document.organisation_id), TH("%s: " % T("Person")), table.person_id.represent(doc_document.organisation_id), ), ), #rheader_tabs ) return rheader return None # ----------------------------------------------------------------------------- def document_tabs(r): """ Display the number of Components in the tabs - currently unused as we don't have these tabs off documents """ tab_opts = [{"tablename": "assess_rat", "resource": "rat", "one_title": "1 Assessment", "num_title": " Assessments", }, {"tablename": "irs_ireport", "resource": "ireport", "one_title": "1 Incident Report", "num_title": " Incident Reports", }, {"tablename": "cr_shelter", "resource": "shelter", "one_title": "1 Shelter", "num_title": " Shelters", }, #{"tablename": "flood_freport", # "resource": "freport", # "one_title": "1 Flood Report", # "num_title": " Flood Reports", #}, {"tablename": "req_req", "resource": "req", "one_title": "1 Request", "num_title": " Requests", }, ] tabs = [(T("Details"), None)] crud_string = s3base.S3CRUD.crud_string for tab_opt in tab_opts: tablename = tab_opt["tablename"] if tablename in db and document_id in db[tablename]: table = db[tablename] query = (table.deleted == False) & \ (table.document_id == r.id) tab_count = db(query).count() if tab_count == 0: label = crud_string(tablename, "label_create") elif tab_count == 1: label = tab_opt["one_title"] else: label = T(str(tab_count) + tab_opt["num_title"] ) tabs.append( (label, tab_opt["resource"] ) ) return tabs # ============================================================================= def image(): """ RESTful CRUD controller """ # Pre-processor def prep(r): # Location Filter s3db.gis_location_filter(r) if r.method in ("create", "create.popup"): doc_id = get_vars.get("~.doc_id", None) if doc_id: # Coming from Profile page s3db.doc_image.doc_id.default = doc_id return True s3.prep = prep output = s3_rest_controller() return output # ============================================================================= def bulk_upload(): """ Custom view to allow bulk uploading of Photos @ToDo: Allow creation of a GIS Feature Layer to view on the map @ToDo: Allow uploading of associated GPX track for timestamp correlation. See r1595 for the previous draft of this work """ s3.stylesheets.append("plugins/fileuploader.css") return dict() def upload_bulk(): """ Receive the Uploaded data from bulk_upload() https://github.com/valums/file-uploader/blob/master/server/readme.txt @ToDo: Read EXIF headers to geolocate the Photos """ tablename = "doc_image" table = s3db[tablename] import cgi source = request.post_vars.get("qqfile", None) if isinstance(source, cgi.FieldStorage) and source.filename: # For IE6-8, Opera, older versions of other browsers you get the file as you normally do with regular form-base uploads. name = source.filename image = source.file else: # For browsers which upload file with progress bar, you will need to get the raw post data and write it to the file. if "name" in request.vars: name = request.vars.name else: HTTP(400, "Invalid Request: Need a Name!") image = request.body.read() # Convert to StringIO for onvalidation/import from s3compat import StringIO image = StringIO(image) source = Storage() source.filename = name source.file = image form = SQLFORM(table) vars = Storage() vars.name = name vars.image = source vars._formname = "%s_create" % tablename # onvalidation callback onvalidation = s3db.get_config(tablename, "create_onvalidation", s3db.get_config(tablename, "onvalidation")) if form.accepts(vars, onvalidation=onvalidation): msg = Storage(success = True) # onaccept callback onaccept = s3db.get_config(tablename, "create_onaccept", s3db.get_config(tablename, "onaccept")) from gluon.tools import callback callback(onaccept, form, tablename=tablename) else: error_msg = "" for error in form.errors: error_msg = "%s\n%s:%s" % (error_msg, error, form.errors[error]) msg = Storage(error = error_msg) response.headers["Content-Type"] = "text/html" # This is what the file-uploader widget expects return json.dumps(msg) # ============================================================================= def ck_upload(): """ Controller to handle uploads to CKEditor Based on https://github.com/timrichardson/web2py_ckeditor4 """ upload = request.vars.upload if upload is None: raise HTTP(401, "Missing required upload.") if not hasattr(upload, "file"): raise HTTP(401, "Upload is not proper type.") path = os.path.join(request.folder, "uploads") # Load Model table = s3db.doc_ckeditor form = SQLFORM.factory(Field("upload", "upload", requires = IS_NOT_EMPTY(), #uploadfs = self.settings.uploadfs, uploadfolder = path, ), table_name = "doc_ckeditor", ) old_filename = upload.filename new_filename = table.upload.store(upload.file, upload.filename) #if self.settings.uploadfs: # length = self.settings.uploadfs.getsize(new_filename) #else: length = os.path.getsize(os.path.join(path, new_filename)) mime_type = upload.headers["content-type"] title = os.path.splitext(old_filename)[0] result = table.validate_and_insert(title = title, filename = old_filename, upload = new_filename, flength = length, mime_type = mime_type, ) if result.id: text = "" else: text = result.errors url = URL(c="default", f="download", args = [new_filename]) return {"text": text, "cknum": request.vars.CKEditorFuncNum, "url": url, } # ----------------------------------------------------------------------------- def ck_browse(): """ Controller to handle uploads to CKEditor """ table = s3db.doc_ckeditor #browse_filter = {} set = db(table.id > 0) #for key, val in browse_filter.items(): # if value[0] == "<": # set = set(table[key] < value[1:]) # elif value[0] == ">": # set = set(table[key] > value[1:]) # elif value[0] == "!": # set = set(table[key] != value[1:]) # else: # set = set(table[key] == value) rows = set.select(orderby = table.title) return {"rows": rows, "cknum": request.vars.CKEditorFuncNum, } # ----------------------------------------------------------------------------- def ck_delete(): """ Controller to handle deletes in CKEditor """ try: filename = request.args[0] except: raise HTTP(401, "Required argument filename missing.") table = s3db.doc_ckeditor db(table.upload == filename).delete() # Delete the file from storage #if self.settings.uploadfs: # self.settings.uploadfs.remove(filename) #else: filepath = os.path.join(request.folder, "uploads", filename) os.unlink(filepath) # ----------------------------------------------------------------------------- def card_config(): return s3_rest_controller() # END =========================================================================
{ "pile_set_name": "Github" }
chooseFileDialogTitle = Seleccione un archivo templateFilter = Plantillas HTML PHPfiles = Archivos PHP
{ "pile_set_name": "Github" }
/* * SonarQube * Copyright (C) 2009-2020 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.db.migration.version.v84.qualitygateconditions; import org.sonar.db.Database; import org.sonar.server.platform.db.migration.version.v84.common.DropPrimaryKeyOnIdColumn; import org.sonar.server.platform.db.migration.version.v84.util.DropPrimaryKeySqlGenerator; public class DropPrimaryKeyOnIdColumnOfQualityGateConditionsTable extends DropPrimaryKeyOnIdColumn { private static final String TABLE_NAME = "quality_gate_conditions"; public DropPrimaryKeyOnIdColumnOfQualityGateConditionsTable(Database db, DropPrimaryKeySqlGenerator dropPrimaryKeySqlGenerator) { super(db, dropPrimaryKeySqlGenerator, TABLE_NAME); } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ module com.sun.mail.util.logging { exports com.sun.mail.util.logging; requires jakarta.mail; requires java.logging; }
{ "pile_set_name": "Github" }
/* * This file is part of the OregonCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <https://www.gnu.org/licenses/>. */ /* ScriptData SDName: boss_maleki_the_pallid SD%Complete: 100 SDComment: SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "stratholme.h" #define SPELL_FROSTBOLT 17503 #define SPELL_DRAINLIFE 20743 #define SPELL_DRAIN_MANA 17243 #define SPELL_ICETOMB 16869 struct boss_maleki_the_pallidAI : public ScriptedAI { boss_maleki_the_pallidAI(Creature* c) : ScriptedAI(c) { pInstance = (ScriptedInstance*)me->GetInstanceData(); } ScriptedInstance* pInstance; uint32 Frostbolt_Timer; uint32 IceTomb_Timer; uint32 DrainLife_Timer; void Reset() { Frostbolt_Timer = 1000; IceTomb_Timer = 16000; DrainLife_Timer = 31000; } void EnterCombat(Unit* /*who*/) { } void JustDied(Unit* /*Killer*/) { if (pInstance) pInstance->SetData(TYPE_PALLID, IN_PROGRESS); } void UpdateAI(const uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; //Frostbolt if (Frostbolt_Timer <= diff) { if (rand() % 100 < 90) DoCastVictim( SPELL_FROSTBOLT); Frostbolt_Timer = 3500; } else Frostbolt_Timer -= diff; //IceTomb if (IceTomb_Timer <= diff) { if (rand() % 100 < 65) DoCastVictim( SPELL_ICETOMB); IceTomb_Timer = 28000; } else IceTomb_Timer -= diff; //DrainLife if (DrainLife_Timer <= diff) { if (rand() % 100 < 55) DoCastVictim( SPELL_DRAINLIFE); DrainLife_Timer = 31000; } else DrainLife_Timer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_maleki_the_pallid(Creature* pCreature) { return new boss_maleki_the_pallidAI (pCreature); } void AddSC_boss_maleki_the_pallid() { Script* newscript; newscript = new Script; newscript->Name = "boss_maleki_the_pallid"; newscript->GetAI = &GetAI_boss_maleki_the_pallid; newscript->RegisterSelf(); }
{ "pile_set_name": "Github" }
using System; using NetOffice; using NetOffice.Attributes; namespace NetOffice.MSProjectApi.Enums { /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> ///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff865493(v=office.14).aspx </remarks> [SupportByVersion("MSProject", 11,12,14)] [EntityType(EntityType.IsEnum)] public enum PjIndicator { /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>0</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorNone = 0, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>1</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSphereLime = 1, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>2</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSphereYellow = 2, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>3</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSphereRed = 3, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>4</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSphereBlack = 4, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>5</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSphereWhite = 5, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>6</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSphereAqua = 6, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>7</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSphereGreen = 7, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>8</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSphereBlue = 8, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>9</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSphereFuschia = 9, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>10</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSpherePurple = 10, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>11</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSphereMaroon = 11, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>12</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSphereGray = 12, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>13</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSphereSilver = 13, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>14</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorFlagLime = 14, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>15</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorFlagYellow = 15, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>16</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorFlagRed = 16, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>17</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorFlagWhite = 17, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>18</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorFlagAqua = 18, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>19</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorFlagBlue = 19, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>20</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorFlagFuschia = 20, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>21</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorFlagSilver = 21, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>22</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSquareLime = 22, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>23</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSquareYellow = 23, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>24</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSquareRed = 24, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>25</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSquareBlack = 25, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>26</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorSquareWhite = 26, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>27</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorPlusLime = 27, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>28</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorPlusYellow = 28, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>29</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorPlusRed = 29, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>30</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorPlusBlack = 30, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>31</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorPlusWhite = 31, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>32</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorMinusLime = 32, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>33</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorMinusYellow = 33, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>34</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorMinusRed = 34, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>35</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorMinusBlack = 35, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>36</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorMinusWhite = 36, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>37</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorDiamondLime = 37, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>38</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorDiamondYellow = 38, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>39</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorDiamondRed = 39, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>40</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorArrowLeft = 40, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>41</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorArrowRight = 41, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>42</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorArrowDouble = 42, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>43</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorArrowUp = 43, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>44</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorArrowDown = 44, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>45</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorCircleSolidFill = 45, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>46</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorCircleBottomFill = 46, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>47</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorCircleLeftFill = 47, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>48</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorCircleTopFill = 48, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>49</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorCircleRightFill = 49, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>50</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorCircleRoundFill = 50, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>51</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorCircleHollow = 51, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>52</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorLightBulbOff = 52, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>53</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorLightBulbOn = 53, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>54</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorCheckMark = 54, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>55</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorDeleteMark = 55, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>56</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorQuestionMark = 56, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>57</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorClock = 57, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>58</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorPushPin = 58, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>59</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorFaceHappyYellow = 59, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>60</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorFaceHappyLime = 60, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>61</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorFaceStraightYellow = 61, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>62</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorFaceStraightAqua = 62, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>63</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorFaceSadYellow = 63, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>64</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorFaceSadRed = 64, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>65</remarks> [SupportByVersion("MSProject", 11,12,14)] pjIndicatorDashGray = 65 } }
{ "pile_set_name": "Github" }
// // © Copyright Henrik Ravn 2004 // // Use, modification and distribution are 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) // using System; using System.IO; using System.Runtime.InteropServices; namespace DotZLib { /// <summary> /// Implements a compressed <see cref="Stream"/>, in GZip (.gz) format. /// </summary> public class GZipStream : Stream, IDisposable { #region Dll Imports [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)] private static extern IntPtr gzopen(string name, string mode); [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] private static extern int gzclose(IntPtr gzFile); [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] private static extern int gzwrite(IntPtr gzFile, int data, int length); [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] private static extern int gzread(IntPtr gzFile, int data, int length); [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] private static extern int gzgetc(IntPtr gzFile); [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] private static extern int gzputc(IntPtr gzFile, int c); #endregion #region Private data private IntPtr _gzFile; private bool _isDisposed = false; private bool _isWriting; #endregion #region Constructors /// <summary> /// Creates a new file as a writeable GZipStream /// </summary> /// <param name="fileName">The name of the compressed file to create</param> /// <param name="level">The compression level to use when adding data</param> /// <exception cref="ZLibException">If an error occurred in the internal zlib function</exception> public GZipStream(string fileName, CompressLevel level) { _isWriting = true; _gzFile = gzopen(fileName, String.Format("wb{0}", (int)level)); if (_gzFile == IntPtr.Zero) throw new ZLibException(-1, "Could not open " + fileName); } /// <summary> /// Opens an existing file as a readable GZipStream /// </summary> /// <param name="fileName">The name of the file to open</param> /// <exception cref="ZLibException">If an error occurred in the internal zlib function</exception> public GZipStream(string fileName) { _isWriting = false; _gzFile = gzopen(fileName, "rb"); if (_gzFile == IntPtr.Zero) throw new ZLibException(-1, "Could not open " + fileName); } #endregion #region Access properties /// <summary> /// Returns true of this stream can be read from, false otherwise /// </summary> public override bool CanRead { get { return !_isWriting; } } /// <summary> /// Returns false. /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Returns true if this tsream is writeable, false otherwise /// </summary> public override bool CanWrite { get { return _isWriting; } } #endregion #region Destructor & IDispose stuff /// <summary> /// Destroys this instance /// </summary> ~GZipStream() { cleanUp(false); } /// <summary> /// Closes the external file handle /// </summary> public void Dispose() { cleanUp(true); } // Does the actual closing of the file handle. private void cleanUp(bool isDisposing) { if (!_isDisposed) { gzclose(_gzFile); _isDisposed = true; } } #endregion #region Basic reading and writing /// <summary> /// Attempts to read a number of bytes from the stream. /// </summary> /// <param name="buffer">The destination data buffer</param> /// <param name="offset">The index of the first destination byte in <c>buffer</c></param> /// <param name="count">The number of bytes requested</param> /// <returns>The number of bytes read</returns> /// <exception cref="ArgumentNullException">If <c>buffer</c> is null</exception> /// <exception cref="ArgumentOutOfRangeException">If <c>count</c> or <c>offset</c> are negative</exception> /// <exception cref="ArgumentException">If <c>offset</c> + <c>count</c> is &gt; buffer.Length</exception> /// <exception cref="NotSupportedException">If this stream is not readable.</exception> /// <exception cref="ObjectDisposedException">If this stream has been disposed.</exception> public override int Read(byte[] buffer, int offset, int count) { if (!CanRead) throw new NotSupportedException(); if (buffer == null) throw new ArgumentNullException(); if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); if ((offset+count) > buffer.Length) throw new ArgumentException(); if (_isDisposed) throw new ObjectDisposedException("GZipStream"); GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned); int result; try { result = gzread(_gzFile, h.AddrOfPinnedObject().ToInt32() + offset, count); if (result < 0) throw new IOException(); } finally { h.Free(); } return result; } /// <summary> /// Attempts to read a single byte from the stream. /// </summary> /// <returns>The byte that was read, or -1 in case of error or End-Of-File</returns> public override int ReadByte() { if (!CanRead) throw new NotSupportedException(); if (_isDisposed) throw new ObjectDisposedException("GZipStream"); return gzgetc(_gzFile); } /// <summary> /// Writes a number of bytes to the stream /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <exception cref="ArgumentNullException">If <c>buffer</c> is null</exception> /// <exception cref="ArgumentOutOfRangeException">If <c>count</c> or <c>offset</c> are negative</exception> /// <exception cref="ArgumentException">If <c>offset</c> + <c>count</c> is &gt; buffer.Length</exception> /// <exception cref="NotSupportedException">If this stream is not writeable.</exception> /// <exception cref="ObjectDisposedException">If this stream has been disposed.</exception> public override void Write(byte[] buffer, int offset, int count) { if (!CanWrite) throw new NotSupportedException(); if (buffer == null) throw new ArgumentNullException(); if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); if ((offset+count) > buffer.Length) throw new ArgumentException(); if (_isDisposed) throw new ObjectDisposedException("GZipStream"); GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { int result = gzwrite(_gzFile, h.AddrOfPinnedObject().ToInt32() + offset, count); if (result < 0) throw new IOException(); } finally { h.Free(); } } /// <summary> /// Writes a single byte to the stream /// </summary> /// <param name="value">The byte to add to the stream.</param> /// <exception cref="NotSupportedException">If this stream is not writeable.</exception> /// <exception cref="ObjectDisposedException">If this stream has been disposed.</exception> public override void WriteByte(byte value) { if (!CanWrite) throw new NotSupportedException(); if (_isDisposed) throw new ObjectDisposedException("GZipStream"); int result = gzputc(_gzFile, (int)value); if (result < 0) throw new IOException(); } #endregion #region Position & length stuff /// <summary> /// Not supported. /// </summary> /// <param name="value"></param> /// <exception cref="NotSupportedException">Always thrown</exception> public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Not suppported. /// </summary> /// <param name="offset"></param> /// <param name="origin"></param> /// <returns></returns> /// <exception cref="NotSupportedException">Always thrown</exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// Flushes the <c>GZipStream</c>. /// </summary> /// <remarks>In this implementation, this method does nothing. This is because excessive /// flushing may degrade the achievable compression rates.</remarks> public override void Flush() { // left empty on purpose } /// <summary> /// Gets/sets the current position in the <c>GZipStream</c>. Not suppported. /// </summary> /// <remarks>In this implementation this property is not supported</remarks> /// <exception cref="NotSupportedException">Always thrown</exception> public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// <summary> /// Gets the size of the stream. Not suppported. /// </summary> /// <remarks>In this implementation this property is not supported</remarks> /// <exception cref="NotSupportedException">Always thrown</exception> public override long Length { get { throw new NotSupportedException(); } } #endregion } }
{ "pile_set_name": "Github" }
import React, { Component, Fragment } from 'react'; import classNames from 'classnames'; import { object } from 'prop-types'; import { withApollo } from 'react-apollo'; import Avatar from '@material-ui/core/Avatar'; import { withStyles } from '@material-ui/core/styles'; import IconButton from '@material-ui/core/IconButton'; import Button from '../Button'; import SignInDialog from '../SignInDialog'; import { withAuth } from '../../utils/Auth'; import getPictureFromUser from '../../utils/getPictureFromUser'; @withAuth @withApollo @withStyles(theme => ({ avatarButton: { height: 6 * theme.spacing(1), width: 6 * theme.spacing(1), padding: 0, }, })) export default class UserMenuButton extends Component { static propTypes = { avatarProps: object, buttonProps: object, }; static defaultProps = { avatarProps: null, buttonProps: null, }; render() { const { className, classes, user, avatarProps, buttonProps, signInDialogOpen, onSignInDialogOpen, onSignInDialogClose, onMenuClick, onAuthorize, onUnauthorize, ...props } = this.props; const avatarSrc = getPictureFromUser(user); if (!user) { return ( <Fragment> <Button className={className} size="small" variant="contained" color="primary" onClick={onSignInDialogOpen} {...buttonProps} {...props}> Sign in </Button> <SignInDialog open={signInDialogOpen} onClose={onSignInDialogClose} /> </Fragment> ); } return ( <IconButton className={classNames(classes.avatarButton, className)} aria-haspopup="true" aria-controls="user-menu" aria-label="user menu" onClick={onMenuClick} {...props}> {avatarSrc ? ( <Avatar alt={user.profile.displayName} src={avatarSrc} {...avatarProps} /> ) : ( <Avatar alt={user.profile.displayName} {...avatarProps}> {user.profile.displayName[0]} </Avatar> )} </IconButton> ); } }
{ "pile_set_name": "Github" }
<?php abstract class PhabricatorModularTransactionType extends Phobject { private $storage; private $viewer; private $editor; final public function getTransactionTypeConstant() { return $this->getPhobjectClassConstant('TRANSACTIONTYPE'); } public function generateOldValue($object) { throw new PhutilMethodNotImplementedException(); } public function generateNewValue($object, $value) { return $value; } public function validateTransactions($object, array $xactions) { return array(); } public function applyInternalEffects($object, $value) { return; } public function applyExternalEffects($object, $value) { return; } public function didCommitTransaction($object, $value) { return; } public function getTransactionHasEffect($object, $old, $new) { return ($old !== $new); } public function extractFilePHIDs($object, $value) { return array(); } public function shouldHide() { return false; } public function shouldHideForFeed() { return false; } public function shouldHideForMail() { return false; } public function shouldHideForNotifications() { return null; } public function getIcon() { return null; } public function getTitle() { return null; } public function getTitleForFeed() { return null; } public function getActionName() { return null; } public function getActionStrength() { return null; } public function getColor() { return null; } public function hasChangeDetailView() { return false; } public function newChangeDetailView() { return null; } public function getMailDiffSectionHeader() { return pht('EDIT DETAILS'); } public function newRemarkupChanges() { return array(); } public function mergeTransactions( $object, PhabricatorApplicationTransaction $u, PhabricatorApplicationTransaction $v) { return null; } final public function setStorage( PhabricatorApplicationTransaction $xaction) { $this->storage = $xaction; return $this; } private function getStorage() { return $this->storage; } final public function setViewer(PhabricatorUser $viewer) { $this->viewer = $viewer; return $this; } final protected function getViewer() { return $this->viewer; } final public function getActor() { return $this->getEditor()->getActor(); } final public function getActingAsPHID() { return $this->getEditor()->getActingAsPHID(); } final public function setEditor( PhabricatorApplicationTransactionEditor $editor) { $this->editor = $editor; return $this; } final protected function getEditor() { if (!$this->editor) { throw new PhutilInvalidStateException('setEditor'); } return $this->editor; } final protected function hasEditor() { return (bool)$this->editor; } final protected function getAuthorPHID() { return $this->getStorage()->getAuthorPHID(); } final protected function getObjectPHID() { return $this->getStorage()->getObjectPHID(); } final protected function getObject() { return $this->getStorage()->getObject(); } final protected function getOldValue() { return $this->getStorage()->getOldValue(); } final protected function getNewValue() { return $this->getStorage()->getNewValue(); } final protected function renderAuthor() { $author_phid = $this->getAuthorPHID(); return $this->getStorage()->renderHandleLink($author_phid); } final protected function renderObject() { $object_phid = $this->getObjectPHID(); return $this->getStorage()->renderHandleLink($object_phid); } final protected function renderHandle($phid) { $viewer = $this->getViewer(); $display = $viewer->renderHandle($phid); if ($this->isTextMode()) { $display->setAsText(true); } return $display; } final protected function renderOldHandle() { return $this->renderHandle($this->getOldValue()); } final protected function renderNewHandle() { return $this->renderHandle($this->getNewValue()); } final protected function renderOldPolicy() { return $this->renderPolicy($this->getOldValue(), 'old'); } final protected function renderNewPolicy() { return $this->renderPolicy($this->getNewValue(), 'new'); } final protected function renderPolicy($phid, $mode) { $viewer = $this->getViewer(); $handles = $viewer->loadHandles(array($phid)); $policy = PhabricatorPolicy::newFromPolicyAndHandle( $phid, $handles[$phid]); $ref = $policy->newRef($viewer); if ($this->isTextMode()) { $name = $ref->getPolicyDisplayName(); } else { $storage = $this->getStorage(); $name = $ref->newTransactionLink($mode, $storage); } return $this->renderValue($name); } final protected function renderHandleList(array $phids) { $viewer = $this->getViewer(); $display = $viewer->renderHandleList($phids) ->setAsInline(true); if ($this->isTextMode()) { $display->setAsText(true); } return $display; } final protected function renderValue($value) { if ($this->isTextMode()) { return sprintf('"%s"', $value); } return phutil_tag( 'span', array( 'class' => 'phui-timeline-value', ), $value); } final protected function renderValueList(array $values) { $result = array(); foreach ($values as $value) { $result[] = $this->renderValue($value); } if ($this->isTextMode()) { return implode(', ', $result); } return phutil_implode_html(', ', $result); } final protected function renderOldValue() { return $this->renderValue($this->getOldValue()); } final protected function renderNewValue() { return $this->renderValue($this->getNewValue()); } final protected function renderDate($epoch) { $viewer = $this->getViewer(); // We accept either epoch timestamps or dictionaries describing a // PhutilCalendarDateTime. if (is_array($epoch)) { $datetime = PhutilCalendarAbsoluteDateTime::newFromDictionary($epoch) ->setViewerTimezone($viewer->getTimezoneIdentifier()); $all_day = $datetime->getIsAllDay(); $epoch = $datetime->getEpoch(); } else { $all_day = false; } if ($all_day) { $display = phabricator_date($epoch, $viewer); } else if ($this->isRenderingTargetExternal()) { // When rendering to text, we explicitly render the offset from UTC to // provide context to the date: the mail may be generating with the // server's settings, or the user may later refer back to it after // changing timezones. $display = phabricator_datetimezone($epoch, $viewer); } else { $display = phabricator_datetime($epoch, $viewer); } return $this->renderValue($display); } final protected function renderOldDate() { return $this->renderDate($this->getOldValue()); } final protected function renderNewDate() { return $this->renderDate($this->getNewValue()); } final protected function newError($title, $message, $xaction = null) { return new PhabricatorApplicationTransactionValidationError( $this->getTransactionTypeConstant(), $title, $message, $xaction); } final protected function newRequiredError($message, $xaction = null) { return $this->newError(pht('Required'), $message, $xaction) ->setIsMissingFieldError(true); } final protected function newInvalidError($message, $xaction = null) { return $this->newError(pht('Invalid'), $message, $xaction); } final protected function isNewObject() { return $this->getEditor()->getIsNewObject(); } final protected function isEmptyTextTransaction($value, array $xactions) { foreach ($xactions as $xaction) { $value = $xaction->getNewValue(); } return !strlen($value); } /** * When rendering to external targets (Email/Asana/etc), we need to include * more information that users can't obtain later. */ final protected function isRenderingTargetExternal() { // Right now, this is our best proxy for this: return $this->isTextMode(); // "TARGET_TEXT" means "EMail" and "TARGET_HTML" means "Web". } final protected function isTextMode() { $target = $this->getStorage()->getRenderingTarget(); return ($target == PhabricatorApplicationTransaction::TARGET_TEXT); } final protected function newRemarkupChange() { return id(new PhabricatorTransactionRemarkupChange()) ->setTransaction($this->getStorage()); } final protected function isCreateTransaction() { return $this->getStorage()->getIsCreateTransaction(); } final protected function getPHIDList(array $old, array $new) { $editor = $this->getEditor(); return $editor->getPHIDList($old, $new); } public function getMetadataValue($key, $default = null) { return $this->getStorage()->getMetadataValue($key, $default); } public function loadTransactionTypeConduitData(array $xactions) { return null; } public function getTransactionTypeForConduit($xaction) { return null; } public function getFieldValuesForConduit($xaction, $data) { return array(); } protected function requireApplicationCapability($capability) { $application_class = $this->getEditor()->getEditorApplicationClass(); $application = newv($application_class, array()); PhabricatorPolicyFilter::requireCapability( $this->getActor(), $application, $capability); } /** * Get a list of capabilities the actor must have on the object to apply * a transaction to it. * * Usually, you should use this to reduce capability requirements when a * transaction (like leaving a Conpherence thread) can be applied without * having edit permission on the object. You can override this method to * remove the CAN_EDIT requirement, or to replace it with a different * requirement. * * If you are increasing capability requirements and need to add an * additional capability or policy requirement above and beyond CAN_EDIT, it * is usually better implemented as a validation check. * * @param object Object being edited. * @param PhabricatorApplicationTransaction Transaction being applied. * @return null|const|list<const> A capability constant (or list of * capability constants) which the actor must have on the object. You can * return `null` as a shorthand for "no capabilities are required". */ public function getRequiredCapabilities( $object, PhabricatorApplicationTransaction $xaction) { return PhabricatorPolicyCapability::CAN_EDIT; } public function shouldTryMFA( $object, PhabricatorApplicationTransaction $xaction) { return false; } // NOTE: See T12921. These APIs are somewhat aspirational. For now, all of // these use "TARGET_TEXT" (even the HTML methods!) and the body methods // actually return Remarkup, not text or HTML. final public function getTitleForTextMail() { return $this->getTitleForMailWithRenderingTarget( PhabricatorApplicationTransaction::TARGET_TEXT); } final public function getTitleForHTMLMail() { return $this->getTitleForMailWithRenderingTarget( PhabricatorApplicationTransaction::TARGET_TEXT); } final public function getBodyForTextMail() { return $this->getBodyForMailWithRenderingTarget( PhabricatorApplicationTransaction::TARGET_TEXT); } final public function getBodyForHTMLMail() { return $this->getBodyForMailWithRenderingTarget( PhabricatorApplicationTransaction::TARGET_TEXT); } private function getTitleForMailWithRenderingTarget($target) { $storage = $this->getStorage(); $old_target = $storage->getRenderingTarget(); try { $storage->setRenderingTarget($target); $result = $this->getTitleForMail(); } catch (Exception $ex) { $storage->setRenderingTarget($old_target); throw $ex; } $storage->setRenderingTarget($old_target); return $result; } private function getBodyForMailWithRenderingTarget($target) { $storage = $this->getStorage(); $old_target = $storage->getRenderingTarget(); try { $storage->setRenderingTarget($target); $result = $this->getBodyForMail(); } catch (Exception $ex) { $storage->setRenderingTarget($old_target); throw $ex; } $storage->setRenderingTarget($old_target); return $result; } protected function getTitleForMail() { return false; } protected function getBodyForMail() { return false; } }
{ "pile_set_name": "Github" }
/* Getopt for GNU. NOTE: getopt is now part of the C library, so if you don't know what "Keep this file name-space clean" means, talk to drepper@gnu.org before changing it! Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 2000 Free Software Foundation, Inc. Copyright (C) 2004,2009,2010,2015 Olly Betts (reworked to allow compilation as C++) The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The GNU C 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with the GNU C Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "xapian/common/gnu_getopt.h" /* #ifdef out all this code if we are using the GNU C Library. GNU getopt is included in the GNU C Library, and linking in this code is a waste when using the GNU C library (especially if it is a shared library). */ #ifndef USE_GLIBC_GNUGETOPT #include <cstdio> using std::fprintf; #ifdef VMS # include <unixlib.h> #endif #ifndef _ /* This is for other GNU distributions with internationalized messages. */ # if 0 //defined HAVE_LIBINTL_H || defined _LIBC # include <libintl.h> # ifndef _ # define _(msgid) gettext (msgid) # endif # else # define _(msgid) (msgid) # endif #endif #ifndef __CYGWIN__ /* This version of `getopt' appears to the caller like standard Unix `getopt' but it behaves differently for the user, since it allows the user to intersperse the options with the other arguments. As `getopt' works, it permutes the elements of ARGV so that, when it is done, all the options precede everything else. Thus all application programs are extended to handle flexible argument order. Setting the environment variable POSIXLY_CORRECT disables permutation. Then the behavior is completely standard. GNU application programs can use a third alternative mode in which they can distinguish the relative order of options and other arguments. */ /* For communication from `getopt' to the caller. When `getopt' finds an option that takes an argument, the argument value is returned here. Also, when `ordering' is RETURN_IN_ORDER, each non-option ARGV-element is returned here. */ char *optarg; /* Index in ARGV of the next element to be scanned. This is used for communication to and from the caller and for communication between successive calls to `getopt'. On entry to `getopt', zero means this is the first call; initialize. When `getopt' returns -1, this is the index of the first of the non-option elements that the caller should itself scan. Otherwise, `optind' communicates from one call to the next how much of ARGV has been scanned so far. */ /* 1003.2 says this must be 1 before any call. */ int optind = 1; /* Callers store zero here to inhibit the error message for unrecognized options. */ int opterr = 1; /* Set to an option character which was unrecognized. This must be initialized on some systems to avoid linking in the system's own getopt implementation. */ int optopt = '?'; #endif /* Formerly, initialization of getopt depended on optind==0, which causes problems with re-calling getopt as programs generally don't know that. */ static int getopt_initialized; /* The next char to be scanned in the option-element in which the last option character we returned was found. This allows us to pick up the scan where we left off. If this is zero, or a null string, it means resume the scan by advancing to the next ARGV-element. */ static char *nextchar; /* Describe how to deal with options that follow non-option ARGV-elements. If the caller did not specify anything, the default is REQUIRE_ORDER if the environment variable POSIXLY_CORRECT is defined, PERMUTE otherwise. REQUIRE_ORDER means don't recognize them as options; stop option processing when the first non-option is seen. This is what Unix does. This mode of operation is selected by either setting the environment variable POSIXLY_CORRECT, or using `+' as the first character of the list of option characters. PERMUTE is the default. We permute the contents of ARGV as we scan, so that eventually all the non-options are at the end. This allows options to be given in any order, even with programs that were not written to expect this. RETURN_IN_ORDER is an option available to programs that were written to expect options and other ARGV-elements in any order and that care about the ordering of the two. We describe each non-option ARGV-element as if it were the argument of an option with character code 1. Using `-' as the first character of the list of option characters selects this mode of operation. The special argument `--' forces an end of option-scanning regardless of the value of `ordering'. In the case of RETURN_IN_ORDER, only `--' can cause `getopt' to return -1 with `optind' != ARGC. */ static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering; /* Value of POSIXLY_CORRECT environment variable. */ static char *posixly_correct; #include <cstring> using std::strlen; using std::strcmp; using std::strncmp; using std::strchr; #include <cstdlib> using std::getenv; /* Handle permutation of arguments. */ /* Describe the part of ARGV that contains non-options that have been skipped. `first_nonopt' is the index in ARGV of the first of them; `last_nonopt' is the index after the last of them. */ static int first_nonopt; static int last_nonopt; /* Exchange two adjacent subsequences of ARGV. One subsequence is elements [first_nonopt,last_nonopt) which contains all the non-options that have been skipped so far. The other is elements [last_nonopt,optind), which contains all the options processed since those non-options were skipped. `first_nonopt' and `last_nonopt' are relocated so that they describe the new indices of the non-options in ARGV after they are moved. */ static void exchange (char **argv) { int bottom = first_nonopt; int middle = last_nonopt; int top = optind; char *tem; /* Exchange the shorter segment with the far end of the longer segment. That puts the shorter segment into the right place. It leaves the longer segment in the right place overall, but it consists of two parts that need to be swapped next. */ while (top > middle && middle > bottom) { if (top - middle > middle - bottom) { /* Bottom segment is the short one. */ int len = middle - bottom; int i; /* Swap it with the top part of the top segment. */ for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[top - (middle - bottom) + i]; argv[top - (middle - bottom) + i] = tem; } /* Exclude the moved bottom segment from further swapping. */ top -= len; } else { /* Top segment is the short one. */ int len = top - middle; int i; /* Swap it with the bottom part of the bottom segment. */ for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[middle + i]; argv[middle + i] = tem; } /* Exclude the moved top segment from further swapping. */ bottom += len; } } /* Update records for the slots the non-options now occupy. */ first_nonopt += (optind - last_nonopt); last_nonopt = optind; } /* Initialize the internal data when the first call is made. */ static const char * getopt_initialize (int argc, char *const *argv, const char *optstring) { /* Suppress possible unused warnings */ (void)argc; (void)argv; /* Start processing options with ARGV-element 1 (since ARGV-element 0 is the program name); the sequence of previously skipped non-option ARGV-elements is empty. */ first_nonopt = last_nonopt = optind; nextchar = NULL; posixly_correct = getenv ("POSIXLY_CORRECT"); /* Determine how to handle the ordering of options and nonoptions. */ if (optstring[0] == '-') { ordering = RETURN_IN_ORDER; ++optstring; } else if (optstring[0] == '+') { ordering = REQUIRE_ORDER; ++optstring; } else if (posixly_correct != NULL) ordering = REQUIRE_ORDER; else ordering = PERMUTE; return optstring; } /* Scan elements of ARGV (whose length is ARGC) for option characters given in OPTSTRING. If an element of ARGV starts with '-', and is not exactly "-" or "--", then it is an option element. The characters of this element (aside from the initial '-') are option characters. If `getopt' is called repeatedly, it returns successively each of the option characters from each of the option elements. If `getopt' finds another option character, it returns that character, updating `optind' and `nextchar' so that the next call to `getopt' can resume the scan with the following option character or ARGV-element. If there are no more option characters, `getopt' returns -1. Then `optind' is the index in ARGV of the first ARGV-element that is not an option. (The ARGV-elements have been permuted so that those that are not options now come last.) OPTSTRING is a string containing the legitimate option characters. If an option character is seen that is not listed in OPTSTRING, return '?' after printing an error message. If you set `opterr' to zero, the error message is suppressed but we still return '?'. If a char in OPTSTRING is followed by a colon, that means it wants an arg, so the following text in the same ARGV-element, or the text of the following ARGV-element, is returned in `optarg'. Two colons mean an option that wants an optional arg; if there is text in the current ARGV-element, it is returned in `optarg', otherwise `optarg' is set to zero. If OPTSTRING starts with `-' or `+', it requests different methods of handling the non-option ARGV-elements. See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. Long-named options begin with `--' instead of `-'. Their names may be abbreviated as long as the abbreviation is unique or is an exact match for some defined option. If they have an argument, it follows the option name in the same ARGV-element, separated from the option name by a `=', or else the in next ARGV-element. When `getopt' finds a long-named option, it returns 0 if that option's `flag' field is nonzero, the value of the option's `val' field if the `flag' field is zero. The elements of ARGV aren't really const, because we permute them. But we pretend they're const in the prototype to be compatible with other systems. LONGOPTS is a vector of `struct option' terminated by an element containing a name which is zero. LONGIND returns the index in LONGOPT of the long-named option found. It is only valid when a long-named option has been found by the most recent call. If LONG_ONLY is nonzero, '-' as well as '--' can introduce long-named options. */ int gnu_getopt_internal_(int argc, char *const *argv, const char *optstring, const struct option *longopts, int *longind, int long_only) { int print_errors = opterr; if (optstring[0] == ':') print_errors = 0; if (argc < 1) return -1; optarg = NULL; if (optind == 0 || !getopt_initialized) { if (optind == 0) optind = 1; /* Don't scan ARGV[0], the program name. */ optstring = getopt_initialize (argc, argv, optstring); getopt_initialized = 1; } /* Test whether ARGV[optind] points to a non-option argument (i.e. it does not have option syntax). */ # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0') if (nextchar == NULL || *nextchar == '\0') { /* Advance to the next ARGV-element. */ /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been moved back by the user (who may also have changed the arguments). */ if (last_nonopt > optind) last_nonopt = optind; if (first_nonopt > optind) first_nonopt = optind; if (ordering == PERMUTE) { /* If we have just processed some options following some non-options, exchange them so that the options come first. */ if (first_nonopt != last_nonopt && last_nonopt != optind) exchange (const_cast<char **>(argv)); else if (last_nonopt != optind) first_nonopt = optind; /* Skip any additional non-options and extend the range of non-options previously skipped. */ while (optind < argc && NONOPTION_P) optind++; last_nonopt = optind; } /* The special ARGV-element `--' means premature end of options. Skip it like a null option, then exchange with previous non-options as if it were an option, then skip everything else like a non-option. */ if (optind != argc && !strcmp (argv[optind], "--")) { optind++; if (first_nonopt != last_nonopt && last_nonopt != optind) exchange (const_cast<char **>(argv)); else if (first_nonopt == last_nonopt) first_nonopt = optind; last_nonopt = argc; optind = argc; } /* If we have done all the ARGV-elements, stop the scan and back over any non-options that we skipped and permuted. */ if (optind == argc) { /* Set the next-arg-index to point at the non-options that we previously skipped, so the caller will digest them. */ if (first_nonopt != last_nonopt) optind = first_nonopt; return -1; } /* If we have come to a non-option and did not permute it, either stop the scan or describe it to the caller and pass it by. */ if (NONOPTION_P) { if (ordering == REQUIRE_ORDER) return -1; optarg = argv[optind++]; return 1; } /* We have found another option-ARGV-element. Skip the initial punctuation. */ nextchar = (argv[optind] + 1 + (longopts != NULL && argv[optind][1] == '-')); } /* Decode the current option-ARGV-element. */ /* Check whether the ARGV-element is a long option. If long_only and the ARGV-element has the form "-f", where f is a valid short option, don't consider it an abbreviated form of a long option that starts with f. Otherwise there would be no way to give the -f short option. On the other hand, if there's a long option "fubar" and the ARGV-element is "-fu", do consider that an abbreviation of the long option, just like "--fu", and not "-f" with arg "u". This distinction seems to be the most useful approach. */ if (longopts != NULL && (argv[optind][1] == '-' || (long_only && (argv[optind][2] || !strchr (optstring, argv[optind][1]))))) { char *nameend; const struct option *p; const struct option *pfound = NULL; int exact = 0; int ambig = 0; int indfound = -1; int option_index; for (nameend = nextchar; *nameend && *nameend != '='; nameend++) /* Do nothing. */ ; /* Test all long options for either exact match or abbreviated matches. */ for (p = longopts, option_index = 0; p->name; p++, option_index++) if (!strncmp (p->name, nextchar, nameend - nextchar)) { if (unsigned(nameend - nextchar) == unsigned(strlen(p->name))) { /* Exact match found. */ pfound = p; indfound = option_index; exact = 1; break; } else if (pfound == NULL) { /* First nonexact match found. */ pfound = p; indfound = option_index; } else if (long_only || pfound->has_arg != p->has_arg || pfound->flag != p->flag || pfound->val != p->val) /* Second or later nonexact match found. */ ambig = 1; } if (ambig && !exact) { if (print_errors) fprintf (stderr, _("%s: option '%s' is ambiguous\n"), argv[0], argv[optind]); nextchar += strlen (nextchar); optind++; optopt = 0; return '?'; } if (pfound != NULL) { option_index = indfound; optind++; if (*nameend) { /* Don't test has_arg with >, because some C compilers don't allow it to be used on enums. */ if (pfound->has_arg) optarg = nameend + 1; else { if (print_errors) { if (argv[optind - 1][1] == '-') /* --option */ fprintf (stderr, _("%s: option '--%s' doesn't allow an argument\n"), argv[0], pfound->name); else /* +option or -option */ fprintf (stderr, _("%s: option '%c%s' doesn't allow an argument\n"), argv[0], argv[optind - 1][0], pfound->name); } nextchar += strlen (nextchar); optopt = pfound->val; return '?'; } } else if (pfound->has_arg == 1) { if (optind < argc) optarg = argv[optind++]; else { if (print_errors) fprintf (stderr, _("%s: option '%s' requires an argument\n"), argv[0], argv[optind - 1]); nextchar += strlen (nextchar); optopt = pfound->val; return optstring[0] == ':' ? ':' : '?'; } } nextchar += strlen (nextchar); if (longind != NULL) *longind = option_index; if (pfound->flag) { *(pfound->flag) = pfound->val; return 0; } return pfound->val; } /* Can't find it as a long option. If this is not getopt_long_only, or the option starts with '--' or is not a valid short option, then it's an error. Otherwise interpret it as a short option. */ if (!long_only || argv[optind][1] == '-' || strchr (optstring, *nextchar) == NULL) { if (print_errors) { if (argv[optind][1] == '-') /* --option */ fprintf (stderr, _("%s: unrecognized option '--%s'\n"), argv[0], nextchar); else /* +option or -option */ fprintf (stderr, _("%s: unrecognized option '%c%s'\n"), argv[0], argv[optind][0], nextchar); } nextchar = const_cast<char *>(""); optind++; optopt = 0; return '?'; } } /* Look at and handle the next short option-character. */ { char c = *nextchar++; const char *temp = strchr (optstring, c); /* Increment `optind' when we start to process its last character. */ if (*nextchar == '\0') ++optind; if (temp == NULL || c == ':') { if (print_errors) { if (posixly_correct) /* 1003.2 specifies the format of this message. */ fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c); else fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c); } optopt = c; return '?'; } /* Convenience. Treat POSIX -W foo same as long option --foo */ if (temp[0] == 'W' && temp[1] == ';') { char *nameend; const struct option *p; const struct option *pfound = NULL; int exact = 0; int ambig = 0; int indfound = 0; int option_index; /* This is an option that requires an argument. */ if (*nextchar != '\0') { optarg = nextchar; /* If we end this ARGV-element by taking the rest as an arg, we must advance to the next element now. */ optind++; } else if (optind == argc) { if (print_errors) { /* 1003.2 specifies the format of this message. */ fprintf (stderr, _("%s: option requires an argument -- %c\n"), argv[0], c); } optopt = c; if (optstring[0] == ':') c = ':'; else c = '?'; return c; } else /* We already incremented `optind' once; increment it again when taking next ARGV-elt as argument. */ optarg = argv[optind++]; /* optarg is now the argument, see if it's in the table of longopts. */ for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++) /* Do nothing. */ ; /* Test all long options for either exact match or abbreviated matches. */ for (p = longopts, option_index = 0; p->name; p++, option_index++) if (!strncmp (p->name, nextchar, nameend - nextchar)) { if (unsigned(nameend - nextchar) == unsigned(strlen(p->name))) { /* Exact match found. */ pfound = p; indfound = option_index; exact = 1; break; } else if (pfound == NULL) { /* First nonexact match found. */ pfound = p; indfound = option_index; } else /* Second or later nonexact match found. */ ambig = 1; } if (ambig && !exact) { if (print_errors) fprintf (stderr, _("%s: option '-W %s' is ambiguous\n"), argv[0], argv[optind]); nextchar += strlen (nextchar); optind++; return '?'; } if (pfound != NULL) { option_index = indfound; if (*nameend) { /* Don't test has_arg with >, because some C compilers don't allow it to be used on enums. */ if (pfound->has_arg) optarg = nameend + 1; else { if (print_errors) fprintf (stderr, _("\ %s: option '-W %s' doesn't allow an argument\n"), argv[0], pfound->name); nextchar += strlen (nextchar); return '?'; } } else if (pfound->has_arg == 1) { if (optind < argc) optarg = argv[optind++]; else { if (print_errors) fprintf (stderr, _("%s: option '%s' requires an argument\n"), argv[0], argv[optind - 1]); nextchar += strlen (nextchar); return optstring[0] == ':' ? ':' : '?'; } } nextchar += strlen (nextchar); if (longind != NULL) *longind = option_index; if (pfound->flag) { *(pfound->flag) = pfound->val; return 0; } return pfound->val; } nextchar = NULL; return 'W'; /* Let the application handle it. */ } if (temp[1] == ':') { if (temp[2] == ':') { /* This is an option that accepts an argument optionally. */ if (*nextchar != '\0') { optarg = nextchar; optind++; } else optarg = NULL; nextchar = NULL; } else { /* This is an option that requires an argument. */ if (*nextchar != '\0') { optarg = nextchar; /* If we end this ARGV-element by taking the rest as an arg, we must advance to the next element now. */ optind++; } else if (optind == argc) { if (print_errors) { /* 1003.2 specifies the format of this message. */ fprintf (stderr, _("%s: option requires an argument -- %c\n"), argv[0], c); } optopt = c; if (optstring[0] == ':') c = ':'; else c = '?'; } else /* We already incremented `optind' once; increment it again when taking next ARGV-elt as argument. */ optarg = argv[optind++]; nextchar = NULL; } } return c; } } #endif /* Not ELIDE_CODE. */
{ "pile_set_name": "Github" }
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __gnu_classpath_jdwp_event_MethodEntryEvent__ #define __gnu_classpath_jdwp_event_MethodEntryEvent__ #pragma interface #include <gnu/classpath/jdwp/event/Event.h> extern "Java" { namespace gnu { namespace classpath { namespace jdwp { namespace event { class MethodEntryEvent; } namespace util { class Location; } } } } } class gnu::classpath::jdwp::event::MethodEntryEvent : public ::gnu::classpath::jdwp::event::Event { public: MethodEntryEvent(::java::lang::Thread *, ::gnu::classpath::jdwp::util::Location *, ::java::lang::Object *); virtual ::java::lang::Object * getParameter(jint); public: // actually protected virtual void _writeData(::java::io::DataOutputStream *); private: ::java::lang::Thread * __attribute__((aligned(__alignof__( ::gnu::classpath::jdwp::event::Event)))) _thread; ::gnu::classpath::jdwp::util::Location * _location; ::java::lang::Object * _instance; public: static ::java::lang::Class class$; }; #endif // __gnu_classpath_jdwp_event_MethodEntryEvent__
{ "pile_set_name": "Github" }
// eslint-disable // this is an auto generated file. This will be overwritten export const createUser = `mutation CreateUser($input: CreateUserInput!) { createUser(input: $input) { id username conversations { items { id convoLinkUserId convoLinkConversationId createdAt updatedAt } nextToken } messages { items { id authorId content messageConversationId createdAt updatedAt } nextToken } createdAt updatedAt } } `; export const updateUser = `mutation UpdateUser($input: UpdateUserInput!) { updateUser(input: $input) { id username conversations { items { id convoLinkUserId convoLinkConversationId createdAt updatedAt } nextToken } messages { items { id authorId content messageConversationId createdAt updatedAt } nextToken } createdAt updatedAt } } `; export const deleteUser = `mutation DeleteUser($input: DeleteUserInput!) { deleteUser(input: $input) { id username conversations { items { id convoLinkUserId convoLinkConversationId createdAt updatedAt } nextToken } messages { items { id authorId content messageConversationId createdAt updatedAt } nextToken } createdAt updatedAt } } `; export const createConvo = `mutation CreateConvo($input: CreateConversationInput!) { createConvo(input: $input) { id messages { items { id authorId content messageConversationId createdAt updatedAt } nextToken } associated { items { id convoLinkUserId convoLinkConversationId createdAt updatedAt } nextToken } name members createdAt updatedAt } } `; export const createMessage = `mutation CreateMessage($input: CreateMessageInput!) { createMessage(input: $input) { id author { id username conversations { nextToken } messages { nextToken } createdAt updatedAt } authorId content conversation { id messages { nextToken } associated { nextToken } name members createdAt updatedAt } messageConversationId createdAt updatedAt } } `; export const updateMessage = `mutation UpdateMessage($input: UpdateMessageInput!) { updateMessage(input: $input) { id author { id username conversations { nextToken } messages { nextToken } createdAt updatedAt } authorId content conversation { id messages { nextToken } associated { nextToken } name members createdAt updatedAt } messageConversationId createdAt updatedAt } } `; export const deleteMessage = `mutation DeleteMessage($input: DeleteMessageInput!) { deleteMessage(input: $input) { id author { id username conversations { nextToken } messages { nextToken } createdAt updatedAt } authorId content conversation { id messages { nextToken } associated { nextToken } name members createdAt updatedAt } messageConversationId createdAt updatedAt } } `; export const createConvoLink = `mutation CreateConvoLink($input: CreateConvoLinkInput!) { createConvoLink(input: $input) { id user { id username conversations { nextToken } messages { nextToken } createdAt updatedAt } convoLinkUserId conversation { id messages { nextToken } associated { nextToken } name members createdAt updatedAt } convoLinkConversationId createdAt updatedAt } } `; export const updateConvoLink = `mutation UpdateConvoLink($input: UpdateConvoLinkInput!) { updateConvoLink(input: $input) { id user { id username conversations { nextToken } messages { nextToken } createdAt updatedAt } convoLinkUserId conversation { id messages { nextToken } associated { nextToken } name members createdAt updatedAt } convoLinkConversationId createdAt updatedAt } } `;
{ "pile_set_name": "Github" }
// Copyright 2009 the Sputnik authors. All rights reserved. /** * String.prototype.match (regexp) * * @path ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A1_T6.js * @description Call match (regexp) function with x argument of new String object, where x is undefined variable */ var __matched = new String("undefined").match(x); var __expected = RegExp(x).exec("undefined"); ////////////////////////////////////////////////////////////////////////////// //CHECK#1 if (__matched.length !== __expected.length) { $ERROR('#1: __matched = new String("undefined").match(x); __expected = RegExp(x).exec("undefined"); __matched.length === __expected.length. Actual: '+__matched.length ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#2 if (__matched.index !== __expected.index) { $ERROR('#2: __matched = new String("undefined").match(x); __expected = RegExp(x).exec("undefined"); __matched.index === __expected.index. Actual: '+__matched.index ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#3 if (__matched.input !== __expected.input) { $ERROR('#3: __matched = new String("undefined").match(x); __expected = RegExp(x).exec("undefined"); __matched.input === __expected.input. Actual: '+__matched.input ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#4 for(var index=0; index<__expected.length; index++) { if (__matched[index]!==__expected[index]) { $ERROR('#4.'+index+': __matched = new String("undefined").match(x); __expected = RegExp(x).exec("undefined"); __matched['+index+']===__expected['+index+']. Actual: '+__matched[index]); } } // ////////////////////////////////////////////////////////////////////////////// var x;
{ "pile_set_name": "Github" }
<?xml version='1.0' encoding='UTF-8' ?> <!-- 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. --> <!ENTITY httpd.major "2"> <!ENTITY httpd.minor "5"> <!ENTITY httpd.patch "0"> <!ENTITY httpd.docs "trunk"> <!-- Version tag for comments --> <!ENTITY httpd.comments "trunk">
{ "pile_set_name": "Github" }
#include "AppDelegate.h" #include "GeneratedPluginRegistrant.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [GeneratedPluginRegistrant registerWithRegistry:self]; // Override point for customization after application launch. return [super application:application didFinishLaunchingWithOptions:launchOptions]; } @end
{ "pile_set_name": "Github" }
System.register([], function () { 'use strict'; return { execute: function () { var foo = () => 'foo'; // /* console.log(foo()); } }; });
{ "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. */ #include "fuse_dfs.h" #include "fuse_options.h" #include <getopt.h> #include "fuse_context_handle.h" void print_options() { fprintf(stderr,"options:\n"); fprintf(stderr, "\tprotected=%s\n",options.protected); fprintf(stderr, "\tserver=%s\n",options.server); fprintf(stderr, "\tport=%d\n",options.port); fprintf(stderr, "\tdebug=%d\n",options.debug); fprintf(stderr, "\tread_only=%d\n",options.read_only); fprintf(stderr, "\tusetrash=%d\n",options.usetrash); fprintf(stderr, "\tentry_timeout=%d\n",options.entry_timeout); fprintf(stderr, "\tattribute_timeout=%d\n",options.attribute_timeout); fprintf(stderr, "\tprivate=%d\n",options.private); fprintf(stderr, "\trdbuffer_size=%d (KBs)\n",(int)options.rdbuffer_size/1024); } const char *program; /** macro to define options */ #define DFSFS_OPT_KEY(t, p, v) { t, offsetof(struct options, p), v } void print_usage(const char *pname) { fprintf(stdout,"USAGE: %s [debug] [--help] [--version] [-oprotected=<colon_seped_list_of_paths] [rw] [-onotrash] [-ousetrash] [-obig_writes] [-oprivate (single user)] [ro] [-oserver=<hadoop_servername>] [-oport=<hadoop_port>] [-oentry_timeout=<secs>] [-oattribute_timeout=<secs>] [-odirect_io] [-onopoermissions] [-o<other fuse option>] <mntpoint> [fuse options]\n",pname); fprintf(stdout,"NOTE: debugging option for fuse is -debug\n"); } /** keys for FUSE_OPT_ options */ enum { KEY_VERSION, KEY_HELP, KEY_USETRASH, KEY_NOTRASH, KEY_RO, KEY_RW, KEY_PRIVATE, KEY_BIGWRITES, KEY_DEBUG, KEY_INITCHECKS, KEY_NOPERMISSIONS, KEY_DIRECTIO, }; struct fuse_opt dfs_opts[] = { DFSFS_OPT_KEY("server=%s", server, 0), DFSFS_OPT_KEY("entry_timeout=%d", entry_timeout, 0), DFSFS_OPT_KEY("attribute_timeout=%d", attribute_timeout, 0), DFSFS_OPT_KEY("protected=%s", protected, 0), DFSFS_OPT_KEY("port=%d", port, 0), DFSFS_OPT_KEY("rdbuffer=%d", rdbuffer_size,0), FUSE_OPT_KEY("private", KEY_PRIVATE), FUSE_OPT_KEY("ro", KEY_RO), FUSE_OPT_KEY("debug", KEY_DEBUG), FUSE_OPT_KEY("initchecks", KEY_INITCHECKS), FUSE_OPT_KEY("nopermissions", KEY_NOPERMISSIONS), FUSE_OPT_KEY("big_writes", KEY_BIGWRITES), FUSE_OPT_KEY("rw", KEY_RW), FUSE_OPT_KEY("usetrash", KEY_USETRASH), FUSE_OPT_KEY("notrash", KEY_NOTRASH), FUSE_OPT_KEY("direct_io", KEY_DIRECTIO), FUSE_OPT_KEY("-v", KEY_VERSION), FUSE_OPT_KEY("--version", KEY_VERSION), FUSE_OPT_KEY("-h", KEY_HELP), FUSE_OPT_KEY("--help", KEY_HELP), FUSE_OPT_END }; int dfs_options(void *data, const char *arg, int key, struct fuse_args *outargs) { (void) data; switch (key) { case FUSE_OPT_KEY_OPT: fprintf(stderr,"fuse-dfs ignoring option %s\n",arg); return 1; case KEY_VERSION: fprintf(stdout,"%s %s\n",program,_FUSE_DFS_VERSION); exit(0); case KEY_HELP: print_usage(program); exit(0); case KEY_USETRASH: options.usetrash = 1; break; case KEY_NOTRASH: options.usetrash = 1; break; case KEY_RO: options.read_only = 1; break; case KEY_RW: options.read_only = 0; break; case KEY_PRIVATE: options.private = 1; break; case KEY_DEBUG: fuse_opt_add_arg(outargs, "-d"); options.debug = 1; break; case KEY_INITCHECKS: options.initchecks = 1; break; case KEY_NOPERMISSIONS: options.no_permissions = 1; break; case KEY_DIRECTIO: options.direct_io = 1; break; case KEY_BIGWRITES: #ifdef FUSE_CAP_BIG_WRITES fuse_opt_add_arg(outargs, "-obig_writes"); #endif break; default: { // try and see if the arg is a URI for DFS int tmp_port; char tmp_server[1024]; if (!sscanf(arg,"dfs://%1024[a-zA-Z0-9_.-]:%d",tmp_server,&tmp_port)) { if (strcmp(arg,"ro") == 0) { options.read_only = 1; } else if (strcmp(arg,"rw") == 0) { options.read_only = 0; } else { fprintf(stderr,"fuse-dfs didn't recognize %s,%d\n",arg,key); fuse_opt_add_arg(outargs,arg); return 0; } } else { options.port = tmp_port; options.server = strdup(tmp_server); fprintf(stderr, "port=%d,server=%s\n", options.port, options.server); } } } return 0; }
{ "pile_set_name": "Github" }
# Translation of Odoo Server. # This file contains the translation of the following modules: # * im_livechat # # Translators: # Rodrigo de Almeida Sottomaior Macedo <rmsolucoeseminformatic4@gmail.com>, 2019 # danimaribeiro <danimaribeiro@gmail.com>, 2019 # Martin Trigaux, 2019 # Clemilton Clementino <clemylton@hotmail.com>, 2019 # Mateus Lopes <mateus1@gmail.com>, 2019 # Luiz Carlos de Lima <luiz.carlos@akretion.com.br>, 2019 # falexandresilva <falexandresilva@gmail.com>, 2019 # grazziano <gra.negocia@gmail.com>, 2019 # André Augusto Firmino Cordeiro <a.cordeito@gmail.com>, 2019 # Diego Bittencourt <diegomb86@gmail.com>, 2019 # Fernando Alencar <fernando@fernandoalencar.com.br>, 2019 # Lauro de Lima <lauro@ciclix.com>, 2019 # Fernanda Marques <fem@odoo.com>, 2020 # Luiz Fernando Gondin <lfpsgs@outlook.com>, 2020 # msgid "" msgstr "" "Project-Id-Version: Odoo Server saas~12.5\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2019-10-01 12:11+0000\n" "PO-Revision-Date: 2019-08-26 09:11+0000\n" "Last-Translator: Luiz Fernando Gondin <lfpsgs@outlook.com>, 2020\n" "Language-Team: Portuguese (Brazil) (https://www.transifex.com/odoo/teams/41243/pt_BR/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: \n" "Language: pt_BR\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_tree msgid "# Messages" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_operator__nbr_channel msgid "# of Sessions" msgstr "# de Sessões" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__nbr_speaker msgid "# of speakers" msgstr "# de participantes" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "% Happy" msgstr "% Feliz" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_channel_rule__action msgid "" "* 'Display the button' displays the chat button on the pages.\n" "* 'Auto popup' displays the button and automatically open the conversation pane.\n" "* 'Hide the button' hides the chat button on the pages." msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.livechat_email_template msgid ", on the" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_kanban msgid "<i class=\"fa fa-user\" role=\"img\" aria-label=\"User\" title=\"User\"/>" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "" "<span class=\"text-muted\">Define rules for your live support channel. You " "can apply an action for the given URL, and per country.<br/>To identify the " "country, GeoIP must be installed on your server, otherwise, the countries of" " the rule will not be taken into account.</span>" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.livechat_email_template msgid "<span style=\"font-size: 10px;\">Livechat Conversation</span><br/>" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.livechat_email_template msgid "<span>Best regards,</span><br/><br/>" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.livechat_email_template msgid "<span>Hello,</span><br/>Here's a copy of your conversation with" msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_report_channel__is_without_answer msgid "" "A session is without answer if the operator did not answer. \n" " If the visitor is also the operator, the session will always be answered." msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel_rule__action msgid "Action" msgstr "Ação" #. module: im_livechat #: model:res.groups,name:im_livechat.im_livechat_group_manager msgid "Administrator" msgstr "Administrador" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_form msgid "Anonymous" msgstr "Anônimo" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_mail_channel__anonymous_name msgid "Anonymous Name" msgstr "Nome do Visitante" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__are_you_inside msgid "Are you inside the matrix?" msgstr "Você está dentro da matrix?" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/js/im_livechat.js:0 #, python-format msgid "Ask something ..." msgstr "Pergunte algo ..." #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_form #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_tree msgid "Attendees" msgstr "Participantes" #. module: im_livechat #: model:ir.model.fields.selection,name:im_livechat.selection__im_livechat_channel_rule__action__auto_popup msgid "Auto popup" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel_rule__auto_popup_timer msgid "Auto popup timer" msgstr "" #. module: im_livechat #: model:ir.model,name:im_livechat.model_ir_autovacuum msgid "Automatic Vacuum" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_form msgid "Avatar" msgstr "Avatar" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__duration #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_operator__duration msgid "Average duration" msgstr "Média de duração" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__nbr_message msgid "Average message" msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_report_channel__time_to_answer msgid "Average time in seconds to give the first answer to the visitor" msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_report_operator__time_to_answer msgid "Average time to give the first answer to the visitor" msgstr "" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/xml/im_livechat.xml:0 #, python-format msgid "Bad" msgstr "Ruim" #. module: im_livechat #: model:ir.actions.act_window,name:im_livechat.im_livechat_canned_response_action #: model:ir.ui.menu,name:im_livechat.canned_responses msgid "Canned Responses" msgstr "" #. module: im_livechat #: model_terms:ir.actions.act_window,help:im_livechat.im_livechat_canned_response_action msgid "" "Canned responses allow you to insert prewritten responses in\n" " your messages by typing <i>:shortcut</i>. The shortcut is\n" " replaced directly in your message, so that you can still edit\n" " it before sending." msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel_rule__channel_id #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__livechat_channel_id #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_operator__livechat_channel_id #: model:ir.model.fields,field_description:im_livechat.field_mail_channel__livechat_channel_id #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_kanban #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_search #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_channel_view_search #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_operator_view_search #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_search msgid "Channel" msgstr "Canal" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__channel_name msgid "Channel Name" msgstr "Nome do Canal" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_rule_view_form msgid "Channel Rule" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "Channel Rules" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_mail_channel__channel_type msgid "Channel Type" msgstr "Tipo de Canal" #. module: im_livechat #: model:ir.ui.menu,name:im_livechat.support_channels msgid "Channels" msgstr "Canais" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__input_placeholder msgid "Chat Input Placeholder" msgstr "Espaço para Digitar no Chat" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/js/im_livechat.js:0 #, python-format msgid "Chat with one of our collaborators" msgstr "Converse com um de nossos colaboradores" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/xml/im_livechat.xml:0 #, python-format msgid "Close conversation" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__technical_name #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_channel_view_search #: model_terms:ir.ui.view,arch_db:im_livechat.rating_rating_view_search_livechat msgid "Code" msgstr "Código" #. module: im_livechat #: model:ir.ui.menu,name:im_livechat.livechat_config msgid "Configuration" msgstr "Configuração" #. module: im_livechat #: model:ir.model,name:im_livechat.model_res_partner msgid "Contact" msgstr "Contato" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__channel_id #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_operator__channel_id msgid "Conversation" msgstr "Conversação" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/js/im_livechat.js:0 #, python-format msgid "Conversation Sent" msgstr "" #. module: im_livechat #: code:addons/im_livechat/models/mail_channel.py:0 #, python-format msgid "Conversation with %s" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "" "Copy and paste this code into your website, within the &lt;head&gt; tag:" msgstr "" "Copie e cole este código em seu website, dentro do marcador &lt;head&gt; :" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel_rule__country_ids #: model:ir.model.fields,field_description:im_livechat.field_mail_channel__country_id msgid "Country" msgstr "País" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__country_id msgid "Country of the visitor" msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_mail_channel__country_id msgid "Country of the visitor of the channel" msgstr "" #. module: im_livechat #: model_terms:ir.actions.act_window,help:im_livechat.mail_channel_action msgid "Create a channel and start chatting to fill up your history." msgstr "" #. module: im_livechat #: model_terms:ir.actions.act_window,help:im_livechat.im_livechat_canned_response_action msgid "Create a new canned response" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__create_uid #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel_rule__create_uid msgid "Created by" msgstr "Criado por" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__create_date #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel_rule__create_date msgid "Created on" msgstr "Criado em" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_search msgid "Creation Date" msgstr "Data de Criação" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_channel_view_search #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_operator_view_search msgid "Creation date" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_channel_view_search msgid "Creation date (hour)" msgstr "Data de criação (hora)" #. module: im_livechat #: model:ir.actions.act_window,name:im_livechat.rating_rating_action_livechat_report #: model:ir.ui.menu,name:im_livechat.rating_rating_menu_livechat msgid "Customer Ratings" msgstr "Avaliações de Clientes" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__day_number msgid "Day Number" msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_report_channel__day_number msgid "Day number of the session (1 is Monday, 7 is Sunday)" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__days_of_activity msgid "Days of activity" msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_channel__button_text msgid "Default text displayed on the Livechat Support Button" msgstr "Texto padrão exibido no botão de suporte do Livechat" #. module: im_livechat #: model_terms:ir.actions.act_window,help:im_livechat.im_livechat_channel_action msgid "Define a new website live chat channel" msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_channel_rule__auto_popup_timer msgid "" "Delay (in seconds) to automatically open the conversation window. Note: the " "selected action must be 'Auto popup' otherwise this parameter will not be " "taken into account." msgstr "" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/xml/im_livechat.xml:0 #, python-format msgid "Did we correctly answer your question ?" msgstr "Como você avalia o seu atendimento?" #. module: im_livechat #: model:ir.model,name:im_livechat.model_mail_channel msgid "Discussion Channel" msgstr "Canal de Discussão" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__display_name #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel_rule__display_name #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__display_name #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_operator__display_name msgid "Display Name" msgstr "Nome exibido" #. module: im_livechat #: model:ir.model.fields.selection,name:im_livechat.selection__im_livechat_channel_rule__action__display_button msgid "Display the button" msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_report_channel__duration #: model:ir.model.fields,help:im_livechat.field_im_livechat_report_operator__duration msgid "Duration of the conversation (in seconds)" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_search msgid "Empty Sessions" msgstr "" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/xml/im_livechat.xml:0 #, python-format msgid "Explain your note" msgstr "Explique suas anotações" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "" "For websites built with the Odoo CMS, go to Website &gt; Configuration &gt; " "Settings and select the Website Live Chat Channel you want to add on your " "website." msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_channel_rule__sequence msgid "" "Given the order to find a matching rule. If 2 rules are matching for the " "given url/country, the one with the lowest sequence will be chosen." msgstr "" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/xml/im_livechat.xml:0 #, python-format msgid "Good" msgstr "Bom" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_channel_view_search #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_operator_view_search #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_search msgid "Group By..." msgstr "Agrupar por..." #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_kanban msgid "Happy face" msgstr "" #. module: im_livechat #: model:ir.model.fields.selection,name:im_livechat.selection__im_livechat_channel_rule__action__hide_button msgid "Hide the button" msgstr "Esconder o botão" #. module: im_livechat #: model:ir.actions.act_window,name:im_livechat.mail_channel_action #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_form #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_tree msgid "History" msgstr "Histórico" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__start_date_hour msgid "Hour of start Date of session" msgstr "Data e Hora do início da sessão" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/js/im_livechat.js:0 #, python-format msgid "How may I help you?" msgstr "Como posso ajudá-lo?" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "How to use the Website Live Chat widget?" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__id #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel_rule__id #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__id #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_operator__id msgid "ID" msgstr "ID" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__image_128 msgid "Image" msgstr "Imagem" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/js/im_livechat.js:0 #, python-format msgid "Invalid email address" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__is_anonymous msgid "Is visitor anonymous" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_kanban msgid "Join" msgstr "Entrar" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "Join Channel" msgstr "Entrar em um canal" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_channel_view_search #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_operator_view_search msgid "Last 24h" msgstr "Últimas 24h" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel____last_update #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel_rule____last_update #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel____last_update #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_operator____last_update msgid "Last Modified on" msgstr "Última modificação em" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__write_uid #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel_rule__write_uid msgid "Last Updated by" msgstr "Última atualização por" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__write_date #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel_rule__write_date msgid "Last Updated on" msgstr "Última atualização em" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_kanban msgid "Leave" msgstr "Sair" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "Leave Channel" msgstr "Sair do Canal" #. module: im_livechat #: model:ir.model,name:im_livechat.model_mail_channel_partner msgid "Listeners of a Channel" msgstr "" #. module: im_livechat #: model:ir.module.category,name:im_livechat.module_category_im_livechat #: model:ir.ui.menu,name:im_livechat.menu_livechat_root msgid "Live Chat" msgstr "Live Chat" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_search msgid "LiveChat Channel Search" msgstr "" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/xml/im_livechat_backend.xml:0 #: code:addons/im_livechat/static/src/xml/im_livechat_backend.xml:0 #: model_terms:ir.ui.view,arch_db:im_livechat.res_users_form_view #, python-format msgid "Livechat" msgstr "Chat" #. module: im_livechat #: model:ir.model,name:im_livechat.model_im_livechat_channel #: model_terms:ir.ui.view,arch_db:im_livechat.rating_rating_view_search_livechat msgid "Livechat Channel" msgstr "Canal de Chat" #. module: im_livechat #: model:ir.model,name:im_livechat.model_im_livechat_channel_rule msgid "Livechat Channel Rules" msgstr "" #. module: im_livechat #: model:ir.model.fields.selection,name:im_livechat.selection__mail_channel__channel_type__livechat msgid "Livechat Conversation" msgstr "Conversa Ao Vivo" #. module: im_livechat #: model:ir.model.constraint,message:im_livechat.constraint_mail_channel_livechat_operator_id msgid "Livechat Operator ID is required for a channel of type livechat." msgstr "" #. module: im_livechat #: model:ir.model,name:im_livechat.model_im_livechat_report_channel msgid "Livechat Support Channel Report" msgstr "" #. module: im_livechat #: model_terms:ir.actions.act_window,help:im_livechat.im_livechat_report_channel_action #: model_terms:ir.actions.act_window,help:im_livechat.im_livechat_report_operator_action msgid "" "Livechat Support Channel Statistics allows you to easily check and analyse " "your company livechat session performance. Extract information about the " "missed sessions, the audiance, the duration of a session, etc." msgstr "" #. module: im_livechat #: model:ir.model,name:im_livechat.model_im_livechat_report_operator msgid "Livechat Support Operator Report" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_channel_view_graph #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_channel_view_pivot #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_operator_view_graph #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_operator_view_pivot msgid "Livechat Support Statistics" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_res_users__livechat_username msgid "Livechat Username" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel_rule__sequence msgid "Matching order" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_channel_view_search msgid "Missed sessions" msgstr "Sessões obsoletas" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__name msgid "Name" msgstr "Nome" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_kanban msgid "Neutral face" msgstr "" #. module: im_livechat #: model_terms:ir.actions.act_window,help:im_livechat.rating_rating_action_livechat_report msgid "No customer ratings on live chat session yet" msgstr "" #. module: im_livechat #: code:addons/im_livechat/models/mail_channel.py:0 #, python-format msgid "No history found" msgstr "Histórico não encontrado" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/js/im_livechat.js:0 #, python-format msgid "" "None of our collaborators seem to be available, please try again later." msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__nbr_channel #: model:ir.model.fields,help:im_livechat.field_im_livechat_report_operator__nbr_channel msgid "Number of conversation" msgstr "Número de conversas" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_report_channel__days_of_activity msgid "Number of days since the first session of the operator" msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_report_channel__nbr_speaker msgid "Number of different speakers" msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_report_channel__nbr_message msgid "Number of message in the conversation" msgstr "" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/xml/im_livechat.xml:0 #, python-format msgid "OK" msgstr "OK" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.livechat_email_template msgid "Odoo" msgstr "Odoo" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.res_users_form_view_simple_modif msgid "Online Chat Name" msgstr "" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/xml/im_livechat.xml:0 #, python-format msgid "Oops! Something went wrong." msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__partner_id #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_operator__partner_id #: model:ir.model.fields,field_description:im_livechat.field_mail_channel__livechat_operator_id #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_channel_view_search #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_operator_view_search msgid "Operator" msgstr "Operador" #. module: im_livechat #: model:ir.actions.act_window,name:im_livechat.im_livechat_report_operator_action #: model:ir.ui.menu,name:im_livechat.menu_reporting_livechat_operator msgid "Operator Analysis" msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_mail_channel__livechat_operator_id msgid "Operator for this specific channel" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__user_ids #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "Operators" msgstr "Operadores" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_kanban msgid "" "Operators\n" " <br/>\n" " <i class=\"fa fa-comments\" role=\"img\" aria-label=\"Comments\" title=\"Comments\"/>" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "" "Operators that do not show any activity In Odoo for more than 30 minutes " "will be considered as disconnected." msgstr "" "Os operadores que não mostrarem nenhuma atividade no Odoo por mais de 30 " "minutos serão considerados como desconectados." #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "Options" msgstr "Opções" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_channel__rating_percentage_satisfaction msgid "Percentage of happy ratings" msgstr "Percentual de Pontuações positivas" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/xml/im_livechat.xml:0 #, python-format msgid "Please check your internet connection." msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.livechat_email_template msgid "Powered by" msgstr "Desenvolvido por" #. module: im_livechat #: model:ir.model,name:im_livechat.model_rating_rating #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__rating #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_tree msgid "Rating" msgstr "Classificação" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__rating_percentage_satisfaction msgid "Rating Satisfaction" msgstr "Pontuação da Satisfação" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/js/im_livechat.js:0 #, python-format msgid "Rating: %s" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_kanban msgid "Rating: Bad" msgstr "Classificação: Ruim" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_kanban msgid "Rating: Great" msgstr "Classificação: Ótimo" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_kanban msgid "Rating: Okay" msgstr "Classificação: Ok" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__rating_ids msgid "Ratings" msgstr "Avaliações" #. module: im_livechat #: model:ir.actions.act_window,name:im_livechat.rating_rating_action_view_livechat_rating msgid "Ratings for livechat channel" msgstr "Classificações do chat" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/xml/im_livechat.xml:0 #, python-format msgid "Receive a copy of this conversation" msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_channel_rule__regex_url msgid "" "Regular expression specifying the web pages this rule will be applied on." msgstr "" "Expressão regular especificando as páginas da web em que esta regra será " "aplicada." #. module: im_livechat #: model:ir.ui.menu,name:im_livechat.menu_reporting_livechat msgid "Report" msgstr "Relatório" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__rule_ids #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_rule_view_tree msgid "Rules" msgstr "Regras" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_kanban msgid "Sad face" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__rating_text msgid "Satisfaction Rate" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "Save your Channel to get your configuration widget." msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__script_external msgid "Script (external)" msgstr "Script (externol)" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_search msgid "Search history" msgstr "Procurar no histórico" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_channel_view_search #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_operator_view_search msgid "Search report" msgstr "Procurar no relatório" #. module: im_livechat #: code:addons/im_livechat/models/mail_channel.py:0 #, python-format msgid "See 15 last visited pages" msgstr "Ver as ultimas 15 páginas visitadas" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_form #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_tree msgid "Session Date" msgstr "Data da Sessão" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_form msgid "Session Form" msgstr "Formulário da Sessão" #. module: im_livechat #: model:ir.actions.act_window,name:im_livechat.im_livechat_report_channel_action #: model:ir.ui.menu,name:im_livechat.menu_reporting_livechat_channel msgid "Session Statistics" msgstr "Estatísticas da Sessão" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__is_unrated msgid "Session not rated" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__is_without_answer msgid "Session(s) without answer" msgstr "" #. module: im_livechat #: model:ir.actions.act_window,name:im_livechat.mail_channel_action_from_livechat_channel #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__channel_ids #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_kanban msgid "Sessions" msgstr "Sessões" #. module: im_livechat #: model:ir.ui.menu,name:im_livechat.session_history msgid "Sessions History" msgstr "Histórico da Sessão" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__start_date #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_operator__start_date msgid "Start Date of session" msgstr "Data de início da sessão" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__start_hour msgid "Start Hour of session" msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_report_channel__start_date #: model:ir.model.fields,help:im_livechat.field_im_livechat_report_operator__start_date msgid "Start date of the conversation" msgstr "Data de início da conversa" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_report_channel__start_hour msgid "Start hour of the conversation" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__button_text msgid "Text of the Button" msgstr "Texto do Botão" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_channel__input_placeholder msgid "Text that prompts the user to initiate the chat." msgstr "" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/js/im_livechat.js:0 #, python-format msgid "Thank you for your feedback" msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_channel_rule__channel_id msgid "The channel of the rule" msgstr "Canal moderador" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_channel__name msgid "The name of the channel" msgstr "O nome do canal" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_channel_rule__country_ids msgid "" "The rule will only be applied for these countries. Example: if you select " "'Belgium' and 'United States' and that you set the action to 'Hide Button', " "the chat button will be hidden on the specified URL from the visitors " "located in these 2 countries. This feature requires GeoIP installed on your " "server." msgstr "" #. module: im_livechat #: model:res.groups,comment:im_livechat.im_livechat_group_manager msgid "The user will be able to delete support channels." msgstr "O usuário poderá excluir canais de suporte." #. module: im_livechat #: model:res.groups,comment:im_livechat.im_livechat_group_user msgid "The user will be able to join support channels." msgstr "O usuário poderá se juntar aos canais de suporte." #. module: im_livechat #: model_terms:ir.actions.act_window,help:im_livechat.rating_rating_action_view_livechat_rating msgid "There is no rating for this channel at the moment" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_channel_view_search #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_operator_view_search #: model_terms:ir.ui.view,arch_db:im_livechat.rating_rating_view_search_livechat msgid "This Week" msgstr "Esta Semana" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_channel__default_message msgid "" "This is an automated 'welcome' message that your visitor will see when they " "initiate a new conversation." msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_res_users__livechat_username msgid "This username will be used as your name in the livechat channels." msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_operator__time_to_answer msgid "Time to answer" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__time_to_answer msgid "Time to answer (sec)" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_report_channel_view_search msgid "Treated sessions" msgstr "" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/xml/im_livechat.xml:0 #, python-format msgid "Try again" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel_rule__regex_url msgid "URL Regex" msgstr "" #. module: im_livechat #: model:ir.model.fields,help:im_livechat.field_im_livechat_channel__web_page msgid "" "URL to a static page where you client can discuss with the operator of the " "channel." msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__uuid msgid "UUID" msgstr "UUID" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form #: model:res.groups,name:im_livechat.im_livechat_group_user msgid "User" msgstr "Usuário" #. module: im_livechat #: model:ir.model,name:im_livechat.model_res_users msgid "Users" msgstr "Usuários" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/controllers/main.py:0 #: code:addons/im_livechat/models/mail_channel.py:0 #: code:addons/im_livechat/static/src/js/im_livechat.js:0 #, python-format msgid "Visitor" msgstr "Visitante" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_report_channel__is_happy msgid "Visitor is Happy" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__web_page msgid "Web Page" msgstr "Página da web" #. module: im_livechat #: model:ir.actions.act_window,name:im_livechat.im_livechat_channel_action msgid "Website Live Chat Channels" msgstr "" #. module: im_livechat #: model:ir.model.fields,field_description:im_livechat.field_im_livechat_channel__default_message msgid "Welcome Message" msgstr "Mensagem de Boas Vindas" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "Widget" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.mail_channel_view_search msgid "With Messages" msgstr "" #. module: im_livechat #: model_terms:ir.actions.act_window,help:im_livechat.im_livechat_channel_action msgid "" "You can create channels for each website on which you want\n" " to integrate the website live chat widget, allowing your website\n" " visitors to talk in real time with your operators." msgstr "" #. module: im_livechat #: model_terms:ir.actions.act_window,help:im_livechat.mail_channel_action msgid "Your chatter history is empty" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_rule_view_form msgid "e.g. /page/contactus" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "e.g. Hello, how may I help you?" msgstr "ex. Olá, como posso ajudar?" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "e.g. YourWebsite.com" msgstr "ex. seusite.com.br" #. module: im_livechat #. openerp-web #: code:addons/im_livechat/static/src/xml/im_livechat.xml:0 #, python-format msgid "mail@example.com" msgstr "" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_view_form msgid "or copy this url and send it by email to your customers or suppliers:" msgstr "" "ou copie e cole esta url e envie para e-mail para seus clientes ou " "fornecedores:" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.im_livechat_channel_rule_view_form msgid "seconds" msgstr "segundos" #. module: im_livechat #: model_terms:ir.ui.view,arch_db:im_livechat.livechat_email_template msgid "{{author_name}}" msgstr ""
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <title>OSM Buildings Classic for OpenLayers</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.2.1/css/ol.css"/> <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.2.1/build/ol.js"></script> <link rel="stylesheet" href="OSMBuildings.css"> <script src="OSMBuildings-OpenLayers.debug.js"></script> <style> html, body { border: 0; margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; } #map { height: 100%; } </style> </head> <body> <div id="map"></div> <script> const map = new ol.Map({ target: 'map', layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], view: new ol.View({ center: ol.proj.fromLonLat([52.52179, 13.39503]), // Berlin // center: ol.proj.fromLonLat([40.711516, -74.011695]), // NYC zoom: 16 }) }); const osmb = new OSMBuildings(); osmb.addTo(map) .date(new Date(2017, 5, 15, 17, 30)) .load() .click(function(e) { console.log('feature clicked:', e); }); // // GeoJSON // // map.setView([52.52179, 13.39503], 18); // Berlin Bodemuseum // // const data = {"type":"FeatureCollection","features":[{"type":"Feature","properties":{"id":1,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.388652,52.520222],[13.388758,52.52021],[13.389204,52.520184],[13.389735,52.520162],[13.390013,52.52015],[13.390153,52.520155],[13.391974,52.520274],[13.392177,52.52029],[13.392477,52.520319],[13.392728,52.520355],[13.393062,52.520414],[13.393416,52.520505],[13.393754,52.520615],[13.394054,52.52073],[13.394226,52.520811],[13.394393,52.520678],[13.394217,52.520597],[13.393905,52.520471],[13.39355,52.52036],[13.393176,52.520268],[13.392811,52.520205],[13.392527,52.520169],[13.392209,52.52014],[13.392006,52.520122],[13.39025,52.520002],[13.390123,52.519993],[13.389317,52.519947],[13.38872,52.5199],[13.388693,52.520002],[13.388652,52.520222]]]]}},{"type":"Feature","properties":{"id":2,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.392946,52.521681],[13.393053,52.521847],[13.393228,52.52174],[13.393363,52.521645],[13.393499,52.521549],[13.393439,52.521523],[13.394023,52.521095],[13.39398,52.521074],[13.394229,52.520907],[13.394066,52.520818],[13.3938,52.521001],[13.393842,52.521027],[13.393242,52.521434],[13.393285,52.52146],[13.392946,52.521681]]]]}},{"type":"Feature","properties":{"id":3,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.393432,52.521863],[13.39371,52.522017],[13.393874,52.521918],[13.393605,52.521756],[13.393432,52.521863]]]]}},{"type":"Feature","properties":{"id":4,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.394871,52.520148],[13.395216,52.52032],[13.395544,52.520072],[13.395374,52.519995],[13.395111,52.519962],[13.394871,52.520148]],[[13.395008,52.520144],[13.395124,52.520049],[13.395292,52.520078],[13.395128,52.520203],[13.395008,52.520144]]]]}},{"type":"Feature","properties":{"id":5,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.393699,52.5202],[13.393927,52.520312],[13.394052,52.520218],[13.393866,52.520126],[13.393746,52.520074],[13.393699,52.5202]]]]}},{"type":"Feature","properties":{"id":6,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.393746,52.520074],[13.393866,52.520126],[13.393871,52.520081],[13.393889,52.520073],[13.393872,52.520056],[13.393903,52.519975],[13.393926,52.519965],[13.394501,52.52004],[13.394479,52.520103],[13.394162,52.520083],[13.394151,52.520148],[13.394319,52.520157],[13.394526,52.520168],[13.394555,52.520146],[13.394623,52.520095],[13.394679,52.520052],[13.394803,52.519958],[13.393834,52.519838],[13.39382,52.519876],[13.393795,52.519942],[13.393746,52.520074]]]]}},{"type":"Feature","properties":{"id":7,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.393867,52.522186],[13.394056,52.522516],[13.394296,52.522483],[13.394093,52.522153],[13.393867,52.522186]]]]}},{"type":"Feature","properties":{"id":9,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.393927,52.520312],[13.394078,52.520388],[13.394206,52.520294],[13.394157,52.52027],[13.394052,52.520218],[13.393927,52.520312]]]]}},{"type":"Feature","properties":{"id":10,"height":15},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.393996,52.521925],[13.394018,52.521993],[13.394044,52.522027],[13.394071,52.522054],[13.394154,52.522098],[13.394256,52.522118],[13.394314,52.522121],[13.394502,52.5221],[13.395601,52.52198],[13.395597,52.521963],[13.396059,52.521915],[13.396104,52.521876],[13.396091,52.521831],[13.396035,52.521803],[13.396074,52.521771],[13.394912,52.5212],[13.394077,52.521797],[13.394017,52.521856],[13.393996,52.521925]],[[13.394702,52.521541],[13.394743,52.521509],[13.394794,52.521506],[13.394905,52.521429],[13.394904,52.521409],[13.394881,52.521396],[13.39493,52.521361],[13.395228,52.52151],[13.394873,52.521627],[13.394702,52.521541]],[[13.395524,52.521723],[13.395602,52.521715],[13.395599,52.521701],[13.395618,52.521686],[13.395741,52.521749],[13.395765,52.521837],[13.395565,52.521854],[13.395524,52.521723]],[[13.395005,52.521779],[13.395327,52.521666],[13.395382,52.521847],[13.39504,52.521885],[13.395005,52.521779]],[[13.394604,52.521879],[13.394829,52.5218],[13.394869,52.521931],[13.394676,52.521955],[13.394604,52.521879]],[[13.394447,52.521727],[13.394577,52.521638],[13.394742,52.521724],[13.394526,52.521798],[13.394447,52.521727]]]]}},{"type":"Feature","properties":{"id":11,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.394078,52.520388],[13.394369,52.520531],[13.394497,52.520438],[13.394299,52.52034],[13.394206,52.520294],[13.394078,52.520388]]]]}},{"type":"Feature","properties":{"id":12,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.394157,52.52027],[13.394206,52.520294],[13.394299,52.52034],[13.39443,52.52024],[13.394515,52.520176],[13.394526,52.520168],[13.394319,52.520157],[13.394157,52.52027]]]]}},{"type":"Feature","properties":{"id":13,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.394226,52.520811],[13.394532,52.520957],[13.394655,52.521015],[13.394965,52.521163],[13.395059,52.521209],[13.395088,52.521188],[13.395121,52.521163],[13.395168,52.521128],[13.395212,52.521095],[13.395247,52.52107],[13.395151,52.521027],[13.394841,52.520884],[13.394711,52.520824],[13.394393,52.520678],[13.394226,52.520811]]]]}},{"type":"Feature","properties":{"id":14,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.394369,52.520531],[13.394712,52.5207],[13.39488,52.520574],[13.394708,52.520488],[13.394665,52.520521],[13.394497,52.520438],[13.394369,52.520531]]]]}},{"type":"Feature","properties":{"id":16,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.39443,52.52024],[13.394793,52.520423],[13.394708,52.520488],[13.39488,52.520574],[13.395053,52.520443],[13.394515,52.520176],[13.39443,52.52024]]]]}},{"type":"Feature","properties":{"id":17,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.394515,52.520176],[13.395053,52.520443],[13.395216,52.52032],[13.394871,52.520148],[13.394803,52.520114],[13.394735,52.52008],[13.394679,52.520052],[13.394623,52.520095],[13.395003,52.520284],[13.39495,52.520323],[13.39476,52.520228],[13.394744,52.52024],[13.394555,52.520146],[13.394526,52.520168],[13.394515,52.520176]]]]}},{"type":"Feature","properties":{"id":19,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.394585,52.521048],[13.394595,52.521053],[13.394614,52.52104],[13.394604,52.521034],[13.394585,52.521048]]]]}},{"type":"Feature","properties":{"id":20,"height":null},"geometry":{"type":"MultiPolygon","coordinates":[[[[13.394679,52.520052],[13.394735,52.52008],[13.394811,52.520019],[13.394902,52.520034],[13.394803,52.520114],[13.394871,52.520148],[13.395111,52.519962],[13.394842,52.519929],[13.394803,52.519958],[13.394679,52.520052]]]]}}]}; // // const osmb = new OSMBuildings(map).set(data); </script> </body> </html>
{ "pile_set_name": "Github" }
/* ======================================================================== * Bootstrap: alert.js v3.3.6 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.VERSION = '3.3.6' Alert.TRANSITION_DURATION = 150 Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.closest('.alert') } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { // detach from parent, fire event then clean up data $parent.detach().trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one('bsTransitionEnd', removeElement) .emulateTransitionEnd(Alert.TRANSITION_DURATION) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery);
{ "pile_set_name": "Github" }
ADD_SUBDIRECTORY(src) ADD_SUBDIRECTORY(ADM_hwAccelEncoder)
{ "pile_set_name": "Github" }
/*-----------------------------------------------------------------------------+ Copyright (c) 2010-2010: Joachim Faulhaber +------------------------------------------------------------------------------+ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENCE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +-----------------------------------------------------------------------------*/ #ifndef BOOST_ICL_ASSOCIATIVE_ELEMENT_CONTAINER_HPP_JOFA_101023 #define BOOST_ICL_ASSOCIATIVE_ELEMENT_CONTAINER_HPP_JOFA_101023 #include <boost/icl/detail/map_algo.hpp> #include <boost/icl/concept/comparable.hpp> #include <boost/icl/concept/container.hpp> #include <boost/icl/concept/element_set.hpp> #include <boost/icl/concept/element_map.hpp> #include <boost/icl/concept/element_associator.hpp> #endif
{ "pile_set_name": "Github" }
# safeguard against accidental misuse if(NOT WINDOWS) message(FATAL_ERROR "decklink for Windows only!") endif(NOT WINDOWS) set(PLUGIN_NAME decklink) add_custom_command( OUTPUT "${CMAKE_CURRENT_SOURCE_DIR}/include/DeckLinkAPI_h.h" "${CMAKE_CURRENT_SOURCE_DIR}/DeckLinkAPI_i.c" COMMAND midl.exe /D _DEBUG /W1 /nologo /char signed /env x64 /iid ${CMAKE_CURRENT_SOURCE_DIR}/DeckLinkAPI_i.c /h "${CMAKE_CURRENT_SOURCE_DIR}/DeckLinkAPI_h.h" /tlb "${VS_VAHANA_PLUGIN_DIR}/decklink.tlb" "${DECKLINK_PATH}\\DeckLinkAPI.idl" ) set(SOURCE_FILES src/export.cpp src/decklink_helpers.cpp src/decklink_writer.cpp src/decklink_discovery.cpp src/decklink_reader.cpp ${CMAKE_CURRENT_SOURCE_DIR}/DeckLinkAPI_i.c ) set(HEADER_FILES include/decklink_helpers.hpp include/decklink_writer.hpp include/decklink_discovery.hpp include/decklink_reader.hpp ) vs_add_IO_library(${PLUGIN_NAME} SHARED ${SOURCE_FILES} ${HEADER_FILES} $<TARGET_OBJECTS:common>) include_lib_vs_headers(${PLUGIN_NAME}) include_discovery_vs_headers(${PLUGIN_NAME}) target_include_directories(${PLUGIN_NAME} PRIVATE include) target_include_directories(${PLUGIN_NAME} PRIVATE .) # NOTE: L23 was added as a quick fix. # @w-m: It's related to giving MIDL a path for /h instead of just a filename, # so the create source file will include <include/DeckLinkAPI_h.h> or something. # Maybe the MIDL command can be fixed to put the header in include/DeckLinkAPI_h.h # but only reference DeckLinkAPI_h.h? Then the search path should be fine. target_include_directories(${PLUGIN_NAME} PRIVATE ../common/include) set_property(TARGET ${PLUGIN_NAME} PROPERTY CXX_STANDARD 14) link_target_to_libvideostitch(${PLUGIN_NAME}) target_compile_definitions(${PLUGIN_NAME} PRIVATE NOMINMAX _USE_MATH_DEFINES) target_link_libraries(${PLUGIN_NAME} PRIVATE ${VS_DISCOVERY})
{ "pile_set_name": "Github" }
.data .globl words .align 4 .type words,@object words: .long 1 .long 2 .long 3 .byte 105 .byte 102 .byte 0 .space 3 .space 2 .long 4 .long 5 .space 4 .byte 102 .byte 111 .byte 114 .space 3 .space 2 .long 6 .long 7 .long 8 .byte 101 .byte 108 .byte 115 .byte 101 .byte 0 .space 1 .space 2 .long 9 .long 10 .long 11 .byte 119 .byte 104 .byte 105 .byte 108 .byte 101 .space 1 .space 2 .long 0 .space 8 .space 8 .size words,100 .globl wordlist .align 4 .type wordlist,@object .size wordlist,4 wordlist: .long words .globl x .align 4 .type x,@object x: .long 1 .long 2 .long 3 .long 4 .long 0 .long 5 .long 6 .space 12 .long 7 .space 16 .size x,60 .globl y .align 4 .type y,@object y: .long x .long x+20 .long x+40 .long 0 .size y,16 .globl main .text .align 16 .type main,@function main: pushl %ebp pushl %ebx pushl %esi pushl %edi movl %esp,%ebp subl $8,%esp movl $0,-8(%ebp) jmp .LC8 .LC5: movl $0,-4(%ebp) jmp .LC12 .LC9: movl -4(%ebp),%edi movl -8(%ebp),%esi movl y(,%esi,4),%esi pushl (%esi,%edi,4) pushl $.LC13 call printf addl $8,%esp .LC10: incl -4(%ebp) .LC12: movl -4(%ebp),%edi movl -8(%ebp),%esi movl y(,%esi,4),%esi cmpl $0,(%esi,%edi,4) jne .LC9 pushl $.LC14 call printf addl $4,%esp .LC6: incl -8(%ebp) .LC8: movl -8(%ebp),%edi movl y(,%edi,4),%edi cmpl $0,%edi jne .LC5 call f pushl wordlist call g addl $4,%esp mov $0,%eax .LC4: movl %ebp,%esp popl %edi popl %esi popl %ebx popl %ebp ret .Lf15: .size main,.Lf15-main .data .align 4 .type keywords.17,@object keywords.17: .long .LC18 .long .LC19 .long .LC20 .long .LC21 .long 0 .size keywords.17,20 .globl f .text .align 16 .type f,@function f: pushl %ebp pushl %ebx pushl %esi pushl %edi movl %esp,%ebp subl $4,%esp leal keywords.17,%edi movl %edi,-4(%ebp) jmp .LC25 .LC22: movl -4(%ebp),%edi pushl (,%edi) pushl $.LC26 call printf addl $8,%esp .LC23: movl -4(%ebp),%edi leal 4(%edi),%edi movl %edi,-4(%ebp) .LC25: movl -4(%ebp),%edi movl (,%edi),%edi cmpl $0,%edi jne .LC22 mov $0,%eax .LC16: movl %ebp,%esp popl %edi popl %esi popl %ebx popl %ebp ret .Lf27: .size f,.Lf27-f .globl g .align 16 .type g,@function g: pushl %ebp pushl %ebx pushl %esi pushl %edi movl %esp,%ebp subl $4,%esp jmp .LC32 .LC29: movl $0,-4(%ebp) jmp .LC36 .LC33: movl -4(%ebp),%edi movl 20(%ebp),%esi pushl (%esi,%edi,4) pushl $.LC37 call printf addl $8,%esp .LC34: incl -4(%ebp) .LC36: movl -4(%ebp),%edi cmpl $3,%edi jb .LC33 movl 20(%ebp),%edi leal 12(%edi),%edi pushl %edi pushl $.LC26 call printf addl $8,%esp .LC30: movl 20(%ebp),%edi leal 20(%edi),%edi movl %edi,20(%ebp) .LC32: movl 20(%ebp),%edi cmpl $0,(,%edi) jne .LC29 call h mov $0,%eax .LC28: movl %ebp,%esp popl %edi popl %esi popl %ebx popl %ebp ret .Lf38: .size g,.Lf38-g .globl h .align 16 .type h,@function h: pushl %ebp pushl %ebx pushl %esi pushl %edi movl %esp,%ebp subl $4,%esp movl $0,-4(%ebp) jmp .LC43 .LC40: imul $20,-4(%ebp),%edi leal words+12(%edi),%esi pushl %esi pushl words+8(%edi) pushl words+4(%edi) pushl words(%edi) pushl $.LC44 call printf addl $20,%esp .LC41: incl -4(%ebp) .LC43: movl -4(%ebp),%edi cmpl $5,%edi jb .LC40 mov $0,%eax .LC39: movl %ebp,%esp popl %edi popl %esi popl %ebx popl %ebp ret .Lf48: .size h,.Lf48-h .data .align 1 .LC44: .byte 37 .byte 100 .byte 32 .byte 37 .byte 100 .byte 32 .byte 37 .byte 100 .byte 32 .byte 37 .byte 115 .byte 10 .byte 0 .align 1 .LC37: .byte 37 .byte 100 .byte 32 .byte 0 .align 1 .LC26: .byte 37 .byte 115 .byte 10 .byte 0 .align 1 .LC21: .byte 119 .byte 104 .byte 105 .byte 108 .byte 101 .byte 0 .align 1 .LC20: .byte 101 .byte 108 .byte 115 .byte 101 .byte 0 .align 1 .LC19: .byte 102 .byte 111 .byte 114 .byte 0 .align 1 .LC18: .byte 105 .byte 102 .byte 0 .align 1 .LC14: .byte 10 .byte 0 .align 1 .LC13: .byte 32 .byte 37 .byte 100 .byte 0 .text .ident "LCC: 4.2"
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0-only /* * An rtc driver for the Dallas/Maxim DS1685/DS1687 and related real-time * chips. * * Copyright (C) 2011-2014 Joshua Kinard <kumba@gentoo.org>. * Copyright (C) 2009 Matthias Fuchs <matthias.fuchs@esd-electronics.com>. * * References: * DS1685/DS1687 3V/5V Real-Time Clocks, 19-5215, Rev 4/10. * DS17x85/DS17x87 3V/5V Real-Time Clocks, 19-5222, Rev 4/10. * DS1689/DS1693 3V/5V Serialized Real-Time Clocks, Rev 112105. * Application Note 90, Using the Multiplex Bus RTC Extended Features. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/bcd.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/rtc.h> #include <linux/workqueue.h> #include <linux/rtc/ds1685.h> #ifdef CONFIG_PROC_FS #include <linux/proc_fs.h> #endif /* ----------------------------------------------------------------------- */ /* Standard read/write functions if platform does not provide overrides */ /** * ds1685_read - read a value from an rtc register. * @rtc: pointer to the ds1685 rtc structure. * @reg: the register address to read. */ static u8 ds1685_read(struct ds1685_priv *rtc, int reg) { return readb((u8 __iomem *)rtc->regs + (reg * rtc->regstep)); } /** * ds1685_write - write a value to an rtc register. * @rtc: pointer to the ds1685 rtc structure. * @reg: the register address to write. * @value: value to write to the register. */ static void ds1685_write(struct ds1685_priv *rtc, int reg, u8 value) { writeb(value, ((u8 __iomem *)rtc->regs + (reg * rtc->regstep))); } /* ----------------------------------------------------------------------- */ /* ----------------------------------------------------------------------- */ /* Inlined functions */ /** * ds1685_rtc_bcd2bin - bcd2bin wrapper in case platform doesn't support BCD. * @rtc: pointer to the ds1685 rtc structure. * @val: u8 time value to consider converting. * @bcd_mask: u8 mask value if BCD mode is used. * @bin_mask: u8 mask value if BIN mode is used. * * Returns the value, converted to BIN if originally in BCD and bcd_mode TRUE. */ static inline u8 ds1685_rtc_bcd2bin(struct ds1685_priv *rtc, u8 val, u8 bcd_mask, u8 bin_mask) { if (rtc->bcd_mode) return (bcd2bin(val) & bcd_mask); return (val & bin_mask); } /** * ds1685_rtc_bin2bcd - bin2bcd wrapper in case platform doesn't support BCD. * @rtc: pointer to the ds1685 rtc structure. * @val: u8 time value to consider converting. * @bin_mask: u8 mask value if BIN mode is used. * @bcd_mask: u8 mask value if BCD mode is used. * * Returns the value, converted to BCD if originally in BIN and bcd_mode TRUE. */ static inline u8 ds1685_rtc_bin2bcd(struct ds1685_priv *rtc, u8 val, u8 bin_mask, u8 bcd_mask) { if (rtc->bcd_mode) return (bin2bcd(val) & bcd_mask); return (val & bin_mask); } /** * s1685_rtc_check_mday - check validity of the day of month. * @rtc: pointer to the ds1685 rtc structure. * @mday: day of month. * * Returns -EDOM if the day of month is not within 1..31 range. */ static inline int ds1685_rtc_check_mday(struct ds1685_priv *rtc, u8 mday) { if (rtc->bcd_mode) { if (mday < 0x01 || mday > 0x31 || (mday & 0x0f) > 0x09) return -EDOM; } else { if (mday < 1 || mday > 31) return -EDOM; } return 0; } /** * ds1685_rtc_switch_to_bank0 - switch the rtc to bank 0. * @rtc: pointer to the ds1685 rtc structure. */ static inline void ds1685_rtc_switch_to_bank0(struct ds1685_priv *rtc) { rtc->write(rtc, RTC_CTRL_A, (rtc->read(rtc, RTC_CTRL_A) & ~(RTC_CTRL_A_DV0))); } /** * ds1685_rtc_switch_to_bank1 - switch the rtc to bank 1. * @rtc: pointer to the ds1685 rtc structure. */ static inline void ds1685_rtc_switch_to_bank1(struct ds1685_priv *rtc) { rtc->write(rtc, RTC_CTRL_A, (rtc->read(rtc, RTC_CTRL_A) | RTC_CTRL_A_DV0)); } /** * ds1685_rtc_begin_data_access - prepare the rtc for data access. * @rtc: pointer to the ds1685 rtc structure. * * This takes several steps to prepare the rtc for access to get/set time * and alarm values from the rtc registers: * - Sets the SET bit in Control Register B. * - Reads Ext Control Register 4A and checks the INCR bit. * - If INCR is active, a short delay is added before Ext Control Register 4A * is read again in a loop until INCR is inactive. * - Switches the rtc to bank 1. This allows access to all relevant * data for normal rtc operation, as bank 0 contains only the nvram. */ static inline void ds1685_rtc_begin_data_access(struct ds1685_priv *rtc) { /* Set the SET bit in Ctrl B */ rtc->write(rtc, RTC_CTRL_B, (rtc->read(rtc, RTC_CTRL_B) | RTC_CTRL_B_SET)); /* Read Ext Ctrl 4A and check the INCR bit to avoid a lockout. */ while (rtc->read(rtc, RTC_EXT_CTRL_4A) & RTC_CTRL_4A_INCR) cpu_relax(); /* Switch to Bank 1 */ ds1685_rtc_switch_to_bank1(rtc); } /** * ds1685_rtc_end_data_access - end data access on the rtc. * @rtc: pointer to the ds1685 rtc structure. * * This ends what was started by ds1685_rtc_begin_data_access: * - Switches the rtc back to bank 0. * - Clears the SET bit in Control Register B. */ static inline void ds1685_rtc_end_data_access(struct ds1685_priv *rtc) { /* Switch back to Bank 0 */ ds1685_rtc_switch_to_bank1(rtc); /* Clear the SET bit in Ctrl B */ rtc->write(rtc, RTC_CTRL_B, (rtc->read(rtc, RTC_CTRL_B) & ~(RTC_CTRL_B_SET))); } /** * ds1685_rtc_get_ssn - retrieve the silicon serial number. * @rtc: pointer to the ds1685 rtc structure. * @ssn: u8 array to hold the bits of the silicon serial number. * * This number starts at 0x40, and is 8-bytes long, ending at 0x47. The * first byte is the model number, the next six bytes are the serial number * digits, and the final byte is a CRC check byte. Together, they form the * silicon serial number. * * These values are stored in bank1, so ds1685_rtc_switch_to_bank1 must be * called first before calling this function, else data will be read out of * the bank0 NVRAM. Be sure to call ds1685_rtc_switch_to_bank0 when done. */ static inline void ds1685_rtc_get_ssn(struct ds1685_priv *rtc, u8 *ssn) { ssn[0] = rtc->read(rtc, RTC_BANK1_SSN_MODEL); ssn[1] = rtc->read(rtc, RTC_BANK1_SSN_BYTE_1); ssn[2] = rtc->read(rtc, RTC_BANK1_SSN_BYTE_2); ssn[3] = rtc->read(rtc, RTC_BANK1_SSN_BYTE_3); ssn[4] = rtc->read(rtc, RTC_BANK1_SSN_BYTE_4); ssn[5] = rtc->read(rtc, RTC_BANK1_SSN_BYTE_5); ssn[6] = rtc->read(rtc, RTC_BANK1_SSN_BYTE_6); ssn[7] = rtc->read(rtc, RTC_BANK1_SSN_CRC); } /* ----------------------------------------------------------------------- */ /* ----------------------------------------------------------------------- */ /* Read/Set Time & Alarm functions */ /** * ds1685_rtc_read_time - reads the time registers. * @dev: pointer to device structure. * @tm: pointer to rtc_time structure. */ static int ds1685_rtc_read_time(struct device *dev, struct rtc_time *tm) { struct ds1685_priv *rtc = dev_get_drvdata(dev); u8 ctrlb, century; u8 seconds, minutes, hours, wday, mday, month, years; /* Fetch the time info from the RTC registers. */ ds1685_rtc_begin_data_access(rtc); seconds = rtc->read(rtc, RTC_SECS); minutes = rtc->read(rtc, RTC_MINS); hours = rtc->read(rtc, RTC_HRS); wday = rtc->read(rtc, RTC_WDAY); mday = rtc->read(rtc, RTC_MDAY); month = rtc->read(rtc, RTC_MONTH); years = rtc->read(rtc, RTC_YEAR); century = rtc->read(rtc, RTC_CENTURY); ctrlb = rtc->read(rtc, RTC_CTRL_B); ds1685_rtc_end_data_access(rtc); /* bcd2bin if needed, perform fixups, and store to rtc_time. */ years = ds1685_rtc_bcd2bin(rtc, years, RTC_YEAR_BCD_MASK, RTC_YEAR_BIN_MASK); century = ds1685_rtc_bcd2bin(rtc, century, RTC_CENTURY_MASK, RTC_CENTURY_MASK); tm->tm_sec = ds1685_rtc_bcd2bin(rtc, seconds, RTC_SECS_BCD_MASK, RTC_SECS_BIN_MASK); tm->tm_min = ds1685_rtc_bcd2bin(rtc, minutes, RTC_MINS_BCD_MASK, RTC_MINS_BIN_MASK); tm->tm_hour = ds1685_rtc_bcd2bin(rtc, hours, RTC_HRS_24_BCD_MASK, RTC_HRS_24_BIN_MASK); tm->tm_wday = (ds1685_rtc_bcd2bin(rtc, wday, RTC_WDAY_MASK, RTC_WDAY_MASK) - 1); tm->tm_mday = ds1685_rtc_bcd2bin(rtc, mday, RTC_MDAY_BCD_MASK, RTC_MDAY_BIN_MASK); tm->tm_mon = (ds1685_rtc_bcd2bin(rtc, month, RTC_MONTH_BCD_MASK, RTC_MONTH_BIN_MASK) - 1); tm->tm_year = ((years + (century * 100)) - 1900); tm->tm_yday = rtc_year_days(tm->tm_mday, tm->tm_mon, tm->tm_year); tm->tm_isdst = 0; /* RTC has hardcoded timezone, so don't use. */ return 0; } /** * ds1685_rtc_set_time - sets the time registers. * @dev: pointer to device structure. * @tm: pointer to rtc_time structure. */ static int ds1685_rtc_set_time(struct device *dev, struct rtc_time *tm) { struct ds1685_priv *rtc = dev_get_drvdata(dev); u8 ctrlb, seconds, minutes, hours, wday, mday, month, years, century; /* Fetch the time info from rtc_time. */ seconds = ds1685_rtc_bin2bcd(rtc, tm->tm_sec, RTC_SECS_BIN_MASK, RTC_SECS_BCD_MASK); minutes = ds1685_rtc_bin2bcd(rtc, tm->tm_min, RTC_MINS_BIN_MASK, RTC_MINS_BCD_MASK); hours = ds1685_rtc_bin2bcd(rtc, tm->tm_hour, RTC_HRS_24_BIN_MASK, RTC_HRS_24_BCD_MASK); wday = ds1685_rtc_bin2bcd(rtc, (tm->tm_wday + 1), RTC_WDAY_MASK, RTC_WDAY_MASK); mday = ds1685_rtc_bin2bcd(rtc, tm->tm_mday, RTC_MDAY_BIN_MASK, RTC_MDAY_BCD_MASK); month = ds1685_rtc_bin2bcd(rtc, (tm->tm_mon + 1), RTC_MONTH_BIN_MASK, RTC_MONTH_BCD_MASK); years = ds1685_rtc_bin2bcd(rtc, (tm->tm_year % 100), RTC_YEAR_BIN_MASK, RTC_YEAR_BCD_MASK); century = ds1685_rtc_bin2bcd(rtc, ((tm->tm_year + 1900) / 100), RTC_CENTURY_MASK, RTC_CENTURY_MASK); /* * Perform Sanity Checks: * - Months: !> 12, Month Day != 0. * - Month Day !> Max days in current month. * - Hours !>= 24, Mins !>= 60, Secs !>= 60, & Weekday !> 7. */ if ((tm->tm_mon > 11) || (mday == 0)) return -EDOM; if (tm->tm_mday > rtc_month_days(tm->tm_mon, tm->tm_year)) return -EDOM; if ((tm->tm_hour >= 24) || (tm->tm_min >= 60) || (tm->tm_sec >= 60) || (wday > 7)) return -EDOM; /* * Set the data mode to use and store the time values in the * RTC registers. */ ds1685_rtc_begin_data_access(rtc); ctrlb = rtc->read(rtc, RTC_CTRL_B); if (rtc->bcd_mode) ctrlb &= ~(RTC_CTRL_B_DM); else ctrlb |= RTC_CTRL_B_DM; rtc->write(rtc, RTC_CTRL_B, ctrlb); rtc->write(rtc, RTC_SECS, seconds); rtc->write(rtc, RTC_MINS, minutes); rtc->write(rtc, RTC_HRS, hours); rtc->write(rtc, RTC_WDAY, wday); rtc->write(rtc, RTC_MDAY, mday); rtc->write(rtc, RTC_MONTH, month); rtc->write(rtc, RTC_YEAR, years); rtc->write(rtc, RTC_CENTURY, century); ds1685_rtc_end_data_access(rtc); return 0; } /** * ds1685_rtc_read_alarm - reads the alarm registers. * @dev: pointer to device structure. * @alrm: pointer to rtc_wkalrm structure. * * There are three primary alarm registers: seconds, minutes, and hours. * A fourth alarm register for the month date is also available in bank1 for * kickstart/wakeup features. The DS1685/DS1687 manual states that a * "don't care" value ranging from 0xc0 to 0xff may be written into one or * more of the three alarm bytes to act as a wildcard value. The fourth * byte doesn't support a "don't care" value. */ static int ds1685_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alrm) { struct ds1685_priv *rtc = dev_get_drvdata(dev); u8 seconds, minutes, hours, mday, ctrlb, ctrlc; int ret; /* Fetch the alarm info from the RTC alarm registers. */ ds1685_rtc_begin_data_access(rtc); seconds = rtc->read(rtc, RTC_SECS_ALARM); minutes = rtc->read(rtc, RTC_MINS_ALARM); hours = rtc->read(rtc, RTC_HRS_ALARM); mday = rtc->read(rtc, RTC_MDAY_ALARM); ctrlb = rtc->read(rtc, RTC_CTRL_B); ctrlc = rtc->read(rtc, RTC_CTRL_C); ds1685_rtc_end_data_access(rtc); /* Check the month date for validity. */ ret = ds1685_rtc_check_mday(rtc, mday); if (ret) return ret; /* * Check the three alarm bytes. * * The Linux RTC system doesn't support the "don't care" capability * of this RTC chip. We check for it anyways in case support is * added in the future and only assign when we care. */ if (likely(seconds < 0xc0)) alrm->time.tm_sec = ds1685_rtc_bcd2bin(rtc, seconds, RTC_SECS_BCD_MASK, RTC_SECS_BIN_MASK); if (likely(minutes < 0xc0)) alrm->time.tm_min = ds1685_rtc_bcd2bin(rtc, minutes, RTC_MINS_BCD_MASK, RTC_MINS_BIN_MASK); if (likely(hours < 0xc0)) alrm->time.tm_hour = ds1685_rtc_bcd2bin(rtc, hours, RTC_HRS_24_BCD_MASK, RTC_HRS_24_BIN_MASK); /* Write the data to rtc_wkalrm. */ alrm->time.tm_mday = ds1685_rtc_bcd2bin(rtc, mday, RTC_MDAY_BCD_MASK, RTC_MDAY_BIN_MASK); alrm->enabled = !!(ctrlb & RTC_CTRL_B_AIE); alrm->pending = !!(ctrlc & RTC_CTRL_C_AF); return 0; } /** * ds1685_rtc_set_alarm - sets the alarm in registers. * @dev: pointer to device structure. * @alrm: pointer to rtc_wkalrm structure. */ static int ds1685_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alrm) { struct ds1685_priv *rtc = dev_get_drvdata(dev); u8 ctrlb, seconds, minutes, hours, mday; int ret; /* Fetch the alarm info and convert to BCD. */ seconds = ds1685_rtc_bin2bcd(rtc, alrm->time.tm_sec, RTC_SECS_BIN_MASK, RTC_SECS_BCD_MASK); minutes = ds1685_rtc_bin2bcd(rtc, alrm->time.tm_min, RTC_MINS_BIN_MASK, RTC_MINS_BCD_MASK); hours = ds1685_rtc_bin2bcd(rtc, alrm->time.tm_hour, RTC_HRS_24_BIN_MASK, RTC_HRS_24_BCD_MASK); mday = ds1685_rtc_bin2bcd(rtc, alrm->time.tm_mday, RTC_MDAY_BIN_MASK, RTC_MDAY_BCD_MASK); /* Check the month date for validity. */ ret = ds1685_rtc_check_mday(rtc, mday); if (ret) return ret; /* * Check the three alarm bytes. * * The Linux RTC system doesn't support the "don't care" capability * of this RTC chip because rtc_valid_tm tries to validate every * field, and we only support four fields. We put the support * here anyways for the future. */ if (unlikely(seconds >= 0xc0)) seconds = 0xff; if (unlikely(minutes >= 0xc0)) minutes = 0xff; if (unlikely(hours >= 0xc0)) hours = 0xff; alrm->time.tm_mon = -1; alrm->time.tm_year = -1; alrm->time.tm_wday = -1; alrm->time.tm_yday = -1; alrm->time.tm_isdst = -1; /* Disable the alarm interrupt first. */ ds1685_rtc_begin_data_access(rtc); ctrlb = rtc->read(rtc, RTC_CTRL_B); rtc->write(rtc, RTC_CTRL_B, (ctrlb & ~(RTC_CTRL_B_AIE))); /* Read ctrlc to clear RTC_CTRL_C_AF. */ rtc->read(rtc, RTC_CTRL_C); /* * Set the data mode to use and store the time values in the * RTC registers. */ ctrlb = rtc->read(rtc, RTC_CTRL_B); if (rtc->bcd_mode) ctrlb &= ~(RTC_CTRL_B_DM); else ctrlb |= RTC_CTRL_B_DM; rtc->write(rtc, RTC_CTRL_B, ctrlb); rtc->write(rtc, RTC_SECS_ALARM, seconds); rtc->write(rtc, RTC_MINS_ALARM, minutes); rtc->write(rtc, RTC_HRS_ALARM, hours); rtc->write(rtc, RTC_MDAY_ALARM, mday); /* Re-enable the alarm if needed. */ if (alrm->enabled) { ctrlb = rtc->read(rtc, RTC_CTRL_B); ctrlb |= RTC_CTRL_B_AIE; rtc->write(rtc, RTC_CTRL_B, ctrlb); } /* Done! */ ds1685_rtc_end_data_access(rtc); return 0; } /* ----------------------------------------------------------------------- */ /* ----------------------------------------------------------------------- */ /* /dev/rtcX Interface functions */ /** * ds1685_rtc_alarm_irq_enable - replaces ioctl() RTC_AIE on/off. * @dev: pointer to device structure. * @enabled: flag indicating whether to enable or disable. */ static int ds1685_rtc_alarm_irq_enable(struct device *dev, unsigned int enabled) { struct ds1685_priv *rtc = dev_get_drvdata(dev); /* Flip the requisite interrupt-enable bit. */ if (enabled) rtc->write(rtc, RTC_CTRL_B, (rtc->read(rtc, RTC_CTRL_B) | RTC_CTRL_B_AIE)); else rtc->write(rtc, RTC_CTRL_B, (rtc->read(rtc, RTC_CTRL_B) & ~(RTC_CTRL_B_AIE))); /* Read Control C to clear all the flag bits. */ rtc->read(rtc, RTC_CTRL_C); return 0; } /* ----------------------------------------------------------------------- */ /* ----------------------------------------------------------------------- */ /* IRQ handler */ /** * ds1685_rtc_extended_irq - take care of extended interrupts * @rtc: pointer to the ds1685 rtc structure. * @pdev: platform device pointer. */ static void ds1685_rtc_extended_irq(struct ds1685_priv *rtc, struct platform_device *pdev) { u8 ctrl4a, ctrl4b; ds1685_rtc_switch_to_bank1(rtc); ctrl4a = rtc->read(rtc, RTC_EXT_CTRL_4A); ctrl4b = rtc->read(rtc, RTC_EXT_CTRL_4B); /* * Check for a kickstart interrupt. With Vcc applied, this * typically means that the power button was pressed, so we * begin the shutdown sequence. */ if ((ctrl4b & RTC_CTRL_4B_KSE) && (ctrl4a & RTC_CTRL_4A_KF)) { /* Briefly disable kickstarts to debounce button presses. */ rtc->write(rtc, RTC_EXT_CTRL_4B, (rtc->read(rtc, RTC_EXT_CTRL_4B) & ~(RTC_CTRL_4B_KSE))); /* Clear the kickstart flag. */ rtc->write(rtc, RTC_EXT_CTRL_4A, (ctrl4a & ~(RTC_CTRL_4A_KF))); /* * Sleep 500ms before re-enabling kickstarts. This allows * adequate time to avoid reading signal jitter as additional * button presses. */ msleep(500); rtc->write(rtc, RTC_EXT_CTRL_4B, (rtc->read(rtc, RTC_EXT_CTRL_4B) | RTC_CTRL_4B_KSE)); /* Call the platform pre-poweroff function. Else, shutdown. */ if (rtc->prepare_poweroff != NULL) rtc->prepare_poweroff(); else ds1685_rtc_poweroff(pdev); } /* * Check for a wake-up interrupt. With Vcc applied, this is * essentially a second alarm interrupt, except it takes into * account the 'date' register in bank1 in addition to the * standard three alarm registers. */ if ((ctrl4b & RTC_CTRL_4B_WIE) && (ctrl4a & RTC_CTRL_4A_WF)) { rtc->write(rtc, RTC_EXT_CTRL_4A, (ctrl4a & ~(RTC_CTRL_4A_WF))); /* Call the platform wake_alarm function if defined. */ if (rtc->wake_alarm != NULL) rtc->wake_alarm(); else dev_warn(&pdev->dev, "Wake Alarm IRQ just occurred!\n"); } /* * Check for a ram-clear interrupt. This happens if RIE=1 and RF=0 * when RCE=1 in 4B. This clears all NVRAM bytes in bank0 by setting * each byte to a logic 1. This has no effect on any extended * NV-SRAM that might be present, nor on the time/calendar/alarm * registers. After a ram-clear is completed, there is a minimum * recovery time of ~150ms in which all reads/writes are locked out. * NOTE: A ram-clear can still occur if RCE=1 and RIE=0. We cannot * catch this scenario. */ if ((ctrl4b & RTC_CTRL_4B_RIE) && (ctrl4a & RTC_CTRL_4A_RF)) { rtc->write(rtc, RTC_EXT_CTRL_4A, (ctrl4a & ~(RTC_CTRL_4A_RF))); msleep(150); /* Call the platform post_ram_clear function if defined. */ if (rtc->post_ram_clear != NULL) rtc->post_ram_clear(); else dev_warn(&pdev->dev, "RAM-Clear IRQ just occurred!\n"); } ds1685_rtc_switch_to_bank0(rtc); } /** * ds1685_rtc_irq_handler - IRQ handler. * @irq: IRQ number. * @dev_id: platform device pointer. */ static irqreturn_t ds1685_rtc_irq_handler(int irq, void *dev_id) { struct platform_device *pdev = dev_id; struct ds1685_priv *rtc = platform_get_drvdata(pdev); struct mutex *rtc_mutex; u8 ctrlb, ctrlc; unsigned long events = 0; u8 num_irqs = 0; /* Abort early if the device isn't ready yet (i.e., DEBUG_SHIRQ). */ if (unlikely(!rtc)) return IRQ_HANDLED; rtc_mutex = &rtc->dev->ops_lock; mutex_lock(rtc_mutex); /* Ctrlb holds the interrupt-enable bits and ctrlc the flag bits. */ ctrlb = rtc->read(rtc, RTC_CTRL_B); ctrlc = rtc->read(rtc, RTC_CTRL_C); /* Is the IRQF bit set? */ if (likely(ctrlc & RTC_CTRL_C_IRQF)) { /* * We need to determine if it was one of the standard * events: PF, AF, or UF. If so, we handle them and * update the RTC core. */ if (likely(ctrlc & RTC_CTRL_B_PAU_MASK)) { events = RTC_IRQF; /* Check for a periodic interrupt. */ if ((ctrlb & RTC_CTRL_B_PIE) && (ctrlc & RTC_CTRL_C_PF)) { events |= RTC_PF; num_irqs++; } /* Check for an alarm interrupt. */ if ((ctrlb & RTC_CTRL_B_AIE) && (ctrlc & RTC_CTRL_C_AF)) { events |= RTC_AF; num_irqs++; } /* Check for an update interrupt. */ if ((ctrlb & RTC_CTRL_B_UIE) && (ctrlc & RTC_CTRL_C_UF)) { events |= RTC_UF; num_irqs++; } } else { /* * One of the "extended" interrupts was received that * is not recognized by the RTC core. */ ds1685_rtc_extended_irq(rtc, pdev); } } rtc_update_irq(rtc->dev, num_irqs, events); mutex_unlock(rtc_mutex); return events ? IRQ_HANDLED : IRQ_NONE; } /* ----------------------------------------------------------------------- */ /* ----------------------------------------------------------------------- */ /* ProcFS interface */ #ifdef CONFIG_PROC_FS #define NUM_REGS 6 /* Num of control registers. */ #define NUM_BITS 8 /* Num bits per register. */ #define NUM_SPACES 4 /* Num spaces between each bit. */ /* * Periodic Interrupt Rates. */ static const char *ds1685_rtc_pirq_rate[16] = { "none", "3.90625ms", "7.8125ms", "0.122070ms", "0.244141ms", "0.488281ms", "0.9765625ms", "1.953125ms", "3.90625ms", "7.8125ms", "15.625ms", "31.25ms", "62.5ms", "125ms", "250ms", "500ms" }; /* * Square-Wave Output Frequencies. */ static const char *ds1685_rtc_sqw_freq[16] = { "none", "256Hz", "128Hz", "8192Hz", "4096Hz", "2048Hz", "1024Hz", "512Hz", "256Hz", "128Hz", "64Hz", "32Hz", "16Hz", "8Hz", "4Hz", "2Hz" }; /** * ds1685_rtc_proc - procfs access function. * @dev: pointer to device structure. * @seq: pointer to seq_file structure. */ static int ds1685_rtc_proc(struct device *dev, struct seq_file *seq) { struct ds1685_priv *rtc = dev_get_drvdata(dev); u8 ctrla, ctrlb, ctrlc, ctrld, ctrl4a, ctrl4b, ssn[8]; char *model; /* Read all the relevant data from the control registers. */ ds1685_rtc_switch_to_bank1(rtc); ds1685_rtc_get_ssn(rtc, ssn); ctrla = rtc->read(rtc, RTC_CTRL_A); ctrlb = rtc->read(rtc, RTC_CTRL_B); ctrlc = rtc->read(rtc, RTC_CTRL_C); ctrld = rtc->read(rtc, RTC_CTRL_D); ctrl4a = rtc->read(rtc, RTC_EXT_CTRL_4A); ctrl4b = rtc->read(rtc, RTC_EXT_CTRL_4B); ds1685_rtc_switch_to_bank0(rtc); /* Determine the RTC model. */ switch (ssn[0]) { case RTC_MODEL_DS1685: model = "DS1685/DS1687\0"; break; case RTC_MODEL_DS1689: model = "DS1689/DS1693\0"; break; case RTC_MODEL_DS17285: model = "DS17285/DS17287\0"; break; case RTC_MODEL_DS17485: model = "DS17485/DS17487\0"; break; case RTC_MODEL_DS17885: model = "DS17885/DS17887\0"; break; default: model = "Unknown\0"; break; } /* Print out the information. */ seq_printf(seq, "Model\t\t: %s\n" "Oscillator\t: %s\n" "12/24hr\t\t: %s\n" "DST\t\t: %s\n" "Data mode\t: %s\n" "Battery\t\t: %s\n" "Aux batt\t: %s\n" "Update IRQ\t: %s\n" "Periodic IRQ\t: %s\n" "Periodic Rate\t: %s\n" "SQW Freq\t: %s\n" "Serial #\t: %8phC\n", model, ((ctrla & RTC_CTRL_A_DV1) ? "enabled" : "disabled"), ((ctrlb & RTC_CTRL_B_2412) ? "24-hour" : "12-hour"), ((ctrlb & RTC_CTRL_B_DSE) ? "enabled" : "disabled"), ((ctrlb & RTC_CTRL_B_DM) ? "binary" : "BCD"), ((ctrld & RTC_CTRL_D_VRT) ? "ok" : "exhausted or n/a"), ((ctrl4a & RTC_CTRL_4A_VRT2) ? "ok" : "exhausted or n/a"), ((ctrlb & RTC_CTRL_B_UIE) ? "yes" : "no"), ((ctrlb & RTC_CTRL_B_PIE) ? "yes" : "no"), (!(ctrl4b & RTC_CTRL_4B_E32K) ? ds1685_rtc_pirq_rate[(ctrla & RTC_CTRL_A_RS_MASK)] : "none"), (!((ctrl4b & RTC_CTRL_4B_E32K)) ? ds1685_rtc_sqw_freq[(ctrla & RTC_CTRL_A_RS_MASK)] : "32768Hz"), ssn); return 0; } #else #define ds1685_rtc_proc NULL #endif /* CONFIG_PROC_FS */ /* ----------------------------------------------------------------------- */ /* ----------------------------------------------------------------------- */ /* RTC Class operations */ static const struct rtc_class_ops ds1685_rtc_ops = { .proc = ds1685_rtc_proc, .read_time = ds1685_rtc_read_time, .set_time = ds1685_rtc_set_time, .read_alarm = ds1685_rtc_read_alarm, .set_alarm = ds1685_rtc_set_alarm, .alarm_irq_enable = ds1685_rtc_alarm_irq_enable, }; /* ----------------------------------------------------------------------- */ static int ds1685_nvram_read(void *priv, unsigned int pos, void *val, size_t size) { struct ds1685_priv *rtc = priv; struct mutex *rtc_mutex = &rtc->dev->ops_lock; ssize_t count; u8 *buf = val; int err; err = mutex_lock_interruptible(rtc_mutex); if (err) return err; ds1685_rtc_switch_to_bank0(rtc); /* Read NVRAM in time and bank0 registers. */ for (count = 0; size > 0 && pos < NVRAM_TOTAL_SZ_BANK0; count++, size--) { if (count < NVRAM_SZ_TIME) *buf++ = rtc->read(rtc, (NVRAM_TIME_BASE + pos++)); else *buf++ = rtc->read(rtc, (NVRAM_BANK0_BASE + pos++)); } #ifndef CONFIG_RTC_DRV_DS1689 if (size > 0) { ds1685_rtc_switch_to_bank1(rtc); #ifndef CONFIG_RTC_DRV_DS1685 /* Enable burst-mode on DS17x85/DS17x87 */ rtc->write(rtc, RTC_EXT_CTRL_4A, (rtc->read(rtc, RTC_EXT_CTRL_4A) | RTC_CTRL_4A_BME)); /* We need one write to RTC_BANK1_RAM_ADDR_LSB to start * reading with burst-mode */ rtc->write(rtc, RTC_BANK1_RAM_ADDR_LSB, (pos - NVRAM_TOTAL_SZ_BANK0)); #endif /* Read NVRAM in bank1 registers. */ for (count = 0; size > 0 && pos < NVRAM_TOTAL_SZ; count++, size--) { #ifdef CONFIG_RTC_DRV_DS1685 /* DS1685/DS1687 has to write to RTC_BANK1_RAM_ADDR * before each read. */ rtc->write(rtc, RTC_BANK1_RAM_ADDR, (pos - NVRAM_TOTAL_SZ_BANK0)); #endif *buf++ = rtc->read(rtc, RTC_BANK1_RAM_DATA_PORT); pos++; } #ifndef CONFIG_RTC_DRV_DS1685 /* Disable burst-mode on DS17x85/DS17x87 */ rtc->write(rtc, RTC_EXT_CTRL_4A, (rtc->read(rtc, RTC_EXT_CTRL_4A) & ~(RTC_CTRL_4A_BME))); #endif ds1685_rtc_switch_to_bank0(rtc); } #endif /* !CONFIG_RTC_DRV_DS1689 */ mutex_unlock(rtc_mutex); return 0; } static int ds1685_nvram_write(void *priv, unsigned int pos, void *val, size_t size) { struct ds1685_priv *rtc = priv; struct mutex *rtc_mutex = &rtc->dev->ops_lock; ssize_t count; u8 *buf = val; int err; err = mutex_lock_interruptible(rtc_mutex); if (err) return err; ds1685_rtc_switch_to_bank0(rtc); /* Write NVRAM in time and bank0 registers. */ for (count = 0; size > 0 && pos < NVRAM_TOTAL_SZ_BANK0; count++, size--) if (count < NVRAM_SZ_TIME) rtc->write(rtc, (NVRAM_TIME_BASE + pos++), *buf++); else rtc->write(rtc, (NVRAM_BANK0_BASE), *buf++); #ifndef CONFIG_RTC_DRV_DS1689 if (size > 0) { ds1685_rtc_switch_to_bank1(rtc); #ifndef CONFIG_RTC_DRV_DS1685 /* Enable burst-mode on DS17x85/DS17x87 */ rtc->write(rtc, RTC_EXT_CTRL_4A, (rtc->read(rtc, RTC_EXT_CTRL_4A) | RTC_CTRL_4A_BME)); /* We need one write to RTC_BANK1_RAM_ADDR_LSB to start * writing with burst-mode */ rtc->write(rtc, RTC_BANK1_RAM_ADDR_LSB, (pos - NVRAM_TOTAL_SZ_BANK0)); #endif /* Write NVRAM in bank1 registers. */ for (count = 0; size > 0 && pos < NVRAM_TOTAL_SZ; count++, size--) { #ifdef CONFIG_RTC_DRV_DS1685 /* DS1685/DS1687 has to write to RTC_BANK1_RAM_ADDR * before each read. */ rtc->write(rtc, RTC_BANK1_RAM_ADDR, (pos - NVRAM_TOTAL_SZ_BANK0)); #endif rtc->write(rtc, RTC_BANK1_RAM_DATA_PORT, *buf++); pos++; } #ifndef CONFIG_RTC_DRV_DS1685 /* Disable burst-mode on DS17x85/DS17x87 */ rtc->write(rtc, RTC_EXT_CTRL_4A, (rtc->read(rtc, RTC_EXT_CTRL_4A) & ~(RTC_CTRL_4A_BME))); #endif ds1685_rtc_switch_to_bank0(rtc); } #endif /* !CONFIG_RTC_DRV_DS1689 */ mutex_unlock(rtc_mutex); return 0; } /* ----------------------------------------------------------------------- */ /* SysFS interface */ /** * ds1685_rtc_sysfs_battery_show - sysfs file for main battery status. * @dev: pointer to device structure. * @attr: pointer to device_attribute structure. * @buf: pointer to char array to hold the output. */ static ssize_t ds1685_rtc_sysfs_battery_show(struct device *dev, struct device_attribute *attr, char *buf) { struct ds1685_priv *rtc = dev_get_drvdata(dev->parent); u8 ctrld; ctrld = rtc->read(rtc, RTC_CTRL_D); return sprintf(buf, "%s\n", (ctrld & RTC_CTRL_D_VRT) ? "ok" : "not ok or N/A"); } static DEVICE_ATTR(battery, S_IRUGO, ds1685_rtc_sysfs_battery_show, NULL); /** * ds1685_rtc_sysfs_auxbatt_show - sysfs file for aux battery status. * @dev: pointer to device structure. * @attr: pointer to device_attribute structure. * @buf: pointer to char array to hold the output. */ static ssize_t ds1685_rtc_sysfs_auxbatt_show(struct device *dev, struct device_attribute *attr, char *buf) { struct ds1685_priv *rtc = dev_get_drvdata(dev->parent); u8 ctrl4a; ds1685_rtc_switch_to_bank1(rtc); ctrl4a = rtc->read(rtc, RTC_EXT_CTRL_4A); ds1685_rtc_switch_to_bank0(rtc); return sprintf(buf, "%s\n", (ctrl4a & RTC_CTRL_4A_VRT2) ? "ok" : "not ok or N/A"); } static DEVICE_ATTR(auxbatt, S_IRUGO, ds1685_rtc_sysfs_auxbatt_show, NULL); /** * ds1685_rtc_sysfs_serial_show - sysfs file for silicon serial number. * @dev: pointer to device structure. * @attr: pointer to device_attribute structure. * @buf: pointer to char array to hold the output. */ static ssize_t ds1685_rtc_sysfs_serial_show(struct device *dev, struct device_attribute *attr, char *buf) { struct ds1685_priv *rtc = dev_get_drvdata(dev->parent); u8 ssn[8]; ds1685_rtc_switch_to_bank1(rtc); ds1685_rtc_get_ssn(rtc, ssn); ds1685_rtc_switch_to_bank0(rtc); return sprintf(buf, "%8phC\n", ssn); } static DEVICE_ATTR(serial, S_IRUGO, ds1685_rtc_sysfs_serial_show, NULL); /** * struct ds1685_rtc_sysfs_misc_attrs - list for misc RTC features. */ static struct attribute* ds1685_rtc_sysfs_misc_attrs[] = { &dev_attr_battery.attr, &dev_attr_auxbatt.attr, &dev_attr_serial.attr, NULL, }; /** * struct ds1685_rtc_sysfs_misc_grp - attr group for misc RTC features. */ static const struct attribute_group ds1685_rtc_sysfs_misc_grp = { .name = "misc", .attrs = ds1685_rtc_sysfs_misc_attrs, }; /* ----------------------------------------------------------------------- */ /* Driver Probe/Removal */ /** * ds1685_rtc_probe - initializes rtc driver. * @pdev: pointer to platform_device structure. */ static int ds1685_rtc_probe(struct platform_device *pdev) { struct rtc_device *rtc_dev; struct resource *res; struct ds1685_priv *rtc; struct ds1685_rtc_platform_data *pdata; u8 ctrla, ctrlb, hours; unsigned char am_pm; int ret = 0; struct nvmem_config nvmem_cfg = { .name = "ds1685_nvram", .size = NVRAM_TOTAL_SZ, .reg_read = ds1685_nvram_read, .reg_write = ds1685_nvram_write, }; /* Get the platform data. */ pdata = (struct ds1685_rtc_platform_data *) pdev->dev.platform_data; if (!pdata) return -ENODEV; /* Allocate memory for the rtc device. */ rtc = devm_kzalloc(&pdev->dev, sizeof(*rtc), GFP_KERNEL); if (!rtc) return -ENOMEM; /* * Allocate/setup any IORESOURCE_MEM resources, if required. Not all * platforms put the RTC in an easy-access place. Like the SGI Octane, * which attaches the RTC to a "ByteBus", hooked to a SuperIO chip * that sits behind the IOC3 PCI metadevice. */ if (pdata->alloc_io_resources) { /* Get the platform resources. */ res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) return -ENXIO; rtc->size = resource_size(res); /* Request a memory region. */ /* XXX: mmio-only for now. */ if (!devm_request_mem_region(&pdev->dev, res->start, rtc->size, pdev->name)) return -EBUSY; /* * Set the base address for the rtc, and ioremap its * registers. */ rtc->baseaddr = res->start; rtc->regs = devm_ioremap(&pdev->dev, res->start, rtc->size); if (!rtc->regs) return -ENOMEM; } rtc->alloc_io_resources = pdata->alloc_io_resources; /* Get the register step size. */ if (pdata->regstep > 0) rtc->regstep = pdata->regstep; else rtc->regstep = 1; /* Platform read function, else default if mmio setup */ if (pdata->plat_read) rtc->read = pdata->plat_read; else if (pdata->alloc_io_resources) rtc->read = ds1685_read; else return -ENXIO; /* Platform write function, else default if mmio setup */ if (pdata->plat_write) rtc->write = pdata->plat_write; else if (pdata->alloc_io_resources) rtc->write = ds1685_write; else return -ENXIO; /* Platform pre-shutdown function, if defined. */ if (pdata->plat_prepare_poweroff) rtc->prepare_poweroff = pdata->plat_prepare_poweroff; /* Platform wake_alarm function, if defined. */ if (pdata->plat_wake_alarm) rtc->wake_alarm = pdata->plat_wake_alarm; /* Platform post_ram_clear function, if defined. */ if (pdata->plat_post_ram_clear) rtc->post_ram_clear = pdata->plat_post_ram_clear; /* set the driver data. */ platform_set_drvdata(pdev, rtc); /* Turn the oscillator on if is not already on (DV1 = 1). */ ctrla = rtc->read(rtc, RTC_CTRL_A); if (!(ctrla & RTC_CTRL_A_DV1)) ctrla |= RTC_CTRL_A_DV1; /* Enable the countdown chain (DV2 = 0) */ ctrla &= ~(RTC_CTRL_A_DV2); /* Clear RS3-RS0 in Control A. */ ctrla &= ~(RTC_CTRL_A_RS_MASK); /* * All done with Control A. Switch to Bank 1 for the remainder of * the RTC setup so we have access to the extended functions. */ ctrla |= RTC_CTRL_A_DV0; rtc->write(rtc, RTC_CTRL_A, ctrla); /* Default to 32768kHz output. */ rtc->write(rtc, RTC_EXT_CTRL_4B, (rtc->read(rtc, RTC_EXT_CTRL_4B) | RTC_CTRL_4B_E32K)); /* Set the SET bit in Control B so we can do some housekeeping. */ rtc->write(rtc, RTC_CTRL_B, (rtc->read(rtc, RTC_CTRL_B) | RTC_CTRL_B_SET)); /* Read Ext Ctrl 4A and check the INCR bit to avoid a lockout. */ while (rtc->read(rtc, RTC_EXT_CTRL_4A) & RTC_CTRL_4A_INCR) cpu_relax(); /* * If the platform supports BCD mode, then set DM=0 in Control B. * Otherwise, set DM=1 for BIN mode. */ ctrlb = rtc->read(rtc, RTC_CTRL_B); if (pdata->bcd_mode) ctrlb &= ~(RTC_CTRL_B_DM); else ctrlb |= RTC_CTRL_B_DM; rtc->bcd_mode = pdata->bcd_mode; /* * Disable Daylight Savings Time (DSE = 0). * The RTC has hardcoded timezone information that is rendered * obselete. We'll let the OS deal with DST settings instead. */ if (ctrlb & RTC_CTRL_B_DSE) ctrlb &= ~(RTC_CTRL_B_DSE); /* Force 24-hour mode (2412 = 1). */ if (!(ctrlb & RTC_CTRL_B_2412)) { /* Reinitialize the time hours. */ hours = rtc->read(rtc, RTC_HRS); am_pm = hours & RTC_HRS_AMPM_MASK; hours = ds1685_rtc_bcd2bin(rtc, hours, RTC_HRS_12_BCD_MASK, RTC_HRS_12_BIN_MASK); hours = ((hours == 12) ? 0 : ((am_pm) ? hours + 12 : hours)); /* Enable 24-hour mode. */ ctrlb |= RTC_CTRL_B_2412; /* Write back to Control B, including DM & DSE bits. */ rtc->write(rtc, RTC_CTRL_B, ctrlb); /* Write the time hours back. */ rtc->write(rtc, RTC_HRS, ds1685_rtc_bin2bcd(rtc, hours, RTC_HRS_24_BIN_MASK, RTC_HRS_24_BCD_MASK)); /* Reinitialize the alarm hours. */ hours = rtc->read(rtc, RTC_HRS_ALARM); am_pm = hours & RTC_HRS_AMPM_MASK; hours = ds1685_rtc_bcd2bin(rtc, hours, RTC_HRS_12_BCD_MASK, RTC_HRS_12_BIN_MASK); hours = ((hours == 12) ? 0 : ((am_pm) ? hours + 12 : hours)); /* Write the alarm hours back. */ rtc->write(rtc, RTC_HRS_ALARM, ds1685_rtc_bin2bcd(rtc, hours, RTC_HRS_24_BIN_MASK, RTC_HRS_24_BCD_MASK)); } else { /* 24-hour mode is already set, so write Control B back. */ rtc->write(rtc, RTC_CTRL_B, ctrlb); } /* Unset the SET bit in Control B so the RTC can update. */ rtc->write(rtc, RTC_CTRL_B, (rtc->read(rtc, RTC_CTRL_B) & ~(RTC_CTRL_B_SET))); /* Check the main battery. */ if (!(rtc->read(rtc, RTC_CTRL_D) & RTC_CTRL_D_VRT)) dev_warn(&pdev->dev, "Main battery is exhausted! RTC may be invalid!\n"); /* Check the auxillary battery. It is optional. */ if (!(rtc->read(rtc, RTC_EXT_CTRL_4A) & RTC_CTRL_4A_VRT2)) dev_warn(&pdev->dev, "Aux battery is exhausted or not available.\n"); /* Read Ctrl B and clear PIE/AIE/UIE. */ rtc->write(rtc, RTC_CTRL_B, (rtc->read(rtc, RTC_CTRL_B) & ~(RTC_CTRL_B_PAU_MASK))); /* Reading Ctrl C auto-clears PF/AF/UF. */ rtc->read(rtc, RTC_CTRL_C); /* Read Ctrl 4B and clear RIE/WIE/KSE. */ rtc->write(rtc, RTC_EXT_CTRL_4B, (rtc->read(rtc, RTC_EXT_CTRL_4B) & ~(RTC_CTRL_4B_RWK_MASK))); /* Clear RF/WF/KF in Ctrl 4A. */ rtc->write(rtc, RTC_EXT_CTRL_4A, (rtc->read(rtc, RTC_EXT_CTRL_4A) & ~(RTC_CTRL_4A_RWK_MASK))); /* * Re-enable KSE to handle power button events. We do not enable * WIE or RIE by default. */ rtc->write(rtc, RTC_EXT_CTRL_4B, (rtc->read(rtc, RTC_EXT_CTRL_4B) | RTC_CTRL_4B_KSE)); rtc_dev = devm_rtc_allocate_device(&pdev->dev); if (IS_ERR(rtc_dev)) return PTR_ERR(rtc_dev); rtc_dev->ops = &ds1685_rtc_ops; /* Century bit is useless because leap year fails in 1900 and 2100 */ rtc_dev->range_min = RTC_TIMESTAMP_BEGIN_2000; rtc_dev->range_max = RTC_TIMESTAMP_END_2099; /* Maximum periodic rate is 8192Hz (0.122070ms). */ rtc_dev->max_user_freq = RTC_MAX_USER_FREQ; /* See if the platform doesn't support UIE. */ if (pdata->uie_unsupported) rtc_dev->uie_unsupported = 1; rtc->uie_unsupported = pdata->uie_unsupported; rtc->dev = rtc_dev; /* * Fetch the IRQ and setup the interrupt handler. * * Not all platforms have the IRQF pin tied to something. If not, the * RTC will still set the *IE / *F flags and raise IRQF in ctrlc, but * there won't be an automatic way of notifying the kernel about it, * unless ctrlc is explicitly polled. */ if (!pdata->no_irq) { ret = platform_get_irq(pdev, 0); if (ret <= 0) return ret; rtc->irq_num = ret; /* Request an IRQ. */ ret = devm_request_threaded_irq(&pdev->dev, rtc->irq_num, NULL, ds1685_rtc_irq_handler, IRQF_SHARED | IRQF_ONESHOT, pdev->name, pdev); /* Check to see if something came back. */ if (unlikely(ret)) { dev_warn(&pdev->dev, "RTC interrupt not available\n"); rtc->irq_num = 0; } } rtc->no_irq = pdata->no_irq; /* Setup complete. */ ds1685_rtc_switch_to_bank0(rtc); ret = rtc_add_group(rtc_dev, &ds1685_rtc_sysfs_misc_grp); if (ret) return ret; rtc_dev->nvram_old_abi = true; nvmem_cfg.priv = rtc; ret = rtc_nvmem_register(rtc_dev, &nvmem_cfg); if (ret) return ret; return rtc_register_device(rtc_dev); } /** * ds1685_rtc_remove - removes rtc driver. * @pdev: pointer to platform_device structure. */ static int ds1685_rtc_remove(struct platform_device *pdev) { struct ds1685_priv *rtc = platform_get_drvdata(pdev); /* Read Ctrl B and clear PIE/AIE/UIE. */ rtc->write(rtc, RTC_CTRL_B, (rtc->read(rtc, RTC_CTRL_B) & ~(RTC_CTRL_B_PAU_MASK))); /* Reading Ctrl C auto-clears PF/AF/UF. */ rtc->read(rtc, RTC_CTRL_C); /* Read Ctrl 4B and clear RIE/WIE/KSE. */ rtc->write(rtc, RTC_EXT_CTRL_4B, (rtc->read(rtc, RTC_EXT_CTRL_4B) & ~(RTC_CTRL_4B_RWK_MASK))); /* Manually clear RF/WF/KF in Ctrl 4A. */ rtc->write(rtc, RTC_EXT_CTRL_4A, (rtc->read(rtc, RTC_EXT_CTRL_4A) & ~(RTC_CTRL_4A_RWK_MASK))); return 0; } /** * ds1685_rtc_driver - rtc driver properties. */ static struct platform_driver ds1685_rtc_driver = { .driver = { .name = "rtc-ds1685", }, .probe = ds1685_rtc_probe, .remove = ds1685_rtc_remove, }; module_platform_driver(ds1685_rtc_driver); /* ----------------------------------------------------------------------- */ /* ----------------------------------------------------------------------- */ /* Poweroff function */ /** * ds1685_rtc_poweroff - uses the RTC chip to power the system off. * @pdev: pointer to platform_device structure. */ void __noreturn ds1685_rtc_poweroff(struct platform_device *pdev) { u8 ctrla, ctrl4a, ctrl4b; struct ds1685_priv *rtc; /* Check for valid RTC data, else, spin forever. */ if (unlikely(!pdev)) { pr_emerg("platform device data not available, spinning forever ...\n"); while(1); unreachable(); } else { /* Get the rtc data. */ rtc = platform_get_drvdata(pdev); /* * Disable our IRQ. We're powering down, so we're not * going to worry about cleaning up. Most of that should * have been taken care of by the shutdown scripts and this * is the final function call. */ if (!rtc->no_irq) disable_irq_nosync(rtc->irq_num); /* Oscillator must be on and the countdown chain enabled. */ ctrla = rtc->read(rtc, RTC_CTRL_A); ctrla |= RTC_CTRL_A_DV1; ctrla &= ~(RTC_CTRL_A_DV2); rtc->write(rtc, RTC_CTRL_A, ctrla); /* * Read Control 4A and check the status of the auxillary * battery. This must be present and working (VRT2 = 1) * for wakeup and kickstart functionality to be useful. */ ds1685_rtc_switch_to_bank1(rtc); ctrl4a = rtc->read(rtc, RTC_EXT_CTRL_4A); if (ctrl4a & RTC_CTRL_4A_VRT2) { /* Clear all of the interrupt flags on Control 4A. */ ctrl4a &= ~(RTC_CTRL_4A_RWK_MASK); rtc->write(rtc, RTC_EXT_CTRL_4A, ctrl4a); /* * The auxillary battery is present and working. * Enable extended functions (ABE=1), enable * wake-up (WIE=1), and enable kickstart (KSE=1) * in Control 4B. */ ctrl4b = rtc->read(rtc, RTC_EXT_CTRL_4B); ctrl4b |= (RTC_CTRL_4B_ABE | RTC_CTRL_4B_WIE | RTC_CTRL_4B_KSE); rtc->write(rtc, RTC_EXT_CTRL_4B, ctrl4b); } /* Set PAB to 1 in Control 4A to power the system down. */ dev_warn(&pdev->dev, "Powerdown.\n"); msleep(20); rtc->write(rtc, RTC_EXT_CTRL_4A, (ctrl4a | RTC_CTRL_4A_PAB)); /* Spin ... we do not switch back to bank0. */ while(1); unreachable(); } } EXPORT_SYMBOL(ds1685_rtc_poweroff); /* ----------------------------------------------------------------------- */ MODULE_AUTHOR("Joshua Kinard <kumba@gentoo.org>"); MODULE_AUTHOR("Matthias Fuchs <matthias.fuchs@esd-electronics.com>"); MODULE_DESCRIPTION("Dallas/Maxim DS1685/DS1687-series RTC driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:rtc-ds1685");
{ "pile_set_name": "Github" }
[Base] ; Pink on White background main_fg = FFFFFF secondary_fg = FFFFFF main_bg = 000000 sidebar_and_player_bg = 000000 tl_selected_hover = EEEEEE cover_overlay_and_shadow = 000000 indicator_fg_and_button_bg = FFFFFF pressing_fg = FF5C86 slider_bg = FFFFFF sidebar_indicator_and_hover_button_bg = FFFFFF sidebar_active_button_fg = 000000 scrollbar_fg_and_selected_row_bg = EBEBEB pressing_button_fg = 000000 pressing_button_bg = FFFFFF selected_button = FE6F61 miscellaneous_bg = 000000 miscellaneous_hover_bg = 383145 preserve_1 = 000000
{ "pile_set_name": "Github" }
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { configureTestBed } from '../../../../testing/unit-test-helper'; import { SharedModule } from '../../../shared/shared.module'; import { RgwUserCapabilityModalComponent } from './rgw-user-capability-modal.component'; describe('RgwUserCapabilityModalComponent', () => { let component: RgwUserCapabilityModalComponent; let fixture: ComponentFixture<RgwUserCapabilityModalComponent>; configureTestBed({ declarations: [RgwUserCapabilityModalComponent], imports: [ReactiveFormsModule, SharedModule, RouterTestingModule], providers: [NgbActiveModal] }); beforeEach(() => { fixture = TestBed.createComponent(RgwUserCapabilityModalComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
{ "pile_set_name": "Github" }
/***************************************************************************/ /* */ /* ftoutln.c */ /* */ /* FreeType outline management (body). */ /* */ /* Copyright 1996-2001, 2002 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* 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. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* All functions are declared in freetype.h. */ /* */ /*************************************************************************/ #include <ft2build.h> #include FT_OUTLINE_H #include FT_INTERNAL_OBJECTS_H /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_outline static const FT_Outline null_outline = { 0, 0, 0, 0, 0, 0 }; /* documentation is in ftoutln.h */ FT_EXPORT_DEF( FT_Error ) FT_Outline_Decompose( FT_Outline* outline, const FT_Outline_Funcs* func_interface, void* user ) { #undef SCALED #define SCALED( x ) ( ( (x) << shift ) - delta ) FT_Vector v_last; FT_Vector v_control; FT_Vector v_start; FT_Vector* point; FT_Vector* limit; char* tags; FT_Error error; FT_Int n; /* index of contour in outline */ FT_UInt first; /* index of first point in contour */ FT_Int tag; /* current point's state */ FT_Int shift; FT_Pos delta; if ( !outline || !func_interface ) return FT_Err_Invalid_Argument; shift = func_interface->shift; delta = func_interface->delta; first = 0; for ( n = 0; n < outline->n_contours; n++ ) { FT_Int last; /* index of last point in contour */ last = outline->contours[n]; limit = outline->points + last; v_start = outline->points[first]; v_last = outline->points[last]; v_start.x = SCALED( v_start.x ); v_start.y = SCALED( v_start.y ); v_last.x = SCALED( v_last.x ); v_last.y = SCALED( v_last.y ); v_control = v_start; point = outline->points + first; tags = outline->tags + first; tag = FT_CURVE_TAG( tags[0] ); /* A contour cannot start with a cubic control point! */ if ( tag == FT_CURVE_TAG_CUBIC ) goto Invalid_Outline; /* check first point to determine origin */ if ( tag == FT_CURVE_TAG_CONIC ) { /* first point is conic control. Yes, this happens. */ if ( FT_CURVE_TAG( outline->tags[last] ) == FT_CURVE_TAG_ON ) { /* start at last point if it is on the curve */ v_start = v_last; limit--; } else { /* if both first and last points are conic, */ /* start at their middle and record its position */ /* for closure */ v_start.x = ( v_start.x + v_last.x ) / 2; v_start.y = ( v_start.y + v_last.y ) / 2; v_last = v_start; } point--; tags--; } error = func_interface->move_to( &v_start, user ); if ( error ) goto Exit; while ( point < limit ) { point++; tags++; tag = FT_CURVE_TAG( tags[0] ); switch ( tag ) { case FT_CURVE_TAG_ON: /* emit a single line_to */ { FT_Vector vec; vec.x = SCALED( point->x ); vec.y = SCALED( point->y ); error = func_interface->line_to( &vec, user ); if ( error ) goto Exit; continue; } case FT_CURVE_TAG_CONIC: /* consume conic arcs */ v_control.x = SCALED( point->x ); v_control.y = SCALED( point->y ); Do_Conic: if ( point < limit ) { FT_Vector vec; FT_Vector v_middle; point++; tags++; tag = FT_CURVE_TAG( tags[0] ); vec.x = SCALED( point->x ); vec.y = SCALED( point->y ); if ( tag == FT_CURVE_TAG_ON ) { error = func_interface->conic_to( &v_control, &vec, user ); if ( error ) goto Exit; continue; } if ( tag != FT_CURVE_TAG_CONIC ) goto Invalid_Outline; v_middle.x = ( v_control.x + vec.x ) / 2; v_middle.y = ( v_control.y + vec.y ) / 2; error = func_interface->conic_to( &v_control, &v_middle, user ); if ( error ) goto Exit; v_control = vec; goto Do_Conic; } error = func_interface->conic_to( &v_control, &v_start, user ); goto Close; default: /* FT_CURVE_TAG_CUBIC */ { FT_Vector vec1, vec2; if ( point + 1 > limit || FT_CURVE_TAG( tags[1] ) != FT_CURVE_TAG_CUBIC ) goto Invalid_Outline; point += 2; tags += 2; vec1.x = SCALED( point[-2].x ); vec1.y = SCALED( point[-2].y ); vec2.x = SCALED( point[-1].x ); vec2.y = SCALED( point[-1].y ); if ( point <= limit ) { FT_Vector vec; vec.x = SCALED( point->x ); vec.y = SCALED( point->y ); error = func_interface->cubic_to( &vec1, &vec2, &vec, user ); if ( error ) goto Exit; continue; } error = func_interface->cubic_to( &vec1, &vec2, &v_start, user ); goto Close; } } } /* close the contour with a line segment */ error = func_interface->line_to( &v_start, user ); Close: if ( error ) goto Exit; first = last + 1; } return 0; Exit: return error; Invalid_Outline: return FT_Err_Invalid_Outline; } FT_EXPORT_DEF( FT_Error ) FT_Outline_New_Internal( FT_Memory memory, FT_UInt numPoints, FT_Int numContours, FT_Outline *anoutline ) { FT_Error error; if ( !anoutline || !memory ) return FT_Err_Invalid_Argument; *anoutline = null_outline; if ( FT_NEW_ARRAY( anoutline->points, numPoints * 2L ) || FT_NEW_ARRAY( anoutline->tags, numPoints ) || FT_NEW_ARRAY( anoutline->contours, numContours ) ) goto Fail; anoutline->n_points = (FT_UShort)numPoints; anoutline->n_contours = (FT_Short)numContours; anoutline->flags |= FT_OUTLINE_OWNER; return FT_Err_Ok; Fail: anoutline->flags |= FT_OUTLINE_OWNER; FT_Outline_Done_Internal( memory, anoutline ); return error; } /* documentation is in ftoutln.h */ FT_EXPORT_DEF( FT_Error ) FT_Outline_New( FT_Library library, FT_UInt numPoints, FT_Int numContours, FT_Outline *anoutline ) { if ( !library ) return FT_Err_Invalid_Library_Handle; return FT_Outline_New_Internal( library->memory, numPoints, numContours, anoutline ); } /* documentation is in ftoutln.h */ FT_EXPORT_DEF( FT_Error ) FT_Outline_Check( FT_Outline* outline ) { if ( outline ) { FT_Int n_points = outline->n_points; FT_Int n_contours = outline->n_contours; FT_Int end0, end; FT_Int n; /* empty glyph? */ if ( n_points == 0 && n_contours == 0 ) return 0; /* check point and contour counts */ if ( n_points <= 0 || n_contours <= 0 ) goto Bad; end0 = end = -1; for ( n = 0; n < n_contours; n++ ) { end = outline->contours[n]; /* note that we don't accept empty contours */ if ( end <= end0 || end >= n_points ) goto Bad; end0 = end; } if ( end != n_points - 1 ) goto Bad; /* XXX: check the tags array */ return 0; } Bad: return FT_Err_Invalid_Argument; } /* documentation is in ftoutln.h */ FT_EXPORT_DEF( FT_Error ) FT_Outline_Copy( FT_Outline* source, FT_Outline *target ) { FT_Int is_owner; if ( !source || !target || source->n_points != target->n_points || source->n_contours != target->n_contours ) return FT_Err_Invalid_Argument; FT_MEM_COPY( target->points, source->points, source->n_points * sizeof ( FT_Vector ) ); FT_MEM_COPY( target->tags, source->tags, source->n_points * sizeof ( FT_Byte ) ); FT_MEM_COPY( target->contours, source->contours, source->n_contours * sizeof ( FT_Short ) ); /* copy all flags, except the `FT_OUTLINE_OWNER' one */ is_owner = target->flags & FT_OUTLINE_OWNER; target->flags = source->flags; target->flags &= ~FT_OUTLINE_OWNER; target->flags |= is_owner; return FT_Err_Ok; } FT_EXPORT_DEF( FT_Error ) FT_Outline_Done_Internal( FT_Memory memory, FT_Outline* outline ) { if ( outline ) { if ( outline->flags & FT_OUTLINE_OWNER ) { FT_FREE( outline->points ); FT_FREE( outline->tags ); FT_FREE( outline->contours ); } *outline = null_outline; return FT_Err_Ok; } else return FT_Err_Invalid_Argument; } /* documentation is in ftoutln.h */ FT_EXPORT_DEF( FT_Error ) FT_Outline_Done( FT_Library library, FT_Outline* outline ) { /* check for valid `outline' in FT_Outline_Done_Internal() */ if ( !library ) return FT_Err_Invalid_Library_Handle; return FT_Outline_Done_Internal( library->memory, outline ); } /* documentation is in ftoutln.h */ FT_EXPORT_DEF( void ) FT_Outline_Get_CBox( FT_Outline* outline, FT_BBox *acbox ) { FT_Pos xMin, yMin, xMax, yMax; if ( outline && acbox ) { if ( outline->n_points == 0 ) { xMin = 0; yMin = 0; xMax = 0; yMax = 0; } else { FT_Vector* vec = outline->points; FT_Vector* limit = vec + outline->n_points; xMin = xMax = vec->x; yMin = yMax = vec->y; vec++; for ( ; vec < limit; vec++ ) { FT_Pos x, y; x = vec->x; if ( x < xMin ) xMin = x; if ( x > xMax ) xMax = x; y = vec->y; if ( y < yMin ) yMin = y; if ( y > yMax ) yMax = y; } } acbox->xMin = xMin; acbox->xMax = xMax; acbox->yMin = yMin; acbox->yMax = yMax; } } /* documentation is in ftoutln.h */ FT_EXPORT_DEF( void ) FT_Outline_Translate( FT_Outline* outline, FT_Pos xOffset, FT_Pos yOffset ) { FT_UShort n; FT_Vector* vec = outline->points; for ( n = 0; n < outline->n_points; n++ ) { vec->x += xOffset; vec->y += yOffset; vec++; } } /* documentation is in ftoutln.h */ FT_EXPORT_DEF( void ) FT_Outline_Reverse( FT_Outline* outline ) { FT_UShort n; FT_Int first, last; first = 0; for ( n = 0; n < outline->n_contours; n++ ) { last = outline->contours[n]; /* reverse point table */ { FT_Vector* p = outline->points + first; FT_Vector* q = outline->points + last; FT_Vector swap; while ( p < q ) { swap = *p; *p = *q; *q = swap; p++; q--; } } /* reverse tags table */ { char* p = outline->tags + first; char* q = outline->tags + last; char swap; while ( p < q ) { swap = *p; *p = *q; *q = swap; p++; q--; } } first = last + 1; } outline->flags ^= FT_OUTLINE_REVERSE_FILL; } /* documentation is in ftoutln.h */ FT_EXPORT_DEF( FT_Error ) FT_Outline_Render( FT_Library library, FT_Outline* outline, FT_Raster_Params* params ) { FT_Error error; FT_Bool update = 0; FT_Renderer renderer; FT_ListNode node; if ( !library ) return FT_Err_Invalid_Library_Handle; if ( !params ) return FT_Err_Invalid_Argument; renderer = library->cur_renderer; node = library->renderers.head; params->source = (void*)outline; error = FT_Err_Cannot_Render_Glyph; while ( renderer ) { error = renderer->raster_render( renderer->raster, params ); if ( !error || FT_ERROR_BASE( error ) != FT_Err_Cannot_Render_Glyph ) break; /* FT_Err_Cannot_Render_Glyph is returned if the render mode */ /* is unsupported by the current renderer for this glyph image */ /* format */ /* now, look for another renderer that supports the same */ /* format */ renderer = FT_Lookup_Renderer( library, FT_GLYPH_FORMAT_OUTLINE, &node ); update = 1; } /* if we changed the current renderer for the glyph image format */ /* we need to select it as the next current one */ if ( !error && update && renderer ) FT_Set_Renderer( library, renderer, 0, 0 ); return error; } /* documentation is in ftoutln.h */ FT_EXPORT_DEF( FT_Error ) FT_Outline_Get_Bitmap( FT_Library library, FT_Outline* outline, FT_Bitmap *abitmap ) { FT_Raster_Params params; if ( !abitmap ) return FT_Err_Invalid_Argument; /* other checks are delayed to FT_Outline_Render() */ params.target = abitmap; params.flags = 0; if ( abitmap->pixel_mode == FT_PIXEL_MODE_GRAY || abitmap->pixel_mode == FT_PIXEL_MODE_LCD || abitmap->pixel_mode == FT_PIXEL_MODE_LCD_V ) params.flags |= FT_RASTER_FLAG_AA; return FT_Outline_Render( library, outline, &params ); } /* documentation is in ftoutln.h */ FT_EXPORT_DEF( void ) FT_Vector_Transform( FT_Vector* vector, FT_Matrix* matrix ) { FT_Pos xz, yz; if ( !vector || !matrix ) return; xz = FT_MulFix( vector->x, matrix->xx ) + FT_MulFix( vector->y, matrix->xy ); yz = FT_MulFix( vector->x, matrix->yx ) + FT_MulFix( vector->y, matrix->yy ); vector->x = xz; vector->y = yz; } /* documentation is in ftoutln.h */ FT_EXPORT_DEF( void ) FT_Outline_Transform( FT_Outline* outline, FT_Matrix* matrix ) { FT_Vector* vec = outline->points; FT_Vector* limit = vec + outline->n_points; for ( ; vec < limit; vec++ ) FT_Vector_Transform( vec, matrix ); } /* END */
{ "pile_set_name": "Github" }
var core = require('./core'); var fs = require('fs'); var path = require('path'); var caller = require('./caller.js'); var nodeModulesPaths = require('./node-modules-paths.js'); module.exports = function (x, opts) { if (!opts) opts = {}; var isFile = opts.isFile || function (file) { try { var stat = fs.statSync(file) } catch (err) { if (err && err.code === 'ENOENT') return false } return stat.isFile() || stat.isFIFO(); }; var readFileSync = opts.readFileSync || fs.readFileSync; var extensions = opts.extensions || [ '.js' ]; var y = opts.basedir || path.dirname(caller()); opts.paths = opts.paths || []; if (x.match(/^(?:\.\.?\/|\/|([A-Za-z]:)?\\)/)) { var m = loadAsFileSync(path.resolve(y, x)) || loadAsDirectorySync(path.resolve(y, x)); if (m) return m; } else { var n = loadNodeModulesSync(x, y); if (n) return n; } if (core[x]) return x; throw new Error("Cannot find module '" + x + "' from '" + y + "'"); function loadAsFileSync (x) { if (isFile(x)) { return x; } for (var i = 0; i < extensions.length; i++) { var file = x + extensions[i]; if (isFile(file)) { return file; } } } function loadAsDirectorySync (x) { var pkgfile = path.join(x, '/package.json'); if (isFile(pkgfile)) { var body = readFileSync(pkgfile, 'utf8'); try { var pkg = JSON.parse(body); if (opts.packageFilter) { pkg = opts.packageFilter(pkg, x); } if (pkg.main) { var m = loadAsFileSync(path.resolve(x, pkg.main)); if (m) return m; var n = loadAsDirectorySync(path.resolve(x, pkg.main)); if (n) return n; } } catch (err) {} } return loadAsFileSync(path.join( x, '/index')); } function loadNodeModulesSync (x, start) { var dirs = nodeModulesPaths(start, opts); for (var i = 0; i < dirs.length; i++) { var dir = dirs[i]; var m = loadAsFileSync(path.join( dir, '/', x)); if (m) return m; var n = loadAsDirectorySync(path.join( dir, '/', x )); if (n) return n; } } };
{ "pile_set_name": "Github" }
{ "_from": "xregexp@2.0.0", "_id": "xregexp@2.0.0", "_inBundle": false, "_integrity": "sha1-UqY+VsoLhKfzpfPWGHLxJq16WUM=", "_location": "/xregexp", "_phantomChildren": {}, "_requested": { "type": "version", "registry": true, "raw": "xregexp@2.0.0", "name": "xregexp", "escapedName": "xregexp", "rawSpec": "2.0.0", "saveSpec": null, "fetchSpec": "2.0.0" }, "_requiredBy": [ "/ftp" ], "_resolved": "https://registry.npmjs.org/xregexp/-/xregexp-2.0.0.tgz", "_shasum": "52a63e56ca0b84a7f3a5f3d61872f126ad7a5943", "_spec": "xregexp@2.0.0", "_where": "/Users/jshore/Documents/Projects/lessons_learned/12_object_playground/node_modules/ftp", "author": { "name": "Steven Levithan", "email": "steves_list@hotmail.com" }, "bugs": { "url": "https://github.com/slevithan/XRegExp/issues" }, "bundleDependencies": false, "deprecated": false, "description": "Extended JavaScript regular expressions", "devDependencies": { "qunit": ">= 0.2.x" }, "engines": { "node": "*" }, "homepage": "http://xregexp.com/", "keywords": [ "regex", "regexp" ], "license": "MIT", "main": "./xregexp-all.js", "name": "xregexp", "repository": { "type": "git", "url": "https://github.com/slevithan/XRegExp.git" }, "scripts": { "test": "node tests/node-qunit.js" }, "version": "2.0.0" }
{ "pile_set_name": "Github" }
// Copyright 2020-present the Material Components for iOS 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. import UIKit import MaterialComponents.MaterialButtons_ButtonThemer import MaterialComponents.MaterialContainerScheme import MaterialComponents.MaterialCards_Theming import MaterialComponents.MaterialButtons_Theming class CustomCard: MDCCard { static let cardWidth: CGFloat = 300; let imageView: UIImageView = UIImageView() let cardButton1: MDCButton = MDCButton() let cardButton2: MDCButton = MDCButton() override func layoutSubviews() { super.layoutSubviews() if imageView.superview == nil { addSubview(imageView) } if cardButton1.superview == nil { addSubview(cardButton1) } if cardButton2.superview == nil { addSubview(cardButton2) } cardButton1.sizeToFit() cardButton2.sizeToFit() imageView.frame = CGRect(x: 0, y: 0, width: CustomCard.cardWidth, height: 200) cardButton1.frame = CGRect(x: 8, y: imageView.frame.maxY + 8, width: cardButton1.frame.width, height: cardButton1.frame.height) cardButton2.frame = CGRect(x: 8, y: cardButton1.frame.maxY + 8, width: cardButton2.frame.width, height: cardButton2.frame.height) } override var intrinsicContentSize: CGSize { return CGSize(width: CustomCard.cardWidth, height: cardButton2.frame.maxY + 8) } } class CardWithImageViewAndButtonsExample: UIViewController { let card: CustomCard = CustomCard() @objc var containerScheme: MDCContainerScheming override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { containerScheme = MDCContainerScheme() super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = containerScheme.colorScheme.backgroundColor } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setUpCard() } func setUpCard() { let bundle = Bundle(for: CardWithImageViewAndButtonsExample.self) card.imageView.image = UIImage(named: "sample-image", in: bundle, compatibleWith: nil) card.cardButton1.setTitle("Action 1", for: .normal) card.cardButton2.setTitle("Action 2", for: .normal) card.cardButton1.applyTextTheme(withScheme: containerScheme) card.cardButton2.applyTextTheme(withScheme: containerScheme) card.cornerRadius = 8 card.applyTheme(withScheme: containerScheme) card.setNeedsLayout() card.layoutIfNeeded() card.frame = CGRect(x: card.frame.minX, y: card.frame.minY, width: card.intrinsicContentSize.width, height: card.intrinsicContentSize.height) if card.superview == nil { view.addSubview(card) } card.center = view.center } } extension CardWithImageViewAndButtonsExample { @objc class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["Cards", "Card README example"], "description": "Cards contain content and actions about a single subject.", "primaryDemo": true, "presentable": true, ] } }
{ "pile_set_name": "Github" }
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var prefix = 'fas'; var iconName = 'arrow-circle-down'; var width = 512; var height = 512; var ligatures = []; var unicode = 'f0ab'; var svgPathData = 'M504 256c0 137-111 248-248 248S8 393 8 256 119 8 256 8s248 111 248 248zm-143.6-28.9L288 302.6V120c0-13.3-10.7-24-24-24h-16c-13.3 0-24 10.7-24 24v182.6l-72.4-75.5c-9.3-9.7-24.8-9.9-34.3-.4l-10.9 11c-9.4 9.4-9.4 24.6 0 33.9L239 404.3c9.4 9.4 24.6 9.4 33.9 0l132.7-132.7c9.4-9.4 9.4-24.6 0-33.9l-10.9-11c-9.5-9.5-25-9.3-34.3.4z'; exports.definition = { prefix: prefix, iconName: iconName, icon: [ width, height, ligatures, unicode, svgPathData ]}; exports.faArrowCircleDown = exports.definition; exports.prefix = prefix; exports.iconName = iconName; exports.width = width; exports.height = height; exports.ligatures = ligatures; exports.unicode = unicode; exports.svgPathData = svgPathData;
{ "pile_set_name": "Github" }
using GVFS.FunctionalTests.FileSystemRunners; using GVFS.FunctionalTests.Properties; using GVFS.FunctionalTests.Should; using GVFS.FunctionalTests.Tools; using GVFS.Tests.Should; using Microsoft.Win32.SafeHandles; using NUnit.Framework; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture { [TestFixture] [Category(Categories.ExtraCoverage)] public class MountTests : TestsWithEnlistmentPerFixture { private const int GVFSGenericError = 3; private const uint GenericRead = 2147483648; private const uint FileFlagBackupSemantics = 3355443; private readonly int fileDeletedBackgroundOperationCode; private readonly int directoryDeletedBackgroundOperationCode; private FileSystemRunner fileSystem; public MountTests() { this.fileSystem = new SystemIORunner(); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { this.fileDeletedBackgroundOperationCode = 16; this.directoryDeletedBackgroundOperationCode = 17; } else { this.fileDeletedBackgroundOperationCode = 3; this.directoryDeletedBackgroundOperationCode = 11; } } [TestCaseSource(typeof(MountSubfolders), MountSubfolders.MountFolders)] public void SecondMountAttemptFails(string mountSubfolder) { this.MountShouldFail(0, "already mounted", this.Enlistment.GetVirtualPathTo(mountSubfolder)); } [TestCase] public void MountFailsOutsideEnlistment() { this.MountShouldFail("is not a valid GVFS enlistment", Path.GetDirectoryName(this.Enlistment.EnlistmentRoot)); } [TestCase] public void MountCopiesMissingReadObjectHook() { this.Enlistment.UnmountGVFS(); string readObjectPath = this.Enlistment.GetDotGitPath("hooks", "read-object" + Settings.Default.BinaryFileNameExtension); readObjectPath.ShouldBeAFile(this.fileSystem); this.fileSystem.DeleteFile(readObjectPath); readObjectPath.ShouldNotExistOnDisk(this.fileSystem); this.Enlistment.MountGVFS(); readObjectPath.ShouldBeAFile(this.fileSystem); } [TestCase] public void MountSetsCoreHooksPath() { try { GVFSHelpers.RegisterForOfflineIO(); this.Enlistment.UnmountGVFS(); GitProcess.Invoke(this.Enlistment.RepoBackingRoot, "config --unset core.hookspath"); string.IsNullOrWhiteSpace( GitProcess.Invoke(this.Enlistment.RepoBackingRoot, "config core.hookspath")) .ShouldBeTrue(); this.Enlistment.MountGVFS(); string expectedHooksPath = this.Enlistment.GetDotGitPath("hooks"); expectedHooksPath = GitHelpers.ConvertPathToGitFormat(expectedHooksPath); GitProcess.Invoke( this.Enlistment.RepoRoot, "config core.hookspath") .Trim('\n') .ShouldEqual(expectedHooksPath); } finally { GVFSHelpers.UnregisterForOfflineIO(); } } [TestCase] [Category(Categories.WindowsOnly)] // Only Windows uses GitHooksLoader.exe and merges hooks public void MountMergesLocalPrePostHooksConfig() { // Create some dummy pre/post command hooks string dummyCommandHookBin = "cmd.exe /c exit 0"; // Confirm git is not already using the dummy hooks string localGitPreCommandHooks = this.Enlistment.GetVirtualPathTo(".git", "hooks", "pre-command.hooks"); localGitPreCommandHooks.ShouldBeAFile(this.fileSystem).WithContents().Contains(dummyCommandHookBin).ShouldBeFalse(); string localGitPostCommandHooks = this.Enlistment.GetVirtualPathTo(".git", "hooks", "post-command.hooks"); localGitPreCommandHooks.ShouldBeAFile(this.fileSystem).WithContents().Contains(dummyCommandHookBin).ShouldBeFalse(); this.Enlistment.UnmountGVFS(); // Create dummy-<pre/post>-command.hooks and set them in the local git config string dummyPreCommandHooksConfig = Path.Combine(this.Enlistment.EnlistmentRoot, "dummy-pre-command.hooks"); this.fileSystem.WriteAllText(dummyPreCommandHooksConfig, dummyCommandHookBin); string dummyOostCommandHooksConfig = Path.Combine(this.Enlistment.EnlistmentRoot, "dummy-post-command.hooks"); this.fileSystem.WriteAllText(dummyOostCommandHooksConfig, dummyCommandHookBin); // Configure the hooks locally GitProcess.Invoke(this.Enlistment.RepoRoot, $"config gvfs.clone.default-pre-command {dummyPreCommandHooksConfig}"); GitProcess.Invoke(this.Enlistment.RepoRoot, $"config gvfs.clone.default-post-command {dummyOostCommandHooksConfig}"); // Mount the repo this.Enlistment.MountGVFS(); // .git\hooks\<pre/post>-command.hooks should now contain our local dummy hook // The dummy pre-command hooks should appear first, and the post-command hook should appear last List<string> mergedPreCommandHooksLines = localGitPreCommandHooks .ShouldBeAFile(this.fileSystem) .WithContents() .Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) .Where(line => !line.StartsWith("#")) .ToList(); mergedPreCommandHooksLines.Count.ShouldEqual(2, $"Expected 2 lines, actual: {string.Join("\n", mergedPreCommandHooksLines)}"); mergedPreCommandHooksLines[0].ShouldEqual(dummyCommandHookBin); List<string> mergedPostCommandHooksLines = localGitPostCommandHooks .ShouldBeAFile(this.fileSystem) .WithContents() .Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) .Where(line => !line.StartsWith("#")) .ToList(); mergedPostCommandHooksLines.Count.ShouldEqual(2, $"Expected 2 lines, actual: {string.Join("\n", mergedPostCommandHooksLines)}"); mergedPostCommandHooksLines[1].ShouldEqual(dummyCommandHookBin); } [TestCase] public void MountChangesMountId() { string mountId = GitProcess.Invoke(this.Enlistment.RepoRoot, "config gvfs.mount-id") .Trim('\n'); this.Enlistment.UnmountGVFS(); this.Enlistment.MountGVFS(); GitProcess.Invoke(this.Enlistment.RepoRoot, "config gvfs.mount-id") .Trim('\n') .ShouldNotEqual(mountId, "gvfs.mount-id should change on every mount"); } [TestCase] public void MountFailsWhenNoOnDiskVersion() { this.Enlistment.UnmountGVFS(); // Get the current disk layout version string majorVersion; string minorVersion; GVFSHelpers.GetPersistedDiskLayoutVersion(this.Enlistment.DotGVFSRoot, out majorVersion, out minorVersion); int majorVersionNum; int minorVersionNum; int.TryParse(majorVersion.ShouldNotBeNull(), out majorVersionNum).ShouldEqual(true); int.TryParse(minorVersion.ShouldNotBeNull(), out minorVersionNum).ShouldEqual(true); // Move the RepoMetadata database to a temp file string versionDatabasePath = Path.Combine(this.Enlistment.DotGVFSRoot, GVFSHelpers.RepoMetadataName); versionDatabasePath.ShouldBeAFile(this.fileSystem); string tempDatabasePath = versionDatabasePath + "_MountFailsWhenNoOnDiskVersion"; tempDatabasePath.ShouldNotExistOnDisk(this.fileSystem); this.fileSystem.MoveFile(versionDatabasePath, tempDatabasePath); versionDatabasePath.ShouldNotExistOnDisk(this.fileSystem); this.MountShouldFail("Failed to upgrade repo disk layout"); // Move the RepoMetadata database back this.fileSystem.DeleteFile(versionDatabasePath); this.fileSystem.MoveFile(tempDatabasePath, versionDatabasePath); tempDatabasePath.ShouldNotExistOnDisk(this.fileSystem); versionDatabasePath.ShouldBeAFile(this.fileSystem); this.Enlistment.MountGVFS(); } [TestCase] public void MountFailsWhenNoLocalCacheRootInRepoMetadata() { this.Enlistment.UnmountGVFS(); string majorVersion; string minorVersion; GVFSHelpers.GetPersistedDiskLayoutVersion(this.Enlistment.DotGVFSRoot, out majorVersion, out minorVersion); majorVersion.ShouldNotBeNull(); minorVersion.ShouldNotBeNull(); string objectsRoot = GVFSHelpers.GetPersistedGitObjectsRoot(this.Enlistment.DotGVFSRoot).ShouldNotBeNull(); string metadataPath = Path.Combine(this.Enlistment.DotGVFSRoot, GVFSHelpers.RepoMetadataName); string metadataBackupPath = metadataPath + ".backup"; this.fileSystem.MoveFile(metadataPath, metadataBackupPath); this.fileSystem.CreateEmptyFile(metadataPath); GVFSHelpers.SaveDiskLayoutVersion(this.Enlistment.DotGVFSRoot, majorVersion, minorVersion); GVFSHelpers.SaveGitObjectsRoot(this.Enlistment.DotGVFSRoot, objectsRoot); this.MountShouldFail("Failed to determine local cache path from repo metadata"); this.fileSystem.DeleteFile(metadataPath); this.fileSystem.MoveFile(metadataBackupPath, metadataPath); this.Enlistment.MountGVFS(); } [TestCase] public void MountFailsWhenNoGitObjectsRootInRepoMetadata() { this.Enlistment.UnmountGVFS(); string majorVersion; string minorVersion; GVFSHelpers.GetPersistedDiskLayoutVersion(this.Enlistment.DotGVFSRoot, out majorVersion, out minorVersion); majorVersion.ShouldNotBeNull(); minorVersion.ShouldNotBeNull(); string localCacheRoot = GVFSHelpers.GetPersistedLocalCacheRoot(this.Enlistment.DotGVFSRoot).ShouldNotBeNull(); string metadataPath = Path.Combine(this.Enlistment.DotGVFSRoot, GVFSHelpers.RepoMetadataName); string metadataBackupPath = metadataPath + ".backup"; this.fileSystem.MoveFile(metadataPath, metadataBackupPath); this.fileSystem.CreateEmptyFile(metadataPath); GVFSHelpers.SaveDiskLayoutVersion(this.Enlistment.DotGVFSRoot, majorVersion, minorVersion); GVFSHelpers.SaveLocalCacheRoot(this.Enlistment.DotGVFSRoot, localCacheRoot); this.MountShouldFail("Failed to determine git objects root from repo metadata"); this.fileSystem.DeleteFile(metadataPath); this.fileSystem.MoveFile(metadataBackupPath, metadataPath); this.Enlistment.MountGVFS(); } [TestCase] public void MountRegeneratesAlternatesFileWhenMissingGitObjectsRoot() { this.Enlistment.UnmountGVFS(); string objectsRoot = GVFSHelpers.GetPersistedGitObjectsRoot(this.Enlistment.DotGVFSRoot).ShouldNotBeNull(); string alternatesFilePath = this.Enlistment.GetDotGitPath("objects", "info", "alternates"); alternatesFilePath.ShouldBeAFile(this.fileSystem).WithContents(objectsRoot); this.fileSystem.WriteAllText(alternatesFilePath, "Z:\\invalidPath"); this.Enlistment.MountGVFS(); alternatesFilePath.ShouldBeAFile(this.fileSystem).WithContents(objectsRoot); } [TestCase] public void MountRegeneratesAlternatesFileWhenMissingFromDisk() { this.Enlistment.UnmountGVFS(); string objectsRoot = GVFSHelpers.GetPersistedGitObjectsRoot(this.Enlistment.DotGVFSRoot).ShouldNotBeNull(); string alternatesFilePath = this.Enlistment.GetDotGitPath("objects", "info", "alternates"); alternatesFilePath.ShouldBeAFile(this.fileSystem).WithContents(objectsRoot); this.fileSystem.DeleteFile(alternatesFilePath); this.Enlistment.MountGVFS(); alternatesFilePath.ShouldBeAFile(this.fileSystem).WithContents(objectsRoot); } [TestCase] public void MountCanProcessSavedBackgroundQueueTasks() { string deletedFileEntry = "Test_EPF_WorkingDirectoryTests/1/2/3/4/ReadDeepProjectedFile.cpp"; string deletedDirEntry = "Test_EPF_WorkingDirectoryTests/1/2/3/4/"; GVFSHelpers.ModifiedPathsShouldNotContain(this.Enlistment, this.fileSystem, deletedFileEntry); GVFSHelpers.ModifiedPathsShouldNotContain(this.Enlistment, this.fileSystem, deletedDirEntry); this.Enlistment.UnmountGVFS(); // Prime the background queue with delete messages string deleteFilePath = Path.Combine("Test_EPF_WorkingDirectoryTests", "1", "2", "3", "4", "ReadDeepProjectedFile.cpp"); string deleteDirPath = Path.Combine("Test_EPF_WorkingDirectoryTests", "1", "2", "3", "4"); string persistedDeleteFileTask = $"A 1\0{this.fileDeletedBackgroundOperationCode}\0{deleteFilePath}\0"; string persistedDeleteDirectoryTask = $"A 2\0{this.directoryDeletedBackgroundOperationCode}\0{deleteDirPath}\0"; this.fileSystem.WriteAllText( Path.Combine(this.Enlistment.EnlistmentRoot, GVFSTestConfig.DotGVFSRoot, "databases", "BackgroundGitOperations.dat"), $"{persistedDeleteFileTask}\r\n{persistedDeleteDirectoryTask}\r\n"); // Background queue should process the delete messages and modifiedPaths should show the change this.Enlistment.MountGVFS(); this.Enlistment.WaitForBackgroundOperations(); GVFSHelpers.ModifiedPathsShouldContain(this.Enlistment, this.fileSystem, deletedFileEntry); GVFSHelpers.ModifiedPathsShouldContain(this.Enlistment, this.fileSystem, deletedDirEntry); } [TestCase] public void MountingARepositoryThatRequiresPlaceholderUpdatesWorks() { string placeholderRelativePath = Path.Combine("EnumerateAndReadTestFiles", "a.txt"); string placeholderPath = this.Enlistment.GetVirtualPathTo(placeholderRelativePath); // Ensure the placeholder is on disk and hydrated placeholderPath.ShouldBeAFile(this.fileSystem).WithContents(); this.Enlistment.UnmountGVFS(); File.Delete(placeholderPath); GVFSHelpers.DeletePlaceholder( Path.Combine(this.Enlistment.DotGVFSRoot, TestConstants.Databases.VFSForGit), placeholderRelativePath); GVFSHelpers.SetPlaceholderUpdatesRequired(this.Enlistment.DotGVFSRoot, true); this.Enlistment.MountGVFS(); } [TestCaseSource(typeof(MountSubfolders), MountSubfolders.MountFolders)] public void MountFailsAfterBreakingDowngrade(string mountSubfolder) { MountSubfolders.EnsureSubfoldersOnDisk(this.Enlistment, this.fileSystem); this.Enlistment.UnmountGVFS(); string majorVersion; string minorVersion; GVFSHelpers.GetPersistedDiskLayoutVersion(this.Enlistment.DotGVFSRoot, out majorVersion, out minorVersion); int majorVersionNum; int minorVersionNum; int.TryParse(majorVersion.ShouldNotBeNull(), out majorVersionNum).ShouldEqual(true); int.TryParse(minorVersion.ShouldNotBeNull(), out minorVersionNum).ShouldEqual(true); GVFSHelpers.SaveDiskLayoutVersion(this.Enlistment.DotGVFSRoot, (majorVersionNum + 1).ToString(), "0"); this.MountShouldFail("do not allow mounting after downgrade", this.Enlistment.GetVirtualPathTo(mountSubfolder)); GVFSHelpers.SaveDiskLayoutVersion(this.Enlistment.DotGVFSRoot, majorVersionNum.ToString(), minorVersionNum.ToString()); this.Enlistment.MountGVFS(); } [TestCaseSource(typeof(MountSubfolders), MountSubfolders.MountFolders)] public void MountFailsUpgradingFromInvalidUpgradePath(string mountSubfolder) { MountSubfolders.EnsureSubfoldersOnDisk(this.Enlistment, this.fileSystem); string headCommitId = GitProcess.Invoke(this.Enlistment.RepoRoot, "rev-parse HEAD"); this.Enlistment.UnmountGVFS(); string majorVersion; string minorVersion; GVFSHelpers.GetPersistedDiskLayoutVersion(this.Enlistment.DotGVFSRoot, out majorVersion, out minorVersion); int majorVersionNum; int minorVersionNum; int.TryParse(majorVersion.ShouldNotBeNull(), out majorVersionNum).ShouldEqual(true); int.TryParse(minorVersion.ShouldNotBeNull(), out minorVersionNum).ShouldEqual(true); // 1 will always be below the minumum support version number GVFSHelpers.SaveDiskLayoutVersion(this.Enlistment.DotGVFSRoot, "1", "0"); this.MountShouldFail("Breaking change to GVFS disk layout has been made since cloning", this.Enlistment.GetVirtualPathTo(mountSubfolder)); GVFSHelpers.SaveDiskLayoutVersion(this.Enlistment.DotGVFSRoot, majorVersionNum.ToString(), minorVersionNum.ToString()); this.Enlistment.MountGVFS(); } // Ported from ProjFS's BugRegressionTest [TestCase] [Category(Categories.WindowsOnly)] public void ProjFS_CMDHangNoneActiveInstance() { this.Enlistment.UnmountGVFS(); using (SafeFileHandle handle = NativeMethods.CreateFile( Path.Combine(this.Enlistment.RepoRoot, "aaa", "aaaa"), GenericRead, FileShare.Read, IntPtr.Zero, FileMode.Open, FileFlagBackupSemantics, IntPtr.Zero)) { int lastError = Marshal.GetLastWin32Error(); handle.IsInvalid.ShouldEqual(true); lastError.ShouldNotEqual(0); // 0 == ERROR_SUCCESS } this.Enlistment.MountGVFS(); } private void MountShouldFail(int expectedExitCode, string expectedErrorMessage, string mountWorkingDirectory = null) { string enlistmentRoot = this.Enlistment.EnlistmentRoot; // TODO: 865304 Use app.config instead of --internal* arguments ProcessStartInfo processInfo = new ProcessStartInfo(GVFSTestConfig.PathToGVFS); processInfo.Arguments = "mount " + TestConstants.InternalUseOnlyFlag + " " + GVFSHelpers.GetInternalParameter(); processInfo.WindowStyle = ProcessWindowStyle.Hidden; processInfo.WorkingDirectory = string.IsNullOrEmpty(mountWorkingDirectory) ? enlistmentRoot : mountWorkingDirectory; processInfo.UseShellExecute = false; processInfo.RedirectStandardOutput = true; ProcessResult result = ProcessHelper.Run(processInfo); result.ExitCode.ShouldEqual(expectedExitCode, $"mount exit code was not {expectedExitCode}. Output: {result.Output}"); result.Output.ShouldContain(expectedErrorMessage); } private void MountShouldFail(string expectedErrorMessage, string mountWorkingDirectory = null) { this.MountShouldFail(GVFSGenericError, expectedErrorMessage, mountWorkingDirectory); } private class MountSubfolders { public const string MountFolders = "Folders"; public static object[] Folders { get { // On Linux, an unmounted repository is completely empty, so we must // only try to mount from the root of the virtual path. if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return new object[] { new object[] { string.Empty } }; } else { return new object[] { new object[] { string.Empty }, new object[] { "GVFS" }, }; } } } public static void EnsureSubfoldersOnDisk(GVFSFunctionalTestEnlistment enlistment, FileSystemRunner fileSystem) { // Enumerate the directory to ensure that the folder is on disk after GVFS is unmounted foreach (object[] folder in Folders) { string folderPath = enlistment.GetVirtualPathTo((string)folder[0]); folderPath.ShouldBeADirectory(fileSystem).WithItems(); } } } } }
{ "pile_set_name": "Github" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.loiane.cursojava.aula36.labs; /** * * @author loiane */ public class Curso { private String nome; private String horario; private Professor professor; private Aluno[] alunos; /** * @return the nome */ public String getNome() { return nome; } /** * @param nome the nome to set */ public void setNome(String nome) { this.nome = nome; } /** * @return the horario */ public String getHorario() { return horario; } /** * @param horario the horario to set */ public void setHorario(String horario) { this.horario = horario; } /** * @return the professor */ public Professor getProfessor() { return professor; } /** * @param professor the professor to set */ public void setProfessor(Professor professor) { this.professor = professor; } /** * @return the alunos */ public Aluno[] getAlunos() { return alunos; } /** * @param alunos the alunos to set */ public void setAlunos(Aluno[] alunos) { this.alunos = alunos; } public String obterInfo(){ String info = "Nome do Curso = " + nome + "\n"; if (professor != null){ info += professor.obterInfo(); } if (alunos != null){ System.out.println("---Alunos---"); for (Aluno aluno : alunos){ if (aluno != null){ info += aluno.obterInfo(); info += "\n"; } } info += "\nMédia da turma = " + obterMediaTurma(); } return info; } public double obterMediaTurma(){ double soma = 0; for (Aluno aluno : alunos){ if (aluno != null){ soma += aluno.obterMedia(); } } return soma/alunos.length; } }
{ "pile_set_name": "Github" }
// // FCViewController.swift // Example // // Created by Teodor Patras on 15/07/16. // Copyright © 2016 teodorpatras. All rights reserved. // import UIKit class FCViewController: CacheableViewController { override class var cacheIdentifier: String { return "FCViewController" } override func viewDidLoad() { super.viewDidLoad() self.title = "First" view.backgroundColor = UIColor(hue:0.57, saturation:0.90, brightness:0.53, alpha:1.00) } }
{ "pile_set_name": "Github" }
/** * Copyright 2019 The JoyQueue 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.joyqueue;
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>files</key> <dict> <key>Headers/FLEX-umbrella.h</key> <data> jkYe0X5631Pe2dyo+Due1BoBzKU= </data> <key>Headers/FLEXArgumentInputColorView.h</key> <data> /AvvZZ7LZpmFhJlrs4ClVsd/tn0= </data> <key>Headers/FLEXArgumentInputFontView.h</key> <data> 9SYBA/Ki3qwlnz21Z27XhvbVjJ8= </data> <key>Headers/FLEXArgumentInputFontsPickerView.h</key> <data> dy3ES8NU12/+WMjO9VCD2/CaWMQ= </data> <key>Headers/FLEXArgumentInputJSONObjectView.h</key> <data> S4wmImQl3cKegXuZa3enbhFkJDw= </data> <key>Headers/FLEXArgumentInputNotSupportedView.h</key> <data> 06uFCfHn95vzctSdKthCSX0UvOo= </data> <key>Headers/FLEXArgumentInputNumberView.h</key> <data> tbuB/lbCiYCae8KolMsZn1DjSL0= </data> <key>Headers/FLEXArgumentInputStringView.h</key> <data> 8YrgqC0rHGg05t+QIbsllMUzRdQ= </data> <key>Headers/FLEXArgumentInputStructView.h</key> <data> U/StPm8HBUc2QFP+YK7fyW+nSWY= </data> <key>Headers/FLEXArgumentInputSwitchView.h</key> <data> qU01gaAsms4itNghkU5b34vR1UU= </data> <key>Headers/FLEXArgumentInputTextView.h</key> <data> hSYqqVf+WyeD95rTiVEw7Cmc8Cc= </data> <key>Headers/FLEXArgumentInputView.h</key> <data> Oc0nnEgfgbYnPgvPpj8KEJakGnQ= </data> <key>Headers/FLEXArgumentInputViewFactory.h</key> <data> lTL4Lj0fXaAXWYFw0pW4SOCbYdc= </data> <key>Headers/FLEXArrayExplorerViewController.h</key> <data> HH72ZQ/svQdcQTec9FLGhJdrcAQ= </data> <key>Headers/FLEXClassExplorerViewController.h</key> <data> FL7HSz9/olhLejidvmIM42DqVys= </data> <key>Headers/FLEXClassesTableViewController.h</key> <data> 4QZYnP0LoHF+iLM+MkdJW6Sl13w= </data> <key>Headers/FLEXDefaultEditorViewController.h</key> <data> hT19z1LkdITSH6uY5oXfTRXrV/s= </data> <key>Headers/FLEXDefaultsExplorerViewController.h</key> <data> mxhRjUH//rcYFMkUluHsqggZ0Ww= </data> <key>Headers/FLEXDescriptionTableViewCell.h</key> <data> abpen+jaFEVX4tbA26Lbb5N0f+c= </data> <key>Headers/FLEXDictionaryExplorerViewController.h</key> <data> LtXGC2ayUQds4L8/vJpW7su+jGQ= </data> <key>Headers/FLEXExplorerToolbar.h</key> <data> nX5cKikkZfajxbYV0PsBqQ56CaQ= </data> <key>Headers/FLEXExplorerViewController.h</key> <data> so0wUBrUW5ZyBasU3kL66AYKQP4= </data> <key>Headers/FLEXFieldEditorView.h</key> <data> /ObvFP0oNQKWJvMZ5cqJTpTiyPo= </data> <key>Headers/FLEXFieldEditorViewController.h</key> <data> G9RXNlKXswwyvnMBi1+ngxL5CEM= </data> <key>Headers/FLEXFileBrowserTableViewController.h</key> <data> nJLi9AUUMCnvH9BOIBhY0YK/grM= </data> <key>Headers/FLEXGlobalsTableViewController.h</key> <data> 5MbjfhK1K1h+CrP+Ywxnc6fGeLU= </data> <key>Headers/FLEXGlobalsTableViewControllerEntry.h</key> <data> bMLmx/FqdV8QzUOD7E59ys7DES0= </data> <key>Headers/FLEXHeapEnumerator.h</key> <data> U6c/tBOEBatjPgqFrTHdqgsgQuY= </data> <key>Headers/FLEXHierarchyTableViewCell.h</key> <data> QvHOk18sHiS+7CS0mHwnXZhKpK0= </data> <key>Headers/FLEXHierarchyTableViewController.h</key> <data> AAQ+3YKnwOEtMqU0saKt1GEgxS8= </data> <key>Headers/FLEXImageExplorerViewController.h</key> <data> 1r/AbkFwnmWz945Sjc/Lynt+k0g= </data> <key>Headers/FLEXImagePreviewViewController.h</key> <data> lBNrbxEB9qWL3FmLGp71su9yjMg= </data> <key>Headers/FLEXInstancesTableViewController.h</key> <data> ps9sSlChvSdoWMPoddpplUtH4yM= </data> <key>Headers/FLEXIvarEditorViewController.h</key> <data> zCC+qV8f7tG1MCy/2kdLtYdYN24= </data> <key>Headers/FLEXLibrariesTableViewController.h</key> <data> yM7SnjrlqhKLcKGctQZ+aim38XQ= </data> <key>Headers/FLEXLiveObjectsTableViewController.h</key> <data> KUM7uV2RFWFO+lVSvy5nMz7hTPQ= </data> <key>Headers/FLEXManager+Private.h</key> <data> mRWLnB70Q84L97eihjespQCmkeY= </data> <key>Headers/FLEXManager.h</key> <data> 0PhUXfaPKlHBySUFT7NqsxfvHoE= </data> <key>Headers/FLEXMethodCallingViewController.h</key> <data> qQroNe3Z2KNvAejDOFaZbwilw2M= </data> <key>Headers/FLEXObjectExplorerFactory.h</key> <data> Zi3Yb51os5bvz2U9zr3pZ0GBqJ4= </data> <key>Headers/FLEXObjectExplorerViewController.h</key> <data> ifeeEh4aBlL13NwjF88pL2OFUHw= </data> <key>Headers/FLEXPropertyEditorViewController.h</key> <data> QXE72Ss4G56iUq51vMHPAOkMyXI= </data> <key>Headers/FLEXResources.h</key> <data> AbsWSKtiIBh0Bho04FLi8MQd3VI= </data> <key>Headers/FLEXRuntimeUtility.h</key> <data> 3myp2xe0niqCokrsRGRJODnvsx0= </data> <key>Headers/FLEXSetExplorerViewController.h</key> <data> ViJeODn5GTzd5oW1z4gd9uVQTZM= </data> <key>Headers/FLEXToolbarItem.h</key> <data> s9ITH6WZDOaHkAPdlqVFfHxaUVI= </data> <key>Headers/FLEXUtility.h</key> <data> Tbicvp2iw4g5jV6MPDjY16/w4GU= </data> <key>Headers/FLEXViewControllerExplorerViewController.h</key> <data> sDj6PDerE0JBwRzPAuyqJ2WBb08= </data> <key>Headers/FLEXViewExplorerViewController.h</key> <data> er6Aa4f40yU6Zo/NCNjRXniTNg4= </data> <key>Headers/FLEXWebViewController.h</key> <data> gWGmoUmd/3tJgPRYWnALyFcG3/g= </data> <key>Headers/FLEXWindow.h</key> <data> 1MpkxaeRHksJaf8cwQ2wgcQy+oE= </data> <key>Info.plist</key> <data> +gO2cJ2iKRzL6cUHDeqCk27WJDM= </data> <key>Modules/module.modulemap</key> <data> aEuw8usei7rJ9P5TK/3F9jEeSeY= </data> </dict> <key>files2</key> <dict> <key>Headers/FLEX-umbrella.h</key> <data> jkYe0X5631Pe2dyo+Due1BoBzKU= </data> <key>Headers/FLEXArgumentInputColorView.h</key> <data> /AvvZZ7LZpmFhJlrs4ClVsd/tn0= </data> <key>Headers/FLEXArgumentInputFontView.h</key> <data> 9SYBA/Ki3qwlnz21Z27XhvbVjJ8= </data> <key>Headers/FLEXArgumentInputFontsPickerView.h</key> <data> dy3ES8NU12/+WMjO9VCD2/CaWMQ= </data> <key>Headers/FLEXArgumentInputJSONObjectView.h</key> <data> S4wmImQl3cKegXuZa3enbhFkJDw= </data> <key>Headers/FLEXArgumentInputNotSupportedView.h</key> <data> 06uFCfHn95vzctSdKthCSX0UvOo= </data> <key>Headers/FLEXArgumentInputNumberView.h</key> <data> tbuB/lbCiYCae8KolMsZn1DjSL0= </data> <key>Headers/FLEXArgumentInputStringView.h</key> <data> 8YrgqC0rHGg05t+QIbsllMUzRdQ= </data> <key>Headers/FLEXArgumentInputStructView.h</key> <data> U/StPm8HBUc2QFP+YK7fyW+nSWY= </data> <key>Headers/FLEXArgumentInputSwitchView.h</key> <data> qU01gaAsms4itNghkU5b34vR1UU= </data> <key>Headers/FLEXArgumentInputTextView.h</key> <data> hSYqqVf+WyeD95rTiVEw7Cmc8Cc= </data> <key>Headers/FLEXArgumentInputView.h</key> <data> Oc0nnEgfgbYnPgvPpj8KEJakGnQ= </data> <key>Headers/FLEXArgumentInputViewFactory.h</key> <data> lTL4Lj0fXaAXWYFw0pW4SOCbYdc= </data> <key>Headers/FLEXArrayExplorerViewController.h</key> <data> HH72ZQ/svQdcQTec9FLGhJdrcAQ= </data> <key>Headers/FLEXClassExplorerViewController.h</key> <data> FL7HSz9/olhLejidvmIM42DqVys= </data> <key>Headers/FLEXClassesTableViewController.h</key> <data> 4QZYnP0LoHF+iLM+MkdJW6Sl13w= </data> <key>Headers/FLEXDefaultEditorViewController.h</key> <data> hT19z1LkdITSH6uY5oXfTRXrV/s= </data> <key>Headers/FLEXDefaultsExplorerViewController.h</key> <data> mxhRjUH//rcYFMkUluHsqggZ0Ww= </data> <key>Headers/FLEXDescriptionTableViewCell.h</key> <data> abpen+jaFEVX4tbA26Lbb5N0f+c= </data> <key>Headers/FLEXDictionaryExplorerViewController.h</key> <data> LtXGC2ayUQds4L8/vJpW7su+jGQ= </data> <key>Headers/FLEXExplorerToolbar.h</key> <data> nX5cKikkZfajxbYV0PsBqQ56CaQ= </data> <key>Headers/FLEXExplorerViewController.h</key> <data> so0wUBrUW5ZyBasU3kL66AYKQP4= </data> <key>Headers/FLEXFieldEditorView.h</key> <data> /ObvFP0oNQKWJvMZ5cqJTpTiyPo= </data> <key>Headers/FLEXFieldEditorViewController.h</key> <data> G9RXNlKXswwyvnMBi1+ngxL5CEM= </data> <key>Headers/FLEXFileBrowserTableViewController.h</key> <data> nJLi9AUUMCnvH9BOIBhY0YK/grM= </data> <key>Headers/FLEXGlobalsTableViewController.h</key> <data> 5MbjfhK1K1h+CrP+Ywxnc6fGeLU= </data> <key>Headers/FLEXGlobalsTableViewControllerEntry.h</key> <data> bMLmx/FqdV8QzUOD7E59ys7DES0= </data> <key>Headers/FLEXHeapEnumerator.h</key> <data> U6c/tBOEBatjPgqFrTHdqgsgQuY= </data> <key>Headers/FLEXHierarchyTableViewCell.h</key> <data> QvHOk18sHiS+7CS0mHwnXZhKpK0= </data> <key>Headers/FLEXHierarchyTableViewController.h</key> <data> AAQ+3YKnwOEtMqU0saKt1GEgxS8= </data> <key>Headers/FLEXImageExplorerViewController.h</key> <data> 1r/AbkFwnmWz945Sjc/Lynt+k0g= </data> <key>Headers/FLEXImagePreviewViewController.h</key> <data> lBNrbxEB9qWL3FmLGp71su9yjMg= </data> <key>Headers/FLEXInstancesTableViewController.h</key> <data> ps9sSlChvSdoWMPoddpplUtH4yM= </data> <key>Headers/FLEXIvarEditorViewController.h</key> <data> zCC+qV8f7tG1MCy/2kdLtYdYN24= </data> <key>Headers/FLEXLibrariesTableViewController.h</key> <data> yM7SnjrlqhKLcKGctQZ+aim38XQ= </data> <key>Headers/FLEXLiveObjectsTableViewController.h</key> <data> KUM7uV2RFWFO+lVSvy5nMz7hTPQ= </data> <key>Headers/FLEXManager+Private.h</key> <data> mRWLnB70Q84L97eihjespQCmkeY= </data> <key>Headers/FLEXManager.h</key> <data> 0PhUXfaPKlHBySUFT7NqsxfvHoE= </data> <key>Headers/FLEXMethodCallingViewController.h</key> <data> qQroNe3Z2KNvAejDOFaZbwilw2M= </data> <key>Headers/FLEXObjectExplorerFactory.h</key> <data> Zi3Yb51os5bvz2U9zr3pZ0GBqJ4= </data> <key>Headers/FLEXObjectExplorerViewController.h</key> <data> ifeeEh4aBlL13NwjF88pL2OFUHw= </data> <key>Headers/FLEXPropertyEditorViewController.h</key> <data> QXE72Ss4G56iUq51vMHPAOkMyXI= </data> <key>Headers/FLEXResources.h</key> <data> AbsWSKtiIBh0Bho04FLi8MQd3VI= </data> <key>Headers/FLEXRuntimeUtility.h</key> <data> 3myp2xe0niqCokrsRGRJODnvsx0= </data> <key>Headers/FLEXSetExplorerViewController.h</key> <data> ViJeODn5GTzd5oW1z4gd9uVQTZM= </data> <key>Headers/FLEXToolbarItem.h</key> <data> s9ITH6WZDOaHkAPdlqVFfHxaUVI= </data> <key>Headers/FLEXUtility.h</key> <data> Tbicvp2iw4g5jV6MPDjY16/w4GU= </data> <key>Headers/FLEXViewControllerExplorerViewController.h</key> <data> sDj6PDerE0JBwRzPAuyqJ2WBb08= </data> <key>Headers/FLEXViewExplorerViewController.h</key> <data> er6Aa4f40yU6Zo/NCNjRXniTNg4= </data> <key>Headers/FLEXWebViewController.h</key> <data> gWGmoUmd/3tJgPRYWnALyFcG3/g= </data> <key>Headers/FLEXWindow.h</key> <data> 1MpkxaeRHksJaf8cwQ2wgcQy+oE= </data> <key>Modules/module.modulemap</key> <data> aEuw8usei7rJ9P5TK/3F9jEeSeY= </data> </dict> <key>rules</key> <dict> <key>^</key> <true/> <key>^.*\.lproj/</key> <dict> <key>optional</key> <true/> <key>weight</key> <real>1000</real> </dict> <key>^.*\.lproj/locversion.plist$</key> <dict> <key>omit</key> <true/> <key>weight</key> <real>1100</real> </dict> <key>^version.plist$</key> <true/> </dict> <key>rules2</key> <dict> <key>.*\.dSYM($|/)</key> <dict> <key>weight</key> <real>11</real> </dict> <key>^</key> <dict> <key>weight</key> <real>20</real> </dict> <key>^(.*/)?\.DS_Store$</key> <dict> <key>omit</key> <true/> <key>weight</key> <real>2000</real> </dict> <key>^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/</key> <dict> <key>nested</key> <true/> <key>weight</key> <real>10</real> </dict> <key>^.*</key> <true/> <key>^.*\.lproj/</key> <dict> <key>optional</key> <true/> <key>weight</key> <real>1000</real> </dict> <key>^.*\.lproj/locversion.plist$</key> <dict> <key>omit</key> <true/> <key>weight</key> <real>1100</real> </dict> <key>^Info\.plist$</key> <dict> <key>omit</key> <true/> <key>weight</key> <real>20</real> </dict> <key>^PkgInfo$</key> <dict> <key>omit</key> <true/> <key>weight</key> <real>20</real> </dict> <key>^[^/]+$</key> <dict> <key>nested</key> <true/> <key>weight</key> <real>10</real> </dict> <key>^embedded\.provisionprofile$</key> <dict> <key>weight</key> <real>20</real> </dict> <key>^version\.plist$</key> <dict> <key>weight</key> <real>20</real> </dict> </dict> </dict> </plist>
{ "pile_set_name": "Github" }
## Double ## Infinity -Infinity Infinity Infinity -Infinity Infinity ## Float ## Infinity -Infinity Infinity Infinity -Infinity Infinity
{ "pile_set_name": "Github" }
/* cryptmodule.c - by Steve Majewski */ #include "Python.h" #include <sys/types.h> #ifdef __VMS #include <openssl/des.h> #endif /* Module crypt */ static PyObject *crypt_crypt(PyObject *self, PyObject *args) { char *word, *salt; #ifndef __VMS extern char * crypt(const char *, const char *); #endif if (!PyArg_ParseTuple(args, "ss:crypt", &word, &salt)) { return NULL; } /* On some platforms (AtheOS) crypt returns NULL for an invalid salt. Return None in that case. XXX Maybe raise an exception? */ return Py_BuildValue("s", crypt(word, salt)); } PyDoc_STRVAR(crypt_crypt__doc__, "crypt(word, salt) -> string\n\ word will usually be a user's password. salt is a 2-character string\n\ which will be used to select one of 4096 variations of DES. The characters\n\ in salt must be either \".\", \"/\", or an alphanumeric character. Returns\n\ the hashed password as a string, which will be composed of characters from\n\ the same alphabet as the salt."); static PyMethodDef crypt_methods[] = { {"crypt", crypt_crypt, METH_VARARGS, crypt_crypt__doc__}, {NULL, NULL} /* sentinel */ }; PyMODINIT_FUNC initcrypt(void) { Py_InitModule("crypt", crypt_methods); }
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: MIT // Copyright (c) 2015-2020 Zig Contributors // This file is part of [zig](https://ziglang.org/), which is MIT licensed. // The MIT license requires this copyright notice to be included in all copies // and substantial portions of the software. // Ported from: // // https://github.com/llvm/llvm-project/blob/2ffb1b0413efa9a24eb3c49e710e36f92e2cb50b/compiler-rt/lib/builtins/modti3.c const udivmod = @import("udivmod.zig").udivmod; const builtin = @import("builtin"); const compiler_rt = @import("../compiler_rt.zig"); pub fn __modti3(a: i128, b: i128) callconv(.C) i128 { @setRuntimeSafety(builtin.is_test); const s_a = a >> (128 - 1); // s = a < 0 ? -1 : 0 const s_b = b >> (128 - 1); // s = b < 0 ? -1 : 0 const an = (a ^ s_a) -% s_a; // negate if s == -1 const bn = (b ^ s_b) -% s_b; // negate if s == -1 var r: u128 = undefined; _ = udivmod(u128, @bitCast(u128, an), @bitCast(u128, bn), &r); return (@bitCast(i128, r) ^ s_a) -% s_a; // negate if s == -1 } const v128 = @import("std").meta.Vector(2, u64); pub fn __modti3_windows_x86_64(a: v128, b: v128) callconv(.C) v128 { return @bitCast(v128, @call(.{ .modifier = .always_inline }, __modti3, .{ @bitCast(i128, a), @bitCast(i128, b), })); } test "import modti3" { _ = @import("modti3_test.zig"); }
{ "pile_set_name": "Github" }
// // MobClick.h // Analytics // // Copyright (C) 2010-2017 Umeng.com . All rights reserved. #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> typedef void(^CallbackBlock)(); /** 统计的场景类别,默认为普通统计;若使用游戏统计API,则需选择游戏场景类别,如E_UM_GAME。 */ typedef NS_ENUM (NSUInteger, eScenarioType) { E_UM_NORMAL = 0, // default value E_UM_GAME = 1, // game E_UM_DPLUS = 4 // DPlus }; @class CLLocation; @interface MobClick : NSObject <UIAlertViewDelegate> #pragma mark basics ///--------------------------------------------------------------------------------------- /// @name 设置 ///--------------------------------------------------------------------------------------- /** 设置 统计场景类型,默认为普通应用统计:E_UM_NORMAL @param 游戏统计必须设置为:E_UM_GAME. @return void. */ + (void)setScenarioType:(eScenarioType)eSType; /** 开启CrashReport收集, 默认YES(开启状态). @param value 设置为NO,可关闭友盟CrashReport收集功能. @return void. */ + (void)setCrashReportEnabled:(BOOL)value; #pragma mark event logs ///--------------------------------------------------------------------------------------- /// @name 页面计时 ///--------------------------------------------------------------------------------------- /** 手动页面时长统计, 记录某个页面展示的时长. @param pageName 统计的页面名称. @param seconds 单位为秒,int型. @return void. */ + (void)logPageView:(NSString *)pageName seconds:(int)seconds; /** 自动页面时长统计, 开始记录某个页面展示时长. 使用方法:必须配对调用beginLogPageView:和endLogPageView:两个函数来完成自动统计,若只调用某一个函数不会生成有效数据。 在该页面展示时调用beginLogPageView:,当退出该页面时调用endLogPageView: @param pageName 统计的页面名称. @return void. */ + (void)beginLogPageView:(NSString *)pageName; /** 自动页面时长统计, 结束记录某个页面展示时长. 使用方法:必须配对调用beginLogPageView:和endLogPageView:两个函数来完成自动统计,若只调用某一个函数不会生成有效数据。 在该页面展示时调用beginLogPageView:,当退出该页面时调用endLogPageView: @param pageName 统计的页面名称. @return void. */ + (void)endLogPageView:(NSString *)pageName; ///--------------------------------------------------------------------------------------- /// @name 事件统计 ///--------------------------------------------------------------------------------------- /** 自定义事件,数量统计. 使用前,请先到友盟App管理后台的设置->编辑自定义事件 中添加相应的事件ID,然后在工程中传入相应的事件ID @param eventId 网站上注册的事件Id. @param label 分类标签。不同的标签会分别进行统计,方便同一事件的不同标签的对比,为nil或空字符串时后台会生成和eventId同名的标签. @param accumulation 累加值。为减少网络交互,可以自行对某一事件ID的某一分类标签进行累加,再传入次数作为参数。 @return void. */ + (void)event:(NSString *)eventId; //等同于 event:eventId label:eventId; /** 自定义事件,数量统计. 使用前,请先到友盟App管理后台的设置->编辑自定义事件 中添加相应的事件ID,然后在工程中传入相应的事件ID */ + (void)event:(NSString *)eventId label:(NSString *)label; // label为nil或@""时,等同于 event:eventId label:eventId; /** 自定义事件,数量统计. 使用前,请先到友盟App管理后台的设置->编辑自定义事件 中添加相应的事件ID,然后在工程中传入相应的事件ID */ + (void)event:(NSString *)eventId attributes:(NSDictionary *)attributes; + (void)event:(NSString *)eventId attributes:(NSDictionary *)attributes counter:(int)number; /** 自定义事件,时长统计. 使用前,请先到友盟App管理后台的设置->编辑自定义事件 中添加相应的事件ID,然后在工程中传入相应的事件ID. beginEvent,endEvent要配对使用,也可以自己计时后通过durations参数传递进来 @param eventId 网站上注册的事件Id. @param label 分类标签。不同的标签会分别进行统计,方便同一事件的不同标签的对比,为nil或空字符串时后台会生成和eventId同名的标签. @param primarykey 这个参数用于和event_id一起标示一个唯一事件,并不会被统计;对于同一个事件在beginEvent和endEvent 中要传递相同的eventId 和 primarykey @param millisecond 自己计时需要的话需要传毫秒进来 @return void. @warning 每个event的attributes不能超过10个 eventId、attributes中key和value都不能使用空格和特殊字符,必须是NSString,且长度不能超过255个字符(否则将截取前255个字符) id, ts, du是保留字段,不能作为eventId及key的名称 */ + (void)beginEvent:(NSString *)eventId; /** 自定义事件,时长统计. 使用前,请先到友盟App管理后台的设置->编辑自定义事件 中添加相应的事件ID,然后在工程中传入相应的事件ID. */ + (void)endEvent:(NSString *)eventId; /** 自定义事件,时长统计. 使用前,请先到友盟App管理后台的设置->编辑自定义事件 中添加相应的事件ID,然后在工程中传入相应的事件ID. */ + (void)beginEvent:(NSString *)eventId label:(NSString *)label; /** 自定义事件,时长统计. 使用前,请先到友盟App管理后台的设置->编辑自定义事件 中添加相应的事件ID,然后在工程中传入相应的事件ID. */ + (void)endEvent:(NSString *)eventId label:(NSString *)label; /** 自定义事件,时长统计. 使用前,请先到友盟App管理后台的设置->编辑自定义事件 中添加相应的事件ID,然后在工程中传入相应的事件ID. */ + (void)beginEvent:(NSString *)eventId primarykey :(NSString *)keyName attributes:(NSDictionary *)attributes; /** 自定义事件,时长统计. 使用前,请先到友盟App管理后台的设置->编辑自定义事件 中添加相应的事件ID,然后在工程中传入相应的事件ID. */ + (void)endEvent:(NSString *)eventId primarykey:(NSString *)keyName; /** 自定义事件,时长统计. 使用前,请先到友盟App管理后台的设置->编辑自定义事件 中添加相应的事件ID,然后在工程中传入相应的事件ID. */ + (void)event:(NSString *)eventId durations:(int)millisecond; /** 自定义事件,时长统计. 使用前,请先到友盟App管理后台的设置->编辑自定义事件 中添加相应的事件ID,然后在工程中传入相应的事件ID. */ + (void)event:(NSString *)eventId label:(NSString *)label durations:(int)millisecond; /** 自定义事件,时长统计. 使用前,请先到友盟App管理后台的设置->编辑自定义事件 中添加相应的事件ID,然后在工程中传入相应的事件ID. */ + (void)event:(NSString *)eventId attributes:(NSDictionary *)attributes durations:(int)millisecond; #pragma mark - user methods /** active user sign-in. 使用sign-In函数后,如果结束该PUID的统计,需要调用sign-Off函数 @param puid : user's ID @param provider : 不能以下划线"_"开头,使用大写字母和数字标识; 如果是上市公司,建议使用股票代码。 @return void. */ + (void)profileSignInWithPUID:(NSString *)puid; + (void)profileSignInWithPUID:(NSString *)puid provider:(NSString *)provider; /** active user sign-off. 停止sign-in PUID的统计 @return void. */ + (void)profileSignOff; ///--------------------------------------------------------------------------------------- /// @name 地理位置设置 /// 需要链接 CoreLocation.framework 并且 #import <CoreLocation/CoreLocation.h> ///--------------------------------------------------------------------------------------- /** 设置经纬度信息 @param latitude 纬度. @param longitude 经度. @return void */ + (void)setLatitude:(double)latitude longitude:(double)longitude; /** 设置经纬度信息 @param location CLLocation 经纬度信息 @return void */ + (void)setLocation:(CLLocation *)location; ///--------------------------------------------------------------------------------------- /// @name Utility函数 ///--------------------------------------------------------------------------------------- /** 判断设备是否越狱,依据是否存在apt和Cydia.app */ + (BOOL)isJailbroken; /** 判断App是否被破解 */ + (BOOL)isPirated; /** 设置 app secret @param secret string @return void. */ + (void)setSecret:(NSString *)secret; + (void)setCrashCBBlock:(CallbackBlock)cbBlock; /** DeepLink事件 @param link 唤起应用的link @return void. */ + (void)onDeepLinkReceived:(NSURL *)link; @end
{ "pile_set_name": "Github" }
<?php namespace Faker\Provider\zh_TW; class PhoneNumber extends \Faker\Provider\PhoneNumber { protected static $formats = array( '+8869########', '+886-9##-###-###', '09########', '09##-###-###', '(02)########', '(02)####-####', '(0#)#######', '(0#)###-####', '(0##)######', '(0##)###-###', ); }
{ "pile_set_name": "Github" }
#ifndef DataRecord_L1RPCHsbConfigRcd_h #define DataRecord_L1RPCHsbConfigRcd_h // -*- C++ -*- // // Package: DataRecord // Class : L1RPCHsbConfigRcd // /**\class L1RPCHsbConfigRcd L1RPCHsbConfigRcd.h CondFormats/DataRecord/interface/L1RPCHsbConfigRcd.h Description: <one line class summary> Usage: <usage> */ #include "FWCore/Utilities/interface/mplVector.h" #include "FWCore/Framework/interface/DependentRecordImplementation.h" #include "CondFormats/DataRecord/interface/L1TriggerKeyListRcd.h" #include "CondFormats/DataRecord/interface/L1TriggerKeyRcd.h" class L1RPCHsbConfigRcd : public edm::eventsetup::DependentRecordImplementation<L1RPCHsbConfigRcd, edm::mpl::Vector<L1TriggerKeyListRcd, L1TriggerKeyRcd> > {}; #endif
{ "pile_set_name": "Github" }
import java.io.*; import java.net.*; public class ExploitableServer { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(Integer.parseInt(args[0])); System.out.println("Server started on port "+serverSocket.getLocalPort()); while(true) { Socket socket=serverSocket.accept(); System.out.println("Connection received from "+socket.getInetAddress()); ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream()); try { Object object = objectInputStream.readObject(); System.out.println("Read object "+object); } catch(Exception e) { System.out.println("Exception caught while reading object"); e.printStackTrace(); } } } catch(Exception e) { e.printStackTrace(); } } }
{ "pile_set_name": "Github" }
Learning human behaviors from motion capture by adversarial imitation Josh Merel, Yuval Tassa, Dhruva TB, Sriram Srinivasan, Jay Lemmon, Ziyu Wang, Greg Wayne, Nicolas Heess > DeepMind Rapid progress in deep reinforcement learning has made it increasingly feasible to train controllers for high-dimensional humanoid bodies. However, methods that use pure reinforcement learning with simple reward functions tend to produce non-humanlike and overly stereotyped movement behaviors. In this work, we extend generative adversarial imitation learning to enable training of generic neural network policies to produce humanlike movement patterns from limited demonstrations consisting only of partially observed state features, without access to actions, even when the demonstrations come from a body with different and unknown physical parameters. We leverage this approach to build sub-skill policies from motion capture data and show that they can be reused to solve tasks when controlled by a higher level controller. [video abstract]
{ "pile_set_name": "Github" }
--- name: underscore version: 1.8.3 type: npm summary: JavaScript's functional programming helper library. homepage: http://underscorejs.org license: mit licenses: - sources: LICENSE text: | Copyright (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. notices: []
{ "pile_set_name": "Github" }
'use strict'; const common = require('../common'); const assert = require('assert'); const PassThrough = require('stream').PassThrough; const readline = require('readline'); // Checks that tab completion still works // when output column size is undefined const iStream = new PassThrough(); const oStream = new PassThrough(); readline.createInterface({ terminal: true, input: iStream, output: oStream, completer: function(line, cb) { cb(null, [['process.stdout', 'process.stdin', 'process.stderr'], line]); } }); let output = ''; oStream.on('data', function(data) { output += data; }); oStream.on('end', common.mustCall(() => { const expect = 'process.stdout\r\n' + 'process.stdin\r\n' + 'process.stderr'; assert(new RegExp(expect).test(output)); })); iStream.write('process.s\t'); assert(/process\.std\b/.test(output)); // Completion works. assert(!/stdout/.test(output)); // Completion doesn’t show all results yet. iStream.write('\t'); oStream.end();
{ "pile_set_name": "Github" }
# # compressed MX RDATA stored in an output buffer # # sentinel name: example.com. # 0 1 2 3 4 5 6 7 8 9 10 1 2 (bytes) #(7) e x a m p l e (3) c o m . 07 65 78 61 6d 70 6c 65 03 63 6f 6d 00 # PREFERENCE: 10 00 0a # EXCHANGE: compressed #(4) m x ptr=0 02 6d 78 c0 00
{ "pile_set_name": "Github" }
#!perl # vim:ts=4:sw=4:expandtab # # Please read the following documents before working on tests: # • https://build.i3wm.org/docs/testsuite.html # (or docs/testsuite) # # • https://build.i3wm.org/docs/lib-i3test.html # (alternatively: perldoc ./testcases/lib/i3test.pm) # # • https://build.i3wm.org/docs/ipc.html # (or docs/ipc) # # • http://onyxneon.com/books/modern_perl/modern_perl_a4.pdf # (unless you are already familiar with Perl) # # Tests for the 'move [window|container] to mark' command # Ticket: #1643 use i3test; # In the following tests descriptions, we will always use the following names: # * 'S' for the source container which is going to be moved, # * 'M' for the marked target container to which 'S' will be moved. my ($A, $B, $S, $M, $F, $source_ws, $target_ws, $ws); my ($nodes, $focus); my $__i3_scratch; my $cmd_result; my $_NET_WM_STATE_REMOVE = 0; my $_NET_WM_STATE_ADD = 1; my $_NET_WM_STATE_TOGGLE = 2; sub set_urgency { my ($win, $urgent_flag) = @_; my $msg = pack "CCSLLLLLL", X11::XCB::CLIENT_MESSAGE, # response_type 32, # format 0, # sequence $win->id, # window $x->atom(name => '_NET_WM_STATE')->id, # message type ($urgent_flag ? $_NET_WM_STATE_ADD : $_NET_WM_STATE_REMOVE), # data32[0] $x->atom(name => '_NET_WM_STATE_DEMANDS_ATTENTION')->id, # data32[1] 0, # data32[2] 0, # data32[3] 0; # data32[4] $x->send_event(0, $x->get_root_window(), X11::XCB::EVENT_MASK_SUBSTRUCTURE_REDIRECT, $msg); } ############################################################################### # Given 'M' and 'S' in a horizontal split, when 'S' is moved to 'M', then # verify that nothing changed. ############################################################################### $ws = fresh_workspace; $M = open_window; cmd 'mark target'; $S = open_window; cmd 'move container to mark target'; sync_with_i3; ($nodes, $focus) = get_ws_content($ws); is(@{$nodes}, 2, 'there are two containers'); is($nodes->[0]->{window}, $M->{id}, 'M is left of S'); is($nodes->[1]->{window}, $S->{id}, 'S is right of M'); ############################################################################### # Given 'S' and 'M' in a horizontal split, when 'S' is moved to 'M', then # both containers switch places. ############################################################################### $ws = fresh_workspace; $S = open_window; $M = open_window; cmd 'mark target'; cmd 'focus left'; cmd 'move container to mark target'; sync_with_i3; ($nodes, $focus) = get_ws_content($ws); is(@{$nodes}, 2, 'there are two containers'); is($nodes->[0]->{window}, $M->{id}, 'M is left of S'); is($nodes->[1]->{window}, $S->{id}, 'S is right of M'); ############################################################################### # Given 'S' and no container 'M' exists, when 'S' is moved to 'M', then # the command is unsuccessful. ############################################################################### $ws = fresh_workspace; $S = open_window; $cmd_result = cmd 'move container to mark absent'; is($cmd_result->[0]->{success}, 0, 'command was unsuccessful'); ############################################################################### # Given 'S' and 'M' on different workspaces, when 'S' is moved to 'M', then # 'S' ends up on the same workspace as 'M'. ############################################################################### $source_ws = fresh_workspace; $S = open_window; $target_ws = fresh_workspace; $M = open_window; cmd 'mark target'; cmd '[id="' . $S->{id} . '"] move container to mark target'; sync_with_i3; ($nodes, $focus) = get_ws_content($source_ws); is(@{$nodes}, 0, 'source workspace is empty'); ($nodes, $focus) = get_ws_content($target_ws); is(@{$nodes}, 2, 'both containers are on the target workspace'); is($nodes->[0]->{window}, $M->{id}, 'M is left of S'); is($nodes->[1]->{window}, $S->{id}, 'S is right of M'); ############################################################################### # Given 'S' and 'M' on different workspaces and 'S' is urgent, when 'S' is # moved to 'M', then the urgency flag is transferred to the target workspace. ############################################################################### $source_ws = fresh_workspace; $S = open_window; $F = open_window; $target_ws = fresh_workspace; $M = open_window; cmd 'mark target'; cmd 'workspace ' . $source_ws; set_urgency($S, 1); cmd '[id="' . $S->{id} . '"] move container to mark target'; sync_with_i3; $source_ws = get_ws($source_ws); $target_ws = get_ws($target_ws); ok(!$source_ws->{urgent}, 'source workspace is no longer urgent'); ok($target_ws->{urgent}, 'target workspace is urgent'); ############################################################################### # Given 'S' and 'M' where 'M' is inside a tabbed container, when 'S' is moved # to 'M', then 'S' ends up as a new tab. ############################################################################### $source_ws = fresh_workspace; $S = open_window; # open tabbed container ['A' 'M' 'B'] $target_ws = fresh_workspace; $A = open_window; cmd 'layout tabbed'; $M = open_window; cmd 'mark target'; $B = open_window; cmd '[id="' . $S->{id} . '"] move container to mark target'; sync_with_i3; ($nodes, $focus) = get_ws_content($target_ws); is(@{$nodes}, 1, 'there is a tabbed container'); $nodes = $nodes->[0]->{nodes}; is(@{$nodes}, 4, 'all four containers are on the target workspace'); is($nodes->[0]->{window}, $A->{id}, 'A is the first tab'); is($nodes->[1]->{window}, $M->{id}, 'M is the second tab'); is($nodes->[2]->{window}, $S->{id}, 'S is the third tab'); is($nodes->[3]->{window}, $B->{id}, 'B is the fourth tab'); ############################################################################### # Given 'S' and 'M' where 'M' is a tabbed container where the currently focused # tab is a nested layout, when 'S' is moved to 'M', then 'S' is a new tab # within 'M'. ############################################################################### $source_ws = fresh_workspace; $S = open_window; $target_ws = fresh_workspace; $A = open_window; cmd 'layout tabbed'; cmd 'focus parent'; cmd 'mark target'; cmd 'focus child'; $B = open_window; cmd 'split h'; $F = open_window; cmd '[id="' . $S->{id} . '"] move container to mark target'; sync_with_i3; ($nodes, $focus) = get_ws_content($target_ws); is(@{$nodes}, 1, 'there is a tabbed container'); $nodes = $nodes->[0]->{nodes}; is(@{$nodes}, 3, 'there are three tabs'); is($nodes->[0]->{window}, $A->{id}, 'A is the first tab'); is($nodes->[2]->{window}, $S->{id}, 'S is the third tab'); ############################################################################### # Given 'S' and 'M' where 'M' is inside a split container inside a tabbed # container, when 'S' is moved to 'M', then 'S' ends up as a container # within the same tab as 'M'. ############################################################################### $source_ws = fresh_workspace; $S = open_window; # open tabbed container ['A'['B' 'M']] $target_ws = fresh_workspace; $A = open_window; cmd 'layout tabbed'; $B = open_window; cmd 'split h'; $M = open_window; cmd 'mark target'; cmd '[id="' . $S->{id} . '"] move container to mark target'; sync_with_i3; ($nodes, $focus) = get_ws_content($target_ws); is(@{$nodes}, 1, 'there is a tabbed container'); $nodes = $nodes->[0]->{nodes}; is(@{$nodes}, 2, 'there are two tabs'); $nodes = $nodes->[1]->{nodes}; is(@{$nodes}, 3, 'the tab with the marked children has three children'); is($nodes->[0]->{window}, $B->{id}, 'B is the first tab'); is($nodes->[1]->{window}, $M->{id}, 'M is the second tab'); is($nodes->[2]->{window}, $S->{id}, 'S is the third tab'); ############################################################################### # Given 'S', 'A' and 'B' where 'A' and 'B' are inside the tabbed container 'M', # when 'S' is moved to 'M', then 'S' ends up as a new tab in 'M'. ############################################################################### $source_ws = fresh_workspace; $S = open_window; $target_ws = fresh_workspace; $A = open_window; cmd 'layout tabbed'; $B = open_window; cmd 'focus parent'; cmd 'mark target'; cmd 'focus child'; cmd '[id="' . $S->{id} . '"] move container to mark target'; sync_with_i3; ($nodes, $focus) = get_ws_content($target_ws); is(@{$nodes}, 1, 'there is a tabbed container'); $nodes = $nodes->[0]->{nodes}; is(@{$nodes}, 3, 'there are three tabs'); is($nodes->[0]->{window}, $A->{id}, 'A is the first tab'); is($nodes->[1]->{window}, $B->{id}, 'B is the second tab'); is($nodes->[2]->{window}, $S->{id}, 'S is the third tab'); ############################################################################### # Given 'S', 'A', 'F' and 'M', where 'M' is a workspace containing a tabbed # container, when 'S' is moved to 'M', then 'S' does not end up as a tab, but # rather as a new window next to the tabbed container. ############################################################################### $source_ws = fresh_workspace; $S = open_window; $target_ws = fresh_workspace; $A = open_window; cmd 'layout tabbed'; $F = open_window; $M = $target_ws; cmd 'focus parent'; cmd 'focus parent'; cmd 'mark target'; cmd 'focus ' . $source_ws; cmd '[id="' . $S->{id} . '"] move container to mark target'; sync_with_i3; ($nodes, $focus) = get_ws_content($target_ws); is(@{$nodes}, 2, 'there is a tabbed container and a window'); is($nodes->[1]->{window}, $S->{id}, 'S is the second window'); ############################################################################### # Given 'S' and 'M' where 'S' is floating and 'M' on a different workspace, # when 'S' is moved to 'M', then 'S' is a floating container on the same # workspaces as 'M'. ############################################################################### $source_ws = fresh_workspace; $S = open_floating_window; $target_ws = fresh_workspace; $M = open_window; cmd 'mark target'; cmd '[id="' . $S->{id} . '"] move container to mark target'; sync_with_i3; is(@{get_ws($target_ws)->{floating_nodes}}, 1, 'target workspace has the container now'); ############################################################################### # Given 'S' and 'M' where 'M' is floating and on a different workspace, # when 'S' is moved to 'M', then 'S' ends up as a tiling container on the # same workspace as 'M'. ############################################################################### $source_ws = fresh_workspace; $S = open_window; $target_ws = fresh_workspace; $M = open_floating_window; cmd 'mark target'; cmd '[id="' . $S->{id} . '"] move container to mark target'; sync_with_i3; ($nodes, $focus) = get_ws_content($target_ws); is(@{$nodes}, 1, 'tiling container moved to the target workspace'); ############################################################################### # Given 'S' and 'M' where 'M' is inside a floating container but not its direct # child, when 'S' is moved to 'M', i3 should not crash. # See issue: #3402 ############################################################################### $target_ws = fresh_workspace; $S = open_window; open_window; cmd 'splitv'; $M = open_window; cmd 'mark target'; cmd 'focus parent, floating enable, focus child'; cmd '[id="' . $S->{id} . '"] move container to mark target'; does_i3_live; # Note: this is not actively supported behavior. $nodes = get_ws($target_ws)->{floating_nodes}->[0]->{nodes}->[0]->{nodes}; is(1, (grep { $_->{window} == $S->{id} } @{$nodes}), 'tiling container moved inside floating container'); ############################################################################### # Given 'S' and 'M' are the same container, when 'S' is moved to 'M', then # the command is ignored. ############################################################################### $ws = fresh_workspace; $S = open_window; $M = $S; cmd 'mark target'; cmd '[id="' . $S->{id} . '"] move container to mark target'; sync_with_i3; does_i3_live; ############################################################################### # Given 'S' and 'M' where 'M' is a workspace and 'S' is on a different # workspace, then 'S' ends up as a tiling container on 'M'. # See issue: #2003 ############################################################################### fresh_workspace; $S = open_window; $target_ws = fresh_workspace; $M = $target_ws; cmd 'mark target'; cmd '[id="' . $S->{id} . '"] move container to mark target'; sync_with_i3; does_i3_live; ($nodes, $focus) = get_ws_content($target_ws); is(@{$nodes}, 1, 'tiling container moved to the target workspace'); ############################################################################### # Given 'S' and 'M' where 'S' is a workspace and 'M' is a container on a # different workspace, then all the contents of workspace 'S' end up in 'M's # workspace. ############################################################################### $S = fresh_workspace; cmd 'mark S'; open_window; open_window; cmd 'splitv'; open_window; open_floating_window; $target_ws = fresh_workspace; $M = open_window; cmd 'mark target'; cmd '[con_mark=S] move container to mark target'; sync_with_i3; ($nodes, $focus) = get_ws_content($target_ws); is(@{$nodes}, 2, 'there is a window and a container with the contents of the original workspace'); is($nodes->[0]->{window}, $M->{id}, 'M remains the first window'); is(@{get_ws($target_ws)->{floating_nodes}}, 1, 'target workspace has the floating container'); ############################################################################### # Given 'S' and 'M', where 'S' is a container and 'M' is a container hidden in # the scratchpad, then move 'S' to the scratchpad ############################################################################### $ws = fresh_workspace; $S = open_window; cmd 'mark S'; $M = open_window; cmd 'mark target'; cmd 'move container to scratchpad'; cmd '[con_mark=S] move container to mark target'; sync_with_i3; ($nodes, $focus) = get_ws_content($ws); is(@{$nodes}, 0, 'there are no tiling windows on the workspace'); is(@{get_ws($ws)->{floating_nodes}}, 0, 'there are no floating containers on the workspace'); $__i3_scratch = get_ws('__i3_scratch'); is(@{$__i3_scratch->{nodes}}, 0, 'there are no tiling windows on the scratchpad workspace'); is(@{$__i3_scratch->{floating_nodes}}, 2, 'there are two floating containers in the scratchpad'); ############################################################################### done_testing;
{ "pile_set_name": "Github" }
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package unicode import ( "testing" "golang.org/x/text/encoding" "golang.org/x/text/encoding/charmap" "golang.org/x/text/encoding/internal/enctest" "golang.org/x/text/transform" ) func TestBasics(t *testing.T) { testCases := []struct { e encoding.Encoding encPrefix string encSuffix string encoded string utf8 string }{{ e: utf16BEIB, encoded: "\x00\x57\x00\xe4\xd8\x35\xdd\x65", utf8: "\x57\u00e4\U0001d565", }, { e: utf16BEEB, encPrefix: "\xfe\xff", encoded: "\x00\x57\x00\xe4\xd8\x35\xdd\x65", utf8: "\x57\u00e4\U0001d565", }, { e: utf16LEIB, encoded: "\x57\x00\xe4\x00\x35\xd8\x65\xdd", utf8: "\x57\u00e4\U0001d565", }, { e: utf16LEEB, encPrefix: "\xff\xfe", encoded: "\x57\x00\xe4\x00\x35\xd8\x65\xdd", utf8: "\x57\u00e4\U0001d565", }} for _, tc := range testCases { enctest.TestEncoding(t, tc.e, tc.encoded, tc.utf8, tc.encPrefix, tc.encSuffix) } } func TestFiles(t *testing.T) { enctest.TestFile(t, UTF8) enctest.TestFile(t, utf16LEIB) } func BenchmarkEncoding(b *testing.B) { enctest.Benchmark(b, UTF8) enctest.Benchmark(b, utf16LEIB) } var ( utf16LEIB = UTF16(LittleEndian, IgnoreBOM) // UTF-16LE (atypical interpretation) utf16LEUB = UTF16(LittleEndian, UseBOM) // UTF-16, LE utf16LEEB = UTF16(LittleEndian, ExpectBOM) // UTF-16, LE, Expect utf16BEIB = UTF16(BigEndian, IgnoreBOM) // UTF-16BE (atypical interpretation) utf16BEUB = UTF16(BigEndian, UseBOM) // UTF-16 default utf16BEEB = UTF16(BigEndian, ExpectBOM) // UTF-16 Expect ) func TestUTF16(t *testing.T) { testCases := []struct { desc string src string notEOF bool // the inverse of atEOF sizeDst int want string nSrc int err error t transform.Transformer }{{ desc: "utf-16 IgnoreBOM dec: empty string", t: utf16BEIB.NewDecoder(), }, { desc: "utf-16 UseBOM dec: empty string", t: utf16BEUB.NewDecoder(), }, { desc: "utf-16 ExpectBOM dec: empty string", err: ErrMissingBOM, t: utf16BEEB.NewDecoder(), }, { desc: "utf-16 dec: BOM determines encoding BE (RFC 2781:3.3)", src: "\xFE\xFF\xD8\x08\xDF\x45\x00\x3D\x00\x52\x00\x61", sizeDst: 100, want: "\U00012345=Ra", nSrc: 12, t: utf16BEUB.NewDecoder(), }, { desc: "utf-16 dec: BOM determines encoding LE (RFC 2781:3.3)", src: "\xFF\xFE\x08\xD8\x45\xDF\x3D\x00\x52\x00\x61\x00", sizeDst: 100, want: "\U00012345=Ra", nSrc: 12, t: utf16LEUB.NewDecoder(), }, { desc: "utf-16 dec: BOM determines encoding LE, change default (RFC 2781:3.3)", src: "\xFF\xFE\x08\xD8\x45\xDF\x3D\x00\x52\x00\x61\x00", sizeDst: 100, want: "\U00012345=Ra", nSrc: 12, t: utf16BEUB.NewDecoder(), }, { desc: "utf-16 dec: Fail on missing BOM when required", src: "\x08\xD8\x45\xDF\x3D\x00\xFF\xFE\xFE\xFF\x00\x52\x00\x61", sizeDst: 100, want: "", nSrc: 0, err: ErrMissingBOM, t: utf16BEEB.NewDecoder(), }, { desc: "utf-16 dec: SHOULD interpret text as big-endian when BOM not present (RFC 2781:4.3)", src: "\xD8\x08\xDF\x45\x00\x3D\x00\x52\x00\x61", sizeDst: 100, want: "\U00012345=Ra", nSrc: 10, t: utf16BEUB.NewDecoder(), }, { // This is an error according to RFC 2781. But errors in RFC 2781 are // open to interpretations, so I guess this is fine. desc: "utf-16le dec: incorrect BOM is an error (RFC 2781:4.1)", src: "\xFE\xFF\x08\xD8\x45\xDF\x3D\x00\x52\x00\x61\x00", sizeDst: 100, want: "\uFFFE\U00012345=Ra", nSrc: 12, t: utf16LEIB.NewDecoder(), }, { desc: "utf-16 enc: SHOULD write BOM (RFC 2781:3.3)", src: "\U00012345=Ra", sizeDst: 100, want: "\xFF\xFE\x08\xD8\x45\xDF\x3D\x00\x52\x00\x61\x00", nSrc: 7, t: utf16LEUB.NewEncoder(), }, { desc: "utf-16 enc: SHOULD write BOM (RFC 2781:3.3)", src: "\U00012345=Ra", sizeDst: 100, want: "\xFE\xFF\xD8\x08\xDF\x45\x00\x3D\x00\x52\x00\x61", nSrc: 7, t: utf16BEUB.NewEncoder(), }, { desc: "utf-16le enc: MUST NOT write BOM (RFC 2781:3.3)", src: "\U00012345=Ra", sizeDst: 100, want: "\x08\xD8\x45\xDF\x3D\x00\x52\x00\x61\x00", nSrc: 7, t: utf16LEIB.NewEncoder(), }, { desc: "utf-16be dec: incorrect UTF-16: odd bytes", src: "\x00", sizeDst: 100, want: "\uFFFD", nSrc: 1, t: utf16BEIB.NewDecoder(), }, { desc: "utf-16be dec: unpaired surrogate, odd bytes", src: "\xD8\x45\x00", sizeDst: 100, want: "\uFFFD\uFFFD", nSrc: 3, t: utf16BEIB.NewDecoder(), }, { desc: "utf-16be dec: unpaired low surrogate + valid text", src: "\xD8\x45\x00a", sizeDst: 100, want: "\uFFFDa", nSrc: 4, t: utf16BEIB.NewDecoder(), }, { desc: "utf-16be dec: unpaired low surrogate + valid text + single byte", src: "\xD8\x45\x00ab", sizeDst: 100, want: "\uFFFDa\uFFFD", nSrc: 5, t: utf16BEIB.NewDecoder(), }, { desc: "utf-16le dec: unpaired high surrogate", src: "\x00\x00\x00\xDC\x12\xD8", sizeDst: 100, want: "\x00\uFFFD\uFFFD", nSrc: 6, t: utf16LEIB.NewDecoder(), }, { desc: "utf-16be dec: two unpaired low surrogates", src: "\xD8\x45\xD8\x12", sizeDst: 100, want: "\uFFFD\uFFFD", nSrc: 4, t: utf16BEIB.NewDecoder(), }, { desc: "utf-16be dec: short dst", src: "\x00a", sizeDst: 0, want: "", nSrc: 0, t: utf16BEIB.NewDecoder(), err: transform.ErrShortDst, }, { desc: "utf-16be dec: short dst surrogate", src: "\xD8\xF5\xDC\x12", sizeDst: 3, want: "", nSrc: 0, t: utf16BEIB.NewDecoder(), err: transform.ErrShortDst, }, { desc: "utf-16be dec: short dst trailing byte", src: "\x00", sizeDst: 2, want: "", nSrc: 0, t: utf16BEIB.NewDecoder(), err: transform.ErrShortDst, }, { desc: "utf-16be dec: short src", src: "\x00", notEOF: true, sizeDst: 3, want: "", nSrc: 0, t: utf16BEIB.NewDecoder(), err: transform.ErrShortSrc, }, { desc: "utf-16 enc", src: "\U00012345=Ra", sizeDst: 100, want: "\xFE\xFF\xD8\x08\xDF\x45\x00\x3D\x00\x52\x00\x61", nSrc: 7, t: utf16BEUB.NewEncoder(), }, { desc: "utf-16 enc: short dst normal", src: "\U00012345=Ra", sizeDst: 9, want: "\xD8\x08\xDF\x45\x00\x3D\x00\x52", nSrc: 6, t: utf16BEIB.NewEncoder(), err: transform.ErrShortDst, }, { desc: "utf-16 enc: short dst surrogate", src: "\U00012345=Ra", sizeDst: 3, want: "", nSrc: 0, t: utf16BEIB.NewEncoder(), err: transform.ErrShortDst, }, { desc: "utf-16 enc: short src", src: "\U00012345=Ra\xC2", notEOF: true, sizeDst: 100, want: "\xD8\x08\xDF\x45\x00\x3D\x00\x52\x00\x61", nSrc: 7, t: utf16BEIB.NewEncoder(), err: transform.ErrShortSrc, }, { desc: "utf-16be dec: don't change byte order mid-stream", src: "\xFE\xFF\xD8\x08\xDF\x45\x00\x3D\xFF\xFE\x00\x52\x00\x61", sizeDst: 100, want: "\U00012345=\ufffeRa", nSrc: 14, t: utf16BEUB.NewDecoder(), }, { desc: "utf-16le dec: don't change byte order mid-stream", src: "\xFF\xFE\x08\xD8\x45\xDF\x3D\x00\xFF\xFE\xFE\xFF\x52\x00\x61\x00", sizeDst: 100, want: "\U00012345=\ufeff\ufffeRa", nSrc: 16, t: utf16LEUB.NewDecoder(), }} for i, tc := range testCases { b := make([]byte, tc.sizeDst) nDst, nSrc, err := tc.t.Transform(b, []byte(tc.src), !tc.notEOF) if err != tc.err { t.Errorf("%d:%s: error was %v; want %v", i, tc.desc, err, tc.err) } if got := string(b[:nDst]); got != tc.want { t.Errorf("%d:%s: result was %q: want %q", i, tc.desc, got, tc.want) } if nSrc != tc.nSrc { t.Errorf("%d:%s: nSrc was %d; want %d", i, tc.desc, nSrc, tc.nSrc) } } } func TestUTF8Decoder(t *testing.T) { testCases := []struct { desc string src string notEOF bool // the inverse of atEOF sizeDst int want string nSrc int err error }{{ desc: "empty string, empty dest buffer", }, { desc: "empty string", sizeDst: 8, }, { desc: "empty string, streaming", notEOF: true, sizeDst: 8, }, { desc: "ascii", src: "abcde", sizeDst: 8, want: "abcde", nSrc: 5, }, { desc: "ascii and error", src: "ab\x80de", sizeDst: 7, want: "ab\ufffdde", nSrc: 5, }, { desc: "valid two-byte sequence", src: "a\u0300bc", sizeDst: 7, want: "a\u0300bc", nSrc: 5, }, { desc: "valid three-byte sequence", src: "a\u0300中", sizeDst: 7, want: "a\u0300中", nSrc: 6, }, { desc: "valid four-byte sequence", src: "a中\U00016F50", sizeDst: 8, want: "a中\U00016F50", nSrc: 8, }, { desc: "short source buffer", src: "abc\xf0\x90", notEOF: true, sizeDst: 10, want: "abc", nSrc: 3, err: transform.ErrShortSrc, }, { // We don't check for the maximal subpart of an ill-formed subsequence // at the end of an open segment. desc: "complete invalid that looks like short at end", src: "abc\xf0\x80", notEOF: true, sizeDst: 10, want: "abc", // instead of "abc\ufffd\ufffd", nSrc: 3, err: transform.ErrShortSrc, }, { desc: "incomplete sequence at end", src: "a\x80bc\xf0\x90", sizeDst: 9, want: "a\ufffdbc\ufffd", nSrc: 6, }, { desc: "invalid second byte", src: "abc\xf0dddd", sizeDst: 10, want: "abc\ufffddddd", nSrc: 8, }, { desc: "invalid second byte at end", src: "abc\xf0d", sizeDst: 10, want: "abc\ufffdd", nSrc: 5, }, { desc: "invalid third byte", src: "a\u0300bc\xf0\x90dddd", sizeDst: 12, want: "a\u0300bc\ufffddddd", nSrc: 11, }, { desc: "invalid third byte at end", src: "a\u0300bc\xf0\x90d", sizeDst: 12, want: "a\u0300bc\ufffdd", nSrc: 8, }, { desc: "invalid fourth byte, tight buffer", src: "a\u0300bc\xf0\x90\x80d", sizeDst: 9, want: "a\u0300bc\ufffdd", nSrc: 9, }, { desc: "invalid fourth byte at end", src: "a\u0300bc\xf0\x90\x80", sizeDst: 8, want: "a\u0300bc\ufffd", nSrc: 8, }, { desc: "invalid fourth byte and short four byte sequence", src: "a\u0300bc\xf0\x90\x80\xf0\x90\x80", notEOF: true, sizeDst: 20, want: "a\u0300bc\ufffd", nSrc: 8, err: transform.ErrShortSrc, }, { desc: "valid four-byte sequence overflowing short buffer", src: "a\u0300bc\xf0\x90\x80\x80", notEOF: true, sizeDst: 8, want: "a\u0300bc", nSrc: 5, err: transform.ErrShortDst, }, { desc: "invalid fourth byte at end short, but short dst", src: "a\u0300bc\xf0\x90\x80\xf0\x90\x80", notEOF: true, sizeDst: 8, // More bytes would fit in the buffer, but this seems to require a more // complicated and slower algorithm. want: "a\u0300bc", // instead of "a\u0300bc" nSrc: 5, err: transform.ErrShortDst, }, { desc: "short dst for error", src: "abc\x80", notEOF: true, sizeDst: 5, want: "abc", nSrc: 3, err: transform.ErrShortDst, }, { desc: "adjusting short dst buffer", src: "abc\x80ef", notEOF: true, sizeDst: 6, want: "abc\ufffd", nSrc: 4, err: transform.ErrShortDst, }} tr := UTF8.NewDecoder() for i, tc := range testCases { b := make([]byte, tc.sizeDst) nDst, nSrc, err := tr.Transform(b, []byte(tc.src), !tc.notEOF) if err != tc.err { t.Errorf("%d:%s: error was %v; want %v", i, tc.desc, err, tc.err) } if got := string(b[:nDst]); got != tc.want { t.Errorf("%d:%s: result was %q: want %q", i, tc.desc, got, tc.want) } if nSrc != tc.nSrc { t.Errorf("%d:%s: nSrc was %d; want %d", i, tc.desc, nSrc, tc.nSrc) } } } func TestBOMOverride(t *testing.T) { dec := BOMOverride(charmap.CodePage437.NewDecoder()) dst := make([]byte, 100) for i, tc := range []struct { src string atEOF bool dst string nSrc int err error }{ 0: {"H\x82ll\x93", true, "Héllô", 5, nil}, 1: {"\uFEFFHéllö", true, "Héllö", 10, nil}, 2: {"\xFE\xFF\x00H\x00e\x00l\x00l\x00o", true, "Hello", 12, nil}, 3: {"\xFF\xFEH\x00e\x00l\x00l\x00o\x00", true, "Hello", 12, nil}, 4: {"\uFEFF", true, "", 3, nil}, 5: {"\xFE\xFF", true, "", 2, nil}, 6: {"\xFF\xFE", true, "", 2, nil}, 7: {"\xEF\xBB", true, "\u2229\u2557", 2, nil}, 8: {"\xEF", true, "\u2229", 1, nil}, 9: {"", true, "", 0, nil}, 10: {"\xFE", true, "\u25a0", 1, nil}, 11: {"\xFF", true, "\u00a0", 1, nil}, 12: {"\xEF\xBB", false, "", 0, transform.ErrShortSrc}, 13: {"\xEF", false, "", 0, transform.ErrShortSrc}, 14: {"", false, "", 0, transform.ErrShortSrc}, 15: {"\xFE", false, "", 0, transform.ErrShortSrc}, 16: {"\xFF", false, "", 0, transform.ErrShortSrc}, 17: {"\xFF\xFE", false, "", 0, transform.ErrShortSrc}, } { dec.Reset() nDst, nSrc, err := dec.Transform(dst, []byte(tc.src), tc.atEOF) got := string(dst[:nDst]) if nSrc != tc.nSrc { t.Errorf("%d: nSrc: got %d; want %d", i, nSrc, tc.nSrc) } if got != tc.dst { t.Errorf("%d: got %+q; want %+q", i, got, tc.dst) } if err != tc.err { t.Errorf("%d: error: got %v; want %v", i, err, tc.err) } } }
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. package org.bondlib; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Partially implements the {@link BondType} contract for generated Bond struct data types. * Leaves the rest of implementation details to generated subclasses specific to the struct type, * which are generated private classes nested within the struct classes. * @param <TStruct> the class of the struct value */ // This API is consumed by codegen, which static analysis isn't aware of. @SuppressWarnings({"unused", "WeakerAccess"}) public abstract class StructBondType<TStruct extends BondSerializable> extends BondType<TStruct> { // The registry of all loaded struct type builders, for generic and non-generic generated struct types. // Entries are added by static initializeBondType methods of the generated struct types which is called // by the static class initializer and can also be called manually if the static class initializer hasn't // completed yet (which happens with circular class dependencies). // // This registry's purpose is to provide an alternative solution to obtain a type descriptor for a struct // type, that can be used when executing generated code initializing fields of struct type descriptors. // An alternative solution is necessary since the user-facing solution of accessing public static fields // BOND_TYPE doesn't work when running as part of initialization of a generated class (the static fields // may not be set yet). Thus, there are two approaches to get a Bond type descriptor for a user-defined // generated struct: // 1. [public-facing API used by all user code] Use the public static field BOND_TYPE which is: // (a) The type descriptor, for struct types that do not declare generic type parameters. or // (b) A builder of type descriptor that takes generic type arguments and returns an instance // of the type descriptor, for struct types that declare generic type parameters. // 2. [private API used only by generated initialization code] Use the protected method getStructType // that returns the type descriptor given the Class and generic type arguments (empty for non-generic // types. This method relies on the registry of struct type builders, and will initialize the class // (thus executing its registration) if necessary. // // Note that #2 doesn't distinguish between generic and non-generic types, by abstracting the type builder // for all types, with empty generic type argument list for non-generic types. On the contrary, #1 has // that distinction since it's intended for public API and needs to be convenient (i.e. it's not elegant // to ask client code to "build" an invariant non-generic type). private static final ConcurrentHashMap< Class<? extends BondSerializable>, StructBondTypeBuilder<? extends BondSerializable>> structTypeBuilderRegistry = new ConcurrentHashMap< Class<? extends BondSerializable>, StructBondTypeBuilder<? extends BondSerializable>>(); private static final String BOND_TYPE_INITIALIZATION_METHOD_NAME = "initializeBondType"; // The global initialization lock, used to initialize type descriptors. // Global locking is necessary to avoid deadlocks when multiple threads initialize generated classes // that reference each other. The contention for this lock is generally not expected to be a problem because: // 1. A lock is acquired only once per type descriptor object when it is actually initialized. This is // achieved by double-checked locking in the ensureInitialized method. // 2. Due to type caching, there is at most one lock acqusition for each type (or each specialization of // a generic type), which is constrained by the application. Note that temporary type descriptors // are used only to lookup the cached equivalent and are themselves not initialized. // This lock is also used to protect schema def initialization, and the same two points above apply. private static final Object initializationLock = new Object(); // set by the constructor (part of the object identity) private final GenericTypeSpecialization genericTypeSpecialization; private final int precomputedHashCode; // set by the initialization method instead of the constructor since may have cyclic dependencies private StructBondType<? super TStruct> baseStructType; private StructField<?>[] structFields; // cached schema def, thread-safe (atomic) read and write from/to memory private volatile SchemaDef schemaDef = null; // indicates whether this instance is initialized, thread-safe (atomic) read and write from/to memory private volatile boolean isInitialized = false; // indicates whether this instance is currently being initialized by the thread holding the global lock; // the flag is used to prevent a thread from re-entering initialization method due to cyclic references private boolean isCurrentlyInitializing = false; /** * Used by generated subclasses to instantiate the type descriptor. * * @param genericTypeSpecialization specialization of a generic struct or null if not a generic struct */ protected StructBondType(GenericTypeSpecialization genericTypeSpecialization) { this.genericTypeSpecialization = genericTypeSpecialization; precomputedHashCode = this.getClass().hashCode() + (genericTypeSpecialization == null ? 0 : genericTypeSpecialization.hashCode()); } /** * Used by generated subclasses to initialize the base struct reference and fields of the type descriptor. * Field types (including fields of the base struct) may refer back to the declaring struct which causes * cyclic dependencies, and therefore this initialization is separated from the constructor. * * @param baseStructType the type descriptor of the base struct or null if it doesn't exist * @param structFields an array of descriptors of the declared fields of the struct (excluding inherited) */ protected final void initializeBaseAndFields( StructBondType<? super TStruct> baseStructType, StructField<?>... structFields) { this.baseStructType = baseStructType; this.structFields = structFields; } /** * Called from generated code to make sure the type descriptor is initialized. */ protected final void ensureInitialized() { // double-checked locking to make sure initialization happens only one in a single thread; // the contention is restricted since there is at most one initialization per each distinct // non-generic struct type or per each distinct specialization of a generic struct type if (!this.isInitialized) { synchronized (initializationLock) { if (!this.isInitialized) { // enter initialization only if not already initializing by the current thread // (which already holds the lock and hence can be the only initializing thread) if (!this.isCurrentlyInitializing) { try { // mark this object as currently being initialized, so that this thread // does not re-enter initialization when there is a cyclic type reference this.isCurrentlyInitializing = true; // initialize (call generated method which initializes struct type fields // and then calls initializeBaseAndFields) and mark this instance as // initialized (using a volatile variable), so that from this point on // every thread will skip initialization and lock acquisition this.initialize(); this.isInitialized = true; } finally { // clean up after the current thread so that if the initialize method // threw an exception and the object was not successfully initialized // then some other thread can still try to initialize // // Please note that the initialize methods do not throw any exceptions // under normal circumstances, and if they throw something then it is // almost certainly a fatal error (e.g. OutOfMemory or ThreadDeath). this.isCurrentlyInitializing = false; } } } } } } /** * Implemented by generated subclasses to initialize the type descriptor, speficially initialize the * fields and then call {@link #initializeBaseAndFields(StructBondType, StructField[])}. */ protected abstract void initialize(); /** * Used by generated subclasses to serialize declared fields of this struct, excluding inherited fields. * * @param context contains the runtime context of the serialization * @param value the value to serialize from * @throws IOException if an I/O error occurred */ protected abstract void serializeStructFields( SerializationContext context, TStruct value) throws IOException; /** * Used by generated subclasses to deserialize declared fields of this struct, excluding inherited fields. * * @param context contains the runtime context of the deserialization * @param value the value to deserialize into * @throws IOException if an I/O error occurred */ protected abstract void deserializeStructFields( TaggedDeserializationContext context, TStruct value) throws IOException; /** * Used by generated subclasses to deserialize fields of this struct using the runtime schema, excluding inherited * fields. * * @param context contains the runtime context of the deserialization * @param structDef the StructDef of this struct * @param value the value to deserialize into * @throws IOException if an I/O error occurred */ protected abstract void deserializeStructFields( UntaggedDeserializationContext context, StructDef structDef, TStruct value) throws IOException; /** * Used by generated subclasses to initialize declared fields of this struct, excluding inherited fields. * * @param value the value to initialize */ protected abstract void initializeStructFields(TStruct value); /** * Used by generated subclasses to memberwise-copy declared fields of this struct, excluding inherited fields. * * @param fromValue the value to copy from * @param toValue the value to copy to */ protected abstract void cloneStructFields(TStruct fromValue, TStruct toValue); /** * Gets the generic specialization or null if not generic struct. * * @return the generic specialization or null if not generic struct */ protected final GenericTypeSpecialization getGenericSpecialization() { return this.genericTypeSpecialization; } /** * Gets the descriptor of the base struct type. * * @return the type descriptor of the base struct or null if there is no base struct */ public final StructBondType<? super TStruct> getBaseStructType() { return this.baseStructType; } /** * Gets an array containing the descriptors of the struct fields. * * @return an array containing the descriptors of the struct fields */ public final StructField<?>[] getStructFields() { return this.structFields.clone(); } /** * Builds a new {@link SchemaDef} instance describing the schema of this struct. * * @return a new schema definition instance */ public final SchemaDef buildSchemaDef() { SchemaDef schemaDef = new SchemaDef(); HashMap<StructBondType<?>, StructDefOrdinalTuple> typeDefMap = new HashMap<StructBondType<?>, StructDefOrdinalTuple>(); schemaDef.root = this.createSchemaTypeDef(typeDefMap); StructDef[] tempArray = new StructDef[typeDefMap.size()]; for (Map.Entry<StructBondType<?>, StructDefOrdinalTuple> e : typeDefMap.entrySet()) { StructDefOrdinalTuple structDefInfo = e.getValue(); tempArray[structDefInfo.ordinal] = structDefInfo.structDef; } schemaDef.structs.addAll(Arrays.asList(tempArray)); return schemaDef; } /** * Returns the {@link SchemaDef} object containing runtime schemas of this struct type * and any referenced struct types (ancestors or types of struct fields). * The returned instance is permanently cached in this type * descriptor and mutating it can have adverse side effects. * * @return schema definition instance */ public final SchemaDef getSchemaDef() { // double-checked locking to make sure the schema is built and cached in a single thread; // the contention is restricted since there is at most one schema building per each distinct // non-generic struct type or per each distinct specialization of a generic struct type if (this.schemaDef == null) { synchronized (initializationLock) { if (this.schemaDef == null) { this.schemaDef = this.buildSchemaDef(); } } } return this.schemaDef; } /** * Returns the {@link StructDef} object represening runtime schema of this struct type. * The returned instance is permanently cached in this type * descriptor and mutating it can have adverse side effects. * * @return struct definition instance */ public final StructDef getStructDef() { return this.getSchemaDef().structs.get(this.schemaDef.root.struct_def); } @Override public final BondDataType getBondDataType() { return BondDataType.BT_STRUCT; } @Override public final boolean isNullableType() { return false; } @Override public final boolean isGenericType() { return this.genericTypeSpecialization != null; } @Override public final BondType<?>[] getGenericTypeArguments() { return this.genericTypeSpecialization != null ? this.genericTypeSpecialization.genericTypeArguments.clone() : null; } @Override public final Class<TStruct> getPrimitiveValueClass() { return null; } @Override protected final TStruct newDefaultValue() { return this.newInstance(); } @Override protected final TStruct cloneValue(TStruct value) { TStruct clonedValue = this.newInstance(); StructBondType<? super TStruct> currentStructType = this; while (currentStructType != null) { currentStructType.cloneStructFields(value, clonedValue); currentStructType = currentStructType.baseStructType; } return clonedValue; } /** * Instantiates a new instance of this struct type. * * @return new struct instance */ public abstract TStruct newInstance(); /** * Returns a value indicating whether this type is a subtype of (or the same as) the argument type. * * @param other the argument type * @return true if this type is the same type or a subtype of the argument type */ public final boolean isSubtypeOf(StructBondType<?> other) { ArgumentHelper.ensureNotNull(other, "other"); StructBondType<?> currentType = this; while (currentType != null) { if (currentType.equals(other)) { return true; } currentType = currentType.baseStructType; } return false; } @Override protected final void serializeValue(SerializationContext context, TStruct value) throws IOException { this.verifyNonNullableValueIsNotSetToNull(value); context.writer.writeStructBegin(this.getStructDef().metadata); if (this.baseStructType != null) { this.baseStructType.serializeValueAsBase(context, value); } this.serializeStructFields(context, value); context.writer.writeStructEnd(); } private void serializeValueAsBase( SerializationContext context, TStruct value) throws IOException { if (this.baseStructType != null) { this.baseStructType.serializeValueAsBase(context, value); } context.writer.writeBaseBegin(this.getStructDef().metadata); this.serializeStructFields(context, value); context.writer.writeBaseEnd(); } @Override protected final TStruct deserializeValue(TaggedDeserializationContext context) throws IOException { TStruct value = this.newDefaultValue(); context.reader.readStructBegin(); if (this.baseStructType != null) { this.baseStructType.deserializeValueAsBase(context, value); } this.deserializeStructFields(context, value); context.reader.readStructEnd(); return value; } private void deserializeValueAsBase(TaggedDeserializationContext context, TStruct value) throws IOException { if (this.baseStructType != null) { this.baseStructType.deserializeValueAsBase(context, value); } context.reader.readBaseBegin(); this.deserializeStructFields(context, value); context.reader.readBaseEnd(); } @Override protected final TStruct deserializeValue( UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { TStruct value = this.newDefaultValue(); this.deserializeValue(context, typeDef, value); return value; } private void deserializeValue( UntaggedDeserializationContext context, TypeDef typeDef, TStruct value) throws IOException { final StructDef structDef = context.schema.structs.get(typeDef.struct_def); if (this.baseStructType != null) { final TypeDef baseDef = structDef.base_def; this.baseStructType.deserializeValue(context, baseDef, value); } this.deserializeStructFields(context, structDef, value); } @Override protected final void serializeField( SerializationContext context, TStruct value, StructField<TStruct> field) throws IOException { this.verifySerializedNonNullableFieldIsNotSetToNull(value, field); // struct fields are never omitted context.writer.writeFieldBegin(BondDataType.BT_STRUCT, field.getId(), field.getFieldDef().metadata); try { this.serializeValue(context, value); } catch (InvalidBondDataException e) { // throws Throw.raiseStructFieldSerializationError(false, field, e, null); } context.writer.writeFieldEnd(); } @Override protected final TStruct deserializeField( TaggedDeserializationContext context, StructField<TStruct> field) throws IOException { // a struct value may be deserialized only from BT_STRUCT if (context.readFieldResult.type.value != BondDataType.BT_STRUCT.value) { // throws Throw.raiseFieldTypeIsNotCompatibleDeserializationError(context.readFieldResult.type, field); } TStruct value = null; try { value = this.deserializeValue(context); } catch (InvalidBondDataException e) { // throws Throw.raiseStructFieldSerializationError(true, field, e, null); } return value; } @Override public final int hashCode() { return this.precomputedHashCode; } @Override public final boolean equals(Object obj) { if (obj instanceof StructBondType<?>) { StructBondType<?> that = (StructBondType<?>) obj; return this.precomputedHashCode == that.precomputedHashCode && this.getClass().equals(that.getClass()) && (this.genericTypeSpecialization == null ? that.genericTypeSpecialization == null : this.genericTypeSpecialization.equals(that.genericTypeSpecialization)); } else { return false; } } /** * Serializes an object into the given protocol writer. * * @param obj the object to serialize * @param writer the protocol writer to write into * @throws IOException if an I/O error occurred */ void serialize(TStruct obj, ProtocolWriter writer) throws IOException { // first pass if (writer instanceof TwoPassProtocolWriter) { ProtocolWriter firstPassWriter = ((TwoPassProtocolWriter) writer).getFirstPassWriter(); if (firstPassWriter != null) { SerializationContext firstPassContext = new SerializationContext(firstPassWriter); this.serializeValue(firstPassContext, obj); } } // second pass SerializationContext context = new SerializationContext(writer); this.serializeValue(context, obj); } /** * Deserializes an object from the given tagged protocol reader. * * @param reader the protocol reader to read from * @return deserialized object * @throws IOException if an I/O error occurred */ TStruct deserialize(TaggedProtocolReader reader) throws IOException { TaggedDeserializationContext context = new TaggedDeserializationContext(reader); return this.deserializeValue(context); } /** * Deserializes an object from the given untagged protocol reader. * * @param reader the protocol reader to read from * @return deserialized object * @throws IOException if an I/O error occurred */ TStruct deserialize(UntaggedProtocolReader reader) throws IOException { return this.deserialize(reader, this.buildSchemaDef()); } /** * Deserializes an object from the given untagged protocol reader using the supplied runtime schema. * * @param reader the protocol reader to read from * @param schema the runtime scheam * @return deserialized object * @throws IOException if an I/O error occurred */ TStruct deserialize(UntaggedProtocolReader reader, SchemaDef schema) throws IOException { UntaggedDeserializationContext context = new UntaggedDeserializationContext(reader, schema); return this.deserializeValue(context, schema.root); } @Override final TypeDef createSchemaTypeDef(HashMap<StructBondType<?>, StructDefOrdinalTuple> structDefMap) { // first need to get the struct def info since need to reference it by the ordinal StructDefOrdinalTuple structDefInfo = structDefMap.get(this); if (structDefInfo == null) { // struct def wasn't created yet, create one and associate with the current struct in the map; int nextOrdinal = structDefMap.size(); StructDef structDef = new StructDef(); structDefInfo = new StructDefOrdinalTuple(structDef, nextOrdinal); // the struct def instance that is associated in the map with the current struct type is not yet // initialized, but any descendants that use this struct will reference the same struct def instance structDefMap.put(this, structDefInfo); this.initializeSchemaStructDef(structDef, structDefMap); } TypeDef typeDef = new TypeDef(); typeDef.id = this.getBondDataType(); typeDef.struct_def = (short) structDefInfo.ordinal; return typeDef; } /** * Codegen helper method that tries to read a field from payload and indicates whether there is a field to read. * * @param context contains the runtime context of the deserialization * @return true if there are more fields to read * @throws IOException if an I/O error occurred */ protected static boolean readField(TaggedDeserializationContext context) throws IOException { context.reader.readFieldBegin(context.readFieldResult); int statusValue = context.readFieldResult.type.value; return statusValue != BondDataType.BT_STOP.value && statusValue != BondDataType.BT_STOP_BASE.value; } private void initializeSchemaStructDef( StructDef structDef, HashMap<StructBondType<?>, StructDefOrdinalTuple> structDefMap) { structDef.metadata.name = this.getName(); structDef.metadata.qualified_name = this.getFullName(); if (this.baseStructType != null) { structDef.base_def = this.baseStructType.createSchemaTypeDef(structDefMap); } for (StructField<?> field : this.structFields) { FieldDef fieldDef = new FieldDef(); fieldDef.metadata.name = field.name; fieldDef.metadata.modifier = field.modifier; initializeSchemaVariantWithDefaultValue(fieldDef.metadata.default_value, field); fieldDef.id = field.id; fieldDef.type = field.fieldType.createSchemaTypeDef(structDefMap); structDef.fields.add(fieldDef); field.fieldDef = fieldDef; } } private void initializeSchemaVariantWithDefaultValue(Variant variant, StructField field) { variant.nothing = field.isDefaultNothing(); if (!variant.nothing) { switch (field.fieldType.getBondDataType().value) { case BondDataType.Values.BT_UINT8: case BondDataType.Values.BT_UINT16: case BondDataType.Values.BT_UINT32: case BondDataType.Values.BT_UINT64: variant.uint_value = ((Number) field.getDefaultValue()).longValue(); break; case BondDataType.Values.BT_INT8: case BondDataType.Values.BT_INT16: case BondDataType.Values.BT_INT64: variant.int_value = ((Number) field.getDefaultValue()).longValue(); break; case BondDataType.Values.BT_INT32: // could be an enum if (field.fieldType instanceof EnumBondType) { variant.int_value = ((BondEnum) field.getDefaultValue()).getValue(); } else { variant.int_value = (Integer) field.getDefaultValue(); } break; case BondDataType.Values.BT_BOOL: // bool is piggy-backing on the int value variant.int_value = (Boolean) field.getDefaultValue() ? 1 : 0; break; case BondDataType.Values.BT_FLOAT: case BondDataType.Values.BT_DOUBLE: variant.double_value = ((Number) field.getDefaultValue()).doubleValue(); break; case BondDataType.Values.BT_STRING: variant.string_value = (String) field.getDefaultValue(); break; case BondDataType.Values.BT_WSTRING: variant.wstring_value = (String) field.getDefaultValue(); break; default: // the default is null for structs and containers break; } } } /** * Registers a struct type builder from generated code. * * @param clazz the struct class * @param structTypeBuilder type builder for the given struct type * @param <TStruct> the Bond struct value class */ protected static <TStruct extends BondSerializable> void registerStructType( Class<TStruct> clazz, StructBondTypeBuilder<TStruct> structTypeBuilder) { structTypeBuilderRegistry.putIfAbsent(clazz, structTypeBuilder); } /** * Gets a type descriptor for a struct represented by a particular generated class. * This method is used when initializing struct type descriptors, so that a particular * type descriptor may access a type descriptor of another type. This method is the only * accessor to a struct type descriptor that is used in generated code when initializing * struct type descriptors (generic type arguments, the base, or fields) and since the * type descriptor is returns is always initialized, there's the invariant condition that * all cached struct type descriptors are initialized. * * @param clazz the struct class * @param genericTypeArguments the generic type arguments in the declaration order * @return a type descriptor instance */ protected static StructBondType<? extends BondSerializable> getStructType( Class<? extends BondSerializable> clazz, BondType<?>... genericTypeArguments) { StructBondTypeBuilder<?> structTypeBuilder = structTypeBuilderRegistry.get(clazz); if (structTypeBuilder == null) { // the type builder is not found in the registry, which could be due to the following two reasons: // 1. The type builder class hasn't been registered yet, which means that the struct class // (whose generated static initializer does this registration) hasn't been initialized yet, or // 2. The struct class was not generated by the same code generator, which should never happen // since this method is protected and intended to be called only from generated code try { // Class initialization may not be enough since the class may already be in the middle of // initialization, where is needed to initialize a referenced class that had a circular // reference back to it. Therefore, call the static initialization method Method typeInitMethod = clazz.getMethod(BOND_TYPE_INITIALIZATION_METHOD_NAME); typeInitMethod.invoke(null); } catch (Exception e) { // if there is an error, then the class implemenation is invalid throw new RuntimeException( "Unexpected program state: invalid struct implementation: " + clazz.getName(), e); } // at this point the class initialization should register the struct type builder; // if it's still not registered then the struct class initialization is not doing what // it should (although the initialization method exists and was successfully invoked), // so the conclusion is that it's not generated per our expectations structTypeBuilder = structTypeBuilderRegistry.get(clazz); if (structTypeBuilder == null) { throw new RuntimeException( "Unexpected program state: invalid struct implementation: " + clazz.getName()); } } // make sure the generic type argument count matches the expected count; // since this should be called only be generated code, this must be always the case if (structTypeBuilder.getGenericTypeParameterCount() != genericTypeArguments.length) { throw new RuntimeException( "Unexpected program state: generic argument count mismatch: " + clazz.getName() + ", expected: " + structTypeBuilder.getGenericTypeParameterCount() + ", actual: " + genericTypeArguments.length); } // build, cache, and initialize the type descriptor return structTypeBuilder.getInitializedFromCache(genericTypeArguments); } /** * Responsible for building and caching Bond struct types with generic type parameters. Please note * that a {@link StructBondType} instance for a generic type can exist only when all generic type * parameters are bound. This class is responsible for this binding: it takes the generic type * arguments and instantiates a new {@link StructBondType} instance representing a specialization * of the generic type. As a special case, it can instantiate new type descriptors for non-generic * types (for which the list of generic type arguments is null). * * @param <TStruct> the class of the struct value */ protected static abstract class StructBondTypeBuilder<TStruct extends BondSerializable> { /** * Gets the number of generic type parameters or (as a special case) 0 for non-generic types. * * @return the number of generic type parameters */ public abstract int getGenericTypeParameterCount(); /** * Creates a new instance of type descriptor that is neither initialized nor cached. This instance * is used to locate the cached instance (or will be cached itself if no cached instance exists yet). * * @param genericTypeArguments generic type arguments * @return new uninitialized uncached type descriptor instance */ protected abstract StructBondType<TStruct> buildNewInstance(BondType<?>[] genericTypeArguments); /** * Returns an initialized instance of the struct type descriptor from the cache, * building/caching/initializing it if necessary. * * @param genericTypeArguments generic type arguments * @return new initialized type descriptor instance (cached) */ public final StructBondType<TStruct> getInitializedFromCache(BondType<?>... genericTypeArguments) { StructBondType<TStruct> cacheKey = this.buildNewInstance(genericTypeArguments); StructBondType<TStruct> cachedType = (StructBondType<TStruct>) getCachedType(cacheKey); cachedType.ensureInitialized(); return cachedType; } } /** * A descriptor of a single field in a struct declaration that encapsulates the details * of that field behavior such as initialization, serialization and deserialization. * This class is the root of the class hierarchy for various Bond types (primitives and objects) * as well as for whether the field defaults to "nothing" (i.e. needs a "Something" wrapper). * The purpose of this class hierarchy is that field initialization/serialization/deserialization * code can just call initialize/serialize/deserialize method without any regard to the field type, * which is setup in the struct type descriptor's {@see StructBondType#initialize} method. * * @param <TField> the class of the field value, using corresponding wrappers for primitive types */ protected static abstract class StructField<TField> { // accessed by subclasses final StructBondType<?> structType; final BondType<TField> fieldType; final short id; final String name; final Modifier modifier; private FieldDef fieldDef; // restrict subclasses to nested classes only private StructField( StructBondType<?> structType, BondType<TField> fieldType, int id, String name, Modifier modifier) { this.structType = structType; this.fieldType = fieldType; this.id = (short) id; this.name = name; this.modifier = modifier; } /** * Gets the declaring struct type descriptor. * * @return the declaring struct type descriptor */ public final StructBondType<?> getStructType() { return this.structType; } /** * Gets the field type descriptor. * * @return the field type descriptor */ public final BondType<TField> getFieldType() { return this.fieldType; } /** * Gets the field definition schema. * * @return field definition schema. */ public final FieldDef getFieldDef() { return this.fieldDef; } /** * Gets the field ID. * * @return the field ID */ public final short getId() { return this.id; } /** * Gets the field name. * * @return the field name */ public final String getName() { return this.name; } /** * Gets the field modifier. * * @return the field modifier */ public final Modifier getModifier() { return this.modifier; } /** * Gets the default value of the field if the field is of primitive data type, or null otherwise. * * @return the default value of the field or null */ public abstract TField getDefaultValue(); /** * Gets a value indicating whether the field is defaulting to "nothing", which means that its * value is wrapped by the {@link Something} wrapper. * * @return a value indicating whether the field is defaulting to "nothing" */ public abstract boolean isDefaultNothing(); /** * Codegen helper to verify deserialized field. * * @param isFieldSet a boolean tracking whether the field was set during deserialization * @throws InvalidBondDataException if the field is required and was not set */ public final void verifyDeserialized(boolean isFieldSet) throws InvalidBondDataException { if (!isFieldSet && this.modifier.value == Modifier.Required.value) { // throws Throw.raiseRequiredStructFieldIsMissingDeserializationError(this); } } final void verifyFieldWasNotYetDeserialized( boolean wasAlreadyDeserialized) throws InvalidBondDataException { if (wasAlreadyDeserialized) { Throw.raiseStructFieldIsPresentMoreThanOnceDeserializationError(this); } } final boolean isOptional() { return this.modifier.value == Modifier.Optional.value; } } /** * Implements the {@link StructField} contract for fields of general object data types * (i.e. any field that is not of a Java primitive type, string, or an enum) that are * not defaulting to "nothing". Since these field types cannot have explicit default * values, there is no constructor that takes a default value. */ protected static final class ObjectStructField<TField> extends StructField<TField> { public ObjectStructField( StructBondType<?> structType, BondType<TField> fieldType, int id, String name, Modifier modifier) { super(structType, fieldType, id, name, modifier); } @Override public final boolean isDefaultNothing() { return false; } @Override public final TField getDefaultValue() { return this.initialize(); } public final TField initialize() { return this.fieldType.newDefaultValue(); } public final TField clone(TField value) { return this.fieldType.cloneValue(value); } public final void serialize( SerializationContext context, TField value) throws IOException { this.fieldType.serializeField(context, value, this); } public final TField deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return this.fieldType.deserializeField(context, this); } public final TField deserialize( UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return this.fieldType.deserializeValue(context, typeDef); } } /** * Implements the {@link StructField} contract for fields of general object data types * (i.e. any field that is not of a Java primitive type, string, or an enum) that are * defaulting to "nothing". The default value for such fields is null (meaning "nothing"). */ protected static final class SomethingObjectStructField<TField> extends StructField<TField> { public SomethingObjectStructField( StructBondType<?> structType, BondType<TField> fieldType, int id, String name, Modifier modifier) { super(structType, fieldType, id, name, modifier); } @Override public final boolean isDefaultNothing() { return true; } @Override public final TField getDefaultValue() { return null; } public final SomethingObject<TField> initialize() { return null; } public final SomethingObject<TField> clone(SomethingObject<TField> value) { return value == null ? null : Something.wrap(this.fieldType.cloneValue(value.value)); } public final void serialize( SerializationContext context, SomethingObject<TField> value) throws IOException { this.fieldType.serializeSomethingField(context, value, this); } public final SomethingObject<TField> deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return this.fieldType.deserializeSomethingField(context, this); } public final SomethingObject<TField> deserialize( UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Something.wrap(this.fieldType.deserializeValue(context, typeDef)); } } /** * Implements the {@link StructField} contract for fields of the uint8 primitive data type * that are not defaulting to "nothing". */ protected static final class UInt8StructField extends StructField<Byte> { private final byte defaultValue; public UInt8StructField( StructBondType<?> structType, int id, String name, Modifier modifier, byte defaultValue) { super(structType, BondTypes.UINT8, id, name, modifier); this.defaultValue = defaultValue; } public UInt8StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { this(structType, id, name, modifier, UInt8BondType.DEFAULT_VALUE_AS_PRIMITIVE); } @Override public final boolean isDefaultNothing() { return false; } @Override public final Byte getDefaultValue() { // box return this.initialize(); } public final byte initialize() { return this.defaultValue; } public final byte clone(byte value) { return value; } public final void serialize( SerializationContext context, byte value) throws IOException { UInt8BondType.serializePrimitiveField(context, value, this); } public final byte deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return UInt8BondType.deserializePrimitiveField(context, this); } public final byte deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return UInt8BondType.deserializePrimitiveValue(context); } } /** * Implements the {@link StructField} contract for fields of the uint8 primitive data type * that are defaulting to "nothing". */ protected static final class SomethingUInt8StructField extends StructField<Byte> { public SomethingUInt8StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { super(structType, BondTypes.UINT8, id, name, modifier); } @Override public final boolean isDefaultNothing() { return true; } @Override public final Byte getDefaultValue() { return null; } public final SomethingByte initialize() { return null; } public final SomethingByte clone(SomethingByte value) { return value == null ? null : Something.wrap(value.value); } public final void serialize( SerializationContext context, SomethingByte value) throws IOException { UInt8BondType.serializePrimitiveSomethingField(context, value, this); } public final SomethingByte deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return UInt8BondType.deserializePrimitiveSomethingField(context, this); } public final SomethingByte deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Something.wrap(UInt8BondType.deserializePrimitiveValue(context)); } } /** * Implements the {@link StructField} contract for fields of the uint16 primitive data type * that are not defaulting to "nothing". */ protected static final class UInt16StructField extends StructField<Short> { private final short defaultValue; public UInt16StructField( StructBondType<?> structType, int id, String name, Modifier modifier, short defaultValue) { super(structType, BondTypes.UINT16, id, name, modifier); this.defaultValue = defaultValue; } public UInt16StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { this(structType, id, name, modifier, UInt16BondType.DEFAULT_VALUE_AS_PRIMITIVE); } @Override public final boolean isDefaultNothing() { return false; } @Override public final Short getDefaultValue() { // box return this.initialize(); } public final short initialize() { return this.defaultValue; } public final short clone(short value) { return value; } public final void serialize( SerializationContext context, short value) throws IOException { UInt16BondType.serializePrimitiveField(context, value, this); } public final short deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return UInt16BondType.deserializePrimitiveField(context, this); } public final short deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return UInt16BondType.deserializePrimitiveValue(context); } } /** * Implements the {@link StructField} contract for fields of the uint16 primitive data type * that are defaulting to "nothing". */ protected static final class SomethingUInt16StructField extends StructField<Short> { public SomethingUInt16StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { super(structType, BondTypes.UINT16, id, name, modifier); } @Override public final boolean isDefaultNothing() { return true; } @Override public final Short getDefaultValue() { return null; } public final SomethingShort initialize() { return null; } public final SomethingShort clone(SomethingShort value) { return value == null ? null : Something.wrap(value.value); } public final void serialize( SerializationContext context, SomethingShort value) throws IOException { UInt16BondType.serializePrimitiveSomethingField(context, value, this); } public final SomethingShort deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return UInt16BondType.deserializePrimitiveSomethingField(context, this); } public final SomethingShort deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Something.wrap(UInt16BondType.deserializePrimitiveValue(context)); } } /** * Implements the {@link StructField} contract for fields of the uint32 primitive data type * that are not defaulting to "nothing". */ protected static final class UInt32StructField extends StructField<Integer> { private final int defaultValue; public UInt32StructField( StructBondType<?> structType, int id, String name, Modifier modifier, int defaultValue) { super(structType, BondTypes.UINT32, id, name, modifier); this.defaultValue = defaultValue; } public UInt32StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { this(structType, id, name, modifier, UInt32BondType.DEFAULT_VALUE_AS_PRIMITIVE); } @Override public final boolean isDefaultNothing() { return false; } @Override public final Integer getDefaultValue() { // box return this.initialize(); } public final int initialize() { return this.defaultValue; } public final int clone(int value) { return value; } public final void serialize( SerializationContext context, int value) throws IOException { UInt32BondType.serializePrimitiveField(context, value, this); } public final int deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return UInt32BondType.deserializePrimitiveField(context, this); } public final int deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return UInt32BondType.deserializePrimitiveValue(context); } } /** * Implements the {@link StructField} contract for fields of the uint32 primitive data type * that are defaulting to "nothing". */ protected static final class SomethingUInt32StructField extends StructField<Integer> { public SomethingUInt32StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { super(structType, BondTypes.UINT32, id, name, modifier); } @Override public final boolean isDefaultNothing() { return true; } @Override public final Integer getDefaultValue() { return null; } public final SomethingInteger initialize() { return null; } public final SomethingInteger clone(SomethingInteger value) { return value == null ? null : Something.wrap(value.value); } public final void serialize( SerializationContext context, SomethingInteger value) throws IOException { UInt32BondType.serializePrimitiveSomethingField(context, value, this); } public final SomethingInteger deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return UInt32BondType.deserializePrimitiveSomethingField(context, this); } public final SomethingInteger deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Something.wrap(UInt32BondType.deserializePrimitiveValue(context)); } } /** * Implements the {@link StructField} contract for fields of the uint64 primitive data type * that are not defaulting to "nothing". */ protected static final class UInt64StructField extends StructField<Long> { private final long defaultValue; public UInt64StructField( StructBondType<?> structType, int id, String name, Modifier modifier, long defaultValue) { super(structType, BondTypes.UINT64, id, name, modifier); this.defaultValue = defaultValue; } public UInt64StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { this(structType, id, name, modifier, UInt64BondType.DEFAULT_VALUE_AS_PRIMITIVE); } @Override public final boolean isDefaultNothing() { return false; } @Override public final Long getDefaultValue() { // box return this.initialize(); } public final long initialize() { return this.defaultValue; } public final long clone(long value) { return value; } public final void serialize( SerializationContext context, long value) throws IOException { UInt64BondType.serializePrimitiveField(context, value, this); } public final long deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return UInt64BondType.deserializePrimitiveField(context, this); } public final long deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return UInt64BondType.deserializePrimitiveValue(context); } } /** * Implements the {@link StructField} contract for fields of the uint64 primitive data type * that are defaulting to "nothing". */ protected static final class SomethingUInt64StructField extends StructField<Long> { public SomethingUInt64StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { super(structType, BondTypes.UINT64, id, name, modifier); } @Override public final boolean isDefaultNothing() { return true; } @Override public final Long getDefaultValue() { return null; } public final SomethingLong initialize() { return null; } public final SomethingLong clone(SomethingLong value) { return value == null ? null : Something.wrap(value.value); } public final void serialize( SerializationContext context, SomethingLong value) throws IOException { UInt64BondType.serializePrimitiveSomethingField(context, value, this); } public final SomethingLong deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return UInt64BondType.deserializePrimitiveSomethingField(context, this); } public final SomethingLong deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Something.wrap(UInt64BondType.deserializePrimitiveValue(context)); } } /** * Implements the {@link StructField} contract for fields of the int8 primitive data type * that are not defaulting to "nothing". */ protected static final class Int8StructField extends StructField<Byte> { private final byte defaultValue; public Int8StructField( StructBondType<?> structType, int id, String name, Modifier modifier, byte defaultValue) { super(structType, BondTypes.INT8, id, name, modifier); this.defaultValue = defaultValue; } public Int8StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { this(structType, id, name, modifier, Int8BondType.DEFAULT_VALUE_AS_PRIMITIVE); } @Override public final boolean isDefaultNothing() { return false; } @Override public final Byte getDefaultValue() { // box return this.initialize(); } public final byte initialize() { return this.defaultValue; } public final byte clone(byte value) { return value; } public final void serialize( SerializationContext context, byte value) throws IOException { Int8BondType.serializePrimitiveField(context, value, this); } public final byte deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return Int8BondType.deserializePrimitiveField(context, this); } public final byte deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Int8BondType.deserializePrimitiveValue(context); } } /** * Implements the {@link StructField} contract for fields of the int8 primitive data type * that are defaulting to "nothing". */ protected static final class SomethingInt8StructField extends StructField<Byte> { public SomethingInt8StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { super(structType, BondTypes.INT8, id, name, modifier); } @Override public final boolean isDefaultNothing() { return true; } @Override public final Byte getDefaultValue() { return null; } public final SomethingByte initialize() { return null; } public final SomethingByte clone(SomethingByte value) { return value == null ? null : Something.wrap(value.value); } public final void serialize( SerializationContext context, SomethingByte value) throws IOException { Int8BondType.serializePrimitiveSomethingField(context, value, this); } public final SomethingByte deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return Int8BondType.deserializePrimitiveSomethingField(context, this); } public final SomethingByte deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Something.wrap(Int8BondType.deserializePrimitiveValue(context)); } } /** * Implements the {@link StructField} contract for fields of the int16 primitive data type * that are not defaulting to "nothing". */ protected static final class Int16StructField extends StructField<Short> { private final short defaultValue; public Int16StructField( StructBondType<?> structType, int id, String name, Modifier modifier, short defaultValue) { super(structType, BondTypes.INT16, id, name, modifier); this.defaultValue = defaultValue; } public Int16StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { this(structType, id, name, modifier, Int16BondType.DEFAULT_VALUE_AS_PRIMITIVE); } @Override public final boolean isDefaultNothing() { return false; } @Override public final Short getDefaultValue() { // box return this.initialize(); } public final short initialize() { return this.defaultValue; } public final short clone(short value) { return value; } public final void serialize( SerializationContext context, short value) throws IOException { Int16BondType.serializePrimitiveField(context, value, this); } public final short deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return Int16BondType.deserializePrimitiveField(context, this); } public final short deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Int16BondType.deserializePrimitiveValue(context); } } /** * Implements the {@link StructField} contract for fields of the int16 primitive data type * that are defaulting to "nothing". */ protected static final class SomethingInt16StructField extends StructField<Short> { public SomethingInt16StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { super(structType, BondTypes.INT16, id, name, modifier); } @Override public final boolean isDefaultNothing() { return true; } @Override public final Short getDefaultValue() { return null; } public final SomethingShort initialize() { return null; } public final SomethingShort clone(SomethingShort value) { return value == null ? null : Something.wrap(value.value); } public final void serialize( SerializationContext context, SomethingShort value) throws IOException { Int16BondType.serializePrimitiveSomethingField(context, value, this); } public final SomethingShort deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return Int16BondType.deserializePrimitiveSomethingField(context, this); } public final SomethingShort deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Something.wrap(Int16BondType.deserializePrimitiveValue(context)); } } /** * Implements the {@link StructField} contract for fields of the int32 primitive data type * that are not defaulting to "nothing". */ protected static final class Int32StructField extends StructField<Integer> { private final int defaultValue; public Int32StructField( StructBondType<?> structType, int id, String name, Modifier modifier, int defaultValue) { super(structType, BondTypes.INT32, id, name, modifier); this.defaultValue = defaultValue; } public Int32StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { this(structType, id, name, modifier, Int32BondType.DEFAULT_VALUE_AS_PRIMITIVE); } @Override public final boolean isDefaultNothing() { return false; } @Override public final Integer getDefaultValue() { // box return this.initialize(); } public final int initialize() { return this.defaultValue; } public final int clone(int value) { return value; } public final void serialize( SerializationContext context, int value) throws IOException { Int32BondType.serializePrimitiveField(context, value, this); } public final int deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return Int32BondType.deserializePrimitiveField(context, this); } public final int deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Int32BondType.deserializePrimitiveValue(context); } } /** * Implements the {@link StructField} contract for fields of the int32 primitive data type * that are defaulting to "nothing". */ protected static final class SomethingInt32StructField extends StructField<Integer> { public SomethingInt32StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { super(structType, BondTypes.INT32, id, name, modifier); } @Override public final boolean isDefaultNothing() { return true; } @Override public final Integer getDefaultValue() { return null; } public final SomethingInteger initialize() { return null; } public final SomethingInteger clone(SomethingInteger value) { return value == null ? null : Something.wrap(value.value); } public final void serialize( SerializationContext context, SomethingInteger value) throws IOException { Int32BondType.serializePrimitiveSomethingField(context, value, this); } public final SomethingInteger deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return Int32BondType.deserializePrimitiveSomethingField(context, this); } public final SomethingInteger deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Something.wrap(Int32BondType.deserializePrimitiveValue(context)); } } /** * Implements the {@link StructField} contract for fields of the int64 primitive data type * that are not defaulting to "nothing". */ protected static final class Int64StructField extends StructField<Long> { private final long defaultValue; public Int64StructField( StructBondType<?> structType, int id, String name, Modifier modifier, long defaultValue) { super(structType, BondTypes.INT64, id, name, modifier); this.defaultValue = defaultValue; } public Int64StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { this(structType, id, name, modifier, Int64BondType.DEFAULT_VALUE_AS_PRIMITIVE); } @Override public final boolean isDefaultNothing() { return false; } @Override public final Long getDefaultValue() { // box return this.initialize(); } public final long initialize() { return this.defaultValue; } public final long clone(long value) { return value; } public final void serialize( SerializationContext context, long value) throws IOException { Int64BondType.serializePrimitiveField(context, value, this); } public final long deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return Int64BondType.deserializePrimitiveField(context, this); } public final long deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Int64BondType.deserializePrimitiveValue(context); } } /** * Implements the {@link StructField} contract for fields of the int64 primitive data type * that are defaulting to "nothing". */ protected static final class SomethingInt64StructField extends StructField<Long> { public SomethingInt64StructField( StructBondType<?> structType, int id, String name, Modifier modifier) { super(structType, BondTypes.INT64, id, name, modifier); } @Override public final boolean isDefaultNothing() { return true; } @Override public final Long getDefaultValue() { return null; } public final SomethingLong initialize() { return null; } public final SomethingLong clone(SomethingLong value) { return value == null ? null : Something.wrap(value.value); } public final void serialize( SerializationContext context, SomethingLong value) throws IOException { Int64BondType.serializePrimitiveSomethingField(context, value, this); } public final SomethingLong deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return Int64BondType.deserializePrimitiveSomethingField(context, this); } public final SomethingLong deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Something.wrap(Int64BondType.deserializePrimitiveValue(context)); } } /** * Implements the {@link StructField} contract for fields of the bool primitive data type * that are not defaulting to "nothing". */ protected static final class BoolStructField extends StructField<Boolean> { private final boolean defaultValue; public BoolStructField( StructBondType<?> structType, int id, String name, Modifier modifier, boolean defaultValue) { super(structType, BondTypes.BOOL, id, name, modifier); this.defaultValue = defaultValue; } public BoolStructField( StructBondType<?> structType, int id, String name, Modifier modifier) { this(structType, id, name, modifier, BoolBondType.DEFAULT_VALUE_AS_PRIMITIVE); } @Override public final boolean isDefaultNothing() { return false; } @Override public final Boolean getDefaultValue() { // box return this.initialize(); } public final boolean initialize() { return this.defaultValue; } public final boolean clone(boolean value) { return value; } public final void serialize( SerializationContext context, boolean value) throws IOException { BoolBondType.serializePrimitiveField(context, value, this); } public final boolean deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return BoolBondType.deserializePrimitiveField(context, this); } public final boolean deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return BoolBondType.deserializePrimitiveValue(context); } } /** * Implements the {@link StructField} contract for fields of the bool primitive data type * that are defaulting to "nothing". */ protected static final class SomethingBoolStructField extends StructField<Boolean> { public SomethingBoolStructField( StructBondType<?> structType, int id, String name, Modifier modifier) { super(structType, BondTypes.BOOL, id, name, modifier); } @Override public final boolean isDefaultNothing() { return true; } @Override public final Boolean getDefaultValue() { return null; } public final SomethingBoolean initialize() { return null; } public final SomethingBoolean clone(SomethingBoolean value) { return value == null ? null : Something.wrap(value.value); } public final void serialize( SerializationContext context, SomethingBoolean value) throws IOException { BoolBondType.serializePrimitiveSomethingField(context, value, this); } public final SomethingBoolean deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return BoolBondType.deserializePrimitiveSomethingField(context, this); } public final SomethingBoolean deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Something.wrap(BoolBondType.deserializePrimitiveValue(context)); } } /** * Implements the {@link StructField} contract for fields of the float primitive data type * that are not defaulting to "nothing". */ protected static final class FloatStructField extends StructField<Float> { private final float defaultValue; public FloatStructField( StructBondType<?> structType, int id, String name, Modifier modifier, float defaultValue) { super(structType, BondTypes.FLOAT, id, name, modifier); this.defaultValue = defaultValue; } public FloatStructField( StructBondType<?> structType, int id, String name, Modifier modifier) { this(structType, id, name, modifier, FloatBondType.DEFAULT_VALUE_AS_PRIMITIVE); } @Override public final boolean isDefaultNothing() { return false; } @Override public final Float getDefaultValue() { // box return this.initialize(); } public final float initialize() { return this.defaultValue; } public final float clone(float value) { return value; } public final void serialize( SerializationContext context, float value) throws IOException { FloatBondType.serializePrimitiveField(context, value, this); } public final float deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return FloatBondType.deserializePrimitiveField(context, this); } public final float deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return FloatBondType.deserializePrimitiveValue(context); } } /** * Implements the {@link StructField} contract for fields of the float primitive data type * that are defaulting to "nothing". */ protected static final class SomethingFloatStructField extends StructField<Float> { public SomethingFloatStructField( StructBondType<?> structType, int id, String name, Modifier modifier) { super(structType, BondTypes.FLOAT, id, name, modifier); } @Override public final boolean isDefaultNothing() { return true; } @Override public final Float getDefaultValue() { return null; } public final SomethingFloat initialize() { return null; } public final SomethingFloat clone(SomethingFloat value) { return value == null ? null : Something.wrap(value.value); } public final void serialize( SerializationContext context, SomethingFloat value) throws IOException { FloatBondType.serializePrimitiveSomethingField(context, value, this); } public final SomethingFloat deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return FloatBondType.deserializePrimitiveSomethingField(context, this); } public final SomethingFloat deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Something.wrap(FloatBondType.deserializePrimitiveValue(context)); } } /** * Implements the {@link StructField} contract for fields of the double primitive data type * that are not defaulting to "nothing". */ protected static final class DoubleStructField extends StructField<Double> { private final double defaultValue; public DoubleStructField( StructBondType<?> structType, int id, String name, Modifier modifier, double defaultValue) { super(structType, BondTypes.DOUBLE, id, name, modifier); this.defaultValue = defaultValue; } public DoubleStructField( StructBondType<?> structType, int id, String name, Modifier modifier) { this(structType, id, name, modifier, DoubleBondType.DEFAULT_VALUE_AS_PRIMITIVE); } @Override public final boolean isDefaultNothing() { return false; } @Override public final Double getDefaultValue() { // box return this.initialize(); } public final double initialize() { return this.defaultValue; } public final double clone(double value) { return value; } public final void serialize( SerializationContext context, double value) throws IOException { DoubleBondType.serializePrimitiveField(context, value, this); } public final double deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return DoubleBondType.deserializePrimitiveField(context, this); } public final double deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return DoubleBondType.deserializePrimitiveValue(context); } } /** * Implements the {@link StructField} contract for fields of the double primitive data type * that are defaulting to "nothing". */ protected static final class SomethingDoubleStructField extends StructField<Double> { public SomethingDoubleStructField( StructBondType<?> structType, int id, String name, Modifier modifier) { super(structType, BondTypes.DOUBLE, id, name, modifier); } @Override public final boolean isDefaultNothing() { return true; } @Override public final Double getDefaultValue() { return null; } public final SomethingDouble initialize() { return null; } public final SomethingDouble clone(SomethingDouble value) { return value == null ? null : Something.wrap(value.value); } public final void serialize( SerializationContext context, SomethingDouble value) throws IOException { DoubleBondType.serializePrimitiveSomethingField(context, value, this); } public final SomethingDouble deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return DoubleBondType.deserializePrimitiveSomethingField(context, this); } public final SomethingDouble deserialize(UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Something.wrap(DoubleBondType.deserializePrimitiveValue(context)); } } /** * Implements the {@link StructField} contract for fields of the string primitive data type * that are not defaulting to "nothing". */ protected static final class StringStructField extends StructField<String> { private final String defaultValue; public StringStructField( StructBondType<?> structType, int id, String name, Modifier modifier, String defaultValue) { super(structType, BondTypes.STRING, id, name, modifier); this.defaultValue = defaultValue; } // used by codegen public StringStructField( StructBondType<?> structType, int id, String name, Modifier modifier) { this(structType, id, name, modifier, StringBondType.DEFAULT_VALUE_AS_OBJECT); } @Override public final boolean isDefaultNothing() { return false; } @Override public final String getDefaultValue() { return this.initialize(); } public final String initialize() { return this.defaultValue; } public final String clone(String value) { return value; } public final void serialize( SerializationContext context, String value) throws IOException { this.fieldType.serializeField(context, value, this); } public final String deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return this.fieldType.deserializeField(context, this); } public final String deserialize( UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return this.fieldType.deserializeValue(context, typeDef); } } /** * Implements the {@link StructField} contract for fields of the string primitive data type * that are defaulting to "nothing". */ protected static final class SomethingStringStructField extends StructField<String> { public SomethingStringStructField( StructBondType<?> structType, int id, String name, Modifier modifier) { super(structType, BondTypes.STRING, id, name, modifier); } @Override public final boolean isDefaultNothing() { return true; } @Override public final String getDefaultValue() { return null; } public final SomethingObject<String> initialize() { return null; } public final SomethingObject<String> clone(SomethingObject<String> value) { return value == null ? null : Something.wrap(value.value); } public final void serialize( SerializationContext context, SomethingObject<String> value) throws IOException { this.fieldType.serializeSomethingField(context, value, this); } public final SomethingObject<String> deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return this.fieldType.deserializeSomethingField(context, this); } public final SomethingObject<String> deserialize( UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Something.wrap(this.fieldType.deserializeValue(context, typeDef)); } } /** * Implements the {@link StructField} contract for fields of the string primitive data type * that are not defaulting to "nothing". */ protected static final class WStringStructField extends StructField<String> { private final String defaultValue; public WStringStructField( StructBondType<?> structType, int id, String name, Modifier modifier, String defaultValue) { super(structType, BondTypes.WSTRING, id, name, modifier); this.defaultValue = defaultValue; } // used by codegen public WStringStructField( StructBondType<?> structType, int id, String name, Modifier modifier) { this(structType, id, name, modifier, WStringBondType.DEFAULT_VALUE_AS_OBJECT); } @Override public final boolean isDefaultNothing() { return false; } @Override public final String getDefaultValue() { return this.initialize(); } public final String initialize() { return this.defaultValue; } public final String clone(String value) { return value; } public final void serialize( SerializationContext context, String value) throws IOException { this.fieldType.serializeField(context, value, this); } public final String deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return this.fieldType.deserializeField(context, this); } public final String deserialize( UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return this.fieldType.deserializeValue(context, typeDef); } } /** * Implements the {@link StructField} contract for fields of the string primitive data type * that are defaulting to "nothing". */ protected static final class SomethingWStringStructField extends StructField<String> { // used by codegen public SomethingWStringStructField( StructBondType<?> structType, int id, String name, Modifier modifier) { super(structType, BondTypes.WSTRING, id, name, modifier); } @Override public final boolean isDefaultNothing() { return true; } @Override public final String getDefaultValue() { return null; } public final SomethingObject<String> initialize() { return null; } public final SomethingObject<String> clone(SomethingObject<String> value) { return value == null ? null : Something.wrap(value.value); } public final void serialize( SerializationContext context, SomethingObject<String> value) throws IOException { this.fieldType.serializeSomethingField(context, value, this); } public final SomethingObject<String> deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return this.fieldType.deserializeSomethingField(context, this); } public final SomethingObject<String> deserialize( UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Something.wrap(this.fieldType.deserializeValue(context, typeDef)); } } /** * Implements the {@link StructField} contract for fields of the string primitive data type * that are not defaulting to "nothing". */ protected static final class EnumStructField<TEnum extends BondEnum<TEnum>> extends StructField<TEnum> { private final TEnum defaultValue; public EnumStructField( StructBondType<?> structType, EnumBondType<TEnum> fieldType, int id, String name, Modifier modifier, TEnum defaultValue) { super(structType, fieldType, id, name, modifier); this.defaultValue = defaultValue; } public EnumStructField( StructBondType<?> structType, EnumBondType<TEnum> fieldType, int id, String name, Modifier modifier) { this(structType, fieldType, id, name, modifier, fieldType.newDefaultValue()); } @Override public final boolean isDefaultNothing() { return false; } @Override public final TEnum getDefaultValue() { return this.initialize(); } public final TEnum initialize() { return this.defaultValue; } public final TEnum clone(TEnum value) { return value; } public final void serialize( SerializationContext context, TEnum value) throws IOException { this.fieldType.serializeField(context, value, this); } public final TEnum deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return this.fieldType.deserializeField(context, this); } public final TEnum deserialize( UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return this.fieldType.deserializeValue(context, typeDef); } } /** * Implements the {@link StructField} contract for fields of the string primitive data type * that are defaulting to "nothing". */ protected static final class SomethingEnumStructField<TEnum extends BondEnum<TEnum>> extends StructField<TEnum> { // used by codegen public SomethingEnumStructField( StructBondType<?> structType, EnumBondType<TEnum> fieldType, int id, String name, Modifier modifier) { super(structType, fieldType, id, name, modifier); } @Override public final boolean isDefaultNothing() { return true; } @Override public final TEnum getDefaultValue() { return null; } public final SomethingObject<TEnum> initialize() { return null; } public final SomethingObject<TEnum> clone(SomethingObject<TEnum> value) { return value == null ? null : Something.wrap(value.value); } public final void serialize( SerializationContext context, SomethingObject<TEnum> value) throws IOException { this.fieldType.serializeSomethingField(context, value, this); } public final SomethingObject<TEnum> deserialize( TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException { this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized); return this.fieldType.deserializeSomethingField(context, this); } public final SomethingObject<TEnum> deserialize( UntaggedDeserializationContext context, TypeDef typeDef) throws IOException { return Something.wrap(this.fieldType.deserializeValue(context, typeDef)); } } }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc --> <title>StyleConstants.CharacterConstants (Java SE 12 &amp; JDK 12 )</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="keywords" content="javax.swing.text.StyleConstants.CharacterConstants class"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> <script type="text/javascript" src="../../../../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif]--> <script type="text/javascript" src="../../../../jquery/jquery-3.3.1.js"></script> <script type="text/javascript" src="../../../../jquery/jquery-migrate-3.0.1.js"></script> <script type="text/javascript" src="../../../../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="StyleConstants.CharacterConstants (Java SE 12 & JDK 12 )"; } } catch(err) { } //--> var pathtoroot = "../../../../"; var useModuleDirectories = true; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <header role="banner"> <nav role="navigation"> <div class="fixedNav"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a id="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../index.html">Overview</a></li> <li><a href="../../../module-summary.html">Module</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/StyleConstants.CharacterConstants.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-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><div style="margin-top: 14px;"><strong>Java SE 12 &amp; JDK 12</strong> </div></div> </div> <div class="subNav"> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested.class.summary">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <ul class="navListSearch"> <li><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </li> </ul> </div> <a id="skip.navbar.top"> <!-- --> </a> <!-- ========= END OF TOP NAVBAR ========= --> </div> <div class="navPadding">&nbsp;</div> <script type="text/javascript"><!-- $('.navPadding').css('padding-top', $('.fixedNav').css("height")); //--> </script> </nav> </header> <!-- ======== START OF CLASS DATA ======== --> <main role="main"> <div class="header"> <div class="subTitle"><span class="moduleLabelInType">Module</span>&nbsp;<a href="../../../module-summary.html">java.desktop</a></div> <div class="subTitle"><span class="packageLabelInType">Package</span>&nbsp;<a href="package-summary.html">javax.swing.text</a></div> <h2 title="Class StyleConstants.CharacterConstants" class="title">Class StyleConstants.CharacterConstants</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li><a href="../../../../java.base/java/lang/Object.html" title="class in java.lang">java.lang.Object</a></li> <li> <ul class="inheritance"> <li><a href="StyleConstants.html" title="class in javax.swing.text">javax.swing.text.StyleConstants</a></li> <li> <ul class="inheritance"> <li>javax.swing.text.StyleConstants.CharacterConstants</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd><code><a href="AttributeSet.CharacterAttribute.html" title="interface in javax.swing.text">AttributeSet.CharacterAttribute</a></code></dd> </dl> <dl> <dt>Enclosing class:</dt> <dd><a href="StyleConstants.html" title="class in javax.swing.text">StyleConstants</a></dd> </dl> <hr> <pre>public static class <span class="typeNameLabel">StyleConstants.CharacterConstants</span> extends <a href="StyleConstants.html" title="class in javax.swing.text">StyleConstants</a> implements <a href="AttributeSet.CharacterAttribute.html" title="interface in javax.swing.text">AttributeSet.CharacterAttribute</a></pre> <div class="block">This is a typesafe enumeration of the <em>well-known</em> attributes that contribute to a character style. These are aliased by the outer class for general presentation.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <section role="region"> <ul class="blockList"> <li class="blockList"><a id="nested.class.summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <ul class="blockList"> <li class="blockList"><a id="nested.classes.inherited.from.class.javax.swing.text.StyleConstants"> <!-- --> </a> <h3>Nested classes/interfaces declared in class&nbsp;javax.swing.text.<a href="StyleConstants.html" title="class in javax.swing.text">StyleConstants</a></h3> <code><a href="StyleConstants.CharacterConstants.html" title="class in javax.swing.text">StyleConstants.CharacterConstants</a>, <a href="StyleConstants.ColorConstants.html" title="class in javax.swing.text">StyleConstants.ColorConstants</a>, <a href="StyleConstants.FontConstants.html" title="class in javax.swing.text">StyleConstants.FontConstants</a>, <a href="StyleConstants.ParagraphConstants.html" title="class in javax.swing.text">StyleConstants.ParagraphConstants</a></code></li> </ul> </li> </ul> </section> <!-- =========== FIELD SUMMARY =========== --> <section role="region"> <ul class="blockList"> <li class="blockList"><a id="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <ul class="blockList"> <li class="blockList"><a id="fields.inherited.from.class.javax.swing.text.StyleConstants"> <!-- --> </a> <h3>Fields declared in class&nbsp;javax.swing.text.<a href="StyleConstants.html" title="class in javax.swing.text">StyleConstants</a></h3> <code><a href="StyleConstants.html#ALIGN_CENTER">ALIGN_CENTER</a>, <a href="StyleConstants.html#ALIGN_JUSTIFIED">ALIGN_JUSTIFIED</a>, <a href="StyleConstants.html#ALIGN_LEFT">ALIGN_LEFT</a>, <a href="StyleConstants.html#ALIGN_RIGHT">ALIGN_RIGHT</a>, <a href="StyleConstants.html#Alignment">Alignment</a>, <a href="StyleConstants.html#Background">Background</a>, <a href="StyleConstants.html#BidiLevel">BidiLevel</a>, <a href="StyleConstants.html#Bold">Bold</a>, <a href="StyleConstants.html#ComponentAttribute">ComponentAttribute</a>, <a href="StyleConstants.html#ComponentElementName">ComponentElementName</a>, <a href="StyleConstants.html#ComposedTextAttribute">ComposedTextAttribute</a>, <a href="StyleConstants.html#Family">Family</a>, <a href="StyleConstants.html#FirstLineIndent">FirstLineIndent</a>, <a href="StyleConstants.html#FontFamily">FontFamily</a>, <a href="StyleConstants.html#FontSize">FontSize</a>, <a href="StyleConstants.html#Foreground">Foreground</a>, <a href="StyleConstants.html#IconAttribute">IconAttribute</a>, <a href="StyleConstants.html#IconElementName">IconElementName</a>, <a href="StyleConstants.html#Italic">Italic</a>, <a href="StyleConstants.html#LeftIndent">LeftIndent</a>, <a href="StyleConstants.html#LineSpacing">LineSpacing</a>, <a href="StyleConstants.html#ModelAttribute">ModelAttribute</a>, <a href="StyleConstants.html#NameAttribute">NameAttribute</a>, <a href="StyleConstants.html#Orientation">Orientation</a>, <a href="StyleConstants.html#ResolveAttribute">ResolveAttribute</a>, <a href="StyleConstants.html#RightIndent">RightIndent</a>, <a href="StyleConstants.html#Size">Size</a>, <a href="StyleConstants.html#SpaceAbove">SpaceAbove</a>, <a href="StyleConstants.html#SpaceBelow">SpaceBelow</a>, <a href="StyleConstants.html#StrikeThrough">StrikeThrough</a>, <a href="StyleConstants.html#Subscript">Subscript</a>, <a href="StyleConstants.html#Superscript">Superscript</a>, <a href="StyleConstants.html#TabSet">TabSet</a>, <a href="StyleConstants.html#Underline">Underline</a></code></li> </ul> </li> </ul> </section> <!-- ========== METHOD SUMMARY =========== --> <section role="region"> <ul class="blockList"> <li class="blockList"><a id="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <ul class="blockList"> <li class="blockList"><a id="methods.inherited.from.class.javax.swing.text.StyleConstants"> <!-- --> </a> <h3>Methods declared in class&nbsp;javax.swing.text.<a href="StyleConstants.html" title="class in javax.swing.text">StyleConstants</a></h3> <code><a href="StyleConstants.html#getAlignment(javax.swing.text.AttributeSet)">getAlignment</a>, <a href="StyleConstants.html#getBackground(javax.swing.text.AttributeSet)">getBackground</a>, <a href="StyleConstants.html#getBidiLevel(javax.swing.text.AttributeSet)">getBidiLevel</a>, <a href="StyleConstants.html#getComponent(javax.swing.text.AttributeSet)">getComponent</a>, <a href="StyleConstants.html#getFirstLineIndent(javax.swing.text.AttributeSet)">getFirstLineIndent</a>, <a href="StyleConstants.html#getFontFamily(javax.swing.text.AttributeSet)">getFontFamily</a>, <a href="StyleConstants.html#getFontSize(javax.swing.text.AttributeSet)">getFontSize</a>, <a href="StyleConstants.html#getForeground(javax.swing.text.AttributeSet)">getForeground</a>, <a href="StyleConstants.html#getIcon(javax.swing.text.AttributeSet)">getIcon</a>, <a href="StyleConstants.html#getLeftIndent(javax.swing.text.AttributeSet)">getLeftIndent</a>, <a href="StyleConstants.html#getLineSpacing(javax.swing.text.AttributeSet)">getLineSpacing</a>, <a href="StyleConstants.html#getRightIndent(javax.swing.text.AttributeSet)">getRightIndent</a>, <a href="StyleConstants.html#getSpaceAbove(javax.swing.text.AttributeSet)">getSpaceAbove</a>, <a href="StyleConstants.html#getSpaceBelow(javax.swing.text.AttributeSet)">getSpaceBelow</a>, <a href="StyleConstants.html#getTabSet(javax.swing.text.AttributeSet)">getTabSet</a>, <a href="StyleConstants.html#isBold(javax.swing.text.AttributeSet)">isBold</a>, <a href="StyleConstants.html#isItalic(javax.swing.text.AttributeSet)">isItalic</a>, <a href="StyleConstants.html#isStrikeThrough(javax.swing.text.AttributeSet)">isStrikeThrough</a>, <a href="StyleConstants.html#isSubscript(javax.swing.text.AttributeSet)">isSubscript</a>, <a href="StyleConstants.html#isSuperscript(javax.swing.text.AttributeSet)">isSuperscript</a>, <a href="StyleConstants.html#isUnderline(javax.swing.text.AttributeSet)">isUnderline</a>, <a href="StyleConstants.html#setAlignment(javax.swing.text.MutableAttributeSet,int)">setAlignment</a>, <a href="StyleConstants.html#setBackground(javax.swing.text.MutableAttributeSet,java.awt.Color)">setBackground</a>, <a href="StyleConstants.html#setBidiLevel(javax.swing.text.MutableAttributeSet,int)">setBidiLevel</a>, <a href="StyleConstants.html#setBold(javax.swing.text.MutableAttributeSet,boolean)">setBold</a>, <a href="StyleConstants.html#setComponent(javax.swing.text.MutableAttributeSet,java.awt.Component)">setComponent</a>, <a href="StyleConstants.html#setFirstLineIndent(javax.swing.text.MutableAttributeSet,float)">setFirstLineIndent</a>, <a href="StyleConstants.html#setFontFamily(javax.swing.text.MutableAttributeSet,java.lang.String)">setFontFamily</a>, <a href="StyleConstants.html#setFontSize(javax.swing.text.MutableAttributeSet,int)">setFontSize</a>, <a href="StyleConstants.html#setForeground(javax.swing.text.MutableAttributeSet,java.awt.Color)">setForeground</a>, <a href="StyleConstants.html#setIcon(javax.swing.text.MutableAttributeSet,javax.swing.Icon)">setIcon</a>, <a href="StyleConstants.html#setItalic(javax.swing.text.MutableAttributeSet,boolean)">setItalic</a>, <a href="StyleConstants.html#setLeftIndent(javax.swing.text.MutableAttributeSet,float)">setLeftIndent</a>, <a href="StyleConstants.html#setLineSpacing(javax.swing.text.MutableAttributeSet,float)">setLineSpacing</a>, <a href="StyleConstants.html#setRightIndent(javax.swing.text.MutableAttributeSet,float)">setRightIndent</a>, <a href="StyleConstants.html#setSpaceAbove(javax.swing.text.MutableAttributeSet,float)">setSpaceAbove</a>, <a href="StyleConstants.html#setSpaceBelow(javax.swing.text.MutableAttributeSet,float)">setSpaceBelow</a>, <a href="StyleConstants.html#setStrikeThrough(javax.swing.text.MutableAttributeSet,boolean)">setStrikeThrough</a>, <a href="StyleConstants.html#setSubscript(javax.swing.text.MutableAttributeSet,boolean)">setSubscript</a>, <a href="StyleConstants.html#setSuperscript(javax.swing.text.MutableAttributeSet,boolean)">setSuperscript</a>, <a href="StyleConstants.html#setTabSet(javax.swing.text.MutableAttributeSet,javax.swing.text.TabSet)">setTabSet</a>, <a href="StyleConstants.html#setUnderline(javax.swing.text.MutableAttributeSet,boolean)">setUnderline</a>, <a href="StyleConstants.html#toString()">toString</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a id="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods declared in class&nbsp;java.lang.<a href="../../../../java.base/java/lang/Object.html" title="class in java.lang">Object</a></h3> <code><a href="../../../../java.base/java/lang/Object.html#clone()">clone</a>, <a href="../../../../java.base/java/lang/Object.html#equals(java.lang.Object)">equals</a>, <a href="../../../../java.base/java/lang/Object.html#finalize()">finalize</a>, <a href="../../../../java.base/java/lang/Object.html#getClass()">getClass</a>, <a href="../../../../java.base/java/lang/Object.html#hashCode()">hashCode</a>, <a href="../../../../java.base/java/lang/Object.html#notify()">notify</a>, <a href="../../../../java.base/java/lang/Object.html#notifyAll()">notifyAll</a>, <a href="../../../../java.base/java/lang/Object.html#wait()">wait</a>, <a href="../../../../java.base/java/lang/Object.html#wait(long)">wait</a>, <a href="../../../../java.base/java/lang/Object.html#wait(long,int)">wait</a></code></li> </ul> </li> </ul> </section> </li> </ul> </div> </div> </main> <!-- ========= END OF CLASS DATA ========= --> <footer role="contentinfo"> <nav role="navigation"> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a id="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../index.html">Overview</a></li> <li><a href="../../../module-summary.html">Module</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/StyleConstants.CharacterConstants.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-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><div style="margin-top: 14px;"><strong>Java SE 12 &amp; JDK 12</strong> </div></div> </div> <div class="subNav"> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested.class.summary">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> </div> <a id="skip.navbar.bottom"> <!-- --> </a> <!-- ======== END OF BOTTOM NAVBAR ======= --> </nav> <p class="legalCopy"><small><a href="https://bugreport.java.com/bugreport/">Report a bug or suggest an enhancement</a><br> For further API reference and developer documentation see the <a href="https://docs.oracle.com/pls/topic/lookup?ctx=javase12.0.2&amp;id=homepage" target="_blank">Java SE Documentation</a>, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.<br> <a href="../../../../../legal/copyright.html">Copyright</a> &copy; 1993, 2019, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.<br>All rights reserved. Use is subject to <a href="https://www.oracle.com/technetwork/java/javase/terms/license/java12.0.2speclicense.html">license terms</a> and the <a href="https://www.oracle.com/technetwork/java/redist-137594.html">documentation redistribution policy</a>. <!-- Version 12.0.2+10 --></small></p> </footer> </body> </html>
{ "pile_set_name": "Github" }
/* * Copyright 2014 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.plugins.ide.internal.resolver.model; import org.gradle.api.artifacts.Configuration; import java.io.File; public class UnresolvedIdeRepoFileDependency extends IdeExtendedRepoFileDependency { private Exception problem; public UnresolvedIdeRepoFileDependency(Configuration declaredConfiguration, File file) { super(declaredConfiguration, file); } public Exception getProblem() { return problem; } public void setProblem(Exception problem) { this.problem = problem; } }
{ "pile_set_name": "Github" }
{ "name": "errno", "authors": [ "Rod Vagg @rvagg <rod@vagg.org> (https://github.com/rvagg)" ], "description": "libuv errno details exposed", "keywords": [ "errors", "errno", "libuv" ], "version": "0.1.7", "main": "errno.js", "dependencies": { "prr": "~1.0.1" }, "bin": { "errno": "./cli.js" }, "devDependencies": { "error-stack-parser": "^2.0.1", "inherits": "^2.0.3", "tape": "~4.8.0" }, "repository": { "type": "git", "url": "https://github.com/rvagg/node-errno.git" }, "license": "MIT", "scripts": { "test": "node --use_strict test.js" } }
{ "pile_set_name": "Github" }
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package windows import ( "syscall" "unsafe" ) const ( NameUnknown = 0 NameFullyQualifiedDN = 1 NameSamCompatible = 2 NameDisplay = 3 NameUniqueId = 6 NameCanonical = 7 NameUserPrincipal = 8 NameCanonicalEx = 9 NameServicePrincipal = 10 NameDnsDomain = 12 ) // This function returns 1 byte BOOLEAN rather than the 4 byte BOOL. // http://blogs.msdn.com/b/drnick/archive/2007/12/19/windows-and-upn-format-credentials.aspx //sys TranslateName(accName *uint16, accNameFormat uint32, desiredNameFormat uint32, translatedName *uint16, nSize *uint32) (err error) [failretval&0xff==0] = secur32.TranslateNameW //sys GetUserNameEx(nameFormat uint32, nameBuffre *uint16, nSize *uint32) (err error) [failretval&0xff==0] = secur32.GetUserNameExW // TranslateAccountName converts a directory service // object name from one format to another. func TranslateAccountName(username string, from, to uint32, initSize int) (string, error) { u, e := UTF16PtrFromString(username) if e != nil { return "", e } n := uint32(50) for { b := make([]uint16, n) e = TranslateName(u, from, to, &b[0], &n) if e == nil { return UTF16ToString(b[:n]), nil } if e != ERROR_INSUFFICIENT_BUFFER { return "", e } if n <= uint32(len(b)) { return "", e } } } const ( // do not reorder NetSetupUnknownStatus = iota NetSetupUnjoined NetSetupWorkgroupName NetSetupDomainName ) type UserInfo10 struct { Name *uint16 Comment *uint16 UsrComment *uint16 FullName *uint16 } //sys NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) = netapi32.NetUserGetInfo //sys NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (neterr error) = netapi32.NetGetJoinInformation //sys NetApiBufferFree(buf *byte) (neterr error) = netapi32.NetApiBufferFree const ( // do not reorder SidTypeUser = 1 + iota SidTypeGroup SidTypeDomain SidTypeAlias SidTypeWellKnownGroup SidTypeDeletedAccount SidTypeInvalid SidTypeUnknown SidTypeComputer SidTypeLabel ) type SidIdentifierAuthority struct { Value [6]byte } var ( SECURITY_NULL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 0}} SECURITY_WORLD_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 1}} SECURITY_LOCAL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 2}} SECURITY_CREATOR_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 3}} SECURITY_NON_UNIQUE_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 4}} SECURITY_NT_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 5}} SECURITY_MANDATORY_LABEL_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 16}} ) const ( SECURITY_NULL_RID = 0 SECURITY_WORLD_RID = 0 SECURITY_LOCAL_RID = 0 SECURITY_CREATOR_OWNER_RID = 0 SECURITY_CREATOR_GROUP_RID = 1 SECURITY_DIALUP_RID = 1 SECURITY_NETWORK_RID = 2 SECURITY_BATCH_RID = 3 SECURITY_INTERACTIVE_RID = 4 SECURITY_LOGON_IDS_RID = 5 SECURITY_SERVICE_RID = 6 SECURITY_LOCAL_SYSTEM_RID = 18 SECURITY_BUILTIN_DOMAIN_RID = 32 SECURITY_PRINCIPAL_SELF_RID = 10 SECURITY_CREATOR_OWNER_SERVER_RID = 0x2 SECURITY_CREATOR_GROUP_SERVER_RID = 0x3 SECURITY_LOGON_IDS_RID_COUNT = 0x3 SECURITY_ANONYMOUS_LOGON_RID = 0x7 SECURITY_PROXY_RID = 0x8 SECURITY_ENTERPRISE_CONTROLLERS_RID = 0x9 SECURITY_SERVER_LOGON_RID = SECURITY_ENTERPRISE_CONTROLLERS_RID SECURITY_AUTHENTICATED_USER_RID = 0xb SECURITY_RESTRICTED_CODE_RID = 0xc SECURITY_NT_NON_UNIQUE_RID = 0x15 ) // Predefined domain-relative RIDs for local groups. // See https://msdn.microsoft.com/en-us/library/windows/desktop/aa379649(v=vs.85).aspx const ( DOMAIN_ALIAS_RID_ADMINS = 0x220 DOMAIN_ALIAS_RID_USERS = 0x221 DOMAIN_ALIAS_RID_GUESTS = 0x222 DOMAIN_ALIAS_RID_POWER_USERS = 0x223 DOMAIN_ALIAS_RID_ACCOUNT_OPS = 0x224 DOMAIN_ALIAS_RID_SYSTEM_OPS = 0x225 DOMAIN_ALIAS_RID_PRINT_OPS = 0x226 DOMAIN_ALIAS_RID_BACKUP_OPS = 0x227 DOMAIN_ALIAS_RID_REPLICATOR = 0x228 DOMAIN_ALIAS_RID_RAS_SERVERS = 0x229 DOMAIN_ALIAS_RID_PREW2KCOMPACCESS = 0x22a DOMAIN_ALIAS_RID_REMOTE_DESKTOP_USERS = 0x22b DOMAIN_ALIAS_RID_NETWORK_CONFIGURATION_OPS = 0x22c DOMAIN_ALIAS_RID_INCOMING_FOREST_TRUST_BUILDERS = 0x22d DOMAIN_ALIAS_RID_MONITORING_USERS = 0x22e DOMAIN_ALIAS_RID_LOGGING_USERS = 0x22f DOMAIN_ALIAS_RID_AUTHORIZATIONACCESS = 0x230 DOMAIN_ALIAS_RID_TS_LICENSE_SERVERS = 0x231 DOMAIN_ALIAS_RID_DCOM_USERS = 0x232 DOMAIN_ALIAS_RID_IUSERS = 0x238 DOMAIN_ALIAS_RID_CRYPTO_OPERATORS = 0x239 DOMAIN_ALIAS_RID_CACHEABLE_PRINCIPALS_GROUP = 0x23b DOMAIN_ALIAS_RID_NON_CACHEABLE_PRINCIPALS_GROUP = 0x23c DOMAIN_ALIAS_RID_EVENT_LOG_READERS_GROUP = 0x23d DOMAIN_ALIAS_RID_CERTSVC_DCOM_ACCESS_GROUP = 0x23e ) //sys LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountSidW //sys LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountNameW //sys ConvertSidToStringSid(sid *SID, stringSid **uint16) (err error) = advapi32.ConvertSidToStringSidW //sys ConvertStringSidToSid(stringSid *uint16, sid **SID) (err error) = advapi32.ConvertStringSidToSidW //sys GetLengthSid(sid *SID) (len uint32) = advapi32.GetLengthSid //sys CopySid(destSidLen uint32, destSid *SID, srcSid *SID) (err error) = advapi32.CopySid //sys AllocateAndInitializeSid(identAuth *SidIdentifierAuthority, subAuth byte, subAuth0 uint32, subAuth1 uint32, subAuth2 uint32, subAuth3 uint32, subAuth4 uint32, subAuth5 uint32, subAuth6 uint32, subAuth7 uint32, sid **SID) (err error) = advapi32.AllocateAndInitializeSid //sys createWellKnownSid(sidType WELL_KNOWN_SID_TYPE, domainSid *SID, sid *SID, sizeSid *uint32) (err error) = advapi32.CreateWellKnownSid //sys isWellKnownSid(sid *SID, sidType WELL_KNOWN_SID_TYPE) (isWellKnown bool) = advapi32.IsWellKnownSid //sys FreeSid(sid *SID) (err error) [failretval!=0] = advapi32.FreeSid //sys EqualSid(sid1 *SID, sid2 *SID) (isEqual bool) = advapi32.EqualSid //sys getSidIdentifierAuthority(sid *SID) (authority *SidIdentifierAuthority) = advapi32.GetSidIdentifierAuthority //sys getSidSubAuthorityCount(sid *SID) (count *uint8) = advapi32.GetSidSubAuthorityCount //sys getSidSubAuthority(sid *SID, index uint32) (subAuthority *uint32) = advapi32.GetSidSubAuthority //sys isValidSid(sid *SID) (isValid bool) = advapi32.IsValidSid // The security identifier (SID) structure is a variable-length // structure used to uniquely identify users or groups. type SID struct{} // StringToSid converts a string-format security identifier // SID into a valid, functional SID. func StringToSid(s string) (*SID, error) { var sid *SID p, e := UTF16PtrFromString(s) if e != nil { return nil, e } e = ConvertStringSidToSid(p, &sid) if e != nil { return nil, e } defer LocalFree((Handle)(unsafe.Pointer(sid))) return sid.Copy() } // LookupSID retrieves a security identifier SID for the account // and the name of the domain on which the account was found. // System specify target computer to search. func LookupSID(system, account string) (sid *SID, domain string, accType uint32, err error) { if len(account) == 0 { return nil, "", 0, syscall.EINVAL } acc, e := UTF16PtrFromString(account) if e != nil { return nil, "", 0, e } var sys *uint16 if len(system) > 0 { sys, e = UTF16PtrFromString(system) if e != nil { return nil, "", 0, e } } n := uint32(50) dn := uint32(50) for { b := make([]byte, n) db := make([]uint16, dn) sid = (*SID)(unsafe.Pointer(&b[0])) e = LookupAccountName(sys, acc, sid, &n, &db[0], &dn, &accType) if e == nil { return sid, UTF16ToString(db), accType, nil } if e != ERROR_INSUFFICIENT_BUFFER { return nil, "", 0, e } if n <= uint32(len(b)) { return nil, "", 0, e } } } // String converts SID to a string format suitable for display, storage, or transmission. func (sid *SID) String() string { var s *uint16 e := ConvertSidToStringSid(sid, &s) if e != nil { return "" } defer LocalFree((Handle)(unsafe.Pointer(s))) return UTF16ToString((*[256]uint16)(unsafe.Pointer(s))[:]) } // Len returns the length, in bytes, of a valid security identifier SID. func (sid *SID) Len() int { return int(GetLengthSid(sid)) } // Copy creates a duplicate of security identifier SID. func (sid *SID) Copy() (*SID, error) { b := make([]byte, sid.Len()) sid2 := (*SID)(unsafe.Pointer(&b[0])) e := CopySid(uint32(len(b)), sid2, sid) if e != nil { return nil, e } return sid2, nil } // IdentifierAuthority returns the identifier authority of the SID. func (sid *SID) IdentifierAuthority() SidIdentifierAuthority { return *getSidIdentifierAuthority(sid) } // SubAuthorityCount returns the number of sub-authorities in the SID. func (sid *SID) SubAuthorityCount() uint8 { return *getSidSubAuthorityCount(sid) } // SubAuthority returns the sub-authority of the SID as specified by // the index, which must be less than sid.SubAuthorityCount(). func (sid *SID) SubAuthority(idx uint32) uint32 { if idx >= uint32(sid.SubAuthorityCount()) { panic("sub-authority index out of range") } return *getSidSubAuthority(sid, idx) } // IsValid returns whether the SID has a valid revision and length. func (sid *SID) IsValid() bool { return isValidSid(sid) } // Equals compares two SIDs for equality. func (sid *SID) Equals(sid2 *SID) bool { return EqualSid(sid, sid2) } // IsWellKnown determines whether the SID matches the well-known sidType. func (sid *SID) IsWellKnown(sidType WELL_KNOWN_SID_TYPE) bool { return isWellKnownSid(sid, sidType) } // LookupAccount retrieves the name of the account for this SID // and the name of the first domain on which this SID is found. // System specify target computer to search for. func (sid *SID) LookupAccount(system string) (account, domain string, accType uint32, err error) { var sys *uint16 if len(system) > 0 { sys, err = UTF16PtrFromString(system) if err != nil { return "", "", 0, err } } n := uint32(50) dn := uint32(50) for { b := make([]uint16, n) db := make([]uint16, dn) e := LookupAccountSid(sys, sid, &b[0], &n, &db[0], &dn, &accType) if e == nil { return UTF16ToString(b), UTF16ToString(db), accType, nil } if e != ERROR_INSUFFICIENT_BUFFER { return "", "", 0, e } if n <= uint32(len(b)) { return "", "", 0, e } } } // Various types of pre-specified SIDs that can be synthesized and compared at runtime. type WELL_KNOWN_SID_TYPE uint32 const ( WinNullSid = 0 WinWorldSid = 1 WinLocalSid = 2 WinCreatorOwnerSid = 3 WinCreatorGroupSid = 4 WinCreatorOwnerServerSid = 5 WinCreatorGroupServerSid = 6 WinNtAuthoritySid = 7 WinDialupSid = 8 WinNetworkSid = 9 WinBatchSid = 10 WinInteractiveSid = 11 WinServiceSid = 12 WinAnonymousSid = 13 WinProxySid = 14 WinEnterpriseControllersSid = 15 WinSelfSid = 16 WinAuthenticatedUserSid = 17 WinRestrictedCodeSid = 18 WinTerminalServerSid = 19 WinRemoteLogonIdSid = 20 WinLogonIdsSid = 21 WinLocalSystemSid = 22 WinLocalServiceSid = 23 WinNetworkServiceSid = 24 WinBuiltinDomainSid = 25 WinBuiltinAdministratorsSid = 26 WinBuiltinUsersSid = 27 WinBuiltinGuestsSid = 28 WinBuiltinPowerUsersSid = 29 WinBuiltinAccountOperatorsSid = 30 WinBuiltinSystemOperatorsSid = 31 WinBuiltinPrintOperatorsSid = 32 WinBuiltinBackupOperatorsSid = 33 WinBuiltinReplicatorSid = 34 WinBuiltinPreWindows2000CompatibleAccessSid = 35 WinBuiltinRemoteDesktopUsersSid = 36 WinBuiltinNetworkConfigurationOperatorsSid = 37 WinAccountAdministratorSid = 38 WinAccountGuestSid = 39 WinAccountKrbtgtSid = 40 WinAccountDomainAdminsSid = 41 WinAccountDomainUsersSid = 42 WinAccountDomainGuestsSid = 43 WinAccountComputersSid = 44 WinAccountControllersSid = 45 WinAccountCertAdminsSid = 46 WinAccountSchemaAdminsSid = 47 WinAccountEnterpriseAdminsSid = 48 WinAccountPolicyAdminsSid = 49 WinAccountRasAndIasServersSid = 50 WinNTLMAuthenticationSid = 51 WinDigestAuthenticationSid = 52 WinSChannelAuthenticationSid = 53 WinThisOrganizationSid = 54 WinOtherOrganizationSid = 55 WinBuiltinIncomingForestTrustBuildersSid = 56 WinBuiltinPerfMonitoringUsersSid = 57 WinBuiltinPerfLoggingUsersSid = 58 WinBuiltinAuthorizationAccessSid = 59 WinBuiltinTerminalServerLicenseServersSid = 60 WinBuiltinDCOMUsersSid = 61 WinBuiltinIUsersSid = 62 WinIUserSid = 63 WinBuiltinCryptoOperatorsSid = 64 WinUntrustedLabelSid = 65 WinLowLabelSid = 66 WinMediumLabelSid = 67 WinHighLabelSid = 68 WinSystemLabelSid = 69 WinWriteRestrictedCodeSid = 70 WinCreatorOwnerRightsSid = 71 WinCacheablePrincipalsGroupSid = 72 WinNonCacheablePrincipalsGroupSid = 73 WinEnterpriseReadonlyControllersSid = 74 WinAccountReadonlyControllersSid = 75 WinBuiltinEventLogReadersGroup = 76 WinNewEnterpriseReadonlyControllersSid = 77 WinBuiltinCertSvcDComAccessGroup = 78 WinMediumPlusLabelSid = 79 WinLocalLogonSid = 80 WinConsoleLogonSid = 81 WinThisOrganizationCertificateSid = 82 WinApplicationPackageAuthoritySid = 83 WinBuiltinAnyPackageSid = 84 WinCapabilityInternetClientSid = 85 WinCapabilityInternetClientServerSid = 86 WinCapabilityPrivateNetworkClientServerSid = 87 WinCapabilityPicturesLibrarySid = 88 WinCapabilityVideosLibrarySid = 89 WinCapabilityMusicLibrarySid = 90 WinCapabilityDocumentsLibrarySid = 91 WinCapabilitySharedUserCertificatesSid = 92 WinCapabilityEnterpriseAuthenticationSid = 93 WinCapabilityRemovableStorageSid = 94 WinBuiltinRDSRemoteAccessServersSid = 95 WinBuiltinRDSEndpointServersSid = 96 WinBuiltinRDSManagementServersSid = 97 WinUserModeDriversSid = 98 WinBuiltinHyperVAdminsSid = 99 WinAccountCloneableControllersSid = 100 WinBuiltinAccessControlAssistanceOperatorsSid = 101 WinBuiltinRemoteManagementUsersSid = 102 WinAuthenticationAuthorityAssertedSid = 103 WinAuthenticationServiceAssertedSid = 104 WinLocalAccountSid = 105 WinLocalAccountAndAdministratorSid = 106 WinAccountProtectedUsersSid = 107 WinCapabilityAppointmentsSid = 108 WinCapabilityContactsSid = 109 WinAccountDefaultSystemManagedSid = 110 WinBuiltinDefaultSystemManagedGroupSid = 111 WinBuiltinStorageReplicaAdminsSid = 112 WinAccountKeyAdminsSid = 113 WinAccountEnterpriseKeyAdminsSid = 114 WinAuthenticationKeyTrustSid = 115 WinAuthenticationKeyPropertyMFASid = 116 WinAuthenticationKeyPropertyAttestationSid = 117 WinAuthenticationFreshKeyAuthSid = 118 WinBuiltinDeviceOwnersSid = 119 ) // Creates a SID for a well-known predefined alias, generally using the constants of the form // Win*Sid, for the local machine. func CreateWellKnownSid(sidType WELL_KNOWN_SID_TYPE) (*SID, error) { return CreateWellKnownDomainSid(sidType, nil) } // Creates a SID for a well-known predefined alias, generally using the constants of the form // Win*Sid, for the domain specified by the domainSid parameter. func CreateWellKnownDomainSid(sidType WELL_KNOWN_SID_TYPE, domainSid *SID) (*SID, error) { n := uint32(50) for { b := make([]byte, n) sid := (*SID)(unsafe.Pointer(&b[0])) err := createWellKnownSid(sidType, domainSid, sid, &n) if err == nil { return sid, nil } if err != ERROR_INSUFFICIENT_BUFFER { return nil, err } if n <= uint32(len(b)) { return nil, err } } } const ( // do not reorder TOKEN_ASSIGN_PRIMARY = 1 << iota TOKEN_DUPLICATE TOKEN_IMPERSONATE TOKEN_QUERY TOKEN_QUERY_SOURCE TOKEN_ADJUST_PRIVILEGES TOKEN_ADJUST_GROUPS TOKEN_ADJUST_DEFAULT TOKEN_ADJUST_SESSIONID TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY TOKEN_WRITE = STANDARD_RIGHTS_WRITE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT TOKEN_EXECUTE = STANDARD_RIGHTS_EXECUTE ) const ( // do not reorder TokenUser = 1 + iota TokenGroups TokenPrivileges TokenOwner TokenPrimaryGroup TokenDefaultDacl TokenSource TokenType TokenImpersonationLevel TokenStatistics TokenRestrictedSids TokenSessionId TokenGroupsAndPrivileges TokenSessionReference TokenSandBoxInert TokenAuditPolicy TokenOrigin TokenElevationType TokenLinkedToken TokenElevation TokenHasRestrictions TokenAccessInformation TokenVirtualizationAllowed TokenVirtualizationEnabled TokenIntegrityLevel TokenUIAccess TokenMandatoryPolicy TokenLogonSid MaxTokenInfoClass ) // Group attributes inside of Tokengroups.Groups[i].Attributes const ( SE_GROUP_MANDATORY = 0x00000001 SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002 SE_GROUP_ENABLED = 0x00000004 SE_GROUP_OWNER = 0x00000008 SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010 SE_GROUP_INTEGRITY = 0x00000020 SE_GROUP_INTEGRITY_ENABLED = 0x00000040 SE_GROUP_LOGON_ID = 0xC0000000 SE_GROUP_RESOURCE = 0x20000000 SE_GROUP_VALID_ATTRIBUTES = SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED | SE_GROUP_OWNER | SE_GROUP_USE_FOR_DENY_ONLY | SE_GROUP_LOGON_ID | SE_GROUP_RESOURCE | SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED ) // Privilege attributes const ( SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001 SE_PRIVILEGE_ENABLED = 0x00000002 SE_PRIVILEGE_REMOVED = 0x00000004 SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000 SE_PRIVILEGE_VALID_ATTRIBUTES = SE_PRIVILEGE_ENABLED_BY_DEFAULT | SE_PRIVILEGE_ENABLED | SE_PRIVILEGE_REMOVED | SE_PRIVILEGE_USED_FOR_ACCESS ) // Token types const ( TokenPrimary = 1 TokenImpersonation = 2 ) // Impersonation levels const ( SecurityAnonymous = 0 SecurityIdentification = 1 SecurityImpersonation = 2 SecurityDelegation = 3 ) type LUID struct { LowPart uint32 HighPart int32 } type LUIDAndAttributes struct { Luid LUID Attributes uint32 } type SIDAndAttributes struct { Sid *SID Attributes uint32 } type Tokenuser struct { User SIDAndAttributes } type Tokenprimarygroup struct { PrimaryGroup *SID } type Tokengroups struct { GroupCount uint32 Groups [1]SIDAndAttributes // Use AllGroups() for iterating. } // AllGroups returns a slice that can be used to iterate over the groups in g. func (g *Tokengroups) AllGroups() []SIDAndAttributes { return (*[(1 << 28) - 1]SIDAndAttributes)(unsafe.Pointer(&g.Groups[0]))[:g.GroupCount:g.GroupCount] } type Tokenprivileges struct { PrivilegeCount uint32 Privileges [1]LUIDAndAttributes // Use AllPrivileges() for iterating. } // AllPrivileges returns a slice that can be used to iterate over the privileges in p. func (p *Tokenprivileges) AllPrivileges() []LUIDAndAttributes { return (*[(1 << 27) - 1]LUIDAndAttributes)(unsafe.Pointer(&p.Privileges[0]))[:p.PrivilegeCount:p.PrivilegeCount] } type Tokenmandatorylabel struct { Label SIDAndAttributes } func (tml *Tokenmandatorylabel) Size() uint32 { return uint32(unsafe.Sizeof(Tokenmandatorylabel{})) + GetLengthSid(tml.Label.Sid) } // Authorization Functions //sys checkTokenMembership(tokenHandle Token, sidToCheck *SID, isMember *int32) (err error) = advapi32.CheckTokenMembership //sys OpenProcessToken(process Handle, access uint32, token *Token) (err error) = advapi32.OpenProcessToken //sys OpenThreadToken(thread Handle, access uint32, openAsSelf bool, token *Token) (err error) = advapi32.OpenThreadToken //sys ImpersonateSelf(impersonationlevel uint32) (err error) = advapi32.ImpersonateSelf //sys RevertToSelf() (err error) = advapi32.RevertToSelf //sys SetThreadToken(thread *Handle, token Token) (err error) = advapi32.SetThreadToken //sys LookupPrivilegeValue(systemname *uint16, name *uint16, luid *LUID) (err error) = advapi32.LookupPrivilegeValueW //sys AdjustTokenPrivileges(token Token, disableAllPrivileges bool, newstate *Tokenprivileges, buflen uint32, prevstate *Tokenprivileges, returnlen *uint32) (err error) = advapi32.AdjustTokenPrivileges //sys AdjustTokenGroups(token Token, resetToDefault bool, newstate *Tokengroups, buflen uint32, prevstate *Tokengroups, returnlen *uint32) (err error) = advapi32.AdjustTokenGroups //sys GetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint32, returnedLen *uint32) (err error) = advapi32.GetTokenInformation //sys SetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint32) (err error) = advapi32.SetTokenInformation //sys DuplicateTokenEx(existingToken Token, desiredAccess uint32, tokenAttributes *SecurityAttributes, impersonationLevel uint32, tokenType uint32, newToken *Token) (err error) = advapi32.DuplicateTokenEx //sys GetUserProfileDirectory(t Token, dir *uint16, dirLen *uint32) (err error) = userenv.GetUserProfileDirectoryW //sys getSystemDirectory(dir *uint16, dirLen uint32) (len uint32, err error) = kernel32.GetSystemDirectoryW //sys getWindowsDirectory(dir *uint16, dirLen uint32) (len uint32, err error) = kernel32.GetWindowsDirectoryW //sys getSystemWindowsDirectory(dir *uint16, dirLen uint32) (len uint32, err error) = kernel32.GetSystemWindowsDirectoryW // An access token contains the security information for a logon session. // The system creates an access token when a user logs on, and every // process executed on behalf of the user has a copy of the token. // The token identifies the user, the user's groups, and the user's // privileges. The system uses the token to control access to securable // objects and to control the ability of the user to perform various // system-related operations on the local computer. type Token Handle // OpenCurrentProcessToken opens an access token associated with current // process with TOKEN_QUERY access. It is a real token that needs to be closed. // // Deprecated: Explicitly call OpenProcessToken(CurrentProcess(), ...) // with the desired access instead, or use GetCurrentProcessToken for a // TOKEN_QUERY token. func OpenCurrentProcessToken() (Token, error) { var token Token err := OpenProcessToken(CurrentProcess(), TOKEN_QUERY, &token) return token, err } // GetCurrentProcessToken returns the access token associated with // the current process. It is a pseudo token that does not need // to be closed. func GetCurrentProcessToken() Token { return Token(^uintptr(4 - 1)) } // GetCurrentThreadToken return the access token associated with // the current thread. It is a pseudo token that does not need // to be closed. func GetCurrentThreadToken() Token { return Token(^uintptr(5 - 1)) } // GetCurrentThreadEffectiveToken returns the effective access token // associated with the current thread. It is a pseudo token that does // not need to be closed. func GetCurrentThreadEffectiveToken() Token { return Token(^uintptr(6 - 1)) } // Close releases access to access token. func (t Token) Close() error { return CloseHandle(Handle(t)) } // getInfo retrieves a specified type of information about an access token. func (t Token) getInfo(class uint32, initSize int) (unsafe.Pointer, error) { n := uint32(initSize) for { b := make([]byte, n) e := GetTokenInformation(t, class, &b[0], uint32(len(b)), &n) if e == nil { return unsafe.Pointer(&b[0]), nil } if e != ERROR_INSUFFICIENT_BUFFER { return nil, e } if n <= uint32(len(b)) { return nil, e } } } // GetTokenUser retrieves access token t user account information. func (t Token) GetTokenUser() (*Tokenuser, error) { i, e := t.getInfo(TokenUser, 50) if e != nil { return nil, e } return (*Tokenuser)(i), nil } // GetTokenGroups retrieves group accounts associated with access token t. func (t Token) GetTokenGroups() (*Tokengroups, error) { i, e := t.getInfo(TokenGroups, 50) if e != nil { return nil, e } return (*Tokengroups)(i), nil } // GetTokenPrimaryGroup retrieves access token t primary group information. // A pointer to a SID structure representing a group that will become // the primary group of any objects created by a process using this access token. func (t Token) GetTokenPrimaryGroup() (*Tokenprimarygroup, error) { i, e := t.getInfo(TokenPrimaryGroup, 50) if e != nil { return nil, e } return (*Tokenprimarygroup)(i), nil } // GetUserProfileDirectory retrieves path to the // root directory of the access token t user's profile. func (t Token) GetUserProfileDirectory() (string, error) { n := uint32(100) for { b := make([]uint16, n) e := GetUserProfileDirectory(t, &b[0], &n) if e == nil { return UTF16ToString(b), nil } if e != ERROR_INSUFFICIENT_BUFFER { return "", e } if n <= uint32(len(b)) { return "", e } } } // IsElevated returns whether the current token is elevated from a UAC perspective. func (token Token) IsElevated() bool { var isElevated uint32 var outLen uint32 err := GetTokenInformation(token, TokenElevation, (*byte)(unsafe.Pointer(&isElevated)), uint32(unsafe.Sizeof(isElevated)), &outLen) if err != nil { return false } return outLen == uint32(unsafe.Sizeof(isElevated)) && isElevated != 0 } // GetLinkedToken returns the linked token, which may be an elevated UAC token. func (token Token) GetLinkedToken() (Token, error) { var linkedToken Token var outLen uint32 err := GetTokenInformation(token, TokenLinkedToken, (*byte)(unsafe.Pointer(&linkedToken)), uint32(unsafe.Sizeof(linkedToken)), &outLen) if err != nil { return Token(0), err } return linkedToken, nil } // GetSystemDirectory retrieves the path to current location of the system // directory, which is typically, though not always, `C:\Windows\System32`. func GetSystemDirectory() (string, error) { n := uint32(MAX_PATH) for { b := make([]uint16, n) l, e := getSystemDirectory(&b[0], n) if e != nil { return "", e } if l <= n { return UTF16ToString(b[:l]), nil } n = l } } // GetWindowsDirectory retrieves the path to current location of the Windows // directory, which is typically, though not always, `C:\Windows`. This may // be a private user directory in the case that the application is running // under a terminal server. func GetWindowsDirectory() (string, error) { n := uint32(MAX_PATH) for { b := make([]uint16, n) l, e := getWindowsDirectory(&b[0], n) if e != nil { return "", e } if l <= n { return UTF16ToString(b[:l]), nil } n = l } } // GetSystemWindowsDirectory retrieves the path to current location of the // Windows directory, which is typically, though not always, `C:\Windows`. func GetSystemWindowsDirectory() (string, error) { n := uint32(MAX_PATH) for { b := make([]uint16, n) l, e := getSystemWindowsDirectory(&b[0], n) if e != nil { return "", e } if l <= n { return UTF16ToString(b[:l]), nil } n = l } } // IsMember reports whether the access token t is a member of the provided SID. func (t Token) IsMember(sid *SID) (bool, error) { var b int32 if e := checkTokenMembership(t, sid, &b); e != nil { return false, e } return b != 0, nil } const ( WTS_CONSOLE_CONNECT = 0x1 WTS_CONSOLE_DISCONNECT = 0x2 WTS_REMOTE_CONNECT = 0x3 WTS_REMOTE_DISCONNECT = 0x4 WTS_SESSION_LOGON = 0x5 WTS_SESSION_LOGOFF = 0x6 WTS_SESSION_LOCK = 0x7 WTS_SESSION_UNLOCK = 0x8 WTS_SESSION_REMOTE_CONTROL = 0x9 WTS_SESSION_CREATE = 0xa WTS_SESSION_TERMINATE = 0xb ) const ( WTSActive = 0 WTSConnected = 1 WTSConnectQuery = 2 WTSShadow = 3 WTSDisconnected = 4 WTSIdle = 5 WTSListen = 6 WTSReset = 7 WTSDown = 8 WTSInit = 9 ) type WTSSESSION_NOTIFICATION struct { Size uint32 SessionID uint32 } type WTS_SESSION_INFO struct { SessionID uint32 WindowStationName *uint16 State uint32 } //sys WTSQueryUserToken(session uint32, token *Token) (err error) = wtsapi32.WTSQueryUserToken //sys WTSEnumerateSessions(handle Handle, reserved uint32, version uint32, sessions **WTS_SESSION_INFO, count *uint32) (err error) = wtsapi32.WTSEnumerateSessionsW //sys WTSFreeMemory(ptr uintptr) = wtsapi32.WTSFreeMemory type ACL struct { aclRevision byte sbz1 byte aclSize uint16 aceCount uint16 sbz2 uint16 } type SECURITY_DESCRIPTOR struct { revision byte sbz1 byte control SECURITY_DESCRIPTOR_CONTROL owner *SID group *SID sacl *ACL dacl *ACL } type SecurityAttributes struct { Length uint32 SecurityDescriptor *SECURITY_DESCRIPTOR InheritHandle uint32 } type SE_OBJECT_TYPE uint32 // Constants for type SE_OBJECT_TYPE const ( SE_UNKNOWN_OBJECT_TYPE = 0 SE_FILE_OBJECT = 1 SE_SERVICE = 2 SE_PRINTER = 3 SE_REGISTRY_KEY = 4 SE_LMSHARE = 5 SE_KERNEL_OBJECT = 6 SE_WINDOW_OBJECT = 7 SE_DS_OBJECT = 8 SE_DS_OBJECT_ALL = 9 SE_PROVIDER_DEFINED_OBJECT = 10 SE_WMIGUID_OBJECT = 11 SE_REGISTRY_WOW64_32KEY = 12 SE_REGISTRY_WOW64_64KEY = 13 ) type SECURITY_INFORMATION uint32 // Constants for type SECURITY_INFORMATION const ( OWNER_SECURITY_INFORMATION = 0x00000001 GROUP_SECURITY_INFORMATION = 0x00000002 DACL_SECURITY_INFORMATION = 0x00000004 SACL_SECURITY_INFORMATION = 0x00000008 LABEL_SECURITY_INFORMATION = 0x00000010 ATTRIBUTE_SECURITY_INFORMATION = 0x00000020 SCOPE_SECURITY_INFORMATION = 0x00000040 BACKUP_SECURITY_INFORMATION = 0x00010000 PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000 PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000 UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000 UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000 ) type SECURITY_DESCRIPTOR_CONTROL uint16 // Constants for type SECURITY_DESCRIPTOR_CONTROL const ( SE_OWNER_DEFAULTED = 0x0001 SE_GROUP_DEFAULTED = 0x0002 SE_DACL_PRESENT = 0x0004 SE_DACL_DEFAULTED = 0x0008 SE_SACL_PRESENT = 0x0010 SE_SACL_DEFAULTED = 0x0020 SE_DACL_AUTO_INHERIT_REQ = 0x0100 SE_SACL_AUTO_INHERIT_REQ = 0x0200 SE_DACL_AUTO_INHERITED = 0x0400 SE_SACL_AUTO_INHERITED = 0x0800 SE_DACL_PROTECTED = 0x1000 SE_SACL_PROTECTED = 0x2000 SE_RM_CONTROL_VALID = 0x4000 SE_SELF_RELATIVE = 0x8000 ) type ACCESS_MASK uint32 // Constants for type ACCESS_MASK const ( DELETE = 0x00010000 READ_CONTROL = 0x00020000 WRITE_DAC = 0x00040000 WRITE_OWNER = 0x00080000 SYNCHRONIZE = 0x00100000 STANDARD_RIGHTS_REQUIRED = 0x000F0000 STANDARD_RIGHTS_READ = READ_CONTROL STANDARD_RIGHTS_WRITE = READ_CONTROL STANDARD_RIGHTS_EXECUTE = READ_CONTROL STANDARD_RIGHTS_ALL = 0x001F0000 SPECIFIC_RIGHTS_ALL = 0x0000FFFF ACCESS_SYSTEM_SECURITY = 0x01000000 MAXIMUM_ALLOWED = 0x02000000 GENERIC_READ = 0x80000000 GENERIC_WRITE = 0x40000000 GENERIC_EXECUTE = 0x20000000 GENERIC_ALL = 0x10000000 ) type ACCESS_MODE uint32 // Constants for type ACCESS_MODE const ( NOT_USED_ACCESS = 0 GRANT_ACCESS = 1 SET_ACCESS = 2 DENY_ACCESS = 3 REVOKE_ACCESS = 4 SET_AUDIT_SUCCESS = 5 SET_AUDIT_FAILURE = 6 ) // Constants for AceFlags and Inheritance fields const ( NO_INHERITANCE = 0x0 SUB_OBJECTS_ONLY_INHERIT = 0x1 SUB_CONTAINERS_ONLY_INHERIT = 0x2 SUB_CONTAINERS_AND_OBJECTS_INHERIT = 0x3 INHERIT_NO_PROPAGATE = 0x4 INHERIT_ONLY = 0x8 INHERITED_ACCESS_ENTRY = 0x10 INHERITED_PARENT = 0x10000000 INHERITED_GRANDPARENT = 0x20000000 OBJECT_INHERIT_ACE = 0x1 CONTAINER_INHERIT_ACE = 0x2 NO_PROPAGATE_INHERIT_ACE = 0x4 INHERIT_ONLY_ACE = 0x8 INHERITED_ACE = 0x10 VALID_INHERIT_FLAGS = 0x1F ) type MULTIPLE_TRUSTEE_OPERATION uint32 // Constants for MULTIPLE_TRUSTEE_OPERATION const ( NO_MULTIPLE_TRUSTEE = 0 TRUSTEE_IS_IMPERSONATE = 1 ) type TRUSTEE_FORM uint32 // Constants for TRUSTEE_FORM const ( TRUSTEE_IS_SID = 0 TRUSTEE_IS_NAME = 1 TRUSTEE_BAD_FORM = 2 TRUSTEE_IS_OBJECTS_AND_SID = 3 TRUSTEE_IS_OBJECTS_AND_NAME = 4 ) type TRUSTEE_TYPE uint32 // Constants for TRUSTEE_TYPE const ( TRUSTEE_IS_UNKNOWN = 0 TRUSTEE_IS_USER = 1 TRUSTEE_IS_GROUP = 2 TRUSTEE_IS_DOMAIN = 3 TRUSTEE_IS_ALIAS = 4 TRUSTEE_IS_WELL_KNOWN_GROUP = 5 TRUSTEE_IS_DELETED = 6 TRUSTEE_IS_INVALID = 7 TRUSTEE_IS_COMPUTER = 8 ) // Constants for ObjectsPresent field const ( ACE_OBJECT_TYPE_PRESENT = 0x1 ACE_INHERITED_OBJECT_TYPE_PRESENT = 0x2 ) type EXPLICIT_ACCESS struct { AccessPermissions ACCESS_MASK AccessMode ACCESS_MODE Inheritance uint32 Trustee TRUSTEE } // This type is the union inside of TRUSTEE and must be created using one of the TrusteeValueFrom* functions. type TrusteeValue uintptr func TrusteeValueFromString(str string) TrusteeValue { return TrusteeValue(unsafe.Pointer(StringToUTF16Ptr(str))) } func TrusteeValueFromSID(sid *SID) TrusteeValue { return TrusteeValue(unsafe.Pointer(sid)) } func TrusteeValueFromObjectsAndSid(objectsAndSid *OBJECTS_AND_SID) TrusteeValue { return TrusteeValue(unsafe.Pointer(objectsAndSid)) } func TrusteeValueFromObjectsAndName(objectsAndName *OBJECTS_AND_NAME) TrusteeValue { return TrusteeValue(unsafe.Pointer(objectsAndName)) } type TRUSTEE struct { MultipleTrustee *TRUSTEE MultipleTrusteeOperation MULTIPLE_TRUSTEE_OPERATION TrusteeForm TRUSTEE_FORM TrusteeType TRUSTEE_TYPE TrusteeValue TrusteeValue } type OBJECTS_AND_SID struct { ObjectsPresent uint32 ObjectTypeGuid GUID InheritedObjectTypeGuid GUID Sid *SID } type OBJECTS_AND_NAME struct { ObjectsPresent uint32 ObjectType SE_OBJECT_TYPE ObjectTypeName *uint16 InheritedObjectTypeName *uint16 Name *uint16 } //sys getSecurityInfo(handle Handle, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner **SID, group **SID, dacl **ACL, sacl **ACL, sd **SECURITY_DESCRIPTOR) (ret error) = advapi32.GetSecurityInfo //sys SetSecurityInfo(handle Handle, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner *SID, group *SID, dacl *ACL, sacl *ACL) = advapi32.SetSecurityInfo //sys getNamedSecurityInfo(objectName string, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner **SID, group **SID, dacl **ACL, sacl **ACL, sd **SECURITY_DESCRIPTOR) (ret error) = advapi32.GetNamedSecurityInfoW //sys SetNamedSecurityInfo(objectName string, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner *SID, group *SID, dacl *ACL, sacl *ACL) (ret error) = advapi32.SetNamedSecurityInfoW //sys buildSecurityDescriptor(owner *TRUSTEE, group *TRUSTEE, countAccessEntries uint32, accessEntries *EXPLICIT_ACCESS, countAuditEntries uint32, auditEntries *EXPLICIT_ACCESS, oldSecurityDescriptor *SECURITY_DESCRIPTOR, sizeNewSecurityDescriptor *uint32, newSecurityDescriptor **SECURITY_DESCRIPTOR) (ret error) = advapi32.BuildSecurityDescriptorW //sys initializeSecurityDescriptor(absoluteSD *SECURITY_DESCRIPTOR, revision uint32) (err error) = advapi32.InitializeSecurityDescriptor //sys getSecurityDescriptorControl(sd *SECURITY_DESCRIPTOR, control *SECURITY_DESCRIPTOR_CONTROL, revision *uint32) (err error) = advapi32.GetSecurityDescriptorControl //sys getSecurityDescriptorDacl(sd *SECURITY_DESCRIPTOR, daclPresent *bool, dacl **ACL, daclDefaulted *bool) (err error) = advapi32.GetSecurityDescriptorDacl //sys getSecurityDescriptorSacl(sd *SECURITY_DESCRIPTOR, saclPresent *bool, sacl **ACL, saclDefaulted *bool) (err error) = advapi32.GetSecurityDescriptorSacl //sys getSecurityDescriptorOwner(sd *SECURITY_DESCRIPTOR, owner **SID, ownerDefaulted *bool) (err error) = advapi32.GetSecurityDescriptorOwner //sys getSecurityDescriptorGroup(sd *SECURITY_DESCRIPTOR, group **SID, groupDefaulted *bool) (err error) = advapi32.GetSecurityDescriptorGroup //sys getSecurityDescriptorLength(sd *SECURITY_DESCRIPTOR) (len uint32) = advapi32.GetSecurityDescriptorLength //sys getSecurityDescriptorRMControl(sd *SECURITY_DESCRIPTOR, rmControl *uint8) (ret error) [failretval!=0] = advapi32.GetSecurityDescriptorRMControl //sys isValidSecurityDescriptor(sd *SECURITY_DESCRIPTOR) (isValid bool) = advapi32.IsValidSecurityDescriptor //sys setSecurityDescriptorControl(sd *SECURITY_DESCRIPTOR, controlBitsOfInterest SECURITY_DESCRIPTOR_CONTROL, controlBitsToSet SECURITY_DESCRIPTOR_CONTROL) (err error) = advapi32.SetSecurityDescriptorControl //sys setSecurityDescriptorDacl(sd *SECURITY_DESCRIPTOR, daclPresent bool, dacl *ACL, daclDefaulted bool) (err error) = advapi32.SetSecurityDescriptorDacl //sys setSecurityDescriptorSacl(sd *SECURITY_DESCRIPTOR, saclPresent bool, sacl *ACL, saclDefaulted bool) (err error) = advapi32.SetSecurityDescriptorSacl //sys setSecurityDescriptorOwner(sd *SECURITY_DESCRIPTOR, owner *SID, ownerDefaulted bool) (err error) = advapi32.SetSecurityDescriptorOwner //sys setSecurityDescriptorGroup(sd *SECURITY_DESCRIPTOR, group *SID, groupDefaulted bool) (err error) = advapi32.SetSecurityDescriptorGroup //sys setSecurityDescriptorRMControl(sd *SECURITY_DESCRIPTOR, rmControl *uint8) = advapi32.SetSecurityDescriptorRMControl //sys convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd **SECURITY_DESCRIPTOR, size *uint32) (err error) = advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW //sys convertSecurityDescriptorToStringSecurityDescriptor(sd *SECURITY_DESCRIPTOR, revision uint32, securityInformation SECURITY_INFORMATION, str **uint16, strLen *uint32) (err error) = advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW //sys makeAbsoluteSD(selfRelativeSD *SECURITY_DESCRIPTOR, absoluteSD *SECURITY_DESCRIPTOR, absoluteSDSize *uint32, dacl *ACL, daclSize *uint32, sacl *ACL, saclSize *uint32, owner *SID, ownerSize *uint32, group *SID, groupSize *uint32) (err error) = advapi32.MakeAbsoluteSD //sys makeSelfRelativeSD(absoluteSD *SECURITY_DESCRIPTOR, selfRelativeSD *SECURITY_DESCRIPTOR, selfRelativeSDSize *uint32) (err error) = advapi32.MakeSelfRelativeSD //sys setEntriesInAcl(countExplicitEntries uint32, explicitEntries *EXPLICIT_ACCESS, oldACL *ACL, newACL **ACL) (ret error) = advapi32.SetEntriesInAclW // Control returns the security descriptor control bits. func (sd *SECURITY_DESCRIPTOR) Control() (control SECURITY_DESCRIPTOR_CONTROL, revision uint32, err error) { err = getSecurityDescriptorControl(sd, &control, &revision) return } // SetControl sets the security descriptor control bits. func (sd *SECURITY_DESCRIPTOR) SetControl(controlBitsOfInterest SECURITY_DESCRIPTOR_CONTROL, controlBitsToSet SECURITY_DESCRIPTOR_CONTROL) error { return setSecurityDescriptorControl(sd, controlBitsOfInterest, controlBitsToSet) } // RMControl returns the security descriptor resource manager control bits. func (sd *SECURITY_DESCRIPTOR) RMControl() (control uint8, err error) { err = getSecurityDescriptorRMControl(sd, &control) return } // SetRMControl sets the security descriptor resource manager control bits. func (sd *SECURITY_DESCRIPTOR) SetRMControl(rmControl uint8) { setSecurityDescriptorRMControl(sd, &rmControl) } // DACL returns the security descriptor DACL and whether it was defaulted. The dacl return value may be nil // if a DACL exists but is an "empty DACL", meaning fully permissive. If the DACL does not exist, err returns // ERROR_OBJECT_NOT_FOUND. func (sd *SECURITY_DESCRIPTOR) DACL() (dacl *ACL, defaulted bool, err error) { var present bool err = getSecurityDescriptorDacl(sd, &present, &dacl, &defaulted) if !present { err = ERROR_OBJECT_NOT_FOUND } return } // SetDACL sets the absolute security descriptor DACL. func (absoluteSD *SECURITY_DESCRIPTOR) SetDACL(dacl *ACL, present, defaulted bool) error { return setSecurityDescriptorDacl(absoluteSD, present, dacl, defaulted) } // SACL returns the security descriptor SACL and whether it was defaulted. The sacl return value may be nil // if a SACL exists but is an "empty SACL", meaning fully permissive. If the SACL does not exist, err returns // ERROR_OBJECT_NOT_FOUND. func (sd *SECURITY_DESCRIPTOR) SACL() (sacl *ACL, defaulted bool, err error) { var present bool err = getSecurityDescriptorSacl(sd, &present, &sacl, &defaulted) if !present { err = ERROR_OBJECT_NOT_FOUND } return } // SetSACL sets the absolute security descriptor SACL. func (absoluteSD *SECURITY_DESCRIPTOR) SetSACL(sacl *ACL, present, defaulted bool) error { return setSecurityDescriptorSacl(absoluteSD, present, sacl, defaulted) } // Owner returns the security descriptor owner and whether it was defaulted. func (sd *SECURITY_DESCRIPTOR) Owner() (owner *SID, defaulted bool, err error) { err = getSecurityDescriptorOwner(sd, &owner, &defaulted) return } // SetOwner sets the absolute security descriptor owner. func (absoluteSD *SECURITY_DESCRIPTOR) SetOwner(owner *SID, defaulted bool) error { return setSecurityDescriptorOwner(absoluteSD, owner, defaulted) } // Group returns the security descriptor group and whether it was defaulted. func (sd *SECURITY_DESCRIPTOR) Group() (group *SID, defaulted bool, err error) { err = getSecurityDescriptorGroup(sd, &group, &defaulted) return } // SetGroup sets the absolute security descriptor owner. func (absoluteSD *SECURITY_DESCRIPTOR) SetGroup(group *SID, defaulted bool) error { return setSecurityDescriptorGroup(absoluteSD, group, defaulted) } // Length returns the length of the security descriptor. func (sd *SECURITY_DESCRIPTOR) Length() uint32 { return getSecurityDescriptorLength(sd) } // IsValid returns whether the security descriptor is valid. func (sd *SECURITY_DESCRIPTOR) IsValid() bool { return isValidSecurityDescriptor(sd) } // String returns the SDDL form of the security descriptor, with a function signature that can be // used with %v formatting directives. func (sd *SECURITY_DESCRIPTOR) String() string { var sddl *uint16 err := convertSecurityDescriptorToStringSecurityDescriptor(sd, 1, 0xff, &sddl, nil) if err != nil { return "" } defer LocalFree(Handle(unsafe.Pointer(sddl))) return UTF16ToString((*[(1 << 30) - 1]uint16)(unsafe.Pointer(sddl))[:]) } // ToAbsolute converts a self-relative security descriptor into an absolute one. func (selfRelativeSD *SECURITY_DESCRIPTOR) ToAbsolute() (absoluteSD *SECURITY_DESCRIPTOR, err error) { control, _, err := selfRelativeSD.Control() if err != nil { return } if control&SE_SELF_RELATIVE == 0 { err = ERROR_INVALID_PARAMETER return } var absoluteSDSize, daclSize, saclSize, ownerSize, groupSize uint32 err = makeAbsoluteSD(selfRelativeSD, nil, &absoluteSDSize, nil, &daclSize, nil, &saclSize, nil, &ownerSize, nil, &groupSize) switch err { case ERROR_INSUFFICIENT_BUFFER: case nil: // makeAbsoluteSD is expected to fail, but it succeeds. return nil, ERROR_INTERNAL_ERROR default: return nil, err } if absoluteSDSize > 0 { absoluteSD = (*SECURITY_DESCRIPTOR)(unsafe.Pointer(&make([]byte, absoluteSDSize)[0])) } var ( dacl *ACL sacl *ACL owner *SID group *SID ) if daclSize > 0 { dacl = (*ACL)(unsafe.Pointer(&make([]byte, daclSize)[0])) } if saclSize > 0 { sacl = (*ACL)(unsafe.Pointer(&make([]byte, saclSize)[0])) } if ownerSize > 0 { owner = (*SID)(unsafe.Pointer(&make([]byte, ownerSize)[0])) } if groupSize > 0 { group = (*SID)(unsafe.Pointer(&make([]byte, groupSize)[0])) } err = makeAbsoluteSD(selfRelativeSD, absoluteSD, &absoluteSDSize, dacl, &daclSize, sacl, &saclSize, owner, &ownerSize, group, &groupSize) return } // ToSelfRelative converts an absolute security descriptor into a self-relative one. func (absoluteSD *SECURITY_DESCRIPTOR) ToSelfRelative() (selfRelativeSD *SECURITY_DESCRIPTOR, err error) { control, _, err := absoluteSD.Control() if err != nil { return } if control&SE_SELF_RELATIVE != 0 { err = ERROR_INVALID_PARAMETER return } var selfRelativeSDSize uint32 err = makeSelfRelativeSD(absoluteSD, nil, &selfRelativeSDSize) switch err { case ERROR_INSUFFICIENT_BUFFER: case nil: // makeSelfRelativeSD is expected to fail, but it succeeds. return nil, ERROR_INTERNAL_ERROR default: return nil, err } if selfRelativeSDSize > 0 { selfRelativeSD = (*SECURITY_DESCRIPTOR)(unsafe.Pointer(&make([]byte, selfRelativeSDSize)[0])) } err = makeSelfRelativeSD(absoluteSD, selfRelativeSD, &selfRelativeSDSize) return } func (selfRelativeSD *SECURITY_DESCRIPTOR) copySelfRelativeSecurityDescriptor() *SECURITY_DESCRIPTOR { sdBytes := make([]byte, selfRelativeSD.Length()) copy(sdBytes, (*[(1 << 31) - 1]byte)(unsafe.Pointer(selfRelativeSD))[:len(sdBytes)]) return (*SECURITY_DESCRIPTOR)(unsafe.Pointer(&sdBytes[0])) } // SecurityDescriptorFromString converts an SDDL string describing a security descriptor into a // self-relative security descriptor object allocated on the Go heap. func SecurityDescriptorFromString(sddl string) (sd *SECURITY_DESCRIPTOR, err error) { var winHeapSD *SECURITY_DESCRIPTOR err = convertStringSecurityDescriptorToSecurityDescriptor(sddl, 1, &winHeapSD, nil) if err != nil { return } defer LocalFree(Handle(unsafe.Pointer(winHeapSD))) return winHeapSD.copySelfRelativeSecurityDescriptor(), nil } // GetSecurityInfo queries the security information for a given handle and returns the self-relative security // descriptor result on the Go heap. func GetSecurityInfo(handle Handle, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION) (sd *SECURITY_DESCRIPTOR, err error) { var winHeapSD *SECURITY_DESCRIPTOR err = getSecurityInfo(handle, objectType, securityInformation, nil, nil, nil, nil, &winHeapSD) if err != nil { return } defer LocalFree(Handle(unsafe.Pointer(winHeapSD))) return winHeapSD.copySelfRelativeSecurityDescriptor(), nil } // GetNamedSecurityInfo queries the security information for a given named object and returns the self-relative security // descriptor result on the Go heap. func GetNamedSecurityInfo(objectName string, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION) (sd *SECURITY_DESCRIPTOR, err error) { var winHeapSD *SECURITY_DESCRIPTOR err = getNamedSecurityInfo(objectName, objectType, securityInformation, nil, nil, nil, nil, &winHeapSD) if err != nil { return } defer LocalFree(Handle(unsafe.Pointer(winHeapSD))) return winHeapSD.copySelfRelativeSecurityDescriptor(), nil } // BuildSecurityDescriptor makes a new security descriptor using the input trustees, explicit access lists, and // prior security descriptor to be merged, any of which can be nil, returning the self-relative security descriptor // result on the Go heap. func BuildSecurityDescriptor(owner *TRUSTEE, group *TRUSTEE, accessEntries []EXPLICIT_ACCESS, auditEntries []EXPLICIT_ACCESS, mergedSecurityDescriptor *SECURITY_DESCRIPTOR) (sd *SECURITY_DESCRIPTOR, err error) { var winHeapSD *SECURITY_DESCRIPTOR var winHeapSDSize uint32 var firstAccessEntry *EXPLICIT_ACCESS if len(accessEntries) > 0 { firstAccessEntry = &accessEntries[0] } var firstAuditEntry *EXPLICIT_ACCESS if len(auditEntries) > 0 { firstAuditEntry = &auditEntries[0] } err = buildSecurityDescriptor(owner, group, uint32(len(accessEntries)), firstAccessEntry, uint32(len(auditEntries)), firstAuditEntry, mergedSecurityDescriptor, &winHeapSDSize, &winHeapSD) if err != nil { return } defer LocalFree(Handle(unsafe.Pointer(winHeapSD))) return winHeapSD.copySelfRelativeSecurityDescriptor(), nil } // NewSecurityDescriptor creates and initializes a new absolute security descriptor. func NewSecurityDescriptor() (absoluteSD *SECURITY_DESCRIPTOR, err error) { absoluteSD = &SECURITY_DESCRIPTOR{} err = initializeSecurityDescriptor(absoluteSD, 1) return } // ACLFromEntries returns a new ACL on the Go heap containing a list of explicit entries as well as those of another ACL. // Both explicitEntries and mergedACL are optional and can be nil. func ACLFromEntries(explicitEntries []EXPLICIT_ACCESS, mergedACL *ACL) (acl *ACL, err error) { var firstExplicitEntry *EXPLICIT_ACCESS if len(explicitEntries) > 0 { firstExplicitEntry = &explicitEntries[0] } var winHeapACL *ACL err = setEntriesInAcl(uint32(len(explicitEntries)), firstExplicitEntry, mergedACL, &winHeapACL) if err != nil { return } defer LocalFree(Handle(unsafe.Pointer(winHeapACL))) aclBytes := make([]byte, winHeapACL.aclSize) copy(aclBytes, (*[(1 << 31) - 1]byte)(unsafe.Pointer(winHeapACL))[:len(aclBytes)]) return (*ACL)(unsafe.Pointer(&aclBytes[0])), nil }
{ "pile_set_name": "Github" }
from __future__ import absolute_import from __future__ import print_function import numpy as np from mimic3models import common_utils import threading import random import os class BatchGen(object): def __init__(self, reader, discretizer, normalizer, batch_size, small_part, target_repl, shuffle, return_names=False): self.batch_size = batch_size self.target_repl = target_repl self.shuffle = shuffle self.return_names = return_names self._load_data(reader, discretizer, normalizer, small_part) self.steps = (len(self.data[0]) + batch_size - 1) // batch_size self.lock = threading.Lock() self.generator = self._generator() def _load_data(self, reader, discretizer, normalizer, small_part=False): N = reader.get_number_of_examples() if small_part: N = 1000 ret = common_utils.read_chunk(reader, N) data = ret["X"] ts = ret["t"] ys = ret["y"] names = ret["name"] data = [discretizer.transform(X, end=t)[0] for (X, t) in zip(data, ts)] if (normalizer is not None): data = [normalizer.transform(X) for X in data] ys = np.array(ys, dtype=np.int32) self.data = (data, ys) self.ts = ts self.names = names def _generator(self): B = self.batch_size while True: if self.shuffle: N = len(self.data[1]) order = list(range(N)) random.shuffle(order) tmp_data = [[None] * N, [None] * N] tmp_names = [None] * N tmp_ts = [None] * N for i in range(N): tmp_data[0][i] = self.data[0][order[i]] tmp_data[1][i] = self.data[1][order[i]] tmp_names[i] = self.names[order[i]] tmp_ts[i] = self.ts[order[i]] self.data = tmp_data self.names = tmp_names self.ts = tmp_ts else: # sort entirely X = self.data[0] y = self.data[1] (X, y, self.names, self.ts) = common_utils.sort_and_shuffle([X, y, self.names, self.ts], B) self.data = [X, y] self.data[1] = np.array(self.data[1]) # this is important for Keras for i in range(0, len(self.data[0]), B): x = self.data[0][i:i+B] y = self.data[1][i:i+B] names = self.names[i:i + B] ts = self.ts[i:i + B] x = common_utils.pad_zeros(x) y = np.array(y) # (B, 25) if self.target_repl: y_rep = np.expand_dims(y, axis=1).repeat(x.shape[1], axis=1) # (B, T, 25) batch_data = (x, [y, y_rep]) else: batch_data = (x, y) if not self.return_names: yield batch_data else: yield {"data": batch_data, "names": names, "ts": ts} def __iter__(self): return self.generator def next(self): with self.lock: return next(self.generator) def __next__(self): return self.next() def save_results(names, ts, predictions, labels, path): n_tasks = 25 common_utils.create_directory(os.path.dirname(path)) with open(path, 'w') as f: header = ["stay", "period_length"] header += ["pred_{}".format(x) for x in range(1, n_tasks + 1)] header += ["label_{}".format(x) for x in range(1, n_tasks + 1)] header = ",".join(header) f.write(header + '\n') for name, t, pred, y in zip(names, ts, predictions, labels): line = [name] line += ["{:.6f}".format(t)] line += ["{:.6f}".format(a) for a in pred] line += [str(a) for a in y] line = ",".join(line) f.write(line + '\n')
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; namespace HotChocolate.Internal { /// <summary> /// The type info provides information about the type structure that is relevant to /// the GraphQL type system. A <see cref="ITypeInfo"/> can be created for runtime /// types as well as for schema types. /// </summary> public interface ITypeInfo { /// <summary> /// Gets the type component that represents the named type. /// </summary> Type NamedType { get; } /// <summary> /// Gets the original type from which this type info was inferred. /// </summary> Type OriginalType { get; } /// <summary> /// The components represent the GraphQL type structure. /// </summary> IReadOnlyList<TypeComponent> Components { get; } /// <summary> /// Defines if the <see cref="NamedType"/> is a GraphQL schema type. /// </summary> bool IsSchemaType { get; } /// <summary> /// Defines if the <see cref="NamedType"/> is a runtime type. /// </summary> bool IsRuntimeType { get; } /// <summary> /// If this type is a schema type then this method defines if it is an input type. /// </summary> bool IsInputType(); /// <summary> /// If this type is a schema type then this method defines if it is an output type. /// </summary> bool IsOutputType(); /// <summary> /// Gets the extended type that contains information /// about type arguments and nullability. /// </summary> IExtendedType GetExtendedType(); } }
{ "pile_set_name": "Github" }
/* * jdhuff.c * * Copyright (C) 1991-1995, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains Huffman entropy decoding routines. * * Much of the complexity here has to do with supporting input suspension. * If the data source module demands suspension, we want to be able to back * up to the start of the current MCU. To do this, we copy state variables * into local working storage, and update them back to the permanent * storage only upon successful completion of an MCU. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jdhuff.h" /* Declarations shared with jdphuff.c */ /* * Expanded entropy decoder object for Huffman decoding. * * The savable_state subrecord contains fields that change within an MCU, * but must not be updated permanently until we complete the MCU. */ typedef struct { int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */ } savable_state; /* This macro is to work around compilers with missing or broken * structure assignment. You'll need to fix this code if you have * such a compiler and you change MAX_COMPS_IN_SCAN. */ #ifndef NO_STRUCT_ASSIGN #define ASSIGN_STATE(dest,src) ((dest) = (src)) #else #if MAX_COMPS_IN_SCAN == 4 #define ASSIGN_STATE(dest,src) \ ((dest).last_dc_val[0] = (src).last_dc_val[0], \ (dest).last_dc_val[1] = (src).last_dc_val[1], \ (dest).last_dc_val[2] = (src).last_dc_val[2], \ (dest).last_dc_val[3] = (src).last_dc_val[3]) #endif #endif typedef struct { struct jpeg_entropy_decoder pub; /* public fields */ /* These fields are loaded into local variables at start of each MCU. * In case of suspension, we exit WITHOUT updating them. */ bitread_perm_state bitstate; /* Bit buffer at start of MCU */ savable_state saved; /* Other state at start of MCU */ /* These fields are NOT loaded into local working state. */ unsigned int restarts_to_go; /* MCUs left in this restart interval */ /* Pointers to derived tables (these workspaces have image lifespan) */ d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS]; d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS]; } huff_entropy_decoder; typedef huff_entropy_decoder * huff_entropy_ptr; /* * Initialize for a Huffman-compressed scan. */ METHODDEF void start_pass_huff_decoder (j_decompress_ptr cinfo) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; int ci, dctbl, actbl; jpeg_component_info * compptr; /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG. * This ought to be an error condition, but we make it a warning because * there are some baseline files out there with all zeroes in these bytes. */ if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 || cinfo->Ah != 0 || cinfo->Al != 0) WARNMS(cinfo, JWRN_NOT_SEQUENTIAL); for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; dctbl = compptr->dc_tbl_no; actbl = compptr->ac_tbl_no; /* Make sure requested tables are present */ if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS || cinfo->dc_huff_tbl_ptrs[dctbl] == NULL) ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl); if (actbl < 0 || actbl >= NUM_HUFF_TBLS || cinfo->ac_huff_tbl_ptrs[actbl] == NULL) ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl); /* Compute derived values for Huffman tables */ /* We may do this more than once for a table, but it's not expensive */ jpeg_make_d_derived_tbl(cinfo, cinfo->dc_huff_tbl_ptrs[dctbl], & entropy->dc_derived_tbls[dctbl]); jpeg_make_d_derived_tbl(cinfo, cinfo->ac_huff_tbl_ptrs[actbl], & entropy->ac_derived_tbls[actbl]); /* Initialize DC predictions to 0 */ entropy->saved.last_dc_val[ci] = 0; } /* Initialize bitread state variables */ entropy->bitstate.bits_left = 0; entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */ entropy->bitstate.printed_eod = FALSE; /* Initialize restart counter */ entropy->restarts_to_go = cinfo->restart_interval; } /* * Compute the derived values for a Huffman table. * Note this is also used by jdphuff.c. */ GLOBAL void jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, JHUFF_TBL * htbl, d_derived_tbl ** pdtbl) { d_derived_tbl *dtbl; int p, i, l, si; int lookbits, ctr; char huffsize[257]; unsigned int huffcode[257]; unsigned int code; /* Allocate a workspace if we haven't already done so. */ if (*pdtbl == NULL) *pdtbl = (d_derived_tbl *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(d_derived_tbl)); dtbl = *pdtbl; dtbl->pub = htbl; /* fill in back link */ /* Figure C.1: make table of Huffman code length for each symbol */ /* Note that this is in code-length order. */ p = 0; for (l = 1; l <= 16; l++) { for (i = 1; i <= (int) htbl->bits[l]; i++) huffsize[p++] = (char) l; } huffsize[p] = 0; /* Figure C.2: generate the codes themselves */ /* Note that this is in code-length order. */ code = 0; si = huffsize[0]; p = 0; while (huffsize[p]) { while (((int) huffsize[p]) == si) { huffcode[p++] = code; code++; } code <<= 1; si++; } /* Figure F.15: generate decoding tables for bit-sequential decoding */ p = 0; for (l = 1; l <= 16; l++) { if (htbl->bits[l]) { dtbl->valptr[l] = p; /* huffval[] index of 1st symbol of code length l */ dtbl->mincode[l] = huffcode[p]; /* minimum code of length l */ p += htbl->bits[l]; dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */ } else { dtbl->maxcode[l] = -1; /* -1 if no codes of this length */ } } dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */ /* Compute lookahead tables to speed up decoding. * First we set all the table entries to 0, indicating "too long"; * then we iterate through the Huffman codes that are short enough and * fill in all the entries that correspond to bit sequences starting * with that code. */ MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits)); p = 0; for (l = 1; l <= HUFF_LOOKAHEAD; l++) { for (i = 1; i <= (int) htbl->bits[l]; i++, p++) { /* l = current code's length, p = its index in huffcode[] & huffval[]. */ /* Generate left-justified code followed by all possible bit sequences */ lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l); for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) { dtbl->look_nbits[lookbits] = l; dtbl->look_sym[lookbits] = htbl->huffval[p]; lookbits++; } } } } /* * Out-of-line code for bit fetching (shared with jdphuff.c). * See jdhuff.h for info about usage. * Note: current values of get_buffer and bits_left are passed as parameters, * but are returned in the corresponding fields of the state struct. * * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width * of get_buffer to be used. (On machines with wider words, an even larger * buffer could be used.) However, on some machines 32-bit shifts are * quite slow and take time proportional to the number of places shifted. * (This is true with most PC compilers, for instance.) In this case it may * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the * average shift distance at the cost of more calls to jpeg_fill_bit_buffer. */ #ifdef SLOW_SHIFT_32 #define MIN_GET_BITS 15 /* minimum allowable value */ #else #define MIN_GET_BITS (BIT_BUF_SIZE-7) #endif GLOBAL boolean jpeg_fill_bit_buffer (bitread_working_state * state, register bit_buf_type get_buffer, register int bits_left, int nbits) /* Load up the bit buffer to a depth of at least nbits */ { /* Copy heavily used state fields into locals (hopefully registers) */ register const JOCTET * next_input_byte = state->next_input_byte; register size_t bytes_in_buffer = state->bytes_in_buffer; register int c; /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */ /* (It is assumed that no request will be for more than that many bits.) */ while (bits_left < MIN_GET_BITS) { /* Attempt to read a byte */ if (state->unread_marker != 0) goto no_more_data; /* can't advance past a marker */ if (bytes_in_buffer == 0) { if (! (*state->cinfo->src->fill_input_buffer) (state->cinfo)) return FALSE; next_input_byte = state->cinfo->src->next_input_byte; bytes_in_buffer = state->cinfo->src->bytes_in_buffer; } bytes_in_buffer--; c = GETJOCTET(*next_input_byte++); /* If it's 0xFF, check and discard stuffed zero byte */ if (c == 0xFF) { do { if (bytes_in_buffer == 0) { if (! (*state->cinfo->src->fill_input_buffer) (state->cinfo)) return FALSE; next_input_byte = state->cinfo->src->next_input_byte; bytes_in_buffer = state->cinfo->src->bytes_in_buffer; } bytes_in_buffer--; c = GETJOCTET(*next_input_byte++); } while (c == 0xFF); if (c == 0) { /* Found FF/00, which represents an FF data byte */ c = 0xFF; } else { /* Oops, it's actually a marker indicating end of compressed data. */ /* Better put it back for use later */ state->unread_marker = c; no_more_data: /* There should be enough bits still left in the data segment; */ /* if so, just break out of the outer while loop. */ if (bits_left >= nbits) break; /* Uh-oh. Report corrupted data to user and stuff zeroes into * the data stream, so that we can produce some kind of image. * Note that this code will be repeated for each byte demanded * for the rest of the segment. We use a nonvolatile flag to ensure * that only one warning message appears. */ if (! *(state->printed_eod_ptr)) { WARNMS(state->cinfo, JWRN_HIT_MARKER); *(state->printed_eod_ptr) = TRUE; } c = 0; /* insert a zero byte into bit buffer */ } } /* OK, load c into get_buffer */ get_buffer = (get_buffer << 8) | c; bits_left += 8; } /* Unload the local registers */ state->next_input_byte = next_input_byte; state->bytes_in_buffer = bytes_in_buffer; state->get_buffer = get_buffer; state->bits_left = bits_left; return TRUE; } /* * Out-of-line code for Huffman code decoding. * See jdhuff.h for info about usage. */ GLOBAL int jpeg_huff_decode (bitread_working_state * state, register bit_buf_type get_buffer, register int bits_left, d_derived_tbl * htbl, int min_bits) { register int l = min_bits; register INT32 code; /* HUFF_DECODE has determined that the code is at least min_bits */ /* bits long, so fetch that many bits in one swoop. */ CHECK_BIT_BUFFER(*state, l, return -1); code = GET_BITS(l); /* Collect the rest of the Huffman code one bit at a time. */ /* This is per Figure F.16 in the JPEG spec. */ while (code > htbl->maxcode[l]) { code <<= 1; CHECK_BIT_BUFFER(*state, 1, return -1); code |= GET_BITS(1); l++; } /* Unload the local registers */ state->get_buffer = get_buffer; state->bits_left = bits_left; /* With garbage input we may reach the sentinel value l = 17. */ if (l > 16) { WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE); return 0; /* fake a zero as the safest result */ } return htbl->pub->huffval[ htbl->valptr[l] + ((int) (code - htbl->mincode[l])) ]; } /* * Figure F.12: extend sign bit. * On some machines, a shift and add will be faster than a table lookup. */ #ifdef AVOID_TABLES #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x)) #else #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x)) static const int extend_test[16] = /* entry n is 2**(n-1) */ { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 }; static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */ { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1, ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1, ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1, ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 }; #endif /* AVOID_TABLES */ /* * Check for a restart marker & resynchronize decoder. * Returns FALSE if must suspend. */ LOCAL boolean process_restart (j_decompress_ptr cinfo) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; int ci; /* Throw away any unused bits remaining in bit buffer; */ /* include any full bytes in next_marker's count of discarded bytes */ cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8; entropy->bitstate.bits_left = 0; /* Advance past the RSTn marker */ if (! (*cinfo->marker->read_restart_marker) (cinfo)) return FALSE; /* Re-initialize DC predictions to 0 */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) entropy->saved.last_dc_val[ci] = 0; /* Reset restart counter */ entropy->restarts_to_go = cinfo->restart_interval; /* Next segment can get another out-of-data warning */ entropy->bitstate.printed_eod = FALSE; return TRUE; } /* * Decode and return one MCU's worth of Huffman-compressed coefficients. * The coefficients are reordered from zigzag order into natural array order, * but are not dequantized. * * The i'th block of the MCU is stored into the block pointed to by * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER. * (Wholesale zeroing is usually a little faster than retail...) * * Returns FALSE if data source requested suspension. In that case no * changes have been made to permanent state. (Exception: some output * coefficients may already have been assigned. This is harmless for * this module, since we'll just re-assign them on the next call.) */ METHODDEF boolean decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data) { huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; register int s, k, r; int blkn, ci; JBLOCKROW block; BITREAD_STATE_VARS; savable_state state; d_derived_tbl * dctbl; d_derived_tbl * actbl; jpeg_component_info * compptr; /* Process restart marker if needed; may have to suspend */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) if (! process_restart(cinfo)) return FALSE; } /* Load up working state */ BITREAD_LOAD_STATE(cinfo,entropy->bitstate); ASSIGN_STATE(state, entropy->saved); /* Outer loop handles each block in the MCU */ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { block = MCU_data[blkn]; ci = cinfo->MCU_membership[blkn]; compptr = cinfo->cur_comp_info[ci]; dctbl = entropy->dc_derived_tbls[compptr->dc_tbl_no]; actbl = entropy->ac_derived_tbls[compptr->ac_tbl_no]; /* Decode a single block's worth of coefficients */ /* Section F.2.2.1: decode the DC coefficient difference */ HUFF_DECODE(s, br_state, dctbl, return FALSE, label1); if (s) { CHECK_BIT_BUFFER(br_state, s, return FALSE); r = GET_BITS(s); s = HUFF_EXTEND(r, s); } /* Shortcut if component's values are not interesting */ if (! compptr->component_needed) goto skip_ACs; /* Convert DC difference to actual value, update last_dc_val */ s += state.last_dc_val[ci]; state.last_dc_val[ci] = s; /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */ (*block)[0] = (JCOEF) s; /* Do we need to decode the AC coefficients for this component? */ if (compptr->DCT_scaled_size > 1) { /* Section F.2.2.2: decode the AC coefficients */ /* Since zeroes are skipped, output area must be cleared beforehand */ for (k = 1; k < DCTSIZE2; k++) { HUFF_DECODE(s, br_state, actbl, return FALSE, label2); r = s >> 4; s &= 15; if (s) { k += r; CHECK_BIT_BUFFER(br_state, s, return FALSE); r = GET_BITS(s); s = HUFF_EXTEND(r, s); /* Output coefficient in natural (dezigzagged) order. * Note: the extra entries in jpeg_natural_order[] will save us * if k >= DCTSIZE2, which could happen if the data is corrupted. */ (*block)[jpeg_natural_order[k]] = (JCOEF) s; } else { if (r != 15) break; k += 15; } } } else { skip_ACs: /* Section F.2.2.2: decode the AC coefficients */ /* In this path we just discard the values */ for (k = 1; k < DCTSIZE2; k++) { HUFF_DECODE(s, br_state, actbl, return FALSE, label3); r = s >> 4; s &= 15; if (s) { k += r; CHECK_BIT_BUFFER(br_state, s, return FALSE); DROP_BITS(s); } else { if (r != 15) break; k += 15; } } } } /* Completed MCU, so update state */ BITREAD_SAVE_STATE(cinfo,entropy->bitstate); ASSIGN_STATE(entropy->saved, state); /* Account for restart interval (no-op if not using restarts) */ entropy->restarts_to_go--; return TRUE; } /* * Module initialization routine for Huffman entropy decoding. */ GLOBAL void jinit_huff_decoder (j_decompress_ptr cinfo) { huff_entropy_ptr entropy; int i; entropy = (huff_entropy_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(huff_entropy_decoder)); cinfo->entropy = (struct jpeg_entropy_decoder *) entropy; entropy->pub.start_pass = start_pass_huff_decoder; entropy->pub.decode_mcu = decode_mcu; /* Mark tables unallocated */ for (i = 0; i < NUM_HUFF_TBLS; i++) { entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL; } }
{ "pile_set_name": "Github" }