text
stringlengths
2
100k
meta
dict
{ "info" : { "author" : "xcode", "version" : 1 } }
{ "pile_set_name": "Github" }
/* ------------------------------------------------------------------------- */ /* -- CONFIGURE SPECIFIED FEATURES -- */ /* ------------------------------------------------------------------------- */ #ifndef __MINGWCONFIG_H #define __MINGWCONFIG_H /* Define if you want to use Batch Mode */ /* #define HAVE_BATCH_FILE_INSERT 1 */ /* Define if you have GCC */ #define HAVE_GCC 1 /* Define if you have sys/bitypes.h */ /* #undef HAVE_SYS_BITYPES_H */ /* Define if you have zlib */ #define HAVE_LIBZ 1 /* Define if you have lzo lib */ #define HAVE_LZO 1 /* File daemon specif libraries */ #define FDLIBS 1 /* Define to 1 if you have `alloca', as a function or macro. */ #ifndef HAVE_MINGW #define alloca _alloca #endif /* Define to 1 if you have the `getmntent' function. */ /*#define HAVE_GETMNTENT 1 */ /* Define to 1 if you have the `getpid' function. */ #define getpid _getpid /* Define to 1 if you have the <grp.h> header file. */ /*#define HAVE_GRP_H 1*/ /* Define to 1 if you have the `lchown' function. */ #define HAVE_LCHOWN 1 /* Define to 1 if you have the `localtime_r' function. */ #define HAVE_LOCALTIME_R 1 /* Define to 1 if you have the <mtio.h> header file. */ /* #undef HAVE_MTIO_H */ /* Define to 1 if you have the `nanosleep' function. */ /* #undef HAVE_NANOSLEEP */ /* Define to 1 if you have the <pwd.h> header file. */ /* #undef HAVE_PWD_H */ /* Define to 1 if you have the `Readdir_r' function. */ /* #undef HAVE_READDIR_R */ /* Define to 1 if you have the <resolv.h> header file. */ /* #undef HAVE_RESOLV_H */ /* Define to 1 if you have the `setenv' function. */ /* #undef HAVE_SETENV */ /* Define to 1 if you have the `putenv' function. */ #define HAVE_PUTENV 1 /* Define to 1 if translation of program messages to the user's native language is requested. */ #if (defined _MSC_VER) && (_MSC_VER >= 1400) // VC8+ /* Enable NLS only if we are using the new VC++. * NLS should also work with VC++ 7.1, but the Makefiles are * not adapted to support it (include, lib...). */ #define ENABLE_NLS 1 #endif #undef LOCALEDIR #define LOCALEDIR "." /* Define to 1 if you have the <sys/mtio.h> header file. */ #define HAVE_SYS_MTIO_H 1 /* Define to 1 if you have the <sys/time.h> header file. */ #define HAVE_SYS_TIME_H 1 /* Define to 1 if you have the <zlib.h> header file. */ #define HAVE_ZLIB_H 1 /* Define to the full name of this package. */ #define PACKAGE_NAME "" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "" /* Define to the version of this package. */ #define PACKAGE_VERSION "" /* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */ #define TIME_WITH_SYS_TIME 1 /* Use long unsigned int for ioctl request */ #define HAVE_IOCTL_ULINT_REQUEST /* Number of bits in a file offset, on hosts where this is settable. */ #define _FILE_OFFSET_BITS 64 /* Define to make fseeko etc. visible, on some hosts. */ #define _LARGEFILE_SOURCE 1 /* Define for large files, on AIX-style hosts. */ #define _LARGE_FILES 1 /* Define to 1 if encryption support should be enabled */ #define HAVE_CRYPTO 1 /* Define to 1 if TLS support should be enabled */ #define HAVE_TLS 1 /* Define to 1 if OpenSSL library is available */ #define HAVE_OPENSSL 1 /* Define to 1 if IPv6 support should be enabled */ #define HAVE_IPV6 1 /* Define to 1 if you have the `getaddrinfo' function. */ #define HAVE_GETADDRINFO 1 /* Define to 1 if you have the `__builtin_va_copy' function. */ #define HAVE___BUILTIN_VA_COPY 1 /* Directory for PID files */ #define PATH_BAREOS_PIDDIR "%TEMP%" /* Directory for daemon files */ #define PATH_BAREOS_WORKINGDIR "%TEMP%" /* Directory for backend drivers */ #define PATH_BAREOS_BACKENDDIR "." /* Define to 1 if dynamic loading of catalog backends is enabled */ #define HAVE_DYNAMIC_CATS_BACKENDS 1 /* Define to 1 if DB batch insert code enabled */ #define USE_BATCH_FILE_INSERT 1 /* Set if you have an SQLite3 Database */ #define HAVE_SQLITE3 1 /* Define to 1 if you have the `sqlite3_threadsafe' function. */ #define HAVE_SQLITE3_THREADSAFE 1 /* Set if you have an PostgreSQL Database */ #define HAVE_POSTGRESQL 1 /* Set if PostgreSQL DB batch insert code enabled */ #define HAVE_POSTGRESQL_BATCH_FILE_INSERT 1 /* Set if have PQisthreadsafe */ #define HAVE_PQISTHREADSAFE 1 /* Define to 1 if LMDB support should be enabled */ #define HAVE_LMDB 1 /* Define to 1 if you have jansson lib */ #define HAVE_JANSSON 1 /* Define to 1 if you have the `glob' function. */ #define HAVE_GLOB 1 #endif /* __MINGWNCONFIG_H */
{ "pile_set_name": "Github" }
// run // Copyright 2019 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. // Make sure the runtime can scan args of an unstarted goroutine // which starts with a reflect-generated function. package main import ( "reflect" "runtime" ) const N = 100 type T struct { } func (t *T) Foo(c chan bool) { c <- true } func main() { t := &T{} runtime.GOMAXPROCS(1) c := make(chan bool, N) for i := 0; i < N; i++ { f := reflect.ValueOf(t).MethodByName("Foo").Interface().(func(chan bool)) go f(c) } runtime.GC() for i := 0; i < N; i++ { <-c } }
{ "pile_set_name": "Github" }
'use strict'; var GetIntrinsic = require('../GetIntrinsic'); var $Number = GetIntrinsic('%Number%'); var $TypeError = GetIntrinsic('%TypeError%'); var $isNaN = require('../helpers/isNaN'); var $isFinite = require('../helpers/isFinite'); var isPrefixOf = require('../helpers/isPrefixOf'); var ToNumber = require('./ToNumber'); var ToPrimitive = require('./ToPrimitive'); var Type = require('./Type'); // https://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5 // eslint-disable-next-line max-statements module.exports = function AbstractRelationalComparison(x, y, LeftFirst) { if (Type(LeftFirst) !== 'Boolean') { throw new $TypeError('Assertion failed: LeftFirst argument must be a Boolean'); } var px; var py; if (LeftFirst) { px = ToPrimitive(x, $Number); py = ToPrimitive(y, $Number); } else { py = ToPrimitive(y, $Number); px = ToPrimitive(x, $Number); } var bothStrings = Type(px) === 'String' && Type(py) === 'String'; if (!bothStrings) { var nx = ToNumber(px); var ny = ToNumber(py); if ($isNaN(nx) || $isNaN(ny)) { return undefined; } if ($isFinite(nx) && $isFinite(ny) && nx === ny) { return false; } if (nx === 0 && ny === 0) { return false; } if (nx === Infinity) { return false; } if (ny === Infinity) { return true; } if (ny === -Infinity) { return false; } if (nx === -Infinity) { return true; } return nx < ny; // by now, these are both nonzero, finite, and not equal } if (isPrefixOf(py, px)) { return false; } if (isPrefixOf(px, py)) { return true; } return px < py; // both strings, neither a prefix of the other. shortcut for steps c-f };
{ "pile_set_name": "Github" }
var common = require('../common'); module.exports = schedule; function schedule(subcmd, opts, args, cb) { var self = this; var finish = common.makeFinisher(opts, cb); if (opts.help) { self.do_help('help', {}, [subcmd], cb); return; } var id = args.shift(); if (!id) { cb(new Error('first argument must be supplied')); return; } self.client.schedule(id, finish); } schedule.options = [ { names: ['help', 'h'], type: 'bool', help: 'Show this help.' }, { names: ['json', 'j'], type: 'bool', help: 'JSON output.' } ]; schedule.help = 'Show a schedule\n\n{{options}}';
{ "pile_set_name": "Github" }
package com.geccocrawler.gecco.utils; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.Set; import org.reflections.ReflectionUtils; /** * 泛型,Type的相关知识 * * http://developer.51cto.com/art/201103/250028.htm http://lsy.iteye.com/blog/220264 * * @author huchengyi * */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class ReflectUtils { /** * 获得类的所有基类和接口 * * @param clazz 类 * @return 所有基类的集合 */ public static Set<Class<?>> getAllSuperType(Class clazz) { return ReflectionUtils.getAllSuperTypes(clazz); } /** * 是否继承某个基类 * * @param childClazz * 子类 * @param superClazz * 基类 * @return 是否继承某个基类 */ public static boolean haveSuperType(Class childClazz, Class superClazz) { for (Class<?> clazz : getAllSuperType(childClazz)) { if (clazz.equals(superClazz)) { return true; } } return false; } /** * 是否继承某个基类 * * @param bean 需要判断的对象bean * @param superClazz 基类 * @return 是否继承某个基类 */ public static boolean haveSuperType(Object bean, Class superClazz) { return haveSuperType(bean.getClass(), superClazz); } public static Class getGenericClass(Type type, int i) { if (type instanceof ParameterizedType) { // 处理泛型类型 return getGenericClass((ParameterizedType) type, i); } else if (type instanceof TypeVariable) { // 处理泛型擦拭对象 return getGenericClass(((TypeVariable) type).getBounds()[0], 0); } else {// class本身也是type,强制转型 return (Class) type; } } private static Class getGenericClass(ParameterizedType parameterizedType, int i) { Object genericClass = parameterizedType.getActualTypeArguments()[i]; if (genericClass instanceof ParameterizedType) { // 处理多级泛型 return (Class) ((ParameterizedType) genericClass).getRawType(); } else if (genericClass instanceof GenericArrayType) { // 处理数组泛型 return (Class) ((GenericArrayType) genericClass).getGenericComponentType(); } else if (genericClass instanceof TypeVariable) { // 处理泛型擦拭对象 return getGenericClass(((TypeVariable) genericClass).getBounds()[0], 0); } else { return (Class) genericClass; } } }
{ "pile_set_name": "Github" }
version https://git-lfs.github.com/spec/v1 oid sha256:4e41fcb3df07351e4fbac3932ad9d062502644ad04ec685cb4e803c3d4f8d774 size 2854
{ "pile_set_name": "Github" }
<!-- input/input.wxml --> <label class='form-item {{disabled? "disabled": ""}} l-class form-item-{{labelLayout}}' style="width:{{width===null?'auto':width+'rpx'}}"> <view class='mask' wx:if="{{disabled}}"></view> <view class='row l-row-class' hidden="{{ showRow ? '' : 'hidden' }}" style="width:{{width}}rpx;"></view> <view wx:if="{{label && !labelCustom}}" hidden="{{hideLabel}}" class='form-label l-label-class form-label-{{labelLayout}}' style='{{labelLayout !== "top" ? "width:"+ labelWidth+ "rpx;" : "" }} height:{{labelLayout=== "top" ? labelWidth + "rpx" : "" }}'> <text><text class='text-require' wx:if="{{required}}">* </text>{{label}}<text wx:if="{{colon}}">:</text> </text> </view> <view wx:else hidden="{{hideLabel}}" class='form-label l-label-class form-label-{{labelLayout}}' style='{{labelLayout !== "top" ? "width:"+ labelWidth+ "rpx;" : "" }} height:{{labelLayout=== "top" ? labelWidth + "rpx" : "" }}'> <slot name="left" /> </view> <!-- 小程序表单组件 --> <input class="input {{hideLabel?'hideLabel':''}} l-input-class" value="{{ value }}" type="{{type}}" password="{{type==='password'}}" placeholder="{{placeholder}}" maxlength="{{maxlength}}" placeholder-class="pls-class" placeholder-style="{{placeholderStyle}}" disabled="{{disabled}}" focus="{{focus}}" bindinput="handleInputChange" bindfocus="handleInputFocus" bindblur="handleInputBlur" bindconfirm="handleInputConfirm" /> <l-icon wx:if="{{showEye&&value}}" name="eye" catch:tap="onTapEyeIcon" size="40" l-class="l-eye l-eye-{{type}}"/> <view class="close" wx:if="{{clear&&value}}" mut-bind:tap="onClearTap"> <view class="close-icon"> <l-icon name="close" color="#fff" size="16" /> </view> </view> <slot name="right"/> <l-error-tip l-error-text-class="l-error-text l-error-text-class" errorText="{{errorText}}" wx:if="{{errorText}}"/> </label>
{ "pile_set_name": "Github" }
### Description The triangle is a primary two-dimensional cell. The triangle is defined by a counterclockwise ordered list of three points. The order of the points specifies the direction of the surface normal using the right-hand rule.
{ "pile_set_name": "Github" }
/* * Camellia * (C) 2012 Jack Lloyd * * Distributed under the terms of the Botan license */ #ifndef BOTAN_CAMELLIA_H__ #define BOTAN_CAMELLIA_H__ #include <botan/block_cipher.h> namespace Botan { /** * Camellia-128 */ class BOTAN_DLL Camellia_128 : public Block_Cipher_Fixed_Params<16, 16> { public: void encrypt_n(const byte in[], byte out[], size_t blocks) const; void decrypt_n(const byte in[], byte out[], size_t blocks) const; void clear() { SK.clear(); } std::string name() const { return "Camellia-128"; } BlockCipher* clone() const { return new Camellia_128; } private: void key_schedule(const byte key[], size_t length); SecureVector<u64bit> SK; }; /** * Camellia-192 */ class BOTAN_DLL Camellia_192 : public Block_Cipher_Fixed_Params<16, 24> { public: void encrypt_n(const byte in[], byte out[], size_t blocks) const; void decrypt_n(const byte in[], byte out[], size_t blocks) const; void clear() { SK.clear(); } std::string name() const { return "Camellia-192"; } BlockCipher* clone() const { return new Camellia_192; } private: void key_schedule(const byte key[], size_t length); SecureVector<u64bit> SK; }; /** * Camellia-256 */ class BOTAN_DLL Camellia_256 : public Block_Cipher_Fixed_Params<16, 32> { public: void encrypt_n(const byte in[], byte out[], size_t blocks) const; void decrypt_n(const byte in[], byte out[], size_t blocks) const; void clear() { SK.clear(); } std::string name() const { return "Camellia-256"; } BlockCipher* clone() const { return new Camellia_256; } private: void key_schedule(const byte key[], size_t length); SecureVector<u64bit> SK; }; } #endif
{ "pile_set_name": "Github" }
<?php namespace Drupal\Tests\Core\Test; use Drupal\Tests\UnitTestCase; use Drupal\KernelTests\KernelTestBase; /** * @group Test * @group legacy * * @coversDefaultClass \Drupal\KernelTests\KernelTestBase */ class KernelTestBaseTest extends UnitTestCase { /** * @expectedDeprecation Drupal\KernelTests\KernelTestBase::isTestInIsolation() is deprecated in Drupal 8.4.x, for removal before the Drupal 9.0.0 release. KernelTestBase tests are always run in isolated processes. * * @covers ::isTestInIsolation */ public function testDeprecatedIsTestInIsolation() { $kernel_test = $this->getMockBuilder(KernelTestBase::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $is_isolated = new \ReflectionMethod($kernel_test, 'isTestInIsolation'); $is_isolated->setAccessible(TRUE); // Assert that the return value is a bool, because this unit test might or // might not be running in process isolation. $this->assertInternalType('bool', $is_isolated->invoke($kernel_test)); } }
{ "pile_set_name": "Github" }
<server> <featureManager> <feature>jaxrs-2.0</feature> <feature>cdi-1.2</feature> <feature>ejbLite-3.2</feature> <feature>concurrent-1.0</feature> </featureManager> <include location="../fatTestPorts.xml"/> <javaPermission className="java.lang.RuntimePermission" name="accessDeclaredMembers"/> <javaPermission className="java.util.PropertyPermission" name="bvt.prop.HTTP_default" actions="read"/> <javaPermission className="java.util.PropertyPermission" name="test.clients" actions="read"/> </server>
{ "pile_set_name": "Github" }
namespace ClassLib106 { public class Class020 { public static string Property => "ClassLib106"; } }
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package v1beta1 import ( "context" "time" v1beta1 "k8s.io/api/extensions/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" scheme "k8s.io/client-go/kubernetes/scheme" rest "k8s.io/client-go/rest" ) // DaemonSetsGetter has a method to return a DaemonSetInterface. // A group's client should implement this interface. type DaemonSetsGetter interface { DaemonSets(namespace string) DaemonSetInterface } // DaemonSetInterface has methods to work with DaemonSet resources. type DaemonSetInterface interface { Create(ctx context.Context, daemonSet *v1beta1.DaemonSet, opts v1.CreateOptions) (*v1beta1.DaemonSet, error) Update(ctx context.Context, daemonSet *v1beta1.DaemonSet, opts v1.UpdateOptions) (*v1beta1.DaemonSet, error) UpdateStatus(ctx context.Context, daemonSet *v1beta1.DaemonSet, opts v1.UpdateOptions) (*v1beta1.DaemonSet, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta1.DaemonSet, error) List(ctx context.Context, opts v1.ListOptions) (*v1beta1.DaemonSetList, error) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.DaemonSet, err error) DaemonSetExpansion } // daemonSets implements DaemonSetInterface type daemonSets struct { client rest.Interface ns string } // newDaemonSets returns a DaemonSets func newDaemonSets(c *ExtensionsV1beta1Client, namespace string) *daemonSets { return &daemonSets{ client: c.RESTClient(), ns: namespace, } } // Get takes name of the daemonSet, and returns the corresponding daemonSet object, and an error if there is any. func (c *daemonSets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.DaemonSet, err error) { result = &v1beta1.DaemonSet{} err = c.client.Get(). Namespace(c.ns). Resource("daemonsets"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(ctx). Into(result) return } // List takes label and field selectors, and returns the list of DaemonSets that match those selectors. func (c *daemonSets) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.DaemonSetList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } result = &v1beta1.DaemonSetList{} err = c.client.Get(). Namespace(c.ns). Resource("daemonsets"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Do(ctx). Into(result) return } // Watch returns a watch.Interface that watches the requested daemonSets. func (c *daemonSets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("daemonsets"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Watch(ctx) } // Create takes the representation of a daemonSet and creates it. Returns the server's representation of the daemonSet, and an error, if there is any. func (c *daemonSets) Create(ctx context.Context, daemonSet *v1beta1.DaemonSet, opts v1.CreateOptions) (result *v1beta1.DaemonSet, err error) { result = &v1beta1.DaemonSet{} err = c.client.Post(). Namespace(c.ns). Resource("daemonsets"). VersionedParams(&opts, scheme.ParameterCodec). Body(daemonSet). Do(ctx). Into(result) return } // Update takes the representation of a daemonSet and updates it. Returns the server's representation of the daemonSet, and an error, if there is any. func (c *daemonSets) Update(ctx context.Context, daemonSet *v1beta1.DaemonSet, opts v1.UpdateOptions) (result *v1beta1.DaemonSet, err error) { result = &v1beta1.DaemonSet{} err = c.client.Put(). Namespace(c.ns). Resource("daemonsets"). Name(daemonSet.Name). VersionedParams(&opts, scheme.ParameterCodec). Body(daemonSet). Do(ctx). Into(result) return } // UpdateStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). func (c *daemonSets) UpdateStatus(ctx context.Context, daemonSet *v1beta1.DaemonSet, opts v1.UpdateOptions) (result *v1beta1.DaemonSet, err error) { result = &v1beta1.DaemonSet{} err = c.client.Put(). Namespace(c.ns). Resource("daemonsets"). Name(daemonSet.Name). SubResource("status"). VersionedParams(&opts, scheme.ParameterCodec). Body(daemonSet). Do(ctx). Into(result) return } // Delete takes name of the daemonSet and deletes it. Returns an error if one occurs. func (c *daemonSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("daemonsets"). Name(name). Body(&opts). Do(ctx). Error() } // DeleteCollection deletes a collection of objects. func (c *daemonSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { var timeout time.Duration if listOpts.TimeoutSeconds != nil { timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second } return c.client.Delete(). Namespace(c.ns). Resource("daemonsets"). VersionedParams(&listOpts, scheme.ParameterCodec). Timeout(timeout). Body(&opts). Do(ctx). Error() } // Patch applies the patch and returns the patched daemonSet. func (c *daemonSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.DaemonSet, err error) { result = &v1beta1.DaemonSet{} err = c.client.Patch(pt). Namespace(c.ns). Resource("daemonsets"). Name(name). SubResource(subresources...). VersionedParams(&opts, scheme.ParameterCodec). Body(data). Do(ctx). Into(result) return }
{ "pile_set_name": "Github" }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.util.environment; public enum CommandMode { RELEASE, TEST; private boolean loggingEnabled; static { RELEASE.loggingEnabled = true; TEST.loggingEnabled = false; } public boolean isLoggingEnabled() { return loggingEnabled; } }
{ "pile_set_name": "Github" }
var isArray = require('./isArray'); /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } module.exports = castArray;
{ "pile_set_name": "Github" }
import openmc import openmc.stats def test_export_to_xml(run_in_tmpdir): s = openmc.Settings() s.run_mode = 'fixed source' s.batches = 1000 s.generations_per_batch = 10 s.inactive = 100 s.particles = 1000000 s.max_lost_particles = 5 s.rel_max_lost_particles = 1e-4 s.keff_trigger = {'type': 'std_dev', 'threshold': 0.001} s.energy_mode = 'continuous-energy' s.max_order = 5 s.source = openmc.Source(space=openmc.stats.Point()) s.output = {'summary': True, 'tallies': False, 'path': 'here'} s.verbosity = 7 s.sourcepoint = {'batches': [50, 150, 500, 1000], 'separate': True, 'write': True, 'overwrite': True} s.statepoint = {'batches': [50, 150, 500, 1000]} s.confidence_intervals = True s.ptables = True s.seed = 17 s.survival_biasing = True s.cutoff = {'weight': 0.25, 'weight_avg': 0.5, 'energy_neutron': 1.0e-5, 'energy_photon': 1000.0, 'energy_electron': 1.0e-5, 'energy_positron': 1.0e-5} mesh = openmc.RegularMesh() mesh.lower_left = (-10., -10., -10.) mesh.upper_right = (10., 10., 10.) mesh.dimension = (5, 5, 5) s.entropy_mesh = mesh s.trigger_active = True s.trigger_max_batches = 10000 s.trigger_batch_interval = 50 s.no_reduce = False s.tabular_legendre = {'enable': True, 'num_points': 50} s.temperature = {'default': 293.6, 'method': 'interpolation', 'multipole': True, 'range': (200., 1000.)} s.trace = (10, 1, 20) s.track = [1, 1, 1, 2, 1, 1] s.ufs_mesh = mesh s.resonance_scattering = {'enable': True, 'method': 'rvs', 'energy_min': 1.0, 'energy_max': 1000.0, 'nuclides': ['U235', 'U238', 'Pu239']} s.volume_calculations = openmc.VolumeCalculation( domains=[openmc.Cell()], samples=1000, lower_left=(-10., -10., -10.), upper_right = (10., 10., 10.)) s.create_fission_neutrons = True s.log_grid_bins = 2000 s.photon_transport = False s.electron_treatment = 'led' s.dagmc = False # Make sure exporting XML works s.export_to_xml() # Generate settings from XML s = openmc.Settings.from_xml() assert s.run_mode == 'fixed source' assert s.batches == 1000 assert s.generations_per_batch == 10 assert s.inactive == 100 assert s.particles == 1000000 assert s.max_lost_particles == 5 assert s.rel_max_lost_particles == 1e-4 assert s.keff_trigger == {'type': 'std_dev', 'threshold': 0.001} assert s.energy_mode == 'continuous-energy' assert s.max_order == 5 assert isinstance(s.source[0], openmc.Source) assert isinstance(s.source[0].space, openmc.stats.Point) assert s.output == {'summary': True, 'tallies': False, 'path': 'here'} assert s.verbosity == 7 assert s.sourcepoint == {'batches': [50, 150, 500, 1000], 'separate': True, 'write': True, 'overwrite': True} assert s.statepoint == {'batches': [50, 150, 500, 1000]} assert s.confidence_intervals assert s.ptables assert s.seed == 17 assert s.survival_biasing assert s.cutoff == {'weight': 0.25, 'weight_avg': 0.5, 'energy_neutron': 1.0e-5, 'energy_photon': 1000.0, 'energy_electron': 1.0e-5, 'energy_positron': 1.0e-5} assert isinstance(s.entropy_mesh, openmc.RegularMesh) assert s.entropy_mesh.lower_left == [-10., -10., -10.] assert s.entropy_mesh.upper_right == [10., 10., 10.] assert s.entropy_mesh.dimension == [5, 5, 5] assert s.trigger_active assert s.trigger_max_batches == 10000 assert s.trigger_batch_interval == 50 assert not s.no_reduce assert s.tabular_legendre == {'enable': True, 'num_points': 50} assert s.temperature == {'default': 293.6, 'method': 'interpolation', 'multipole': True, 'range': [200., 1000.]} assert s.trace == [10, 1, 20] assert s.track == [1, 1, 1, 2, 1, 1] assert isinstance(s.ufs_mesh, openmc.RegularMesh) assert s.ufs_mesh.lower_left == [-10., -10., -10.] assert s.ufs_mesh.upper_right == [10., 10., 10.] assert s.ufs_mesh.dimension == [5, 5, 5] assert s.resonance_scattering == {'enable': True, 'method': 'rvs', 'energy_min': 1.0, 'energy_max': 1000.0, 'nuclides': ['U235', 'U238', 'Pu239']} assert s.create_fission_neutrons assert s.log_grid_bins == 2000 assert not s.photon_transport assert s.electron_treatment == 'led' assert not s.dagmc
{ "pile_set_name": "Github" }
/** * 开发版本的文件导入 */ (function (){ var paths = [ 'editor.js', 'core/browser.js', 'core/utils.js', 'core/EventBase.js', 'core/dtd.js', 'core/domUtils.js', 'core/Range.js', 'core/Selection.js', 'core/Editor.js', 'core/Editor.defaultoptions.js', 'core/loadconfig.js', 'core/ajax.js', 'core/filterword.js', 'core/node.js', 'core/htmlparser.js', 'core/filternode.js', 'core/plugin.js', 'core/keymap.js', 'core/localstorage.js', 'plugins/defaultfilter.js', 'plugins/inserthtml.js', 'plugins/autotypeset.js', 'plugins/autosubmit.js', 'plugins/background.js', 'plugins/image.js', 'plugins/justify.js', 'plugins/font.js', 'plugins/link.js', 'plugins/iframe.js', 'plugins/scrawl.js', 'plugins/removeformat.js', 'plugins/blockquote.js', 'plugins/convertcase.js', 'plugins/indent.js', 'plugins/print.js', 'plugins/preview.js', 'plugins/selectall.js', 'plugins/paragraph.js', 'plugins/directionality.js', 'plugins/horizontal.js', 'plugins/time.js', 'plugins/rowspacing.js', 'plugins/lineheight.js', 'plugins/insertcode.js', 'plugins/cleardoc.js', 'plugins/anchor.js', 'plugins/wordcount.js', 'plugins/pagebreak.js', 'plugins/wordimage.js', 'plugins/dragdrop.js', 'plugins/undo.js', 'plugins/copy.js', 'plugins/paste.js', 'plugins/puretxtpaste.js', 'plugins/list.js', 'plugins/source.js', 'plugins/enterkey.js', 'plugins/keystrokes.js', 'plugins/fiximgclick.js', 'plugins/autolink.js', 'plugins/autoheight.js', 'plugins/autofloat.js', 'plugins/video.js', 'plugins/table.core.js', 'plugins/table.cmds.js', 'plugins/table.action.js', 'plugins/table.sort.js', 'plugins/contextmenu.js', 'plugins/shortcutmenu.js', 'plugins/basestyle.js', 'plugins/elementpath.js', 'plugins/formatmatch.js', 'plugins/searchreplace.js', 'plugins/customstyle.js', 'plugins/catchremoteimage.js', 'plugins/snapscreen.js', 'plugins/insertparagraph.js', 'plugins/webapp.js', 'plugins/template.js', 'plugins/music.js', 'plugins/autoupload.js', 'plugins/autosave.js', 'plugins/charts.js', 'plugins/section.js', 'plugins/simpleupload.js', 'plugins/serverparam.js', 'plugins/insertfile.js', 'ui/ui.js', 'ui/uiutils.js', 'ui/uibase.js', 'ui/separator.js', 'ui/mask.js', 'ui/popup.js', 'ui/colorpicker.js', 'ui/tablepicker.js', 'ui/stateful.js', 'ui/button.js', 'ui/splitbutton.js', 'ui/colorbutton.js', 'ui/tablebutton.js', 'ui/autotypesetpicker.js', 'ui/autotypesetbutton.js', 'ui/cellalignpicker.js', 'ui/pastepicker.js', 'ui/toolbar.js', 'ui/menu.js', 'ui/combox.js', 'ui/dialog.js', 'ui/menubutton.js', 'ui/multiMenu.js', 'ui/shortcutmenu.js', 'ui/breakline.js', 'ui/message.js', 'adapter/editorui.js', 'adapter/editor.js', 'adapter/message.js', 'adapter/autosave.js' ], baseURL = '../_src/'; for (var i=0,pi;pi = paths[i++];) { document.write('<script type="text/javascript" src="'+ baseURL + pi +'"></script>'); } })();
{ "pile_set_name": "Github" }
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; background-color: #ffffff; overflow: hidden; margin: 0; } #chartdiv { width: 100%; height: 100vh; overflow: hidden; }
{ "pile_set_name": "Github" }
// Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "client/windows/crash_generation/crash_generation_client.h" #include <cassert> #include <utility> #include "client/windows/common/ipc_protocol.h" namespace google_breakpad { const int kPipeBusyWaitTimeoutMs = 2000; #ifdef _DEBUG const DWORD kWaitForServerTimeoutMs = INFINITE; #else const DWORD kWaitForServerTimeoutMs = 15000; #endif const int kPipeConnectMaxAttempts = 2; const DWORD kPipeDesiredAccess = FILE_READ_DATA | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES; const DWORD kPipeFlagsAndAttributes = SECURITY_IDENTIFICATION | SECURITY_SQOS_PRESENT; const DWORD kPipeMode = PIPE_READMODE_MESSAGE; const size_t kWaitEventCount = 2; // This function is orphan for production code. It can be used // for debugging to help repro some scenarios like the client // is slow in writing to the pipe after connecting, the client // is slow in reading from the pipe after writing, etc. The parameter // overlapped below is not used and it is present to match the signature // of this function to TransactNamedPipe Win32 API. Uncomment if needed // for debugging. /** static bool TransactNamedPipeDebugHelper(HANDLE pipe, const void* in_buffer, DWORD in_size, void* out_buffer, DWORD out_size, DWORD* bytes_count, LPOVERLAPPED) { // Uncomment the next sleep to create a gap before writing // to pipe. // Sleep(5000); if (!WriteFile(pipe, in_buffer, in_size, bytes_count, NULL)) { return false; } // Uncomment the next sleep to create a gap between write // and read. // Sleep(5000); return ReadFile(pipe, out_buffer, out_size, bytes_count, NULL) != FALSE; } **/ CrashGenerationClient::CrashGenerationClient( const wchar_t* pipe_name, MINIDUMP_TYPE dump_type, const CustomClientInfo* custom_info) : pipe_name_(pipe_name), pipe_handle_(NULL), custom_info_(), dump_type_(dump_type), crash_event_(NULL), crash_generated_(NULL), server_alive_(NULL), server_process_id_(0), thread_id_(0), exception_pointers_(NULL) { memset(&assert_info_, 0, sizeof(assert_info_)); if (custom_info) { custom_info_ = *custom_info; } } CrashGenerationClient::CrashGenerationClient( HANDLE pipe_handle, MINIDUMP_TYPE dump_type, const CustomClientInfo* custom_info) : pipe_name_(), pipe_handle_(pipe_handle), custom_info_(), dump_type_(dump_type), crash_event_(NULL), crash_generated_(NULL), server_alive_(NULL), server_process_id_(0), thread_id_(0), exception_pointers_(NULL) { memset(&assert_info_, 0, sizeof(assert_info_)); if (custom_info) { custom_info_ = *custom_info; } } CrashGenerationClient::~CrashGenerationClient() { if (crash_event_) { CloseHandle(crash_event_); } if (crash_generated_) { CloseHandle(crash_generated_); } if (server_alive_) { CloseHandle(server_alive_); } } // Performs the registration step with the server process. // The registration step involves communicating with the server // via a named pipe. The client sends the following pieces of // data to the server: // // * Message tag indicating the client is requesting registration. // * Process id of the client process. // * Address of a DWORD variable in the client address space // that will contain the thread id of the client thread that // caused the crash. // * Address of a EXCEPTION_POINTERS* variable in the client // address space that will point to an instance of EXCEPTION_POINTERS // when the crash happens. // * Address of an instance of MDRawAssertionInfo that will contain // relevant information in case of non-exception crashes like assertion // failures and pure calls. // // In return the client expects the following information from the server: // // * Message tag indicating successful registration. // * Server process id. // * Handle to an object that client can signal to request dump // generation from the server. // * Handle to an object that client can wait on after requesting // dump generation for the server to finish dump generation. // * Handle to a mutex object that client can wait on to make sure // server is still alive. // // If any step of the expected behavior mentioned above fails, the // registration step is not considered successful and hence out-of-process // dump generation service is not available. // // Returns true if the registration is successful; false otherwise. bool CrashGenerationClient::Register() { if (IsRegistered()) { return true; } HANDLE pipe = ConnectToServer(); if (!pipe) { return false; } bool success = RegisterClient(pipe); CloseHandle(pipe); return success; } bool CrashGenerationClient::RequestUpload(DWORD crash_id) { HANDLE pipe = ConnectToServer(); if (!pipe) { return false; } CustomClientInfo custom_info = {NULL, 0}; ProtocolMessage msg(MESSAGE_TAG_UPLOAD_REQUEST, crash_id, static_cast<MINIDUMP_TYPE>(NULL), NULL, NULL, NULL, custom_info, NULL, NULL, NULL); DWORD bytes_count = 0; bool success = WriteFile(pipe, &msg, sizeof(msg), &bytes_count, NULL) != 0; CloseHandle(pipe); return success; } HANDLE CrashGenerationClient::ConnectToServer() { HANDLE pipe = ConnectToPipe(pipe_name_.c_str(), kPipeDesiredAccess, kPipeFlagsAndAttributes); if (!pipe) { return NULL; } DWORD mode = kPipeMode; if (!SetNamedPipeHandleState(pipe, &mode, NULL, NULL)) { CloseHandle(pipe); pipe = NULL; } return pipe; } bool CrashGenerationClient::RegisterClient(HANDLE pipe) { ProtocolMessage msg(MESSAGE_TAG_REGISTRATION_REQUEST, GetCurrentProcessId(), dump_type_, &thread_id_, &exception_pointers_, &assert_info_, custom_info_, NULL, NULL, NULL); ProtocolMessage reply; DWORD bytes_count = 0; // The call to TransactNamedPipe below can be changed to a call // to TransactNamedPipeDebugHelper to help repro some scenarios. // For details see comments for TransactNamedPipeDebugHelper. if (!TransactNamedPipe(pipe, &msg, sizeof(msg), &reply, sizeof(ProtocolMessage), &bytes_count, NULL)) { return false; } if (!ValidateResponse(reply)) { return false; } ProtocolMessage ack_msg; ack_msg.tag = MESSAGE_TAG_REGISTRATION_ACK; if (!WriteFile(pipe, &ack_msg, sizeof(ack_msg), &bytes_count, NULL)) { return false; } crash_event_ = reply.dump_request_handle; crash_generated_ = reply.dump_generated_handle; server_alive_ = reply.server_alive_handle; server_process_id_ = reply.id; return true; } HANDLE CrashGenerationClient::ConnectToPipe(const wchar_t* pipe_name, DWORD pipe_access, DWORD flags_attrs) { if (pipe_handle_) { HANDLE t = pipe_handle_; pipe_handle_ = NULL; return t; } for (int i = 0; i < kPipeConnectMaxAttempts; ++i) { HANDLE pipe = CreateFile(pipe_name, pipe_access, 0, NULL, OPEN_EXISTING, flags_attrs, NULL); if (pipe != INVALID_HANDLE_VALUE) { return pipe; } // Cannot continue retrying if error is something other than // ERROR_PIPE_BUSY. if (GetLastError() != ERROR_PIPE_BUSY) { break; } // Cannot continue retrying if wait on pipe fails. if (!WaitNamedPipe(pipe_name, kPipeBusyWaitTimeoutMs)) { break; } } return NULL; } bool CrashGenerationClient::ValidateResponse( const ProtocolMessage& msg) const { return (msg.tag == MESSAGE_TAG_REGISTRATION_RESPONSE) && (msg.id != 0) && (msg.dump_request_handle != NULL) && (msg.dump_generated_handle != NULL) && (msg.server_alive_handle != NULL); } bool CrashGenerationClient::IsRegistered() const { return crash_event_ != NULL; } bool CrashGenerationClient::RequestDump(EXCEPTION_POINTERS* ex_info, MDRawAssertionInfo* assert_info) { if (!IsRegistered()) { return false; } exception_pointers_ = ex_info; thread_id_ = GetCurrentThreadId(); if (assert_info) { memcpy(&assert_info_, assert_info, sizeof(assert_info_)); } else { memset(&assert_info_, 0, sizeof(assert_info_)); } return SignalCrashEventAndWait(); } bool CrashGenerationClient::RequestDump(EXCEPTION_POINTERS* ex_info) { return RequestDump(ex_info, NULL); } bool CrashGenerationClient::RequestDump(MDRawAssertionInfo* assert_info) { return RequestDump(NULL, assert_info); } bool CrashGenerationClient::SignalCrashEventAndWait() { assert(crash_event_); assert(crash_generated_); assert(server_alive_); // Reset the dump generated event before signaling the crash // event so that the server can set the dump generated event // once it is done generating the event. if (!ResetEvent(crash_generated_)) { return false; } if (!SetEvent(crash_event_)) { return false; } HANDLE wait_handles[kWaitEventCount] = {crash_generated_, server_alive_}; DWORD result = WaitForMultipleObjects(kWaitEventCount, wait_handles, FALSE, kWaitForServerTimeoutMs); // Crash dump was successfully generated only if the server // signaled the crash generated event. return result == WAIT_OBJECT_0; } HANDLE CrashGenerationClient::DuplicatePipeToClientProcess(const wchar_t* pipe_name, HANDLE hProcess) { for (int i = 0; i < kPipeConnectMaxAttempts; ++i) { HANDLE local_pipe = CreateFile(pipe_name, kPipeDesiredAccess, 0, NULL, OPEN_EXISTING, kPipeFlagsAndAttributes, NULL); if (local_pipe != INVALID_HANDLE_VALUE) { HANDLE remotePipe = INVALID_HANDLE_VALUE; if (DuplicateHandle(GetCurrentProcess(), local_pipe, hProcess, &remotePipe, 0, FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) { return remotePipe; } else { return INVALID_HANDLE_VALUE; } } // Cannot continue retrying if the error wasn't a busy pipe. if (GetLastError() != ERROR_PIPE_BUSY) { return INVALID_HANDLE_VALUE; } if (!WaitNamedPipe(pipe_name, kPipeBusyWaitTimeoutMs)) { return INVALID_HANDLE_VALUE; } } return INVALID_HANDLE_VALUE; } } // namespace google_breakpad
{ "pile_set_name": "Github" }
[ { "op" : "add", "path" : "/effects", "value" : [ [ "meat_plant" ] ] } ]
{ "pile_set_name": "Github" }
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * Class representing a HandledErrorDetailsReasonFramesItem. */ class HandledErrorDetailsReasonFramesItem { /** * Create a HandledErrorDetailsReasonFramesItem. * @property {string} [className] name of the class * @property {string} [method] name of the method * @property {boolean} [classMethod] is a class method * @property {string} [file] name of the file * @property {number} [line] line number * @property {boolean} [appCode] this line isn't from any framework * @property {string} [frameworkName] Name of the framework * @property {string} [codeFormatted] Formatted frame string * @property {string} [codeRaw] Unformatted Frame string * @property {string} [language] programming language of the frame. Possible * values include: 'JavaScript', 'CSharp', 'Objective-C', 'Objective-Cpp', * 'Cpp', 'C', 'Swift', 'Java', 'Unknown' * @property {string} [methodParams] parameters of the frames method * @property {string} [exceptionType] Exception type. * @property {string} [osExceptionType] OS exception type. (aka. SIGNAL) */ constructor() { } /** * Defines the metadata of HandledErrorDetailsReasonFramesItem * * @returns {object} metadata of HandledErrorDetailsReasonFramesItem * */ mapper() { return { required: false, serializedName: 'HandledErrorDetails_reasonFramesItem', type: { name: 'Composite', className: 'HandledErrorDetailsReasonFramesItem', modelProperties: { className: { required: false, serializedName: 'className', type: { name: 'String' } }, method: { required: false, serializedName: 'method', type: { name: 'String' } }, classMethod: { required: false, serializedName: 'classMethod', type: { name: 'Boolean' } }, file: { required: false, serializedName: 'file', type: { name: 'String' } }, line: { required: false, serializedName: 'line', type: { name: 'Number' } }, appCode: { required: false, serializedName: 'appCode', type: { name: 'Boolean' } }, frameworkName: { required: false, serializedName: 'frameworkName', type: { name: 'String' } }, codeFormatted: { required: false, serializedName: 'codeFormatted', type: { name: 'String' } }, codeRaw: { required: false, serializedName: 'codeRaw', type: { name: 'String' } }, language: { required: false, serializedName: 'language', type: { name: 'String' } }, methodParams: { required: false, serializedName: 'methodParams', type: { name: 'String' } }, exceptionType: { required: false, serializedName: 'exceptionType', type: { name: 'String' } }, osExceptionType: { required: false, serializedName: 'osExceptionType', type: { name: 'String' } } } } }; } } module.exports = HandledErrorDetailsReasonFramesItem;
{ "pile_set_name": "Github" }
<?php /* $Id: nusoapmime.php,v 1.13 2010/04/26 20:15:08 snichol Exp $ NuSOAP - Web Services Toolkit for PHP Copyright (c) 2002 NuSphere Corporation This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA The NuSOAP project home is: http://sourceforge.net/projects/nusoap/ The primary support for NuSOAP is the mailing list: [email protected] If you have any questions or comments, please email: Dietrich Ayala [email protected] http://dietrich.ganx4.com/nusoap NuSphere Corporation http://www.nusphere.com */ /*require_once('nusoap.php');*/ /* PEAR Mail_MIME library */ require_once('Mail/mimeDecode.php'); require_once('Mail/mimePart.php'); /** * nusoap_client_mime client supporting MIME attachments defined at * http://www.w3.org/TR/SOAP-attachments. It depends on the PEAR Mail_MIME library. * * @author Scott Nichol <[email protected]> * @author Thanks to Guillaume and Henning Reich for posting great attachment code to the mail list * @version $Id: nusoapmime.php,v 1.13 2010/04/26 20:15:08 snichol Exp $ * @access public * @package External * @subpackage soap */ class nusoap_client_mime extends nusoap_client { /** * @var array Each array element in the return is an associative array with keys * data, filename, contenttype, cid * @access private */ var $requestAttachments = array(); /** * @var array Each array element in the return is an associative array with keys * data, filename, contenttype, cid * @access private */ var $responseAttachments; /** * @var string * @access private */ var $mimeContentType; /** * adds a MIME attachment to the current request. * * If the $data parameter contains an empty string, this method will read * the contents of the file named by the $filename parameter. * * If the $cid parameter is false, this method will generate the cid. * * @param string $data The data of the attachment * @param string $filename The filename of the attachment (default is empty string) * @param string $contenttype The MIME Content-Type of the attachment (default is application/octet-stream) * @param string $cid The content-id (cid) of the attachment (default is false) * @return string The content-id (cid) of the attachment * @access public */ function addAttachment($data, $filename = '', $contenttype = 'application/octet-stream', $cid = false) { if (! $cid) { $cid = md5(uniqid(time())); } $info['data'] = $data; $info['filename'] = $filename; $info['contenttype'] = $contenttype; $info['cid'] = $cid; $this->requestAttachments[] = $info; return $cid; } /** * clears the MIME attachments for the current request. * * @access public */ function clearAttachments() { $this->requestAttachments = array(); } /** * gets the MIME attachments from the current response. * * Each array element in the return is an associative array with keys * data, filename, contenttype, cid. These keys correspond to the parameters * for addAttachment. * * @return array The attachments. * @access public */ function getAttachments() { return $this->responseAttachments; } /** * gets the HTTP body for the current request. * * @param string $soapmsg The SOAP payload * @return string The HTTP body, which includes the SOAP payload * @access private */ function getHTTPBody($soapmsg) { if (count($this->requestAttachments) > 0) { $params['content_type'] = 'multipart/related; type="text/xml"'; $mimeMessage = new Mail_mimePart('', $params); unset($params); $params['content_type'] = 'text/xml'; $params['encoding'] = '8bit'; $params['charset'] = $this->soap_defencoding; $mimeMessage->addSubpart($soapmsg, $params); foreach ($this->requestAttachments as $att) { unset($params); $params['content_type'] = $att['contenttype']; $params['encoding'] = 'base64'; $params['disposition'] = 'attachment'; $params['dfilename'] = $att['filename']; $params['cid'] = $att['cid']; if ($att['data'] == '' && $att['filename'] <> '') { if ($fd = fopen($att['filename'], 'rb')) { $data = fread($fd, filesize($att['filename'])); fclose($fd); } else { $data = ''; } $mimeMessage->addSubpart($data, $params); } else { $mimeMessage->addSubpart($att['data'], $params); } } $output = $mimeMessage->encode(); $mimeHeaders = $output['headers']; foreach ($mimeHeaders as $k => $v) { $this->debug("MIME header $k: $v"); if (strtolower($k) == 'content-type') { // PHP header() seems to strip leading whitespace starting // the second line, so force everything to one line $this->mimeContentType = str_replace("\r\n", " ", $v); } } return $output['body']; } return parent::getHTTPBody($soapmsg); } /** * gets the HTTP content type for the current request. * * Note: getHTTPBody must be called before this. * * @return string the HTTP content type for the current request. * @access private */ function getHTTPContentType() { if (count($this->requestAttachments) > 0) { return $this->mimeContentType; } return parent::getHTTPContentType(); } /** * gets the HTTP content type charset for the current request. * returns false for non-text content types. * * Note: getHTTPBody must be called before this. * * @return string the HTTP content type charset for the current request. * @access private */ function getHTTPContentTypeCharset() { if (count($this->requestAttachments) > 0) { return false; } return parent::getHTTPContentTypeCharset(); } /** * processes SOAP message returned from server * * @param array $headers The HTTP headers * @param string $data unprocessed response data from server * @return mixed value of the message, decoded into a PHP type * @access private */ function parseResponse($headers, $data) { $this->debug('Entering parseResponse() for payload of length ' . strlen($data) . ' and type of ' . $headers['content-type']); $this->responseAttachments = array(); if (strstr($headers['content-type'], 'multipart/related')) { $this->debug('Decode multipart/related'); $input = ''; foreach ($headers as $k => $v) { $input .= "$k: $v\r\n"; } $params['input'] = $input . "\r\n" . $data; $params['include_bodies'] = true; $params['decode_bodies'] = true; $params['decode_headers'] = true; $structure = Mail_mimeDecode::decode($params); foreach ($structure->parts as $part) { if (!isset($part->disposition) && (strstr($part->headers['content-type'], 'text/xml'))) { $this->debug('Have root part of type ' . $part->headers['content-type']); $root = $part->body; $return = parent::parseResponse($part->headers, $part->body); } else { $this->debug('Have an attachment of type ' . $part->headers['content-type']); $info['data'] = $part->body; $info['filename'] = isset($part->d_parameters['filename']) ? $part->d_parameters['filename'] : ''; $info['contenttype'] = $part->headers['content-type']; $info['cid'] = $part->headers['content-id']; $this->responseAttachments[] = $info; } } if (isset($return)) { $this->responseData = $root; return $return; } $this->setError('No root part found in multipart/related content'); return ''; } $this->debug('Not multipart/related'); return parent::parseResponse($headers, $data); } } /* * For backwards compatiblity, define soapclientmime unless the PHP SOAP extension is loaded. */ if (!extension_loaded('soap')) { class soapclientmime extends nusoap_client_mime { } } /** * nusoap_server_mime server supporting MIME attachments defined at * http://www.w3.org/TR/SOAP-attachments. It depends on the PEAR Mail_MIME library. * * @author Scott Nichol <[email protected]> * @author Thanks to Guillaume and Henning Reich for posting great attachment code to the mail list * @version $Id: nusoapmime.php,v 1.13 2010/04/26 20:15:08 snichol Exp $ * @access public */ class nusoap_server_mime extends nusoap_server { /** * @var array Each array element in the return is an associative array with keys * data, filename, contenttype, cid * @access private */ var $requestAttachments = array(); /** * @var array Each array element in the return is an associative array with keys * data, filename, contenttype, cid * @access private */ var $responseAttachments; /** * @var string * @access private */ var $mimeContentType; /** * adds a MIME attachment to the current response. * * If the $data parameter contains an empty string, this method will read * the contents of the file named by the $filename parameter. * * If the $cid parameter is false, this method will generate the cid. * * @param string $data The data of the attachment * @param string $filename The filename of the attachment (default is empty string) * @param string $contenttype The MIME Content-Type of the attachment (default is application/octet-stream) * @param string $cid The content-id (cid) of the attachment (default is false) * @return string The content-id (cid) of the attachment * @access public */ function addAttachment($data, $filename = '', $contenttype = 'application/octet-stream', $cid = false) { if (! $cid) { $cid = md5(uniqid(time())); } $info['data'] = $data; $info['filename'] = $filename; $info['contenttype'] = $contenttype; $info['cid'] = $cid; $this->responseAttachments[] = $info; return $cid; } /** * clears the MIME attachments for the current response. * * @access public */ function clearAttachments() { $this->responseAttachments = array(); } /** * gets the MIME attachments from the current request. * * Each array element in the return is an associative array with keys * data, filename, contenttype, cid. These keys correspond to the parameters * for addAttachment. * * @return array The attachments. * @access public */ function getAttachments() { return $this->requestAttachments; } /** * gets the HTTP body for the current response. * * @param string $soapmsg The SOAP payload * @return string The HTTP body, which includes the SOAP payload * @access private */ function getHTTPBody($soapmsg) { if (count($this->responseAttachments) > 0) { $params['content_type'] = 'multipart/related; type="text/xml"'; $mimeMessage = new Mail_mimePart('', $params); unset($params); $params['content_type'] = 'text/xml'; $params['encoding'] = '8bit'; $params['charset'] = $this->soap_defencoding; $mimeMessage->addSubpart($soapmsg, $params); foreach ($this->responseAttachments as $att) { unset($params); $params['content_type'] = $att['contenttype']; $params['encoding'] = 'base64'; $params['disposition'] = 'attachment'; $params['dfilename'] = $att['filename']; $params['cid'] = $att['cid']; if ($att['data'] == '' && $att['filename'] <> '') { if ($fd = fopen($att['filename'], 'rb')) { $data = fread($fd, filesize($att['filename'])); fclose($fd); } else { $data = ''; } $mimeMessage->addSubpart($data, $params); } else { $mimeMessage->addSubpart($att['data'], $params); } } $output = $mimeMessage->encode(); $mimeHeaders = $output['headers']; foreach ($mimeHeaders as $k => $v) { $this->debug("MIME header $k: $v"); if (strtolower($k) == 'content-type') { // PHP header() seems to strip leading whitespace starting // the second line, so force everything to one line $this->mimeContentType = str_replace("\r\n", " ", $v); } } return $output['body']; } return parent::getHTTPBody($soapmsg); } /** * gets the HTTP content type for the current response. * * Note: getHTTPBody must be called before this. * * @return string the HTTP content type for the current response. * @access private */ function getHTTPContentType() { if (count($this->responseAttachments) > 0) { return $this->mimeContentType; } return parent::getHTTPContentType(); } /** * gets the HTTP content type charset for the current response. * returns false for non-text content types. * * Note: getHTTPBody must be called before this. * * @return string the HTTP content type charset for the current response. * @access private */ function getHTTPContentTypeCharset() { if (count($this->responseAttachments) > 0) { return false; } return parent::getHTTPContentTypeCharset(); } /** * processes SOAP message received from client * * @param array $headers The HTTP headers * @param string $data unprocessed request data from client * @return mixed value of the message, decoded into a PHP type * @access private */ function parseRequest($headers, $data) { $this->debug('Entering parseRequest() for payload of length ' . strlen($data) . ' and type of ' . $headers['content-type']); $this->requestAttachments = array(); if (strstr($headers['content-type'], 'multipart/related')) { $this->debug('Decode multipart/related'); $input = ''; foreach ($headers as $k => $v) { $input .= "$k: $v\r\n"; } $params['input'] = $input . "\r\n" . $data; $params['include_bodies'] = true; $params['decode_bodies'] = true; $params['decode_headers'] = true; $structure = Mail_mimeDecode::decode($params); foreach ($structure->parts as $part) { if (!isset($part->disposition) && (strstr($part->headers['content-type'], 'text/xml'))) { $this->debug('Have root part of type ' . $part->headers['content-type']); $return = parent::parseRequest($part->headers, $part->body); } else { $this->debug('Have an attachment of type ' . $part->headers['content-type']); $info['data'] = $part->body; $info['filename'] = isset($part->d_parameters['filename']) ? $part->d_parameters['filename'] : ''; $info['contenttype'] = $part->headers['content-type']; $info['cid'] = $part->headers['content-id']; $this->requestAttachments[] = $info; } } if (isset($return)) { return $return; } $this->setError('No root part found in multipart/related content'); return; } $this->debug('Not multipart/related'); return parent::parseRequest($headers, $data); } } /* * For backwards compatiblity */ class nusoapservermime extends nusoap_server_mime { } ?>
{ "pile_set_name": "Github" }
gcr.io/google_containers/kube-aggregator-arm:v1.9.2-beta.0
{ "pile_set_name": "Github" }
--- addr: '0xbc63acdfafa94bd4d8c2bb7a8552281f107242c0' decimals: 18 description: >- CriptoSocial was successful in its beta version, and to commemorate, it incorporated into its platform a token, the MaxxToken, which will be distributed 50% in airdrop, 10% in ICO (to enter it into exchanges and develop mobile applications) and 40% bonus in CriptoSocialCriptoSocial is a social network aimed at the public of crypto-currencies, so that its users share their experiences, but hear an event that made everything change, the users started to do project marketing and serve ads, using the points of refference of the platform, transforming the platform into much more than a simple social network, but in a marketing platform with centralized target public, so we decided to create a decentralized token to subsidize our users with something that they can use beyond the borders of CriptoSocial. links: - Website: https://airdrop.criptosocial.com.br name: MaxxToken symbol: MXX
{ "pile_set_name": "Github" }
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import { IndexLink } from 'react-router'; import { usage, todo } from './styles'; import { example, p, link } from '../homepage/styles'; import { setConfig } from '../../actions'; class Usage extends Component { /*eslint-disable */ static onEnter({store, nextState, replaceState, callback}) { fetch('/api/v1/conf').then((r) => { return r.json(); }).then((conf) => { store.dispatch(setConfig(conf)); console.log('Faked connection latency! Please, take a look ---> `server/api.go:22`'); callback(); }); } /*eslint-enable */ render() { return <div className={usage}> <Helmet title='Usage' /> <h2 className={example}>Usage:</h2> <div className={p}> <span className={todo}>// TODO: write an article</span> <pre className={todo}>config: {JSON.stringify(this.props.config, null, 2)}</pre> </div> <br /> go <IndexLink to='/' className={link}>home</IndexLink> </div>; } } export default connect(store => ({ config: store.config }))(Usage);
{ "pile_set_name": "Github" }
_This file was generated programmatically using the `meta/exhibitions-glossary.json` document._ count_objects == count_objects_public == date_end == date_start == department_id == id == is_active == text == title == url == videos == videos.description == videos.dimensions == videos.formats == videos.formats.mp4 == videos.formats.mp4.1080 == videos.formats.mp4.1080_subtitled == videos.formats.mp4.720 == videos.formats.mp4.720_subtitled == videos.id == videos.image_fingerprints == videos.secret == videos.secret_o == videos.sq_offset == videos.srt == videos.title == videos.video_fingerprint == videos.youtube_url ==
{ "pile_set_name": "Github" }
--- author: catalin type: normal category: must-know tags: - introduction - workout links: - >- [www.hacksparrow.com](http://www.hacksparrow.com/node-js-exports-vs-module-exports.html){website} --- # `exports` vs. `module.exports` in **Node** --- ## Content Exporting a module in **Node** can be done in different ways. The most common is using the `exports` object: ```javascript //what is exported (other.js) exports.say = function() { console.log('Hello from Enki!'); }; //how to import var sample = require('./other.js'); sample.say(); // 'Hello from Enki!' ``` However, `exports` is just a helper for `module.exports`. The latter is ultimately returned by your module when called. `exports` only collects properties and attaches them to `module.exports` if and only if it doesn't have something on it already. ```javascript module.exports = 'Oops!'; exports.say = function() { console.log('Hello from Enki!'); } ``` If we import it the same way as above, this will result in a `TypeError` because `module.exports` already had something in it. Export an array with `module.exports`: ```javascript module.exports = [ 'A', 'B', 'C']; var sample = require('./other.js'); console.log(sample[2]); // 'C' ``` --- ## Practice What is the output of the following JavaScript code? ??? ```javascript module.exports = ['a', 'k', 'K', 'y', 'a']; var test = require('./other.js'); console.log(test[2]); console.log(test[4]); console.log(test[3]); console.log(test[0]); console.log(test[1]); ``` - Kayak - kayak - kayaK - ayakK - yakaK --- ## Revision `exports` is a helper for? ??? - module.exports - module.imports - module - imports
{ "pile_set_name": "Github" }
# Order matters here. Interface files rely on library files, and # component implementations rely on both the interfaces and the libs $(info components makeflag $(MAKEFLAGS)) MAKEFLAGS=-I$(shell pwd) ENABLE_STK:=${shell grep ENABLE_STACK_MANAGER include/cos_stkmgr_configure.h | awk '{print $$3 }' } #$(info ENABLE_STK = "${ENABLE_STK}") ifeq ($(ENABLE_STK), 1) export ENABLE_STACK_MANAGER:=1 endif ifdef ENABLE_STACK_MANAGER $(info ####### Stack Manager is Enabled #######) else $(info ####### Stack Manager is Disabled #######) endif all: make $(MAKEFLAGS) -C lib make $(MAKEFLAGS) -C interface make $(MAKEFLAGS) -C implementation cp: make $(MAKEFLAGS) -C implementation cp clean: make $(MAKEFLAGS) -C lib clean make $(MAKEFLAGS) -C interface clean make $(MAKEFLAGS) -C implementation clean distclean: make $(MAKEFLAGS) -C lib distclean init: make $(MAKEFLAGS) -C lib init make $(MAKEFLAGS) -C interface init make $(MAKEFLAGS) -C implementation init idl: $(MAKE) $(MAKEFLAGS) -C interface idl
{ "pile_set_name": "Github" }
#include <Python.h> //////////////////////////////////////// // Methods //////////////////////////////////////// static PyObject* hello_world(PyObject *self, PyObject *args) { return Py_BuildValue("s", "Hello World"); } //////////////////////////////////////// // Module Definition //////////////////////////////////////// PyDoc_STRVAR(module_doc, "Simple 'Hello World' Module"); static PyMethodDef methods[] = { { "hello_world", hello_world, METH_VARARGS, "Say hello." }, {NULL, NULL}, }; static PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, // PyModuleDef_HEAD_INIT "hello", // module name module_doc, // docstring 0, // size of per-module area methods, // methods (table of module-level functions) NULL, // array of slot definitions NULL, // traverse function for GC NULL, // clear function for GC NULL // deallocation function }; PyMODINIT_FUNC PyInit_hello(void) { return PyModule_Create(&moduledef); } ////////////////////////////////////////
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>Test</title> <style> #content-image:before { content: url(icon1x.jpg); content: -webkit-image-set(url(icon1x.jpg) 1x, url(icon2x.jpg) 2x); } </style> </head> <body> <div id="content-image"></div> </body> </html>
{ "pile_set_name": "Github" }
/***************************************************************************** * EventHandler.java ***************************************************************************** * Copyright © 2011-2014 VLC authors and VideoLAN * * 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 2.1 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.videolan.libvlc; import android.os.Bundle; import android.os.Handler; import android.os.Message; import java.util.ArrayList; public class EventHandler { /* * Be sure to subscribe to events you need in the JNI too. */ //public static final int MediaMetaChanged = 0; //public static final int MediaSubItemAdded = 1; //public static final int MediaDurationChanged = 2; public static final int MediaParsedChanged = 3; //public static final int MediaFreed = 4; //public static final int MediaStateChanged = 5; //public static final int MediaPlayerMediaChanged = 0x100; //public static final int MediaPlayerNothingSpecial = 0x101; //public static final int MediaPlayerOpening = 0x102; public static final int MediaPlayerBuffering = 0x103; public static final int MediaPlayerPlaying = 0x104; public static final int MediaPlayerPaused = 0x105; public static final int MediaPlayerStopped = 0x106; //public static final int MediaPlayerForward = 0x107; //public static final int MediaPlayerBackward = 0x108; public static final int MediaPlayerEndReached = 0x109; public static final int MediaPlayerEncounteredError = 0x10a; public static final int MediaPlayerTimeChanged = 0x10b; public static final int MediaPlayerPositionChanged = 0x10c; //public static final int MediaPlayerSeekableChanged = 0x10d; //public static final int MediaPlayerPausableChanged = 0x10e; //public static final int MediaPlayerTitleChanged = 0x10f; //public static final int MediaPlayerSnapshotTaken = 0x110; public static final int MediaPlayerLengthChanged = 0x111; public static final int MediaPlayerVout = 0x112; //public static final int MediaListItemAdded = 0x200; //public static final int MediaListWillAddItem = 0x201; //public static final int MediaListItemDeleted = 0x202; //public static final int MediaListWillDeleteItem = 0x203; //public static final int MediaListViewItemAdded = 0x300; //public static final int MediaListViewWillAddItem = 0x301; //public static final int MediaListViewItemDeleted = 0x302; //public static final int MediaListViewWillDeleteItem = 0x303; //public static final int MediaListPlayerPlayed = 0x400; //public static final int MediaListPlayerNextItemSet = 0x401; //public static final int MediaListPlayerStopped = 0x402; //public static final int MediaDiscovererStarted = 0x500; //public static final int MediaDiscovererEnded = 0x501; //public static final int VlmMediaAdded = 0x600; //public static final int VlmMediaRemoved = 0x601; //public static final int VlmMediaChanged = 0x602; //public static final int VlmMediaInstanceStarted = 0x603; //public static final int VlmMediaInstanceStopped = 0x604; //public static final int VlmMediaInstanceStatusInit = 0x605; //public static final int VlmMediaInstanceStatusOpening = 0x606; //public static final int VlmMediaInstanceStatusPlaying = 0x607; //public static final int VlmMediaInstanceStatusPause = 0x608; //public static final int VlmMediaInstanceStatusEnd = 0x609; //public static final int VlmMediaInstanceStatusError = 0x60a; public static final int CustomMediaListExpanding = 0x2000; public static final int CustomMediaListExpandingEnd = 0x2001; public static final int CustomMediaListItemAdded = 0x2002; public static final int CustomMediaListItemDeleted = 0x2003; public static final int CustomMediaListItemMoved = 0x2004; public static final int HardwareAccelerationError = 0x3000; private ArrayList<Handler> mEventHandler; private static EventHandler mInstance; EventHandler() { mEventHandler = new ArrayList<Handler>(); } public static EventHandler getInstance() { if (mInstance == null) { mInstance = new EventHandler(); } return mInstance; } public void addHandler(Handler handler) { if (!mEventHandler.contains(handler)) mEventHandler.add(handler); } public void removeHandler(Handler handler) { mEventHandler.remove(handler); } /** This method is called by a native thread **/ public void callback(int event, Bundle b) { b.putInt("event", event); for (int i = 0; i < mEventHandler.size(); i++) { Message msg = Message.obtain(); msg.setData(b); mEventHandler.get(i).sendMessage(msg); } } }
{ "pile_set_name": "Github" }
# Calamares Release Process <!-- SPDX-FileCopyrightText: 2015 Teo Mrnjavac <[email protected]> SPDX-FileCopyrightText: 2017 Adriaan de Groot <[email protected]> SPDX-License-Identifier: GPL-3.0-or-later --> > Calamares releases are now rolling when-they-are-ready releases. > Releases are made from *calamares* and tagged there. When, in future, > LTS releases resume, these steps may be edited again. > > Most things are automated through the release script [RELEASE.sh](RELEASE.sh) ## (1) Preparation * Make sure all tests pass. ``` make make test ``` Note that *all* means all-that-make-sense. The partition-manager tests need an additional environment variable to be set for some tests, which will destroy an attached disk. This is not always desirable. There are some sample config-files that are empty and which fail the config-tests. * Pull latest translations from Transifex. We only push / pull translations from master, so longer-lived branches (e.g. 3.1.x) don't get translation updates. This is to keep the translation workflow simple. The script automatically commits changes to the translations. ``` sh ci/txpull.sh ``` * Update the list of enabled translation languages in `CMakeLists.txt`. Check the [translation site][transifex] for the list of languages with fairly complete translations, or use `ci/txstats.py` for an automated suggestion. If there are changes, commit them. * Push the changes. * Check defaults in `settings.conf` and other configuration files. * Drop the RC variable to 0 in `CMakeLists.txt`, *CALAMARES_VERSION_RC*. * Edit `CHANGES` and set the date of the release. * Commit both. This is usually done with commit-message *Changes: pre-release housekeeping*. ## (2) Release Day * Run the helper script `ci/RELEASE.sh` or follow steps below. The script checks: - for uncommitted local changes, - if translations are up-to-date and translators have had enough time to chase new strings, - that the build is successful (with gcc and clang, if available), - tests pass, - tarball can be created, - tarball can be signed. On success, it prints out a suitable signature- and SHA256 blurb for use in the release announcement. ## (3) Release Follow the instructions printed by the release script. * Push the tags. * Create a new release on GitHub. * Upload tarball and signature. * Publish release article on `calamares.io`. * Close associated milestone on GitHub if it's entirely done. * Update topic on #calamares IRC channel. ## (4) Post-Release * Bump the version number in `CMakeLists.txt` in the `project()` command. * Set *CALAMARES_VERSION_RC* back to 1. * Add a placeholder entry for the next release in `CHANGES` with date text *not released yet*. * Commit and push that, usually with the message *Changes: post-release housekeeping*. ``` # 3.2.XX (unreleased) # This release contains contributions from (alphabetically by first name): - No external contributors yet ## Core ## - No core changes yet ## Modules ## - No module changes yet ``` # Related Material > This section isn't directly related to any specific release, > but bears on all releases. ## GPG Key Maintainence Calamares uses GPG Keys for signing the tarballs and some commits (tags, mostly). Calamares uses the **maintainer's** personal GPG key for this. This section details some GPG activities that the maintainer should do with those keys. - Signing sub-key. It's convenient to use a signing sub-key specifically for the signing of Calamares. To do so, add a key to the private key. It's recommended to use key expiry, and to update signing keys periodically. - Run `gpg -K` to find the key ID of your personal GPG secret key. - Run `gpg --edit-key <keyid>` to edit that personal GPG key. - In gpg edit-mode, use `addkey`, then pick a key type that is *sign-only* (e.g. type 4, *RSA (sign only)*), then pick a keysize (3072 seems ok as of 2020) and set a key expiry time, (e.g. in 18 months time). - After generation, the secret key information is printed again, now including the new signing subkey: ``` ssb rsa3072/0xCFDDC96F12B1915C created: 2020-07-11 expires: 2022-01-02 usage: S ``` - Update the `RELEASE.sh` script with a new signing sub-key ID when a new one is generated. Also announce the change of signing sub-key (e.g. on the Calmares site or as part of a release announcement). - Send the updated key to keyservers with `gpg --send-keys <keyid>` - Optional: sanitize the keyring for use in development machines. Export the current subkeys of the master key and keep **only** those secret keys around. There is documentation [here](https://blog.tinned-software.net/create-gnupg-key-with-sub-keys-to-sign-encrypt-authenticate/) but be careful. - Export the public key material with `gpg --export --armor <keyid>`, possibly also setting an output file. - Upload that public key to the relevant GitHub profile. - Upload that public key to the Calamares site.
{ "pile_set_name": "Github" }
{% if theme.google_analytics %} <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '{{ theme.google_analytics }}', 'auto'); ga('send', 'pageview'); </script> {% endif %}
{ "pile_set_name": "Github" }
{# Annotations #} <style> .hide-title { opacity: 0.5; } .hide-title:hover { opacity: 1; } .hide-title input { position: relative; top: -2px; } </style> <div class="vis-option-type-group group-open"> <label class="group-title"> <i class="fa fa-chevron-up expand-group pull-right"></i> <i class="fa fa-chevron-down collapse-group pull-right"></i> {% trans "annotate / title" %}</label> <div class="option-group-content vis-option-type-chart-description"> <div class="story-title control-group"> <div style="position:relative"> <label class="hide-title" style="display: block;position: absolute;right: 0;top: 0;font-size: 12px;color: #777;" class="checkbox"> <input id="hide-title" type="checkbox">&nbsp;{% trans "annotate / hide-title" %} </label> <label class="control-label" for="text-title">{% trans "Title" %}</label> <input type="text" id="text-title" class="input-xlarge span4" /> <label class="control-label" for="text-intro">{% trans "Description" %}</label> <textarea type="text" id="text-intro" class="input-xlarge span4"></textarea> <label class="control-label" for="text-notes">{% trans "Notes" %}</label> <input type="text" id="text-notes" class="input-xlarge span4" /> </div> <div class="row"> <div class="span2"> <label class="control-label">{% trans "Source name" %}</label> <input {% if chart.isFork %}disabled{% endif %} id="describe-source-name" type="text" class="span2" placeholder="{% trans "name of the organisation" %}"> </div> <div class="span2"> <label class="control-label">{% trans "Source URL" %}</label> <input {% if chart.isFork %}disabled{% endif %} id="describe-source-url" type="text" class="span2" placeholder="{% trans "URL of the dataset" %}"> </div> </div> {% if not chart.organization or chart.organization.settings('flags.byline') != false %} <div class="chart-byline"> <label class="control-label">{% trans "visualize / annotate / byline" %}</label> <input id="describe-byline" type="text" class="input-xlarge span4" placeholder="{% trans "visualize / annotate / byline / placeholder" %}"> </div> {% endif %} </div> </div> </div> {{ hook('custom_annotation_controls', chart) }} {{ hook('after_custom_annotation_controls', vis) }} {% if vis.annotate_options %} {% for key, option in vis.annotate_options %} {% if option.type == 'group' %} <div id="vis-options-{{ key }}" data-group-key="{{ key }}" class="vis-option-type-group{% if option.open %} group-open{% endif %}"> <label class="group-title"> {{ option.label|raw }} <i class="fa fa-chevron-up expand-group pull-right"></i> <i class="fa fa-chevron-down collapse-group pull-right"></i> </label> <div class="option-group-content"> {% for key, option in option.options %} {{ block('option') }} {% endfor %} </div> </div> {% else %} {{ block('option') }} {% endif %} {% endfor %} {% else %} <div class="vis-option-type-group group-open"> <label class="group-title"> {% trans "annotate / highlight element" %} <i class="fa fa-chevron-up expand-group pull-right"></i> <i class="fa fa-chevron-down collapse-group pull-right"></i> </label> <div class="option-group-content highlight-elements"> {{ svelte('highlight', {'chart': chart }) }} </div> </div> {% endif %} {% block option %} {% if theme['option-filter'][vis.id][key] or (not option.hidden and not option.expert) %} <div class="control-group vis-option-group vis-option-type-{{ option.type }}{% if option.inline %} inline{% endif %}" id="vis-options-{{ key }}"> {% if option.help %} <a title="{{ option.help }}" class="vis-option-help"><span>?</span></a> {% endif %} {{ hook('vis_option_controls', option, key) }} </div> {% endif %} {% endblock %}
{ "pile_set_name": "Github" }
import React from "react"; import { presentWallet, presentNode, presentFarmer, changeMainMenu, presentTrading, presentPlotter } from "../modules/mainMenu"; import { useSelector } from "react-redux"; import { logOut } from "../modules/message"; import { useDispatch } from "react-redux"; import List from "@material-ui/core/List"; import Divider from "@material-ui/core/Divider"; import { changeEntranceMenu, presentSelectKeys } from "../modules/entranceMenu"; import walletSidebarLogo from "../assets/img/wallet_sidebar.svg"; // Tell webpack this JS file uses this image import farmSidebarLogo from "../assets/img/farm_sidebar.svg"; import helpSidebarLogo from "../assets/img/help_sidebar.svg"; import homeSidebarLogo from "../assets/img/home_sidebar.svg"; import plotSidebarLogo from "../assets/img/plot_sidebar.svg"; import poolSidebarLogo from "../assets/img/pool_sidebar.svg"; import { makeStyles } from "@material-ui/core/styles"; const useStyles = makeStyles(theme => ({ div: { textAlign: "center", cursor: "pointer" }, label: { fontFamily: "Roboto", fontWeight: "300", fontSize: "16px", fontStyle: "normal", marginTop: "5px" }, labelChosen: { fontFamily: "Roboto", fontWeight: "500", fontSize: "16px", fontStyle: "normal", marginTop: "5px" } })); const menuItems = [ { label: "Full Node", present: presentNode, icon: <img src={homeSidebarLogo} alt="Logo" /> }, { label: "Wallets", present: presentWallet, icon: <img src={walletSidebarLogo} alt="Logo" /> }, { label: "Plot", present: presentPlotter, icon: <img src={plotSidebarLogo} alt="Logo" /> }, { label: "Farm", present: presentFarmer, icon: <img src={farmSidebarLogo} alt="Logo" /> }, { label: "Trade", present: presentTrading, icon: <img src={poolSidebarLogo} alt="Logo" /> }, { label: "Keys", changeKeys: true, icon: <img src={helpSidebarLogo} alt="Logo" /> } ]; const MenuItem = (menuItem, currentView) => { const classes = useStyles(); const dispatch = useDispatch(); const item = menuItem; function presentMe() { if (item.changeKeys) { dispatch(logOut("log_out", {})); dispatch(changeEntranceMenu(presentSelectKeys)); } else { dispatch(changeMainMenu(item.present)); } } const labelClass = currentView === item.present ? classes.labelChosen : classes.label; return ( <div className={classes.div} onClick={presentMe} key={item.label}> {item.icon} <p className={labelClass}>{item.label}</p> </div> ); }; export const SideBar = () => { const currentView = useSelector(state => state.main_menu.view); return ( <div> <List>{menuItems.map(item => MenuItem(item, currentView))}</List> <Divider /> </div> ); };
{ "pile_set_name": "Github" }
blank_issues_enabled: true # contact_links: # - name: Samuel Gratzl # url: https://www.sgratzl.com # about: Please ask and answer questions here.
{ "pile_set_name": "Github" }
<Project> <PropertyGroup Condition="'$(Configuration)'=='Release'"> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings> </PropertyGroup> <PropertyGroup> <CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)\CodeAnalysis\CodeAnalysis.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <PropertyGroup> <LangVersion>7.1</LangVersion> </PropertyGroup> <ItemGroup> <AdditionalFiles Include="$(MSBuildThisFileDirectory)\CodeAnalysis\Menees.Analyzers.Settings.xml" /> </ItemGroup> </Project>
{ "pile_set_name": "Github" }
{ "api": { "BackgroundFetchRecord": { "__compat": { "mdn_url": "https://developer.mozilla.org/docs/Web/API/BackgroundFetchRecord", "support": { "chrome": { "version_added": "74" }, "chrome_android": { "version_added": "74" }, "edge": { "version_added": false }, "firefox": { "version_added": false }, "firefox_android": { "version_added": false }, "ie": { "version_added": false }, "opera": { "version_added": "62" }, "opera_android": { "version_added": "53" }, "safari": { "version_added": false }, "safari_ios": { "version_added": false }, "samsunginternet_android": { "version_added": "11.0" }, "webview_android": { "version_added": false } }, "status": { "experimental": true, "standard_track": true, "deprecated": false } }, "request": { "__compat": { "mdn_url": "https://developer.mozilla.org/docs/Web/API/BackgroundFetchRecord/request", "support": { "chrome": { "version_added": "74" }, "chrome_android": { "version_added": "74" }, "edge": { "version_added": false }, "firefox": { "version_added": false }, "firefox_android": { "version_added": false }, "ie": { "version_added": false }, "opera": { "version_added": "62" }, "opera_android": { "version_added": "53" }, "safari": { "version_added": false }, "safari_ios": { "version_added": false }, "samsunginternet_android": { "version_added": "11.0" }, "webview_android": { "version_added": false } }, "status": { "experimental": true, "standard_track": true, "deprecated": false } } }, "responseReady": { "__compat": { "mdn_url": "https://developer.mozilla.org/docs/Web/API/BackgroundFetchRecord/responseReady", "support": { "chrome": { "version_added": "74" }, "chrome_android": { "version_added": "74" }, "edge": { "version_added": false }, "firefox": { "version_added": false }, "firefox_android": { "version_added": false }, "ie": { "version_added": false }, "opera": { "version_added": "62" }, "opera_android": { "version_added": "53" }, "safari": { "version_added": false }, "safari_ios": { "version_added": false }, "samsunginternet_android": { "version_added": "11.0" }, "webview_android": { "version_added": false } }, "status": { "experimental": true, "standard_track": true, "deprecated": false } } } } } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd"> <!-- Copyright © 1991-2016 Unicode, Inc. For terms of use, see http://www.unicode.org/copyright.html Unicode and the Unicode Logo are registered trademarks of Unicode, Inc. in the U.S. and other countries. CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/) --> <ldml> <identity> <version number="$Revision: 12740 $"/> <language type="en"/> <territory type="SZ"/> </identity> <dates> <timeZoneNames> <metazone type="Africa_Central"> <short> <standard>CAT</standard> </short> </metazone> <metazone type="Africa_Eastern"> <short> <standard>EAT</standard> </short> </metazone> <metazone type="Africa_Southern"> <short> <standard>SAST</standard> </short> </metazone> <metazone type="Africa_Western"> <short> <generic>WAT</generic> <standard>WAT</standard> <daylight>WAST</daylight> </short> </metazone> </timeZoneNames> </dates> <numbers> <currencies> <currency type="SZL"> <symbol>E</symbol> </currency> </currencies> </numbers> </ldml>
{ "pile_set_name": "Github" }
azure.cosmos package ==================== Submodules ---------- .. toctree:: azure.cosmos.diagnostics azure.cosmos.errors azure.cosmos.http_constants Module contents --------------- .. automodule:: azure.cosmos :members: :undoc-members: :show-inheritance:
{ "pile_set_name": "Github" }
// RUN: %clang_cc1 -fsyntax-only -verify %s int test(int, char**) { bool signed; // expected-error {{'bool' cannot be signed or unsigned}} expected-warning {{declaration does not declare anything}} return 0; }
{ "pile_set_name": "Github" }
package com.aralink.sslsignature.sso.jwt; import io.jsonwebtoken.impl.crypto.MacProvider; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.Key; import javax.crypto.spec.SecretKeySpec; public class HMACKeyContainer { private Key key; public HMACKeyContainer()throws IOException{ this(null); } public HMACKeyContainer(String keyFile) throws IOException{ if (keyFile == null || keyFile.length()==0){ keyFile = "jwthmac.key"; } Path path = Paths.get(keyFile); if (!path.toFile().exists()){ //File not exists. Create new File generateKey(path); } else { //Reads the HMAC key from file byte[] data = Files.readAllBytes(path); key = hmacKeyFromEncoded(data); System.out.println("init HMAC key from file: "+path.toAbsolutePath()); } } public Key getHmacKey(){ return key; } private Key generateKey(Path path) throws IOException{ //path..createNewFile(); key = MacProvider.generateKey(JWTManager.DEFAULT_HMAC_KEY_ALGORITHM); byte data[] = key.getEncoded(); Files.write(path, data); System.out.println("created new HMAC key in file: "+path.toAbsolutePath()); return key; } public static Key hmacKeyFromEncoded(byte encodedHmacKey[]){ if (encodedHmacKey != null && encodedHmacKey.length>0){ Key key = new SecretKeySpec(encodedHmacKey,JWTManager.DEFAULT_HMAC_KEY_ALGORITHM.getJcaName()); return key; } return null; } }
{ "pile_set_name": "Github" }
/* Auto-generated by generate-wrappers.py script. Do not modify */ #if defined(__arm__) || defined(__aarch64__) #include <u8maxpool/16x9p8q-neon.c> #endif /* defined(__arm__) || defined(__aarch64__) */
{ "pile_set_name": "Github" }
/* * Copyright 2009-2020 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 * * https://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.springframework.integration.monitor; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.junit.Test; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.GenericMessage; /** * @author Dave Syer * @author Gary Russell * @author Artem Bilan */ public class HandlerMonitoringIntegrationTests { private static final Log logger = LogFactory.getLog(HandlerMonitoringIntegrationTests.class); private MessageChannel channel; private Service service; private IntegrationMBeanExporter messageHandlersMonitor; public void setMessageHandlersMonitor(IntegrationMBeanExporter messageHandlersMonitor) { this.messageHandlersMonitor = messageHandlersMonitor; } public void setService(Service service) { this.service = service; } @Test public void testSendAndHandleWithEndpointName() { // The handler monitor is registered under the endpoint id (since it is explicit) doTest("explicit-handler.xml", "input", "explicit"); } @Test public void testSendAndHandleWithAnonymousHandler() { doTest("anonymous-handler.xml", "anonymous", "anonymous"); } @Test public void testSendAndHandleWithProxiedHandler() { doTest("proxy-handler.xml", "anonymous", "anonymous"); } @Test public void testErrorLogger() { ClassPathXmlApplicationContext context = createContext("anonymous-handler.xml", "anonymous"); try { assertThat(Arrays.asList(messageHandlersMonitor.getHandlerNames()).contains("errorLogger")).isTrue(); } finally { context.close(); } } private void doTest(String config, String channelName, String monitor) { ClassPathXmlApplicationContext context = createContext(config, channelName); try { int before = service.getCounter(); channel.send(new GenericMessage<>("bar")); assertThat(service.getCounter()).isEqualTo(before + 1); } finally { context.close(); } } private ClassPathXmlApplicationContext createContext(String config, String channelName) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config, getClass()); context.getAutowireCapableBeanFactory() .autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); channel = context.getBean(channelName, MessageChannel.class); return context; } public interface Service { void execute(String input) throws Exception; int getCounter(); } public static class SimpleService implements Service { private int counter; @Override public void execute(String input) throws Exception { Thread.sleep(10L); // make the duration non-zero this.counter++; } @Override public int getCounter() { return counter; } } @Aspect public static class HandlerInterceptor { @Before("execution(* *..*Tests*(String)) && args(input)") public void around(String input) { logger.debug("Handling: " + input); } } }
{ "pile_set_name": "Github" }
// license:BSD-3-Clause // copyright-holders:Tyler J. Stachecki,Ryan Holtz inline rsp_vec_t vec_vch(rsp_vec_t vs, rsp_vec_t vt, rsp_vec_t zero, rsp_vec_t *ge, rsp_vec_t *le, rsp_vec_t *eq, rsp_vec_t *sign, rsp_vec_t *vce) { // sign = (vs ^ vt) < 0 *sign = _mm_xor_si128(vs, vt); *sign = _mm_cmplt_epi16(*sign, zero); // sign_negvt = sign ? -vt : vt rsp_vec_t sign_negvt = _mm_xor_si128(vt, *sign); sign_negvt = _mm_sub_epi16(sign_negvt, *sign); // Compute diff, diff_zero: rsp_vec_t diff = _mm_sub_epi16(vs, sign_negvt); rsp_vec_t diff_zero = _mm_cmpeq_epi16(diff, zero); // Compute le/ge: rsp_vec_t vt_neg = _mm_cmplt_epi16(vt, zero); rsp_vec_t diff_lez = _mm_cmpgt_epi16(diff, zero); rsp_vec_t diff_gez = _mm_or_si128(diff_lez, diff_zero); diff_lez = _mm_cmpeq_epi16(zero, diff_lez); #if (defined(__SSE4_1__) || defined(_MSC_VER)) *ge = _mm_blendv_epi8(diff_gez, vt_neg, *sign); *le = _mm_blendv_epi8(vt_neg, diff_lez, *sign); #else *ge = _mm_and_si128(*sign, vt_neg); diff_gez = _mm_andnot_si128(*sign, diff_gez); *ge = _mm_or_si128(*ge, diff_gez); *le = _mm_and_si128(*sign, diff_lez); diff_lez = _mm_andnot_si128(*sign, vt_neg); *le = _mm_or_si128(*le, diff_lez); #endif // Compute vce: *vce = _mm_cmpeq_epi16(diff, *sign); *vce = _mm_and_si128(*vce, *sign); // Compute !eq: *eq = _mm_or_si128(diff_zero, *vce); *eq = _mm_cmpeq_epi16(*eq, zero); // Compute result: #if (defined(__SSE4_1__) || defined(_MSC_VER)) rsp_vec_t diff_sel_mask = _mm_blendv_epi8(*ge, *le, *sign); return _mm_blendv_epi8(vs, sign_negvt, diff_sel_mask); #else diff_lez = _mm_and_si128(*sign, *le); diff_gez = _mm_andnot_si128(*sign, *ge); rsp_vec_t diff_sel_mask = _mm_or_si128(diff_lez, diff_gez); diff_lez = _mm_and_si128(diff_sel_mask, sign_negvt); diff_gez = _mm_andnot_si128(diff_sel_mask, vs); return _mm_or_si128(diff_lez, diff_gez); #endif }
{ "pile_set_name": "Github" }
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatNumber, formatPercentage } from 'common/format'; import { TooltipElement } from 'common/Tooltip'; import Analyzer from 'parser/core/Analyzer'; import StatisticBox from 'interface/others/StatisticBox'; import SuggestionThresholds from '../../SuggestionThresholds'; class LuminousBarrier extends Analyzer { totalAbsorb = 0; wastedAbsorb = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.LUMINOUS_BARRIER_TALENT.id); } on_byPlayer_applybuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.LUMINOUS_BARRIER_TALENT.id) { return; } this.totalAbsorb += event.absorb; } on_byPlayer_removebuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.LUMINOUS_BARRIER_TALENT.id) { return; } if (event.absorb > 0) { this.wastedAbsorb += event.absorb; } } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.LUMINOUS_BARRIER_TALENT.id} />} value={`${formatNumber(this.wastedAbsorb / this.owner.fightDuration * 1000)} HPS`} label={( <TooltipElement content={`The amount of shield absorb remaining on Luminous Barrier instances that have expired. There was a total of ${formatNumber(this.wastedAbsorb)} (${formatPercentage(this.wastedAbsorb / this.totalAbsorb)} %) unused Luminous Barrier absorb on a total of ${formatNumber(this.totalAbsorb)} applied.`}> Unused LB absorb </TooltipElement> )} /> ); } suggestions(when) { const wastedPourcentage = this.wastedAbsorb / this.totalAbsorb || 0; when(wastedPourcentage).isGreaterThan(SuggestionThresholds.LUMINOUS_BARRIER_TALENT_WASTED.minor) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>Your <SpellLink id={SPELLS.LUMINOUS_BARRIER_TALENT.id} /> usage can be improved.</span>) .icon(SPELLS.LUMINOUS_BARRIER_TALENT.icon) .actual(`${formatPercentage(wastedPourcentage)}% wasted`) .recommended(`<${Math.round(formatPercentage(recommended))}% is recommended`) .regular(SuggestionThresholds.LUMINOUS_BARRIER_TALENT_WASTED.regular).major(SuggestionThresholds.LUMINOUS_BARRIER_TALENT_WASTED.major); }); } } export default LuminousBarrier;
{ "pile_set_name": "Github" }
{ "forge_marker": 1, "defaults": { "model": "rail_flat", "textures": { "rail": "railcraft:blocks/tracks/flex/high_speed_electric_flat" }, "transform": "forge:default-block" }, "variants": { "shape": { "north_south": { "model": "rail_flat" }, "east_west": { "model": "rail_flat", "y": 90 }, "ascending_east": { "model": "rail_raised_ne", "y": 90 }, "ascending_west": { "model": "rail_raised_sw", "y": 90 }, "ascending_north": { "model": "rail_raised_ne" }, "ascending_south": { "model": "rail_raised_sw" }, "south_east": { "textures": { "rail": "railcraft:blocks/tracks/flex/high_speed_electric_turned" }, "model": "rail_curved" }, "south_west": { "textures": { "rail": "railcraft:blocks/tracks/flex/high_speed_electric_turned" }, "model": "rail_curved", "y": 90 }, "north_west": { "textures": { "rail": "railcraft:blocks/tracks/flex/high_speed_electric_turned" }, "model": "rail_curved", "y": 180 }, "north_east": { "textures": { "rail": "railcraft:blocks/tracks/flex/high_speed_electric_turned" }, "model": "rail_curved", "y": 270 } } } }
{ "pile_set_name": "Github" }
# -------------------------------------------------------- # Deformable Convolutional Networks # Copyright (c) 2017 Microsoft # Licensed under The MIT License [see LICENSE for details] # Modified by Haozhi Qi # -------------------------------------------------------- # Based on: # MX-RCNN # Copyright (c) 2016 by Contributors # Licence under The Apache 2.0 License # https://github.com/ijkguo/mx-rcnn/ # -------------------------------------------------------- import _init_paths import cv2 import argparse import pprint import os import sys from config.config import config, update_config def parse_args(): parser = argparse.ArgumentParser(description='Train Faster-RCNN network') # general parser.add_argument('--cfg', help='experiment configure file name', required=True, type=str) args, rest = parser.parse_known_args() # update config update_config(args.cfg) # training parser.add_argument('--frequent', help='frequency of logging', default=config.default.frequent, type=int) args = parser.parse_args() return args args = parse_args() curr_path = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(curr_path, '../external/mxnet', config.MXNET_VERSION)) import shutil import numpy as np import mxnet as mx from symbols import * from core.loader import PyramidAnchorIterator from core import callback, metric from core.module import MutableModule from utils.create_logger import create_logger from utils.load_data import load_gt_roidb, merge_roidb, filter_roidb from utils.load_model import load_param from utils.PrefetchingIter import PrefetchingIter from utils.lr_scheduler import WarmupMultiFactorScheduler def train_net(args, ctx, pretrained, epoch, prefix, begin_epoch, end_epoch, lr, lr_step): mx.random.seed(3) np.random.seed(3) logger, final_output_path = create_logger(config.output_path, args.cfg, config.dataset.image_set) prefix = os.path.join(final_output_path, prefix) # load symbol shutil.copy2(os.path.join(curr_path, 'symbols', config.symbol + '.py'), final_output_path) sym_instance = eval(config.symbol + '.' + config.symbol)() sym = sym_instance.get_symbol(config, is_train=True) feat_pyramid_level = np.log2(config.network.RPN_FEAT_STRIDE).astype(int) feat_sym = [sym.get_internals()['rpn_cls_score_p' + str(x) + '_output'] for x in feat_pyramid_level] # setup multi-gpu batch_size = len(ctx) input_batch_size = config.TRAIN.BATCH_IMAGES * batch_size # print config pprint.pprint(config) logger.info('training config:{}\n'.format(pprint.pformat(config))) # load dataset and prepare imdb for training image_sets = [iset for iset in config.dataset.image_set.split('+')] roidbs = [load_gt_roidb(config.dataset.dataset, image_set, config.dataset.root_path, config.dataset.dataset_path, flip=config.TRAIN.FLIP) for image_set in image_sets] roidb = merge_roidb(roidbs) roidb = filter_roidb(roidb, config) # load training data train_data = PyramidAnchorIterator(feat_sym, roidb, config, batch_size=input_batch_size, shuffle=config.TRAIN.SHUFFLE, ctx=ctx, feat_strides=config.network.RPN_FEAT_STRIDE, anchor_scales=config.network.ANCHOR_SCALES, anchor_ratios=config.network.ANCHOR_RATIOS, aspect_grouping=config.TRAIN.ASPECT_GROUPING, allowed_border=np.inf) # infer max shape max_data_shape = [('data', (config.TRAIN.BATCH_IMAGES, 3, max([v[0] for v in config.SCALES]), max([v[1] for v in config.SCALES])))] max_data_shape, max_label_shape = train_data.infer_shape(max_data_shape) max_data_shape.append(('gt_boxes', (config.TRAIN.BATCH_IMAGES, 100, 5))) print 'providing maximum shape', max_data_shape, max_label_shape data_shape_dict = dict(train_data.provide_data_single + train_data.provide_label_single) pprint.pprint(data_shape_dict) sym_instance.infer_shape(data_shape_dict) # load and initialize params if config.TRAIN.RESUME: print('continue training from ', begin_epoch) arg_params, aux_params = load_param(prefix, begin_epoch, convert=True) else: arg_params, aux_params = load_param(pretrained, epoch, convert=True) sym_instance.init_weight(config, arg_params, aux_params) # check parameter shapes sym_instance.check_parameter_shapes(arg_params, aux_params, data_shape_dict) # create solver fixed_param_prefix = config.network.FIXED_PARAMS data_names = [k[0] for k in train_data.provide_data_single] label_names = [k[0] for k in train_data.provide_label_single] mod = MutableModule(sym, data_names=data_names, label_names=label_names, logger=logger, context=ctx, max_data_shapes=[max_data_shape for _ in range(batch_size)], max_label_shapes=[max_label_shape for _ in range(batch_size)], fixed_param_prefix=fixed_param_prefix) if config.TRAIN.RESUME: mod._preload_opt_states = '%s-%04d.states'%(prefix, begin_epoch) # decide training params # metric rpn_eval_metric = metric.RPNAccMetric() rpn_cls_metric = metric.RPNLogLossMetric() rpn_bbox_metric = metric.RPNL1LossMetric() rpn_fg_metric = metric.RPNFGFraction(config) eval_metric = metric.RCNNAccMetric(config) eval_fg_metric = metric.RCNNFGAccuracy(config) cls_metric = metric.RCNNLogLossMetric(config) bbox_metric = metric.RCNNL1LossMetric(config) eval_metrics = mx.metric.CompositeEvalMetric() # rpn_eval_metric, rpn_cls_metric, rpn_bbox_metric, eval_metric, cls_metric, bbox_metric for child_metric in [rpn_eval_metric, rpn_cls_metric, rpn_bbox_metric, rpn_fg_metric, eval_fg_metric, eval_metric, cls_metric, bbox_metric]: eval_metrics.add(child_metric) # callback batch_end_callback = callback.Speedometer(train_data.batch_size, frequent=args.frequent) means = np.tile(np.array(config.TRAIN.BBOX_MEANS), 2 if config.CLASS_AGNOSTIC else config.dataset.NUM_CLASSES) stds = np.tile(np.array(config.TRAIN.BBOX_STDS), 2 if config.CLASS_AGNOSTIC else config.dataset.NUM_CLASSES) epoch_end_callback = [mx.callback.module_checkpoint(mod, prefix, period=1, save_optimizer_states=True), callback.do_checkpoint(prefix, means, stds)] # decide learning rate base_lr = lr lr_factor = config.TRAIN.lr_factor lr_epoch = [float(epoch) for epoch in lr_step.split(',')] lr_epoch_diff = [epoch - begin_epoch for epoch in lr_epoch if epoch > begin_epoch] lr = base_lr * (lr_factor ** (len(lr_epoch) - len(lr_epoch_diff))) lr_iters = [int(epoch * len(roidb) / batch_size) for epoch in lr_epoch_diff] print('lr', lr, 'lr_epoch_diff', lr_epoch_diff, 'lr_iters', lr_iters) lr_scheduler = WarmupMultiFactorScheduler(lr_iters, lr_factor, config.TRAIN.warmup, config.TRAIN.warmup_lr, config.TRAIN.warmup_step) # optimizer optimizer_params = {'momentum': config.TRAIN.momentum, 'wd': config.TRAIN.wd, 'learning_rate': lr, 'lr_scheduler': lr_scheduler, 'clip_gradient': None} # if not isinstance(train_data, PrefetchingIter): train_data = PrefetchingIter(train_data) # train mod.fit(train_data, eval_metric=eval_metrics, epoch_end_callback=epoch_end_callback, batch_end_callback=batch_end_callback, kvstore=config.default.kvstore, optimizer='sgd', optimizer_params=optimizer_params, arg_params=arg_params, aux_params=aux_params, begin_epoch=begin_epoch, num_epoch=end_epoch) def main(): print('Called with argument:', args) ctx = [mx.gpu(int(i)) for i in config.gpus.split(',')] train_net(args, ctx, config.network.pretrained, config.network.pretrained_epoch, config.TRAIN.model_prefix, config.TRAIN.begin_epoch, config.TRAIN.end_epoch, config.TRAIN.lr, config.TRAIN.lr_step) if __name__ == '__main__': main()
{ "pile_set_name": "Github" }
.footer .content a.open-source-icon(href="http://opensource.alibaba.com/") img(src="http://zos.alipayobjects.com/rmsportal/OCGqTPRSXYMsKjGiHPuP.png") div.license Released under Apache License div.copyright Copyright ©️ 2019 Alibaba Inc.
{ "pile_set_name": "Github" }
### `tf.contrib.framework.local_variable(initial_value, validate_shape=True, name=None)` {#local_variable} Create variable and add it to `GraphKeys.LOCAL_VARIABLES` collection. ##### Args: * <b>`initial_value`</b>: See variables.Variable.__init__. * <b>`validate_shape`</b>: See variables.Variable.__init__. * <b>`name`</b>: See variables.Variable.__init__. ##### Returns: New variable.
{ "pile_set_name": "Github" }
1 301 601 901 1201 1501 1801 2101 2401 2701
{ "pile_set_name": "Github" }
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - xuri * - sycuato * - bokideckonja * - Luo Ning * - William Yang (williamyang233) */ return array_merge(require __DIR__.'/zh_Hans.php', [ 'formats' => [ 'LT' => 'HH:mm', 'LTS' => 'HH:mm:ss', 'L' => 'YYYY/MM/DD', 'LL' => 'YYYY年M月D日', 'LLL' => 'YYYY年M月D日 A h点mm分', 'LLLL' => 'YYYY年M月D日dddd A h点mm分', ], ]);
{ "pile_set_name": "Github" }
// Copyright 2009 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. // +build amd64,darwin package unix import ( "syscall" ) //sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error) func setTimespec(sec, nsec int64) Timespec { return Timespec{Sec: sec, Nsec: nsec} } func setTimeval(sec, usec int64) Timeval { return Timeval{Sec: sec, Usec: int32(usec)} } //sysnb gettimeofday(tp *Timeval) (sec int64, usec int32, err error) func Gettimeofday(tv *Timeval) (err error) { // The tv passed to gettimeofday must be non-nil // but is otherwise unused. The answers come back // in the two registers. sec, usec, err := gettimeofday(tv) tv.Sec = sec tv.Usec = usec return err } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint64(fd) k.Filter = int16(mode) k.Flags = uint16(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (msghdr *Msghdr) SetIovlen(length int) { msghdr.Iovlen = int32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) // SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions // of darwin/amd64 the syscall is called sysctl instead of __sysctl. const SYS___SYSCTL = SYS_SYSCTL //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 //sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 //sys Fstatfs(fd int, stat *Statfs_t) (err error) = SYS_FSTATFS64 //sys getfsstat(buf unsafe.Pointer, size uintptr, flags int) (n int, err error) = SYS_GETFSSTAT64 //sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 //sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 //sys Statfs(path string, stat *Statfs_t) (err error) = SYS_STATFS64
{ "pile_set_name": "Github" }
# encoding: ascii-8bit # Copyright 2014 Ball Aerospace & Technologies Corp. # All Rights Reserved. # # This program is free software; you can modify and/or redistribute it # under the terms of the GNU General Public License # as published by the Free Software Foundation; version 3 with # attribution addendums as found in the LICENSE.txt require 'open3' # Cross-platform way of finding an executable in the $PATH. # # which('ruby') #=> /usr/bin/ruby def which(cmd) exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : [''] ENV['PATH'].split(File::PATH_SEPARATOR).each do |path| exts.each { |ext| exe = File.join(path, "#{cmd}#{ext}") return exe if File.executable?(exe) && !File.directory?(exe) } end return nil end # Pure Ruby CRC class to avoid circular dependency with c_cosmos class RakeCrc32 attr_reader :crc32_poly attr_reader :crc32_seed attr_reader :crc32_xor attr_reader :crc32_table attr_reader :crc32_raw_table # Default Polynomial for 32-bit CRC DEFAULT_CRC32_POLY = 0x04C11DB7 # Default Seed for 32-bit CRC DEFAULT_CRC32_SEED = 0xFFFFFFFF def initialize(crc32_poly = DEFAULT_CRC32_POLY, crc32_seed = DEFAULT_CRC32_SEED, crc32_xor = true) @crc32_poly = crc32_poly @crc32_seed = crc32_seed @crc32_xor = crc32_xor @crc32_table = [] (0..255).each do |index| entry = compute_crc32_table_entry(index) @crc32_table << entry end end # Calculate a 32-bit CRC def calc(data, seed = nil) seed = @crc32_seed unless seed crc = seed data.each_byte do |byte| index = ((crc >> 24) ^ byte) & 0xFF crc = ((crc << 8) ^ @crc32_table[index]) & 0xFFFFFFFF end if @crc32_xor crc ^ 0xFFFFFFFF else crc end end protected # Compute a single entry in the 32-bit crc lookup table def compute_crc32_table_entry(index) crc = index << 24 8.times do if ((crc & 0x80000000) != 0) crc = (crc << 1) ^ @crc32_poly else crc = crc << 1 end end return (crc & 0xFFFFFFFF) end end require 'yard' if RUBY_ENGINE == 'ruby' # Import the rake tasks import 'tasks/manifest.rake' import 'tasks/spec.rake' import 'tasks/gemfile_stats.rake' # Update the built in task dependencies task :default => [:spec] # :test task :require_version do unless ENV['VERSION'] puts "VERSION is required: rake <task> VERSION=X.X.X" exit 1 end end task :devkit do if RUBY_ENGINE == 'ruby' if RUBY_PLATFORM[0..2] == 'x64' if File.exist?("C:/msys64/mingw64") ENV['RI_DEVKIT'] = "C:\\msys64" ENV['MSYSTEM']="MINGW64" ENV['PKG_CONFIG_PATH']="/mingw64/lib/pkgconfig:/mingw64/share/pkgconfig" ENV['ACLOCAL_PATH']="/mingw64/share/aclocal:/usr/share/aclocal" ENV['MANPATH']="/mingw64/share/man" ENV['MINGW_PACKAGE_PREFIX']="mingw-w64-x86_64" ENV['LANG']="en_US.UTF-8" ENV['PATH'] = 'C:\\msys64\\mingw64\\bin;C:\\msys64\\usr\\bin;' + ENV['PATH'] end else if File.exist?("C:/msys64/mingw32") ENV['RI_DEVKIT'] = "C:\\msys64" ENV['MSYSTEM']="MINGW32" ENV['PKG_CONFIG_PATH']="/mingw32/lib/pkgconfig:/mingw32/share/pkgconfig" ENV['ACLOCAL_PATH']="/mingw32/share/aclocal:/usr/share/aclocal" ENV['MANPATH']="/mingw32/share/man" ENV['MINGW_PACKAGE_PREFIX']="mingw-w64-i686" ENV['LANG']="en_US.UTF-8" ENV['PATH'] = 'C:\\msys64\\mingw32\\bin;C:\\msys64\\usr\\bin;' + ENV['PATH'] end end end end task :build => [:devkit] do if RUBY_ENGINE == 'ruby' _, platform, *_ = RUBY_PLATFORM.split("-") saved = Dir.pwd shared_extension = 'so' shared_extension = 'bundle' if platform =~ /darwin/ extensions = [ 'crc', 'low_fragmentation_array', 'polynomial_conversion', 'config_parser', 'string', 'array', 'cosmos_io', 'tabbed_plots_config', 'telemetry', 'line_graph', 'packet', 'platform', 'buffered_file'] extensions.each do |extension_name| Dir.chdir "ext/cosmos/ext/#{extension_name}" FileUtils.rm_f Dir.glob('*.o') FileUtils.rm_f Dir.glob("*.#{shared_extension}") FileUtils.rm_f Dir.glob('*.def') FileUtils.rm_f 'Makefile' system('ruby extconf.rb') system('make') FileUtils.copy("#{extension_name}.#{shared_extension}", '../../../../lib/cosmos/ext/.') FileUtils.rm_f Dir.glob('*.o') FileUtils.rm_f Dir.glob("*.#{shared_extension}") FileUtils.rm_f Dir.glob('*.def') FileUtils.rm_f 'Makefile' Dir.chdir saved end end end task :git_checkout_master do system('git checkout master') end task :install_crc do saved = Dir.pwd Dir.chdir 'demo' system('bundle exec rake crc_official') Dir.chdir saved saved = Dir.pwd Dir.chdir 'install' system('bundle exec rake crc_official') Dir.chdir saved end task :gem => [:require_version] do _, platform, *_ = RUBY_PLATFORM.split("-") if platform == 'mswin32' or platform == 'mingw32' raise "Building gem is not supported on Windows because file permissions are lost" end system('gem build cosmos.gemspec') end task :commit_release_ticket => [:require_version, :git_checkout_master] do system('git add data/crc.txt') system('git add demo/config/data/crc.txt') system('git add install/config/data/crc.txt') system('git add lib/cosmos/version.rb') system('git add Manifest.txt') system("git commit -m \"Release COSMOS #{ENV['VERSION']}\"") system("git push") end task :tag_release => [:require_version] do system("git tag -a v#{ENV['VERSION']} -m \"COSMOS #{ENV['VERSION']}\"") system("git push --tags") end task :version => [:require_version] do puts "Getting the revision from git" revision = `git rev-parse HEAD`.chomp # Update cosmos_version.rb version = ENV['VERSION'].dup major,minor,patch = version.to_s.split('.') File.open('lib/cosmos/version.rb', 'w') do |file| file.puts "# encoding: ascii-8bit" file.puts "" file.puts "COSMOS_VERSION = '#{version}'" file.puts "module Cosmos" file.puts " module Version" file.puts " MAJOR = '#{major}'" file.puts " MINOR = '#{minor}'" file.puts " PATCH = '#{patch}'" file.puts " BUILD = '#{revision}'" file.puts " end" file.puts " VERSION = '#{version}'" file.puts "end" end puts "Successfully updated lib/cosmos/version.rb" # Create the crc.txt file crc = RakeCrc32.new File.open("data/crc.txt",'w') do |file| Dir[File.join('lib','**','*.rb')].each do |filename| file_data = File.open(filename, 'rb').read.gsub("\x0D\x0A", "\x0A") file.puts "\"#{filename}\" #{sprintf("0x%08X", crc.calc(file_data))}" end end end task :metrics do puts "\nRunning flog and creating flog_report.txt" `flog lib > flog_report.txt` puts "\nRunning flay and creating flay_report.txt" `flay lib > flay_report.txt` puts "\nRunning reek and creating reek_report.txt" `reek lib > reek_report.txt` puts "\nRunning roodi and creating roodi_report.txt" `roodi -config=roodi.yml lib > roodi_report.txt` end task :stress do puts "Running each spec individual with GC.stress = true..." puts ENV['STRESS'] = "1" failed = [] Dir['spec/**/*_spec.rb'].each do |spec_file| puts "Running: rspec #{spec_file}" output, status = Open3.capture2e("rspec #{spec_file}") if status.success? puts " success (#{status}):" #puts output puts else puts " error (#{status}):" puts output puts failed << spec_file end end if failed.length > 0 puts "Failed specs:" failed.each do |f| puts " #{f}" end else puts "Success!" end end # Make all the main.sh files executable in the demo and install Mac applications task :mac_app_exec_bit do %w(demo install).each do |root| Dir["#{root}/tools/mac/**/Contents/MacOS/main.sh"].each do |main| `git add --chmod=+x #{main}` end end end if RUBY_ENGINE == 'ruby' YARD::Rake::YardocTask.new do |t| t.options = ['--protected'] # See all options by typing 'yardoc --help' end end task :release => [:require_version, :git_checkout_master, :build, :spec, :manifest, :version, :install_crc, :gem] task :commit_release => [:commit_release_ticket, :tag_release] task :docker_build do _, platform, *_ = RUBY_PLATFORM.split("-") if (platform == 'mswin32' or platform == 'mingw32') and which('winpty') system('winpty docker build --tag cosmos-dev .') else system('docker build --tag cosmos-dev .') end end task :docker_run do STDOUT.puts "Note, this is not automated on purpose to ensure each step is successful (with user entry of credentials for github/rubygems.org)" STDOUT.puts "Steps to perform a COSMOS release:" STDOUT.puts "1. git config --global user.name \"Last, First\"" STDOUT.puts "2. git config --global user.email \"[email protected]\"" STDOUT.puts "3. git pull" STDOUT.puts "4. export VERSION=X.X.X" STDOUT.puts "5. rake release" STDOUT.puts "6. rake commit_release" STDOUT.puts "7. export PATH=/opt/jruby/bin:$PATH" STDOUT.puts "8. rake gem" STDOUT.puts "9. /usr/bin/gem push cosmos-X.X.X.gem" STDOUT.puts "10. /usr/bin/gem push cosmos-X.X.X-java.gem" STDOUT.puts "11. cd /devel/cosmos-docker" STDOUT.puts "12. git pull" STDOUT.puts "13. Update COSMOS_VERSION in all Dockerfiles. Also update README.md" STDOUT.puts "14. git commit -a -m \"Release COSMOS vX.X.X\"" STDOUT.puts "15. git push" STDOUT.puts "16. git checkout -b vX.X.X" STDOUT.puts "17. git push --set-upstream origin vX.X.X" STDOUT.puts "18. Update release notes on github.com and cosmosrb.com" system('docker run -it --rm cosmos-dev') end
{ "pile_set_name": "Github" }
#!/usr/bin/python3 # -*- coding: utf-8 -*- import logging from telegram.ext import Dispatcher, CommandHandler from utils.config_loader import config from utils.callback import callback_delete_message from utils.restricted import restricted logger = logging.getLogger(__name__) def init(dispatcher: Dispatcher): """Provide handlers initialization.""" dispatcher.add_handler(CommandHandler('help', get_help)) @restricted def get_help(update, context): message = '发送google drive链接,或者转发带有google drive的信息即可手动转存。\n' \ '需要使用 /sa 和 /folders 进行配置\n\n' \ '以下是本BOT的命令:\n\n' \ '/folders - 设置收藏文件夹\n' \ '/sa - 仅限私聊,上传包含sa的ZIP文件夹,在标题写上/sa设置Service Account\n' \ '/4999baoyue - 仅限私聊,商业洽谈,请附上留言\n' \ '/help - 输出本帮助\n' rsp = update.message.reply_text(message) rsp.done.wait(timeout=60) message_id = rsp.result().message_id if update.message.chat_id < 0: context.job_queue.run_once(callback_delete_message, config.TIMER_TO_DELETE_MESSAGE, context=(update.message.chat_id, message_id)) context.job_queue.run_once(callback_delete_message, config.TIMER_TO_DELETE_MESSAGE, context=(update.message.chat_id, update.message.message_id))
{ "pile_set_name": "Github" }
// *************************************************************************** // * // * Copyright (C) 2013 International Business Machines // * Corporation and others. All Rights Reserved. // * Tool: com.ibm.icu.dev.tool.cldr.LDML2ICUConverter.java // * Source File:<path>/common/rbnf/es_CL.xml // * // *************************************************************************** es_CL{ %%Parent{"es_419"} Version{"2.0.82.42"} }
{ "pile_set_name": "Github" }
<?php /** * Checks that all uses of TRUE, FALSE and NULL are uppercase. * * @author Greg Sherwood <[email protected]> * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence */ namespace PHP_CodeSniffer\Standards\Generic\Sniffs\PHP; use PHP_CodeSniffer\Sniffs\Sniff; use PHP_CodeSniffer\Files\File; class UpperCaseConstantSniff implements Sniff { /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { return [ T_TRUE, T_FALSE, T_NULL, ]; }//end register() /** * Processes this sniff, when one of its tokens is encountered. * * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. * @param int $stackPtr The position of the current token in the * stack passed in $tokens. * * @return void */ public function process(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); $keyword = $tokens[$stackPtr]['content']; $expected = strtoupper($keyword); if ($keyword !== $expected) { if ($keyword === strtolower($keyword)) { $phpcsFile->recordMetric($stackPtr, 'PHP constant case', 'lower'); } else { $phpcsFile->recordMetric($stackPtr, 'PHP constant case', 'mixed'); } $error = 'TRUE, FALSE and NULL must be uppercase; expected "%s" but found "%s"'; $data = [ $expected, $keyword, ]; $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Found', $data); if ($fix === true) { $phpcsFile->fixer->replaceToken($stackPtr, $expected); } } else { $phpcsFile->recordMetric($stackPtr, 'PHP constant case', 'upper'); } }//end process() }//end class
{ "pile_set_name": "Github" }
// Copyright (C) 2011 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_IMGLAB_CONVERT_PASCAl_XML_H__ #define DLIB_IMGLAB_CONVERT_PASCAl_XML_H__ #include "common.h" #include <dlib/cmd_line_parser.h> void convert_pascal_xml(const dlib::command_line_parser& parser); #endif // DLIB_IMGLAB_CONVERT_PASCAl_XML_H__
{ "pile_set_name": "Github" }
三上梨奈最新番号 【MVF-173】美人教師 暴行現場 35 【TMAF-004】全裸立ち電マ連続アクメ 4時間 【CRPD-248】女性専用ショタコン風俗 何でもするよ!ぼく○才 【RCT-037】公衆の面前で赤面おもらし連発!羞恥心感和センサーで動く強制失禁バイブ 【ID-027】丸の内美人女子社員生中出し 2</a>2008-05-30TMA$$$TMA177分钟
{ "pile_set_name": "Github" }
/* CoreImage - CIFilterShape.h Copyright (c) 2015 Apple, Inc. All rights reserved. */ #import <Foundation/Foundation.h> #import <CoreImage/CoreImageDefines.h> NS_ASSUME_NONNULL_BEGIN NS_CLASS_AVAILABLE(10_4, 9_0) @interface CIFilterShape : NSObject <NSCopying> { @public uint32_t _pad; void *_priv; } /* Create a shape representing the smallest integral rect containing 'r'. */ + (instancetype)shapeWithRect:(CGRect)r; /* Initializer. */ - (instancetype)initWithRect:(CGRect)r; /* Create a shape from the result of transforming the shape by 'm'. If * 'flag' is false the new shape will contain all pixels in the * transformed shape (and possibly some outside the transformed shape). * If 'flag' is false the new shape will contain a subset of the pixels * in the transformed shape (but none of those outside the transformed * shape). */ - (CIFilterShape *)transformBy:(CGAffineTransform)m interior:(BOOL)flag; /* Create a shape representing the shape inset by 'delta'. */ - (CIFilterShape *)insetByX:(int)dx Y:(int)dy; /* Create a shape representing the union of the shape and 's2'. */ - (CIFilterShape *)unionWith:(CIFilterShape *)s2; /* Create a shape representing the union of the shape and the smallest * integral rect containing 'r'. */ - (CIFilterShape *)unionWithRect:(CGRect)r; /* Create a shape representing the intersection of the shape and 's2'. */ - (CIFilterShape *)intersectWith:(CIFilterShape *)s2; /* Create a shape representing the intersection of the shape and the smallest * integral rect containing 'r'. */ - (CIFilterShape *)intersectWithRect:(CGRect)r; /* Returns an integral rect that bounds the shape. */ @property (readonly) CGRect extent; @end NS_ASSUME_NONNULL_END
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffcecece" > <com.github.nuptboyzhb.lib.SuperSwipeRefreshLayout android:id="@+id/swipe_refresh" android:layout_width="match_parent" android:layout_height="match_parent" > <android.support.v4.widget.NestedScrollView android:id="@+id/scroll_view" android:layout_width="match_parent" android:layout_height="match_parent" > <RelativeLayout android:id="@+id/linear_layout" android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/textview" android:layout_width="match_parent" android:layout_height="900dp" android:background="#ffceaaaa" android:gravity="center" android:text="I am in NestedScrollView" /> </RelativeLayout> </android.support.v4.widget.NestedScrollView> </com.github.nuptboyzhb.lib.SuperSwipeRefreshLayout> </RelativeLayout>
{ "pile_set_name": "Github" }
# frozen_string_literal: true require "cases/helper" require "models/topic" require "models/reply" require "models/developer" require "models/computer" require "models/parrot" require "models/company" require "models/price_estimate" class ValidationsTest < ActiveRecord::TestCase fixtures :topics, :developers # Most of the tests mess with the validations of Topic, so lets repair it all the time. # Other classes we mess with will be dealt with in the specific tests repair_validations(Topic) def test_valid_uses_create_context_when_new r = WrongReply.new r.title = "Wrong Create" assert_not_predicate r, :valid? assert r.errors[:title].any?, "A reply with a bad title should mark that attribute as invalid" assert_equal ["is Wrong Create"], r.errors[:title], "A reply with a bad content should contain an error" end def test_valid_uses_update_context_when_persisted r = WrongReply.new r.title = "Bad" r.content = "Good" assert r.save, "First validation should be successful" r.title = "Wrong Update" assert_not r.valid?, "Second validation should fail" assert r.errors[:title].any?, "A reply with a bad title should mark that attribute as invalid" assert_equal ["is Wrong Update"], r.errors[:title], "A reply with a bad content should contain an error" end def test_valid_using_special_context r = WrongReply.new(title: "Valid title") assert_not r.valid?(:special_case) assert_equal "Invalid", r.errors[:author_name].join r.author_name = "secret" r.content = "Good" assert r.valid?(:special_case) r.author_name = nil assert_not r.valid?(:special_case) assert_equal "Invalid", r.errors[:author_name].join r.author_name = "secret" assert r.valid?(:special_case) end def test_invalid_using_multiple_contexts r = WrongReply.new(title: "Wrong Create") assert r.invalid?([:special_case, :create]) assert_equal "Invalid", r.errors[:author_name].join assert_equal "is Wrong Create", r.errors[:title].join end def test_validate r = WrongReply.new r.validate assert_empty r.errors[:author_name] r.validate(:special_case) assert_not_empty r.errors[:author_name] r.author_name = "secret" r.validate(:special_case) assert_empty r.errors[:author_name] end def test_invalid_record_exception assert_raise(ActiveRecord::RecordInvalid) { WrongReply.create! } assert_raise(ActiveRecord::RecordInvalid) { WrongReply.new.save! } r = WrongReply.new invalid = assert_raise ActiveRecord::RecordInvalid do r.save! end assert_equal r, invalid.record end def test_validate_with_bang assert_raise(ActiveRecord::RecordInvalid) do WrongReply.new.validate! end end def test_validate_with_bang_and_context assert_raise(ActiveRecord::RecordInvalid) do WrongReply.new.validate!(:special_case) end r = WrongReply.new(title: "Valid title", author_name: "secret", content: "Good") assert r.validate!(:special_case) end def test_exception_on_create_bang_many assert_raise(ActiveRecord::RecordInvalid) do WrongReply.create!([ { "title" => "OK" }, { "title" => "Wrong Create" }]) end end def test_exception_on_create_bang_with_block assert_raise(ActiveRecord::RecordInvalid) do WrongReply.create!("title" => "OK") do |r| r.content = nil end end end def test_exception_on_create_bang_many_with_block assert_raise(ActiveRecord::RecordInvalid) do WrongReply.create!([{ "title" => "OK" }, { "title" => "Wrong Create" }]) do |r| r.content = nil end end end def test_save_without_validation reply = WrongReply.new assert_not reply.save assert reply.save(validate: false) end def test_validates_acceptance_of_with_non_existent_table Object.const_set :IncorporealModel, Class.new(ActiveRecord::Base) assert_nothing_raised do IncorporealModel.validates_acceptance_of(:incorporeal_column) end end def test_throw_away_typing d = Developer.new("name" => "David", "salary" => "100,000") assert_not_predicate d, :valid? assert_equal 100, d.salary assert_equal "100,000", d.salary_before_type_cast end def test_validates_acceptance_of_with_undefined_attribute_methods klass = Class.new(Topic) klass.validates_acceptance_of(:approved) topic = klass.new(approved: true) klass.undefine_attribute_methods assert topic.approved end def test_validates_acceptance_of_as_database_column klass = Class.new(Topic) klass.validates_acceptance_of(:approved) topic = klass.create("approved" => true) assert topic["approved"] end def test_validators assert_equal 1, Parrot.validators.size assert_equal 1, Company.validators.size assert_equal 1, Parrot.validators_on(:name).size assert_equal 1, Company.validators_on(:name).size end def test_numericality_validation_with_mutation klass = Class.new(Topic) do attribute :wibble, :string validates_numericality_of :wibble, only_integer: true end topic = klass.new(wibble: "123-4567") topic.wibble.gsub!("-", "") assert_predicate topic, :valid? end def test_numericality_validation_checks_against_raw_value klass = Class.new(Topic) do def self.model_name ActiveModel::Name.new(self, nil, "Topic") end attribute :wibble, :decimal, scale: 2, precision: 9 validates_numericality_of :wibble, greater_than_or_equal_to: BigDecimal("97.18") end assert_not_predicate klass.new(wibble: "97.179"), :valid? assert_not_predicate klass.new(wibble: 97.179), :valid? assert_not_predicate klass.new(wibble: BigDecimal("97.179")), :valid? end def test_numericality_validator_wont_be_affected_by_custom_getter price_estimate = PriceEstimate.new(price: 50) assert_equal "$50.00", price_estimate.price assert_equal 50, price_estimate.price_before_type_cast assert_equal 50, price_estimate.read_attribute(:price) assert_predicate price_estimate, :price_came_from_user? assert_predicate price_estimate, :valid? price_estimate.save! assert_not_predicate price_estimate, :price_came_from_user? assert_predicate price_estimate, :valid? end def test_acceptance_validator_doesnt_require_db_connection klass = Class.new(ActiveRecord::Base) do self.table_name = "posts" end klass.reset_column_information assert_no_queries do klass.validates_acceptance_of(:foo) end end end
{ "pile_set_name": "Github" }
/* * Copyright 2000 by Hans Reiser, licensing governed by reiserfs/README * * Trivial changes by Alan Cox to remove EHASHCOLLISION for compatibility * * Trivial Changes: * Rights granted to Hans Reiser to redistribute under other terms providing * he accepts all liability including but not limited to patent, fitness * for purpose, and direct or indirect claims arising from failure to perform. * * NO WARRANTY */ #include <linux/time.h> #include <linux/bitops.h> #include <linux/slab.h> #include "reiserfs.h" #include "acl.h" #include "xattr.h" #include <linux/quotaops.h> #define INC_DIR_INODE_NLINK(i) if (i->i_nlink != 1) { inc_nlink(i); if (i->i_nlink >= REISERFS_LINK_MAX) set_nlink(i, 1); } #define DEC_DIR_INODE_NLINK(i) if (i->i_nlink != 1) drop_nlink(i); /* * directory item contains array of entry headers. This performs * binary search through that array */ static int bin_search_in_dir_item(struct reiserfs_dir_entry *de, loff_t off) { struct item_head *ih = de->de_ih; struct reiserfs_de_head *deh = de->de_deh; int rbound, lbound, j; lbound = 0; rbound = ih_entry_count(ih) - 1; for (j = (rbound + lbound) / 2; lbound <= rbound; j = (rbound + lbound) / 2) { if (off < deh_offset(deh + j)) { rbound = j - 1; continue; } if (off > deh_offset(deh + j)) { lbound = j + 1; continue; } /* this is not name found, but matched third key component */ de->de_entry_num = j; return NAME_FOUND; } de->de_entry_num = lbound; return NAME_NOT_FOUND; } /* * comment? maybe something like set de to point to what the path points to? */ static inline void set_de_item_location(struct reiserfs_dir_entry *de, struct treepath *path) { de->de_bh = get_last_bh(path); de->de_ih = tp_item_head(path); de->de_deh = B_I_DEH(de->de_bh, de->de_ih); de->de_item_num = PATH_LAST_POSITION(path); } /* * de_bh, de_ih, de_deh (points to first element of array), de_item_num is set */ inline void set_de_name_and_namelen(struct reiserfs_dir_entry *de) { struct reiserfs_de_head *deh = de->de_deh + de->de_entry_num; BUG_ON(de->de_entry_num >= ih_entry_count(de->de_ih)); de->de_entrylen = entry_length(de->de_bh, de->de_ih, de->de_entry_num); de->de_namelen = de->de_entrylen - (de_with_sd(deh) ? SD_SIZE : 0); de->de_name = ih_item_body(de->de_bh, de->de_ih) + deh_location(deh); if (de->de_name[de->de_namelen - 1] == 0) de->de_namelen = strlen(de->de_name); } /* what entry points to */ static inline void set_de_object_key(struct reiserfs_dir_entry *de) { BUG_ON(de->de_entry_num >= ih_entry_count(de->de_ih)); de->de_dir_id = deh_dir_id(&de->de_deh[de->de_entry_num]); de->de_objectid = deh_objectid(&de->de_deh[de->de_entry_num]); } static inline void store_de_entry_key(struct reiserfs_dir_entry *de) { struct reiserfs_de_head *deh = de->de_deh + de->de_entry_num; BUG_ON(de->de_entry_num >= ih_entry_count(de->de_ih)); /* store key of the found entry */ de->de_entry_key.version = KEY_FORMAT_3_5; de->de_entry_key.on_disk_key.k_dir_id = le32_to_cpu(de->de_ih->ih_key.k_dir_id); de->de_entry_key.on_disk_key.k_objectid = le32_to_cpu(de->de_ih->ih_key.k_objectid); set_cpu_key_k_offset(&de->de_entry_key, deh_offset(deh)); set_cpu_key_k_type(&de->de_entry_key, TYPE_DIRENTRY); } /* * We assign a key to each directory item, and place multiple entries in a * single directory item. A directory item has a key equal to the key of * the first directory entry in it. * This function first calls search_by_key, then, if item whose first entry * matches is not found it looks for the entry inside directory item found * by search_by_key. Fills the path to the entry, and to the entry position * in the item */ /* The function is NOT SCHEDULE-SAFE! */ int search_by_entry_key(struct super_block *sb, const struct cpu_key *key, struct treepath *path, struct reiserfs_dir_entry *de) { int retval; retval = search_item(sb, key, path); switch (retval) { case ITEM_NOT_FOUND: if (!PATH_LAST_POSITION(path)) { reiserfs_error(sb, "vs-7000", "search_by_key " "returned item position == 0"); pathrelse(path); return IO_ERROR; } PATH_LAST_POSITION(path)--; case ITEM_FOUND: break; case IO_ERROR: return retval; default: pathrelse(path); reiserfs_error(sb, "vs-7002", "no path to here"); return IO_ERROR; } set_de_item_location(de, path); #ifdef CONFIG_REISERFS_CHECK if (!is_direntry_le_ih(de->de_ih) || COMP_SHORT_KEYS(&de->de_ih->ih_key, key)) { print_block(de->de_bh, 0, -1, -1); reiserfs_panic(sb, "vs-7005", "found item %h is not directory " "item or does not belong to the same directory " "as key %K", de->de_ih, key); } #endif /* CONFIG_REISERFS_CHECK */ /* * binary search in directory item by third component of the * key. sets de->de_entry_num of de */ retval = bin_search_in_dir_item(de, cpu_key_k_offset(key)); path->pos_in_item = de->de_entry_num; if (retval != NAME_NOT_FOUND) { /* * ugly, but rename needs de_bh, de_deh, de_name, * de_namelen, de_objectid set */ set_de_name_and_namelen(de); set_de_object_key(de); } return retval; } /* Keyed 32-bit hash function using TEA in a Davis-Meyer function */ /* * The third component is hashed, and you can choose from more than * one hash function. Per directory hashes are not yet implemented * but are thought about. This function should be moved to hashes.c * Jedi, please do so. -Hans */ static __u32 get_third_component(struct super_block *s, const char *name, int len) { __u32 res; if (!len || (len == 1 && name[0] == '.')) return DOT_OFFSET; if (len == 2 && name[0] == '.' && name[1] == '.') return DOT_DOT_OFFSET; res = REISERFS_SB(s)->s_hash_function(name, len); /* take bits from 7-th to 30-th including both bounds */ res = GET_HASH_VALUE(res); if (res == 0) /* * needed to have no names before "." and ".." those have hash * value == 0 and generation conters 1 and 2 accordingly */ res = 128; return res + MAX_GENERATION_NUMBER; } static int reiserfs_match(struct reiserfs_dir_entry *de, const char *name, int namelen) { int retval = NAME_NOT_FOUND; if ((namelen == de->de_namelen) && !memcmp(de->de_name, name, de->de_namelen)) retval = (de_visible(de->de_deh + de->de_entry_num) ? NAME_FOUND : NAME_FOUND_INVISIBLE); return retval; } /* de's de_bh, de_ih, de_deh, de_item_num, de_entry_num are set already */ /* used when hash collisions exist */ static int linear_search_in_dir_item(struct cpu_key *key, struct reiserfs_dir_entry *de, const char *name, int namelen) { struct reiserfs_de_head *deh = de->de_deh; int retval; int i; i = de->de_entry_num; if (i == ih_entry_count(de->de_ih) || GET_HASH_VALUE(deh_offset(deh + i)) != GET_HASH_VALUE(cpu_key_k_offset(key))) { i--; } RFALSE(de->de_deh != B_I_DEH(de->de_bh, de->de_ih), "vs-7010: array of entry headers not found"); deh += i; for (; i >= 0; i--, deh--) { /* hash value does not match, no need to check whole name */ if (GET_HASH_VALUE(deh_offset(deh)) != GET_HASH_VALUE(cpu_key_k_offset(key))) { return NAME_NOT_FOUND; } /* mark that this generation number is used */ if (de->de_gen_number_bit_string) set_bit(GET_GENERATION_NUMBER(deh_offset(deh)), de->de_gen_number_bit_string); /* calculate pointer to name and namelen */ de->de_entry_num = i; set_de_name_and_namelen(de); /* * de's de_name, de_namelen, de_recordlen are set. * Fill the rest. */ if ((retval = reiserfs_match(de, name, namelen)) != NAME_NOT_FOUND) { /* key of pointed object */ set_de_object_key(de); store_de_entry_key(de); /* retval can be NAME_FOUND or NAME_FOUND_INVISIBLE */ return retval; } } if (GET_GENERATION_NUMBER(le_ih_k_offset(de->de_ih)) == 0) /* * we have reached left most entry in the node. In common we * have to go to the left neighbor, but if generation counter * is 0 already, we know for sure, that there is no name with * the same hash value */ /* * FIXME: this work correctly only because hash value can not * be 0. Btw, in case of Yura's hash it is probably possible, * so, this is a bug */ return NAME_NOT_FOUND; RFALSE(de->de_item_num, "vs-7015: two diritems of the same directory in one node?"); return GOTO_PREVIOUS_ITEM; } /* * may return NAME_FOUND, NAME_FOUND_INVISIBLE, NAME_NOT_FOUND * FIXME: should add something like IOERROR */ static int reiserfs_find_entry(struct inode *dir, const char *name, int namelen, struct treepath *path_to_entry, struct reiserfs_dir_entry *de) { struct cpu_key key_to_search; int retval; if (namelen > REISERFS_MAX_NAME(dir->i_sb->s_blocksize)) return NAME_NOT_FOUND; /* we will search for this key in the tree */ make_cpu_key(&key_to_search, dir, get_third_component(dir->i_sb, name, namelen), TYPE_DIRENTRY, 3); while (1) { retval = search_by_entry_key(dir->i_sb, &key_to_search, path_to_entry, de); if (retval == IO_ERROR) { reiserfs_error(dir->i_sb, "zam-7001", "io error"); return IO_ERROR; } /* compare names for all entries having given hash value */ retval = linear_search_in_dir_item(&key_to_search, de, name, namelen); /* * there is no need to scan directory anymore. * Given entry found or does not exist */ if (retval != GOTO_PREVIOUS_ITEM) { path_to_entry->pos_in_item = de->de_entry_num; return retval; } /* * there is left neighboring item of this directory * and given entry can be there */ set_cpu_key_k_offset(&key_to_search, le_ih_k_offset(de->de_ih) - 1); pathrelse(path_to_entry); } /* while (1) */ } static struct dentry *reiserfs_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags) { int retval; struct inode *inode = NULL; struct reiserfs_dir_entry de; INITIALIZE_PATH(path_to_entry); if (REISERFS_MAX_NAME(dir->i_sb->s_blocksize) < dentry->d_name.len) return ERR_PTR(-ENAMETOOLONG); reiserfs_write_lock(dir->i_sb); de.de_gen_number_bit_string = NULL; retval = reiserfs_find_entry(dir, dentry->d_name.name, dentry->d_name.len, &path_to_entry, &de); pathrelse(&path_to_entry); if (retval == NAME_FOUND) { inode = reiserfs_iget(dir->i_sb, (struct cpu_key *)&de.de_dir_id); if (!inode || IS_ERR(inode)) { reiserfs_write_unlock(dir->i_sb); return ERR_PTR(-EACCES); } /* * Propagate the private flag so we know we're * in the priv tree */ if (IS_PRIVATE(dir)) inode->i_flags |= S_PRIVATE; } reiserfs_write_unlock(dir->i_sb); if (retval == IO_ERROR) { return ERR_PTR(-EIO); } return d_splice_alias(inode, dentry); } /* * looks up the dentry of the parent directory for child. * taken from ext2_get_parent */ struct dentry *reiserfs_get_parent(struct dentry *child) { int retval; struct inode *inode = NULL; struct reiserfs_dir_entry de; INITIALIZE_PATH(path_to_entry); struct inode *dir = d_inode(child); if (dir->i_nlink == 0) { return ERR_PTR(-ENOENT); } de.de_gen_number_bit_string = NULL; reiserfs_write_lock(dir->i_sb); retval = reiserfs_find_entry(dir, "..", 2, &path_to_entry, &de); pathrelse(&path_to_entry); if (retval != NAME_FOUND) { reiserfs_write_unlock(dir->i_sb); return ERR_PTR(-ENOENT); } inode = reiserfs_iget(dir->i_sb, (struct cpu_key *)&de.de_dir_id); reiserfs_write_unlock(dir->i_sb); return d_obtain_alias(inode); } /* add entry to the directory (entry can be hidden). insert definition of when hidden directories are used here -Hans Does not mark dir inode dirty, do it after successesfull call to it */ static int reiserfs_add_entry(struct reiserfs_transaction_handle *th, struct inode *dir, const char *name, int namelen, struct inode *inode, int visible) { struct cpu_key entry_key; struct reiserfs_de_head *deh; INITIALIZE_PATH(path); struct reiserfs_dir_entry de; DECLARE_BITMAP(bit_string, MAX_GENERATION_NUMBER + 1); int gen_number; /* * 48 bytes now and we avoid kmalloc if we * create file with short name */ char small_buf[32 + DEH_SIZE]; char *buffer; int buflen, paste_size; int retval; BUG_ON(!th->t_trans_id); /* cannot allow items to be added into a busy deleted directory */ if (!namelen) return -EINVAL; if (namelen > REISERFS_MAX_NAME(dir->i_sb->s_blocksize)) return -ENAMETOOLONG; /* each entry has unique key. compose it */ make_cpu_key(&entry_key, dir, get_third_component(dir->i_sb, name, namelen), TYPE_DIRENTRY, 3); /* get memory for composing the entry */ buflen = DEH_SIZE + ROUND_UP(namelen); if (buflen > sizeof(small_buf)) { buffer = kmalloc(buflen, GFP_NOFS); if (!buffer) return -ENOMEM; } else buffer = small_buf; paste_size = (get_inode_sd_version(dir) == STAT_DATA_V1) ? (DEH_SIZE + namelen) : buflen; /* * fill buffer : directory entry head, name[, dir objectid | , * stat data | ,stat data, dir objectid ] */ deh = (struct reiserfs_de_head *)buffer; deh->deh_location = 0; /* JDM Endian safe if 0 */ put_deh_offset(deh, cpu_key_k_offset(&entry_key)); deh->deh_state = 0; /* JDM Endian safe if 0 */ /* put key (ino analog) to de */ /* safe: k_dir_id is le */ deh->deh_dir_id = INODE_PKEY(inode)->k_dir_id; /* safe: k_objectid is le */ deh->deh_objectid = INODE_PKEY(inode)->k_objectid; /* copy name */ memcpy((char *)(deh + 1), name, namelen); /* padd by 0s to the 4 byte boundary */ padd_item((char *)(deh + 1), ROUND_UP(namelen), namelen); /* * entry is ready to be pasted into tree, set 'visibility' * and 'stat data in entry' attributes */ mark_de_without_sd(deh); visible ? mark_de_visible(deh) : mark_de_hidden(deh); /* find the proper place for the new entry */ memset(bit_string, 0, sizeof(bit_string)); de.de_gen_number_bit_string = bit_string; retval = reiserfs_find_entry(dir, name, namelen, &path, &de); if (retval != NAME_NOT_FOUND) { if (buffer != small_buf) kfree(buffer); pathrelse(&path); if (retval == IO_ERROR) { return -EIO; } if (retval != NAME_FOUND) { reiserfs_error(dir->i_sb, "zam-7002", "reiserfs_find_entry() returned " "unexpected value (%d)", retval); } return -EEXIST; } gen_number = find_first_zero_bit(bit_string, MAX_GENERATION_NUMBER + 1); if (gen_number > MAX_GENERATION_NUMBER) { /* there is no free generation number */ reiserfs_warning(dir->i_sb, "reiserfs-7010", "Congratulations! we have got hash function " "screwed up"); if (buffer != small_buf) kfree(buffer); pathrelse(&path); return -EBUSY; } /* adjust offset of directory enrty */ put_deh_offset(deh, SET_GENERATION_NUMBER(deh_offset(deh), gen_number)); set_cpu_key_k_offset(&entry_key, deh_offset(deh)); /* update max-hash-collisions counter in reiserfs_sb_info */ PROC_INFO_MAX(th->t_super, max_hash_collisions, gen_number); /* we need to re-search for the insertion point */ if (gen_number != 0) { if (search_by_entry_key(dir->i_sb, &entry_key, &path, &de) != NAME_NOT_FOUND) { reiserfs_warning(dir->i_sb, "vs-7032", "entry with this key (%K) already " "exists", &entry_key); if (buffer != small_buf) kfree(buffer); pathrelse(&path); return -EBUSY; } } /* perform the insertion of the entry that we have prepared */ retval = reiserfs_paste_into_item(th, &path, &entry_key, dir, buffer, paste_size); if (buffer != small_buf) kfree(buffer); if (retval) { reiserfs_check_path(&path); return retval; } dir->i_size += paste_size; dir->i_mtime = dir->i_ctime = current_time(dir); if (!S_ISDIR(inode->i_mode) && visible) /* reiserfs_mkdir or reiserfs_rename will do that by itself */ reiserfs_update_sd(th, dir); reiserfs_check_path(&path); return 0; } /* * quota utility function, call if you've had to abort after calling * new_inode_init, and have not called reiserfs_new_inode yet. * This should only be called on inodes that do not have stat data * inserted into the tree yet. */ static int drop_new_inode(struct inode *inode) { dquot_drop(inode); make_bad_inode(inode); inode->i_flags |= S_NOQUOTA; iput(inode); return 0; } /* * utility function that does setup for reiserfs_new_inode. * dquot_initialize needs lots of credits so it's better to have it * outside of a transaction, so we had to pull some bits of * reiserfs_new_inode out into this func. */ static int new_inode_init(struct inode *inode, struct inode *dir, umode_t mode) { /* * Make inode invalid - just in case we are going to drop it before * the initialization happens */ INODE_PKEY(inode)->k_objectid = 0; /* * the quota init calls have to know who to charge the quota to, so * we have to set uid and gid here */ inode_init_owner(inode, dir, mode); return dquot_initialize(inode); } static int reiserfs_create(struct inode *dir, struct dentry *dentry, umode_t mode, bool excl) { int retval; struct inode *inode; /* * We need blocks for transaction + (user+group)*(quotas * for new inode + update of quota for directory owner) */ int jbegin_count = JOURNAL_PER_BALANCE_CNT * 2 + 2 * (REISERFS_QUOTA_INIT_BLOCKS(dir->i_sb) + REISERFS_QUOTA_TRANS_BLOCKS(dir->i_sb)); struct reiserfs_transaction_handle th; struct reiserfs_security_handle security; retval = dquot_initialize(dir); if (retval) return retval; if (!(inode = new_inode(dir->i_sb))) { return -ENOMEM; } retval = new_inode_init(inode, dir, mode); if (retval) { drop_new_inode(inode); return retval; } jbegin_count += reiserfs_cache_default_acl(dir); retval = reiserfs_security_init(dir, inode, &dentry->d_name, &security); if (retval < 0) { drop_new_inode(inode); return retval; } jbegin_count += retval; reiserfs_write_lock(dir->i_sb); retval = journal_begin(&th, dir->i_sb, jbegin_count); if (retval) { drop_new_inode(inode); goto out_failed; } retval = reiserfs_new_inode(&th, dir, mode, NULL, 0 /*i_size */ , dentry, inode, &security); if (retval) goto out_failed; inode->i_op = &reiserfs_file_inode_operations; inode->i_fop = &reiserfs_file_operations; inode->i_mapping->a_ops = &reiserfs_address_space_operations; retval = reiserfs_add_entry(&th, dir, dentry->d_name.name, dentry->d_name.len, inode, 1 /*visible */ ); if (retval) { int err; drop_nlink(inode); reiserfs_update_sd(&th, inode); err = journal_end(&th); if (err) retval = err; unlock_new_inode(inode); iput(inode); goto out_failed; } reiserfs_update_inode_transaction(inode); reiserfs_update_inode_transaction(dir); d_instantiate_new(dentry, inode); retval = journal_end(&th); out_failed: reiserfs_write_unlock(dir->i_sb); return retval; } static int reiserfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t rdev) { int retval; struct inode *inode; struct reiserfs_transaction_handle th; struct reiserfs_security_handle security; /* * We need blocks for transaction + (user+group)*(quotas * for new inode + update of quota for directory owner) */ int jbegin_count = JOURNAL_PER_BALANCE_CNT * 3 + 2 * (REISERFS_QUOTA_INIT_BLOCKS(dir->i_sb) + REISERFS_QUOTA_TRANS_BLOCKS(dir->i_sb)); retval = dquot_initialize(dir); if (retval) return retval; if (!(inode = new_inode(dir->i_sb))) { return -ENOMEM; } retval = new_inode_init(inode, dir, mode); if (retval) { drop_new_inode(inode); return retval; } jbegin_count += reiserfs_cache_default_acl(dir); retval = reiserfs_security_init(dir, inode, &dentry->d_name, &security); if (retval < 0) { drop_new_inode(inode); return retval; } jbegin_count += retval; reiserfs_write_lock(dir->i_sb); retval = journal_begin(&th, dir->i_sb, jbegin_count); if (retval) { drop_new_inode(inode); goto out_failed; } retval = reiserfs_new_inode(&th, dir, mode, NULL, 0 /*i_size */ , dentry, inode, &security); if (retval) { goto out_failed; } inode->i_op = &reiserfs_special_inode_operations; init_special_inode(inode, inode->i_mode, rdev); /* FIXME: needed for block and char devices only */ reiserfs_update_sd(&th, inode); reiserfs_update_inode_transaction(inode); reiserfs_update_inode_transaction(dir); retval = reiserfs_add_entry(&th, dir, dentry->d_name.name, dentry->d_name.len, inode, 1 /*visible */ ); if (retval) { int err; drop_nlink(inode); reiserfs_update_sd(&th, inode); err = journal_end(&th); if (err) retval = err; unlock_new_inode(inode); iput(inode); goto out_failed; } d_instantiate_new(dentry, inode); retval = journal_end(&th); out_failed: reiserfs_write_unlock(dir->i_sb); return retval; } static int reiserfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode) { int retval; struct inode *inode; struct reiserfs_transaction_handle th; struct reiserfs_security_handle security; /* * We need blocks for transaction + (user+group)*(quotas * for new inode + update of quota for directory owner) */ int jbegin_count = JOURNAL_PER_BALANCE_CNT * 3 + 2 * (REISERFS_QUOTA_INIT_BLOCKS(dir->i_sb) + REISERFS_QUOTA_TRANS_BLOCKS(dir->i_sb)); retval = dquot_initialize(dir); if (retval) return retval; #ifdef DISPLACE_NEW_PACKING_LOCALITIES /* * set flag that new packing locality created and new blocks * for the content of that directory are not displaced yet */ REISERFS_I(dir)->new_packing_locality = 1; #endif mode = S_IFDIR | mode; if (!(inode = new_inode(dir->i_sb))) { return -ENOMEM; } retval = new_inode_init(inode, dir, mode); if (retval) { drop_new_inode(inode); return retval; } jbegin_count += reiserfs_cache_default_acl(dir); retval = reiserfs_security_init(dir, inode, &dentry->d_name, &security); if (retval < 0) { drop_new_inode(inode); return retval; } jbegin_count += retval; reiserfs_write_lock(dir->i_sb); retval = journal_begin(&th, dir->i_sb, jbegin_count); if (retval) { drop_new_inode(inode); goto out_failed; } /* * inc the link count now, so another writer doesn't overflow * it while we sleep later on. */ INC_DIR_INODE_NLINK(dir) retval = reiserfs_new_inode(&th, dir, mode, NULL /*symlink */ , old_format_only(dir->i_sb) ? EMPTY_DIR_SIZE_V1 : EMPTY_DIR_SIZE, dentry, inode, &security); if (retval) { DEC_DIR_INODE_NLINK(dir) goto out_failed; } reiserfs_update_inode_transaction(inode); reiserfs_update_inode_transaction(dir); inode->i_op = &reiserfs_dir_inode_operations; inode->i_fop = &reiserfs_dir_operations; /* note, _this_ add_entry will not update dir's stat data */ retval = reiserfs_add_entry(&th, dir, dentry->d_name.name, dentry->d_name.len, inode, 1 /*visible */ ); if (retval) { int err; clear_nlink(inode); DEC_DIR_INODE_NLINK(dir); reiserfs_update_sd(&th, inode); err = journal_end(&th); if (err) retval = err; unlock_new_inode(inode); iput(inode); goto out_failed; } /* the above add_entry did not update dir's stat data */ reiserfs_update_sd(&th, dir); d_instantiate_new(dentry, inode); retval = journal_end(&th); out_failed: reiserfs_write_unlock(dir->i_sb); return retval; } static inline int reiserfs_empty_dir(struct inode *inode) { /* * we can cheat because an old format dir cannot have * EMPTY_DIR_SIZE, and a new format dir cannot have * EMPTY_DIR_SIZE_V1. So, if the inode is either size, * regardless of disk format version, the directory is empty. */ if (inode->i_size != EMPTY_DIR_SIZE && inode->i_size != EMPTY_DIR_SIZE_V1) { return 0; } return 1; } static int reiserfs_rmdir(struct inode *dir, struct dentry *dentry) { int retval, err; struct inode *inode; struct reiserfs_transaction_handle th; int jbegin_count; INITIALIZE_PATH(path); struct reiserfs_dir_entry de; /* * we will be doing 2 balancings and update 2 stat data, we * change quotas of the owner of the directory and of the owner * of the parent directory. The quota structure is possibly * deleted only on last iput => outside of this transaction */ jbegin_count = JOURNAL_PER_BALANCE_CNT * 2 + 2 + 4 * REISERFS_QUOTA_TRANS_BLOCKS(dir->i_sb); retval = dquot_initialize(dir); if (retval) return retval; reiserfs_write_lock(dir->i_sb); retval = journal_begin(&th, dir->i_sb, jbegin_count); if (retval) goto out_rmdir; de.de_gen_number_bit_string = NULL; if ((retval = reiserfs_find_entry(dir, dentry->d_name.name, dentry->d_name.len, &path, &de)) == NAME_NOT_FOUND) { retval = -ENOENT; goto end_rmdir; } else if (retval == IO_ERROR) { retval = -EIO; goto end_rmdir; } inode = d_inode(dentry); reiserfs_update_inode_transaction(inode); reiserfs_update_inode_transaction(dir); if (de.de_objectid != inode->i_ino) { /* * FIXME: compare key of an object and a key found in the entry */ retval = -EIO; goto end_rmdir; } if (!reiserfs_empty_dir(inode)) { retval = -ENOTEMPTY; goto end_rmdir; } /* cut entry from dir directory */ retval = reiserfs_cut_from_item(&th, &path, &de.de_entry_key, dir, NULL, /* page */ 0 /*new file size - not used here */ ); if (retval < 0) goto end_rmdir; if (inode->i_nlink != 2 && inode->i_nlink != 1) reiserfs_error(inode->i_sb, "reiserfs-7040", "empty directory has nlink != 2 (%d)", inode->i_nlink); clear_nlink(inode); inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(dir); reiserfs_update_sd(&th, inode); DEC_DIR_INODE_NLINK(dir) dir->i_size -= (DEH_SIZE + de.de_entrylen); reiserfs_update_sd(&th, dir); /* prevent empty directory from getting lost */ add_save_link(&th, inode, 0 /* not truncate */ ); retval = journal_end(&th); reiserfs_check_path(&path); out_rmdir: reiserfs_write_unlock(dir->i_sb); return retval; end_rmdir: /* * we must release path, because we did not call * reiserfs_cut_from_item, or reiserfs_cut_from_item does not * release path if operation was not complete */ pathrelse(&path); err = journal_end(&th); reiserfs_write_unlock(dir->i_sb); return err ? err : retval; } static int reiserfs_unlink(struct inode *dir, struct dentry *dentry) { int retval, err; struct inode *inode; struct reiserfs_dir_entry de; INITIALIZE_PATH(path); struct reiserfs_transaction_handle th; int jbegin_count; unsigned long savelink; retval = dquot_initialize(dir); if (retval) return retval; inode = d_inode(dentry); /* * in this transaction we can be doing at max two balancings and * update two stat datas, we change quotas of the owner of the * directory and of the owner of the parent directory. The quota * structure is possibly deleted only on iput => outside of * this transaction */ jbegin_count = JOURNAL_PER_BALANCE_CNT * 2 + 2 + 4 * REISERFS_QUOTA_TRANS_BLOCKS(dir->i_sb); reiserfs_write_lock(dir->i_sb); retval = journal_begin(&th, dir->i_sb, jbegin_count); if (retval) goto out_unlink; de.de_gen_number_bit_string = NULL; if ((retval = reiserfs_find_entry(dir, dentry->d_name.name, dentry->d_name.len, &path, &de)) == NAME_NOT_FOUND) { retval = -ENOENT; goto end_unlink; } else if (retval == IO_ERROR) { retval = -EIO; goto end_unlink; } reiserfs_update_inode_transaction(inode); reiserfs_update_inode_transaction(dir); if (de.de_objectid != inode->i_ino) { /* * FIXME: compare key of an object and a key found in the entry */ retval = -EIO; goto end_unlink; } if (!inode->i_nlink) { reiserfs_warning(inode->i_sb, "reiserfs-7042", "deleting nonexistent file (%lu), %d", inode->i_ino, inode->i_nlink); set_nlink(inode, 1); } drop_nlink(inode); /* * we schedule before doing the add_save_link call, save the link * count so we don't race */ savelink = inode->i_nlink; retval = reiserfs_cut_from_item(&th, &path, &de.de_entry_key, dir, NULL, 0); if (retval < 0) { inc_nlink(inode); goto end_unlink; } inode->i_ctime = current_time(inode); reiserfs_update_sd(&th, inode); dir->i_size -= (de.de_entrylen + DEH_SIZE); dir->i_ctime = dir->i_mtime = current_time(dir); reiserfs_update_sd(&th, dir); if (!savelink) /* prevent file from getting lost */ add_save_link(&th, inode, 0 /* not truncate */ ); retval = journal_end(&th); reiserfs_check_path(&path); reiserfs_write_unlock(dir->i_sb); return retval; end_unlink: pathrelse(&path); err = journal_end(&th); reiserfs_check_path(&path); if (err) retval = err; out_unlink: reiserfs_write_unlock(dir->i_sb); return retval; } static int reiserfs_symlink(struct inode *parent_dir, struct dentry *dentry, const char *symname) { int retval; struct inode *inode; char *name; int item_len; struct reiserfs_transaction_handle th; struct reiserfs_security_handle security; int mode = S_IFLNK | S_IRWXUGO; /* * We need blocks for transaction + (user+group)*(quotas for * new inode + update of quota for directory owner) */ int jbegin_count = JOURNAL_PER_BALANCE_CNT * 3 + 2 * (REISERFS_QUOTA_INIT_BLOCKS(parent_dir->i_sb) + REISERFS_QUOTA_TRANS_BLOCKS(parent_dir->i_sb)); retval = dquot_initialize(parent_dir); if (retval) return retval; if (!(inode = new_inode(parent_dir->i_sb))) { return -ENOMEM; } retval = new_inode_init(inode, parent_dir, mode); if (retval) { drop_new_inode(inode); return retval; } retval = reiserfs_security_init(parent_dir, inode, &dentry->d_name, &security); if (retval < 0) { drop_new_inode(inode); return retval; } jbegin_count += retval; reiserfs_write_lock(parent_dir->i_sb); item_len = ROUND_UP(strlen(symname)); if (item_len > MAX_DIRECT_ITEM_LEN(parent_dir->i_sb->s_blocksize)) { retval = -ENAMETOOLONG; drop_new_inode(inode); goto out_failed; } name = kmalloc(item_len, GFP_NOFS); if (!name) { drop_new_inode(inode); retval = -ENOMEM; goto out_failed; } memcpy(name, symname, strlen(symname)); padd_item(name, item_len, strlen(symname)); retval = journal_begin(&th, parent_dir->i_sb, jbegin_count); if (retval) { drop_new_inode(inode); kfree(name); goto out_failed; } retval = reiserfs_new_inode(&th, parent_dir, mode, name, strlen(symname), dentry, inode, &security); kfree(name); if (retval) { /* reiserfs_new_inode iputs for us */ goto out_failed; } reiserfs_update_inode_transaction(inode); reiserfs_update_inode_transaction(parent_dir); inode->i_op = &reiserfs_symlink_inode_operations; inode_nohighmem(inode); inode->i_mapping->a_ops = &reiserfs_address_space_operations; retval = reiserfs_add_entry(&th, parent_dir, dentry->d_name.name, dentry->d_name.len, inode, 1 /*visible */ ); if (retval) { int err; drop_nlink(inode); reiserfs_update_sd(&th, inode); err = journal_end(&th); if (err) retval = err; unlock_new_inode(inode); iput(inode); goto out_failed; } d_instantiate_new(dentry, inode); retval = journal_end(&th); out_failed: reiserfs_write_unlock(parent_dir->i_sb); return retval; } static int reiserfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry) { int retval; struct inode *inode = d_inode(old_dentry); struct reiserfs_transaction_handle th; /* * We need blocks for transaction + update of quotas for * the owners of the directory */ int jbegin_count = JOURNAL_PER_BALANCE_CNT * 3 + 2 * REISERFS_QUOTA_TRANS_BLOCKS(dir->i_sb); retval = dquot_initialize(dir); if (retval) return retval; reiserfs_write_lock(dir->i_sb); if (inode->i_nlink >= REISERFS_LINK_MAX) { /* FIXME: sd_nlink is 32 bit for new files */ reiserfs_write_unlock(dir->i_sb); return -EMLINK; } /* inc before scheduling so reiserfs_unlink knows we are here */ inc_nlink(inode); retval = journal_begin(&th, dir->i_sb, jbegin_count); if (retval) { drop_nlink(inode); reiserfs_write_unlock(dir->i_sb); return retval; } /* create new entry */ retval = reiserfs_add_entry(&th, dir, dentry->d_name.name, dentry->d_name.len, inode, 1 /*visible */ ); reiserfs_update_inode_transaction(inode); reiserfs_update_inode_transaction(dir); if (retval) { int err; drop_nlink(inode); err = journal_end(&th); reiserfs_write_unlock(dir->i_sb); return err ? err : retval; } inode->i_ctime = current_time(inode); reiserfs_update_sd(&th, inode); ihold(inode); d_instantiate(dentry, inode); retval = journal_end(&th); reiserfs_write_unlock(dir->i_sb); return retval; } /* de contains information pointing to an entry which */ static int de_still_valid(const char *name, int len, struct reiserfs_dir_entry *de) { struct reiserfs_dir_entry tmp = *de; /* recalculate pointer to name and name length */ set_de_name_and_namelen(&tmp); /* FIXME: could check more */ if (tmp.de_namelen != len || memcmp(name, de->de_name, len)) return 0; return 1; } static int entry_points_to_object(const char *name, int len, struct reiserfs_dir_entry *de, struct inode *inode) { if (!de_still_valid(name, len, de)) return 0; if (inode) { if (!de_visible(de->de_deh + de->de_entry_num)) reiserfs_panic(inode->i_sb, "vs-7042", "entry must be visible"); return (de->de_objectid == inode->i_ino) ? 1 : 0; } /* this must be added hidden entry */ if (de_visible(de->de_deh + de->de_entry_num)) reiserfs_panic(NULL, "vs-7043", "entry must be visible"); return 1; } /* sets key of objectid the entry has to point to */ static void set_ino_in_dir_entry(struct reiserfs_dir_entry *de, struct reiserfs_key *key) { /* JDM These operations are endian safe - both are le */ de->de_deh[de->de_entry_num].deh_dir_id = key->k_dir_id; de->de_deh[de->de_entry_num].deh_objectid = key->k_objectid; } /* * process, that is going to call fix_nodes/do_balance must hold only * one path. If it holds 2 or more, it can get into endless waiting in * get_empty_nodes or its clones */ static int reiserfs_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, unsigned int flags) { int retval; INITIALIZE_PATH(old_entry_path); INITIALIZE_PATH(new_entry_path); INITIALIZE_PATH(dot_dot_entry_path); struct item_head new_entry_ih, old_entry_ih, dot_dot_ih; struct reiserfs_dir_entry old_de, new_de, dot_dot_de; struct inode *old_inode, *new_dentry_inode; struct reiserfs_transaction_handle th; int jbegin_count; umode_t old_inode_mode; unsigned long savelink = 1; struct timespec64 ctime; if (flags & ~RENAME_NOREPLACE) return -EINVAL; /* * three balancings: (1) old name removal, (2) new name insertion * and (3) maybe "save" link insertion * stat data updates: (1) old directory, * (2) new directory and (3) maybe old object stat data (when it is * directory) and (4) maybe stat data of object to which new entry * pointed initially and (5) maybe block containing ".." of * renamed directory * quota updates: two parent directories */ jbegin_count = JOURNAL_PER_BALANCE_CNT * 3 + 5 + 4 * REISERFS_QUOTA_TRANS_BLOCKS(old_dir->i_sb); retval = dquot_initialize(old_dir); if (retval) return retval; retval = dquot_initialize(new_dir); if (retval) return retval; old_inode = d_inode(old_dentry); new_dentry_inode = d_inode(new_dentry); /* * make sure that oldname still exists and points to an object we * are going to rename */ old_de.de_gen_number_bit_string = NULL; reiserfs_write_lock(old_dir->i_sb); retval = reiserfs_find_entry(old_dir, old_dentry->d_name.name, old_dentry->d_name.len, &old_entry_path, &old_de); pathrelse(&old_entry_path); if (retval == IO_ERROR) { reiserfs_write_unlock(old_dir->i_sb); return -EIO; } if (retval != NAME_FOUND || old_de.de_objectid != old_inode->i_ino) { reiserfs_write_unlock(old_dir->i_sb); return -ENOENT; } old_inode_mode = old_inode->i_mode; if (S_ISDIR(old_inode_mode)) { /* * make sure that directory being renamed has correct ".." * and that its new parent directory has not too many links * already */ if (new_dentry_inode) { if (!reiserfs_empty_dir(new_dentry_inode)) { reiserfs_write_unlock(old_dir->i_sb); return -ENOTEMPTY; } } /* * directory is renamed, its parent directory will be changed, * so find ".." entry */ dot_dot_de.de_gen_number_bit_string = NULL; retval = reiserfs_find_entry(old_inode, "..", 2, &dot_dot_entry_path, &dot_dot_de); pathrelse(&dot_dot_entry_path); if (retval != NAME_FOUND) { reiserfs_write_unlock(old_dir->i_sb); return -EIO; } /* inode number of .. must equal old_dir->i_ino */ if (dot_dot_de.de_objectid != old_dir->i_ino) { reiserfs_write_unlock(old_dir->i_sb); return -EIO; } } retval = journal_begin(&th, old_dir->i_sb, jbegin_count); if (retval) { reiserfs_write_unlock(old_dir->i_sb); return retval; } /* add new entry (or find the existing one) */ retval = reiserfs_add_entry(&th, new_dir, new_dentry->d_name.name, new_dentry->d_name.len, old_inode, 0); if (retval == -EEXIST) { if (!new_dentry_inode) { reiserfs_panic(old_dir->i_sb, "vs-7050", "new entry is found, new inode == 0"); } } else if (retval) { int err = journal_end(&th); reiserfs_write_unlock(old_dir->i_sb); return err ? err : retval; } reiserfs_update_inode_transaction(old_dir); reiserfs_update_inode_transaction(new_dir); /* * this makes it so an fsync on an open fd for the old name will * commit the rename operation */ reiserfs_update_inode_transaction(old_inode); if (new_dentry_inode) reiserfs_update_inode_transaction(new_dentry_inode); while (1) { /* * look for old name using corresponding entry key * (found by reiserfs_find_entry) */ if ((retval = search_by_entry_key(new_dir->i_sb, &old_de.de_entry_key, &old_entry_path, &old_de)) != NAME_FOUND) { pathrelse(&old_entry_path); journal_end(&th); reiserfs_write_unlock(old_dir->i_sb); return -EIO; } copy_item_head(&old_entry_ih, tp_item_head(&old_entry_path)); reiserfs_prepare_for_journal(old_inode->i_sb, old_de.de_bh, 1); /* look for new name by reiserfs_find_entry */ new_de.de_gen_number_bit_string = NULL; retval = reiserfs_find_entry(new_dir, new_dentry->d_name.name, new_dentry->d_name.len, &new_entry_path, &new_de); /* * reiserfs_add_entry should not return IO_ERROR, * because it is called with essentially same parameters from * reiserfs_add_entry above, and we'll catch any i/o errors * before we get here. */ if (retval != NAME_FOUND_INVISIBLE && retval != NAME_FOUND) { pathrelse(&new_entry_path); pathrelse(&old_entry_path); journal_end(&th); reiserfs_write_unlock(old_dir->i_sb); return -EIO; } copy_item_head(&new_entry_ih, tp_item_head(&new_entry_path)); reiserfs_prepare_for_journal(old_inode->i_sb, new_de.de_bh, 1); if (S_ISDIR(old_inode->i_mode)) { if ((retval = search_by_entry_key(new_dir->i_sb, &dot_dot_de.de_entry_key, &dot_dot_entry_path, &dot_dot_de)) != NAME_FOUND) { pathrelse(&dot_dot_entry_path); pathrelse(&new_entry_path); pathrelse(&old_entry_path); journal_end(&th); reiserfs_write_unlock(old_dir->i_sb); return -EIO; } copy_item_head(&dot_dot_ih, tp_item_head(&dot_dot_entry_path)); /* node containing ".." gets into transaction */ reiserfs_prepare_for_journal(old_inode->i_sb, dot_dot_de.de_bh, 1); } /* * we should check seals here, not do * this stuff, yes? Then, having * gathered everything into RAM we * should lock the buffers, yes? -Hans */ /* * probably. our rename needs to hold more * than one path at once. The seals would * have to be written to deal with multi-path * issues -chris */ /* * sanity checking before doing the rename - avoid races many * of the above checks could have scheduled. We have to be * sure our items haven't been shifted by another process. */ if (item_moved(&new_entry_ih, &new_entry_path) || !entry_points_to_object(new_dentry->d_name.name, new_dentry->d_name.len, &new_de, new_dentry_inode) || item_moved(&old_entry_ih, &old_entry_path) || !entry_points_to_object(old_dentry->d_name.name, old_dentry->d_name.len, &old_de, old_inode)) { reiserfs_restore_prepared_buffer(old_inode->i_sb, new_de.de_bh); reiserfs_restore_prepared_buffer(old_inode->i_sb, old_de.de_bh); if (S_ISDIR(old_inode_mode)) reiserfs_restore_prepared_buffer(old_inode-> i_sb, dot_dot_de. de_bh); continue; } if (S_ISDIR(old_inode_mode)) { if (item_moved(&dot_dot_ih, &dot_dot_entry_path) || !entry_points_to_object("..", 2, &dot_dot_de, old_dir)) { reiserfs_restore_prepared_buffer(old_inode-> i_sb, old_de.de_bh); reiserfs_restore_prepared_buffer(old_inode-> i_sb, new_de.de_bh); reiserfs_restore_prepared_buffer(old_inode-> i_sb, dot_dot_de. de_bh); continue; } } RFALSE(S_ISDIR(old_inode_mode) && !buffer_journal_prepared(dot_dot_de.de_bh), ""); break; } /* * ok, all the changes can be done in one fell swoop when we * have claimed all the buffers needed. */ mark_de_visible(new_de.de_deh + new_de.de_entry_num); set_ino_in_dir_entry(&new_de, INODE_PKEY(old_inode)); journal_mark_dirty(&th, new_de.de_bh); mark_de_hidden(old_de.de_deh + old_de.de_entry_num); journal_mark_dirty(&th, old_de.de_bh); ctime = current_time(old_dir); old_dir->i_ctime = old_dir->i_mtime = ctime; new_dir->i_ctime = new_dir->i_mtime = ctime; /* * thanks to Alex Adriaanse <[email protected]> for patch * which adds ctime update of renamed object */ old_inode->i_ctime = ctime; if (new_dentry_inode) { /* adjust link number of the victim */ if (S_ISDIR(new_dentry_inode->i_mode)) { clear_nlink(new_dentry_inode); } else { drop_nlink(new_dentry_inode); } new_dentry_inode->i_ctime = ctime; savelink = new_dentry_inode->i_nlink; } if (S_ISDIR(old_inode_mode)) { /* adjust ".." of renamed directory */ set_ino_in_dir_entry(&dot_dot_de, INODE_PKEY(new_dir)); journal_mark_dirty(&th, dot_dot_de.de_bh); /* * there (in new_dir) was no directory, so it got new link * (".." of renamed directory) */ if (!new_dentry_inode) INC_DIR_INODE_NLINK(new_dir); /* old directory lost one link - ".. " of renamed directory */ DEC_DIR_INODE_NLINK(old_dir); } /* * looks like in 2.3.99pre3 brelse is atomic. * so we can use pathrelse */ pathrelse(&new_entry_path); pathrelse(&dot_dot_entry_path); /* * FIXME: this reiserfs_cut_from_item's return value may screw up * anybody, but it will panic if will not be able to find the * entry. This needs one more clean up */ if (reiserfs_cut_from_item (&th, &old_entry_path, &old_de.de_entry_key, old_dir, NULL, 0) < 0) reiserfs_error(old_dir->i_sb, "vs-7060", "couldn't not cut old name. Fsck later?"); old_dir->i_size -= DEH_SIZE + old_de.de_entrylen; reiserfs_update_sd(&th, old_dir); reiserfs_update_sd(&th, new_dir); reiserfs_update_sd(&th, old_inode); if (new_dentry_inode) { if (savelink == 0) add_save_link(&th, new_dentry_inode, 0 /* not truncate */ ); reiserfs_update_sd(&th, new_dentry_inode); } retval = journal_end(&th); reiserfs_write_unlock(old_dir->i_sb); return retval; } /* directories can handle most operations... */ const struct inode_operations reiserfs_dir_inode_operations = { .create = reiserfs_create, .lookup = reiserfs_lookup, .link = reiserfs_link, .unlink = reiserfs_unlink, .symlink = reiserfs_symlink, .mkdir = reiserfs_mkdir, .rmdir = reiserfs_rmdir, .mknod = reiserfs_mknod, .rename = reiserfs_rename, .setattr = reiserfs_setattr, .listxattr = reiserfs_listxattr, .permission = reiserfs_permission, .get_acl = reiserfs_get_acl, .set_acl = reiserfs_set_acl, }; /* * symlink operations.. same as page_symlink_inode_operations, with xattr * stuff added */ const struct inode_operations reiserfs_symlink_inode_operations = { .get_link = page_get_link, .setattr = reiserfs_setattr, .listxattr = reiserfs_listxattr, .permission = reiserfs_permission, }; /* * special file operations.. just xattr/acl stuff */ const struct inode_operations reiserfs_special_inode_operations = { .setattr = reiserfs_setattr, .listxattr = reiserfs_listxattr, .permission = reiserfs_permission, .get_acl = reiserfs_get_acl, .set_acl = reiserfs_set_acl, };
{ "pile_set_name": "Github" }
/* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; var util = require('./util'); // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other // operating systems these days (capturing the result). var REGEX_NEWLINE = /(\r?\n)/g; // Matches a Windows-style newline, or any character. var REGEX_CHARACTER = /\r\n|[\s\S]/g; /** * SourceNodes provide a way to abstract over interpolating/concatenating * snippets of generated JavaScript source code while maintaining the line and * column information associated with the original source code. * * @param aLine The original line number. * @param aColumn The original column number. * @param aSource The original source's filename. * @param aChunks Optional. An array of strings which are snippets of * generated JS, or other SourceNodes. * @param aName The original identifier. */ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine === undefined ? null : aLine; this.column = aColumn === undefined ? null : aColumn; this.source = aSource === undefined ? null : aSource; this.name = aName === undefined ? null : aName; if (aChunks != null) this.add(aChunks); } /** * Creates a SourceNode from generated code and a SourceMapConsumer. * * @param aGeneratedCode The generated code * @param aSourceMapConsumer The SourceMap for the generated code */ SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) { // The SourceNode we want to fill with the generated code // and the SourceMap var node = new SourceNode(); // All even indices of this array are one line of the generated code, // while all odd indices are the newlines between two adjacent lines // (since `REGEX_NEWLINE` captures its match). // Processed fragments are removed from this array, by calling `shiftNextLine`. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); var shiftNextLine = function() { var lineContents = remainingLines.shift(); // The last line of a file might not have a newline. var newLine = remainingLines.shift() || ""; return lineContents + newLine; }; // We need to remember the position of "remainingLines" var lastGeneratedLine = 1, lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. // To extract it current and last mapping is used. // Here we store the last mapping. var lastMapping = null; aSourceMapConsumer.eachMapping(function (mapping) { if (lastMapping !== null) { // We add the code from "lastMapping" to "mapping": // First check if there is a new line in between. if (lastGeneratedLine < mapping.generatedLine) { var code = ""; // Associate first line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); lastGeneratedLine++; lastGeneratedColumn = 0; // The remaining code is added without mapping } else { // There is no new line in between. // Associate the code between "lastGeneratedColumn" and // "mapping.generatedColumn" with "lastMapping" var nextLine = remainingLines[0]; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[0] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); // No more remaining code, continue lastMapping = mapping; return; } } // We add the generated code until the first mapping // to the SourceNode without any mapping. // Each line is added as separate string. while (lastGeneratedLine < mapping.generatedLine) { node.add(shiftNextLine()); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[0]; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[0] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } lastMapping = mapping; }, this); // We have processed all mappings. if (remainingLines.length > 0) { if (lastMapping) { // Associate the remaining code in the current line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); } // and add the remaining lines without any mapping node.add(remainingLines.join("")); } // Copy sourcesContent into SourceNode aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === undefined) { node.add(code); } else { node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, mapping.source, code, mapping.name)); } } }; /** * Add a chunk of generated JS to this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function (chunk) { this.add(chunk); }, this); } else if (aChunk instanceof SourceNode || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Add a chunk of generated JS to the beginning of this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i = aChunk.length-1; i >= 0; i--) { this.prepend(aChunk[i]); } } else if (aChunk instanceof SourceNode || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Walk over the tree of JS snippets in this node and its children. The * walking function is called once for each snippet of JS and is passed that * snippet and the its original associated source's line/column location. * * @param aFn The traversal function. */ SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; if (chunk instanceof SourceNode) { chunk.walk(aFn); } else { if (chunk !== '') { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. * * @param aSep The separator. */ SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len-1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); this.children = newChildren; } return this; }; /** * Call String.prototype.replace on the very right-most source snippet. Useful * for trimming whitespace from the end of a source node, etc. * * @param aPattern The pattern to replace. * @param aReplacement The thing to replace the pattern with. */ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild instanceof SourceNode) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === 'string') { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push(''.replace(aPattern, aReplacement)); } return this; }; /** * Set the source content for a source file. This will be added to the SourceMapGenerator * in the sourcesContent field. * * @param aSourceFile The filename of the source file * @param aSourceContent The content of the source file */ SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; }; /** * Walk over the tree of SourceNodes. The walking function is called for each * source file content and is passed the filename and source content. * * @param aFn The traversal function. */ SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i = 0, len = this.children.length; i < len; i++) { if (this.children[i] instanceof SourceNode) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; /** * Return the string representation of this source node. Walks over the tree * and concatenates all the various snippets together to one string. */ SourceNode.prototype.toString = function SourceNode_toString() { var str = ""; this.walk(function (chunk) { str += chunk; }); return str; }; /** * Returns the string representation of this source node along with a source * map. */ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function (chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if(lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } chunk.match(REGEX_CHARACTER).forEach(function (ch, idx, array) { if (REGEX_NEWLINE.test(ch)) { generated.line++; generated.column = 0; // Mappings end at eol if (idx + 1 === array.length) { lastOriginalSource = null; sourceMappingActive = false; } else if (sourceMappingActive) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } } else { generated.column += ch.length; } }); }); this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map }; }; exports.SourceNode = SourceNode; });
{ "pile_set_name": "Github" }
// Copyright 2009 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 bufio_test import ( . "bufio" "bytes" "errors" "fmt" "io" "io/ioutil" "strings" "testing" "testing/iotest" "unicode/utf8" ) // Reads from a reader and rot13s the result. type rot13Reader struct { r io.Reader } func newRot13Reader(r io.Reader) *rot13Reader { r13 := new(rot13Reader) r13.r = r return r13 } func (r13 *rot13Reader) Read(p []byte) (int, error) { n, err := r13.r.Read(p) if err != nil { return n, err } for i := 0; i < n; i++ { c := p[i] | 0x20 // lowercase byte if 'a' <= c && c <= 'm' { p[i] += 13 } else if 'n' <= c && c <= 'z' { p[i] -= 13 } } return n, nil } // Call ReadByte to accumulate the text of a file func readBytes(buf *Reader) string { var b [1000]byte nb := 0 for { c, err := buf.ReadByte() if err == io.EOF { break } if err == nil { b[nb] = c nb++ } else if err != iotest.ErrTimeout { panic("Data: " + err.Error()) } } return string(b[0:nb]) } func TestReaderSimple(t *testing.T) { data := "hello world" b := NewReader(bytes.NewBufferString(data)) if s := readBytes(b); s != "hello world" { t.Errorf("simple hello world test failed: got %q", s) } b = NewReader(newRot13Reader(bytes.NewBufferString(data))) if s := readBytes(b); s != "uryyb jbeyq" { t.Errorf("rot13 hello world test failed: got %q", s) } } type readMaker struct { name string fn func(io.Reader) io.Reader } var readMakers = []readMaker{ {"full", func(r io.Reader) io.Reader { return r }}, {"byte", iotest.OneByteReader}, {"half", iotest.HalfReader}, {"data+err", iotest.DataErrReader}, {"timeout", iotest.TimeoutReader}, } // Call ReadString (which ends up calling everything else) // to accumulate the text of a file. func readLines(b *Reader) string { s := "" for { s1, err := b.ReadString('\n') if err == io.EOF { break } if err != nil && err != iotest.ErrTimeout { panic("GetLines: " + err.Error()) } s += s1 } return s } // Call Read to accumulate the text of a file func reads(buf *Reader, m int) string { var b [1000]byte nb := 0 for { n, err := buf.Read(b[nb : nb+m]) nb += n if err == io.EOF { break } } return string(b[0:nb]) } type bufReader struct { name string fn func(*Reader) string } var bufreaders = []bufReader{ {"1", func(b *Reader) string { return reads(b, 1) }}, {"2", func(b *Reader) string { return reads(b, 2) }}, {"3", func(b *Reader) string { return reads(b, 3) }}, {"4", func(b *Reader) string { return reads(b, 4) }}, {"5", func(b *Reader) string { return reads(b, 5) }}, {"7", func(b *Reader) string { return reads(b, 7) }}, {"bytes", readBytes}, {"lines", readLines}, } const minReadBufferSize = 16 var bufsizes = []int{ minReadBufferSize, 23, 32, 46, 64, 93, 128, 1024, 4096, } func TestReader(t *testing.T) { var texts [31]string str := "" all := "" for i := 0; i < len(texts)-1; i++ { texts[i] = str + "\n" all += texts[i] str += string(i%26 + 'a') } texts[len(texts)-1] = all for h := 0; h < len(texts); h++ { text := texts[h] for i := 0; i < len(readMakers); i++ { for j := 0; j < len(bufreaders); j++ { for k := 0; k < len(bufsizes); k++ { readmaker := readMakers[i] bufreader := bufreaders[j] bufsize := bufsizes[k] read := readmaker.fn(bytes.NewBufferString(text)) buf := NewReaderSize(read, bufsize) s := bufreader.fn(buf) if s != text { t.Errorf("reader=%s fn=%s bufsize=%d want=%q got=%q", readmaker.name, bufreader.name, bufsize, text, s) } } } } } } // A StringReader delivers its data one string segment at a time via Read. type StringReader struct { data []string step int } func (r *StringReader) Read(p []byte) (n int, err error) { if r.step < len(r.data) { s := r.data[r.step] n = copy(p, s) r.step++ } else { err = io.EOF } return } func readRuneSegments(t *testing.T, segments []string) { got := "" want := strings.Join(segments, "") r := NewReader(&StringReader{data: segments}) for { r, _, err := r.ReadRune() if err != nil { if err != io.EOF { return } break } got += string(r) } if got != want { t.Errorf("segments=%v got=%s want=%s", segments, got, want) } } var segmentList = [][]string{ {}, {""}, {"日", "本語"}, {"\u65e5", "\u672c", "\u8a9e"}, {"\U000065e5", "\U0000672c", "\U00008a9e"}, {"\xe6", "\x97\xa5\xe6", "\x9c\xac\xe8\xaa\x9e"}, {"Hello", ", ", "World", "!"}, {"Hello", ", ", "", "World", "!"}, } func TestReadRune(t *testing.T) { for _, s := range segmentList { readRuneSegments(t, s) } } func TestUnreadRune(t *testing.T) { got := "" segments := []string{"Hello, world:", "日本語"} data := strings.Join(segments, "") r := NewReader(&StringReader{data: segments}) // Normal execution. for { r1, _, err := r.ReadRune() if err != nil { if err != io.EOF { t.Error("unexpected EOF") } break } got += string(r1) // Put it back and read it again if err = r.UnreadRune(); err != nil { t.Error("unexpected error on UnreadRune:", err) } r2, _, err := r.ReadRune() if err != nil { t.Error("unexpected error reading after unreading:", err) } if r1 != r2 { t.Errorf("incorrect rune after unread: got %c wanted %c", r1, r2) } } if got != data { t.Errorf("want=%q got=%q", data, got) } } // Test that UnreadRune fails if the preceding operation was not a ReadRune. func TestUnreadRuneError(t *testing.T) { buf := make([]byte, 3) // All runes in this test are 3 bytes long r := NewReader(&StringReader{data: []string{"日本語日本語日本語"}}) if r.UnreadRune() == nil { t.Error("expected error on UnreadRune from fresh buffer") } _, _, err := r.ReadRune() if err != nil { t.Error("unexpected error on ReadRune (1):", err) } if err = r.UnreadRune(); err != nil { t.Error("unexpected error on UnreadRune (1):", err) } if r.UnreadRune() == nil { t.Error("expected error after UnreadRune (1)") } // Test error after Read. _, _, err = r.ReadRune() // reset state if err != nil { t.Error("unexpected error on ReadRune (2):", err) } _, err = r.Read(buf) if err != nil { t.Error("unexpected error on Read (2):", err) } if r.UnreadRune() == nil { t.Error("expected error after Read (2)") } // Test error after ReadByte. _, _, err = r.ReadRune() // reset state if err != nil { t.Error("unexpected error on ReadRune (2):", err) } for _ = range buf { _, err = r.ReadByte() if err != nil { t.Error("unexpected error on ReadByte (2):", err) } } if r.UnreadRune() == nil { t.Error("expected error after ReadByte") } // Test error after UnreadByte. _, _, err = r.ReadRune() // reset state if err != nil { t.Error("unexpected error on ReadRune (3):", err) } _, err = r.ReadByte() if err != nil { t.Error("unexpected error on ReadByte (3):", err) } err = r.UnreadByte() if err != nil { t.Error("unexpected error on UnreadByte (3):", err) } if r.UnreadRune() == nil { t.Error("expected error after UnreadByte (3)") } } func TestUnreadRuneAtEOF(t *testing.T) { // UnreadRune/ReadRune should error at EOF (was a bug; used to panic) r := NewReader(strings.NewReader("x")) r.ReadRune() r.ReadRune() r.UnreadRune() _, _, err := r.ReadRune() if err == nil { t.Error("expected error at EOF") } else if err != io.EOF { t.Error("expected EOF; got", err) } } func TestReadWriteRune(t *testing.T) { const NRune = 1000 byteBuf := new(bytes.Buffer) w := NewWriter(byteBuf) // Write the runes out using WriteRune buf := make([]byte, utf8.UTFMax) for r := rune(0); r < NRune; r++ { size := utf8.EncodeRune(buf, r) nbytes, err := w.WriteRune(r) if err != nil { t.Fatalf("WriteRune(0x%x) error: %s", r, err) } if nbytes != size { t.Fatalf("WriteRune(0x%x) expected %d, got %d", r, size, nbytes) } } w.Flush() r := NewReader(byteBuf) // Read them back with ReadRune for r1 := rune(0); r1 < NRune; r1++ { size := utf8.EncodeRune(buf, r1) nr, nbytes, err := r.ReadRune() if nr != r1 || nbytes != size || err != nil { t.Fatalf("ReadRune(0x%x) got 0x%x,%d not 0x%x,%d (err=%s)", r1, nr, nbytes, r1, size, err) } } } func TestWriter(t *testing.T) { var data [8192]byte for i := 0; i < len(data); i++ { data[i] = byte(' ' + i%('~'-' ')) } w := new(bytes.Buffer) for i := 0; i < len(bufsizes); i++ { for j := 0; j < len(bufsizes); j++ { nwrite := bufsizes[i] bs := bufsizes[j] // Write nwrite bytes using buffer size bs. // Check that the right amount makes it out // and that the data is correct. w.Reset() buf := NewWriterSize(w, bs) context := fmt.Sprintf("nwrite=%d bufsize=%d", nwrite, bs) n, e1 := buf.Write(data[0:nwrite]) if e1 != nil || n != nwrite { t.Errorf("%s: buf.Write %d = %d, %v", context, nwrite, n, e1) continue } if e := buf.Flush(); e != nil { t.Errorf("%s: buf.Flush = %v", context, e) } written := w.Bytes() if len(written) != nwrite { t.Errorf("%s: %d bytes written", context, len(written)) } for l := 0; l < len(written); l++ { if written[i] != data[i] { t.Errorf("wrong bytes written") t.Errorf("want=%q", data[0:len(written)]) t.Errorf("have=%q", written) } } } } } // Check that write errors are returned properly. type errorWriterTest struct { n, m int err error expect error } func (w errorWriterTest) Write(p []byte) (int, error) { return len(p) * w.n / w.m, w.err } var errorWriterTests = []errorWriterTest{ {0, 1, nil, io.ErrShortWrite}, {1, 2, nil, io.ErrShortWrite}, {1, 1, nil, nil}, {0, 1, io.ErrClosedPipe, io.ErrClosedPipe}, {1, 2, io.ErrClosedPipe, io.ErrClosedPipe}, {1, 1, io.ErrClosedPipe, io.ErrClosedPipe}, } func TestWriteErrors(t *testing.T) { for _, w := range errorWriterTests { buf := NewWriter(w) _, e := buf.Write([]byte("hello world")) if e != nil { t.Errorf("Write hello to %v: %v", w, e) continue } // Two flushes, to verify the error is sticky. for i := 0; i < 2; i++ { e = buf.Flush() if e != w.expect { t.Errorf("Flush %d/2 %v: got %v, wanted %v", i+1, w, e, w.expect) } } } } func TestNewReaderSizeIdempotent(t *testing.T) { const BufSize = 1000 b := NewReaderSize(bytes.NewBufferString("hello world"), BufSize) // Does it recognize itself? b1 := NewReaderSize(b, BufSize) if b1 != b { t.Error("NewReaderSize did not detect underlying Reader") } // Does it wrap if existing buffer is too small? b2 := NewReaderSize(b, 2*BufSize) if b2 == b { t.Error("NewReaderSize did not enlarge buffer") } } func TestNewWriterSizeIdempotent(t *testing.T) { const BufSize = 1000 b := NewWriterSize(new(bytes.Buffer), BufSize) // Does it recognize itself? b1 := NewWriterSize(b, BufSize) if b1 != b { t.Error("NewWriterSize did not detect underlying Writer") } // Does it wrap if existing buffer is too small? b2 := NewWriterSize(b, 2*BufSize) if b2 == b { t.Error("NewWriterSize did not enlarge buffer") } } func TestWriteString(t *testing.T) { const BufSize = 8 buf := new(bytes.Buffer) b := NewWriterSize(buf, BufSize) b.WriteString("0") // easy b.WriteString("123456") // still easy b.WriteString("7890") // easy after flush b.WriteString("abcdefghijklmnopqrstuvwxy") // hard b.WriteString("z") if err := b.Flush(); err != nil { t.Error("WriteString", err) } s := "01234567890abcdefghijklmnopqrstuvwxyz" if string(buf.Bytes()) != s { t.Errorf("WriteString wants %q gets %q", s, string(buf.Bytes())) } } func TestBufferFull(t *testing.T) { const longString = "And now, hello, world! It is the time for all good men to come to the aid of their party" buf := NewReaderSize(strings.NewReader(longString), minReadBufferSize) line, err := buf.ReadSlice('!') if string(line) != "And now, hello, " || err != ErrBufferFull { t.Errorf("first ReadSlice(,) = %q, %v", line, err) } line, err = buf.ReadSlice('!') if string(line) != "world!" || err != nil { t.Errorf("second ReadSlice(,) = %q, %v", line, err) } } func TestPeek(t *testing.T) { p := make([]byte, 10) // string is 16 (minReadBufferSize) long. buf := NewReaderSize(strings.NewReader("abcdefghijklmnop"), minReadBufferSize) if s, err := buf.Peek(1); string(s) != "a" || err != nil { t.Fatalf("want %q got %q, err=%v", "a", string(s), err) } if s, err := buf.Peek(4); string(s) != "abcd" || err != nil { t.Fatalf("want %q got %q, err=%v", "abcd", string(s), err) } if _, err := buf.Peek(32); err != ErrBufferFull { t.Fatalf("want ErrBufFull got %v", err) } if _, err := buf.Read(p[0:3]); string(p[0:3]) != "abc" || err != nil { t.Fatalf("want %q got %q, err=%v", "abc", string(p[0:3]), err) } if s, err := buf.Peek(1); string(s) != "d" || err != nil { t.Fatalf("want %q got %q, err=%v", "d", string(s), err) } if s, err := buf.Peek(2); string(s) != "de" || err != nil { t.Fatalf("want %q got %q, err=%v", "de", string(s), err) } if _, err := buf.Read(p[0:3]); string(p[0:3]) != "def" || err != nil { t.Fatalf("want %q got %q, err=%v", "def", string(p[0:3]), err) } if s, err := buf.Peek(4); string(s) != "ghij" || err != nil { t.Fatalf("want %q got %q, err=%v", "ghij", string(s), err) } if _, err := buf.Read(p[0:]); string(p[0:]) != "ghijklmnop" || err != nil { t.Fatalf("want %q got %q, err=%v", "ghijklmnop", string(p[0:minReadBufferSize]), err) } if s, err := buf.Peek(0); string(s) != "" || err != nil { t.Fatalf("want %q got %q, err=%v", "", string(s), err) } if _, err := buf.Peek(1); err != io.EOF { t.Fatalf("want EOF got %v", err) } // Test for issue 3022, not exposing a reader's error on a successful Peek. buf = NewReaderSize(dataAndEOFReader("abcd"), 32) if s, err := buf.Peek(2); string(s) != "ab" || err != nil { t.Errorf(`Peek(2) on "abcd", EOF = %q, %v; want "ab", nil`, string(s), err) } if s, err := buf.Peek(4); string(s) != "abcd" || err != nil { t.Errorf(`Peek(4) on "abcd", EOF = %q, %v; want "abcd", nil`, string(s), err) } if n, err := buf.Read(p[0:5]); string(p[0:n]) != "abcd" || err != nil { t.Fatalf("Read after peek = %q, %v; want abcd, EOF", p[0:n], err) } if n, err := buf.Read(p[0:1]); string(p[0:n]) != "" || err != io.EOF { t.Fatalf(`second Read after peek = %q, %v; want "", EOF`, p[0:n], err) } } type dataAndEOFReader string func (r dataAndEOFReader) Read(p []byte) (int, error) { return copy(p, r), io.EOF } func TestPeekThenUnreadRune(t *testing.T) { // This sequence used to cause a crash. r := NewReader(strings.NewReader("x")) r.ReadRune() r.Peek(1) r.UnreadRune() r.ReadRune() // Used to panic here } var testOutput = []byte("0123456789abcdefghijklmnopqrstuvwxy") var testInput = []byte("012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy") var testInputrn = []byte("012\r\n345\r\n678\r\n9ab\r\ncde\r\nfgh\r\nijk\r\nlmn\r\nopq\r\nrst\r\nuvw\r\nxy\r\n\n\r\n") // TestReader wraps a []byte and returns reads of a specific length. type testReader struct { data []byte stride int } func (t *testReader) Read(buf []byte) (n int, err error) { n = t.stride if n > len(t.data) { n = len(t.data) } if n > len(buf) { n = len(buf) } copy(buf, t.data) t.data = t.data[n:] if len(t.data) == 0 { err = io.EOF } return } func testReadLine(t *testing.T, input []byte) { //for stride := 1; stride < len(input); stride++ { for stride := 1; stride < 2; stride++ { done := 0 reader := testReader{input, stride} l := NewReaderSize(&reader, len(input)+1) for { line, isPrefix, err := l.ReadLine() if len(line) > 0 && err != nil { t.Errorf("ReadLine returned both data and error: %s", err) } if isPrefix { t.Errorf("ReadLine returned prefix") } if err != nil { if err != io.EOF { t.Fatalf("Got unknown error: %s", err) } break } if want := testOutput[done : done+len(line)]; !bytes.Equal(want, line) { t.Errorf("Bad line at stride %d: want: %x got: %x", stride, want, line) } done += len(line) } if done != len(testOutput) { t.Errorf("ReadLine didn't return everything: got: %d, want: %d (stride: %d)", done, len(testOutput), stride) } } } func TestReadLine(t *testing.T) { testReadLine(t, testInput) testReadLine(t, testInputrn) } func TestLineTooLong(t *testing.T) { data := make([]byte, 0) for i := 0; i < minReadBufferSize*5/2; i++ { data = append(data, '0'+byte(i%10)) } buf := bytes.NewBuffer(data) l := NewReaderSize(buf, minReadBufferSize) line, isPrefix, err := l.ReadLine() if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil { t.Errorf("bad result for first line: got %q want %q %v", line, data[:minReadBufferSize], err) } data = data[len(line):] line, isPrefix, err = l.ReadLine() if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil { t.Errorf("bad result for second line: got %q want %q %v", line, data[:minReadBufferSize], err) } data = data[len(line):] line, isPrefix, err = l.ReadLine() if isPrefix || !bytes.Equal(line, data[:minReadBufferSize/2]) || err != nil { t.Errorf("bad result for third line: got %q want %q %v", line, data[:minReadBufferSize/2], err) } line, isPrefix, err = l.ReadLine() if isPrefix || err == nil { t.Errorf("expected no more lines: %x %s", line, err) } } func TestReadAfterLines(t *testing.T) { line1 := "this is line1" restData := "this is line2\nthis is line 3\n" inbuf := bytes.NewBuffer([]byte(line1 + "\n" + restData)) outbuf := new(bytes.Buffer) maxLineLength := len(line1) + len(restData)/2 l := NewReaderSize(inbuf, maxLineLength) line, isPrefix, err := l.ReadLine() if isPrefix || err != nil || string(line) != line1 { t.Errorf("bad result for first line: isPrefix=%v err=%v line=%q", isPrefix, err, string(line)) } n, err := io.Copy(outbuf, l) if int(n) != len(restData) || err != nil { t.Errorf("bad result for Read: n=%d err=%v", n, err) } if outbuf.String() != restData { t.Errorf("bad result for Read: got %q; expected %q", outbuf.String(), restData) } } func TestReadEmptyBuffer(t *testing.T) { l := NewReaderSize(new(bytes.Buffer), minReadBufferSize) line, isPrefix, err := l.ReadLine() if err != io.EOF { t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err) } } func TestLinesAfterRead(t *testing.T) { l := NewReaderSize(bytes.NewBuffer([]byte("foo")), minReadBufferSize) _, err := ioutil.ReadAll(l) if err != nil { t.Error(err) return } line, isPrefix, err := l.ReadLine() if err != io.EOF { t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err) } } func TestReadLineNonNilLineOrError(t *testing.T) { r := NewReader(strings.NewReader("line 1\n")) for i := 0; i < 2; i++ { l, _, err := r.ReadLine() if l != nil && err != nil { t.Fatalf("on line %d/2; ReadLine=%#v, %v; want non-nil line or Error, but not both", i+1, l, err) } } } type readLineResult struct { line []byte isPrefix bool err error } var readLineNewlinesTests = []struct { input string expect []readLineResult }{ {"012345678901234\r\n012345678901234\r\n", []readLineResult{ {[]byte("012345678901234"), true, nil}, {nil, false, nil}, {[]byte("012345678901234"), true, nil}, {nil, false, nil}, {nil, false, io.EOF}, }}, {"0123456789012345\r012345678901234\r", []readLineResult{ {[]byte("0123456789012345"), true, nil}, {[]byte("\r012345678901234"), true, nil}, {[]byte("\r"), false, nil}, {nil, false, io.EOF}, }}, } func TestReadLineNewlines(t *testing.T) { for _, e := range readLineNewlinesTests { testReadLineNewlines(t, e.input, e.expect) } } func testReadLineNewlines(t *testing.T, input string, expect []readLineResult) { b := NewReaderSize(strings.NewReader(input), minReadBufferSize) for i, e := range expect { line, isPrefix, err := b.ReadLine() if !bytes.Equal(line, e.line) { t.Errorf("%q call %d, line == %q, want %q", input, i, line, e.line) return } if isPrefix != e.isPrefix { t.Errorf("%q call %d, isPrefix == %v, want %v", input, i, isPrefix, e.isPrefix) return } if err != e.err { t.Errorf("%q call %d, err == %v, want %v", input, i, err, e.err) return } } } func createTestInput(n int) []byte { input := make([]byte, n) for i := range input { // 101 and 251 are arbitrary prime numbers. // The idea is to create an input sequence // which doesn't repeat too frequently. input[i] = byte(i % 251) if i%101 == 0 { input[i] ^= byte(i / 101) } } return input } func TestReaderWriteTo(t *testing.T) { input := createTestInput(8192) r := NewReader(onlyReader{bytes.NewBuffer(input)}) w := new(bytes.Buffer) if n, err := r.WriteTo(w); err != nil || n != int64(len(input)) { t.Fatalf("r.WriteTo(w) = %d, %v, want %d, nil", n, err, len(input)) } for i, val := range w.Bytes() { if val != input[i] { t.Errorf("after write: out[%d] = %#x, want %#x", i, val, input[i]) } } } type errorWriterToTest struct { rn, wn int rerr, werr error expected error } func (r errorWriterToTest) Read(p []byte) (int, error) { return len(p) * r.rn, r.rerr } func (w errorWriterToTest) Write(p []byte) (int, error) { return len(p) * w.wn, w.werr } var errorWriterToTests = []errorWriterToTest{ {1, 0, nil, io.ErrClosedPipe, io.ErrClosedPipe}, {0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe}, {0, 0, io.ErrUnexpectedEOF, io.ErrClosedPipe, io.ErrClosedPipe}, {0, 1, io.EOF, nil, nil}, } func TestReaderWriteToErrors(t *testing.T) { for i, rw := range errorWriterToTests { r := NewReader(rw) if _, err := r.WriteTo(rw); err != rw.expected { t.Errorf("r.WriteTo(errorWriterToTests[%d]) = _, %v, want _,%v", i, err, rw.expected) } } } func TestWriterReadFrom(t *testing.T) { ws := []func(io.Writer) io.Writer{ func(w io.Writer) io.Writer { return onlyWriter{w} }, func(w io.Writer) io.Writer { return w }, } rs := []func(io.Reader) io.Reader{ iotest.DataErrReader, func(r io.Reader) io.Reader { return r }, } for ri, rfunc := range rs { for wi, wfunc := range ws { input := createTestInput(8192) b := new(bytes.Buffer) w := NewWriter(wfunc(b)) r := rfunc(bytes.NewBuffer(input)) if n, err := w.ReadFrom(r); err != nil || n != int64(len(input)) { t.Errorf("ws[%d],rs[%d]: w.ReadFrom(r) = %d, %v, want %d, nil", wi, ri, n, err, len(input)) continue } if got, want := b.String(), string(input); got != want { t.Errorf("ws[%d], rs[%d]:\ngot %q\nwant %q\n", wi, ri, got, want) } } } } type errorReaderFromTest struct { rn, wn int rerr, werr error expected error } func (r errorReaderFromTest) Read(p []byte) (int, error) { return len(p) * r.rn, r.rerr } func (w errorReaderFromTest) Write(p []byte) (int, error) { return len(p) * w.wn, w.werr } var errorReaderFromTests = []errorReaderFromTest{ {0, 1, io.EOF, nil, nil}, {1, 1, io.EOF, nil, nil}, {0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe}, {0, 0, io.ErrClosedPipe, io.ErrShortWrite, io.ErrClosedPipe}, {1, 0, nil, io.ErrShortWrite, io.ErrShortWrite}, } func TestWriterReadFromErrors(t *testing.T) { for i, rw := range errorReaderFromTests { w := NewWriter(rw) if _, err := w.ReadFrom(rw); err != rw.expected { t.Errorf("w.ReadFrom(errorReaderFromTests[%d]) = _, %v, want _,%v", i, err, rw.expected) } } } // TestWriterReadFromCounts tests that using io.Copy to copy into a // bufio.Writer does not prematurely flush the buffer. For example, when // buffering writes to a network socket, excessive network writes should be // avoided. func TestWriterReadFromCounts(t *testing.T) { var w0 writeCountingDiscard b0 := NewWriterSize(&w0, 1234) b0.WriteString(strings.Repeat("x", 1000)) if w0 != 0 { t.Fatalf("write 1000 'x's: got %d writes, want 0", w0) } b0.WriteString(strings.Repeat("x", 200)) if w0 != 0 { t.Fatalf("write 1200 'x's: got %d writes, want 0", w0) } io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 30))}) if w0 != 0 { t.Fatalf("write 1230 'x's: got %d writes, want 0", w0) } io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 9))}) if w0 != 1 { t.Fatalf("write 1239 'x's: got %d writes, want 1", w0) } var w1 writeCountingDiscard b1 := NewWriterSize(&w1, 1234) b1.WriteString(strings.Repeat("x", 1200)) b1.Flush() if w1 != 1 { t.Fatalf("flush 1200 'x's: got %d writes, want 1", w1) } b1.WriteString(strings.Repeat("x", 89)) if w1 != 1 { t.Fatalf("write 1200 + 89 'x's: got %d writes, want 1", w1) } io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 700))}) if w1 != 1 { t.Fatalf("write 1200 + 789 'x's: got %d writes, want 1", w1) } io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 600))}) if w1 != 2 { t.Fatalf("write 1200 + 1389 'x's: got %d writes, want 2", w1) } b1.Flush() if w1 != 3 { t.Fatalf("flush 1200 + 1389 'x's: got %d writes, want 3", w1) } } // A writeCountingDiscard is like ioutil.Discard and counts the number of times // Write is called on it. type writeCountingDiscard int func (w *writeCountingDiscard) Write(p []byte) (int, error) { *w++ return len(p), nil } type negativeReader int func (r *negativeReader) Read([]byte) (int, error) { return -1, nil } func TestNegativeRead(t *testing.T) { // should panic with a description pointing at the reader, not at itself. // (should NOT panic with slice index error, for example.) b := NewReader(new(negativeReader)) defer func() { switch err := recover().(type) { case nil: t.Fatal("read did not panic") case error: if !strings.Contains(err.Error(), "reader returned negative count from Read") { t.Fatalf("wrong panic: %v", err) } default: t.Fatalf("unexpected panic value: %T(%v)", err, err) } }() b.Read(make([]byte, 100)) } var errFake = errors.New("fake error") type errorThenGoodReader struct { didErr bool nread int } func (r *errorThenGoodReader) Read(p []byte) (int, error) { r.nread++ if !r.didErr { r.didErr = true return 0, errFake } return len(p), nil } func TestReaderClearError(t *testing.T) { r := &errorThenGoodReader{} b := NewReader(r) buf := make([]byte, 1) if _, err := b.Read(nil); err != nil { t.Fatalf("1st nil Read = %v; want nil", err) } if _, err := b.Read(buf); err != errFake { t.Fatalf("1st Read = %v; want errFake", err) } if _, err := b.Read(nil); err != nil { t.Fatalf("2nd nil Read = %v; want nil", err) } if _, err := b.Read(buf); err != nil { t.Fatalf("3rd Read with buffer = %v; want nil", err) } if r.nread != 2 { t.Errorf("num reads = %d; want 2", r.nread) } } // An onlyReader only implements io.Reader, no matter what other methods the underlying implementation may have. type onlyReader struct { r io.Reader } func (r onlyReader) Read(b []byte) (int, error) { return r.r.Read(b) } // An onlyWriter only implements io.Writer, no matter what other methods the underlying implementation may have. type onlyWriter struct { w io.Writer } func (w onlyWriter) Write(b []byte) (int, error) { return w.w.Write(b) } func BenchmarkReaderCopyOptimal(b *testing.B) { // Optimal case is where the underlying reader implements io.WriterTo for i := 0; i < b.N; i++ { b.StopTimer() src := NewReader(bytes.NewBuffer(make([]byte, 8192))) dst := onlyWriter{new(bytes.Buffer)} b.StartTimer() io.Copy(dst, src) } } func BenchmarkReaderCopyUnoptimal(b *testing.B) { // Unoptimal case is where the underlying reader doesn't implement io.WriterTo for i := 0; i < b.N; i++ { b.StopTimer() src := NewReader(onlyReader{bytes.NewBuffer(make([]byte, 8192))}) dst := onlyWriter{new(bytes.Buffer)} b.StartTimer() io.Copy(dst, src) } } func BenchmarkReaderCopyNoWriteTo(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() src := onlyReader{NewReader(bytes.NewBuffer(make([]byte, 8192)))} dst := onlyWriter{new(bytes.Buffer)} b.StartTimer() io.Copy(dst, src) } } func BenchmarkWriterCopyOptimal(b *testing.B) { // Optimal case is where the underlying writer implements io.ReaderFrom for i := 0; i < b.N; i++ { b.StopTimer() src := onlyReader{bytes.NewBuffer(make([]byte, 8192))} dst := NewWriter(new(bytes.Buffer)) b.StartTimer() io.Copy(dst, src) } } func BenchmarkWriterCopyUnoptimal(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() src := onlyReader{bytes.NewBuffer(make([]byte, 8192))} dst := NewWriter(onlyWriter{new(bytes.Buffer)}) b.StartTimer() io.Copy(dst, src) } } func BenchmarkWriterCopyNoReadFrom(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() src := onlyReader{bytes.NewBuffer(make([]byte, 8192))} dst := onlyWriter{NewWriter(new(bytes.Buffer))} b.StartTimer() io.Copy(dst, src) } }
{ "pile_set_name": "Github" }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Flurl.Util; namespace Flurl.Http { /// <summary> /// Fluent extension methods for working with HTTP request headers. /// </summary> public static class HeaderExtensions { /// <summary> /// Sets an HTTP header to be sent with this IFlurlRequest or all requests made with this IFlurlClient. /// </summary> /// <param name="clientOrRequest">The IFlurlClient or IFlurlRequest.</param> /// <param name="name">HTTP header name.</param> /// <param name="value">HTTP header value.</param> /// <returns>This IFlurlClient or IFlurlRequest.</returns> public static T WithHeader<T>(this T clientOrRequest, string name, object value) where T : IHttpSettingsContainer { if (value == null) clientOrRequest.Headers.Remove(name); else clientOrRequest.Headers.AddOrReplace(name, value.ToInvariantString()); return clientOrRequest; } /// <summary> /// Sets HTTP headers based on property names/values of the provided object, or keys/values if object is a dictionary, to be sent with this IFlurlRequest or all requests made with this IFlurlClient. /// </summary> /// <param name="clientOrRequest">The IFlurlClient or IFlurlRequest.</param> /// <param name="headers">Names/values of HTTP headers to set. Typically an anonymous object or IDictionary.</param> /// <param name="replaceUnderscoreWithHyphen">If true, underscores in property names will be replaced by hyphens. Default is true.</param> /// <returns>This IFlurlClient or IFlurlRequest.</returns> public static T WithHeaders<T>(this T clientOrRequest, object headers, bool replaceUnderscoreWithHyphen = true) where T : IHttpSettingsContainer { if (headers == null) return clientOrRequest; // underscore replacement only applies when object properties are parsed to kv pairs replaceUnderscoreWithHyphen = replaceUnderscoreWithHyphen && !(headers is string) && !(headers is IEnumerable); foreach (var kv in headers.ToKeyValuePairs()) { var key = replaceUnderscoreWithHyphen ? kv.Key.Replace("_", "-") : kv.Key; clientOrRequest.WithHeader(key, kv.Value); } return clientOrRequest; } /// <summary> /// Sets HTTP authorization header according to Basic Authentication protocol to be sent with this IFlurlRequest or all requests made with this IFlurlClient. /// </summary> /// <param name="clientOrRequest">The IFlurlClient or IFlurlRequest.</param> /// <param name="username">Username of authenticating user.</param> /// <param name="password">Password of authenticating user.</param> /// <returns>This IFlurlClient or IFlurlRequest.</returns> public static T WithBasicAuth<T>(this T clientOrRequest, string username, string password) where T : IHttpSettingsContainer { // http://stackoverflow.com/questions/14627399/setting-authorization-header-of-httpclient var encodedCreds = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}")); return clientOrRequest.WithHeader("Authorization", $"Basic {encodedCreds}"); } /// <summary> /// Sets HTTP authorization header with acquired bearer token according to OAuth 2.0 specification to be sent with this IFlurlRequest or all requests made with this IFlurlClient. /// </summary> /// <param name="clientOrRequest">The IFlurlClient or IFlurlRequest.</param> /// <param name="token">The acquired bearer token to pass.</param> /// <returns>This IFlurlClient or IFlurlRequest.</returns> public static T WithOAuthBearerToken<T>(this T clientOrRequest, string token) where T : IHttpSettingsContainer { return clientOrRequest.WithHeader("Authorization", $"Bearer {token}"); } } }
{ "pile_set_name": "Github" }
/* Copyright (C) 2003 Jean-Marc Valin */ /** @file fixed_debug.h @brief Fixed-point operations with debugging */ /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FIXED_DEBUG_H #define FIXED_DEBUG_H #include <stdio.h> extern long long spx_mips; #define MIPS_INC spx_mips++, #define QCONST16(x,bits) ((spx_word16_t)(.5+(x)*(((spx_word32_t)1)<<(bits)))) #define QCONST32(x,bits) ((spx_word32_t)(.5+(x)*(((spx_word32_t)1)<<(bits)))) #define VERIFY_SHORT(x) ((x)<=32767&&(x)>=-32768) #define VERIFY_INT(x) ((x)<=2147483647LL&&(x)>=-2147483648LL) static inline short NEG16(int x) { int res; if (!VERIFY_SHORT(x)) { fprintf (stderr, "NEG16: input is not short: %d\n", (int)x); } res = -x; if (!VERIFY_SHORT(res)) fprintf (stderr, "NEG16: output is not short: %d\n", (int)res); spx_mips++; return res; } static inline int NEG32(long long x) { long long res; if (!VERIFY_INT(x)) { fprintf (stderr, "NEG16: input is not int: %d\n", (int)x); } res = -x; if (!VERIFY_INT(res)) fprintf (stderr, "NEG16: output is not int: %d\n", (int)res); spx_mips++; return res; } #define EXTRACT16(x) _EXTRACT16(x, __FILE__, __LINE__) static inline short _EXTRACT16(int x, char *file, int line) { int res; if (!VERIFY_SHORT(x)) { fprintf (stderr, "EXTRACT16: input is not short: %d in %s: line %d\n", x, file, line); } res = x; spx_mips++; return res; } #define EXTEND32(x) _EXTEND32(x, __FILE__, __LINE__) static inline int _EXTEND32(int x, char *file, int line) { int res; if (!VERIFY_SHORT(x)) { fprintf (stderr, "EXTEND32: input is not short: %d in %s: line %d\n", x, file, line); } res = x; spx_mips++; return res; } #define SHR16(a, shift) _SHR16(a, shift, __FILE__, __LINE__) static inline short _SHR16(int a, int shift, char *file, int line) { int res; if (!VERIFY_SHORT(a) || !VERIFY_SHORT(shift)) { fprintf (stderr, "SHR16: inputs are not short: %d >> %d in %s: line %d\n", a, shift, file, line); } res = a>>shift; if (!VERIFY_SHORT(res)) fprintf (stderr, "SHR16: output is not short: %d in %s: line %d\n", res, file, line); spx_mips++; return res; } #define SHL16(a, shift) _SHL16(a, shift, __FILE__, __LINE__) static inline short _SHL16(int a, int shift, char *file, int line) { int res; if (!VERIFY_SHORT(a) || !VERIFY_SHORT(shift)) { fprintf (stderr, "SHL16: inputs are not short: %d %d in %s: line %d\n", a, shift, file, line); } res = a<<shift; if (!VERIFY_SHORT(res)) fprintf (stderr, "SHL16: output is not short: %d in %s: line %d\n", res, file, line); spx_mips++; return res; } static inline int SHR32(long long a, int shift) { long long res; if (!VERIFY_INT(a) || !VERIFY_SHORT(shift)) { fprintf (stderr, "SHR32: inputs are not int: %d %d\n", (int)a, shift); } res = a>>shift; if (!VERIFY_INT(res)) { fprintf (stderr, "SHR32: output is not int: %d\n", (int)res); } spx_mips++; return res; } static inline int SHL32(long long a, int shift) { long long res; if (!VERIFY_INT(a) || !VERIFY_SHORT(shift)) { fprintf (stderr, "SHL32: inputs are not int: %d %d\n", (int)a, shift); } res = a<<shift; if (!VERIFY_INT(res)) { fprintf (stderr, "SHL32: output is not int: %d\n", (int)res); } spx_mips++; return res; } #define PSHR16(a,shift) (SHR16(ADD16((a),((1<<((shift))>>1))),shift)) #define PSHR32(a,shift) (SHR32(ADD32((a),((EXTEND32(1)<<((shift))>>1))),shift)) #define VSHR32(a, shift) (((shift)>0) ? SHR32(a, shift) : SHL32(a, -(shift))) #define SATURATE16(x,a) (((x)>(a) ? (a) : (x)<-(a) ? -(a) : (x))) #define SATURATE32(x,a) (((x)>(a) ? (a) : (x)<-(a) ? -(a) : (x))) //#define SHR(a,shift) ((a) >> (shift)) //#define SHL(a,shift) ((a) << (shift)) #define ADD16(a, b) _ADD16(a, b, __FILE__, __LINE__) static inline short _ADD16(int a, int b, char *file, int line) { int res; if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) { fprintf (stderr, "ADD16: inputs are not short: %d %d in %s: line %d\n", a, b, file, line); } res = a+b; if (!VERIFY_SHORT(res)) { fprintf (stderr, "ADD16: output is not short: %d+%d=%d in %s: line %d\n", a,b,res, file, line); } spx_mips++; return res; } #define SUB16(a, b) _SUB16(a, b, __FILE__, __LINE__) static inline short _SUB16(int a, int b, char *file, int line) { int res; if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) { fprintf (stderr, "SUB16: inputs are not short: %d %d in %s: line %d\n", a, b, file, line); } res = a-b; if (!VERIFY_SHORT(res)) fprintf (stderr, "SUB16: output is not short: %d in %s: line %d\n", res, file, line); spx_mips++; return res; } #define ADD32(a, b) _ADD32(a, b, __FILE__, __LINE__) static inline int _ADD32(long long a, long long b, char *file, int line) { long long res; if (!VERIFY_INT(a) || !VERIFY_INT(b)) { fprintf (stderr, "ADD32: inputs are not int: %d %d in %s: line %d\n", (int)a, (int)b, file, line); } res = a+b; if (!VERIFY_INT(res)) { fprintf (stderr, "ADD32: output is not int: %d in %s: line %d\n", (int)res, file, line); } spx_mips++; return res; } static inline int SUB32(long long a, long long b) { long long res; if (!VERIFY_INT(a) || !VERIFY_INT(b)) { fprintf (stderr, "SUB32: inputs are not int: %d %d\n", (int)a, (int)b); } res = a-b; if (!VERIFY_INT(res)) fprintf (stderr, "SUB32: output is not int: %d\n", (int)res); spx_mips++; return res; } #define ADD64(a,b) (MIPS_INC(a)+(b)) /* result fits in 16 bits */ static inline short MULT16_16_16(int a, int b) { int res; if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) { fprintf (stderr, "MULT16_16_16: inputs are not short: %d %d\n", a, b); } res = a*b; if (!VERIFY_SHORT(res)) fprintf (stderr, "MULT16_16_16: output is not short: %d\n", res); spx_mips++; return res; } #define MULT16_16(a, b) _MULT16_16(a, b, __FILE__, __LINE__) static inline int _MULT16_16(int a, int b, char *file, int line) { long long res; if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) { fprintf (stderr, "MULT16_16: inputs are not short: %d %d in %s: line %d\n", a, b, file, line); } res = ((long long)a)*b; if (!VERIFY_INT(res)) fprintf (stderr, "MULT16_16: output is not int: %d in %s: line %d\n", (int)res, file, line); spx_mips++; return res; } #define MAC16_16(c,a,b) (spx_mips--,ADD32((c),MULT16_16((a),(b)))) #define MAC16_16_Q11(c,a,b) (EXTRACT16(ADD16((c),EXTRACT16(SHR32(MULT16_16((a),(b)),11))))) #define MAC16_16_Q13(c,a,b) (EXTRACT16(ADD16((c),EXTRACT16(SHR32(MULT16_16((a),(b)),13))))) #define MAC16_16_P13(c,a,b) (EXTRACT16(ADD32((c),SHR32(ADD32(4096,MULT16_16((a),(b))),13)))) #define MULT16_32_QX(a, b, Q) _MULT16_32_QX(a, b, Q, __FILE__, __LINE__) static inline int _MULT16_32_QX(int a, long long b, int Q, char *file, int line) { long long res; if (!VERIFY_SHORT(a) || !VERIFY_INT(b)) { fprintf (stderr, "MULT16_32_Q%d: inputs are not short+int: %d %d in %s: line %d\n", Q, (int)a, (int)b, file, line); } if (ABS32(b)>=(EXTEND32(1)<<(15+Q))) fprintf (stderr, "MULT16_32_Q%d: second operand too large: %d %d in %s: line %d\n", Q, (int)a, (int)b, file, line); res = (((long long)a)*(long long)b) >> Q; if (!VERIFY_INT(res)) fprintf (stderr, "MULT16_32_Q%d: output is not int: %d*%d=%d in %s: line %d\n", Q, (int)a, (int)b,(int)res, file, line); spx_mips+=5; return res; } static inline int MULT16_32_PX(int a, long long b, int Q) { long long res; if (!VERIFY_SHORT(a) || !VERIFY_INT(b)) { fprintf (stderr, "MULT16_32_P%d: inputs are not short+int: %d %d\n", Q, (int)a, (int)b); } if (ABS32(b)>=(EXTEND32(1)<<(15+Q))) fprintf (stderr, "MULT16_32_Q%d: second operand too large: %d %d\n", Q, (int)a, (int)b); res = ((((long long)a)*(long long)b) + ((EXTEND32(1)<<Q)>>1))>> Q; if (!VERIFY_INT(res)) fprintf (stderr, "MULT16_32_P%d: output is not int: %d*%d=%d\n", Q, (int)a, (int)b,(int)res); spx_mips+=5; return res; } #define MULT16_32_Q11(a,b) MULT16_32_QX(a,b,11) #define MAC16_32_Q11(c,a,b) ADD32((c),MULT16_32_Q11((a),(b))) #define MULT16_32_Q12(a,b) MULT16_32_QX(a,b,12) #define MULT16_32_Q13(a,b) MULT16_32_QX(a,b,13) #define MULT16_32_Q14(a,b) MULT16_32_QX(a,b,14) #define MULT16_32_Q15(a,b) MULT16_32_QX(a,b,15) #define MULT16_32_P15(a,b) MULT16_32_PX(a,b,15) #define MAC16_32_Q15(c,a,b) ADD32((c),MULT16_32_Q15((a),(b))) static inline int SATURATE(int a, int b) { if (a>b) a=b; if (a<-b) a = -b; return a; } static inline int MULT16_16_Q11_32(int a, int b) { long long res; if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) { fprintf (stderr, "MULT16_16_Q11: inputs are not short: %d %d\n", a, b); } res = ((long long)a)*b; res >>= 11; if (!VERIFY_INT(res)) fprintf (stderr, "MULT16_16_Q11: output is not short: %d*%d=%d\n", (int)a, (int)b, (int)res); spx_mips+=3; return res; } static inline short MULT16_16_Q13(int a, int b) { long long res; if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) { fprintf (stderr, "MULT16_16_Q13: inputs are not short: %d %d\n", a, b); } res = ((long long)a)*b; res >>= 13; if (!VERIFY_SHORT(res)) fprintf (stderr, "MULT16_16_Q13: output is not short: %d*%d=%d\n", a, b, (int)res); spx_mips+=3; return res; } static inline short MULT16_16_Q14(int a, int b) { long long res; if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) { fprintf (stderr, "MULT16_16_Q14: inputs are not short: %d %d\n", a, b); } res = ((long long)a)*b; res >>= 14; if (!VERIFY_SHORT(res)) fprintf (stderr, "MULT16_16_Q14: output is not short: %d\n", (int)res); spx_mips+=3; return res; } static inline short MULT16_16_Q15(int a, int b) { long long res; if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) { fprintf (stderr, "MULT16_16_Q15: inputs are not short: %d %d\n", a, b); } res = ((long long)a)*b; res >>= 15; if (!VERIFY_SHORT(res)) { fprintf (stderr, "MULT16_16_Q15: output is not short: %d\n", (int)res); } spx_mips+=3; return res; } static inline short MULT16_16_P13(int a, int b) { long long res; if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) { fprintf (stderr, "MULT16_16_P13: inputs are not short: %d %d\n", a, b); } res = ((long long)a)*b; res += 4096; if (!VERIFY_INT(res)) fprintf (stderr, "MULT16_16_P13: overflow: %d*%d=%d\n", a, b, (int)res); res >>= 13; if (!VERIFY_SHORT(res)) fprintf (stderr, "MULT16_16_P13: output is not short: %d*%d=%d\n", a, b, (int)res); spx_mips+=4; return res; } static inline short MULT16_16_P14(int a, int b) { long long res; if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) { fprintf (stderr, "MULT16_16_P14: inputs are not short: %d %d\n", a, b); } res = ((long long)a)*b; res += 8192; if (!VERIFY_INT(res)) fprintf (stderr, "MULT16_16_P14: overflow: %d*%d=%d\n", a, b, (int)res); res >>= 14; if (!VERIFY_SHORT(res)) fprintf (stderr, "MULT16_16_P14: output is not short: %d*%d=%d\n", a, b, (int)res); spx_mips+=4; return res; } static inline short MULT16_16_P15(int a, int b) { long long res; if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) { fprintf (stderr, "MULT16_16_P15: inputs are not short: %d %d\n", a, b); } res = ((long long)a)*b; res += 16384; if (!VERIFY_INT(res)) fprintf (stderr, "MULT16_16_P15: overflow: %d*%d=%d\n", a, b, (int)res); res >>= 15; if (!VERIFY_SHORT(res)) fprintf (stderr, "MULT16_16_P15: output is not short: %d*%d=%d\n", a, b, (int)res); spx_mips+=4; return res; } #define DIV32_16(a, b) _DIV32_16(a, b, __FILE__, __LINE__) static inline int _DIV32_16(long long a, long long b, char *file, int line) { long long res; if (b==0) { fprintf(stderr, "DIV32_16: divide by zero: %d/%d in %s: line %d\n", (int)a, (int)b, file, line); return 0; } if (!VERIFY_INT(a) || !VERIFY_SHORT(b)) { fprintf (stderr, "DIV32_16: inputs are not int/short: %d %d in %s: line %d\n", (int)a, (int)b, file, line); } res = a/b; if (!VERIFY_SHORT(res)) { fprintf (stderr, "DIV32_16: output is not short: %d / %d = %d in %s: line %d\n", (int)a,(int)b,(int)res, file, line); if (res>32767) res = 32767; if (res<-32768) res = -32768; } spx_mips+=20; return res; } #define DIV32(a, b) _DIV32(a, b, __FILE__, __LINE__) static inline int _DIV32(long long a, long long b, char *file, int line) { long long res; if (b==0) { fprintf(stderr, "DIV32: divide by zero: %d/%d in %s: line %d\n", (int)a, (int)b, file, line); return 0; } if (!VERIFY_INT(a) || !VERIFY_INT(b)) { fprintf (stderr, "DIV32: inputs are not int/short: %d %d in %s: line %d\n", (int)a, (int)b, file, line); } res = a/b; if (!VERIFY_INT(res)) fprintf (stderr, "DIV32: output is not int: %d in %s: line %d\n", (int)res, file, line); spx_mips+=36; return res; } #define PDIV32(a,b) DIV32(ADD32((a),(b)>>1),b) #define PDIV32_16(a,b) DIV32_16(ADD32((a),(b)>>1),b) #endif
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 4efcffd7ae23f1e41943fd914b18da10 NativeFormatImporter: externalObjects: {} mainObjectFileID: 2100000 userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
## This file has a Velocity error. ## It's intentionally not saved with a 'vm' suffix ## to avoid errors in IDE ## Note: text directly from VELOCITY-96 #macro (myMacro $arg1 $list) This is text from velPTest2.vm #myMacro('name', ['apples', 'oranges'] More text
{ "pile_set_name": "Github" }
package com.rsen.db.converter; import android.database.Cursor; import com.rsen.db.sqlite.ColumnDbType; /** * Author: wyouflf * Date: 13-11-4 * Time: 下午10:51 */ public class BooleanColumnConverter implements ColumnConverter<Boolean> { @Override public Boolean getFieldValue(final Cursor cursor, int index) { return cursor.isNull(index) ? null : cursor.getInt(index) == 1; } @Override public Object fieldValue2DbValue(Boolean fieldValue) { if (fieldValue == null) return null; return fieldValue ? 1 : 0; } @Override public ColumnDbType getColumnDbType() { return ColumnDbType.INTEGER; } }
{ "pile_set_name": "Github" }
# frozen_string_literal: false require_relative 'utils' if defined?(OpenSSL) && defined?(OpenSSL::Engine) class OpenSSL::TestEngine < OpenSSL::TestCase def test_engines_free # [ruby-dev:44173] with_openssl <<-'end;' OpenSSL::Engine.load("openssl") OpenSSL::Engine.engines OpenSSL::Engine.engines end; end def test_openssl_engine_builtin with_openssl <<-'end;' orig = OpenSSL::Engine.engines pend "'openssl' is already loaded" if orig.any? { |e| e.id == "openssl" } engine = OpenSSL::Engine.load("openssl") assert_equal(true, engine) assert_equal(1, OpenSSL::Engine.engines.size - orig.size) end; end def test_openssl_engine_by_id_string with_openssl <<-'end;' orig = OpenSSL::Engine.engines pend "'openssl' is already loaded" if orig.any? { |e| e.id == "openssl" } engine = get_engine assert_not_nil(engine) assert_equal(1, OpenSSL::Engine.engines.size - orig.size) end; end def test_openssl_engine_id_name_inspect with_openssl <<-'end;' engine = get_engine assert_equal("openssl", engine.id) assert_not_nil(engine.name) assert_not_nil(engine.inspect) end; end def test_openssl_engine_digest_sha1 with_openssl <<-'end;' engine = get_engine digest = engine.digest("SHA1") assert_not_nil(digest) data = "test" assert_equal(OpenSSL::Digest::SHA1.digest(data), digest.digest(data)) end; end def test_openssl_engine_cipher_rc4 begin OpenSSL::Cipher.new("rc4") rescue OpenSSL::Cipher::CipherError pend "RC4 is not supported" end with_openssl(<<-'end;', ignore_stderr: true) engine = get_engine algo = "RC4" data = "a" * 1000 key = OpenSSL::Random.random_bytes(16) encrypted = crypt_data(data, key, :encrypt) { engine.cipher(algo) } decrypted = crypt_data(encrypted, key, :decrypt) { OpenSSL::Cipher.new(algo) } assert_equal(data, decrypted) end; end private # this is required because OpenSSL::Engine methods change global state def with_openssl(code, **opts) assert_separately([{ "OSSL_MDEBUG" => nil }, "-ropenssl"], <<~"end;", **opts) require #{__FILE__.dump} include OpenSSL::TestEngine::Utils #{code} end; end module Utils def get_engine OpenSSL::Engine.by_id("openssl") end def crypt_data(data, key, mode) cipher = yield cipher.send mode cipher.key = key cipher.update(data) + cipher.final end end end end
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <resources> <!-- From: file:/Users/cmanus/code/src/github.com/go-react-native/android/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/res/values-si-rLK/values-si-rLK.xml --> <eat-comment/> <string msgid="4600421777120114993" name="abc_action_bar_home_description">"ගෙදරට සංචාලනය කරන්න"</string> <string msgid="1397052879051804371" name="abc_action_bar_home_description_format">"%1$s, %2$s"</string> <string msgid="6623331958280229229" name="abc_action_bar_home_subtitle_description_format">"%1$s, %2$s, %3$s"</string> <string msgid="1594238315039666878" name="abc_action_bar_up_description">"ඉහලට සංචාලනය කරන්න"</string> <string msgid="3588849162933574182" name="abc_action_menu_overflow_description">"තවත් විකල්ප"</string> <string msgid="4076576682505996667" name="abc_action_mode_done">"අවසාන වූ"</string> <string msgid="7468859129482906941" name="abc_activity_chooser_view_see_all">"සියල්ල බලන්න"</string> <string msgid="2031811694353399454" name="abc_activitychooserview_choose_application">"යෙදුමක් තෝරන්න"</string> <string msgid="7723749260725869598" name="abc_search_hint">"සොයන්න..."</string> <string msgid="3691816814315814921" name="abc_searchview_description_clear">"විමසුම හිස් කරන්න"</string> <string msgid="2550479030709304392" name="abc_searchview_description_query">"සෙවුම් විමසුම"</string> <string msgid="8264924765203268293" name="abc_searchview_description_search">"සෙවීම"</string> <string msgid="8928215447528550784" name="abc_searchview_description_submit">"විමසුම යොමු කරන්න"</string> <string msgid="893419373245838918" name="abc_searchview_description_voice">"හඬ සෙවීම"</string> <string msgid="3421042268587513524" name="abc_shareactionprovider_share_with">"සමඟ බෙදාගන්න"</string> <string msgid="7165123711973476752" name="abc_shareactionprovider_share_with_application">"%s සමඟ බෙදාගන්න"</string> <string msgid="1603543279005712093" name="abc_toolbar_collapse_description">"හකුළන්න"</string> <string msgid="2869576371154716097" name="status_bar_notification_info_overflow">"999+"</string> </resources>
{ "pile_set_name": "Github" }
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from parlai.mturk.core.worlds import MTurkTaskWorld from parlai.core.worlds import validate from joblib import Parallel, delayed from parlai.tasks.dealnodeal.agents import NegotiationTeacher from parlai.tasks.dealnodeal.agents import get_tag from parlai.tasks.dealnodeal.agents import WELCOME_MESSAGE import random class MTurkDealNoDealDialogWorld(MTurkTaskWorld): """World where two agents have a dialogue to negotiate a deal. """ def __init__(self, opt, agents=None, shared=None): # Add passed in agents directly. if agents is not None: random.shuffle(agents) self.agents = agents self.acts = [None] * len(agents) self.episodeDone = False self.task = NegotiationTeacher(opt=opt) self.first_turn = True self.choices = dict() self.selection = False self.turns = 0 self.num_negotiations = 0 def parley(self): """Alternate taking turns, until both agents have made a choice (indicated by a turn starting with <selection>) """ if self.first_turn: # Use NegotiationTeacher to load data for us data = ( self.task.episodes[self.num_negotiations % len(self.task.episodes)] .strip() .split() ) self.num_negotiations += 1 for agent, tag in zip(self.agents, ['input', 'partner_input']): (book_cnt, book_val, hat_cnt, hat_val, ball_cnt, ball_val) = get_tag( data, tag ) action = {} action['text'] = WELCOME_MESSAGE.format( book_cnt=book_cnt, book_val=book_val, hat_cnt=hat_cnt, hat_val=hat_val, ball_cnt=ball_cnt, ball_val=ball_val, ) action['items'] = { "book_cnt": book_cnt, "book_val": book_val, "hat_cnt": hat_cnt, "hat_val": hat_val, "ball_cnt": ball_cnt, "ball_val": ball_val, } agent.observe(validate(action)) self.first_turn = False else: self.turns += 1 for _index, agent in enumerate(self.agents): if agent in self.choices: # This agent has already made a choice continue try: act = agent.act(timeout=None) except TypeError: act = agent.act() # not MTurkAgent for other_agent in self.agents: if other_agent != agent: other_agent.observe(validate(act)) if act["text"].startswith("<selection>") and self.turns > 1: # Making a choice self.choices[agent] = act["text"] self.selection = True if len(self.choices) == len(self.agents): self.first_turn = True self.episodeDone = True elif act['episode_done']: # Action is not selection but episode ended due to # disconnection or timeout or returned hit self.episodeDone = True def episode_done(self): return self.episodeDone def shutdown(self): """Shutdown all mturk agents in parallel, otherwise if one mturk agent is disconnected then it could prevent other mturk agents from completing. """ global shutdown_agent def shutdown_agent(agent): try: agent.shutdown(timeout=None) except Exception: agent.shutdown() # not MTurkAgent Parallel(n_jobs=len(self.agents), backend='threading')( delayed(shutdown_agent)(agent) for agent in self.agents )
{ "pile_set_name": "Github" }
import { partial, string, number } from '../../..' export const Struct = partial({ name: string(), age: number(), }) export const data = { name: 'john', age: 42, } export const output = { name: 'john', age: 42, }
{ "pile_set_name": "Github" }
/* Simple DirectMedia Layer Copyright (C) 1997-2014 Sam Lantinga <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef _SDL_thread_h #define _SDL_thread_h /** * \file SDL_thread.h * * Header for the SDL thread management routines. */ #include "SDL_stdinc.h" #include "SDL_error.h" /* Thread synchronization primitives */ #include "SDL_atomic.h" #include "SDL_mutex.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* The SDL thread structure, defined in SDL_thread.c */ struct SDL_Thread; typedef struct SDL_Thread SDL_Thread; /* The SDL thread ID */ typedef unsigned long SDL_threadID; /* Thread local storage ID, 0 is the invalid ID */ typedef unsigned int SDL_TLSID; /** * The SDL thread priority. * * \note On many systems you require special privileges to set high priority. */ typedef enum { SDL_THREAD_PRIORITY_LOW, SDL_THREAD_PRIORITY_NORMAL, SDL_THREAD_PRIORITY_HIGH } SDL_ThreadPriority; /** * The function passed to SDL_CreateThread(). * It is passed a void* user context parameter and returns an int. */ typedef int (SDLCALL * SDL_ThreadFunction) (void *data); #if defined(__WIN32__) && !defined(HAVE_LIBC) /** * \file SDL_thread.h * * We compile SDL into a DLL. This means, that it's the DLL which * creates a new thread for the calling process with the SDL_CreateThread() * API. There is a problem with this, that only the RTL of the SDL.DLL will * be initialized for those threads, and not the RTL of the calling * application! * * To solve this, we make a little hack here. * * We'll always use the caller's _beginthread() and _endthread() APIs to * start a new thread. This way, if it's the SDL.DLL which uses this API, * then the RTL of SDL.DLL will be used to create the new thread, and if it's * the application, then the RTL of the application will be used. * * So, in short: * Always use the _beginthread() and _endthread() of the calling runtime * library! */ #define SDL_PASSED_BEGINTHREAD_ENDTHREAD #include <process.h> /* This has _beginthread() and _endthread() defined! */ typedef uintptr_t(__cdecl * pfnSDL_CurrentBeginThread) (void *, unsigned, unsigned (__stdcall * func) (void *), void *arg, unsigned, unsigned *threadID); typedef void (__cdecl * pfnSDL_CurrentEndThread) (unsigned code); /** * Create a thread. */ extern DECLSPEC SDL_Thread *SDLCALL SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread); /** * Create a thread. */ #if defined(SDL_CreateThread) && SDL_DYNAMIC_API #undef SDL_CreateThread #define SDL_CreateThread(fn, name, data) SDL_CreateThread_REAL(fn, name, data, (pfnSDL_CurrentBeginThread)_beginthreadex, (pfnSDL_CurrentEndThread)_endthreadex) #else #define SDL_CreateThread(fn, name, data) SDL_CreateThread(fn, name, data, (pfnSDL_CurrentBeginThread)_beginthreadex, (pfnSDL_CurrentEndThread)_endthreadex) #endif #else /** * Create a thread. * * Thread naming is a little complicated: Most systems have very small * limits for the string length (Haiku has 32 bytes, Linux currently has 16, * Visual C++ 6.0 has nine!), and possibly other arbitrary rules. You'll * have to see what happens with your system's debugger. The name should be * UTF-8 (but using the naming limits of C identifiers is a better bet). * There are no requirements for thread naming conventions, so long as the * string is null-terminated UTF-8, but these guidelines are helpful in * choosing a name: * * http://stackoverflow.com/questions/149932/naming-conventions-for-threads * * If a system imposes requirements, SDL will try to munge the string for * it (truncate, etc), but the original string contents will be available * from SDL_GetThreadName(). */ extern DECLSPEC SDL_Thread *SDLCALL SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data); #endif /** * Get the thread name, as it was specified in SDL_CreateThread(). * This function returns a pointer to a UTF-8 string that names the * specified thread, or NULL if it doesn't have a name. This is internal * memory, not to be free()'d by the caller, and remains valid until the * specified thread is cleaned up by SDL_WaitThread(). */ extern DECLSPEC const char *SDLCALL SDL_GetThreadName(SDL_Thread *thread); /** * Get the thread identifier for the current thread. */ extern DECLSPEC SDL_threadID SDLCALL SDL_ThreadID(void); /** * Get the thread identifier for the specified thread. * * Equivalent to SDL_ThreadID() if the specified thread is NULL. */ extern DECLSPEC SDL_threadID SDLCALL SDL_GetThreadID(SDL_Thread * thread); /** * Set the priority for the current thread */ extern DECLSPEC int SDLCALL SDL_SetThreadPriority(SDL_ThreadPriority priority); /** * Wait for a thread to finish. Threads that haven't been detached will * remain (as a "zombie") until this function cleans them up. Not doing so * is a resource leak. * * Once a thread has been cleaned up through this function, the SDL_Thread * that references it becomes invalid and should not be referenced again. * As such, only one thread may call SDL_WaitThread() on another. * * The return code for the thread function is placed in the area * pointed to by \c status, if \c status is not NULL. * * You may not wait on a thread that has been used in a call to * SDL_DetachThread(). Use either that function or this one, but not * both, or behavior is undefined. * * It is safe to pass NULL to this function; it is a no-op. */ extern DECLSPEC void SDLCALL SDL_WaitThread(SDL_Thread * thread, int *status); /** * A thread may be "detached" to signify that it should not remain until * another thread has called SDL_WaitThread() on it. Detaching a thread * is useful for long-running threads that nothing needs to synchronize * with or further manage. When a detached thread is done, it simply * goes away. * * There is no way to recover the return code of a detached thread. If you * need this, don't detach the thread and instead use SDL_WaitThread(). * * Once a thread is detached, you should usually assume the SDL_Thread isn't * safe to reference again, as it will become invalid immediately upon * the detached thread's exit, instead of remaining until someone has called * SDL_WaitThread() to finally clean it up. As such, don't detach the same * thread more than once. * * If a thread has already exited when passed to SDL_DetachThread(), it will * stop waiting for a call to SDL_WaitThread() and clean up immediately. * It is not safe to detach a thread that might be used with SDL_WaitThread(). * * You may not call SDL_WaitThread() on a thread that has been detached. * Use either that function or this one, but not both, or behavior is * undefined. * * It is safe to pass NULL to this function; it is a no-op. */ extern DECLSPEC void SDLCALL SDL_DetachThread(SDL_Thread * thread); /** * \brief Create an identifier that is globally visible to all threads but refers to data that is thread-specific. * * \return The newly created thread local storage identifier, or 0 on error * * \code * static SDL_SpinLock tls_lock; * static SDL_TLSID thread_local_storage; * * void SetMyThreadData(void *value) * { * if (!thread_local_storage) { * SDL_AtomicLock(&tls_lock); * if (!thread_local_storage) { * thread_local_storage = SDL_TLSCreate(); * } * SDL_AtomicUnLock(&tls_lock); * } * SDL_TLSSet(thread_local_storage, value); * } * * void *GetMyThreadData(void) * { * return SDL_TLSGet(thread_local_storage); * } * \endcode * * \sa SDL_TLSGet() * \sa SDL_TLSSet() */ extern DECLSPEC SDL_TLSID SDLCALL SDL_TLSCreate(void); /** * \brief Get the value associated with a thread local storage ID for the current thread. * * \param id The thread local storage ID * * \return The value associated with the ID for the current thread, or NULL if no value has been set. * * \sa SDL_TLSCreate() * \sa SDL_TLSSet() */ extern DECLSPEC void * SDLCALL SDL_TLSGet(SDL_TLSID id); /** * \brief Set the value associated with a thread local storage ID for the current thread. * * \param id The thread local storage ID * \param value The value to associate with the ID for the current thread * \param destructor A function called when the thread exits, to free the value. * * \return 0 on success, -1 on error * * \sa SDL_TLSCreate() * \sa SDL_TLSGet() */ extern DECLSPEC int SDLCALL SDL_TLSSet(SDL_TLSID id, const void *value, void (*destructor)(void*)); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_thread_h */ /* vi: set ts=4 sw=4 expandtab: */
{ "pile_set_name": "Github" }
/* html2canvas 0.4.1 <http://html2canvas.hertzen.com> Copyright (c) 2013 Niklas von Hertzen Released under MIT License */ (function(window, document, undefined){ //"use strict"; var _html2canvas = {}, previousElement, computedCSS, html2canvas; _html2canvas.Util = {}; _html2canvas.Util.log = function(a) { if (_html2canvas.logging && window.console && window.console.log) { window.console.log(a); } }; _html2canvas.Util.trimText = (function(isNative){ return function(input) { return isNative ? isNative.apply(input) : ((input || '') + '').replace( /^\s+|\s+$/g , '' ); }; })(String.prototype.trim); _html2canvas.Util.asFloat = function(v) { return parseFloat(v); }; (function() { // TODO: support all possible length values var TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g; var TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g; _html2canvas.Util.parseTextShadows = function (value) { if (!value || value === 'none') { return []; } // find multiple shadow declarations var shadows = value.match(TEXT_SHADOW_PROPERTY), results = []; for (var i = 0; shadows && (i < shadows.length); i++) { var s = shadows[i].match(TEXT_SHADOW_VALUES); results.push({ color: s[0], offsetX: s[1] ? s[1].replace('px', '') : 0, offsetY: s[2] ? s[2].replace('px', '') : 0, blur: s[3] ? s[3].replace('px', '') : 0 }); } return results; }; })(); _html2canvas.Util.parseBackgroundImage = function (value) { var whitespace = ' \r\n\t', method, definition, prefix, prefix_i, block, results = [], c, mode = 0, numParen = 0, quote, args; var appendResult = function(){ if(method) { if(definition.substr( 0, 1 ) === '"') { definition = definition.substr( 1, definition.length - 2 ); } if(definition) { args.push(definition); } if(method.substr( 0, 1 ) === '-' && (prefix_i = method.indexOf( '-', 1 ) + 1) > 0) { prefix = method.substr( 0, prefix_i); method = method.substr( prefix_i ); } results.push({ prefix: prefix, method: method.toLowerCase(), value: block, args: args }); } args = []; //for some odd reason, setting .length = 0 didn't work in safari method = prefix = definition = block = ''; }; appendResult(); for(var i = 0, ii = value.length; i<ii; i++) { c = value[i]; if(mode === 0 && whitespace.indexOf( c ) > -1){ continue; } switch(c) { case '"': if(!quote) { quote = c; } else if(quote === c) { quote = null; } break; case '(': if(quote) { break; } else if(mode === 0) { mode = 1; block += c; continue; } else { numParen++; } break; case ')': if(quote) { break; } else if(mode === 1) { if(numParen === 0) { mode = 0; block += c; appendResult(); continue; } else { numParen--; } } break; case ',': if(quote) { break; } else if(mode === 0) { appendResult(); continue; } else if (mode === 1) { if(numParen === 0 && !method.match(/^url$/i)) { args.push(definition); definition = ''; block += c; continue; } } break; } block += c; if(mode === 0) { method += c; } else { definition += c; } } appendResult(); return results; }; _html2canvas.Util.Bounds = function (element) { var clientRect, bounds = {}; if (element.getBoundingClientRect){ clientRect = element.getBoundingClientRect(); // TODO add scroll position to bounds, so no scrolling of window necessary bounds.top = clientRect.top; bounds.bottom = clientRect.bottom || (clientRect.top + clientRect.height); bounds.left = clientRect.left; bounds.width = element.offsetWidth; bounds.height = element.offsetHeight; } return bounds; }; // TODO ideally, we'd want everything to go through this function instead of Util.Bounds, // but would require further work to calculate the correct positions for elements with offsetParents _html2canvas.Util.OffsetBounds = function (element) { var parent = element.offsetParent ? _html2canvas.Util.OffsetBounds(element.offsetParent) : {top: 0, left: 0}; return { top: element.offsetTop + parent.top, bottom: element.offsetTop + element.offsetHeight + parent.top, left: element.offsetLeft + parent.left, width: element.offsetWidth, height: element.offsetHeight }; }; function toPX(element, attribute, value ) { var rsLeft = element.runtimeStyle && element.runtimeStyle[attribute], left, style = element.style; // Check if we are not dealing with pixels, (Opera has issues with this) // Ported from jQuery css.js // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !/^-?[0-9]+\.?[0-9]*(?:px)?$/i.test( value ) && /^-?\d/.test(value) ) { // Remember the original values left = style.left; // Put in the new values to get a computed value out if (rsLeft) { element.runtimeStyle.left = element.currentStyle.left; } style.left = attribute === "fontSize" ? "1em" : (value || 0); value = style.pixelLeft + "px"; // Revert the changed values style.left = left; if (rsLeft) { element.runtimeStyle.left = rsLeft; } } if (!/^(thin|medium|thick)$/i.test(value)) { return Math.round(parseFloat(value)) + "px"; } return value; } function asInt(val) { return parseInt(val, 10); } function isPercentage(value) { return value.toString().indexOf("%") !== -1; } function parseBackgroundSizePosition(value, element, attribute, index) { value = (value || '').split(','); value = value[index || 0] || value[0] || 'auto'; value = _html2canvas.Util.trimText(value).split(' '); if(attribute === 'backgroundSize' && (value[0] && value[0].match(/^(cover|contain|auto)$/))) { return value; } else { value[0] = (value[0].indexOf( "%" ) === -1) ? toPX(element, attribute + "X", value[0]) : value[0]; if(value[1] === undefined) { if(attribute === 'backgroundSize') { value[1] = 'auto'; return value; } else { // IE 9 doesn't return double digit always value[1] = value[0]; } } value[1] = (value[1].indexOf("%") === -1) ? toPX(element, attribute + "Y", value[1]) : value[1]; } return value; } _html2canvas.Util.getCSS = function (element, attribute, index) { if (previousElement !== element) { computedCSS = document.defaultView.getComputedStyle(element, null); } var value = computedCSS[attribute]; if (/^background(Size|Position)$/.test(attribute)) { return parseBackgroundSizePosition(value, element, attribute, index); } else if (/border(Top|Bottom)(Left|Right)Radius/.test(attribute)) { var arr = value.split(" "); if (arr.length <= 1) { arr[1] = arr[0]; } return arr.map(asInt); } return value; }; _html2canvas.Util.resizeBounds = function( current_width, current_height, target_width, target_height, stretch_mode ){ var target_ratio = target_width / target_height, current_ratio = current_width / current_height, output_width, output_height; if(!stretch_mode || stretch_mode === 'auto') { output_width = target_width; output_height = target_height; } else if(target_ratio < current_ratio ^ stretch_mode === 'contain') { output_height = target_height; output_width = target_height * current_ratio; } else { output_width = target_width; output_height = target_width / current_ratio; } return { width: output_width, height: output_height }; }; _html2canvas.Util.BackgroundPosition = function(element, bounds, image, imageIndex, backgroundSize ) { var backgroundPosition = _html2canvas.Util.getCSS(element, 'backgroundPosition', imageIndex), leftPosition, topPosition; if (backgroundPosition.length === 1){ backgroundPosition = [backgroundPosition[0], backgroundPosition[0]]; } if (isPercentage(backgroundPosition[0])){ leftPosition = (bounds.width - (backgroundSize || image).width) * (parseFloat(backgroundPosition[0]) / 100); } else { leftPosition = parseInt(backgroundPosition[0], 10); } if (backgroundPosition[1] === 'auto') { topPosition = leftPosition / image.width * image.height; } else if (isPercentage(backgroundPosition[1])){ topPosition = (bounds.height - (backgroundSize || image).height) * parseFloat(backgroundPosition[1]) / 100; } else { topPosition = parseInt(backgroundPosition[1], 10); } if (backgroundPosition[0] === 'auto') { leftPosition = topPosition / image.height * image.width; } return {left: leftPosition, top: topPosition}; }; _html2canvas.Util.BackgroundSize = function(element, bounds, image, imageIndex) { var backgroundSize = _html2canvas.Util.getCSS(element, 'backgroundSize', imageIndex), width, height; if (backgroundSize.length === 1) { backgroundSize = [backgroundSize[0], backgroundSize[0]]; } if (isPercentage(backgroundSize[0])) { width = bounds.width * parseFloat(backgroundSize[0]) / 100; } else if (/contain|cover/.test(backgroundSize[0])) { return _html2canvas.Util.resizeBounds(image.width, image.height, bounds.width, bounds.height, backgroundSize[0]); } else { width = parseInt(backgroundSize[0], 10); } if (backgroundSize[0] === 'auto' && backgroundSize[1] === 'auto') { height = image.height; } else if (backgroundSize[1] === 'auto') { height = width / image.width * image.height; } else if (isPercentage(backgroundSize[1])) { height = bounds.height * parseFloat(backgroundSize[1]) / 100; } else { height = parseInt(backgroundSize[1], 10); } if (backgroundSize[0] === 'auto') { width = height / image.height * image.width; } return {width: width, height: height}; }; _html2canvas.Util.BackgroundRepeat = function(element, imageIndex) { var backgroundRepeat = _html2canvas.Util.getCSS(element, "backgroundRepeat").split(",").map(_html2canvas.Util.trimText); return backgroundRepeat[imageIndex] || backgroundRepeat[0]; }; _html2canvas.Util.Extend = function (options, defaults) { for (var key in options) { if (options.hasOwnProperty(key)) { defaults[key] = options[key]; } } return defaults; }; /* * Derived from jQuery.contents() * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ _html2canvas.Util.Children = function( elem ) { var children; try { children = (elem.nodeName && elem.nodeName.toUpperCase() === "IFRAME") ? elem.contentDocument || elem.contentWindow.document : (function(array) { var ret = []; if (array !== null) { (function(first, second ) { var i = first.length, j = 0; if (typeof second.length === "number") { for (var l = second.length; j < l; j++) { first[i++] = second[j]; } } else { while (second[j] !== undefined) { first[i++] = second[j++]; } } first.length = i; return first; })(ret, array); } return ret; })(elem.childNodes); } catch (ex) { _html2canvas.Util.log("html2canvas.Util.Children failed with exception: " + ex.message); children = []; } return children; }; _html2canvas.Util.isTransparent = function(backgroundColor) { return (!backgroundColor || backgroundColor === "transparent" || backgroundColor === "rgba(0, 0, 0, 0)"); }; _html2canvas.Util.Font = (function () { var fontData = {}; return function(font, fontSize, doc) { if (fontData[font + "-" + fontSize] !== undefined) { return fontData[font + "-" + fontSize]; } var container = doc.createElement('div'), img = doc.createElement('img'), span = doc.createElement('span'), sampleText = 'Hidden Text', baseline, middle, metricsObj; container.style.visibility = "hidden"; container.style.fontFamily = font; container.style.fontSize = fontSize; container.style.margin = 0; container.style.padding = 0; doc.body.appendChild(container); // http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever (handtinywhite.gif) img.src = "data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACwAAAAAAQABAAACAkQBADs="; img.width = 1; img.height = 1; img.style.margin = 0; img.style.padding = 0; img.style.verticalAlign = "baseline"; span.style.fontFamily = font; span.style.fontSize = fontSize; span.style.margin = 0; span.style.padding = 0; span.appendChild(doc.createTextNode(sampleText)); container.appendChild(span); container.appendChild(img); baseline = (img.offsetTop - span.offsetTop) + 1; container.removeChild(span); container.appendChild(doc.createTextNode(sampleText)); container.style.lineHeight = "normal"; img.style.verticalAlign = "super"; middle = (img.offsetTop-container.offsetTop) + 1; metricsObj = { baseline: baseline, lineWidth: 1, middle: middle }; fontData[font + "-" + fontSize] = metricsObj; doc.body.removeChild(container); return metricsObj; }; })(); (function(){ var Util = _html2canvas.Util, Generate = {}; _html2canvas.Generate = Generate; var reGradients = [ /^(-webkit-linear-gradient)\(([a-z\s]+)([\w\d\.\s,%\(\)]+)\)$/, /^(-o-linear-gradient)\(([a-z\s]+)([\w\d\.\s,%\(\)]+)\)$/, /^(-webkit-gradient)\((linear|radial),\s((?:\d{1,3}%?)\s(?:\d{1,3}%?),\s(?:\d{1,3}%?)\s(?:\d{1,3}%?))([\w\d\.\s,%\(\)\-]+)\)$/, /^(-moz-linear-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?))([\w\d\.\s,%\(\)]+)\)$/, /^(-webkit-radial-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?)),\s(\w+)\s([a-z\-]+)([\w\d\.\s,%\(\)]+)\)$/, /^(-moz-radial-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?)),\s(\w+)\s?([a-z\-]*)([\w\d\.\s,%\(\)]+)\)$/, /^(-o-radial-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?)),\s(\w+)\s([a-z\-]+)([\w\d\.\s,%\(\)]+)\)$/ ]; /* * TODO: Add IE10 vendor prefix (-ms) support * TODO: Add W3C gradient (linear-gradient) support * TODO: Add old Webkit -webkit-gradient(radial, ...) support * TODO: Maybe some RegExp optimizations are possible ;o) */ Generate.parseGradient = function(css, bounds) { var gradient, i, len = reGradients.length, m1, stop, m2, m2Len, step, m3, tl,tr,br,bl; for(i = 0; i < len; i+=1){ m1 = css.match(reGradients[i]); if(m1) { break; } } if(m1) { switch(m1[1]) { case '-webkit-linear-gradient': case '-o-linear-gradient': gradient = { type: 'linear', x0: null, y0: null, x1: null, y1: null, colorStops: [] }; // get coordinates m2 = m1[2].match(/\w+/g); if(m2){ m2Len = m2.length; for(i = 0; i < m2Len; i+=1){ switch(m2[i]) { case 'top': gradient.y0 = 0; gradient.y1 = bounds.height; break; case 'right': gradient.x0 = bounds.width; gradient.x1 = 0; break; case 'bottom': gradient.y0 = bounds.height; gradient.y1 = 0; break; case 'left': gradient.x0 = 0; gradient.x1 = bounds.width; break; } } } if(gradient.x0 === null && gradient.x1 === null){ // center gradient.x0 = gradient.x1 = bounds.width / 2; } if(gradient.y0 === null && gradient.y1 === null){ // center gradient.y0 = gradient.y1 = bounds.height / 2; } // get colors and stops m2 = m1[3].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)(?:\s\d{1,3}(?:%|px))?)+/g); if(m2){ m2Len = m2.length; step = 1 / Math.max(m2Len - 1, 1); for(i = 0; i < m2Len; i+=1){ m3 = m2[i].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/); if(m3[2]){ stop = parseFloat(m3[2]); if(m3[3] === '%'){ stop /= 100; } else { // px - stupid opera stop /= bounds.width; } } else { stop = i * step; } gradient.colorStops.push({ color: m3[1], stop: stop }); } } break; case '-webkit-gradient': gradient = { type: m1[2] === 'radial' ? 'circle' : m1[2], // TODO: Add radial gradient support for older mozilla definitions x0: 0, y0: 0, x1: 0, y1: 0, colorStops: [] }; // get coordinates m2 = m1[3].match(/(\d{1,3})%?\s(\d{1,3})%?,\s(\d{1,3})%?\s(\d{1,3})%?/); if(m2){ gradient.x0 = (m2[1] * bounds.width) / 100; gradient.y0 = (m2[2] * bounds.height) / 100; gradient.x1 = (m2[3] * bounds.width) / 100; gradient.y1 = (m2[4] * bounds.height) / 100; } // get colors and stops m2 = m1[4].match(/((?:from|to|color-stop)\((?:[0-9\.]+,\s)?(?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)\))+/g); if(m2){ m2Len = m2.length; for(i = 0; i < m2Len; i+=1){ m3 = m2[i].match(/(from|to|color-stop)\(([0-9\.]+)?(?:,\s)?((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\)/); stop = parseFloat(m3[2]); if(m3[1] === 'from') { stop = 0.0; } if(m3[1] === 'to') { stop = 1.0; } gradient.colorStops.push({ color: m3[3], stop: stop }); } } break; case '-moz-linear-gradient': gradient = { type: 'linear', x0: 0, y0: 0, x1: 0, y1: 0, colorStops: [] }; // get coordinates m2 = m1[2].match(/(\d{1,3})%?\s(\d{1,3})%?/); // m2[1] == 0% -> left // m2[1] == 50% -> center // m2[1] == 100% -> right // m2[2] == 0% -> top // m2[2] == 50% -> center // m2[2] == 100% -> bottom if(m2){ gradient.x0 = (m2[1] * bounds.width) / 100; gradient.y0 = (m2[2] * bounds.height) / 100; gradient.x1 = bounds.width - gradient.x0; gradient.y1 = bounds.height - gradient.y0; } // get colors and stops m2 = m1[3].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)(?:\s\d{1,3}%)?)+/g); if(m2){ m2Len = m2.length; step = 1 / Math.max(m2Len - 1, 1); for(i = 0; i < m2Len; i+=1){ m3 = m2[i].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%)?/); if(m3[2]){ stop = parseFloat(m3[2]); if(m3[3]){ // percentage stop /= 100; } } else { stop = i * step; } gradient.colorStops.push({ color: m3[1], stop: stop }); } } break; case '-webkit-radial-gradient': case '-moz-radial-gradient': case '-o-radial-gradient': gradient = { type: 'circle', x0: 0, y0: 0, x1: bounds.width, y1: bounds.height, cx: 0, cy: 0, rx: 0, ry: 0, colorStops: [] }; // center m2 = m1[2].match(/(\d{1,3})%?\s(\d{1,3})%?/); if(m2){ gradient.cx = (m2[1] * bounds.width) / 100; gradient.cy = (m2[2] * bounds.height) / 100; } // size m2 = m1[3].match(/\w+/); m3 = m1[4].match(/[a-z\-]*/); if(m2 && m3){ switch(m3[0]){ case 'farthest-corner': case 'cover': // is equivalent to farthest-corner case '': // mozilla removes "cover" from definition :( tl = Math.sqrt(Math.pow(gradient.cx, 2) + Math.pow(gradient.cy, 2)); tr = Math.sqrt(Math.pow(gradient.cx, 2) + Math.pow(gradient.y1 - gradient.cy, 2)); br = Math.sqrt(Math.pow(gradient.x1 - gradient.cx, 2) + Math.pow(gradient.y1 - gradient.cy, 2)); bl = Math.sqrt(Math.pow(gradient.x1 - gradient.cx, 2) + Math.pow(gradient.cy, 2)); gradient.rx = gradient.ry = Math.max(tl, tr, br, bl); break; case 'closest-corner': tl = Math.sqrt(Math.pow(gradient.cx, 2) + Math.pow(gradient.cy, 2)); tr = Math.sqrt(Math.pow(gradient.cx, 2) + Math.pow(gradient.y1 - gradient.cy, 2)); br = Math.sqrt(Math.pow(gradient.x1 - gradient.cx, 2) + Math.pow(gradient.y1 - gradient.cy, 2)); bl = Math.sqrt(Math.pow(gradient.x1 - gradient.cx, 2) + Math.pow(gradient.cy, 2)); gradient.rx = gradient.ry = Math.min(tl, tr, br, bl); break; case 'farthest-side': if(m2[0] === 'circle'){ gradient.rx = gradient.ry = Math.max( gradient.cx, gradient.cy, gradient.x1 - gradient.cx, gradient.y1 - gradient.cy ); } else { // ellipse gradient.type = m2[0]; gradient.rx = Math.max( gradient.cx, gradient.x1 - gradient.cx ); gradient.ry = Math.max( gradient.cy, gradient.y1 - gradient.cy ); } break; case 'closest-side': case 'contain': // is equivalent to closest-side if(m2[0] === 'circle'){ gradient.rx = gradient.ry = Math.min( gradient.cx, gradient.cy, gradient.x1 - gradient.cx, gradient.y1 - gradient.cy ); } else { // ellipse gradient.type = m2[0]; gradient.rx = Math.min( gradient.cx, gradient.x1 - gradient.cx ); gradient.ry = Math.min( gradient.cy, gradient.y1 - gradient.cy ); } break; // TODO: add support for "30px 40px" sizes (webkit only) } } // color stops m2 = m1[5].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)(?:\s\d{1,3}(?:%|px))?)+/g); if(m2){ m2Len = m2.length; step = 1 / Math.max(m2Len - 1, 1); for(i = 0; i < m2Len; i+=1){ m3 = m2[i].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/); if(m3[2]){ stop = parseFloat(m3[2]); if(m3[3] === '%'){ stop /= 100; } else { // px - stupid opera stop /= bounds.width; } } else { stop = i * step; } gradient.colorStops.push({ color: m3[1], stop: stop }); } } break; } } return gradient; }; function addScrollStops(grad) { return function(colorStop) { try { grad.addColorStop(colorStop.stop, colorStop.color); } catch(e) { Util.log(['failed to add color stop: ', e, '; tried to add: ', colorStop]); } }; } Generate.Gradient = function(src, bounds) { if(bounds.width === 0 || bounds.height === 0) { return; } var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), gradient, grad; canvas.width = bounds.width; canvas.height = bounds.height; // TODO: add support for multi defined background gradients gradient = _html2canvas.Generate.parseGradient(src, bounds); if(gradient) { switch(gradient.type) { case 'linear': grad = ctx.createLinearGradient(gradient.x0, gradient.y0, gradient.x1, gradient.y1); gradient.colorStops.forEach(addScrollStops(grad)); ctx.fillStyle = grad; ctx.fillRect(0, 0, bounds.width, bounds.height); break; case 'circle': grad = ctx.createRadialGradient(gradient.cx, gradient.cy, 0, gradient.cx, gradient.cy, gradient.rx); gradient.colorStops.forEach(addScrollStops(grad)); ctx.fillStyle = grad; ctx.fillRect(0, 0, bounds.width, bounds.height); break; case 'ellipse': var canvasRadial = document.createElement('canvas'), ctxRadial = canvasRadial.getContext('2d'), ri = Math.max(gradient.rx, gradient.ry), di = ri * 2; canvasRadial.width = canvasRadial.height = di; grad = ctxRadial.createRadialGradient(gradient.rx, gradient.ry, 0, gradient.rx, gradient.ry, ri); gradient.colorStops.forEach(addScrollStops(grad)); ctxRadial.fillStyle = grad; ctxRadial.fillRect(0, 0, di, di); ctx.fillStyle = gradient.colorStops[gradient.colorStops.length - 1].color; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(canvasRadial, gradient.cx - gradient.rx, gradient.cy - gradient.ry, 2 * gradient.rx, 2 * gradient.ry); break; } } return canvas; }; Generate.ListAlpha = function(number) { var tmp = "", modulus; do { modulus = number % 26; tmp = String.fromCharCode((modulus) + 64) + tmp; number = number / 26; }while((number*26) > 26); return tmp; }; Generate.ListRoman = function(number) { var romanArray = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"], decimal = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1], roman = "", v, len = romanArray.length; if (number <= 0 || number >= 4000) { return number; } for (v=0; v < len; v+=1) { while (number >= decimal[v]) { number -= decimal[v]; roman += romanArray[v]; } } return roman; }; })(); function h2cRenderContext(width, height) { var storage = []; return { storage: storage, width: width, height: height, clip: function() { storage.push({ type: "function", name: "clip", 'arguments': arguments }); }, translate: function() { storage.push({ type: "function", name: "translate", 'arguments': arguments }); }, fill: function() { storage.push({ type: "function", name: "fill", 'arguments': arguments }); }, save: function() { storage.push({ type: "function", name: "save", 'arguments': arguments }); }, restore: function() { storage.push({ type: "function", name: "restore", 'arguments': arguments }); }, fillRect: function () { storage.push({ type: "function", name: "fillRect", 'arguments': arguments }); }, createPattern: function() { storage.push({ type: "function", name: "createPattern", 'arguments': arguments }); }, drawShape: function() { var shape = []; storage.push({ type: "function", name: "drawShape", 'arguments': shape }); return { moveTo: function() { shape.push({ name: "moveTo", 'arguments': arguments }); }, lineTo: function() { shape.push({ name: "lineTo", 'arguments': arguments }); }, arcTo: function() { shape.push({ name: "arcTo", 'arguments': arguments }); }, bezierCurveTo: function() { shape.push({ name: "bezierCurveTo", 'arguments': arguments }); }, quadraticCurveTo: function() { shape.push({ name: "quadraticCurveTo", 'arguments': arguments }); } }; }, drawImage: function () { storage.push({ type: "function", name: "drawImage", 'arguments': arguments }); }, fillText: function () { storage.push({ type: "function", name: "fillText", 'arguments': arguments }); }, setVariable: function (variable, value) { storage.push({ type: "variable", name: variable, 'arguments': value }); return value; } }; } _html2canvas.Parse = function (images, options, cb) { window.scroll(0,0); var element = (( options.elements === undefined ) ? document.body : options.elements[0]), // select body by default numDraws = 0, doc = element.ownerDocument, Util = _html2canvas.Util, support = Util.Support(options, doc), ignoreElementsRegExp = new RegExp("(" + options.ignoreElements + ")"), body = doc.body, getCSS = Util.getCSS, pseudoHide = "___html2canvas___pseudoelement", hidePseudoElementsStyles = doc.createElement('style'); hidePseudoElementsStyles.innerHTML = '.' + pseudoHide + '-parent:before { content: "" !important; display: none !important; }' + '.' + pseudoHide + '-parent:after { content: "" !important; display: none !important; }'; body.appendChild(hidePseudoElementsStyles); images = images || {}; init(); function init() { var background = getCSS(document.documentElement, "backgroundColor"), transparentBackground = (Util.isTransparent(background) && element === document.body), stack = renderElement(element, null, false, transparentBackground); // create pseudo elements in a single pass to prevent synchronous layouts addPseudoElements(element); parseChildren(element, stack, function() { if (transparentBackground) { background = stack.backgroundColor; } removePseudoElements(); Util.log('Done parsing, moving to Render.'); cb({ backgroundColor: background, stack: stack }); }); } // Given a root element, find all pseudo elements below, create elements mocking pseudo element styles // so we can process them as normal elements, and hide the original pseudo elements so they don't interfere // with layout. function addPseudoElements(el) { // These are done in discrete steps to prevent a relayout loop caused by addClass() invalidating // layouts & getPseudoElement calling getComputedStyle. var jobs = [], classes = []; getPseudoElementClasses(); findPseudoElements(el); runJobs(); function getPseudoElementClasses(){ var findPsuedoEls = /:before|:after/; var sheets = document.styleSheets; for (var i = 0, j = sheets.length; i < j; i++) { try { var rules = sheets[i].cssRules; for (var k = 0, l = rules.length; k < l; k++) { if(findPsuedoEls.test(rules[k].selectorText)) { classes.push(rules[k].selectorText); } } } catch(e) { // will throw security exception for style sheets loaded from external domains } } // Trim off the :after and :before (or ::after and ::before) for (i = 0, j = classes.length; i < j; i++) { classes[i] = classes[i].match(/(^[^:]*)/)[1]; } } // Using the list of elements we know how pseudo el styles, create fake pseudo elements. function findPseudoElements(el) { var els = document.querySelectorAll(classes.join(',')); for(var i = 0, j = els.length; i < j; i++) { createPseudoElements(els[i]); } } // Create pseudo elements & add them to a job queue. function createPseudoElements(el) { var before = getPseudoElement(el, ':before'), after = getPseudoElement(el, ':after'); if(before) { jobs.push({type: 'before', pseudo: before, el: el}); } if (after) { jobs.push({type: 'after', pseudo: after, el: el}); } } // Adds a class to the pseudo's parent to prevent the original before/after from messing // with layouts. // Execute the inserts & addClass() calls in a batch to prevent relayouts. function runJobs() { // Add Class jobs.forEach(function(job){ addClass(job.el, pseudoHide + "-parent"); }); // Insert el jobs.forEach(function(job){ if(job.type === 'before'){ job.el.insertBefore(job.pseudo, job.el.firstChild); } else { job.el.appendChild(job.pseudo); } }); } } // Delete our fake pseudo elements from the DOM. This will remove those actual elements // and the classes on their parents that hide the actual pseudo elements. // Note that NodeLists are 'live' collections so you can't use a for loop here. They are // actually deleted from the NodeList after each iteration. function removePseudoElements(){ // delete pseudo elements body.removeChild(hidePseudoElementsStyles); var pseudos = document.getElementsByClassName(pseudoHide + "-element"); while (pseudos.length) { pseudos[0].parentNode.removeChild(pseudos[0]); } // Remove pseudo hiding classes var parents = document.getElementsByClassName(pseudoHide + "-parent"); while(parents.length) { removeClass(parents[0], pseudoHide + "-parent"); } } function addClass (el, className) { if (el.classList) { el.classList.add(className); } else { el.className = el.className + " " + className; } } function removeClass (el, className) { if (el.classList) { el.classList.remove(className); } else { el.className = el.className.replace(className, "").trim(); } } function hasClass (el, className) { return el.className.indexOf(className) > -1; } // Note that this doesn't work in < IE8, but we don't support that anyhow function nodeListToArray (nodeList) { return Array.prototype.slice.call(nodeList); } function documentWidth () { return Math.max( Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth), Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth), Math.max(doc.body.clientWidth, doc.documentElement.clientWidth) ); } function documentHeight () { return Math.max( Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight), Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight), Math.max(doc.body.clientHeight, doc.documentElement.clientHeight) ); } function getCSSInt(element, attribute) { var val = parseInt(getCSS(element, attribute), 10); return (isNaN(val)) ? 0 : val; // borders in old IE are throwing 'medium' for demo.html } function renderRect (ctx, x, y, w, h, bgcolor) { if (bgcolor !== "transparent"){ ctx.setVariable("fillStyle", bgcolor); ctx.fillRect(x, y, w, h); numDraws+=1; } } function capitalize(m, p1, p2) { if (m.length > 0) { return p1 + p2.toUpperCase(); } } function textTransform (text, transform) { switch(transform){ case "lowercase": return text.toLowerCase(); case "capitalize": return text.replace( /(^|\s|:|-|\(|\))([a-z])/g, capitalize); case "uppercase": return text.toUpperCase(); default: return text; } } function noLetterSpacing(letter_spacing) { return (/^(normal|none|0px)$/.test(letter_spacing)); } function drawText(currentText, x, y, ctx){ if (currentText !== null && Util.trimText(currentText).length > 0) { ctx.fillText(currentText, x, y); numDraws+=1; } } function setTextVariables(ctx, el, text_decoration, color) { var align = false, bold = getCSS(el, "fontWeight"), family = getCSS(el, "fontFamily"), size = getCSS(el, "fontSize"), shadows = Util.parseTextShadows(getCSS(el, "textShadow")); switch(parseInt(bold, 10)){ case 401: bold = "bold"; break; case 400: bold = "normal"; break; } ctx.setVariable("fillStyle", color); ctx.setVariable("font", [getCSS(el, "fontStyle"), getCSS(el, "fontVariant"), bold, size, family].join(" ")); ctx.setVariable("textAlign", (align) ? "right" : "left"); if (shadows.length) { // TODO: support multiple text shadows // apply the first text shadow ctx.setVariable("shadowColor", shadows[0].color); ctx.setVariable("shadowOffsetX", shadows[0].offsetX); ctx.setVariable("shadowOffsetY", shadows[0].offsetY); ctx.setVariable("shadowBlur", shadows[0].blur); } if (text_decoration !== "none"){ return Util.Font(family, size, doc); } } function renderTextDecoration(ctx, text_decoration, bounds, metrics, color) { switch(text_decoration) { case "underline": // Draws a line at the baseline of the font // TODO As some browsers display the line as more than 1px if the font-size is big, need to take that into account both in position and size renderRect(ctx, bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, color); break; case "overline": renderRect(ctx, bounds.left, Math.round(bounds.top), bounds.width, 1, color); break; case "line-through": // TODO try and find exact position for line-through renderRect(ctx, bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, color); break; } } function getTextBounds(state, text, textDecoration, isLast, transform) { var bounds; if (support.rangeBounds && !transform) { if (textDecoration !== "none" || Util.trimText(text).length !== 0) { bounds = textRangeBounds(text, state.node, state.textOffset); } state.textOffset += text.length; } else if (state.node && typeof state.node.nodeValue === "string" ){ var newTextNode = (isLast) ? state.node.splitText(text.length) : null; bounds = textWrapperBounds(state.node, transform); state.node = newTextNode; } return bounds; } function textRangeBounds(text, textNode, textOffset) { var range = doc.createRange(); range.setStart(textNode, textOffset); range.setEnd(textNode, textOffset + text.length); return range.getBoundingClientRect(); } function textWrapperBounds(oldTextNode, transform) { var parent = oldTextNode.parentNode, wrapElement = doc.createElement('wrapper'), backupText = oldTextNode.cloneNode(true); wrapElement.appendChild(oldTextNode.cloneNode(true)); parent.replaceChild(wrapElement, oldTextNode); var bounds = transform ? Util.OffsetBounds(wrapElement) : Util.Bounds(wrapElement); parent.replaceChild(backupText, wrapElement); return bounds; } function renderText(el, textNode, stack) { var ctx = stack.ctx, color = getCSS(el, "color"), textDecoration = getCSS(el, "textDecoration"), textAlign = getCSS(el, "textAlign"), metrics, textList, state = { node: textNode, textOffset: 0 }; if (Util.trimText(textNode.nodeValue).length > 0) { textNode.nodeValue = textTransform(textNode.nodeValue, getCSS(el, "textTransform")); textAlign = textAlign.replace(["-webkit-auto"],["auto"]); textList = (!options.letterRendering && /^(left|right|justify|auto)$/.test(textAlign) && noLetterSpacing(getCSS(el, "letterSpacing"))) ? textNode.nodeValue.split(/(\b| )/) : textNode.nodeValue.split(""); metrics = setTextVariables(ctx, el, textDecoration, color); if (options.chinese) { textList.forEach(function(word, index) { if (/.*[\u4E00-\u9FA5].*$/.test(word)) { word = word.split(""); word.unshift(index, 1); textList.splice.apply(textList, word); } }); } textList.forEach(function(text, index) { var bounds = getTextBounds(state, text, textDecoration, (index < textList.length - 1), stack.transform.matrix); if (bounds) { drawText(text, bounds.left, bounds.bottom, ctx); renderTextDecoration(ctx, textDecoration, bounds, metrics, color); } }); } } function listPosition (element, val) { var boundElement = doc.createElement( "boundelement" ), originalType, bounds; boundElement.style.display = "inline"; originalType = element.style.listStyleType; element.style.listStyleType = "none"; boundElement.appendChild(doc.createTextNode(val)); element.insertBefore(boundElement, element.firstChild); bounds = Util.Bounds(boundElement); element.removeChild(boundElement); element.style.listStyleType = originalType; return bounds; } function elementIndex(el) { var i = -1, count = 1, childs = el.parentNode.childNodes; if (el.parentNode) { while(childs[++i] !== el) { if (childs[i].nodeType === 1) { count++; } } return count; } else { return -1; } } function listItemText(element, type) { var currentIndex = elementIndex(element), text; switch(type){ case "decimal": text = currentIndex; break; case "decimal-leading-zero": text = (currentIndex.toString().length === 1) ? currentIndex = "0" + currentIndex.toString() : currentIndex.toString(); break; case "upper-roman": text = _html2canvas.Generate.ListRoman( currentIndex ); break; case "lower-roman": text = _html2canvas.Generate.ListRoman( currentIndex ).toLowerCase(); break; case "lower-alpha": text = _html2canvas.Generate.ListAlpha( currentIndex ).toLowerCase(); break; case "upper-alpha": text = _html2canvas.Generate.ListAlpha( currentIndex ); break; } return text + ". "; } function renderListItem(element, stack, elBounds) { var x, text, ctx = stack.ctx, type = getCSS(element, "listStyleType"), listBounds; if (/^(decimal|decimal-leading-zero|upper-alpha|upper-latin|upper-roman|lower-alpha|lower-greek|lower-latin|lower-roman)$/i.test(type)) { text = listItemText(element, type); listBounds = listPosition(element, text); setTextVariables(ctx, element, "none", getCSS(element, "color")); if (getCSS(element, "listStylePosition") === "inside") { ctx.setVariable("textAlign", "left"); x = elBounds.left; } else { return; } drawText(text, x, listBounds.bottom, ctx); } } function loadImage (src){ var img = images[src]; return (img && img.succeeded === true) ? img.img : false; } function clipBounds(src, dst){ var x = Math.max(src.left, dst.left), y = Math.max(src.top, dst.top), x2 = Math.min((src.left + src.width), (dst.left + dst.width)), y2 = Math.min((src.top + src.height), (dst.top + dst.height)); return { left:x, top:y, width:x2-x, height:y2-y }; } function setZ(element, stack, parentStack){ var newContext, isPositioned = stack.cssPosition !== 'static', zIndex = isPositioned ? getCSS(element, 'zIndex') : 'auto', opacity = getCSS(element, 'opacity'), isFloated = getCSS(element, 'cssFloat') !== 'none'; // https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context // When a new stacking context should be created: // the root element (HTML), // positioned (absolutely or relatively) with a z-index value other than "auto", // elements with an opacity value less than 1. (See the specification for opacity), // on mobile WebKit and Chrome 22+, position: fixed always creates a new stacking context, even when z-index is "auto" (See this post) stack.zIndex = newContext = h2czContext(zIndex); newContext.isPositioned = isPositioned; newContext.isFloated = isFloated; newContext.opacity = opacity; newContext.ownStacking = (zIndex !== 'auto' || opacity < 1); newContext.depth = parentStack ? (parentStack.zIndex.depth + 1) : 0; if (parentStack) { parentStack.zIndex.children.push(stack); } } function h2czContext(zindex) { return { depth: 0, zindex: zindex, children: [] }; } function renderImage(ctx, element, image, bounds, borders) { var paddingLeft = getCSSInt(element, 'paddingLeft'), paddingTop = getCSSInt(element, 'paddingTop'), paddingRight = getCSSInt(element, 'paddingRight'), paddingBottom = getCSSInt(element, 'paddingBottom'); drawImage( ctx, image, 0, //sx 0, //sy image.width, //sw image.height, //sh bounds.left + paddingLeft + borders[3].width, //dx bounds.top + paddingTop + borders[0].width, // dy bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight), //dw bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom) //dh ); } function getBorderData(element) { return ["Top", "Right", "Bottom", "Left"].map(function(side) { return { width: getCSSInt(element, 'border' + side + 'Width'), color: getCSS(element, 'border' + side + 'Color') }; }); } function getBorderRadiusData(element) { return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) { return getCSS(element, 'border' + side + 'Radius'); }); } function getCurvePoints(x, y, r1, r2) { var kappa = 4 * ((Math.sqrt(2) - 1) / 3); var ox = (r1) * kappa, // control point offset horizontal oy = (r2) * kappa, // control point offset vertical xm = x + r1, // x-middle ym = y + r2; // y-middle return { topLeft: bezierCurve({ x:x, y:ym }, { x:x, y:ym - oy }, { x:xm - ox, y:y }, { x:xm, y:y }), topRight: bezierCurve({ x:x, y:y }, { x:x + ox, y:y }, { x:xm, y:ym - oy }, { x:xm, y:ym }), bottomRight: bezierCurve({ x:xm, y:y }, { x:xm, y:y + oy }, { x:x + ox, y:ym }, { x:x, y:ym }), bottomLeft: bezierCurve({ x:xm, y:ym }, { x:xm - ox, y:ym }, { x:x, y:y + oy }, { x:x, y:y }) }; } function bezierCurve(start, startControl, endControl, end) { var lerp = function (a, b, t) { return { x:a.x + (b.x - a.x) * t, y:a.y + (b.y - a.y) * t }; }; return { start: start, startControl: startControl, endControl: endControl, end: end, subdivide: function(t) { var ab = lerp(start, startControl, t), bc = lerp(startControl, endControl, t), cd = lerp(endControl, end, t), abbc = lerp(ab, bc, t), bccd = lerp(bc, cd, t), dest = lerp(abbc, bccd, t); return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)]; }, curveTo: function(borderArgs) { borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]); }, curveToReversed: function(borderArgs) { borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]); } }; } function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) { if (radius1[0] > 0 || radius1[1] > 0) { borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]); corner1[0].curveTo(borderArgs); corner1[1].curveTo(borderArgs); } else { borderArgs.push(["line", x, y]); } if (radius2[0] > 0 || radius2[1] > 0) { borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]); } } function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) { var borderArgs = []; if (radius1[0] > 0 || radius1[1] > 0) { borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]); outer1[1].curveTo(borderArgs); } else { borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]); } if (radius2[0] > 0 || radius2[1] > 0) { borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]); outer2[0].curveTo(borderArgs); borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]); inner2[0].curveToReversed(borderArgs); } else { borderArgs.push([ "line", borderData.c2[0], borderData.c2[1]]); borderArgs.push([ "line", borderData.c3[0], borderData.c3[1]]); } if (radius1[0] > 0 || radius1[1] > 0) { borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]); inner1[1].curveToReversed(borderArgs); } else { borderArgs.push([ "line", borderData.c4[0], borderData.c4[1]]); } return borderArgs; } function calculateCurvePoints(bounds, borderRadius, borders) { var x = bounds.left, y = bounds.top, width = bounds.width, height = bounds.height, tlh = borderRadius[0][0], tlv = borderRadius[0][1], trh = borderRadius[1][0], trv = borderRadius[1][1], brh = borderRadius[2][0], brv = borderRadius[2][1], blh = borderRadius[3][0], blv = borderRadius[3][1], topWidth = width - trh, rightHeight = height - brv, bottomWidth = width - brh, leftHeight = height - blv; return { topLeftOuter: getCurvePoints( x, y, tlh, tlv ).topLeft.subdivide(0.5), topLeftInner: getCurvePoints( x + borders[3].width, y + borders[0].width, Math.max(0, tlh - borders[3].width), Math.max(0, tlv - borders[0].width) ).topLeft.subdivide(0.5), topRightOuter: getCurvePoints( x + topWidth, y, trh, trv ).topRight.subdivide(0.5), topRightInner: getCurvePoints( x + Math.min(topWidth, width + borders[3].width), y + borders[0].width, (topWidth > width + borders[3].width) ? 0 :trh - borders[3].width, trv - borders[0].width ).topRight.subdivide(0.5), bottomRightOuter: getCurvePoints( x + bottomWidth, y + rightHeight, brh, brv ).bottomRight.subdivide(0.5), bottomRightInner: getCurvePoints( x + Math.min(bottomWidth, width + borders[3].width), y + Math.min(rightHeight, height + borders[0].width), Math.max(0, brh - borders[1].width), Math.max(0, brv - borders[2].width) ).bottomRight.subdivide(0.5), bottomLeftOuter: getCurvePoints( x, y + leftHeight, blh, blv ).bottomLeft.subdivide(0.5), bottomLeftInner: getCurvePoints( x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), Math.max(0, blv - borders[2].width) ).bottomLeft.subdivide(0.5) }; } function getBorderClip(element, borderPoints, borders, radius, bounds) { var backgroundClip = getCSS(element, 'backgroundClip'), borderArgs = []; switch(backgroundClip) { case "content-box": case "padding-box": parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width); parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width); parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width); parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width); break; default: parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top); parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top); parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height); parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height); break; } return borderArgs; } function parseBorders(element, bounds, borders){ var x = bounds.left, y = bounds.top, width = bounds.width, height = bounds.height, borderSide, bx, by, bw, bh, borderArgs, // http://www.w3.org/TR/css3-background/#the-border-radius borderRadius = getBorderRadiusData(element), borderPoints = calculateCurvePoints(bounds, borderRadius, borders), borderData = { clip: getBorderClip(element, borderPoints, borders, borderRadius, bounds), borders: [] }; for (borderSide = 0; borderSide < 4; borderSide++) { if (borders[borderSide].width > 0) { bx = x; by = y; bw = width; bh = height - (borders[2].width); switch(borderSide) { case 0: // top border bh = borders[0].width; borderArgs = drawSide({ c1: [bx, by], c2: [bx + bw, by], c3: [bx + bw - borders[1].width, by + bh], c4: [bx + borders[3].width, by + bh] }, borderRadius[0], borderRadius[1], borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner); break; case 1: // right border bx = x + width - (borders[1].width); bw = borders[1].width; borderArgs = drawSide({ c1: [bx + bw, by], c2: [bx + bw, by + bh + borders[2].width], c3: [bx, by + bh], c4: [bx, by + borders[0].width] }, borderRadius[1], borderRadius[2], borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner); break; case 2: // bottom border by = (by + height) - (borders[2].width); bh = borders[2].width; borderArgs = drawSide({ c1: [bx + bw, by + bh], c2: [bx, by + bh], c3: [bx + borders[3].width, by], c4: [bx + bw - borders[3].width, by] }, borderRadius[2], borderRadius[3], borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner); break; case 3: // left border bw = borders[3].width; borderArgs = drawSide({ c1: [bx, by + bh + borders[2].width], c2: [bx, by], c3: [bx + bw, by + borders[0].width], c4: [bx + bw, by + bh] }, borderRadius[3], borderRadius[0], borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner); break; } borderData.borders.push({ args: borderArgs, color: borders[borderSide].color }); } } return borderData; } function createShape(ctx, args) { var shape = ctx.drawShape(); args.forEach(function(border, index) { shape[(index === 0) ? "moveTo" : border[0] + "To" ].apply(null, border.slice(1)); }); return shape; } function renderBorders(ctx, borderArgs, color) { if (color !== "transparent") { ctx.setVariable( "fillStyle", color); createShape(ctx, borderArgs); ctx.fill(); numDraws+=1; } } function renderFormValue (el, bounds, stack){ var valueWrap = doc.createElement('valuewrap'), cssPropertyArray = ['lineHeight','textAlign','fontFamily','color','fontSize','paddingLeft','paddingTop','width','height','border','borderLeftWidth','borderTopWidth'], textValue, textNode; cssPropertyArray.forEach(function(property) { try { valueWrap.style[property] = getCSS(el, property); } catch(e) { // Older IE has issues with "border" Util.log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message); } }); valueWrap.style.borderColor = "black"; valueWrap.style.borderStyle = "solid"; valueWrap.style.display = "block"; valueWrap.style.position = "absolute"; if (/^(submit|reset|button|text|password)$/.test(el.type) || el.nodeName === "SELECT"){ valueWrap.style.lineHeight = getCSS(el, "height"); } valueWrap.style.top = bounds.top + "px"; valueWrap.style.left = bounds.left + "px"; textValue = (el.nodeName === "SELECT") ? (el.options[el.selectedIndex] || 0).text : el.value; if(!textValue) { textValue = el.placeholder; } textNode = doc.createTextNode(textValue); valueWrap.appendChild(textNode); body.appendChild(valueWrap); renderText(el, textNode, stack); body.removeChild(valueWrap); } function drawImage (ctx) { ctx.drawImage.apply(ctx, Array.prototype.slice.call(arguments, 1)); numDraws+=1; } function getPseudoElement(el, which) { var elStyle = window.getComputedStyle(el, which); var parentStyle = window.getComputedStyle(el); // If no content attribute is present, the pseudo element is hidden, // or the parent has a content property equal to the content on the pseudo element, // move along. if(!elStyle || !elStyle.content || elStyle.content === "none" || elStyle.content === "-moz-alt-content" || elStyle.display === "none" || parentStyle.content === elStyle.content) { return; } var content = elStyle.content + ''; // Strip inner quotes if(content[0] === "'" || content[0] === "\"") { content = content.replace(/(^['"])|(['"]$)/g, ''); } var isImage = content.substr( 0, 3 ) === 'url', elps = document.createElement( isImage ? 'img' : 'span' ); elps.className = pseudoHide + "-element "; Object.keys(elStyle).filter(indexedProperty).forEach(function(prop) { // Prevent assigning of read only CSS Rules, ex. length, parentRule try { elps.style[prop] = elStyle[prop]; } catch (e) { Util.log(['Tried to assign readonly property ', prop, 'Error:', e]); } }); if(isImage) { elps.src = Util.parseBackgroundImage(content)[0].args[0]; } else { elps.innerHTML = content; } return elps; } function indexedProperty(property) { return (isNaN(window.parseInt(property, 10))); } function renderBackgroundRepeat(ctx, image, backgroundPosition, bounds) { var offsetX = Math.round(bounds.left + backgroundPosition.left), offsetY = Math.round(bounds.top + backgroundPosition.top); ctx.createPattern(image); ctx.translate(offsetX, offsetY); ctx.fill(); ctx.translate(-offsetX, -offsetY); } function backgroundRepeatShape(ctx, image, backgroundPosition, bounds, left, top, width, height) { var args = []; args.push(["line", Math.round(left), Math.round(top)]); args.push(["line", Math.round(left + width), Math.round(top)]); args.push(["line", Math.round(left + width), Math.round(height + top)]); args.push(["line", Math.round(left), Math.round(height + top)]); createShape(ctx, args); ctx.save(); ctx.clip(); renderBackgroundRepeat(ctx, image, backgroundPosition, bounds); ctx.restore(); } function renderBackgroundColor(ctx, backgroundBounds, bgcolor) { renderRect( ctx, backgroundBounds.left, backgroundBounds.top, backgroundBounds.width, backgroundBounds.height, bgcolor ); } function renderBackgroundRepeating(el, bounds, ctx, image, imageIndex) { var backgroundSize = Util.BackgroundSize(el, bounds, image, imageIndex), backgroundPosition = Util.BackgroundPosition(el, bounds, image, imageIndex, backgroundSize), backgroundRepeat = Util.BackgroundRepeat(el, imageIndex); image = resizeImage(image, backgroundSize); switch (backgroundRepeat) { case "repeat-x": case "repeat no-repeat": backgroundRepeatShape(ctx, image, backgroundPosition, bounds, bounds.left, bounds.top + backgroundPosition.top, 99999, image.height); break; case "repeat-y": case "no-repeat repeat": backgroundRepeatShape(ctx, image, backgroundPosition, bounds, bounds.left + backgroundPosition.left, bounds.top, image.width, 99999); break; case "no-repeat": backgroundRepeatShape(ctx, image, backgroundPosition, bounds, bounds.left + backgroundPosition.left, bounds.top + backgroundPosition.top, image.width, image.height); break; default: renderBackgroundRepeat(ctx, image, backgroundPosition, { top: bounds.top, left: bounds.left, width: image.width, height: image.height }); break; } } function renderBackgroundImage(element, bounds, ctx) { var backgroundImage = getCSS(element, "backgroundImage"), backgroundImages = Util.parseBackgroundImage(backgroundImage), image, imageIndex = backgroundImages.length; while(imageIndex--) { backgroundImage = backgroundImages[imageIndex]; if (!backgroundImage.args || backgroundImage.args.length === 0) { continue; } var key = backgroundImage.method === 'url' ? backgroundImage.args[0] : backgroundImage.value; image = loadImage(key); // TODO add support for background-origin if (image) { renderBackgroundRepeating(element, bounds, ctx, image, imageIndex); } else { Util.log("html2canvas: Error loading background:", backgroundImage); } } } function resizeImage(image, bounds) { if(image.width === bounds.width && image.height === bounds.height) { return image; } var ctx, canvas = doc.createElement('canvas'); canvas.width = bounds.width; canvas.height = bounds.height; ctx = canvas.getContext("2d"); drawImage(ctx, image, 0, 0, image.width, image.height, 0, 0, bounds.width, bounds.height ); return canvas; } function setOpacity(ctx, element, parentStack) { return ctx.setVariable("globalAlpha", getCSS(element, "opacity") * ((parentStack) ? parentStack.opacity : 1)); } function removePx(str) { return str.replace("px", ""); } function getTransform(element, parentStack) { var transformRegExp = /(matrix)\((.+)\)/; var transform = getCSS(element, "transform") || getCSS(element, "-webkit-transform") || getCSS(element, "-moz-transform") || getCSS(element, "-ms-transform") || getCSS(element, "-o-transform"); var transformOrigin = getCSS(element, "transform-origin") || getCSS(element, "-webkit-transform-origin") || getCSS(element, "-moz-transform-origin") || getCSS(element, "-ms-transform-origin") || getCSS(element, "-o-transform-origin") || "0px 0px"; transformOrigin = transformOrigin.split(" ").map(removePx).map(Util.asFloat); var matrix; if (transform && transform !== "none") { var match = transform.match(transformRegExp); if (match) { switch(match[1]) { case "matrix": matrix = match[2].split(",").map(Util.trimText).map(Util.asFloat); break; } } } return { origin: transformOrigin, matrix: matrix }; } function createStack(element, parentStack, bounds, transform) { var ctx = h2cRenderContext((!parentStack) ? documentWidth() : bounds.width , (!parentStack) ? documentHeight() : bounds.height), stack = { ctx: ctx, opacity: setOpacity(ctx, element, parentStack), cssPosition: getCSS(element, "position"), borders: getBorderData(element), transform: transform, clip: (parentStack && parentStack.clip) ? Util.Extend( {}, parentStack.clip ) : null }; setZ(element, stack, parentStack); // TODO correct overflow for absolute content residing under a static position if (options.useOverflow === true && /(hidden|scroll|auto)/.test(getCSS(element, "overflow")) === true && /(BODY)/i.test(element.nodeName) === false){ stack.clip = (stack.clip) ? clipBounds(stack.clip, bounds) : bounds; } return stack; } function getBackgroundBounds(borders, bounds, clip) { var backgroundBounds = { left: bounds.left + borders[3].width, top: bounds.top + borders[0].width, width: bounds.width - (borders[1].width + borders[3].width), height: bounds.height - (borders[0].width + borders[2].width) }; if (clip) { backgroundBounds = clipBounds(backgroundBounds, clip); } return backgroundBounds; } function getBounds(element, transform) { var bounds = (transform.matrix) ? Util.OffsetBounds(element) : Util.Bounds(element); transform.origin[0] += bounds.left; transform.origin[1] += bounds.top; return bounds; } function renderElement(element, parentStack, ignoreBackground) { var transform = getTransform(element, parentStack), bounds = getBounds(element, transform), image, stack = createStack(element, parentStack, bounds, transform), borders = stack.borders, ctx = stack.ctx, backgroundBounds = getBackgroundBounds(borders, bounds, stack.clip), borderData = parseBorders(element, bounds, borders), backgroundColor = (ignoreElementsRegExp.test(element.nodeName)) ? "#efefef" : getCSS(element, "backgroundColor"); createShape(ctx, borderData.clip); ctx.save(); ctx.clip(); if (backgroundBounds.height > 0 && backgroundBounds.width > 0 && !ignoreBackground) { renderBackgroundColor(ctx, bounds, backgroundColor); renderBackgroundImage(element, backgroundBounds, ctx); } else if (ignoreBackground) { stack.backgroundColor = backgroundColor; } ctx.restore(); borderData.borders.forEach(function(border) { renderBorders(ctx, border.args, border.color); }); switch(element.nodeName){ case "IMG": if ((image = loadImage(element.getAttribute('src')))) { renderImage(ctx, element, image, bounds, borders); } else { Util.log("html2canvas: Error loading <img>:" + element.getAttribute('src')); } break; case "INPUT": // TODO add all relevant type's, i.e. HTML5 new stuff // todo add support for placeholder attribute for browsers which support it if (/^(text|url|email|submit|button|reset)$/.test(element.type) && (element.value || element.placeholder || "").length > 0){ renderFormValue(element, bounds, stack); } break; case "TEXTAREA": if ((element.value || element.placeholder || "").length > 0){ renderFormValue(element, bounds, stack); } break; case "SELECT": if ((element.options||element.placeholder || "").length > 0){ renderFormValue(element, bounds, stack); } break; case "LI": renderListItem(element, stack, backgroundBounds); break; case "CANVAS": renderImage(ctx, element, element, bounds, borders); break; } return stack; } function isElementVisible(element) { return (getCSS(element, 'display') !== "none" && getCSS(element, 'visibility') !== "hidden" && !element.hasAttribute("data-html2canvas-ignore")); } function parseElement (element, stack, cb) { if (!cb) { cb = function(){}; } if (isElementVisible(element)) { stack = renderElement(element, stack, false) || stack; if (!ignoreElementsRegExp.test(element.nodeName)) { return parseChildren(element, stack, cb); } } cb(); } function parseChildren(element, stack, cb) { var children = Util.Children(element); // After all nodes have processed, finished() will call the cb. // We add one and kick it off so this will still work when children.length === 0. // Note that unless async is true, this will happen synchronously, just will callbacks. var jobs = children.length + 1; finished(); if (options.async) { children.forEach(function(node) { // Don't block the page from rendering setTimeout(function(){ parseNode(node); }, 0); }); } else { children.forEach(parseNode); } function parseNode(node) { if (node.nodeType === node.ELEMENT_NODE) { parseElement(node, stack, finished); } else if (node.nodeType === node.TEXT_NODE) { renderText(element, node, stack); finished(); } else { finished(); } } function finished(el) { if (--jobs <= 0){ Util.log("finished rendering " + children.length + " children."); cb(); } } } }; _html2canvas.Preload = function( options ) { var images = { numLoaded: 0, // also failed are counted here numFailed: 0, numTotal: 0, cleanupDone: false }, pageOrigin, Util = _html2canvas.Util, methods, i, count = 0, element = options.elements[0] || document.body, doc = element.ownerDocument, domImages = element.getElementsByTagName('img'), // Fetch images of the present element only imgLen = domImages.length, link = doc.createElement("a"), supportCORS = (function( img ){ return (img.crossOrigin !== undefined); })(new Image()), timeoutTimer; link.href = window.location.href; pageOrigin = link.protocol + link.host; function isSameOrigin(url){ link.href = url; link.href = link.href; // YES, BELIEVE IT OR NOT, that is required for IE9 - http://jsfiddle.net/niklasvh/2e48b/ var origin = link.protocol + link.host; return (origin === pageOrigin); } function start(){ Util.log("html2canvas: start: images: " + images.numLoaded + " / " + images.numTotal + " (failed: " + images.numFailed + ")"); if (!images.firstRun && images.numLoaded >= images.numTotal){ Util.log("Finished loading images: # " + images.numTotal + " (failed: " + images.numFailed + ")"); if (typeof options.complete === "function"){ options.complete(images); } } } // TODO modify proxy to serve images with CORS enabled, where available function proxyGetImage(url, img, imageObj){ var callback_name, scriptUrl = options.proxy, script; link.href = url; url = link.href; // work around for pages with base href="" set - WARNING: this may change the url callback_name = 'html2canvas_' + (count++); imageObj.callbackname = callback_name; if (scriptUrl.indexOf("?") > -1) { scriptUrl += "&"; } else { scriptUrl += "?"; } scriptUrl += 'url=' + encodeURIComponent(url) + '&callback=' + callback_name; script = doc.createElement("script"); window[callback_name] = function(a){ if (a.substring(0,6) === "error:"){ imageObj.succeeded = false; images.numLoaded++; images.numFailed++; start(); } else { setImageLoadHandlers(img, imageObj); img.src = a; } window[callback_name] = undefined; // to work with IE<9 // NOTE: that the undefined callback property-name still exists on the window object (for IE<9) try { delete window[callback_name]; // for all browser that support this } catch(ex) {} script.parentNode.removeChild(script); script = null; delete imageObj.script; delete imageObj.callbackname; }; script.setAttribute("type", "text/javascript"); script.setAttribute("src", scriptUrl); imageObj.script = script; window.document.body.appendChild(script); } function loadPseudoElement(element, type) { var style = window.getComputedStyle(element, type), content = style.content; if (content.substr(0, 3) === 'url') { methods.loadImage(_html2canvas.Util.parseBackgroundImage(content)[0].args[0]); } loadBackgroundImages(style.backgroundImage, element); } function loadPseudoElementImages(element) { loadPseudoElement(element, ":before"); loadPseudoElement(element, ":after"); } function loadGradientImage(backgroundImage, bounds) { var img = _html2canvas.Generate.Gradient(backgroundImage, bounds); if (img !== undefined){ images[backgroundImage] = { img: img, succeeded: true }; images.numTotal++; images.numLoaded++; start(); } } function invalidBackgrounds(background_image) { return (background_image && background_image.method && background_image.args && background_image.args.length > 0 ); } function loadBackgroundImages(background_image, el) { var bounds; _html2canvas.Util.parseBackgroundImage(background_image).filter(invalidBackgrounds).forEach(function(background_image) { if (background_image.method === 'url') { methods.loadImage(background_image.args[0]); } else if(background_image.method.match(/\-?gradient$/)) { if(bounds === undefined) { bounds = _html2canvas.Util.Bounds(el); } loadGradientImage(background_image.value, bounds); } }); } function getImages (el) { var elNodeType = false; // Firefox fails with permission denied on pages with iframes try { Util.Children(el).forEach(getImages); } catch( e ) {} try { elNodeType = el.nodeType; } catch (ex) { elNodeType = false; Util.log("html2canvas: failed to access some element's nodeType - Exception: " + ex.message); } if (elNodeType === 1 || elNodeType === undefined) { loadPseudoElementImages(el); try { loadBackgroundImages(Util.getCSS(el, 'backgroundImage'), el); } catch(e) { Util.log("html2canvas: failed to get background-image - Exception: " + e.message); } loadBackgroundImages(el); } } function setImageLoadHandlers(img, imageObj) { img.onload = function() { if ( imageObj.timer !== undefined ) { // CORS succeeded window.clearTimeout( imageObj.timer ); } images.numLoaded++; imageObj.succeeded = true; img.onerror = img.onload = null; start(); }; img.onerror = function() { if (img.crossOrigin === "anonymous") { // CORS failed window.clearTimeout( imageObj.timer ); // let's try with proxy instead if ( options.proxy ) { var src = img.src; img = new Image(); imageObj.img = img; img.src = src; proxyGetImage( img.src, img, imageObj ); return; } } images.numLoaded++; images.numFailed++; imageObj.succeeded = false; img.onerror = img.onload = null; start(); }; } methods = { loadImage: function( src ) { var img, imageObj; if ( src && images[src] === undefined ) { img = new Image(); if ( src.match(/data:image\/.*;base64,/i) ) { img.src = src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''); imageObj = images[src] = { img: img }; images.numTotal++; setImageLoadHandlers(img, imageObj); } else if ( isSameOrigin( src ) || options.allowTaint === true ) { imageObj = images[src] = { img: img }; images.numTotal++; setImageLoadHandlers(img, imageObj); img.src = src; } else if ( supportCORS && !options.allowTaint && options.useCORS ) { // attempt to load with CORS img.crossOrigin = "anonymous"; imageObj = images[src] = { img: img }; images.numTotal++; setImageLoadHandlers(img, imageObj); img.src = src; } else if ( options.proxy ) { imageObj = images[src] = { img: img }; images.numTotal++; proxyGetImage( src, img, imageObj ); } } }, cleanupDOM: function(cause) { var img, src; if (!images.cleanupDone) { if (cause && typeof cause === "string") { Util.log("html2canvas: Cleanup because: " + cause); } else { Util.log("html2canvas: Cleanup after timeout: " + options.timeout + " ms."); } for (src in images) { if (images.hasOwnProperty(src)) { img = images[src]; if (typeof img === "object" && img.callbackname && img.succeeded === undefined) { // cancel proxy image request window[img.callbackname] = undefined; // to work with IE<9 // NOTE: that the undefined callback property-name still exists on the window object (for IE<9) try { delete window[img.callbackname]; // for all browser that support this } catch(ex) {} if (img.script && img.script.parentNode) { img.script.setAttribute("src", "about:blank"); // try to cancel running request img.script.parentNode.removeChild(img.script); } images.numLoaded++; images.numFailed++; Util.log("html2canvas: Cleaned up failed img: '" + src + "' Steps: " + images.numLoaded + " / " + images.numTotal); } } } // cancel any pending requests if(window.stop !== undefined) { window.stop(); } else if(document.execCommand !== undefined) { document.execCommand("Stop", false); } if (document.close !== undefined) { document.close(); } images.cleanupDone = true; if (!(cause && typeof cause === "string")) { start(); } } }, renderingDone: function() { if (timeoutTimer) { window.clearTimeout(timeoutTimer); } } }; if (options.timeout > 0) { timeoutTimer = window.setTimeout(methods.cleanupDOM, options.timeout); } Util.log('html2canvas: Preload starts: finding background-images'); images.firstRun = true; getImages(element); Util.log('html2canvas: Preload: Finding images'); // load <img> images for (i = 0; i < imgLen; i+=1){ methods.loadImage( domImages[i].getAttribute( "src" ) ); } images.firstRun = false; Util.log('html2canvas: Preload: Done.'); if (images.numTotal === images.numLoaded) { start(); } return methods; }; _html2canvas.Renderer = function(parseQueue, options){ function sortZindex(a, b) { if (a === 'children') { return -1; } else if (b === 'children') { return 1; } else { return a - b; } } // http://www.w3.org/TR/CSS21/zindex.html function createRenderQueue(parseQueue) { var queue = [], rootContext; rootContext = (function buildStackingContext(rootNode) { var rootContext = {}; function insert(context, node, specialParent) { var zi = (node.zIndex.zindex === 'auto') ? 0 : Number(node.zIndex.zindex), contextForChildren = context, // the stacking context for children isPositioned = node.zIndex.isPositioned, isFloated = node.zIndex.isFloated, stub = {node: node}, childrenDest = specialParent; // where children without z-index should be pushed into if (node.zIndex.ownStacking) { contextForChildren = stub.context = { children: [{node:node, children: []}] }; childrenDest = undefined; } else if (isPositioned || isFloated) { childrenDest = stub.children = []; } if (zi === 0 && specialParent) { specialParent.push(stub); } else { if (!context[zi]) { context[zi] = []; } context[zi].push(stub); } node.zIndex.children.forEach(function(childNode) { insert(contextForChildren, childNode, childrenDest); }); } insert(rootContext, rootNode); return rootContext; })(parseQueue); function sortZ(context) { Object.keys(context).sort(sortZindex).forEach(function(zi) { var nonPositioned = [], floated = [], positioned = [], list = []; // positioned after static context[zi].forEach(function(v) { if (v.node.zIndex.isPositioned || v.node.zIndex.opacity < 1) { // http://www.w3.org/TR/css3-color/#transparency // non-positioned element with opactiy < 1 should be stacked as if it were a positioned element with ‘z-index: 0’ and ‘opacity: 1’. positioned.push(v); } else if (v.node.zIndex.isFloated) { floated.push(v); } else { nonPositioned.push(v); } }); (function walk(arr) { arr.forEach(function(v) { list.push(v); if (v.children) { walk(v.children); } }); })(nonPositioned.concat(floated, positioned)); list.forEach(function(v) { if (v.context) { sortZ(v.context); } else { queue.push(v.node); } }); }); } sortZ(rootContext); return queue; } function getRenderer(rendererName) { var renderer; if (typeof options.renderer === "string" && _html2canvas.Renderer[rendererName] !== undefined) { renderer = _html2canvas.Renderer[rendererName](options); } else if (typeof rendererName === "function") { renderer = rendererName(options); } else { throw new Error("Unknown renderer"); } if ( typeof renderer !== "function" ) { throw new Error("Invalid renderer defined"); } return renderer; } return getRenderer(options.renderer)(parseQueue, options, document, createRenderQueue(parseQueue.stack), _html2canvas); }; _html2canvas.Util.Support = function (options, doc) { function supportSVGRendering() { var img = new Image(), canvas = doc.createElement("canvas"), ctx = (canvas.getContext === undefined) ? false : canvas.getContext("2d"); if (ctx === false) { return false; } canvas.width = canvas.height = 10; img.src = [ "data:image/svg+xml,", "<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'>", "<foreignObject width='10' height='10'>", "<div xmlns='http://www.w3.org/1999/xhtml' style='width:10;height:10;'>", "sup", "</div>", "</foreignObject>", "</svg>" ].join(""); try { ctx.drawImage(img, 0, 0); canvas.toDataURL(); } catch(e) { return false; } _html2canvas.Util.log('html2canvas: Parse: SVG powered rendering available'); return true; } // Test whether we can use ranges to measure bounding boxes // Opera doesn't provide valid bounds.height/bottom even though it supports the method. function supportRangeBounds() { var r, testElement, rangeBounds, rangeHeight, support = false; if (doc.createRange) { r = doc.createRange(); if (r.getBoundingClientRect) { testElement = doc.createElement('boundtest'); testElement.style.height = "123px"; testElement.style.display = "block"; doc.body.appendChild(testElement); r.selectNode(testElement); rangeBounds = r.getBoundingClientRect(); rangeHeight = rangeBounds.height; if (rangeHeight === 123) { support = true; } doc.body.removeChild(testElement); } } return support; } return { rangeBounds: supportRangeBounds(), svgRendering: options.svgRendering && supportSVGRendering() }; }; window.html2canvas = function(elements, opts) { elements = (elements.length) ? elements : [elements]; var queue, canvas, options = { // general logging: false, elements: elements, background: "#fff", // preload options proxy: null, timeout: 0, // no timeout useCORS: false, // try to load images as CORS (where available), before falling back to proxy allowTaint: false, // whether to allow images to taint the canvas, won't need proxy if set to true // parse options svgRendering: false, // use svg powered rendering where available (FF11+) ignoreElements: "IFRAME|OBJECT|PARAM", useOverflow: true, letterRendering: false, chinese: false, async: false, // If true, parsing will not block, but if the user scrolls during parse the image can get weird // render options width: null, height: null, taintTest: true, // do a taint test with all images before applying to canvas renderer: "Canvas" }; options = _html2canvas.Util.Extend(opts, options); _html2canvas.logging = options.logging; options.complete = function( images ) { if (typeof options.onpreloaded === "function") { if ( options.onpreloaded( images ) === false ) { return; } } _html2canvas.Parse( images, options, function(queue) { if (typeof options.onparsed === "function") { if ( options.onparsed( queue ) === false ) { return; } } canvas = _html2canvas.Renderer( queue, options ); if (typeof options.onrendered === "function") { options.onrendered( canvas ); } }); }; // for pages without images, we still want this to be async, i.e. return methods before executing window.setTimeout( function(){ _html2canvas.Preload( options ); }, 0 ); return { render: function( queue, opts ) { return _html2canvas.Renderer( queue, _html2canvas.Util.Extend(opts, options) ); }, parse: function( images, opts ) { return _html2canvas.Parse( images, _html2canvas.Util.Extend(opts, options) ); }, preload: function( opts ) { return _html2canvas.Preload( _html2canvas.Util.Extend(opts, options) ); }, log: _html2canvas.Util.log }; }; window.html2canvas.log = _html2canvas.Util.log; // for renderers window.html2canvas.Renderer = { Canvas: undefined // We are assuming this will be used }; _html2canvas.Renderer.Canvas = function(options) { options = options || {}; var doc = document, safeImages = [], testCanvas = document.createElement("canvas"), testctx = testCanvas.getContext("2d"), Util = _html2canvas.Util, canvas = options.canvas || doc.createElement('canvas'); function createShape(ctx, args) { ctx.beginPath(); args.forEach(function(arg) { ctx[arg.name].apply(ctx, arg['arguments']); }); ctx.closePath(); } function safeImage(item) { if (safeImages.indexOf(item['arguments'][0].src) === -1) { testctx.drawImage(item['arguments'][0], 0, 0); try { testctx.getImageData(0, 0, 1, 1); } catch(e) { testCanvas = doc.createElement("canvas"); testctx = testCanvas.getContext("2d"); return false; } safeImages.push(item['arguments'][0].src); } return true; } function renderItem(ctx, item) { switch(item.type){ case "variable": ctx[item.name] = item['arguments']; break; case "function": switch(item.name) { case "createPattern": if (item['arguments'][0].width > 0 && item['arguments'][0].height > 0) { try { ctx.fillStyle = ctx.createPattern(item['arguments'][0], "repeat"); } catch(e) { Util.log("html2canvas: Renderer: Error creating pattern", e.message); } } break; case "drawShape": createShape(ctx, item['arguments']); break; case "drawImage": if (item['arguments'][8] > 0 && item['arguments'][7] > 0) { if (!options.taintTest || (options.taintTest && safeImage(item))) { ctx.drawImage.apply( ctx, item['arguments'] ); } } break; default: ctx[item.name].apply(ctx, item['arguments']); } break; } } return function(parsedData, options, document, queue, _html2canvas) { var ctx = canvas.getContext("2d"), newCanvas, bounds, fstyle, zStack = parsedData.stack; canvas.width = canvas.style.width = options.width || zStack.ctx.width; canvas.height = canvas.style.height = options.height || zStack.ctx.height; fstyle = ctx.fillStyle; ctx.fillStyle = (Util.isTransparent(parsedData.backgroundColor) && options.background !== undefined) ? options.background : parsedData.backgroundColor; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = fstyle; queue.forEach(function(storageContext) { // set common settings for canvas ctx.textBaseline = "bottom"; ctx.save(); if (storageContext.transform.matrix) { ctx.translate(storageContext.transform.origin[0], storageContext.transform.origin[1]); ctx.transform.apply(ctx, storageContext.transform.matrix); ctx.translate(-storageContext.transform.origin[0], -storageContext.transform.origin[1]); } if (storageContext.clip){ ctx.beginPath(); ctx.rect(storageContext.clip.left, storageContext.clip.top, storageContext.clip.width, storageContext.clip.height); ctx.clip(); } if (storageContext.ctx.storage) { storageContext.ctx.storage.forEach(function(item) { renderItem(ctx, item); }); } ctx.restore(); }); Util.log("html2canvas: Renderer: Canvas renderer done - returning canvas obj"); if (options.elements.length === 1) { if (typeof options.elements[0] === "object" && options.elements[0].nodeName !== "BODY") { // crop image to the bounds of selected (single) element bounds = _html2canvas.Util.Bounds(options.elements[0]); newCanvas = document.createElement('canvas'); newCanvas.width = Math.ceil(bounds.width); newCanvas.height = Math.ceil(bounds.height); ctx = newCanvas.getContext("2d"); ctx.drawImage(canvas, bounds.left, bounds.top, bounds.width, bounds.height, 0, 0, bounds.width, bounds.height); canvas = null; return newCanvas; } } return canvas; }; }; })(window,document);
{ "pile_set_name": "Github" }
var crux = crux || {}; // Whether this is the produciton script or staging script crux.isProdScript = true; // Default URL used for the connector crux.defaultUrl = 'www.google.com'; // Key used for the lastDataUpdate flag crux.lastDataUpdateFlag = 'lastDataUpdate'; // Apps Script cache duration in seconds crux.secondsInMinute = 60; crux.minutesInHour = 60; crux.cacheDurationInHour = 3; crux.cacheDuration = crux.secondsInMinute * crux.minutesInHour * crux.cacheDurationInHour; // Exceptions for script properties that will not get flushed crux.cacheFlushWhitelist = [ 'oauth2.bigQuery', 'oauth2.firebase', 'admins', 'bigQuery.client', 'firebase.client', crux.lastDataUpdateFlag ]; // Query used to pull data from BigQuery crux.dataQueryString = 'SELECT * FROM `chrome-ux-report.materialized.metrics_summary` WHERE origin = @url'; // Query used to validated URL from BigQuery crux.valudateQueryString = 'SELECT origin FROM `chrome-ux-report.materialized.origin_summary` WHERE origin = @url LIMIT 1'; function getConfig(request) { var customConfig = [ { type: 'TEXTINPUT', name: 'url', displayName: 'Enter origin URL:', placeholder: 'e.g. ' + crux.defaultUrl, parameterControl: { allowOverride: true } }, { type: 'INFO', name: 'information', text: "'https://' is added by default. If needed, add 'http://' at the URL beginning (e.g. http://example.com)" } ]; // For admin users, show the additional option for changing the // lastDataUpdate flag. This date indicates when the original dataset // in BigQuery was last updated and is saved in script properties on update. // While caching to Apps Script or Firebase, each Url's cache is tagged with // this date. Later when cache is retrived, the tagged date is compared against // the date in script properties to determine if cache should be reset. if (isAdminUser()) { var lastUpdate = propStore.get('script', crux.lastDataUpdateFlag); customConfig.push({ type: 'TEXTINPUT', name: crux.lastDataUpdateFlag, displayName: 'ADMIN ONLY: Date when BigQuery dataset was updated last (YYYYMMDD)', placeholder: lastUpdate }); } return { configParams: customConfig }; } crux.Schema = [ { name: 'yyyymm', label: 'Release', description: 'Year and month of the release. Corresponds to the table names on BigQuery.', dataType: 'STRING', semantics: { conceptType: 'DIMENSION', semanticType: 'YEAR_MONTH' } }, { name: 'yyyymmdd', label: 'yyyymmdd', description: 'Year, month, and day of the release where the day is always the first of the month. This is needed for the month-over-month comparisons.', dataType: 'STRING', semantics: { conceptType: 'DIMENSION', semanticType: 'YEAR_MONTH_DAY' } }, { name: 'origin', label: 'origin', description: "The URL of the website including protocol and optional subdomain, for example 'https://www.example.com'.", dataType: 'STRING', semantics: { conceptType: 'DIMENSION', semanticType: 'TEXT' } }, { name: 'fast_fp', label: 'Fast FP', description: 'The percent of First Paint experiences < 1 second.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'avg_fp', label: 'Average FP', description: 'The percent of First Paint experiences >= 1 second and < 2.5 seconds.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'slow_fp', label: 'Slow FP', description: 'The percent of First Paint experiences >= 2.5 seconds.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'fast_fcp', label: 'Fast FCP', description: 'The percent of First Contentful Paint experiences < 1 second.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'avg_fcp', label: 'Average FCP', description: 'The percent of First Contentful Paint experiences >= 1 second and < 2.5 seconds.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'slow_fcp', label: 'Slow FCP', description: 'The percent of First Contentful Paint experiences >= 2.5 seconds.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'fast_dcl', label: 'Fast DCL', description: 'The percent of DOM Content Loaded experiences < 1.5 second.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'avg_dcl', label: 'Average DCL', description: 'The percent of DOM Content Loaded experiences >= 1.5 second and < 3.5 seconds.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'slow_dcl', label: 'Slow DCL', description: 'The percent of DOM Content Loaded experiences >= 3.5 seconds.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'fast_ol', label: 'Fast OL', description: 'The percent of Onload experiences < 2.5 second.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'avg_ol', label: 'Average OL', description: 'The percent of Onload experiences >= 2.5 second and < 6.5 seconds.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'slow_ol', label: 'Slow OL', description: 'The percent of Onload experiences >= 6.5 seconds.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'fast_fid', label: 'Fast FID', description: 'The percent of First Input Delay experiences < 50 milliseconds.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'avg_fid', label: 'Average FID', description: 'The percent of First Input Delay experiences >= 50 milliseconds and < 250 milliseconds.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'slow_fid', label: 'Slow FID', description: 'The percent of First Input Delay experiences >= 250 milliseconds.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'desktopDensity', label: 'Desktop', description: 'The proportion of experiences on desktop devices.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'phoneDensity', label: 'Phone', description: 'The proportion of experiences on phone devices.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'tabletDensity', label: 'Tablet', description: 'The proportion of experiences on tablet devices.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: '_4GDensity', label: '4G', description: 'The proportion of experiences on 4G-like connections.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: '_3GDensity', label: '3G', description: 'The proportion of experiences on 3G-like connections.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: '_2GDensity', label: '2G', description: 'The proportion of experiences on 2G-like connections.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'slow2GDensity', label: 'Slow 2G', description: 'The proportion of experiences on Slow2G-like connections.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } }, { name: 'offlineDensity', label: 'Offline', description: 'The proportion of experiences on offline connections.', dataType: 'NUMBER', defaultAggregationType: 'SUM', semantics: { conceptType: 'METRIC', semanticType: 'PERCENT', isReaggregatable: true } } ]; function getSchema(request) { // Caches the data beforehand. This call also returns an error if // config url is invalid or does not exist in the database. The error // stops the users from proceeding from the config screen. getOriginDataset(request); return { schema: crux.Schema }; } /** * Returns whether the BigQuery dataset has been updated. Also updates the * lastDataUpdate flag. * * @param {object} request getSchema/getData request parameter. * @returns {string} Last dataset update in YYYYMMDD format. */ function getDatasetUpdate(request) { var lastDataUpdate = propStore.get('script', crux.lastDataUpdateFlag); var configLastDataUpdate = request.configParams && request.configParams.lastDataUpdate; var shouldUpdate = false; if (configLastDataUpdate !== undefined) { shouldUpdate = configLastDataUpdate > lastDataUpdate; } if (shouldUpdate) { lastDataUpdate = request.configParams.lastDataUpdate; updateDataUpdateFlag(lastDataUpdate); } return lastDataUpdate; } /** * Resets all script properties except for the ones in persistent list. * Deletes the cache in Firebase. */ function flushCache() { var tempStorage = {}; crux.cacheFlushWhitelist.forEach(function(property) { tempStorage[property] = propStore.get('script', property); }); propStore.flush('script'); crux.cacheFlushWhitelist.forEach(function(property) { tempStorage[property] = tempStorage[property] || ''; propStore.set('script', property, tempStorage[property]); }); try { fbFlushCache(); } catch (e) { throwError(false, undefined, 'Failed to flush cache.'); } } /** * Updates the lastDataUpdate flag, and clears Firebase cache. * * @param {number} newDataUpdate The timestamp for last data update in YYYYMMDD format. */ function updateDataUpdateFlag(newDataUpdate) { if (isAdminUser()) { propStore.set('script', crux.lastDataUpdateFlag, newDataUpdate); console.log('BigQuery dataset was updated'); flushCache(); } } /** * Returns the validated or default URL given the config. * * @param {object} configParams config parameters from request. * @returns {string} The url for the endpoint. */ function validateUrl(configParams) { var url = crux.defaultUrl; if (configParams !== undefined && configParams.url !== undefined) { url = configParams.url; } // Remove '/' at the end var lastChar = url.substring(url.length - 1); if (lastChar === '/') { url = url.substring(0, url.length - 1); } // Add 'https://' at the beginning if needed var urlHttps = url.toLowerCase().substring(0, 8) === 'https://'; var urlHttp = url.toLowerCase().substring(0, 7) === 'http://'; if (!urlHttps && !urlHttp) { url = 'https://' + url; } return url; } /** * Completes all necessary queries, caching and returns the full dataset for * the given endpoint. * * @param {object} request getSchema/getData request parameter. * @returns {object} Full dataset for given endpoint. */ function getOriginDataset(request) { var origin = {}; origin.lastUpdate = getDatasetUpdate(request); origin.url = validateUrl(request.configParams); origin.url = origin.url.toLowerCase(); origin.key = digest(origin.url); // If an origin has not been previously cached, a dashboard might trigger // multiple getData calls simulteniousy for the same origin. This can result // in multiple calls to BigQuery / Firebase. Using a user lock ensures that // only one query is make to BigQuery / Firebase and rest of the requests // are made to Apps Script cache. var userLock = LockService.getUserLock(); userLock.waitLock(15000); var lastFirebaseUpdate = propStore.get('script', origin.key); var bqIsFresh = !lastFirebaseUpdate || origin.lastUpdate > lastFirebaseUpdate; var scriptCache = CacheService.getScriptCache(); try { urlExistsInDb(origin.url); } catch (e) { userLock.releaseLock(); throw new Error( 'DS_USER: There are over 4 million origins in this dataset, but ' + origin.url + " is not one of them! Have you tried adding 'www' or 'http' to your origin? \n\n\n" ); } if (bqIsFresh) { try { console.log('hitting BigQuery for ' + origin.url); origin.data = getBqData(origin.url); } catch (e) { userLock.releaseLock(); throwError( true, 'There are over 4 million origins in this dataset, but ' + origin.url + " is not one of them! Have you tried adding 'www' or 'http' to your origin?" ); } } else { var cachedData = scriptCache.get(origin.key); if (cachedData && cachedData !== 'undefined') { userLock.releaseLock(); console.log('hitting Apps Script cache for ' + origin.url); return JSON.parse(cachedData); } } processFirebase(origin); console.log('saving apps script cache for ' + origin.url); scriptCache.put(origin.key, JSON.stringify(origin.data), crux.cacheDuration); userLock.releaseLock(); return origin.data; } function urlExistsInDb(url) { var bqRequest = { query: crux.valudateQueryString, queryParameters: [ { parameterType: { type: 'STRING' }, parameterValue: { value: url }, name: 'url' } ], useLegacySql: false }; var queryResults = getBigQueryResults(bqRequest); var queryStatus = queryResults.data === []; return queryStatus; } function getData(request) { // Create schema for requested fields var requestedSchema = request.fields.map(function(field) { for (var i = 0; i < crux.Schema.length; i++) { if (crux.Schema[i].name == field.name) { return crux.Schema[i]; } } }); // Fetch the data var originDataset = getOriginDataset(request); // Transform fetched data and filter for requested fields var headerIndex = {}; originDataset.headers.forEach(function(header, index) { headerIndex[header] = index; }); var requestedData = originDataset.data.map(function(rowData) { var values = []; requestedSchema.forEach(function(field) { var fieldIndex = headerIndex[field.name]; var fieldValue = rowData[fieldIndex]; values.push(fieldValue); }); return { values: values }; }); return { schema: requestedSchema, rows: requestedData }; } function getAuthType() { return { type: 'NONE' }; } function isAdminUser() { var userEmail = Session.getEffectiveUser().getEmail(); // List of admin users are kept in script property var admins = propStore.get('script', 'admins'); admins = JSON.parse(admins); var response = admins.indexOf(userEmail) >= 0; return response; } // Return the deployment envirnment for the script. Use "staging" for admin users // and "prod" for others. This will be used to change the Firebase db path. crux.getEnvironment = function() { var environment = crux.isProdScript ? 'prod' : 'staging'; return environment; }; function throwError(userSafe, userMessage, adminMessage) { var cc = DataStudioApp.createCommunityConnector(); if (userSafe) { var error = cc.newUserError(); if (userMessage) { error.setText(userMessage); } if (adminMessage) { error.setDebugText(adminMessage); } error.throwException(); } else { cc.newDebugError() .setText(adminMessage) .throwException(); } }
{ "pile_set_name": "Github" }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <queue> // priority_queue(const priority_queue&) = default; #include <queue> #include <cassert> #include <functional> #include "test_macros.h" template <class C> C make(int n) { C c; for (int i = 0; i < n; ++i) c.push_back(i); return c; } int main(int, char**) { std::vector<int> v = make<std::vector<int> >(5); std::priority_queue<int, std::vector<int>, std::greater<int> > qo(std::greater<int>(), v); std::priority_queue<int, std::vector<int>, std::greater<int> > q = qo; assert(q.size() == 5); assert(q.top() == 0); return 0; }
{ "pile_set_name": "Github" }
#import <AppKit/NSRuleEditor.h> @implementation NSRuleEditor -initWithCoder:(NSCoder *)coder { [super initWithCoder:coder]; return self; } -(void)encodeWithCoder:(NSCoder*)coder { } @end
{ "pile_set_name": "Github" }
#ADD_LIBRARY(Kazmath STATIC ${KAZMATH_SRCS}) #INSTALL(TARGETS Kazmath ARCHIVE DESTINATION lib) INCLUDE_DIRECTORIES( ${CMAKE_SOURCE_DIR}/include ) ADD_LIBRARY(kazmath STATIC ${KAZMATH_SOURCES}) INSTALL(TARGETS kazmath ARCHIVE DESTINATION lib) #ADD_LIBRARY(KazmathGL STATIC ${GL_UTILS_SRCS}) #INSTALL(TARGETS KazmathGL ARCHIVE DESTINATION lib) INSTALL(FILES ${KAZMATH_HEADERS} DESTINATION include/kazmath) INSTALL(FILES ${GL_UTILS_HEADERS} DESTINATION include/kazmath/GL)
{ "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. */ from('knative:event/hello.1') .log('Received 1: ${body}') from('knative:event/hello.2') .log('Received 2: ${body}')
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 1b192f0504c69874ebbfef73a65e75d5 timeCreated: 1529573795 licenseType: Pro MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
TARGET ?= ps2_usb_rev1_unimap MCU = atmega32u4 CONFIG_H = config.h BOOTLOADER_SIZE = 4096 BOOTMAGIC_ENABLE ?= no MOUSEKEY_ENABLE ?= yes EXTRAKEY_ENABLE ?= yes CONSOLE_ENABLE ?= yes COMMAND_ENABLE ?= yes NKRO_ENABLE ?= yes PS2_USE_USART = yes PS2_USE_INT = no PS2_USE_BUSYWAIT = no UNIMAP_ENABLE = yes KEYMAP_SECTION_ENABLE = yes include Makefile
{ "pile_set_name": "Github" }
module ml { /** * Vector class */ export class Vector { constructor(private elements: number[]) { } get size(): number { return this.elements.length; } static create(elements: number[]): Vector { return new Vector(elements.slice()); } static rand(n: number): Vector { var elements: number[] = []; while(n--) { elements.push(Math.random()); } return Vector.create(elements); } static zeros(n: number): Vector { var elements: number[] = []; while(n--) { elements.push(0); } return Vector.create(elements); } static arange(n: number): Vector { var elements: number[] = []; for(var i = 0; i < n; i++) { elements[i] = i; } return Vector.create(elements); } public clone(): Vector { return Vector.create(this.elements); } public at(i: number): number { //return (i < 1 || i > this.elements.length) ? null : this.elements[i - 1]; return this.elements[i - 1]; } public add(vector: Vector): Vector { var v: number[] = vector.elements; if(this.elements.length !== v.length) { return null; } return this.map((x, i) => x + v[i - 1]); } public subtract(vector: Vector): Vector { var v: number[] = vector.elements; if(this.elements.length !== v.length) { return null; } return this.map((x, i) => x - v[i - 1]); } public multiply(k: number): Vector { return this.map(x => x * k); } public dot(vector: Vector): number { var v: number[] = vector.elements, product: number = 0, n: number = this.elements.length; if(n !== v.length) { return null; } while(n--) { product += this.elements[n] * v[n]; } return product; } public cross(vector: Vector): Vector { var b: number[] = vector.elements; if(this.elements.length !== 3 || b.length !== 3) { return null; } var a: number[] = this.elements; return Vector.create([ (a[1] * b[2]) - (a[2] * b[1]), (a[2] * b[0]) - (a[0] * b[2]), (a[0] * b[1]) - (a[1] * b[0]) ]); } public mean(): number { var l: number = this.elements.length; var sum: number = 0.0; for(var i = 0; i < l; i++) { sum += this.elements[i]; } return sum / l; } public toString(): string { return "[" + this.elements.join(", ") + "]"; } public map(fn: Function): Vector { var elements: number[] = []; this.forEach((x, i) => elements.push(fn.call(this, x, i))); return Vector.create(elements); } private forEach(fn: Function): void { var n: number = this.elements.length; for(var i = 0; i < n; i++) { fn.call(this, this.elements[i], i + 1); } } } }
{ "pile_set_name": "Github" }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-example17-jquery</title> <script src="../../components/jquery-2.1.1/jquery.js"></script> <script src="../../../angular.js"></script> <script src="script.js"></script> </head> <body ng-app="docsIsolationExample"> <div ng-controller="Controller"> <my-customer info="naomi"></my-customer> </div> </body> </html>
{ "pile_set_name": "Github" }
// @target: es5 // @module: commonjs // @declaration: true // @filename: es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0.ts export var a = 10; // @filename: es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_1.ts import defaultBinding, * as nameSpaceBinding from "./es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0"; var x: number = nameSpaceBinding.a;
{ "pile_set_name": "Github" }
var THREE = require('three'); module.exports = edgeView; function edgeView(scene) { var total = 0; var positions; // positions of each edge in the graph (array of objects pairs from, to) var colors, points; // buffer attributes that represent edge. var geometry, edgeMesh; var colorDirty; return { initPositions: initPositions, update: update, needsUpdate: needsUpdate, color: color }; function needsUpdate() { return colorDirty; } function update() { for (var i = 0; i < total; ++i) { updateEdgePosition(i); } geometry.getAttribute('position').needsUpdate = true; if (colorDirty) { geometry.getAttribute('color').needsUpdate = true; colorDirty = false; } } function color(idx, fromColorHex, toColorHex) { updateEdgeColor(idx/2, fromColorHex, toColorHex); } function initPositions(edgePositions) { positions = edgePositions; total = positions.length/2; points = new Float32Array(total * 6); var colorsInitialized = (colors !== undefined) && colors.length === total * 6; if (!colorsInitialized) colors = new Float32Array(total * 6); for (var i = 0; i < total; ++i) { updateEdgePosition(i); if (!colorsInitialized) updateEdgeColor(i); } geometry = new THREE.BufferGeometry(); var material = new THREE.LineBasicMaterial({ vertexColors: THREE.VertexColors }); geometry.addAttribute('position', new THREE.BufferAttribute(points, 3)); geometry.addAttribute('color', new THREE.BufferAttribute(colors, 3)); if (edgeMesh) { scene.remove(edgeMesh); } edgeMesh = new THREE.Line(geometry, material, THREE.LinePieces); edgeMesh.frustumCulled = false; scene.add(edgeMesh); } function updateEdgeColor(i, fromColorHex, toColorHex) { if (typeof fromColorHex !== 'number') fromColorHex = 0x333333; if (typeof toColorHex !== 'number') toColorHex = fromColorHex; var i6 = i * 6; colors[i6 ] = ((fromColorHex >> 16) & 0xFF)/0xFF; colors[i6 + 1] = ((fromColorHex >> 8) & 0xFF)/0xFF; colors[i6 + 2] = (fromColorHex & 0xFF)/0xFF; colors[i6 + 3] = ((toColorHex >> 16) & 0xFF)/0xFF; colors[i6 + 4] = ((toColorHex >> 8) & 0xFF)/0xFF; colors[i6 + 5] = ( toColorHex & 0xFF)/0xFF; colorDirty = true; } function updateEdgePosition(i) { var from = positions[2 * i]; var to = positions[2 * i + 1]; var i6 = i * 6; points[i6] = from.x; points[i6 + 1] = from.y; points[i6 + 2] = from.z; points[i6 + 3] = to.x; points[i6 + 4] = to.y; points[i6 + 5] = to.z; } }
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.Win32; namespace DevAudit.AuditLibrary { public class ChocolateyPackageSource : PackageSource { #region Constructors public ChocolateyPackageSource(Dictionary<string, object> package_source_options, EventHandler<EnvironmentEventArgs> message_handler) : base(package_source_options,message_handler) { } #endregion #region Overriden properties public override string PackageManagerId { get { return "chocolatey"; } } public override string PackageManagerLabel { get { return "Chocolatey"; } } public override string DefaultPackageManagerConfigurationFile { get { return string.Empty; } } #endregion #region Overriden methods //run and parse output from choco list -lo command. public override IEnumerable<Package> GetPackages(params string[] o) { string choco_command = @"C:\ProgramData\chocolatey\choco.exe"; string process_output = "", process_error = ""; ProcessStartInfo psi = new ProcessStartInfo(choco_command); psi.Arguments = @"list -lo"; psi.CreateNoWindow = true; psi.RedirectStandardError = true; psi.RedirectStandardOutput = true; psi.UseShellExecute = false; Process p = new Process(); p.EnableRaisingEvents = true; p.StartInfo = psi; List<Package> packages = new List<Package>(); p.OutputDataReceived += (object sender, DataReceivedEventArgs e) => { string first = @"(\d+)\s+packages installed"; if (!String.IsNullOrEmpty(e.Data)) { process_output += e.Data + Environment.NewLine; Match m = Regex.Match(e.Data.Trim(), first); if (m.Success) { return; } else { string[] output = e.Data.Trim().Split(' '); if ((output == null) || (output != null) && (output.Length < 2)) { throw new Exception("Could not parse output from choco command: " + e.Data); } else { packages.Add(new Package("chocolatey", output[0], output[1], "")); } } }; }; p.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => { if (!String.IsNullOrEmpty(e.Data)) { process_error += e.Data + Environment.NewLine; }; }; try { p.Start(); } catch (Win32Exception e) { if (e.Message == "The system cannot find the file specified") { throw new Exception("Chocolatey is not installed on this computer or is not on the current PATH.", e); } } p.BeginErrorReadLine(); p.BeginOutputReadLine(); p.WaitForExit(); p.Close(); return packages; } public override bool IsVulnerabilityVersionInPackageVersionRange(string vulnerability_version, string package_version) { return vulnerability_version == package_version; } #endregion } }
{ "pile_set_name": "Github" }
/********************************************* 作者:曹旭升 QQ:279060597 访问博客了解详细介绍及更多内容: http://blog.shengxunwei.com **********************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml; using Sheng.SailingEase.ComponentModel.Design; using Sheng.SailingEase.Drawing; using Sheng.SailingEase.ComponentModel; using Sheng.SailingEase.Infrastructure; using System.Diagnostics; namespace Sheng.SailingEase.Core.Development { [PropertyGridCellProvideAttribute(typeof(PropertyImageResourceChooseEditorAttribute))] class ImageResourceChooseCell : DataGridViewTextBoxCell, IPropertyGirdCell { IResourceComponentService _resourceService = ServiceUnity.ResourceService; public ImageResourceChooseCell() { } public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) { this._oldValue = this.Value; this._oldValueInitialize = true; base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle); ImageResourceChooseCellEditingControl ctl = DataGridView.EditingControl as ImageResourceChooseCellEditingControl; if (this.Value != null) { ctl.ResourceName = this.Value.ToString(); } else { ctl.ResourceName = String.Empty; } } public override Type EditType { get { return typeof(ImageResourceChooseCellEditingControl); } } public override Type ValueType { get { return typeof(String); } } public override object DefaultNewRowValue { get { return String.Empty; } } protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts); graphics.FillRectangle(Brushes.White, cellBounds.X + 1, cellBounds.Y + 1, cellBounds.Width - 2, cellBounds.Height - 2); int imageLocationX = cellBounds.X + 2; int imageLocationY = cellBounds.Y + 2; int imageSizeW = 16; int imageSizeH = 16; Rectangle imageBounds = new Rectangle(imageLocationX, imageLocationY, imageSizeW, imageSizeH); int textLocationX = imageLocationX + imageSizeW + 2; int textLocationY = cellBounds.Y + 4; Point textLoation = new Point(textLocationX, textLocationY); if (this.Value != null && this.Value.ToString() != String.Empty) { string resourceName = this.Value.ToString(); Image imageDraw; if (_resourceService.Container(resourceName)) { ImageResourceInfo imageResource = _resourceService.GetImageResource(resourceName); Image image = imageResource.GetImage(); imageDraw = DrawingTool.GetScaleImage(image, imageSizeW, imageSizeH); if (image != imageDraw) image.Dispose(); } else { imageDraw = DrawingTool.Mark.FileNotFind(imageBounds.Size); } try { graphics.DrawImage(imageDraw, imageBounds); } catch (Exception exception) { Debug.Assert(false, exception.Message); imageDraw = DrawingTool.Mark.FileNotFind(imageBounds.Size); graphics.DrawImage(imageDraw, imageBounds); } imageDraw.Dispose(); Font font = new Font(cellStyle.Font, cellStyle.Font.Style | FontStyle.Bold); Brush textBrush = new SolidBrush(cellStyle.ForeColor); graphics.DrawString(resourceName, font, textBrush, textLoation); font.Dispose(); textBrush.Dispose(); } } protected override bool SetValue(int rowIndex, object value) { bool changed = (base.GetValue(rowIndex) != null && value != null) && base.GetValue(rowIndex).ToString().Equals(value) == false; PropertyGridValidateResult validateResult = this.Owner.ValidateValue(this.OwnerRow.PropertyName, value, changed); if (validateResult.Success == false) { this.ErrorText = validateResult.Message; return false; } return base.SetValue(rowIndex, value); } public PropertyGridPad Owner { get; set; } public PropertyGridRow OwnerRow { get; set; } private PropertyRelatorAttribute _propertyRelatorAttribute; public PropertyRelatorAttribute PropertyRelatorAttribute { get { return _propertyRelatorAttribute; } set { _propertyRelatorAttribute = value; } } private DefaultValueAttribute _defaultValueAttribute; public DefaultValueAttribute DefaultValueAttribute { get { return _defaultValueAttribute; } set { _defaultValueAttribute = value; } } private PropertyEditorAttribute _propertyEditorAttribute; public PropertyEditorAttribute PropertyEditorAttribute { get { return _propertyEditorAttribute; } set { _propertyEditorAttribute = value; } } public string GetPropertyXml(string xmlNodeName) { XmlDocument xmlDoc = new XmlDocument(); XmlElement xmlElement = xmlDoc.CreateElement(xmlNodeName); if (this.Value != null) { xmlElement.InnerText = this.Value.ToString(); } xmlDoc.AppendChild(xmlElement); return xmlDoc.OuterXml; } public string GetPropertyString() { if (this.Value == null) { return String.Empty; } return this.Value.ToString(); } public void SetPropertyValue(object value) { this.Value = value; } public object GetPropertyValue() { if (this.Value == null) { return string.Empty; } return this.Value; } private bool _oldValueInitialize = false; private object _oldValue = null; public object GetPropertyOldValue() { if (!_oldValueInitialize) return this.Value; else return _oldValue; } } }
{ "pile_set_name": "Github" }
/* Copyright (c) 2012, Broadcom Europe Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*============================================================================= VideoCore OS Abstraction Layer - Queue public header file =============================================================================*/ #ifndef VCOS_QUEUE_H #define VCOS_QUEUE_H #ifdef __cplusplus extern "C" { #endif #include "interface/vcos/vcos_types.h" #include "vcos.h" /** \file vcos_queue.h * * API for accessing a fixed length queue. * * Nucleus offers variable length items, but this feature is not used * in the current code base, so is withdrawn to simplify the API. */ /** Create a fixed length queue. * * @param queue Pointer to queue control block * @param name Name of queue * @param message_size Size of each queue message item in words (words are sizeof VCOS_UNSIGNED). * @param queue_start Start address of queue area * @param queue_size Size in words (words are sizeof VCOS_UNSIGNED) of queue * */ VCOS_INLINE_DECL VCOS_STATUS_T vcos_queue_create(VCOS_QUEUE_T *queue, const char *name, VCOS_UNSIGNED message_size, void *queue_start, VCOS_UNSIGNED queue_size); /** Delete a queue. * @param queue The queue to delete */ VCOS_INLINE_DECL void vcos_queue_delete(VCOS_QUEUE_T *queue); /** Send an item to a queue. If there is no space, the call with * either block waiting for space, or return an error, depending * on the value of the wait parameter. * * @param queue The queue to send to * @param src The data to send (length set when queue was created) * @param wait Whether to wait for space (VCOS_SUSPEND) or fail if * no space (VCOS_NO_SUSPEND). * * @return If space available, returns VCOS_SUCCESS. Otherwise returns * VCOS_EAGAIN if no space available before timeout expires. * */ VCOS_INLINE_DECL VCOS_STATUS_T vcos_queue_send(VCOS_QUEUE_T *queue, const void *src, VCOS_UNSIGNED wait); /** Receive an item from a queue. * @param queue The queue to receive from * @param dst Where to write the data to * @param wait Whether to wait (VCOS_SUSPEND) or fail if * empty (VCOS_NO_SUSPEND). * * @return If an item is available, returns VCOS_SUCCESS. Otherwise returns * VCOS_EAGAIN if no item available before timeout expires. */ VCOS_INLINE_DECL VCOS_STATUS_T vcos_queue_receive(VCOS_QUEUE_T *queue, void *dst, VCOS_UNSIGNED wait); #ifdef __cplusplus } #endif #endif
{ "pile_set_name": "Github" }
# context filter option file #This Filter is usable with the following version(s) of Aspell ASPELL >=0.51 #This line will be printed when typing `aspell help context' DESCRIPTION experimental filter for hiding delimited contexts STATIC filter OPTION delimiters TYPE list DESCRIPTION context delimiters (separated by spaces) DEFAULT " " DEFAULT /* */ DEFAULT // \0 ENDOPTION OPTION visible-first TYPE bool DESCRIPTION swaps visible and invisible text DEFAULT false ENDOPTION
{ "pile_set_name": "Github" }
/* * Copyright (C) 2011 Thorsten Liebig ([email protected]) * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "engine_interface_cylindrical_fdtd.h" Engine_Interface_Cylindrical_FDTD::Engine_Interface_Cylindrical_FDTD(Operator_sse* op) : Engine_Interface_SSE_FDTD(op) { m_Op_Cyl = dynamic_cast<Operator_Cylinder*>(op); if (m_Op_Cyl==NULL) { cerr << "Engine_Interface_Cylindrical_FDTD::Engine_Interface_Cylindrical_FDTD: Error: Operator is not a cylindrical operator! Exit!" << endl; exit(1); } } Engine_Interface_Cylindrical_FDTD::~Engine_Interface_Cylindrical_FDTD() { } double* Engine_Interface_Cylindrical_FDTD::GetHField(const unsigned int* pos, double* out) const { if (m_Op_Cyl->GetClosedAlpha()==false) return Engine_Interface_FDTD::GetHField(pos, out); unsigned int iPos[] = {pos[0],pos[1],pos[2]}; if ((m_InterpolType==CELL_INTERPOLATE) && (pos[1]==m_Op->GetNumberOfLines(1))) iPos[1]=0; if ((m_InterpolType==NODE_INTERPOLATE) && (iPos[1]==0)) iPos[1]=m_Op->GetNumberOfLines(1); return Engine_Interface_FDTD::GetHField(iPos, out); } double* Engine_Interface_Cylindrical_FDTD::GetRawInterpolatedField(const unsigned int* pos, double* out, int type) const { if (m_Op_Cyl->GetClosedAlpha()==false) return Engine_Interface_FDTD::GetRawInterpolatedField(pos,out,type); unsigned int iPos[] = {pos[0],pos[1],pos[2]}; if ((m_InterpolType==NODE_INTERPOLATE) && (pos[1]==0)) iPos[1]=m_Op->GetNumberOfLines(1); if ((m_InterpolType==CELL_INTERPOLATE) && (pos[1]==m_Op->GetNumberOfLines(1))) iPos[1]=0; return Engine_Interface_FDTD::GetRawInterpolatedField(iPos,out,type); }
{ "pile_set_name": "Github" }
/* Copyright (C) Intel Corp. 2006. All Rights Reserved. Intel funded Tungsten Graphics (http://www.tungstengraphics.com) to develop this 3D driver. 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 (including the next paragraph) shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **********************************************************************/ /* * Authors: * Keith Whitwell <[email protected]> */ #include "cairoint.h" #include "cairo-drm-intel-brw-eu.h" #include <assert.h> #include <stdlib.h> #include <string.h> /* How does predicate control work when execution_size != 8? Do I * need to test/set for 0xffff when execution_size is 16? */ void brw_set_predicate_control_flag_value( struct brw_compile *p, uint32_t value ) { p->current->header.predicate_control = BRW_PREDICATE_NONE; if (value != 0xff) { if (value != p->flag_value) { brw_push_insn_state(p); brw_MOV(p, brw_flag_reg(), brw_imm_uw(value)); p->flag_value = value; brw_pop_insn_state(p); } p->current->header.predicate_control = BRW_PREDICATE_NORMAL; } } void brw_set_predicate_control( struct brw_compile *p, uint32_t pc ) { p->current->header.predicate_control = pc; } void brw_set_conditionalmod( struct brw_compile *p, uint32_t conditional ) { p->current->header.destreg__conditonalmod = conditional; } void brw_set_access_mode( struct brw_compile *p, uint32_t access_mode ) { p->current->header.access_mode = access_mode; } void brw_set_compression_control( struct brw_compile *p, int compression_control ) { p->current->header.compression_control = compression_control; } void brw_set_mask_control( struct brw_compile *p, uint32_t value ) { p->current->header.mask_control = value; } void brw_set_saturate( struct brw_compile *p, uint32_t value ) { p->current->header.saturate = value; } void brw_push_insn_state( struct brw_compile *p ) { assert(p->current != &p->stack[BRW_EU_MAX_INSN_STACK-1]); memcpy(p->current+1, p->current, sizeof(struct brw_instruction)); p->current++; } void brw_pop_insn_state( struct brw_compile *p ) { assert(p->current != p->stack); p->current--; } /************************************************************************/ void brw_compile_init (struct brw_compile *p, cairo_bool_t is_g4x) { p->nr_insn = 0; p->current = p->stack; memset (p->current, 0, sizeof (p->current[0])); p->is_g4x = is_g4x; /* Some defaults? */ brw_set_mask_control (p, BRW_MASK_ENABLE); /* what does this do? */ brw_set_saturate (p, 0); brw_set_compression_control (p, BRW_COMPRESSION_NONE); brw_set_predicate_control_flag_value (p, 0xff); } const uint32_t * brw_get_program (struct brw_compile *p, uint32_t *sz) { *sz = p->nr_insn * sizeof (struct brw_instruction); return (const uint32_t *)p->store; } /* * Subroutine calls require special attention. * Mesa instructions may be expanded into multiple hardware instructions * so the prog_instruction::BranchTarget field can't be used as an index * into the hardware instructions. * * The BranchTarget field isn't needed, however. Mesa's GLSL compiler * emits CAL and BGNSUB instructions with labels that can be used to map * subroutine calls to actual subroutine code blocks. * * The structures and function here implement patching of CAL instructions * so they jump to the right subroutine code... */ /* * For each OPCODE_BGNSUB we create one of these. */ struct brw_glsl_label { const char *name; /*< the label string */ uint32_t position; /*< the position of the brw instruction for this label */ struct brw_glsl_label *next; /*< next in linked list */ }; /* * For each OPCODE_CAL we create one of these. */ struct brw_glsl_call { uint32_t call_inst_pos; /*< location of the CAL instruction */ const char *sub_name; /*< name of subroutine to call */ struct brw_glsl_call *next; /*< next in linked list */ }; /* * Called for each OPCODE_BGNSUB. */ void brw_save_label(struct brw_compile *c, const char *name, uint32_t position) { struct brw_glsl_label *label = calloc(1, sizeof *label); label->name = name; label->position = position; label->next = c->first_label; c->first_label = label; } /* * Called for each OPCODE_CAL. */ void brw_save_call(struct brw_compile *c, const char *name, uint32_t call_pos) { struct brw_glsl_call *call = calloc(1, sizeof *call); call->call_inst_pos = call_pos; call->sub_name = name; call->next = c->first_call; c->first_call = call; } /* * Lookup a label, return label's position/offset. */ static uint32_t brw_lookup_label(struct brw_compile *c, const char *name) { const struct brw_glsl_label *label; for (label = c->first_label; label; label = label->next) { if (strcmp(name, label->name) == 0) { return label->position; } } abort(); /* should never happen */ return ~0; } /* * When we're done generating code, this function is called to resolve * subroutine calls. */ void brw_resolve_cals(struct brw_compile *c) { const struct brw_glsl_call *call; for (call = c->first_call; call; call = call->next) { const uint32_t sub_loc = brw_lookup_label(c, call->sub_name); struct brw_instruction *brw_call_inst = &c->store[call->call_inst_pos]; struct brw_instruction *brw_sub_inst = &c->store[sub_loc]; int32_t offset = brw_sub_inst - brw_call_inst; /* patch brw_inst1 to point to brw_inst2 */ brw_set_src1(brw_call_inst, brw_imm_d(offset * 16)); } /* free linked list of calls */ { struct brw_glsl_call *call, *next; for (call = c->first_call; call; call = next) { next = call->next; free(call); } c->first_call = NULL; } /* free linked list of labels */ { struct brw_glsl_label *label, *next; for (label = c->first_label; label; label = next) { next = label->next; free(label); } c->first_label = NULL; } }
{ "pile_set_name": "Github" }
# Encoding file: macTurkish, single-byte S 003F 0 1 00 0000000100020003000400050006000700080009000A000B000C000D000E000F 0010001100120013001400150016001700180019001A001B001C001D001E001F 0020002100220023002400250026002700280029002A002B002C002D002E002F 0030003100320033003400350036003700380039003A003B003C003D003E003F 0040004100420043004400450046004700480049004A004B004C004D004E004F 0050005100520053005400550056005700580059005A005B005C005D005E005F 0060006100620063006400650066006700680069006A006B006C006D006E006F 0070007100720073007400750076007700780079007A007B007C007D007E007F 00C400C500C700C900D100D600DC00E100E000E200E400E300E500E700E900E8 00EA00EB00ED00EC00EE00EF00F100F300F200F400F600F500FA00F900FB00FC 202000B000A200A300A7202200B600DF00AE00A9212200B400A8226000C600D8 221E00B12264226500A500B522022211220F03C0222B00AA00BA03A900E600F8 00BF00A100AC221A01922248220600AB00BB202600A000C000C300D501520153 20132014201C201D2018201900F725CA00FF0178011E011F01300131015E015F 202100B7201A201E203000C200CA00C100CB00C800CD00CE00CF00CC00D300D4 F8FF00D200DA00DB00D9F8A002C602DC00AF02D802D902DA00B802DD02DB02C7
{ "pile_set_name": "Github" }
/* * Copyright 2008 Advanced Micro Devices, Inc. * Copyright 2008 Red Hat Inc. * Copyright 2009 Jerome Glisse. * * 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. * * Authors: Dave Airlie * Alex Deucher * Jerome Glisse * Christian König */ #include <drm/drmP.h> #include "radeon.h" /* * IB * IBs (Indirect Buffers) and areas of GPU accessible memory where * commands are stored. You can put a pointer to the IB in the * command ring and the hw will fetch the commands from the IB * and execute them. Generally userspace acceleration drivers * produce command buffers which are send to the kernel and * put in IBs for execution by the requested ring. */ static int radeon_debugfs_sa_init(struct radeon_device *rdev); /** * radeon_ib_get - request an IB (Indirect Buffer) * * @rdev: radeon_device pointer * @ring: ring index the IB is associated with * @ib: IB object returned * @size: requested IB size * * Request an IB (all asics). IBs are allocated using the * suballocator. * Returns 0 on success, error on failure. */ int radeon_ib_get(struct radeon_device *rdev, int ring, struct radeon_ib *ib, struct radeon_vm *vm, unsigned size) { int r; r = radeon_sa_bo_new(rdev, &rdev->ring_tmp_bo, &ib->sa_bo, size, 256); if (r) { dev_err(rdev->dev, "failed to get a new IB (%d)\n", r); return r; } radeon_sync_create(&ib->sync); ib->ring = ring; ib->fence = NULL; ib->ptr = radeon_sa_bo_cpu_addr(ib->sa_bo); ib->vm = vm; if (vm) { /* ib pool is bound at RADEON_VA_IB_OFFSET in virtual address * space and soffset is the offset inside the pool bo */ ib->gpu_addr = ib->sa_bo->soffset + RADEON_VA_IB_OFFSET; } else { ib->gpu_addr = radeon_sa_bo_gpu_addr(ib->sa_bo); } ib->is_const_ib = false; return 0; } /** * radeon_ib_free - free an IB (Indirect Buffer) * * @rdev: radeon_device pointer * @ib: IB object to free * * Free an IB (all asics). */ void radeon_ib_free(struct radeon_device *rdev, struct radeon_ib *ib) { radeon_sync_free(rdev, &ib->sync, ib->fence); radeon_sa_bo_free(rdev, &ib->sa_bo, ib->fence); radeon_fence_unref(&ib->fence); } /** * radeon_ib_schedule - schedule an IB (Indirect Buffer) on the ring * * @rdev: radeon_device pointer * @ib: IB object to schedule * @const_ib: Const IB to schedule (SI only) * @hdp_flush: Whether or not to perform an HDP cache flush * * Schedule an IB on the associated ring (all asics). * Returns 0 on success, error on failure. * * On SI, there are two parallel engines fed from the primary ring, * the CE (Constant Engine) and the DE (Drawing Engine). Since * resource descriptors have moved to memory, the CE allows you to * prime the caches while the DE is updating register state so that * the resource descriptors will be already in cache when the draw is * processed. To accomplish this, the userspace driver submits two * IBs, one for the CE and one for the DE. If there is a CE IB (called * a CONST_IB), it will be put on the ring prior to the DE IB. Prior * to SI there was just a DE IB. */ int radeon_ib_schedule(struct radeon_device *rdev, struct radeon_ib *ib, struct radeon_ib *const_ib, bool hdp_flush) { struct radeon_ring *ring = &rdev->ring[ib->ring]; int r = 0; if (!ib->length_dw || !ring->ready) { /* TODO: Nothings in the ib we should report. */ dev_err(rdev->dev, "couldn't schedule ib\n"); return -EINVAL; } /* 64 dwords should be enough for fence too */ r = radeon_ring_lock(rdev, ring, 64 + RADEON_NUM_SYNCS * 8); if (r) { dev_err(rdev->dev, "scheduling IB failed (%d).\n", r); return r; } /* grab a vm id if necessary */ if (ib->vm) { struct radeon_fence *vm_id_fence; vm_id_fence = radeon_vm_grab_id(rdev, ib->vm, ib->ring); radeon_sync_fence(&ib->sync, vm_id_fence); } /* sync with other rings */ r = radeon_sync_rings(rdev, &ib->sync, ib->ring); if (r) { dev_err(rdev->dev, "failed to sync rings (%d)\n", r); radeon_ring_unlock_undo(rdev, ring); return r; } if (ib->vm) radeon_vm_flush(rdev, ib->vm, ib->ring, ib->sync.last_vm_update); if (const_ib) { radeon_ring_ib_execute(rdev, const_ib->ring, const_ib); radeon_sync_free(rdev, &const_ib->sync, NULL); } radeon_ring_ib_execute(rdev, ib->ring, ib); r = radeon_fence_emit(rdev, &ib->fence, ib->ring); if (r) { dev_err(rdev->dev, "failed to emit fence for new IB (%d)\n", r); radeon_ring_unlock_undo(rdev, ring); return r; } if (const_ib) { const_ib->fence = radeon_fence_ref(ib->fence); } if (ib->vm) radeon_vm_fence(rdev, ib->vm, ib->fence); radeon_ring_unlock_commit(rdev, ring, hdp_flush); return 0; } /** * radeon_ib_pool_init - Init the IB (Indirect Buffer) pool * * @rdev: radeon_device pointer * * Initialize the suballocator to manage a pool of memory * for use as IBs (all asics). * Returns 0 on success, error on failure. */ int radeon_ib_pool_init(struct radeon_device *rdev) { int r; if (rdev->ib_pool_ready) { return 0; } if (rdev->family >= CHIP_BONAIRE) { r = radeon_sa_bo_manager_init(rdev, &rdev->ring_tmp_bo, RADEON_IB_POOL_SIZE*64*1024, RADEON_GPU_PAGE_SIZE, RADEON_GEM_DOMAIN_GTT, RADEON_GEM_GTT_WC); } else { /* Before CIK, it's better to stick to cacheable GTT due * to the command stream checking */ r = radeon_sa_bo_manager_init(rdev, &rdev->ring_tmp_bo, RADEON_IB_POOL_SIZE*64*1024, RADEON_GPU_PAGE_SIZE, RADEON_GEM_DOMAIN_GTT, 0); } if (r) { return r; } r = radeon_sa_bo_manager_start(rdev, &rdev->ring_tmp_bo); if (r) { return r; } rdev->ib_pool_ready = true; if (radeon_debugfs_sa_init(rdev)) { dev_err(rdev->dev, "failed to register debugfs file for SA\n"); } return 0; } /** * radeon_ib_pool_fini - Free the IB (Indirect Buffer) pool * * @rdev: radeon_device pointer * * Tear down the suballocator managing the pool of memory * for use as IBs (all asics). */ void radeon_ib_pool_fini(struct radeon_device *rdev) { if (rdev->ib_pool_ready) { radeon_sa_bo_manager_suspend(rdev, &rdev->ring_tmp_bo); radeon_sa_bo_manager_fini(rdev, &rdev->ring_tmp_bo); rdev->ib_pool_ready = false; } } /** * radeon_ib_ring_tests - test IBs on the rings * * @rdev: radeon_device pointer * * Test an IB (Indirect Buffer) on each ring. * If the test fails, disable the ring. * Returns 0 on success, error if the primary GFX ring * IB test fails. */ int radeon_ib_ring_tests(struct radeon_device *rdev) { unsigned i; int r; for (i = 0; i < RADEON_NUM_RINGS; ++i) { struct radeon_ring *ring = &rdev->ring[i]; if (!ring->ready) continue; r = radeon_ib_test(rdev, i, ring); if (r) { radeon_fence_driver_force_completion(rdev, i); ring->ready = false; rdev->needs_reset = false; if (i == RADEON_RING_TYPE_GFX_INDEX) { /* oh, oh, that's really bad */ DRM_ERROR("radeon: failed testing IB on GFX ring (%d).\n", r); rdev->accel_working = false; return r; } else { /* still not good, but we can live with it */ DRM_ERROR("radeon: failed testing IB on ring %d (%d).\n", i, r); } } } return 0; } /* * Debugfs info */ #if defined(CONFIG_DEBUG_FS) static int radeon_debugfs_sa_info(struct seq_file *m, void *data) { struct drm_info_node *node = (struct drm_info_node *) m->private; struct drm_device *dev = node->minor->dev; struct radeon_device *rdev = dev->dev_private; radeon_sa_bo_dump_debug_info(&rdev->ring_tmp_bo, m); return 0; } static struct drm_info_list radeon_debugfs_sa_list[] = { {"radeon_sa_info", &radeon_debugfs_sa_info, 0, NULL}, }; #endif static int radeon_debugfs_sa_init(struct radeon_device *rdev) { #if defined(CONFIG_DEBUG_FS) return radeon_debugfs_add_files(rdev, radeon_debugfs_sa_list, 1); #else return 0; #endif }
{ "pile_set_name": "Github" }
// // Custom variables // ------------------------------------------------------------ // // Font Bootstrap overwrites // --------------------------------- $font-family-sans-serif: "PT Sans", "Helvetica Neue", Helvetica, Arial, sans-serif !default; $font-family-serif: "Museo Slab", Georgia, "Times New Roman", Times, serif !default; $font-family-base: $font-family-serif !default; $font-size-base: 16px !default; $line-height-base: 1.625 !default; // 26 / 16 $font-size-code-block: 14px !default; $headings-font-family: $font-family-sans-serif !default; $headings-font-weight: 700 !default; // // Other Bootstrap Overwrites // --------------------------------- $pre-scrollable-max-height: 30em !default; // // Colors // --------------------------------- $main-color: #8ba644 !default; // avocado-green $topic-java: #9c27b0 !default; $topic-javafx: #673ab7 !default; $topic-dart: #00bcd4 !default; $topic-html-css: #5677fc !default; $panel-hover-border: #adadad !default;
{ "pile_set_name": "Github" }
/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Mathematics (glm.g-truc.net) /// /// Copyright (c) 2005 - 2015 G-Truc Creation (www.g-truc.net) /// 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. /// /// Restrictions: /// By making use of the Software for military purposes, you choose to make /// a Bunny unhappy. /// /// 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. /// /// @ref gtc_type_aligned /// @file glm/gtc/type_aligned.inl /// @date 2014-11-23 / 2014-11-23 /// @author Christophe Riccio /////////////////////////////////////////////////////////////////////////////////// namespace glm { }
{ "pile_set_name": "Github" }
# SPDX-License-Identifier: GPL-2.0 config SAMSUNG_MC bool "Samsung Exynos Memory Controller support" if COMPILE_TEST help Support for the Memory Controller (MC) devices found on Samsung Exynos SoCs. if SAMSUNG_MC config EXYNOS_SROM bool "Exynos SROM controller driver" if COMPILE_TEST depends on (ARM && ARCH_EXYNOS) || (COMPILE_TEST && HAS_IOMEM) endif
{ "pile_set_name": "Github" }
<?php namespace Directus\Authentication\Sso; use Directus\Util\ArrayUtils; use League\OAuth2\Client\Token\AccessToken; abstract class TwoSocialProvider extends AbstractSocialProvider { /** * @inheritDoc */ public function getRequestAuthorizationUrl() { $options = [ 'scope' => $this->getScopes() ]; return $this->provider->getAuthorizationUrl($options); } /** * @inheritDoc */ public function request() { $requestUrl = $this->getRequestAuthorizationUrl(); header('Location: ' . $requestUrl); } /** * @inheritdoc */ public function handle() { return $this->getUserFromCode([ 'code' => ArrayUtils::get($_GET, 'code') ]); } /** * @inheritdoc */ public function getUserFromCode(array $data) { // Try to get an access token (using the authorization code grant) $token = $this->provider->getAccessToken('authorization_code', [ 'code' => ArrayUtils::get($data, 'code') ]); return new SocialUser([ 'email' => $this->getResourceOwnerEmail($token) ]); } /** * Gets the resource owner email * * @param AccessToken $token * * @return string */ protected function getResourceOwnerEmail(AccessToken $token) { $user = $this->provider->getResourceOwner($token); return $user->getEmail(); } /** * Get the list of scopes for the current service * * @return array */ abstract public function getScopes(); }
{ "pile_set_name": "Github" }