text
stringlengths
2
99.9k
meta
dict
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Form * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** Zend_Dojo_Form_Decorator_DijitContainer */ #require_once 'Zend/Dojo/Form/Decorator/DijitContainer.php'; /** * ContentPane * * Render a dijit ContentPane * * @uses Zend_Dojo_Form_Decorator_DijitContainer * @package Zend_Dojo * @subpackage Form_Decorator * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ class Zend_Dojo_Form_Decorator_ContentPane extends Zend_Dojo_Form_Decorator_DijitContainer { /** * View helper * @var string */ protected $_helper = 'ContentPane'; }
{ "pile_set_name": "Github" }
/* * Copyright 2012 Decebal Suiu * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with * the License. You may obtain a copy of the License in the LICENSE file, or at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.wicketstuff.dashboard; import java.io.Serializable; /** * Container for a widget location on a screen: column + row * @author Decebal Suiu */ public class WidgetLocation implements Serializable { private static final long serialVersionUID = 1L; private int column; private int row; public WidgetLocation() { } public WidgetLocation(int column, int row) { this.column = column; this.row = row; } public int getColumn() { return column; } public void setColumn(int column) { this.column = column; } public int getRow() { return row; } public void setRow(int row) { this.row = row; } public void incrementRow() { row++; } public void decrementRow() { row--; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + column; result = prime * result + row; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } WidgetLocation other = (WidgetLocation) obj; if (column != other.column) { return false; } if (row != other.row) { return false; } return true; } @Override public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("WidgetLocation["); buffer.append("column = ").append(column); buffer.append(" row = ").append(row); buffer.append("]"); return buffer.toString(); } }
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 2001-2011 Hartmut Kaiser Copyright (c) 2013 Agustin Berge Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_SPIRIT_X3_HANDLES_CONTAINER_DEC_18_2010_0920AM) #define BOOST_SPIRIT_X3_HANDLES_CONTAINER_DEC_18_2010_0920AM #include <boost/mpl/bool.hpp> namespace boost { namespace spirit { namespace x3 { namespace traits { /////////////////////////////////////////////////////////////////////////// // Whether a component handles container attributes intrinsically // (or whether container attributes need to be split up separately). // By default, this gets the Component's handles_container nested value. // Components may specialize this if such a handles_container is not // readily available (e.g. expensive to compute at compile time). /////////////////////////////////////////////////////////////////////////// template <typename Component, typename Context, typename Enable = void> struct handles_container : mpl::bool_<Component::handles_container> {}; }}}} #endif
{ "pile_set_name": "Github" }
op { graph_op_name: "MatrixBandPart" endpoint { name: "linalg.BandPart" } }
{ "pile_set_name": "Github" }
<?php return [ /* |-------------------------------------------------------------------------- | Password Reminder Language Lines |-------------------------------------------------------------------------- | | The following language lines are the default lines which match reasons | that are given by the password broker for a password update attempt | has failed, such as for an invalid token or invalid new password. | */ 'password' => 'A senha deve conter pelo menos oito caracteres e ser igual à confirmação.', 'reset' => 'Sua senha foi redefinida!', 'sent' => 'Enviamos um link para redefinir a sua senha por e-mail.', 'token' => 'Esse código de redefinição de senha é inválido.', 'user' => 'Não conseguimos encontrar nenhum usuário com o endereço de e-mail informado.', ];
{ "pile_set_name": "Github" }
BlipSearchPanel = require('../base_mobile').BlipSearchPanel Renderer = require('../renderer_mobile').Renderer formatDate = require('../../../share/utils/datetime').formatDate class MentionsPanel extends BlipSearchPanel __init: -> mentionsProcessor = require('./processor').instance refreshParams = { isVisible: false visibleUpdateInterval: window.uiConf.search.refreshInterval.visible hiddenUpdateInterval: window.uiConf.search.refreshInterval.hidden unvisibleBrowserTabUpdateInterval: null } super(mentionsProcessor, refreshParams, Renderer) __parseResponseItem: (item) -> id = @__getItemId(item.waveId, item.blipId) return @__getItem(id) if not item.changed @__getCommonItem(id, item.title, item.snippet, formatDate(item.lastSent), formatDate(item.lastSent, true), item.senderName || item.senderEmail, item.senderAvatar, !item.isRead, item.waveId, item.blipId) __getSearchFunction: -> 'network.message.searchMessageContent' __getPanelName: -> 'mentionsPanel' exports.MentionsPanel = MentionsPanel
{ "pile_set_name": "Github" }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Mupen64plus-rsp-hle - common.h * * Mupen64Plus homepage: https://mupen64plus.org/ * * Copyright (C) 2014 Bobby Smiles * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef COMMON_H #define COMMON_H /* macro for unused variable warning suppression */ #ifdef __GNUC__ # define UNUSED(x) UNUSED_ ## x __attribute__((__unused__)) #else # define UNUSED(x) UNUSED_ ## x #endif /* macro for inline keyword */ #ifdef _MSC_VER #define inline __inline #endif #endif
{ "pile_set_name": "Github" }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Collections.Generic; using YamlDotNet.Serialization; namespace KubeClient.Models { /// <summary> /// ObjectMeta is metadata that all persisted resources must have, which includes all objects users must create. /// </summary> public partial class ObjectMetaV1 { /// <summary> /// Additional data (if any) that does not correspond to properties defined on the <see cref="ObjectMetaV1"/> model. /// </summary> [JsonExtensionData] readonly Dictionary<string, JToken> _extensionData = new Dictionary<string, JToken>(); /// <summary> /// Additional serialised data (if any) that does not correspond to properties defined on the <see cref="ObjectMetaV1"/> model. /// </summary> [JsonIgnore, YamlIgnore] public IDictionary<string, JToken> ExtensionData => _extensionData; } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2015 Alejandro Martinez ([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 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "RideMetric.h" #include "Units.h" #include "Settings.h" #include "RideFileCache.h" #include "VDOTCalculator.h" #include "RideItem.h" #include "Context.h" #include "Athlete.h" #include "Specification.h" #include <cmath> #include <assert.h> #include <QApplication> // Daniels VDOT class VDOT : public RideMetric { Q_DECLARE_TR_FUNCTIONS(VDOT) double vdot; public: VDOT() : vdot(0.0) { setSymbol("VDOT"); setInternalName("VDOT"); } void initialize() { setName(tr("VDOT")); setMetricUnits(tr("ml/min/kg")); setImperialUnits(tr("ml/min/kg")); setType(RideMetric::Peak); setPrecision(1); setDescription(tr("Daniels' VDOT computed from best average pace for durations from 4 min 4 hr")); } void compute(RideItem *item, Specification, const QHash<QString,RideMetric*> &) { // not a run if (!item->isRun) { setValue(RideFile::NIL); setCount(0); return; } // build a cache -- VDOT does not work with intervals ! RideFileCache rfc(item->ride()); // search for max VDOT from 4 min to 4 hr vdot = 0.0; int iMax = std::min(rfc.meanMaxArray(RideFile::kph).size(), 14400); for (int i = 240; i < iMax; i++) { double vel = rfc.meanMaxArray(RideFile::kph)[i]*1000.0/60.0; vdot = std::max(vdot, VDOTCalculator::vdot(i / 60.0, vel)); } setValue(vdot); setCount(1); } bool isRelevantForRide(const RideItem *ride) const { return ride->isRun; } MetricClass classification() const { return Undefined; } MetricValidity validity() const { return Unknown; } RideMetric *clone() const { return new VDOT(*this); } }; // Daniels T-Pace class TPace : public RideMetric { Q_DECLARE_TR_FUNCTIONS(TPace) double tPace; public: TPace() : tPace(0.0) { setSymbol("TPace"); setInternalName("TPace"); } // TPace ordering is reversed bool isLowerBetter() const { return true; } // Overrides to use Pace units setting QString units(bool) const { bool metricRunPace = appsettings->value(NULL, GC_PACE, GlobalContext::context()->useMetricUnits).toBool(); return RideMetric::units(metricRunPace); } double value(bool) const { bool metricRunPace = appsettings->value(NULL, GC_PACE, GlobalContext::context()->useMetricUnits).toBool(); return RideMetric::value(metricRunPace); } QString toString(bool metric) const { return time_to_string(value(metric)*60); } void initialize() { setName(tr("TPace")); setType(RideMetric::Low); setMetricUnits(tr("min/km")); setImperialUnits(tr("min/mile")); setPrecision(1); setConversion(KM_PER_MILE); setDescription(tr("Daniels' TPace, computed as 90%vVDOT from VDOT metric, in min/km or min/mile")); } void compute(RideItem *item, Specification, const QHash<QString,RideMetric*> &deps) { // not a run if (!item->isRun) { setValue(RideFile::NIL); setCount(0); return; } assert(deps.contains("VDOT")); VDOT *vdot = dynamic_cast<VDOT*>(deps.value("VDOT")); assert(vdot); // TPace corresponds to 90%vVDOT if (vdot->value() > 0) { tPace = 1000.0/VDOTCalculator::vVdot(vdot->value())/0.9; } else { tPace = 0.0; } setValue(tPace); setCount(1); } bool isRelevantForRide(const RideItem *ride) const { return ride->isRun; } MetricClass classification() const { return Undefined; } MetricValidity validity() const { return Unknown; } RideMetric *clone() const { return new TPace(*this); } }; static bool added() { RideMetricFactory::instance().addMetric(VDOT()); QVector<QString> deps; deps.append("VDOT"); RideMetricFactory::instance().addMetric(TPace(), &deps); return true; } static bool added_ = added();
{ "pile_set_name": "Github" }
# USER ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **INTEGER_64** | | [optional] [default to null] **username** | [**STRING_32**](STRING_32.md) | | [optional] [default to null] **first_name** | [**STRING_32**](STRING_32.md) | | [optional] [default to null] **last_name** | [**STRING_32**](STRING_32.md) | | [optional] [default to null] **email** | [**STRING_32**](STRING_32.md) | | [optional] [default to null] **password** | [**STRING_32**](STRING_32.md) | | [optional] [default to null] **phone** | [**STRING_32**](STRING_32.md) | | [optional] [default to null] **user_status** | **INTEGER_32** | User Status | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
{ "pile_set_name": "Github" }
package s import ( . "github.com/alecthomas/chroma" // nolint "github.com/alecthomas/chroma/lexers/internal" ) // Sas lexer. var Sas = internal.Register(MustNewLexer( &Config{ Name: "SAS", Aliases: []string{"sas"}, Filenames: []string{"*.SAS", "*.sas"}, MimeTypes: []string{"text/x-sas", "text/sas", "application/x-sas"}, CaseInsensitive: true, }, Rules{ "root": { Include("comments"), Include("proc-data"), Include("cards-datalines"), Include("logs"), Include("general"), {`.`, Text, nil}, {`\\\n`, Text, nil}, {`\n`, Text, nil}, }, "comments": { {`^\s*\*.*?;`, Comment, nil}, {`/\*.*?\*/`, Comment, nil}, {`^\s*\*(.|\n)*?;`, CommentMultiline, nil}, {`/[*](.|\n)*?[*]/`, CommentMultiline, nil}, }, "proc-data": { {`(^|;)\s*(proc \w+|data|run|quit)[\s;]`, KeywordReserved, nil}, }, "cards-datalines": { {`^\s*(datalines|cards)\s*;\s*$`, Keyword, Push("data")}, }, "data": { {`(.|\n)*^\s*;\s*$`, Other, Pop(1)}, }, "logs": { {`\n?^\s*%?put `, Keyword, Push("log-messages")}, }, "log-messages": { {`NOTE(:|-).*`, Generic, Pop(1)}, {`WARNING(:|-).*`, GenericEmph, Pop(1)}, {`ERROR(:|-).*`, GenericError, Pop(1)}, Include("general"), }, "general": { Include("keywords"), Include("vars-strings"), Include("special"), Include("numbers"), }, "keywords": { {Words(`\b`, `\b`, `abort`, `array`, `attrib`, `by`, `call`, `cards`, `cards4`, `catname`, `continue`, `datalines`, `datalines4`, `delete`, `delim`, `delimiter`, `display`, `dm`, `drop`, `endsas`, `error`, `file`, `filename`, `footnote`, `format`, `goto`, `in`, `infile`, `informat`, `input`, `keep`, `label`, `leave`, `length`, `libname`, `link`, `list`, `lostcard`, `merge`, `missing`, `modify`, `options`, `output`, `out`, `page`, `put`, `redirect`, `remove`, `rename`, `replace`, `retain`, `return`, `select`, `set`, `skip`, `startsas`, `stop`, `title`, `update`, `waitsas`, `where`, `window`, `x`, `systask`), Keyword, nil}, {Words(`\b`, `\b`, `add`, `and`, `alter`, `as`, `cascade`, `check`, `create`, `delete`, `describe`, `distinct`, `drop`, `foreign`, `from`, `group`, `having`, `index`, `insert`, `into`, `in`, `key`, `like`, `message`, `modify`, `msgtype`, `not`, `null`, `on`, `or`, `order`, `primary`, `references`, `reset`, `restrict`, `select`, `set`, `table`, `unique`, `update`, `validate`, `view`, `where`), Keyword, nil}, {Words(`\b`, `\b`, `do`, `if`, `then`, `else`, `end`, `until`, `while`), Keyword, nil}, {Words(`%`, `\b`, `bquote`, `nrbquote`, `cmpres`, `qcmpres`, `compstor`, `datatyp`, `display`, `do`, `else`, `end`, `eval`, `global`, `goto`, `if`, `index`, `input`, `keydef`, `label`, `left`, `length`, `let`, `local`, `lowcase`, `macro`, `mend`, `nrquote`, `nrstr`, `put`, `qleft`, `qlowcase`, `qscan`, `qsubstr`, `qsysfunc`, `qtrim`, `quote`, `qupcase`, `scan`, `str`, `substr`, `superq`, `syscall`, `sysevalf`, `sysexec`, `sysfunc`, `sysget`, `syslput`, `sysprod`, `sysrc`, `sysrput`, `then`, `to`, `trim`, `unquote`, `until`, `upcase`, `verify`, `while`, `window`), NameBuiltin, nil}, {Words(`\b`, `\(`, `abs`, `addr`, `airy`, `arcos`, `arsin`, `atan`, `attrc`, `attrn`, `band`, `betainv`, `blshift`, `bnot`, `bor`, `brshift`, `bxor`, `byte`, `cdf`, `ceil`, `cexist`, `cinv`, `close`, `cnonct`, `collate`, `compbl`, `compound`, `compress`, `cos`, `cosh`, `css`, `curobs`, `cv`, `daccdb`, `daccdbsl`, `daccsl`, `daccsyd`, `dacctab`, `dairy`, `date`, `datejul`, `datepart`, `datetime`, `day`, `dclose`, `depdb`, `depdbsl`, `depsl`, `depsyd`, `deptab`, `dequote`, `dhms`, `dif`, `digamma`, `dim`, `dinfo`, `dnum`, `dopen`, `doptname`, `doptnum`, `dread`, `dropnote`, `dsname`, `erf`, `erfc`, `exist`, `exp`, `fappend`, `fclose`, `fcol`, `fdelete`, `fetch`, `fetchobs`, `fexist`, `fget`, `fileexist`, `filename`, `fileref`, `finfo`, `finv`, `fipname`, `fipnamel`, `fipstate`, `floor`, `fnonct`, `fnote`, `fopen`, `foptname`, `foptnum`, `fpoint`, `fpos`, `fput`, `fread`, `frewind`, `frlen`, `fsep`, `fuzz`, `fwrite`, `gaminv`, `gamma`, `getoption`, `getvarc`, `getvarn`, `hbound`, `hms`, `hosthelp`, `hour`, `ibessel`, `index`, `indexc`, `indexw`, `input`, `inputc`, `inputn`, `int`, `intck`, `intnx`, `intrr`, `irr`, `jbessel`, `juldate`, `kurtosis`, `lag`, `lbound`, `left`, `length`, `lgamma`, `libname`, `libref`, `log`, `log10`, `log2`, `logpdf`, `logpmf`, `logsdf`, `lowcase`, `max`, `mdy`, `mean`, `min`, `minute`, `mod`, `month`, `mopen`, `mort`, `n`, `netpv`, `nmiss`, `normal`, `note`, `npv`, `open`, `ordinal`, `pathname`, `pdf`, `peek`, `peekc`, `pmf`, `point`, `poisson`, `poke`, `probbeta`, `probbnml`, `probchi`, `probf`, `probgam`, `probhypr`, `probit`, `probnegb`, `probnorm`, `probt`, `put`, `putc`, `putn`, `qtr`, `quote`, `ranbin`, `rancau`, `ranexp`, `rangam`, `range`, `rank`, `rannor`, `ranpoi`, `rantbl`, `rantri`, `ranuni`, `repeat`, `resolve`, `reverse`, `rewind`, `right`, `round`, `saving`, `scan`, `sdf`, `second`, `sign`, `sin`, `sinh`, `skewness`, `soundex`, `spedis`, `sqrt`, `std`, `stderr`, `stfips`, `stname`, `stnamel`, `substr`, `sum`, `symget`, `sysget`, `sysmsg`, `sysprod`, `sysrc`, `system`, `tan`, `tanh`, `time`, `timepart`, `tinv`, `tnonct`, `today`, `translate`, `tranwrd`, `trigamma`, `trim`, `trimn`, `trunc`, `uniform`, `upcase`, `uss`, `var`, `varfmt`, `varinfmt`, `varlabel`, `varlen`, `varname`, `varnum`, `varray`, `varrayx`, `vartype`, `verify`, `vformat`, `vformatd`, `vformatdx`, `vformatn`, `vformatnx`, `vformatw`, `vformatwx`, `vformatx`, `vinarray`, `vinarrayx`, `vinformat`, `vinformatd`, `vinformatdx`, `vinformatn`, `vinformatnx`, `vinformatw`, `vinformatwx`, `vinformatx`, `vlabel`, `vlabelx`, `vlength`, `vlengthx`, `vname`, `vnamex`, `vtype`, `vtypex`, `weekday`, `year`, `yyq`, `zipfips`, `zipname`, `zipnamel`, `zipstate`), NameBuiltin, nil}, }, "vars-strings": { {`&[a-z_]\w{0,31}\.?`, NameVariable, nil}, {`%[a-z_]\w{0,31}`, NameFunction, nil}, {`\'`, LiteralString, Push("string_squote")}, {`"`, LiteralString, Push("string_dquote")}, }, "string_squote": { {`'`, LiteralString, Pop(1)}, {`\\\\|\\"|\\\n`, LiteralStringEscape, nil}, {`[^$\'\\]+`, LiteralString, nil}, {`[$\'\\]`, LiteralString, nil}, }, "string_dquote": { {`"`, LiteralString, Pop(1)}, {`\\\\|\\"|\\\n`, LiteralStringEscape, nil}, {`&`, NameVariable, Push("validvar")}, {`[^$&"\\]+`, LiteralString, nil}, {`[$"\\]`, LiteralString, nil}, }, "validvar": { {`[a-z_]\w{0,31}\.?`, NameVariable, Pop(1)}, }, "numbers": { {`\b[+-]?([0-9]+(\.[0-9]+)?|\.[0-9]+|\.)(E[+-]?[0-9]+)?i?\b`, LiteralNumber, nil}, }, "special": { {`(null|missing|_all_|_automatic_|_character_|_n_|_infile_|_name_|_null_|_numeric_|_user_|_webout_)`, KeywordConstant, nil}, }, }, ))
{ "pile_set_name": "Github" }
// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package lzma supports the decoding and encoding of LZMA streams. // Reader and Writer support the classic LZMA format. Reader2 and // Writer2 support the decoding and encoding of LZMA2 streams. // // The package is written completely in Go and doesn't rely on any external // library. package lzma import ( "errors" "io" ) // ReaderConfig stores the parameters for the reader of the classic LZMA // format. type ReaderConfig struct { DictCap int } // fill converts the zero values of the configuration to the default values. func (c *ReaderConfig) fill() { if c.DictCap == 0 { c.DictCap = 8 * 1024 * 1024 } } // Verify checks the reader configuration for errors. Zero values will // be replaced by default values. func (c *ReaderConfig) Verify() error { c.fill() if !(MinDictCap <= c.DictCap && int64(c.DictCap) <= MaxDictCap) { return errors.New("lzma: dictionary capacity is out of range") } return nil } // Reader provides a reader for LZMA files or streams. type Reader struct { lzma io.Reader h header d *decoder } // NewReader creates a new reader for an LZMA stream using the classic // format. NewReader reads and checks the header of the LZMA stream. func NewReader(lzma io.Reader) (r *Reader, err error) { return ReaderConfig{}.NewReader(lzma) } // NewReader creates a new reader for an LZMA stream in the classic // format. The function reads and verifies the the header of the LZMA // stream. func (c ReaderConfig) NewReader(lzma io.Reader) (r *Reader, err error) { if err = c.Verify(); err != nil { return nil, err } data := make([]byte, HeaderLen) if _, err := io.ReadFull(lzma, data); err != nil { if err == io.EOF { return nil, errors.New("lzma: unexpected EOF") } return nil, err } r = &Reader{lzma: lzma} if err = r.h.unmarshalBinary(data); err != nil { return nil, err } if r.h.dictCap < MinDictCap { return nil, errors.New("lzma: dictionary capacity too small") } dictCap := r.h.dictCap if c.DictCap > dictCap { dictCap = c.DictCap } state := newState(r.h.properties) dict, err := newDecoderDict(dictCap) if err != nil { return nil, err } r.d, err = newDecoder(ByteReader(lzma), state, dict, r.h.size) if err != nil { return nil, err } return r, nil } // EOSMarker indicates that an EOS marker has been encountered. func (r *Reader) EOSMarker() bool { return r.d.eosMarker } // Read returns uncompressed data. func (r *Reader) Read(p []byte) (n int, err error) { return r.d.Read(p) }
{ "pile_set_name": "Github" }
// Download the Node helper library from www.twilio.com/docs/libraries/node#installation // These identifiers are your accountSid and authToken from // https://www.twilio.com/console const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const authToken = 'your_auth_token'; const client = require('twilio')(accountSid, authToken); const credentialOpts = { apiKey: 'gcm_api_key', friendlyName: 'MyGCMCredential', type: 'gcm', }; client.notify.credentials .create(credentialOpts) .then(credential => console.log(credential.sid)) .catch(error => console.log(error)) .done();
{ "pile_set_name": "Github" }
/* * Copyright (c) 2015-2017, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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. */ #ifndef __NS_TIMER_STUB_H__ #define __NS_TIMER_STUB_H__ #ifdef __cplusplus extern "C" { #endif typedef struct { int8_t int8_value; void (*cb)(int8_t, uint16_t); } ns_timer_stub_def; extern ns_timer_stub_def ns_timer_stub; #ifdef __cplusplus } #endif #endif // __NS_TIMER_STUB_H__
{ "pile_set_name": "Github" }
<?php /** * Support * * @package GetSimple * @subpackage Support */ # Setup inclusions $load['plugin'] = true; include('inc/common.php'); login_cookie_check(); exec_action('load-support'); $pagetitle = i18n_r('SUPPORT'); get_template('header'); ?> <?php include('template/include-nav.php'); ?> <div class="bodycontent clearfix"> <div id="maincontent"> <div class="main"> <h3 class="floated"><?php i18n('GETTING_STARTED');?></h3> <div class="edit-nav clearfix" > <?php exec_action(get_filename_id().'-edit-nav'); ?> </div> <?php exec_action(get_filename_id().'-body'); ?> <ul> <li><a href="http://get-simple.info/docs/" target="_blank" ><?php i18n('SIDE_DOCUMENTATION'); ?></a></li> <li><a href="http://get-simple.info/forum/" target="_blank" ><?php i18n('SUPPORT_FORUM'); ?></a></li> <li><a href="http://get-simple.info/extend/" target="_blank" ><?php echo str_replace(array('<em>','</em>'), '', i18n_r('GET_PLUGINS_LINK')); ?></a></li> <li><a href="share.php?term=<?php i18n('SHARE'); ?>" rel="fancybox" ><?php i18n('SHARE'); ?> GetSimple</a></li> <li><a href="https://github.com/GetSimpleCMS" target="_blank">Github SVN</a></li> </ul> <p><?php i18n('WELCOME_MSG'); ?> <?php i18n('WELCOME_P'); ?></p> <ul> <li><a href="health-check.php"><?php i18n('WEB_HEALTH_CHECK'); ?></a></li> <li><a href="edit.php"><?php i18n('CREATE_NEW_PAGE'); ?></a></li> <li><a href="upload.php"><?php i18n('UPLOADIFY_BUTTON'); ?></a></li> <li><a href="settings.php"><?php i18n('GENERAL_SETTINGS'); ?></a></li> <li><a href="theme.php"><?php i18n('CHOOSE_THEME'); ?></a></li> <?php exec_action('welcome-link'); // @hook welcome-link support welcome list links output ?> <?php exec_action('welcome-doc-link'); // @hook welcome-doc-link support welcome list links output?> </ul> <h3><?php i18n('SUPPORT');?></h3> <ul> <li><a href="log.php?log=failedlogins.log"><?php i18n('VIEW_FAILED_LOGIN');?></a></li> <li><a href="plugins.php"><?php i18n('PLUGINS_MANAGEMENT');?></a></li> <li><a href="backups.php"><?php i18n('PAGE_BACKUPS');?></a></li> <li><a href="archive.php"><?php i18n('WEBSITE_ARCHIVES');?></a></li> <li><a href="theme.php"><?php i18n('THEME_MANAGEMENT');?></a></li> <li><a href="sitemap.php"><?php i18n('VIEW_SITEMAP');?></a></li> <br/> <?php exec_action('support-extras'); // @hook support-extras support links list html ?> </ul> </div> </div> <div id="sidebar" > <?php include('template/sidebar-support.php'); ?> </div> </div> <?php get_template('footer'); ?>
{ "pile_set_name": "Github" }
/* * Copyright (c) 2009 - 2018 Deutsches Elektronen-Synchroton, * Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * 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 Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program (see the file COPYING.LIB for more * details); if not, write to the Free Software Foundation, Inc., * 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.dcache.nfs; import java.net.Inet4Address; import java.net.InetAddress; import java.net.Inet6Address; import java.net.UnknownHostException; import java.util.Objects; import java.util.function.Predicate; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.net.InetAddresses.forString; import static com.google.common.net.InetAddresses.isInetAddress; import static com.google.common.primitives.Ints.fromByteArray; import static com.google.common.primitives.Longs.fromBytes; public abstract class InetAddressMatcher implements Predicate<InetAddress> { private final String pattern; /* disable subclassing */ protected InetAddressMatcher(String pattern) { this.pattern = pattern; } public boolean match(InetAddress addr) { return test(addr); } public String getPattern() { return pattern; } @Override public int hashCode() { int hash = 5; hash = 59 * hash + Objects.hashCode(this.pattern); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final InetAddressMatcher other = (InetAddressMatcher) obj; if (!Objects.equals(this.pattern, other.pattern)) { return false; } return true; } public static InetAddressMatcher forPattern(String s) throws UnknownHostException { String hostAndMask[] = s.split("/"); checkArgument(hostAndMask.length < 3, "Invalid host specification: " + s); if (!isInetAddress(hostAndMask[0])) { checkArgument (hostAndMask.length == 1, "Invalid host specification (hostname with mask): " + s); if (s.indexOf('*') != -1 || s.indexOf('?') != -1) { return new RegexpNameMatcher(toRegExp(s)); } else { return new HostNameMatcher(s); } } InetAddress net = forString(hostAndMask[0]); if (hostAndMask.length == 2) { /* * if subnet mask defined */ return new IpAddressMatcher(s, net, Integer.parseInt(hostAndMask[1])); } return new IpAddressMatcher(s, net); } public static class IpAddressMatcher extends InetAddressMatcher { private static final int IPv4_FULL_MASK = 32; private static final int IPv6_FULL_MASK = 128; private static final int IPv6_HALF_MASK = 64; private final byte[] netBytes; private final int mask; private static int fullMaskOf(InetAddress address) { if (address instanceof Inet4Address) { return IPv4_FULL_MASK; } if (address instanceof Inet6Address) { return IPv6_FULL_MASK; } throw new IllegalArgumentException("Unsupported Inet type: " + address.getClass().getName()); } public IpAddressMatcher(String pattern, InetAddress subnet) { this(pattern, subnet, fullMaskOf(subnet)); } public IpAddressMatcher(String pattern, InetAddress subnet, int mask) { super(pattern); this.netBytes = subnet.getAddress(); this.mask = mask; checkArgument(mask >= 0, "Netmask should be positive"); if (this.netBytes.length == 4) { checkArgument(mask <= IPv4_FULL_MASK, "Netmask for ipv4 can't be bigger than" + IPv4_FULL_MASK); } else { checkArgument(mask <= IPv6_FULL_MASK, "Netmask for ipv6 can't be bigger than" + IPv6_FULL_MASK); } } @Override public boolean test(InetAddress ip) { byte[] ipBytes = ip.getAddress(); if (ipBytes.length != netBytes.length) { return false; } if (ipBytes.length == 4) { /* * IPv4 can be represented as a 32 bit ints. */ int ipAsInt = fromByteArray(ipBytes); int netAsBytes = fromByteArray(netBytes); return (ipAsInt ^ netAsBytes) >> (IPv4_FULL_MASK - mask) == 0; } /** * IPv6 can be represented as two 64 bit longs. * * We evaluate second long only if bitmask bigger than 64. The * second longs are created only if needed as it turned to be the * slowest part. */ long ipAsLong0 = fromBytes(ipBytes[0], ipBytes[1], ipBytes[2], ipBytes[3], ipBytes[4], ipBytes[5], ipBytes[6], ipBytes[7]); long netAsLong0 = fromBytes(netBytes[0], netBytes[1], netBytes[2], netBytes[3], netBytes[4], netBytes[5], netBytes[6], netBytes[7]); if (mask > 64) { long ipAsLong1 = fromBytes(ipBytes[8], ipBytes[9], ipBytes[10], ipBytes[11], ipBytes[12], ipBytes[13], ipBytes[14], ipBytes[15]); long netAsLong1 = fromBytes(netBytes[8], netBytes[9], netBytes[10], netBytes[11], netBytes[12], netBytes[13], netBytes[14], netBytes[15]); return (ipAsLong0 == netAsLong0) & (ipAsLong1 ^ netAsLong1) >> (IPv6_FULL_MASK - mask) == 0; } return (ipAsLong0 ^ netAsLong0) >> (IPv6_HALF_MASK - mask) == 0; } } private static String toRegExp(String s) { return s.replace(".", "\\.").replace("?", ".").replace("*", ".*"); } public static class RegexpNameMatcher extends InetAddressMatcher { private final Pattern regexpPattern; public RegexpNameMatcher(String pattern) { super(pattern); this.regexpPattern = Pattern.compile(pattern); } @Override public boolean test(InetAddress ip) { return regexpPattern.matcher(ip.getHostName()).matches(); } } public static class HostNameMatcher extends InetAddressMatcher { HostNameMatcher(String hostname) throws UnknownHostException { super(hostname); } @Override public boolean test(InetAddress ip) { try { // jvm caches DNS results. We are fine to query on each request InetAddress[] addrs = InetAddress.getAllByName(getPattern()); for(InetAddress addr: addrs) { if (addr.equals(ip)) { return true; } } }catch (UnknownHostException e) { return false; } return false; } } }
{ "pile_set_name": "Github" }
#define NULL_CHARACTER '\0' /* use iso_c_binding, only : c_int, c_char interface subroutine c_pool_hash(hash, key) bind(c) use iso_c_binding, only : c_int, c_char integer (c_int), intent(inout) :: hash character (c_char), dimension(*), intent(in) :: key end subroutine c_pool_hash end interface */ void c_pool_hash(int* hash, char* key) { int i; unsigned int whash; whash = 0; for (i=0; key[i] != NULL_CHARACTER; i++) { whash += (unsigned int)key[i]; } *hash = (int)(whash & 0x7fffffff); }
{ "pile_set_name": "Github" }
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="?attr/colorControlNormal"> <path android:fillColor="@android:color/white" android:pathData="M6,2v6h0.01L6,8.01 10,12l-4,4 0.01,0.01L6,16.01L6,22h12v-5.99h-0.01L18,16l-4,-4 4,-3.99 -0.01,-0.01L18,8L18,2L6,2zM16,16.5L16,20L8,20v-3.5l4,-4 4,4zM12,11.5l-4,-4L8,4h8v3.5l-4,4z"/> </vector>
{ "pile_set_name": "Github" }
"Pssssst. Over here Look in the file called Notes...."
{ "pile_set_name": "Github" }
/* Copyright 2016 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. */ package integer // IntMax returns the maximum of the params func IntMax(a, b int) int { if b > a { return b } return a } // IntMin returns the minimum of the params func IntMin(a, b int) int { if b < a { return b } return a } // Int32Max returns the maximum of the params func Int32Max(a, b int32) int32 { if b > a { return b } return a } // Int32Min returns the minimum of the params func Int32Min(a, b int32) int32 { if b < a { return b } return a } // Int64Max returns the maximum of the params func Int64Max(a, b int64) int64 { if b > a { return b } return a } // Int64Min returns the minimum of the params func Int64Min(a, b int64) int64 { if b < a { return b } return a } // RoundToInt32 rounds floats into integer numbers. func RoundToInt32(a float64) int32 { if a < 0 { return int32(a - 0.5) } return int32(a + 0.5) }
{ "pile_set_name": "Github" }
from demo.with_wsgi.ops.flask import flask_app, PRE_FLASK from demo.with_wsgi.ops.tornado import tornado_app, PRE_TORNADO from falsy.falsy import FALSY f = FALSY(static_dir='demo/with_wsgi/static') \ .swagger('demo/with_wsgi/spec.yml', ui=True, ui_language='zh-cn', theme='normal') \ .wsgi(flask_app, PRE_FLASK) \ .wsgi(tornado_app, PRE_TORNADO) api = f.api
{ "pile_set_name": "Github" }
import typescript from "rollup-plugin-typescript" import resolve from "rollup-plugin-node-resolve" import cleanup from "rollup-plugin-cleanup" export default { input: "./slinky/Slinky.ts", output:{ file: '../Slinky.sketchplugin/Contents/Sketch/Slinky.js', format: "es", sourcemap: false }, plugins: [ typescript(), resolve(), cleanup() ] }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <Filter Include="源文件"> <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> </Filter> <Filter Include="头文件"> <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> </Filter> <Filter Include="资源文件"> <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions> </Filter> </ItemGroup> <ItemGroup> <None Include="ReadMe.txt" /> </ItemGroup> <ItemGroup> <ClCompile Include="simplest_ffmpeg_video_filter.cpp"> <Filter>源文件</Filter> </ClCompile> </ItemGroup> </Project>
{ "pile_set_name": "Github" }
#ifndef __OSD_SDL_H__ #define __OSD_SDL_H__ typedef SDL_Joystick OSDEP_Joystick; typedef SDL_Color OSDEP_Color; typedef SDL_Surface OSDEP_Surface; typedef struct _OSDEP_VMode { int w; int h; } OSDEP_VMode; extern uint8_t OSDEP_key[2048]; // the following functions all need to be implemented in order for a port to // function correctly void OSDEP_Init(void); void OSDEP_Quit(void); void OSDEP_keyInit(void); void OSDEP_WarpMouse(int x, int y); void OSDEP_Flip(OSDEP_Surface *s); uint32_t OSDEP_GetTicks(void); void OSDEP_UpdateRect(SDL_Surface *screen, Sint32 x, Sint32 y, Sint32 w, Sint32 h); int OSDEP_IsFullScreen(void); OSDEP_VMode ** OSDEP_ListModes(void); void OSDEP_SetCaption(char *title, char *icon); OSDEP_Surface * OSDEP_SetVideoMode(int width, int height, int bpp, char fs); int OSDEP_SetPalette(OSDEP_Surface *surface, OSDEP_Color *colors, int firstcolor, int ncolors); int32_t OSDEP_NumJoysticks(void); OSDEP_Joystick *OSDEP_JoystickOpen(int n); void OSDEP_JoystickClose(OSDEP_Joystick *joy); int OSDEP_JoystickNumButtons(int n); int OSDEP_JoystickNumHats(int n); int OSDEP_JoystickNumAxes(int n); uint8_t OSDEP_JoystickGetButton(OSDEP_Joystick *joystick, int button); int16_t OSDEP_JoystickGetAxis(OSDEP_Joystick *joystick, int axis); char * OSDEP_JoystickName(int n); #endif
{ "pile_set_name": "Github" }
function rk4(f, t0, y0, t1, n) { h = (t1-t0)/(n-1) a = J(n, 2, 0) a[1, 1] = t = t0 a[1, 2] = y = y0 for (i=2; i<=n; i++) { k1 = h*(*f)(t, y) k2 = h*(*f)(t+0.5*h, y+0.5*k1) k3 = h*(*f)(t+0.5*h, y+0.5*k2) k4 = h*(*f)(t+h, y+k3) t = t+h y = y+(k1+2*k2+2*k3+k4)/6 a[i, 1] = t a[i, 2] = y } return(a) } function f(t, y) { return(t*sqrt(y)) } a = rk4(&f(), 0, 1, 10, 101) t = a[., 1] a = a, a[., 2]:-(t:^2:+4):^2:/16 a[range(1,101,10), .] 1 2 3 +----------------------------------------------+ 1 | 0 1 0 | 2 | 1 1.562499854 -1.45722e-07 | 3 | 2 3.999999081 -9.19479e-07 | 4 | 3 10.56249709 -2.90956e-06 | 5 | 4 24.99999377 -6.23491e-06 | 6 | 5 52.56248918 -.0000108197 | 7 | 6 99.99998341 -.0000165946 | 8 | 7 175.5624765 -.0000235177 | 9 | 8 288.9999684 -.0000315652 | 10 | 9 451.5624593 -.0000407232 | 11 | 10 675.999949 -.0000509833 | +----------------------------------------------+
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2017 The Android Open Source Project 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. --> <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="36dp" android:height="36dp" android:viewportWidth="25" android:viewportHeight="25"> <path android:fillColor="#FFFFFFFF" android:pathData="M19,7h-8v6h8L19,7zM21,3L3,3c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,1.98 2,1.98h18c1.1,0 2,-0.88 2,-1.98L23,5c0,-1.1 -0.9,-2 -2,-2zM21,19.01L3,19.01L3,4.98h18v14.03z"/> </vector>
{ "pile_set_name": "Github" }
//render Video srource $.extend(Video.prototype, { renderSource: function() { var setSource = this.params.setSource; if (!setSource) { this._sourceEmpty(); return; } var canType = this.getCanPlayType(); if (!canType) { this._contSuppotVideo(); return; } var src = setSource(canType); this._renderVideo(src); this._videoControl() }, //when source is empty _sourceEmpty: function() { }, //when browse not support video _contSuppotVideo: function() { }, //render video element and set $video oubject _renderVideo: function(src) { var params = this.params; var virtualFullScreen = params.virtualFullScreen; var video = $(('<div class="yvp_video"><video width="100%" height="100%" _preload="none" x-webkit-airplay="true" src="${videosrc}" ' + (virtualFullScreen? 'webkit-playsinline':'') + '></video></div>').replace(/\${.*\}/i, src)); this.$el.append(video); this.$video = video.find('video'); }, _videoControl: function() { var params = this.params; var __ = this; if (params.autoPlay) { this.$video[0].play(); } //set is play value this.$video.on('pause', function() { __.isPlay = false; }).on('play', function() { __.isPlay = true; }).on('ended', function() { __.isPlay = false; }) this.$video.on('error', function() { __._deadlyError(); if ($.isFunction(params.error)) { params.error(); } }).on('loadedmetadata', function() { if ($.isFunction(params.success)) { params.success(__.$video[0], __.$el, __); } }); this.controlsInit(); } });
{ "pile_set_name": "Github" }
From [email protected] Thu Sep 26 11:04:32 2002 Return-Path: <[email protected]> Delivered-To: [email protected] Received: from localhost (jalapeno [127.0.0.1]) by jmason.org (Postfix) with ESMTP id 90BF116F03 for <jm@localhost>; Thu, 26 Sep 2002 11:04:30 +0100 (IST) Received: from jalapeno [127.0.0.1] by localhost with IMAP (fetchmail-5.9.0) for jm@localhost (single-drop); Thu, 26 Sep 2002 11:04:30 +0100 (IST) Received: from xent.com ([64.161.22.236]) by dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g8PLFFC14432 for <[email protected]>; Wed, 25 Sep 2002 22:15:15 +0100 Received: from lair.xent.com (localhost [127.0.0.1]) by xent.com (Postfix) with ESMTP id CB1062940E9; Wed, 25 Sep 2002 14:11:09 -0700 (PDT) Delivered-To: [email protected] Received: from cats.ucsc.edu (cats-mx2.ucsc.edu [128.114.129.35]) by xent.com (Postfix) with ESMTP id BD72429409A for <[email protected]>; Wed, 25 Sep 2002 14:10:49 -0700 (PDT) Received: from Tycho (dhcp-55-196.cse.ucsc.edu [128.114.55.196]) by cats.ucsc.edu (8.10.1/8.10.1) with SMTP id g8PHxFT27510 for <[email protected]>; Wed, 25 Sep 2002 10:59:15 -0700 (PDT) From: "Jim Whitehead" <[email protected]> To: <[email protected]> Subject: RE: CO2 and climate (was RE: Goodbye Global Warming) Message-Id: <[email protected]> MIME-Version: 1.0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit X-Priority: 3 (Normal) X-Msmail-Priority: Normal X-Mailer: Microsoft Outlook IMO, Build 9.0.2416 (9.0.2911.0) In-Reply-To: <1032885762.24435.78.camel@avalon> Importance: Normal X-Mimeole: Produced By Microsoft MimeOLE V5.50.4133.2400 X-Ucsc-Cats-Mailscanner: Found to be clean Sender: [email protected] Errors-To: [email protected] X-Beenthere: [email protected] X-Mailman-Version: 2.0.11 Precedence: bulk List-Help: <mailto:[email protected]?subject=help> List-Post: <mailto:[email protected]> List-Subscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:[email protected]?subject=subscribe> List-Id: Friends of Rohit Khare <fork.xent.com> List-Unsubscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:[email protected]?subject=unsubscribe> List-Archive: <http://xent.com/pipermail/fork/> Date: Wed, 25 Sep 2002 10:56:41 -0700 OK, let's bring some data into the discussion: http://www.grida.no/climate/vital/02.htm (A graph, derived from Vostok ice core samples, of CO2 and temperature fluctuations over the past 400k years). > Recent high-resolution studies of historical CO2 concentrations and > temperatures over hundreds of thousands of years have shown a modest > correlation between the two. In a number of cases, CO2 level increases > are not in phase with temperature increases and actually trail the > increase in temperature by a short time i.e. increases in temperature > preceded increases in CO2 concentrations. The more studies that are done > of the geological record, the more it seems that CO2 concentrations are > correlated with temperature increases, but are not significantly > causative. Based on the Vostok data, you are right, there is a very strong correlation between temperature and CO2 concentrations, but it doesn't always appear to be causal. > With respect to absolute CO2 concentrations, it is also important to > point out that our best data to date suggests that they follow a fairly > regular cycle with a period of about 100,000 years. Also correct -- the peak of each cycle is at about 290-300 ppm CO2. > As it > happens, current CO2 concentrations are within 10% of other previous > cyclical concentration peaks for which we have good data. Not correct. Mauna Loa data <http://www.grida.no/climate/vital/06.htm> and <http://cdiac.ornl.gov/ftp/ndp001/maunaloa.co2> show that the current CO2 concentrations are at 370ppm, 18% *greater* than the *highest* recorded value from the past 400k years. Furthermore, CO2 concentrations are growing at 15ppm every 10 years, much faster than any recorded increase in the Vostok data (though perhaps the Vostok data isn't capable of such fine resolution). > In other words, we may be adding to the CO2 levels, No, we are *definitely* adding to CO2 levels. Look at the following chart: http://www.grida.no/climate/vital/07.htm (Shows CO2 concentrations since 1870, the "historical record"). Not only is the CO2 increase over 130 years unprecedented in the Vostok record, it is clear that the rate of change is *increasing*, not decreasing. There is no other compelling explanation for this increase, except for anthropogenic input. You're really out on the fringe if you're debating this -- even global warming skeptics generally concede this point. > but it looks a lot like we > would be building a molehill on top of a mountain in the historical > record. At the very least, there is nothing anomalous about current CO2 > concentrations. Wrong again. Current CO2 levels are currently unprecedented over the past 400k years, unless there is some mechanism that allows CO2 levels to quickly spike, and then return back to "normal" background levels (and hence the spike might not show up in the ice cores). Still, by around 2075-2100 we will have reached 500 ppm CO2, a level that even you would have a hard time arguing away. > Also, CO2 levels interact with the biosphere in a manner that ultimately > affects temperature. Again, the interaction is not entirely > predictable, but this is believed to be one of the regulating negative > feedback systems mentioned above. Yes, clouds and oceans are a big unknown. Still, we know ocean water has a finite capacity to store CO2, and if the world temperature doesn't increase, but we all have Seattle-like weather all the time, the effects would be enormous. > Last, as greenhouse gases go, CO2 isn't particularly potent, although it > makes up for it in volume in some cases. Gases such as water and > methane have a far greater impact as greenhouse gases on a per molecule > basis. Water vapor may actually be the key greenhouse gas, something > that CO2 only indirectly effects through its interaction with the > biosphere. Correct. Data on relative contributions of greenhouse gasses: http://www.grida.no/climate/vital/05.htm Note that methane concentrations now are *much* higher than pre-industrial levels (many cows farting, and rice paddies outgassing), and methane is also a contributor in the formation of atmospheric water vapor. Another clearly anthropogenic increase in a greenhouse gas. I'm in favor of reductions in methane levels as well. Data on water vapor here: http://www.agu.org/sci_soc/mockler.html > CO2 was an easy mark for early environmentalism, but all the recent > studies and data I've seen gives me the impression that it is largely a > passenger on the climate ride rather than the driver. I tend to think that holistic, and techical approaches would work best in reducing global warming. I favor an energy policy that has a mix of solar, wind and nuclear, with all carbon-based combustion using renewable sources of C-H bonds. Aggressive pursuit of carbon sink strategies also makes sense (burying trees deep underground, for example). Approaches that involve reductions in lifestyle to a "sustainable" level are unrealistic -- Americans just won't do it (you'd be surprised at the number of climate change researchers driving SUVs). But, as California showed during last year's energy crisis, shifts in patterns of consumption are possible, and improved efficiency is an easy sell. - Jim
{ "pile_set_name": "Github" }
## The XMLs we expect (order is important) XML|${jetty.home}/etc/optional.xml XML|${jetty.home}/etc/base.xml XML|${jetty.home}/etc/main.xml # The LIBs we expect (order is irrelevant) LIB|${jetty.home}/lib/base.jar LIB|${jetty.home}/lib/main.jar LIB|${jetty.home}/lib/other.jar LIB|${jetty.home}/lib/optional.jar # The Properties we expect (order is irrelevant) PROP|main.prop=value0 PROP|optional.prop=value0 # Files / Directories to create EXISTS|maindir/ EXISTS|start.ini OUTPUT|INFO : copy ..jetty.base./start.d/main.ini into ..jetty.base./start.ini OUTPUT|INFO : optional initialized in ..jetty.base./start.ini OUTPUT|INFO : mkdir ..jetty.base./maindir OUTPUT|INFO : Base directory was modified
{ "pile_set_name": "Github" }
// // YCViewControllerProtocol.h // RenCheRen // // Created by 王隆帅 on 15/12/22. // Copyright © 2015年 王隆帅. All rights reserved. // #import <Foundation/Foundation.h> @protocol YCViewModelProtocol; @protocol YCViewControllerProtocol <NSObject> @optional - (instancetype)initWithViewModel:(id <YCViewModelProtocol>)viewModel; - (void)yc_bindViewModel; - (void)yc_addSubviews; - (void)yc_layoutNavigation; - (void)yc_getNewData; - (void)recoverKeyboard; @end
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (c) 2000-2003,2005 Silicon Graphics, Inc. * All Rights Reserved. */ #include "xfs.h" struct xstats xfsstats; static int counter_val(struct xfsstats __percpu *stats, int idx) { int val = 0, cpu; for_each_possible_cpu(cpu) val += *(((__u32 *)per_cpu_ptr(stats, cpu) + idx)); return val; } int xfs_stats_format(struct xfsstats __percpu *stats, char *buf) { int i, j; int len = 0; uint64_t xs_xstrat_bytes = 0; uint64_t xs_write_bytes = 0; uint64_t xs_read_bytes = 0; static const struct xstats_entry { char *desc; int endpoint; } xstats[] = { { "extent_alloc", xfsstats_offset(xs_abt_lookup) }, { "abt", xfsstats_offset(xs_blk_mapr) }, { "blk_map", xfsstats_offset(xs_bmbt_lookup) }, { "bmbt", xfsstats_offset(xs_dir_lookup) }, { "dir", xfsstats_offset(xs_trans_sync) }, { "trans", xfsstats_offset(xs_ig_attempts) }, { "ig", xfsstats_offset(xs_log_writes) }, { "log", xfsstats_offset(xs_try_logspace)}, { "push_ail", xfsstats_offset(xs_xstrat_quick)}, { "xstrat", xfsstats_offset(xs_write_calls) }, { "rw", xfsstats_offset(xs_attr_get) }, { "attr", xfsstats_offset(xs_iflush_count)}, { "icluster", xfsstats_offset(vn_active) }, { "vnodes", xfsstats_offset(xb_get) }, { "buf", xfsstats_offset(xs_abtb_2) }, { "abtb2", xfsstats_offset(xs_abtc_2) }, { "abtc2", xfsstats_offset(xs_bmbt_2) }, { "bmbt2", xfsstats_offset(xs_ibt_2) }, { "ibt2", xfsstats_offset(xs_fibt_2) }, { "fibt2", xfsstats_offset(xs_rmap_2) }, { "rmapbt", xfsstats_offset(xs_refcbt_2) }, { "refcntbt", xfsstats_offset(xs_qm_dqreclaims)}, /* we print both series of quota information together */ { "qm", xfsstats_offset(xs_xstrat_bytes)}, }; /* Loop over all stats groups */ for (i = j = 0; i < ARRAY_SIZE(xstats); i++) { len += scnprintf(buf + len, PATH_MAX - len, "%s", xstats[i].desc); /* inner loop does each group */ for (; j < xstats[i].endpoint; j++) len += scnprintf(buf + len, PATH_MAX - len, " %u", counter_val(stats, j)); len += scnprintf(buf + len, PATH_MAX - len, "\n"); } /* extra precision counters */ for_each_possible_cpu(i) { xs_xstrat_bytes += per_cpu_ptr(stats, i)->s.xs_xstrat_bytes; xs_write_bytes += per_cpu_ptr(stats, i)->s.xs_write_bytes; xs_read_bytes += per_cpu_ptr(stats, i)->s.xs_read_bytes; } len += scnprintf(buf + len, PATH_MAX-len, "xpc %Lu %Lu %Lu\n", xs_xstrat_bytes, xs_write_bytes, xs_read_bytes); len += scnprintf(buf + len, PATH_MAX-len, "debug %u\n", #if defined(DEBUG) 1); #else 0); #endif return len; } void xfs_stats_clearall(struct xfsstats __percpu *stats) { int c; uint32_t vn_active; xfs_notice(NULL, "Clearing xfsstats"); for_each_possible_cpu(c) { preempt_disable(); /* save vn_active, it's a universal truth! */ vn_active = per_cpu_ptr(stats, c)->s.vn_active; memset(per_cpu_ptr(stats, c), 0, sizeof(*stats)); per_cpu_ptr(stats, c)->s.vn_active = vn_active; preempt_enable(); } } #ifdef CONFIG_PROC_FS /* legacy quota interfaces */ #ifdef CONFIG_XFS_QUOTA #define XFSSTAT_START_XQMSTAT xfsstats_offset(xs_qm_dqreclaims) #define XFSSTAT_END_XQMSTAT xfsstats_offset(xs_qm_dquot) static int xqm_proc_show(struct seq_file *m, void *v) { /* maximum; incore; ratio free to inuse; freelist */ seq_printf(m, "%d\t%d\t%d\t%u\n", 0, counter_val(xfsstats.xs_stats, XFSSTAT_END_XQMSTAT), 0, counter_val(xfsstats.xs_stats, XFSSTAT_END_XQMSTAT + 1)); return 0; } /* legacy quota stats interface no 2 */ static int xqmstat_proc_show(struct seq_file *m, void *v) { int j; seq_printf(m, "qm"); for (j = XFSSTAT_START_XQMSTAT; j < XFSSTAT_END_XQMSTAT; j++) seq_printf(m, " %u", counter_val(xfsstats.xs_stats, j)); seq_putc(m, '\n'); return 0; } #endif /* CONFIG_XFS_QUOTA */ int xfs_init_procfs(void) { if (!proc_mkdir("fs/xfs", NULL)) return -ENOMEM; if (!proc_symlink("fs/xfs/stat", NULL, "/sys/fs/xfs/stats/stats")) goto out; #ifdef CONFIG_XFS_QUOTA if (!proc_create_single("fs/xfs/xqmstat", 0, NULL, xqmstat_proc_show)) goto out; if (!proc_create_single("fs/xfs/xqm", 0, NULL, xqm_proc_show)) goto out; #endif return 0; out: remove_proc_subtree("fs/xfs", NULL); return -ENOMEM; } void xfs_cleanup_procfs(void) { remove_proc_subtree("fs/xfs", NULL); } #endif /* CONFIG_PROC_FS */
{ "pile_set_name": "Github" }
# -*- encoding: utf-8 -*- from pupylib.PupyModule import PupyArgumentParser from pupylib.PupyOutput import MultiPart, Table, Color, Line, TruncateToTerm from pupylib.PupyCompleter import commands_completer usage = 'Show help' parser = PupyArgumentParser(prog='help', description=usage) parser.add_argument('module', nargs='?', help='Show information about command', completer=commands_completer) parser.add_argument('-M', '--modules', action='store_true', help='Show information about all modules') def do(server, handler, config, args): tables = [] if args.module: if handler.commands.has(args.module): command = handler.commands.get(args.module) tables.append(Line( Color('Command:', 'yellow'), Color(args.module+':', 'green'), command.usage or 'No description')) if hasattr(command.parser, 'add_help'): tables.append(command.parser.format_help()) else: parser = command.parser(server, PupyArgumentParser, config) tables.append(parser.parse_args(['--help'])) for module in server.iter_modules(): if module.get_name().lower() == args.module.lower(): if module.__doc__: doc = module.__doc__.strip() else: doc = '' tables.append(Line( Color('Module:', 'yellow'), Color(args.module+':', 'green'), doc.title().split('\n')[0])) if module.arg_parser.add_help: tables.append(module.arg_parser.format_help()) else: tables.append(module.arg_parser.parse_args(['--help'])) clients = server.get_clients(handler.default_filter) if clients: ctable = [] for client in clients: compatible = module.is_compatible_with(client) ctable.append({ 'OK': Color( 'Y' if compatible else 'N', 'green' if compatible else 'grey' ), 'CLIENT': Color( str(client), 'green' if compatible else 'grey' ) }) tables.append( Table(ctable, ['OK', 'CLIENT'], Color('Compatibility', 'yellow'), False)) for command, alias in config.items("aliases"): if command == args.module: tables.append(Line( Color('Alias:', 'yellow'), Color(args.module+':', 'green'), alias)) else: commands = [] for command, description in handler.commands.list(): commands.append({ 'COMMAND': command, 'DESCRIPTION': description }) tables.append(Table(commands, ['COMMAND', 'DESCRIPTION'], Color('COMMANDS', 'yellow'))) if args.modules: modules = sorted(list(server.iter_modules()), key=(lambda x:x.category)) table = [] for mod in modules: compatible = all( mod.is_compatible_with(client) for client in server.get_clients(handler.default_filter)) compatible_some = any( mod.is_compatible_with(client) for client in server.get_clients(handler.default_filter)) if mod.__doc__: doc = mod.__doc__.strip() else: doc = '' category = mod.category name = mod.get_name() brief = doc.title().split('\n')[0] if compatible: pass elif compatible_some: category = Color(category, 'grey') name = Color(name, 'grey') brief = Color(brief, 'grey') else: category = Color(category, 'darkgrey') name = Color(name, 'darkgrey') brief = Color(brief, 'darkgrey') table.append({ 'CATEGORY': category, 'NAME': name, 'HELP': brief }) tables.append(TruncateToTerm(Table( table, ['CATEGORY', 'NAME', 'HELP'], Color('MODULES', 'yellow')))) else: aliased = [] for module, description in server.get_aliased_modules(): aliased.append({ 'MODULE': module, 'DESCRIPTION': description }) if aliased: tables.append(Table(aliased, ['MODULE', 'DESCRIPTION'], Color('ALIASED MODULES', 'yellow'))) aliases = [] for command, alias in config.items("aliases"): aliases.append({ 'ALIAS': command, 'COMMAND': alias }) if aliases: tables.append(Table(aliases, ['ALIAS', 'COMMAND'], Color('ALIASES', 'yellow'))) if not args.modules: tables.append(Line('Use', Color('help -M', 'green'), 'command to show all available modules')) handler.display(MultiPart(tables))
{ "pile_set_name": "Github" }
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; /// Dark theme ThemeData darkTheme() { return ThemeData( textTheme: GoogleFonts.ibmPlexSansTextTheme(ThemeData.dark().textTheme), brightness: Brightness.dark, primarySwatch: Colors.cyan, accentColor: Colors.cyan, cardColor: const Color(0xFF222222), scaffoldBackgroundColor: const Color(0xFF0E0E0E), cardTheme: const CardTheme(shape: RoundedRectangleBorder()), dialogTheme: DialogTheme( elevation: 10, shape: Border.all(color: Colors.white24), backgroundColor: Colors.black87, ), ).copyWith( visualDensity: VisualDensity.adaptivePlatformDensity, ); }
{ "pile_set_name": "Github" }
var Glob = require("../").Glob var pattern = "{./*/*,/*,/usr/local/*}" console.log(pattern) var mg = new Glob(pattern, {mark: true}, function (er, matches) { console.log("matches", matches) }) console.log("after")
{ "pile_set_name": "Github" }
/* ktti.c (c) 1998 Grant R. Guenther <[email protected]> Under the terms of the GNU General Public License. ktti.c is a low-level protocol driver for the KT Technology parallel port adapter. This adapter is used in the "PHd" portable hard-drives. As far as I can tell, this device supports 4-bit mode _only_. */ #define KTTI_VERSION "1.0" #include <linux/module.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/wait.h> #include <asm/io.h> #include "paride.h" #define j44(a,b) (((a>>4)&0x0f)|(b&0xf0)) /* cont = 0 - access the IDE register file cont = 1 - access the IDE command set */ static int cont_map[2] = { 0x10, 0x08 }; static void ktti_write_regr( PIA *pi, int cont, int regr, int val) { int r; r = regr + cont_map[cont]; w0(r); w2(0xb); w2(0xa); w2(3); w2(6); w0(val); w2(3); w0(0); w2(6); w2(0xb); } static int ktti_read_regr( PIA *pi, int cont, int regr ) { int a, b, r; r = regr + cont_map[cont]; w0(r); w2(0xb); w2(0xa); w2(9); w2(0xc); w2(9); a = r1(); w2(0xc); b = r1(); w2(9); w2(0xc); w2(9); return j44(a,b); } static void ktti_read_block( PIA *pi, char * buf, int count ) { int k, a, b; for (k=0;k<count/2;k++) { w0(0x10); w2(0xb); w2(0xa); w2(9); w2(0xc); w2(9); a = r1(); w2(0xc); b = r1(); w2(9); buf[2*k] = j44(a,b); a = r1(); w2(0xc); b = r1(); w2(9); buf[2*k+1] = j44(a,b); } } static void ktti_write_block( PIA *pi, char * buf, int count ) { int k; for (k=0;k<count/2;k++) { w0(0x10); w2(0xb); w2(0xa); w2(3); w2(6); w0(buf[2*k]); w2(3); w0(buf[2*k+1]); w2(6); w2(0xb); } } static void ktti_connect ( PIA *pi ) { pi->saved_r0 = r0(); pi->saved_r2 = r2(); w2(0xb); w2(0xa); w0(0); w2(3); w2(6); } static void ktti_disconnect ( PIA *pi ) { w2(0xb); w2(0xa); w0(0xa0); w2(3); w2(4); w0(pi->saved_r0); w2(pi->saved_r2); } static void ktti_log_adapter( PIA *pi, char * scratch, int verbose ) { printk("%s: ktti %s, KT adapter at 0x%x, delay %d\n", pi->device,KTTI_VERSION,pi->port,pi->delay); } static struct pi_protocol ktti = { .owner = THIS_MODULE, .name = "ktti", .max_mode = 1, .epp_first = 2, .default_delay = 1, .max_units = 1, .write_regr = ktti_write_regr, .read_regr = ktti_read_regr, .write_block = ktti_write_block, .read_block = ktti_read_block, .connect = ktti_connect, .disconnect = ktti_disconnect, .log_adapter = ktti_log_adapter, }; static int __init ktti_init(void) { return paride_register(&ktti); } static void __exit ktti_exit(void) { paride_unregister(&ktti); } MODULE_LICENSE("GPL"); module_init(ktti_init) module_exit(ktti_exit)
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0 /* * ep0.c - DesignWare USB3 DRD Controller Endpoint 0 Handling * * Copyright (C) 2010-2011 Texas Instruments Incorporated - https://www.ti.com * * Authors: Felipe Balbi <[email protected]>, * Sebastian Andrzej Siewior <[email protected]> */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/platform_device.h> #include <linux/pm_runtime.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/list.h> #include <linux/dma-mapping.h> #include <linux/usb/ch9.h> #include <linux/usb/gadget.h> #include <linux/usb/composite.h> #include "core.h" #include "debug.h" #include "gadget.h" #include "io.h" static void __dwc3_ep0_do_control_status(struct dwc3 *dwc, struct dwc3_ep *dep); static void __dwc3_ep0_do_control_data(struct dwc3 *dwc, struct dwc3_ep *dep, struct dwc3_request *req); static void dwc3_ep0_prepare_one_trb(struct dwc3_ep *dep, dma_addr_t buf_dma, u32 len, u32 type, bool chain) { struct dwc3_trb *trb; struct dwc3 *dwc; dwc = dep->dwc; trb = &dwc->ep0_trb[dep->trb_enqueue]; if (chain) dep->trb_enqueue++; trb->bpl = lower_32_bits(buf_dma); trb->bph = upper_32_bits(buf_dma); trb->size = len; trb->ctrl = type; trb->ctrl |= (DWC3_TRB_CTRL_HWO | DWC3_TRB_CTRL_ISP_IMI); if (chain) trb->ctrl |= DWC3_TRB_CTRL_CHN; else trb->ctrl |= (DWC3_TRB_CTRL_IOC | DWC3_TRB_CTRL_LST); trace_dwc3_prepare_trb(dep, trb); } static int dwc3_ep0_start_trans(struct dwc3_ep *dep) { struct dwc3_gadget_ep_cmd_params params; struct dwc3 *dwc; int ret; if (dep->flags & DWC3_EP_TRANSFER_STARTED) return 0; dwc = dep->dwc; memset(&params, 0, sizeof(params)); params.param0 = upper_32_bits(dwc->ep0_trb_addr); params.param1 = lower_32_bits(dwc->ep0_trb_addr); ret = dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_STARTTRANSFER, &params); if (ret < 0) return ret; dwc->ep0_next_event = DWC3_EP0_COMPLETE; return 0; } static int __dwc3_gadget_ep0_queue(struct dwc3_ep *dep, struct dwc3_request *req) { struct dwc3 *dwc = dep->dwc; req->request.actual = 0; req->request.status = -EINPROGRESS; req->epnum = dep->number; list_add_tail(&req->list, &dep->pending_list); /* * Gadget driver might not be quick enough to queue a request * before we get a Transfer Not Ready event on this endpoint. * * In that case, we will set DWC3_EP_PENDING_REQUEST. When that * flag is set, it's telling us that as soon as Gadget queues the * required request, we should kick the transfer here because the * IRQ we were waiting for is long gone. */ if (dep->flags & DWC3_EP_PENDING_REQUEST) { unsigned direction; direction = !!(dep->flags & DWC3_EP0_DIR_IN); if (dwc->ep0state != EP0_DATA_PHASE) { dev_WARN(dwc->dev, "Unexpected pending request\n"); return 0; } __dwc3_ep0_do_control_data(dwc, dwc->eps[direction], req); dep->flags &= ~(DWC3_EP_PENDING_REQUEST | DWC3_EP0_DIR_IN); return 0; } /* * In case gadget driver asked us to delay the STATUS phase, * handle it here. */ if (dwc->delayed_status) { unsigned direction; direction = !dwc->ep0_expect_in; dwc->delayed_status = false; usb_gadget_set_state(&dwc->gadget, USB_STATE_CONFIGURED); if (dwc->ep0state == EP0_STATUS_PHASE) __dwc3_ep0_do_control_status(dwc, dwc->eps[direction]); return 0; } /* * Unfortunately we have uncovered a limitation wrt the Data Phase. * * Section 9.4 says we can wait for the XferNotReady(DATA) event to * come before issueing Start Transfer command, but if we do, we will * miss situations where the host starts another SETUP phase instead of * the DATA phase. Such cases happen at least on TD.7.6 of the Link * Layer Compliance Suite. * * The problem surfaces due to the fact that in case of back-to-back * SETUP packets there will be no XferNotReady(DATA) generated and we * will be stuck waiting for XferNotReady(DATA) forever. * * By looking at tables 9-13 and 9-14 of the Databook, we can see that * it tells us to start Data Phase right away. It also mentions that if * we receive a SETUP phase instead of the DATA phase, core will issue * XferComplete for the DATA phase, before actually initiating it in * the wire, with the TRB's status set to "SETUP_PENDING". Such status * can only be used to print some debugging logs, as the core expects * us to go through to the STATUS phase and start a CONTROL_STATUS TRB, * just so it completes right away, without transferring anything and, * only then, we can go back to the SETUP phase. * * Because of this scenario, SNPS decided to change the programming * model of control transfers and support on-demand transfers only for * the STATUS phase. To fix the issue we have now, we will always wait * for gadget driver to queue the DATA phase's struct usb_request, then * start it right away. * * If we're actually in a 2-stage transfer, we will wait for * XferNotReady(STATUS). */ if (dwc->three_stage_setup) { unsigned direction; direction = dwc->ep0_expect_in; dwc->ep0state = EP0_DATA_PHASE; __dwc3_ep0_do_control_data(dwc, dwc->eps[direction], req); dep->flags &= ~DWC3_EP0_DIR_IN; } return 0; } int dwc3_gadget_ep0_queue(struct usb_ep *ep, struct usb_request *request, gfp_t gfp_flags) { struct dwc3_request *req = to_dwc3_request(request); struct dwc3_ep *dep = to_dwc3_ep(ep); struct dwc3 *dwc = dep->dwc; unsigned long flags; int ret; spin_lock_irqsave(&dwc->lock, flags); if (!dep->endpoint.desc) { dev_err(dwc->dev, "%s: can't queue to disabled endpoint\n", dep->name); ret = -ESHUTDOWN; goto out; } /* we share one TRB for ep0/1 */ if (!list_empty(&dep->pending_list)) { ret = -EBUSY; goto out; } ret = __dwc3_gadget_ep0_queue(dep, req); out: spin_unlock_irqrestore(&dwc->lock, flags); return ret; } static void dwc3_ep0_stall_and_restart(struct dwc3 *dwc) { struct dwc3_ep *dep; /* reinitialize physical ep1 */ dep = dwc->eps[1]; dep->flags = DWC3_EP_ENABLED; /* stall is always issued on EP0 */ dep = dwc->eps[0]; __dwc3_gadget_ep_set_halt(dep, 1, false); dep->flags = DWC3_EP_ENABLED; dwc->delayed_status = false; if (!list_empty(&dep->pending_list)) { struct dwc3_request *req; req = next_request(&dep->pending_list); dwc3_gadget_giveback(dep, req, -ECONNRESET); } dwc->ep0state = EP0_SETUP_PHASE; dwc3_ep0_out_start(dwc); } int __dwc3_gadget_ep0_set_halt(struct usb_ep *ep, int value) { struct dwc3_ep *dep = to_dwc3_ep(ep); struct dwc3 *dwc = dep->dwc; dwc3_ep0_stall_and_restart(dwc); return 0; } int dwc3_gadget_ep0_set_halt(struct usb_ep *ep, int value) { struct dwc3_ep *dep = to_dwc3_ep(ep); struct dwc3 *dwc = dep->dwc; unsigned long flags; int ret; spin_lock_irqsave(&dwc->lock, flags); ret = __dwc3_gadget_ep0_set_halt(ep, value); spin_unlock_irqrestore(&dwc->lock, flags); return ret; } void dwc3_ep0_out_start(struct dwc3 *dwc) { struct dwc3_ep *dep; int ret; complete(&dwc->ep0_in_setup); dep = dwc->eps[0]; dwc3_ep0_prepare_one_trb(dep, dwc->ep0_trb_addr, 8, DWC3_TRBCTL_CONTROL_SETUP, false); ret = dwc3_ep0_start_trans(dep); WARN_ON(ret < 0); } static struct dwc3_ep *dwc3_wIndex_to_dep(struct dwc3 *dwc, __le16 wIndex_le) { struct dwc3_ep *dep; u32 windex = le16_to_cpu(wIndex_le); u32 epnum; epnum = (windex & USB_ENDPOINT_NUMBER_MASK) << 1; if ((windex & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN) epnum |= 1; dep = dwc->eps[epnum]; if (dep->flags & DWC3_EP_ENABLED) return dep; return NULL; } static void dwc3_ep0_status_cmpl(struct usb_ep *ep, struct usb_request *req) { } /* * ch 9.4.5 */ static int dwc3_ep0_handle_status(struct dwc3 *dwc, struct usb_ctrlrequest *ctrl) { struct dwc3_ep *dep; u32 recip; u32 value; u32 reg; u16 usb_status = 0; __le16 *response_pkt; /* We don't support PTM_STATUS */ value = le16_to_cpu(ctrl->wValue); if (value != 0) return -EINVAL; recip = ctrl->bRequestType & USB_RECIP_MASK; switch (recip) { case USB_RECIP_DEVICE: /* * LTM will be set once we know how to set this in HW. */ usb_status |= dwc->gadget.is_selfpowered; if ((dwc->speed == DWC3_DSTS_SUPERSPEED) || (dwc->speed == DWC3_DSTS_SUPERSPEED_PLUS)) { reg = dwc3_readl(dwc->regs, DWC3_DCTL); if (reg & DWC3_DCTL_INITU1ENA) usb_status |= 1 << USB_DEV_STAT_U1_ENABLED; if (reg & DWC3_DCTL_INITU2ENA) usb_status |= 1 << USB_DEV_STAT_U2_ENABLED; } break; case USB_RECIP_INTERFACE: /* * Function Remote Wake Capable D0 * Function Remote Wakeup D1 */ break; case USB_RECIP_ENDPOINT: dep = dwc3_wIndex_to_dep(dwc, ctrl->wIndex); if (!dep) return -EINVAL; if (dep->flags & DWC3_EP_STALL) usb_status = 1 << USB_ENDPOINT_HALT; break; default: return -EINVAL; } response_pkt = (__le16 *) dwc->setup_buf; *response_pkt = cpu_to_le16(usb_status); dep = dwc->eps[0]; dwc->ep0_usb_req.dep = dep; dwc->ep0_usb_req.request.length = sizeof(*response_pkt); dwc->ep0_usb_req.request.buf = dwc->setup_buf; dwc->ep0_usb_req.request.complete = dwc3_ep0_status_cmpl; return __dwc3_gadget_ep0_queue(dep, &dwc->ep0_usb_req); } static int dwc3_ep0_handle_u1(struct dwc3 *dwc, enum usb_device_state state, int set) { u32 reg; if (state != USB_STATE_CONFIGURED) return -EINVAL; if ((dwc->speed != DWC3_DSTS_SUPERSPEED) && (dwc->speed != DWC3_DSTS_SUPERSPEED_PLUS)) return -EINVAL; if (set && dwc->dis_u1_entry_quirk) return -EINVAL; reg = dwc3_readl(dwc->regs, DWC3_DCTL); if (set) reg |= DWC3_DCTL_INITU1ENA; else reg &= ~DWC3_DCTL_INITU1ENA; dwc3_writel(dwc->regs, DWC3_DCTL, reg); return 0; } static int dwc3_ep0_handle_u2(struct dwc3 *dwc, enum usb_device_state state, int set) { u32 reg; if (state != USB_STATE_CONFIGURED) return -EINVAL; if ((dwc->speed != DWC3_DSTS_SUPERSPEED) && (dwc->speed != DWC3_DSTS_SUPERSPEED_PLUS)) return -EINVAL; if (set && dwc->dis_u2_entry_quirk) return -EINVAL; reg = dwc3_readl(dwc->regs, DWC3_DCTL); if (set) reg |= DWC3_DCTL_INITU2ENA; else reg &= ~DWC3_DCTL_INITU2ENA; dwc3_writel(dwc->regs, DWC3_DCTL, reg); return 0; } static int dwc3_ep0_handle_test(struct dwc3 *dwc, enum usb_device_state state, u32 wIndex, int set) { if ((wIndex & 0xff) != 0) return -EINVAL; if (!set) return -EINVAL; switch (wIndex >> 8) { case USB_TEST_J: case USB_TEST_K: case USB_TEST_SE0_NAK: case USB_TEST_PACKET: case USB_TEST_FORCE_ENABLE: dwc->test_mode_nr = wIndex >> 8; dwc->test_mode = true; break; default: return -EINVAL; } return 0; } static int dwc3_ep0_handle_device(struct dwc3 *dwc, struct usb_ctrlrequest *ctrl, int set) { enum usb_device_state state; u32 wValue; u32 wIndex; int ret = 0; wValue = le16_to_cpu(ctrl->wValue); wIndex = le16_to_cpu(ctrl->wIndex); state = dwc->gadget.state; switch (wValue) { case USB_DEVICE_REMOTE_WAKEUP: break; /* * 9.4.1 says only only for SS, in AddressState only for * default control pipe */ case USB_DEVICE_U1_ENABLE: ret = dwc3_ep0_handle_u1(dwc, state, set); break; case USB_DEVICE_U2_ENABLE: ret = dwc3_ep0_handle_u2(dwc, state, set); break; case USB_DEVICE_LTM_ENABLE: ret = -EINVAL; break; case USB_DEVICE_TEST_MODE: ret = dwc3_ep0_handle_test(dwc, state, wIndex, set); break; default: ret = -EINVAL; } return ret; } static int dwc3_ep0_handle_intf(struct dwc3 *dwc, struct usb_ctrlrequest *ctrl, int set) { u32 wValue; int ret = 0; wValue = le16_to_cpu(ctrl->wValue); switch (wValue) { case USB_INTRF_FUNC_SUSPEND: /* * REVISIT: Ideally we would enable some low power mode here, * however it's unclear what we should be doing here. * * For now, we're not doing anything, just making sure we return * 0 so USB Command Verifier tests pass without any errors. */ break; default: ret = -EINVAL; } return ret; } static int dwc3_ep0_handle_endpoint(struct dwc3 *dwc, struct usb_ctrlrequest *ctrl, int set) { struct dwc3_ep *dep; u32 wValue; int ret; wValue = le16_to_cpu(ctrl->wValue); switch (wValue) { case USB_ENDPOINT_HALT: dep = dwc3_wIndex_to_dep(dwc, ctrl->wIndex); if (!dep) return -EINVAL; if (set == 0 && (dep->flags & DWC3_EP_WEDGE)) break; ret = __dwc3_gadget_ep_set_halt(dep, set, true); if (ret) return -EINVAL; break; default: return -EINVAL; } return 0; } static int dwc3_ep0_handle_feature(struct dwc3 *dwc, struct usb_ctrlrequest *ctrl, int set) { u32 recip; int ret; recip = ctrl->bRequestType & USB_RECIP_MASK; switch (recip) { case USB_RECIP_DEVICE: ret = dwc3_ep0_handle_device(dwc, ctrl, set); break; case USB_RECIP_INTERFACE: ret = dwc3_ep0_handle_intf(dwc, ctrl, set); break; case USB_RECIP_ENDPOINT: ret = dwc3_ep0_handle_endpoint(dwc, ctrl, set); break; default: ret = -EINVAL; } return ret; } static int dwc3_ep0_set_address(struct dwc3 *dwc, struct usb_ctrlrequest *ctrl) { enum usb_device_state state = dwc->gadget.state; u32 addr; u32 reg; addr = le16_to_cpu(ctrl->wValue); if (addr > 127) { dev_err(dwc->dev, "invalid device address %d\n", addr); return -EINVAL; } if (state == USB_STATE_CONFIGURED) { dev_err(dwc->dev, "can't SetAddress() from Configured State\n"); return -EINVAL; } reg = dwc3_readl(dwc->regs, DWC3_DCFG); reg &= ~(DWC3_DCFG_DEVADDR_MASK); reg |= DWC3_DCFG_DEVADDR(addr); dwc3_writel(dwc->regs, DWC3_DCFG, reg); if (addr) usb_gadget_set_state(&dwc->gadget, USB_STATE_ADDRESS); else usb_gadget_set_state(&dwc->gadget, USB_STATE_DEFAULT); return 0; } static int dwc3_ep0_delegate_req(struct dwc3 *dwc, struct usb_ctrlrequest *ctrl) { int ret; spin_unlock(&dwc->lock); ret = dwc->gadget_driver->setup(&dwc->gadget, ctrl); spin_lock(&dwc->lock); return ret; } static int dwc3_ep0_set_config(struct dwc3 *dwc, struct usb_ctrlrequest *ctrl) { enum usb_device_state state = dwc->gadget.state; u32 cfg; int ret; u32 reg; cfg = le16_to_cpu(ctrl->wValue); switch (state) { case USB_STATE_DEFAULT: return -EINVAL; case USB_STATE_ADDRESS: ret = dwc3_ep0_delegate_req(dwc, ctrl); /* if the cfg matches and the cfg is non zero */ if (cfg && (!ret || (ret == USB_GADGET_DELAYED_STATUS))) { /* * only change state if set_config has already * been processed. If gadget driver returns * USB_GADGET_DELAYED_STATUS, we will wait * to change the state on the next usb_ep_queue() */ if (ret == 0) usb_gadget_set_state(&dwc->gadget, USB_STATE_CONFIGURED); /* * Enable transition to U1/U2 state when * nothing is pending from application. */ reg = dwc3_readl(dwc->regs, DWC3_DCTL); if (!dwc->dis_u1_entry_quirk) reg |= DWC3_DCTL_ACCEPTU1ENA; if (!dwc->dis_u2_entry_quirk) reg |= DWC3_DCTL_ACCEPTU2ENA; dwc3_writel(dwc->regs, DWC3_DCTL, reg); } break; case USB_STATE_CONFIGURED: ret = dwc3_ep0_delegate_req(dwc, ctrl); if (!cfg && !ret) usb_gadget_set_state(&dwc->gadget, USB_STATE_ADDRESS); break; default: ret = -EINVAL; } return ret; } static void dwc3_ep0_set_sel_cmpl(struct usb_ep *ep, struct usb_request *req) { struct dwc3_ep *dep = to_dwc3_ep(ep); struct dwc3 *dwc = dep->dwc; u32 param = 0; u32 reg; struct timing { u8 u1sel; u8 u1pel; __le16 u2sel; __le16 u2pel; } __packed timing; int ret; memcpy(&timing, req->buf, sizeof(timing)); dwc->u1sel = timing.u1sel; dwc->u1pel = timing.u1pel; dwc->u2sel = le16_to_cpu(timing.u2sel); dwc->u2pel = le16_to_cpu(timing.u2pel); reg = dwc3_readl(dwc->regs, DWC3_DCTL); if (reg & DWC3_DCTL_INITU2ENA) param = dwc->u2pel; if (reg & DWC3_DCTL_INITU1ENA) param = dwc->u1pel; /* * According to Synopsys Databook, if parameter is * greater than 125, a value of zero should be * programmed in the register. */ if (param > 125) param = 0; /* now that we have the time, issue DGCMD Set Sel */ ret = dwc3_send_gadget_generic_command(dwc, DWC3_DGCMD_SET_PERIODIC_PAR, param); WARN_ON(ret < 0); } static int dwc3_ep0_set_sel(struct dwc3 *dwc, struct usb_ctrlrequest *ctrl) { struct dwc3_ep *dep; enum usb_device_state state = dwc->gadget.state; u16 wLength; if (state == USB_STATE_DEFAULT) return -EINVAL; wLength = le16_to_cpu(ctrl->wLength); if (wLength != 6) { dev_err(dwc->dev, "Set SEL should be 6 bytes, got %d\n", wLength); return -EINVAL; } /* * To handle Set SEL we need to receive 6 bytes from Host. So let's * queue a usb_request for 6 bytes. * * Remember, though, this controller can't handle non-wMaxPacketSize * aligned transfers on the OUT direction, so we queue a request for * wMaxPacketSize instead. */ dep = dwc->eps[0]; dwc->ep0_usb_req.dep = dep; dwc->ep0_usb_req.request.length = dep->endpoint.maxpacket; dwc->ep0_usb_req.request.buf = dwc->setup_buf; dwc->ep0_usb_req.request.complete = dwc3_ep0_set_sel_cmpl; return __dwc3_gadget_ep0_queue(dep, &dwc->ep0_usb_req); } static int dwc3_ep0_set_isoch_delay(struct dwc3 *dwc, struct usb_ctrlrequest *ctrl) { u16 wLength; u16 wValue; u16 wIndex; wValue = le16_to_cpu(ctrl->wValue); wLength = le16_to_cpu(ctrl->wLength); wIndex = le16_to_cpu(ctrl->wIndex); if (wIndex || wLength) return -EINVAL; dwc->gadget.isoch_delay = wValue; return 0; } static int dwc3_ep0_std_request(struct dwc3 *dwc, struct usb_ctrlrequest *ctrl) { int ret; switch (ctrl->bRequest) { case USB_REQ_GET_STATUS: ret = dwc3_ep0_handle_status(dwc, ctrl); break; case USB_REQ_CLEAR_FEATURE: ret = dwc3_ep0_handle_feature(dwc, ctrl, 0); break; case USB_REQ_SET_FEATURE: ret = dwc3_ep0_handle_feature(dwc, ctrl, 1); break; case USB_REQ_SET_ADDRESS: ret = dwc3_ep0_set_address(dwc, ctrl); break; case USB_REQ_SET_CONFIGURATION: ret = dwc3_ep0_set_config(dwc, ctrl); break; case USB_REQ_SET_SEL: ret = dwc3_ep0_set_sel(dwc, ctrl); break; case USB_REQ_SET_ISOCH_DELAY: ret = dwc3_ep0_set_isoch_delay(dwc, ctrl); break; default: ret = dwc3_ep0_delegate_req(dwc, ctrl); break; } return ret; } static void dwc3_ep0_inspect_setup(struct dwc3 *dwc, const struct dwc3_event_depevt *event) { struct usb_ctrlrequest *ctrl = (void *) dwc->ep0_trb; int ret = -EINVAL; u32 len; if (!dwc->gadget_driver) goto out; trace_dwc3_ctrl_req(ctrl); len = le16_to_cpu(ctrl->wLength); if (!len) { dwc->three_stage_setup = false; dwc->ep0_expect_in = false; dwc->ep0_next_event = DWC3_EP0_NRDY_STATUS; } else { dwc->three_stage_setup = true; dwc->ep0_expect_in = !!(ctrl->bRequestType & USB_DIR_IN); dwc->ep0_next_event = DWC3_EP0_NRDY_DATA; } if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) ret = dwc3_ep0_std_request(dwc, ctrl); else ret = dwc3_ep0_delegate_req(dwc, ctrl); if (ret == USB_GADGET_DELAYED_STATUS) dwc->delayed_status = true; out: if (ret < 0) dwc3_ep0_stall_and_restart(dwc); } static void dwc3_ep0_complete_data(struct dwc3 *dwc, const struct dwc3_event_depevt *event) { struct dwc3_request *r; struct usb_request *ur; struct dwc3_trb *trb; struct dwc3_ep *ep0; u32 transferred = 0; u32 status; u32 length; u8 epnum; epnum = event->endpoint_number; ep0 = dwc->eps[0]; dwc->ep0_next_event = DWC3_EP0_NRDY_STATUS; trb = dwc->ep0_trb; trace_dwc3_complete_trb(ep0, trb); r = next_request(&ep0->pending_list); if (!r) return; status = DWC3_TRB_SIZE_TRBSTS(trb->size); if (status == DWC3_TRBSTS_SETUP_PENDING) { dwc->setup_packet_pending = true; if (r) dwc3_gadget_giveback(ep0, r, -ECONNRESET); return; } ur = &r->request; length = trb->size & DWC3_TRB_SIZE_MASK; transferred = ur->length - length; ur->actual += transferred; if ((IS_ALIGNED(ur->length, ep0->endpoint.maxpacket) && ur->length && ur->zero) || dwc->ep0_bounced) { trb++; trb->ctrl &= ~DWC3_TRB_CTRL_HWO; trace_dwc3_complete_trb(ep0, trb); if (r->direction) dwc->eps[1]->trb_enqueue = 0; else dwc->eps[0]->trb_enqueue = 0; dwc->ep0_bounced = false; } if ((epnum & 1) && ur->actual < ur->length) dwc3_ep0_stall_and_restart(dwc); else dwc3_gadget_giveback(ep0, r, 0); } static void dwc3_ep0_complete_status(struct dwc3 *dwc, const struct dwc3_event_depevt *event) { struct dwc3_request *r; struct dwc3_ep *dep; struct dwc3_trb *trb; u32 status; dep = dwc->eps[0]; trb = dwc->ep0_trb; trace_dwc3_complete_trb(dep, trb); if (!list_empty(&dep->pending_list)) { r = next_request(&dep->pending_list); dwc3_gadget_giveback(dep, r, 0); } if (dwc->test_mode) { int ret; ret = dwc3_gadget_set_test_mode(dwc, dwc->test_mode_nr); if (ret < 0) { dev_err(dwc->dev, "invalid test #%d\n", dwc->test_mode_nr); dwc3_ep0_stall_and_restart(dwc); return; } } status = DWC3_TRB_SIZE_TRBSTS(trb->size); if (status == DWC3_TRBSTS_SETUP_PENDING) dwc->setup_packet_pending = true; dwc->ep0state = EP0_SETUP_PHASE; dwc3_ep0_out_start(dwc); } static void dwc3_ep0_xfer_complete(struct dwc3 *dwc, const struct dwc3_event_depevt *event) { struct dwc3_ep *dep = dwc->eps[event->endpoint_number]; dep->flags &= ~DWC3_EP_TRANSFER_STARTED; dep->resource_index = 0; dwc->setup_packet_pending = false; switch (dwc->ep0state) { case EP0_SETUP_PHASE: dwc3_ep0_inspect_setup(dwc, event); break; case EP0_DATA_PHASE: dwc3_ep0_complete_data(dwc, event); break; case EP0_STATUS_PHASE: dwc3_ep0_complete_status(dwc, event); break; default: WARN(true, "UNKNOWN ep0state %d\n", dwc->ep0state); } } static void __dwc3_ep0_do_control_data(struct dwc3 *dwc, struct dwc3_ep *dep, struct dwc3_request *req) { int ret; req->direction = !!dep->number; if (req->request.length == 0) { dwc3_ep0_prepare_one_trb(dep, dwc->ep0_trb_addr, 0, DWC3_TRBCTL_CONTROL_DATA, false); ret = dwc3_ep0_start_trans(dep); } else if (!IS_ALIGNED(req->request.length, dep->endpoint.maxpacket) && (dep->number == 0)) { u32 maxpacket; u32 rem; ret = usb_gadget_map_request_by_dev(dwc->sysdev, &req->request, dep->number); if (ret) return; maxpacket = dep->endpoint.maxpacket; rem = req->request.length % maxpacket; dwc->ep0_bounced = true; /* prepare normal TRB */ dwc3_ep0_prepare_one_trb(dep, req->request.dma, req->request.length, DWC3_TRBCTL_CONTROL_DATA, true); req->trb = &dwc->ep0_trb[dep->trb_enqueue - 1]; /* Now prepare one extra TRB to align transfer size */ dwc3_ep0_prepare_one_trb(dep, dwc->bounce_addr, maxpacket - rem, DWC3_TRBCTL_CONTROL_DATA, false); ret = dwc3_ep0_start_trans(dep); } else if (IS_ALIGNED(req->request.length, dep->endpoint.maxpacket) && req->request.length && req->request.zero) { ret = usb_gadget_map_request_by_dev(dwc->sysdev, &req->request, dep->number); if (ret) return; /* prepare normal TRB */ dwc3_ep0_prepare_one_trb(dep, req->request.dma, req->request.length, DWC3_TRBCTL_CONTROL_DATA, true); req->trb = &dwc->ep0_trb[dep->trb_enqueue - 1]; /* Now prepare one extra TRB to align transfer size */ dwc3_ep0_prepare_one_trb(dep, dwc->bounce_addr, 0, DWC3_TRBCTL_CONTROL_DATA, false); ret = dwc3_ep0_start_trans(dep); } else { ret = usb_gadget_map_request_by_dev(dwc->sysdev, &req->request, dep->number); if (ret) return; dwc3_ep0_prepare_one_trb(dep, req->request.dma, req->request.length, DWC3_TRBCTL_CONTROL_DATA, false); req->trb = &dwc->ep0_trb[dep->trb_enqueue]; ret = dwc3_ep0_start_trans(dep); } WARN_ON(ret < 0); } static int dwc3_ep0_start_control_status(struct dwc3_ep *dep) { struct dwc3 *dwc = dep->dwc; u32 type; type = dwc->three_stage_setup ? DWC3_TRBCTL_CONTROL_STATUS3 : DWC3_TRBCTL_CONTROL_STATUS2; dwc3_ep0_prepare_one_trb(dep, dwc->ep0_trb_addr, 0, type, false); return dwc3_ep0_start_trans(dep); } static void __dwc3_ep0_do_control_status(struct dwc3 *dwc, struct dwc3_ep *dep) { WARN_ON(dwc3_ep0_start_control_status(dep)); } static void dwc3_ep0_do_control_status(struct dwc3 *dwc, const struct dwc3_event_depevt *event) { struct dwc3_ep *dep = dwc->eps[event->endpoint_number]; __dwc3_ep0_do_control_status(dwc, dep); } static void dwc3_ep0_end_control_data(struct dwc3 *dwc, struct dwc3_ep *dep) { struct dwc3_gadget_ep_cmd_params params; u32 cmd; int ret; if (!dep->resource_index) return; cmd = DWC3_DEPCMD_ENDTRANSFER; cmd |= DWC3_DEPCMD_CMDIOC; cmd |= DWC3_DEPCMD_PARAM(dep->resource_index); memset(&params, 0, sizeof(params)); ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params); WARN_ON_ONCE(ret); dep->resource_index = 0; } static void dwc3_ep0_xfernotready(struct dwc3 *dwc, const struct dwc3_event_depevt *event) { switch (event->status) { case DEPEVT_STATUS_CONTROL_DATA: /* * We already have a DATA transfer in the controller's cache, * if we receive a XferNotReady(DATA) we will ignore it, unless * it's for the wrong direction. * * In that case, we must issue END_TRANSFER command to the Data * Phase we already have started and issue SetStall on the * control endpoint. */ if (dwc->ep0_expect_in != event->endpoint_number) { struct dwc3_ep *dep = dwc->eps[dwc->ep0_expect_in]; dev_err(dwc->dev, "unexpected direction for Data Phase\n"); dwc3_ep0_end_control_data(dwc, dep); dwc3_ep0_stall_and_restart(dwc); return; } break; case DEPEVT_STATUS_CONTROL_STATUS: if (dwc->ep0_next_event != DWC3_EP0_NRDY_STATUS) return; dwc->ep0state = EP0_STATUS_PHASE; if (dwc->delayed_status) { struct dwc3_ep *dep = dwc->eps[0]; WARN_ON_ONCE(event->endpoint_number != 1); /* * We should handle the delay STATUS phase here if the * request for handling delay STATUS has been queued * into the list. */ if (!list_empty(&dep->pending_list)) { dwc->delayed_status = false; usb_gadget_set_state(&dwc->gadget, USB_STATE_CONFIGURED); dwc3_ep0_do_control_status(dwc, event); } return; } dwc3_ep0_do_control_status(dwc, event); } } void dwc3_ep0_interrupt(struct dwc3 *dwc, const struct dwc3_event_depevt *event) { struct dwc3_ep *dep = dwc->eps[event->endpoint_number]; u8 cmd; switch (event->endpoint_event) { case DWC3_DEPEVT_XFERCOMPLETE: dwc3_ep0_xfer_complete(dwc, event); break; case DWC3_DEPEVT_XFERNOTREADY: dwc3_ep0_xfernotready(dwc, event); break; case DWC3_DEPEVT_XFERINPROGRESS: case DWC3_DEPEVT_RXTXFIFOEVT: case DWC3_DEPEVT_STREAMEVT: break; case DWC3_DEPEVT_EPCMDCMPLT: cmd = DEPEVT_PARAMETER_CMD(event->parameters); if (cmd == DWC3_DEPCMD_ENDTRANSFER) { dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING; dep->flags &= ~DWC3_EP_TRANSFER_STARTED; } break; } }
{ "pile_set_name": "Github" }
import os import cv2 import matplotlib.pyplot as plt import numpy as np import tqdm import random # root='/media/hilab/sagniksSSD/Sagnik/DewarpNet/swat3d/' # filenames=['7/2_427_8-cp_Page_1362-4rw0001','7/2_87_5-ec_Page_040-AZI0001','7/1_811_3-ny_Page_554-sof0001','7/2_168_4-ny_Page_888-qoK0001', # '7/1_50_7-ns_Page_527-fyQ0001','7/827_6-ny_Page_040-x410001','7/762_7-ns_Page_579-UzD0001','7/2_456_6-pp_Page_278-tUY0001', # '7/1_996_5-ns_Page_402-icm0001','7/2_85_5-ns_Page_523-rgf0001'] def tight_crop(im, fm): # different tight crop msk=((fm[:,:,0]!=0)&(fm[:,:,1]!=0)&(fm[:,:,2]!=0)).astype(np.uint8) [y, x] = (msk).nonzero() minx = min(x) maxx = max(x) miny = min(y) maxy = max(y) im = im[miny : maxy + 1, minx : maxx + 1, :] fm = fm[miny : maxy + 1, minx : maxx + 1, :] # px = int((maxx - minx) * 0.07) # py = int((maxy - miny) * 0.07) # im = np.pad(im, ((py, py + 1), (px, px + 1), (0, 0)), 'constant') # fm = np.pad(fm, ((py, py + 1), (px, px + 1), (0, 0)), 'constant') # # crop # cx1 = int(random.randint(0, 3) / 7.0 * px) # cx2 = int(random.randint(0, 3) / 7.0 * px + 1) # cy1 = int(random.randint(0, 3) / 7.0 * py) # cy2 = int(random.randint(0, 3) / 7.0 * py + 1) s = 20 im = np.pad(im, ((s, s), (s, s), (0, 0)), 'constant') fm = np.pad(fm, ((s, s), (s, s), (0, 0)), 'constant') cx1 = random.randint(0, s - 5) cx2 = random.randint(0, s - 5) + 1 cy1 = random.randint(0, s - 5) cy2 = random.randint(0, s - 5) + 1 im = im[cy1 : -cy2, cx1 : -cx2, :] fm = fm[cy1 : -cy2, cx1 : -cx2, :] return im, fm def color_jitter(im, brightness=0, contrast=0, saturation=0, hue=0): f = random.uniform(1 - contrast, 1 + contrast) im = np.clip(im * f, 0., 1.) f = random.uniform(-brightness, brightness) im = np.clip(im + f, 0., 1.).astype(np.float32) hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) f = random.uniform(-hue, hue)*360. hsv[:,:,0] = np.clip(hsv[:,:,0] + f, 0., 360.) f = random.uniform(-saturation, saturation) hsv[:,:,1] = np.clip(hsv[:,:,1] + f, 0., 1.) im = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB) return im def change_intensity(img): chance=random.uniform(0,1) # print(chance) nimg = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) if chance>0.3: inc=random.randint(15,50) # print(inc) #increase v = nimg[:, :, 2] v = np.where(v <= 255 - inc, v + inc, 255) nimg[:, :, 2] = v nimg = cv2.cvtColor(nimg, cv2.COLOR_HSV2BGR) # f,axarr=plt.subplots(1,2) # axarr[0].imshow(img) # axarr[1].imshow(nimg) # plt.show() return nimg def change_hue_sat(img): chance=random.uniform(0,1) # print(chance) nimg = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) if chance>0.3: inc=random.randint(5,15) # print(inc) #increase v = nimg[:, :, 0] v = np.where(v <= 255 - inc, v + inc, 255) nimg[:, :, 0] = v if chance>0.3: inc=random.randint(5,15) # print(inc) #increase v = nimg[:, :, 1] v = np.where(v <= 255 - inc, v + inc, 255) nimg[:, :, 1] = v nimg = cv2.cvtColor(nimg, cv2.COLOR_HSV2BGR) # f,axarr=plt.subplots(1,2) # axarr[0].imshow(img) # axarr[1].imshow(nimg) # plt.show() return nimg def data_aug(im, fm, bg): im=im/255.0 bg=bg/255.0 # im, fm = tight_crop(im, fm) # change background img # msk = fm[:, :, 0] > 0 msk=((fm[:,:,0]!=0)&(fm[:,:,1]!=0)&(fm[:,:,2]!=0)).astype(np.uint8) msk = np.expand_dims(msk, axis=2) # replace bg [fh, fw, _] = im.shape chance=random.random() if chance > 0.3: bg = cv2.resize(bg, (200, 200)) bg = np.tile(bg, (3, 3, 1)) bg = bg[: fh, : fw, :] elif chance < 0.3 and chance> 0.2: c = np.array([random.random(), random.random(), random.random()]) bg = np.ones((fh, fw, 3)) * c else: bg=np.zeros((fh, fw, 3)) msk=np.ones((fh, fw, 3)) im = bg * (1 - msk) + im * msk # jitter color im = color_jitter(im, 0.2, 0.2, 0.6, 0.6) # im = change_hue_sat(im) # im = change_intensity(im) # plt.imshow(im) # plt.show() # plt.imshow(fm) # plt.show() return im, fm # def main(): # tex_id=random.randint(1,5640) # with open(os.path.join(root[:-7],'augtexnames.txt'),'r') as f: # for i in range(tex_id): # txpth=f.readline().strip() # for im_name in filenames: # im_path = os.path.join(root,'img',im_name+'.png') # img=cv2.imread(im_path).astype(np.uint8) # lbl_path = os.path.join(root, 'wc',im_name+'.exr') # lbl = cv2.imread(lbl_path, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH) # tex=cv2.imread(os.path.join(root[:-7],txpth)).astype(np.uint8) # bg=cv2.resize(tex,(img.shape[1],img.shape[0]),interpolation=cv2.INTER_LANCZOS4) # img,lbl=data_aug(img,lbl,bg) # if __name__ == '__main__': # main()
{ "pile_set_name": "Github" }
# Require management scripts written by Otto Behrens and Danie Roux require File.join(File.dirname(__FILE__), 'contrib/ottobehrens/stone') # Set the GemStoneInstallation paths for a default install of MagLev, based # on $MAGLEV_HOME, but respect the $GEMSTONE env variable, if set ML = ENV['MAGLEV_HOME'] GemStoneInstallation.current = GemStoneInstallation.new( ENV['GEMSTONE'] || "#{ML}/gemstone", # installation_directory "#{ML}/etc/conf.d", # config_directory "#{ML}/data", # installation_extent_directory "#{ML}/log", # base log directory "#{ML}/backups", # backup directory 'extent0.ruby.dbf') # initial extent name def (GemStoneInstallation.current).initial_extent File.join(ML, "bin", @initial_extent_name) end class MagLevStone < Stone def config_file_template File.open(File.dirname(__FILE__) + "/maglev_stone.conf.template").read end def key_file "#{ML}/etc/maglev.demo.key" end def create_skeleton mkdir_p @gemstone_installation.config_directory mkdir_p @gemstone_installation.backup_directory super end # Will remove everything in the stone's data directory! def destroy! super rm_rf data_directory end # Will remove everything in the stone's data directory! def clobber_data! fail "Can not clobber data on a running stone" if running? rm_rf extent_directory rm_rf tranlog_directories mkdir_p extent_directory mkdir_p tranlog_directories end def reload with_server_stopped do destroy! initialize_new_stone end end def start(netldiname='gs64ldi') ENV['gs64ldi'] = netldiname puts "=== Starting with netldiname #{netldiname}" super() ensure_prims_loaded end def take_snapshot with_server_stopped { make_offline_backup } end def restore_snapshot with_server_stopped { restore_offline_backup } end def make_offline_backup fail "Must stop server before making offline backup." if running? puts "Making offline backup to: #{backup_directory}/#{snapshot_filename}" Dir.chdir(extent_directory) log_sh "tar zcf #{backup_directory}/#{snapshot_filename} *dbf" end def restore_offline_backup fail "Must stop server before restoring full backup." if running? clobber_data! puts "Restoring offline backup from: #{backup_directory}/#{snapshot_to_restore}" Dir.chdir(extent_directory) log_sh "tar zxfv #{backup_directory}/#{snapshot_to_restore}" end def snapshot_filename "#{name}_extent.tgz" # TODO allow multiple snapshot files by time of day # "#{name}_#{Time.now.strftime("%Y%d%H-%H%M")}.bak.tgz" end def snapshot_to_restore "#{name}_extent.tgz" # TODO allow selection of snapshot file to restore end def initialize_gemstone_environment super FORK_ENV['GEMSTONE_NAME'] = name # Tell gslist and others where the root of the install is. FORK_ENV['GEMSTONE_GLOBAL_DIR'] = ENV['MAGLEV_HOME'] end # Loads the primitives if they haven't been loaded, then commits the # transaction. Does nothing if prims are already loaded. def ensure_prims_loaded if running? reload_prims unless prims_loaded?(@name) end end def reload_everything start unless running? puts "Reloading src/smalltalk for #{@name}. This may take a minute..." filename = "#{ML}/src/smalltalk/load#{@name}everything.gs" ENV["imageRubyDir"] = "#{ML}/src/smalltalk/ruby" File.open(filename, "w") do |f| f.write(<<-EOS) set gemstone #{@name} level 0 display oops display resultcheck errorcount iferr 1 exit 2 set user SystemUser pass swordfish login iferr 2 stack output push baseruby.out input #{ML}/src/smalltalk/fileinImageRubyDir.gs commit logout exit EOS end input_file(filename , false) FileUtils.rm_f filename reload_file_tree end def reload_file_tree start unless running? puts "Loading src/packages for #{@name}. This may take a minute..." script = File.read("#{ML}/src/smalltalk/loadfiletree.gs") filename = "#{ML}/src/smalltalk/load#{@name}filetree.gs" File.open(filename, "w") do |f| f << script.gsub("MAGLEV_HOME", ML) end input_file(filename , false) FileUtils.rm_f filename reload_prims end def reload_prims start unless running? puts "Loading Kernel for #{@name}. This may take a few seconds..." input_file("#{ML}/src/smalltalk/ruby/allprims.topaz", false) stonename = ENV["STONENAME"] begin ENV["STONENAME"] = "" system("#{ML}/bin/maglev-ruby", "--stone", @name, "#{ML}/src/kernel/extensions.rb") ensure ENV["STONENAME"] = stonename end end def prims_loaded?(name='maglev') begin cmds = ["output append #{topaz_logfile}", "set u DataCurator p swordfish gemstone #{name}", "login", "obj RubyPrimsLoaded", "output pop", "exit"] Topaz.new(self).commands(cmds) rescue Exception => e # Ignore the exception. If test for obj RubyPrimsLoaded will cause # topaz to exit with a non-zero exit status, which is what we want, # so that we can return true or false. end $?.success? end def topaz_session Topaz.new(self).interactive_session end private # Executes the block with the server stopped. Will # restart the server if the server was running when # with_server_stopped was called. def with_server_stopped was_running = self.running? stop if was_running yield start if was_running end def webtools www_dir = "#{GemStoneInstallation.current.installation_directory}/examples/www" unless File.exist?("#{www_dir}/installAndRun.tpz") unless File.exist?(gss = "#{ML}/../svn") || File.exist?(gss = "#{ML}/../HPI-GSS") raise "cannot run webtools, please copy the code to #{www_dir}" end FileUtils.chmod("+w", www_dir) Dir["#{gss}/examples/www/*"].each do |file| FileUtils.cp_r(file, www_dir) end end cmds = ["set u DataCurator p swordfish gemstone #{name}", "login", "input $GEMSTONE/examples/www/installAndRun.tpz"] puts "WebTools running on localhost:8080" Topaz.new(self).commands(cmds) end end
{ "pile_set_name": "Github" }
/** * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE */ import { MediaMatcher } from '@angular/cdk/layout'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { distinctUntilChanged, map, startWith } from 'rxjs/operators'; import { NzResizeService } from './resize'; export enum NzBreakpointEnum { xxl = 'xxl', xl = 'xl', lg = 'lg', md = 'md', sm = 'sm', xs = 'xs' } export type BreakpointMap = { [key in NzBreakpointEnum]: string }; export type BreakpointBooleanMap = { [key in NzBreakpointEnum]: boolean }; export type NzBreakpointKey = keyof typeof NzBreakpointEnum; export const gridResponsiveMap: BreakpointMap = { xs: '(max-width: 575px)', sm: '(min-width: 576px)', md: '(min-width: 768px)', lg: '(min-width: 992px)', xl: '(min-width: 1200px)', xxl: '(min-width: 1600px)' }; export const siderResponsiveMap: BreakpointMap = { xs: '(max-width: 479.98px)', sm: '(max-width: 575.98px)', md: '(max-width: 767.98px)', lg: '(max-width: 991.98px)', xl: '(max-width: 1199.98px)', xxl: '(max-width: 1599.98px)' }; @Injectable({ providedIn: 'root' }) export class NzBreakpointService { constructor(private resizeService: NzResizeService, private mediaMatcher: MediaMatcher) { this.resizeService.subscribe().subscribe(() => {}); } subscribe(breakpointMap: BreakpointMap): Observable<NzBreakpointEnum>; subscribe(breakpointMap: BreakpointMap, fullMap: true): Observable<BreakpointBooleanMap>; subscribe(breakpointMap: BreakpointMap, fullMap?: true): Observable<NzBreakpointEnum | BreakpointBooleanMap> { if (fullMap) { const get = () => this.matchMedia(breakpointMap, true); return this.resizeService.subscribe().pipe( map(get), startWith(get()), distinctUntilChanged((x: [NzBreakpointEnum, BreakpointBooleanMap], y: [NzBreakpointEnum, BreakpointBooleanMap]) => x[0] === y[0]), map(x => x[1]) ); } else { const get = () => this.matchMedia(breakpointMap); return this.resizeService.subscribe().pipe(map(get), startWith(get()), distinctUntilChanged()); } } private matchMedia(breakpointMap: BreakpointMap): NzBreakpointEnum; private matchMedia(breakpointMap: BreakpointMap, fullMap: true): [NzBreakpointEnum, BreakpointBooleanMap]; private matchMedia(breakpointMap: BreakpointMap, fullMap?: true): NzBreakpointEnum | [NzBreakpointEnum, BreakpointBooleanMap] { let bp = NzBreakpointEnum.md; const breakpointBooleanMap: Partial<BreakpointBooleanMap> = {}; Object.keys(breakpointMap).map(breakpoint => { const castBP = breakpoint as NzBreakpointEnum; const matched = this.mediaMatcher.matchMedia(gridResponsiveMap[castBP]).matches; breakpointBooleanMap[breakpoint as NzBreakpointEnum] = matched; if (matched) { bp = castBP; } }); if (fullMap) { return [bp, breakpointBooleanMap as BreakpointBooleanMap]; } else { return bp; } } }
{ "pile_set_name": "Github" }
package swarm import ( "bytes" "fmt" "io/ioutil" "testing" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/cli/internal/test" "github.com/pkg/errors" // Import builders to get the builder function as package function . "github.com/docker/docker/cli/internal/test/builders" "github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/golden" ) func TestSwarmUnlockKeyErrors(t *testing.T) { testCases := []struct { name string args []string flags map[string]string swarmInspectFunc func() (swarm.Swarm, error) swarmUpdateFunc func(swarm swarm.Spec, flags swarm.UpdateFlags) error swarmGetUnlockKeyFunc func() (types.SwarmUnlockKeyResponse, error) expectedError string }{ { name: "too-many-args", args: []string{"foo"}, expectedError: "accepts no argument(s)", }, { name: "swarm-inspect-rotate-failed", flags: map[string]string{ flagRotate: "true", }, swarmInspectFunc: func() (swarm.Swarm, error) { return swarm.Swarm{}, errors.Errorf("error inspecting the swarm") }, expectedError: "error inspecting the swarm", }, { name: "swarm-rotate-no-autolock-failed", flags: map[string]string{ flagRotate: "true", }, swarmInspectFunc: func() (swarm.Swarm, error) { return *Swarm(), nil }, expectedError: "cannot rotate because autolock is not turned on", }, { name: "swarm-update-failed", flags: map[string]string{ flagRotate: "true", }, swarmInspectFunc: func() (swarm.Swarm, error) { return *Swarm(Autolock()), nil }, swarmUpdateFunc: func(swarm swarm.Spec, flags swarm.UpdateFlags) error { return errors.Errorf("error updating the swarm") }, expectedError: "error updating the swarm", }, { name: "swarm-get-unlock-key-failed", swarmGetUnlockKeyFunc: func() (types.SwarmUnlockKeyResponse, error) { return types.SwarmUnlockKeyResponse{}, errors.Errorf("error getting unlock key") }, expectedError: "error getting unlock key", }, { name: "swarm-no-unlock-key-failed", swarmGetUnlockKeyFunc: func() (types.SwarmUnlockKeyResponse, error) { return types.SwarmUnlockKeyResponse{ UnlockKey: "", }, nil }, expectedError: "no unlock key is set", }, } for _, tc := range testCases { buf := new(bytes.Buffer) cmd := newUnlockKeyCommand( test.NewFakeCli(&fakeClient{ swarmInspectFunc: tc.swarmInspectFunc, swarmUpdateFunc: tc.swarmUpdateFunc, swarmGetUnlockKeyFunc: tc.swarmGetUnlockKeyFunc, }, buf)) cmd.SetArgs(tc.args) for key, value := range tc.flags { cmd.Flags().Set(key, value) } cmd.SetOutput(ioutil.Discard) assert.Error(t, cmd.Execute(), tc.expectedError) } } func TestSwarmUnlockKey(t *testing.T) { testCases := []struct { name string args []string flags map[string]string swarmInspectFunc func() (swarm.Swarm, error) swarmUpdateFunc func(swarm swarm.Spec, flags swarm.UpdateFlags) error swarmGetUnlockKeyFunc func() (types.SwarmUnlockKeyResponse, error) }{ { name: "unlock-key", swarmGetUnlockKeyFunc: func() (types.SwarmUnlockKeyResponse, error) { return types.SwarmUnlockKeyResponse{ UnlockKey: "unlock-key", }, nil }, }, { name: "unlock-key-quiet", flags: map[string]string{ flagQuiet: "true", }, swarmGetUnlockKeyFunc: func() (types.SwarmUnlockKeyResponse, error) { return types.SwarmUnlockKeyResponse{ UnlockKey: "unlock-key", }, nil }, }, { name: "unlock-key-rotate", flags: map[string]string{ flagRotate: "true", }, swarmInspectFunc: func() (swarm.Swarm, error) { return *Swarm(Autolock()), nil }, swarmGetUnlockKeyFunc: func() (types.SwarmUnlockKeyResponse, error) { return types.SwarmUnlockKeyResponse{ UnlockKey: "unlock-key", }, nil }, }, { name: "unlock-key-rotate-quiet", flags: map[string]string{ flagQuiet: "true", flagRotate: "true", }, swarmInspectFunc: func() (swarm.Swarm, error) { return *Swarm(Autolock()), nil }, swarmGetUnlockKeyFunc: func() (types.SwarmUnlockKeyResponse, error) { return types.SwarmUnlockKeyResponse{ UnlockKey: "unlock-key", }, nil }, }, } for _, tc := range testCases { buf := new(bytes.Buffer) cmd := newUnlockKeyCommand( test.NewFakeCli(&fakeClient{ swarmInspectFunc: tc.swarmInspectFunc, swarmUpdateFunc: tc.swarmUpdateFunc, swarmGetUnlockKeyFunc: tc.swarmGetUnlockKeyFunc, }, buf)) cmd.SetArgs(tc.args) for key, value := range tc.flags { cmd.Flags().Set(key, value) } assert.NilError(t, cmd.Execute()) actual := buf.String() expected := golden.Get(t, []byte(actual), fmt.Sprintf("unlockkeys-%s.golden", tc.name)) assert.EqualNormalizedString(t, assert.RemoveSpace, actual, string(expected)) } }
{ "pile_set_name": "Github" }
package com.tencent.mm.pluginsdk.ui.chat; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; final class af implements DialogInterface.OnClickListener { af(ad paramad) {} public final void onClick(DialogInterface paramDialogInterface, int paramInt) {} } /* Location: * Qualified Name: com.tencent.mm.pluginsdk.ui.chat.af * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
{ "pile_set_name": "Github" }
# makefile for netcat, based off same ol' "generic makefile". # Usually do "make systype" -- if your systype isn't defined, try "generic" # or something else that most closely matches, see where it goes wrong, fix # it, and MAIL THE DIFFS back to Hobbit. ### PREDEFINES # DEFAULTS, possibly overridden by <systype> recursive call: # pick gcc if you'd rather , and/or do -g instead of -O if debugging # debugging # DFLAGS = -DTEST -DDEBUG CFLAGS = -O XFLAGS = # xtra cflags, set by systype targets XLIBS = # xtra libs if necessary? # -Bstatic for sunos, -static for gcc, etc. You want this, trust me. STATIC = CC = gcc $(CFLAGS) LD = $(CC) # linker; defaults to unstripped executables o = o # object extension ALL = nc -include Makefile.local ### BOGON-CATCHERS bogus: @echo "Usage: make <systype> [options]" ### HARD TARGETS nc: netcat.c $(LD) $(DFLAGS) $(XFLAGS) $(STATIC) -o nc netcat.c $(XLIBS) nc-dos: @echo "DOS?! Maybe someday, but not now" ### SYSTYPES -- in the same order as in generic.h, please # designed for msc and nmake, but easy to change for your compiler. # Recursive make may fail if you're short on memory -- u-fix! # Note special hard-target and "quotes" instead of 'quotes' ... dos: $(MAKE) -e $(ALL)-dos $(MFLAGS) CC="cl /nologo" XLIBS= \ XFLAGS="/AS -D__MSDOS__ -DMSDOS" o=obj ultrix: make -e $(ALL) $(MFLAGS) XFLAGS='-DULTRIX' # you may need XLIBS='-lresolv -l44bsd' if you have BIND 4.9.x sunos: make -e $(ALL) $(MFLAGS) XFLAGS='-DSUNOS' STATIC=-Bstatic \ XLIBS='-lresolv' # Pick this one ahead of "solaris" if you actually have the nonshared # libraries [lib*.a] on your machine. By default, the Sun twits don't ship # or install them, forcing you to use shared libs for any network apps. # Kludged for gcc, which many regard as the only thing available. solaris-static: make -e $(ALL) $(MFLAGS) XFLAGS='-DSYSV=4 -D__svr4__ -DSOLARIS' \ CC=gcc STATIC=-static XLIBS='-lnsl -lsocket -lresolv' # the more usual shared-lib version... solaris: make -e $(ALL) $(MFLAGS) XFLAGS='-DSYSV=4 -D__svr4__ -DSOLARIS' \ CC=gcc STATIC= XLIBS='-lnsl -lsocket -lresolv' aix: make -e $(ALL) $(MFLAGS) XFLAGS='-DAIX' linux: make -e $(ALL) $(MFLAGS) XFLAGS='-DLINUX' STATIC=-static # irix 5.2, dunno 'bout earlier versions. If STATIC='-non_shared' doesn't # work for you, null it out and yell at SGI for their STUPID default # of apparently not installing /usr/lib/nonshared/*. Sheesh. irix: make -e $(ALL) $(MFLAGS) XFLAGS='-DIRIX -DSYSV=4 -D__svr4__' \ STATIC=-non_shared osf: make -e $(ALL) $(MFLAGS) XFLAGS='-DOSF' STATIC=-non_shared # virtually the same as netbsd/bsd44lite/whatever freebsd: make -e $(ALL) $(MFLAGS) XFLAGS='-DFREEBSD' STATIC=-static bsdi: make -e $(ALL) $(MFLAGS) XFLAGS='-DBSDI' STATIC=-Bstatic netbsd: make -e $(ALL) $(MFLAGS) XFLAGS='-DNETBSD' STATIC=-static # finally got to an hpux box, which turns out to be *really* warped. # STATIC here means "linker subprocess gets args '-a archive'" which causes # /lib/libc.a to be searched ahead of '-a shared', or /lib/libc.sl. hpux: make -e $(ALL) $(MFLAGS) XFLAGS='-DHPUX' STATIC="-Wl,-a,archive" # unixware from [email protected]; apparently no static because of the # same idiotic lack of link libraries unixware: make -e $(ALL) $(MFLAGS) XFLAGS='-DUNIXWARE -DSYSV=4 -D__svr4__' \ STATIC= XLIBS='-L/usr/lib -lnsl -lsocket -lresolv' # from Declan Rieb at sandia, for a/ux 3.1.1 [also suggests using gcc]: aux: make -e $(ALL) $(MFLAGS) XFLAGS='-DAUX' STATIC=-static CC=gcc # Nexstep from mudge: NeXT cc is really old gcc next: make -e $(ALL) $(MFLAGS) XFLAGS='-DNEXT' STATIC=-Bstatic # start with this for a new architecture, and see what breaks. generic: make -e $(ALL) $(MFLAGS) XFLAGS='-DGENERIC' STATIC= # Still at large: dgux dynix ??? ### RANDOM clean: rm -f $(ALL) *.o *.obj
{ "pile_set_name": "Github" }
# Copyright (c) 2009 Boudewijn Rempt <[email protected]> # # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. # # - try to find glew library and include files # GLEW_INCLUDE_DIR, where to find GL/glew.h, etc. # GLEW_LIBRARIES, the libraries to link against # GLEW_FOUND, If false, do not try to use GLEW. # Also defined, but not for general use are: # GLEW_GLEW_LIBRARY = the full path to the glew library. IF (WIN32) IF(CYGWIN) FIND_PATH( GLEW_INCLUDE_DIR GL/glew.h) FIND_LIBRARY( GLEW_GLEW_LIBRARY glew32 ${OPENGL_LIBRARY_DIR} /usr/lib/w32api /usr/X11R6/lib ) ELSE(CYGWIN) FIND_PATH( GLEW_INCLUDE_DIR GL/glew.h $ENV{GLEW_ROOT_PATH}/include ) FIND_LIBRARY( GLEW_GLEW_LIBRARY NAMES glew glew32 PATHS $ENV{GLEW_ROOT_PATH}/lib ${OPENGL_LIBRARY_DIR} ) ENDIF(CYGWIN) ELSE (WIN32) IF (APPLE) # These values for Apple could probably do with improvement. FIND_PATH( GLEW_INCLUDE_DIR glew.h /System/Library/Frameworks/GLEW.framework/Versions/A/Headers ${OPENGL_LIBRARY_DIR} ) SET(GLEW_GLEW_LIBRARY "-framework GLEW" CACHE STRING "GLEW library for OSX") SET(GLEW_cocoa_LIBRARY "-framework Cocoa" CACHE STRING "Cocoa framework for OSX") ELSE (APPLE) FIND_PATH( GLEW_INCLUDE_DIR GL/glew.h /usr/include/GL /usr/openwin/share/include /usr/openwin/include /usr/X11R6/include /usr/include/X11 /opt/graphics/OpenGL/include /opt/graphics/OpenGL/contrib/libglew ) FIND_LIBRARY( GLEW_GLEW_LIBRARY GLEW /usr/openwin/lib /usr/X11R6/lib ) ENDIF (APPLE) ENDIF (WIN32) SET( GLEW_FOUND "NO" ) IF(GLEW_INCLUDE_DIR) IF(GLEW_GLEW_LIBRARY) # Is -lXi and -lXmu required on all platforms that have it? # If not, we need some way to figure out what platform we are on. SET( GLEW_LIBRARIES ${GLEW_GLEW_LIBRARY} ${GLEW_cocoa_LIBRARY} ) SET( GLEW_FOUND "YES" ) #The following deprecated settings are for backwards compatibility with CMake1.4 SET (GLEW_LIBRARY ${GLEW_LIBRARIES}) SET (GLEW_INCLUDE_PATH ${GLEW_INCLUDE_DIR}) ENDIF(GLEW_GLEW_LIBRARY) ENDIF(GLEW_INCLUDE_DIR) IF(GLEW_FOUND) IF(NOT GLEW_FIND_QUIETLY) MESSAGE(STATUS "Found Glew: ${GLEW_LIBRARIES}") ENDIF(NOT GLEW_FIND_QUIETLY) ELSE(GLEW_FOUND) IF(GLEW_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Could not find Glew") ENDIF(GLEW_FIND_REQUIRED) ENDIF(GLEW_FOUND) MARK_AS_ADVANCED( GLEW_INCLUDE_DIR GLEW_GLEW_LIBRARY GLEW_Xmu_LIBRARY GLEW_Xi_LIBRARY )
{ "pile_set_name": "Github" }
/* crypto/asn1/f_string.c */ /* Copyright (C) 1995-1998 Eric Young ([email protected]) * All rights reserved. * * This package is an SSL implementation written * by Eric Young ([email protected]). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson ([email protected]). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young ([email protected])" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson ([email protected])" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR 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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include "cryptlib.h" #include <openssl/buffer.h> #include <openssl/asn1.h> int i2a_ASN1_STRING(BIO *bp, ASN1_STRING *a, int type) { int i, n = 0; static const char *h = "0123456789ABCDEF"; char buf[2]; if (a == NULL) return (0); if (a->length == 0) { if (BIO_write(bp, "0", 1) != 1) goto err; n = 1; } else { for (i = 0; i < a->length; i++) { if ((i != 0) && (i % 35 == 0)) { if (BIO_write(bp, "\\\n", 2) != 2) goto err; n += 2; } buf[0] = h[((unsigned char)a->data[i] >> 4) & 0x0f]; buf[1] = h[((unsigned char)a->data[i]) & 0x0f]; if (BIO_write(bp, buf, 2) != 2) goto err; n += 2; } } return (n); err: return (-1); } int a2i_ASN1_STRING(BIO *bp, ASN1_STRING *bs, char *buf, int size) { int ret = 0; int i, j, k, m, n, again, bufsize; unsigned char *s = NULL, *sp; unsigned char *bufp; int num = 0, slen = 0, first = 1; bufsize = BIO_gets(bp, buf, size); for (;;) { if (bufsize < 1) { if (first) break; else goto err_sl; } first = 0; i = bufsize; if (buf[i - 1] == '\n') buf[--i] = '\0'; if (i == 0) goto err_sl; if (buf[i - 1] == '\r') buf[--i] = '\0'; if (i == 0) goto err_sl; again = (buf[i - 1] == '\\'); for (j = i - 1; j > 0; j--) { #ifndef CHARSET_EBCDIC if (!(((buf[j] >= '0') && (buf[j] <= '9')) || ((buf[j] >= 'a') && (buf[j] <= 'f')) || ((buf[j] >= 'A') && (buf[j] <= 'F')))) #else /* * This #ifdef is not strictly necessary, since the characters * A...F a...f 0...9 are contiguous (yes, even in EBCDIC - but * not the whole alphabet). Nevertheless, isxdigit() is faster. */ if (!isxdigit(buf[j])) #endif { i = j; break; } } buf[i] = '\0'; /* * We have now cleared all the crap off the end of the line */ if (i < 2) goto err_sl; bufp = (unsigned char *)buf; k = 0; i -= again; if (i % 2 != 0) { ASN1err(ASN1_F_A2I_ASN1_STRING, ASN1_R_ODD_NUMBER_OF_CHARS); goto err; } i /= 2; if (num + i > slen) { if (s == NULL) sp = (unsigned char *)OPENSSL_malloc((unsigned int)num + i * 2); else sp = (unsigned char *)OPENSSL_realloc(s, (unsigned int)num + i * 2); if (sp == NULL) { ASN1err(ASN1_F_A2I_ASN1_STRING, ERR_R_MALLOC_FAILURE); goto err; } s = sp; slen = num + i * 2; } for (j = 0; j < i; j++, k += 2) { for (n = 0; n < 2; n++) { m = bufp[k + n]; if ((m >= '0') && (m <= '9')) m -= '0'; else if ((m >= 'a') && (m <= 'f')) m = m - 'a' + 10; else if ((m >= 'A') && (m <= 'F')) m = m - 'A' + 10; else { ASN1err(ASN1_F_A2I_ASN1_STRING, ASN1_R_NON_HEX_CHARACTERS); goto err; } s[num + j] <<= 4; s[num + j] |= m; } } num += i; if (again) bufsize = BIO_gets(bp, buf, size); else break; } bs->length = num; bs->data = s; ret = 1; err: if (0) { err_sl: ASN1err(ASN1_F_A2I_ASN1_STRING, ASN1_R_SHORT_LINE); } if (ret != 1) OPENSSL_free(s); return (ret); }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: b5aadac20fc53d04abe0492399479ce5 timeCreated: 1528580594 licenseType: Free MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
using System.ComponentModel; using Bing.Admin.Service.Extensions; using Bing.AspNetCore; using Bing.Core.Modularity; using Bing.Permissions.Extensions; using Microsoft.Extensions.DependencyInjection; namespace Bing.Admin.Modules { /// <summary> /// 身份认证模块 /// </summary> [Description("身份认证模块")] [DependsOnModule(typeof(AspNetCoreModule))] public class AuthenticationModule : AspNetCoreBingModule { /// <summary> /// 模块级别。级别越小越先启动 /// </summary> public override ModuleLevel Level => ModuleLevel.Application; /// <summary> /// 模块启动顺序。模块启动的顺序先按级别启动,同一级别内部再按此顺序启动, /// 级别默认为0,表示无依赖,需要在同级别有依赖顺序的时候,再重写为>0的顺序值 /// </summary> public override int Order => 1; /// <summary> /// 添加服务。将模块服务添加到依赖注入服务容器中 /// </summary> /// <param name="services">服务集合</param> public override IServiceCollection AddServices(IServiceCollection services) { var configuration = services.GetConfiguration(); // 添加权限服务 services.AddPermission(o => { o.Store.StoreOriginalPassword = true; o.Password.MinLength = 6; }); // 添加Jwt认证 services.AddJwt(configuration); return services; } } }
{ "pile_set_name": "Github" }
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif
{ "pile_set_name": "Github" }
{ "images" : [ { "idiom" : "universal", "scale" : "1x" }, { "idiom" : "universal", "scale" : "2x" }, { "idiom" : "universal", "filename" : "[email protected]", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } }
{ "pile_set_name": "Github" }
// fast brush painter for composition modes which can be implemented with blendfuncs // no mask, used for fast filling of aliased primitives (or multisampled) void main() { gl_FragColor = brush(); }
{ "pile_set_name": "Github" }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "hiredis.h" int main(void) { unsigned int j; redisContext *c; redisReply *reply; struct timeval timeout = { 1, 500000 }; // 1.5 seconds c = redisConnectWithTimeout((char*)"127.0.0.2", 6379, timeout); if (c->err) { printf("Connection error: %s\n", c->errstr); exit(1); } /* PING server */ reply = redisCommand(c,"PING"); printf("PING: %s\n", reply->str); freeReplyObject(reply); /* Set a key */ reply = redisCommand(c,"SET %s %s", "foo", "hello world"); printf("SET: %s\n", reply->str); freeReplyObject(reply); /* Set a key using binary safe API */ reply = redisCommand(c,"SET %b %b", "bar", 3, "hello", 5); printf("SET (binary API): %s\n", reply->str); freeReplyObject(reply); /* Try a GET and two INCR */ reply = redisCommand(c,"GET foo"); printf("GET foo: %s\n", reply->str); freeReplyObject(reply); reply = redisCommand(c,"INCR counter"); printf("INCR counter: %lld\n", reply->integer); freeReplyObject(reply); /* again ... */ reply = redisCommand(c,"INCR counter"); printf("INCR counter: %lld\n", reply->integer); freeReplyObject(reply); /* Create a list of numbers, from 0 to 9 */ reply = redisCommand(c,"DEL mylist"); freeReplyObject(reply); for (j = 0; j < 10; j++) { char buf[64]; snprintf(buf,64,"%d",j); reply = redisCommand(c,"LPUSH mylist element-%s", buf); freeReplyObject(reply); } /* Let's check what we have inside the list */ reply = redisCommand(c,"LRANGE mylist 0 -1"); if (reply->type == REDIS_REPLY_ARRAY) { for (j = 0; j < reply->elements; j++) { printf("%u) %s\n", j, reply->element[j]->str); } } freeReplyObject(reply); return 0; }
{ "pile_set_name": "Github" }
function M = UpdateIndices_Manual(hfig,cIX,gIX,numK) setappdata(hfig,'cIX',cIX); setappdata(hfig,'gIX',gIX); M = GetTimeIndexedData(hfig); % M_0 = GetTimeIndexedData(hfig,'isAllCells'); setappdata(hfig,'M',M); if exist('numK','var'), setappdata(hfig,'numK',double(numK)); end
{ "pile_set_name": "Github" }
/* * Copyright 2006-2012 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.batch.item.database.support; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.batch.item.database.Order; import org.springframework.util.StringUtils; /** * Generic Paging Query Provider using standard SQL:2003 windowing functions. * These features are supported by DB2, Oracle, SQL Server 2005, Sybase and * Apache Derby version 10.4.1.3 * * @author Thomas Risberg * @author Michael Minella * @since 2.0 */ public class SqlWindowingPagingQueryProvider extends AbstractSqlPagingQueryProvider { @Override public String generateFirstPageQuery(int pageSize) { StringBuilder sql = new StringBuilder(); sql.append("SELECT * FROM ( "); sql.append("SELECT ").append(StringUtils.hasText(getOrderedQueryAlias()) ? getOrderedQueryAlias() + ".*, " : "*, "); sql.append("ROW_NUMBER() OVER (").append(getOverClause()); sql.append(") AS ROW_NUMBER"); sql.append(getOverSubstituteClauseStart()); sql.append(" FROM ").append(getFromClause()).append( getWhereClause() == null ? "" : " WHERE " + getWhereClause()); sql.append(getGroupClause() == null ? "" : " GROUP BY " + getGroupClause()); sql.append(getOverSubstituteClauseEnd()); sql.append(") ").append(getSubQueryAlias()).append("WHERE ").append(extractTableAlias()).append( "ROW_NUMBER <= ").append(pageSize); sql.append(" ORDER BY ").append(SqlPagingQueryUtils.buildSortClause(this)); return sql.toString(); } protected String getOrderedQueryAlias() { return ""; } protected Object getSubQueryAlias() { return "AS TMP_SUB "; } protected Object extractTableAlias() { String alias = "" + getSubQueryAlias(); if (StringUtils.hasText(alias) && alias.toUpperCase().startsWith("AS")) { alias = alias.substring(3).trim() + "."; } return alias; } @Override public String generateRemainingPagesQuery(int pageSize) { StringBuilder sql = new StringBuilder(); sql.append("SELECT * FROM ( "); sql.append("SELECT ").append(StringUtils.hasText(getOrderedQueryAlias()) ? getOrderedQueryAlias() + ".*, " : "*, "); sql.append("ROW_NUMBER() OVER (").append(getOverClause()); sql.append(") AS ROW_NUMBER"); sql.append(getOverSubstituteClauseStart()); sql.append(" FROM ").append(getFromClause()); if (getWhereClause() != null) { sql.append(" WHERE "); sql.append(getWhereClause()); } sql.append(getGroupClause() == null ? "" : " GROUP BY " + getGroupClause()); sql.append(getOverSubstituteClauseEnd()); sql.append(") ").append(getSubQueryAlias()).append("WHERE ").append(extractTableAlias()).append( "ROW_NUMBER <= ").append(pageSize); sql.append(" AND "); SqlPagingQueryUtils.buildSortConditions(this, sql); sql.append(" ORDER BY ").append(SqlPagingQueryUtils.buildSortClause(this)); return sql.toString(); } @Override public String generateJumpToItemQuery(int itemIndex, int pageSize) { int page = itemIndex / pageSize; int lastRowNum = (page * pageSize); if (lastRowNum <= 0) { lastRowNum = 1; } StringBuilder sql = new StringBuilder(); sql.append("SELECT "); buildSortKeySelect(sql, getSortKeysReplaced(extractTableAlias())); sql.append(" FROM ( "); sql.append("SELECT "); buildSortKeySelect(sql); sql.append(", ROW_NUMBER() OVER (").append(getOverClause()); sql.append(") AS ROW_NUMBER"); sql.append(getOverSubstituteClauseStart()); sql.append(" FROM ").append(getFromClause()); sql.append(getWhereClause() == null ? "" : " WHERE " + getWhereClause()); sql.append(getGroupClause() == null ? "" : " GROUP BY " + getGroupClause()); sql.append(getOverSubstituteClauseEnd()); sql.append(") ").append(getSubQueryAlias()).append("WHERE ").append(extractTableAlias()).append( "ROW_NUMBER = ").append(lastRowNum); sql.append(" ORDER BY ").append(SqlPagingQueryUtils.buildSortClause(getSortKeysReplaced(extractTableAlias()))); return sql.toString(); } private Map<String, Order> getSortKeysReplaced(Object qualifierReplacement) { final String newQualifier = "" + qualifierReplacement; final Map<String, Order> sortKeys = new LinkedHashMap<>(); for (Map.Entry<String, Order> sortKey : getSortKeys().entrySet()) { sortKeys.put(sortKey.getKey().replaceFirst("^.*\\.", newQualifier), sortKey.getValue()); } return sortKeys; } private void buildSortKeySelect(StringBuilder sql) { buildSortKeySelect(sql, null); } private void buildSortKeySelect(StringBuilder sql, Map<String, Order> sortKeys) { String prefix = ""; if (sortKeys == null) { sortKeys = getSortKeys(); } for (Map.Entry<String, Order> sortKey : sortKeys.entrySet()) { sql.append(prefix); prefix = ", "; sql.append(sortKey.getKey()); } } protected String getOverClause() { StringBuilder sql = new StringBuilder(); sql.append(" ORDER BY ").append(buildSortClause(this)); return sql.toString(); } protected String getOverSubstituteClauseStart() { return ""; } protected String getOverSubstituteClauseEnd() { return ""; } /** * Generates ORDER BY attributes based on the sort keys. * * @param provider * @return a String that can be appended to an ORDER BY clause. */ private String buildSortClause(AbstractSqlPagingQueryProvider provider) { return SqlPagingQueryUtils.buildSortClause(provider.getSortKeysWithoutAliases()); } }
{ "pile_set_name": "Github" }
/* TA-LIB Copyright (c) 1999-2007, Mario Fortier * 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 name of author 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 * REGENTS 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. */ /* List of contributors: * * Initial Name/description * ------------------------------------------------------------------- * AC Angelo Ciceri * * * Change history: * * MMDDYY BY Description * ------------------------------------------------------------------- * 022005 AC Creation * */ /**** START GENCODE SECTION 1 - DO NOT DELETE THIS LINE ****/ /* All code within this section is automatically * generated by gen_code. Any modification will be lost * next time gen_code is run. */ /* Generated */ /* Generated */ #if defined( _MANAGED ) /* Generated */ #include "TA-Lib-Core.h" /* Generated */ #define TA_INTERNAL_ERROR(Id) (RetCode::InternalError) /* Generated */ namespace TicTacTec { namespace TA { namespace Library { /* Generated */ #elif defined( _JAVA ) /* Generated */ #include "ta_defs.h" /* Generated */ #include "ta_java_defs.h" /* Generated */ #define TA_INTERNAL_ERROR(Id) (RetCode.InternalError) /* Generated */ #else /* Generated */ #include <string.h> /* Generated */ #include <math.h> /* Generated */ #include "ta_func.h" /* Generated */ #endif /* Generated */ /* Generated */ #ifndef TA_UTILITY_H /* Generated */ #include "ta_utility.h" /* Generated */ #endif /* Generated */ /* Generated */ #ifndef TA_MEMORY_H /* Generated */ #include "ta_memory.h" /* Generated */ #endif /* Generated */ /* Generated */ #define TA_PREFIX(x) TA_##x /* Generated */ #define INPUT_TYPE double /* Generated */ /* Generated */ #if defined( _MANAGED ) /* Generated */ int Core::CdlMatHoldLookback( double optInPenetration ) /* From 0 to TA_REAL_MAX */ /* Generated */ /* Generated */ #elif defined( _JAVA ) /* Generated */ public int cdlMatHoldLookback( double optInPenetration ) /* From 0 to TA_REAL_MAX */ /* Generated */ /* Generated */ #else /* Generated */ int TA_CDLMATHOLD_Lookback( double optInPenetration ) /* From 0 to TA_REAL_MAX */ /* Generated */ /* Generated */ #endif /**** END GENCODE SECTION 1 - DO NOT DELETE THIS LINE ****/ { /* insert local variable here */ /**** START GENCODE SECTION 2 - DO NOT DELETE THIS LINE ****/ /* Generated */ #ifndef TA_FUNC_NO_RANGE_CHECK /* Generated */ if( optInPenetration == TA_REAL_DEFAULT ) /* Generated */ optInPenetration = 5.000000e-1; /* Generated */ else if( (optInPenetration < 0.000000e+0) ||/* Generated */ (optInPenetration > 3.000000e+37) ) /* Generated */ return -1; /* Generated */ /* Generated */ #endif /* TA_FUNC_NO_RANGE_CHECK */ /**** END GENCODE SECTION 2 - DO NOT DELETE THIS LINE ****/ /* insert lookback code here. */ UNUSED_VARIABLE(optInPenetration); return max( TA_CANDLEAVGPERIOD(BodyShort), TA_CANDLEAVGPERIOD(BodyLong) ) + 4; } /**** START GENCODE SECTION 3 - DO NOT DELETE THIS LINE ****/ /* * TA_CDLMATHOLD - Mat Hold * * Input = Open, High, Low, Close * Output = int * * Optional Parameters * ------------------- * optInPenetration:(From 0 to TA_REAL_MAX) * Percentage of penetration of a candle within another candle * * */ /* Generated */ /* Generated */ #if defined( _MANAGED ) && defined( USE_SUBARRAY ) /* Generated */ enum class Core::RetCode Core::CdlMatHold( int startIdx, /* Generated */ int endIdx, /* Generated */ SubArray^ inOpen, /* Generated */ SubArray^ inHigh, /* Generated */ SubArray^ inLow, /* Generated */ SubArray^ inClose, /* Generated */ double optInPenetration, /* From 0 to TA_REAL_MAX */ /* Generated */ [Out]int% outBegIdx, /* Generated */ [Out]int% outNBElement, /* Generated */ cli::array<int>^ outInteger ) /* Generated */ #elif defined( _MANAGED ) /* Generated */ enum class Core::RetCode Core::CdlMatHold( int startIdx, /* Generated */ int endIdx, /* Generated */ cli::array<double>^ inOpen, /* Generated */ cli::array<double>^ inHigh, /* Generated */ cli::array<double>^ inLow, /* Generated */ cli::array<double>^ inClose, /* Generated */ double optInPenetration, /* From 0 to TA_REAL_MAX */ /* Generated */ [Out]int% outBegIdx, /* Generated */ [Out]int% outNBElement, /* Generated */ cli::array<int>^ outInteger ) /* Generated */ #elif defined( _JAVA ) /* Generated */ public RetCode cdlMatHold( int startIdx, /* Generated */ int endIdx, /* Generated */ double inOpen[], /* Generated */ double inHigh[], /* Generated */ double inLow[], /* Generated */ double inClose[], /* Generated */ double optInPenetration, /* From 0 to TA_REAL_MAX */ /* Generated */ MInteger outBegIdx, /* Generated */ MInteger outNBElement, /* Generated */ int outInteger[] ) /* Generated */ #else /* Generated */ TA_RetCode TA_CDLMATHOLD( int startIdx, /* Generated */ int endIdx, /* Generated */ const double inOpen[], /* Generated */ const double inHigh[], /* Generated */ const double inLow[], /* Generated */ const double inClose[], /* Generated */ double optInPenetration, /* From 0 to TA_REAL_MAX */ /* Generated */ int *outBegIdx, /* Generated */ int *outNBElement, /* Generated */ int outInteger[] ) /* Generated */ #endif /**** END GENCODE SECTION 3 - DO NOT DELETE THIS LINE ****/ { /* Insert local variables here. */ ARRAY_LOCAL(BodyPeriodTotal,5); int i, outIdx, totIdx, BodyShortTrailingIdx, BodyLongTrailingIdx, lookbackTotal; /**** START GENCODE SECTION 4 - DO NOT DELETE THIS LINE ****/ /* Generated */ /* Generated */ #ifndef TA_FUNC_NO_RANGE_CHECK /* Generated */ /* Generated */ /* Validate the requested output range. */ /* Generated */ if( startIdx < 0 ) /* Generated */ return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_START_INDEX,OutOfRangeStartIndex); /* Generated */ if( (endIdx < 0) || (endIdx < startIdx)) /* Generated */ return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_END_INDEX,OutOfRangeEndIndex); /* Generated */ /* Generated */ #if !defined(_JAVA) /* Generated */ /* Verify required price component. */ /* Generated */ if(!inOpen||!inHigh||!inLow||!inClose) /* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam); /* Generated */ /* Generated */ #endif /* !defined(_JAVA)*/ /* Generated */ if( optInPenetration == TA_REAL_DEFAULT ) /* Generated */ optInPenetration = 5.000000e-1; /* Generated */ else if( (optInPenetration < 0.000000e+0) ||/* Generated */ (optInPenetration > 3.000000e+37) ) /* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam); /* Generated */ /* Generated */ #if !defined(_JAVA) /* Generated */ if( !outInteger ) /* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam); /* Generated */ /* Generated */ #endif /* !defined(_JAVA) */ /* Generated */ #endif /* TA_FUNC_NO_RANGE_CHECK */ /* Generated */ /**** END GENCODE SECTION 4 - DO NOT DELETE THIS LINE ****/ /* Identify the minimum number of price bar needed * to calculate at least one output. */ lookbackTotal = LOOKBACK_CALL(CDLMATHOLD)(optInPenetration); /* Move up the start index if there is not * enough initial data. */ if( startIdx < lookbackTotal ) startIdx = lookbackTotal; /* Make sure there is still something to evaluate. */ if( startIdx > endIdx ) { VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx); VALUE_HANDLE_DEREF_TO_ZERO(outNBElement); return ENUM_VALUE(RetCode,TA_SUCCESS,Success); } /* Do the calculation using tight loops. */ /* Add-up the initial period, except for the last value. */ BodyPeriodTotal[4] = 0; BodyPeriodTotal[3] = 0; BodyPeriodTotal[2] = 0; BodyPeriodTotal[1] = 0; BodyPeriodTotal[0] = 0; BodyShortTrailingIdx = startIdx - TA_CANDLEAVGPERIOD(BodyShort); BodyLongTrailingIdx = startIdx - TA_CANDLEAVGPERIOD(BodyLong); i = BodyShortTrailingIdx; while( i < startIdx ) { BodyPeriodTotal[3] += TA_CANDLERANGE( BodyShort, i-3 ); BodyPeriodTotal[2] += TA_CANDLERANGE( BodyShort, i-2 ); BodyPeriodTotal[1] += TA_CANDLERANGE( BodyShort, i-1 ); i++; } i = BodyLongTrailingIdx; while( i < startIdx ) { BodyPeriodTotal[4] += TA_CANDLERANGE( BodyLong, i-4 ); i++; } i = startIdx; /* Proceed with the calculation for the requested range. * Must have: * - first candle: long white candle * - upside gap between the first and the second bodies * - second candle: small black candle * - third and fourth candles: falling small real body candlesticks (commonly black) that hold within the long * white candle's body and are higher than the reaction days of the rising three methods * - fifth candle: white candle that opens above the previous small candle's close and closes higher than the * high of the highest reaction day * The meaning of "short" and "long" is specified with TA_SetCandleSettings; * "hold within" means "a part of the real body must be within"; * optInPenetration is the maximum percentage of the first white body the reaction days can penetrate (it is * to specify how much the reaction days should be "higher than the reaction days of the rising three methods") * outInteger is positive (1 to 100): mat hold is always bullish */ outIdx = 0; do { if( // 1st long, then 3 small TA_REALBODY(i-4) > TA_CANDLEAVERAGE( BodyLong, BodyPeriodTotal[4], i-4 ) && TA_REALBODY(i-3) < TA_CANDLEAVERAGE( BodyShort, BodyPeriodTotal[3], i-3 ) && TA_REALBODY(i-2) < TA_CANDLEAVERAGE( BodyShort, BodyPeriodTotal[2], i-2 ) && TA_REALBODY(i-1) < TA_CANDLEAVERAGE( BodyShort, BodyPeriodTotal[1], i-1 ) && // white, black, 2 black or white, white TA_CANDLECOLOR(i-4) == 1 && TA_CANDLECOLOR(i-3) == -1 && TA_CANDLECOLOR(i) == 1 && // upside gap 1st to 2nd TA_REALBODYGAPUP(i-3,i-4) && // 3rd to 4th hold within 1st: a part of the real body must be within 1st real body min(inOpen[i-2], inClose[i-2]) < inClose[i-4] && min(inOpen[i-1], inClose[i-1]) < inClose[i-4] && // reaction days penetrate first body less than optInPenetration percent min(inOpen[i-2], inClose[i-2]) > inClose[i-4] - TA_REALBODY(i-4) * optInPenetration && min(inOpen[i-1], inClose[i-1]) > inClose[i-4] - TA_REALBODY(i-4) * optInPenetration && // 2nd to 4th are falling max(inClose[i-2], inOpen[i-2]) < inOpen[i-3] && max(inClose[i-1], inOpen[i-1]) < max(inClose[i-2], inOpen[i-2]) && // 5th opens above the prior close inOpen[i] > inClose[i-1] && // 5th closes above the highest high of the reaction days inClose[i] > max(max(inHigh[i-3], inHigh[i-2]), inHigh[i-1]) ) outInteger[outIdx++] = 100; else outInteger[outIdx++] = 0; /* add the current range and subtract the first range: this is done after the pattern recognition * when avgPeriod is not 0, that means "compare with the previous candles" (it excludes the current candle) */ BodyPeriodTotal[4] += TA_CANDLERANGE( BodyLong, i-4 ) - TA_CANDLERANGE( BodyLong, BodyLongTrailingIdx-4 ); for (totIdx = 3; totIdx >= 1; --totIdx) BodyPeriodTotal[totIdx] += TA_CANDLERANGE( BodyShort, i-totIdx ) - TA_CANDLERANGE( BodyShort, BodyShortTrailingIdx-totIdx ); i++; BodyShortTrailingIdx++; BodyLongTrailingIdx++; } while( i <= endIdx ); /* All done. Indicate the output limits and return. */ VALUE_HANDLE_DEREF(outNBElement) = outIdx; VALUE_HANDLE_DEREF(outBegIdx) = startIdx; return ENUM_VALUE(RetCode,TA_SUCCESS,Success); } /**** START GENCODE SECTION 5 - DO NOT DELETE THIS LINE ****/ /* Generated */ /* Generated */ #define USE_SINGLE_PRECISION_INPUT /* Generated */ #if !defined( _MANAGED ) && !defined( _JAVA ) /* Generated */ #undef TA_PREFIX /* Generated */ #define TA_PREFIX(x) TA_S_##x /* Generated */ #endif /* Generated */ #undef INPUT_TYPE /* Generated */ #define INPUT_TYPE float /* Generated */ #if defined( _MANAGED ) /* Generated */ enum class Core::RetCode Core::CdlMatHold( int startIdx, /* Generated */ int endIdx, /* Generated */ cli::array<float>^ inOpen, /* Generated */ cli::array<float>^ inHigh, /* Generated */ cli::array<float>^ inLow, /* Generated */ cli::array<float>^ inClose, /* Generated */ double optInPenetration, /* From 0 to TA_REAL_MAX */ /* Generated */ [Out]int% outBegIdx, /* Generated */ [Out]int% outNBElement, /* Generated */ cli::array<int>^ outInteger ) /* Generated */ #elif defined( _JAVA ) /* Generated */ public RetCode cdlMatHold( int startIdx, /* Generated */ int endIdx, /* Generated */ float inOpen[], /* Generated */ float inHigh[], /* Generated */ float inLow[], /* Generated */ float inClose[], /* Generated */ double optInPenetration, /* From 0 to TA_REAL_MAX */ /* Generated */ MInteger outBegIdx, /* Generated */ MInteger outNBElement, /* Generated */ int outInteger[] ) /* Generated */ #else /* Generated */ TA_RetCode TA_S_CDLMATHOLD( int startIdx, /* Generated */ int endIdx, /* Generated */ const float inOpen[], /* Generated */ const float inHigh[], /* Generated */ const float inLow[], /* Generated */ const float inClose[], /* Generated */ double optInPenetration, /* From 0 to TA_REAL_MAX */ /* Generated */ int *outBegIdx, /* Generated */ int *outNBElement, /* Generated */ int outInteger[] ) /* Generated */ #endif /* Generated */ { /* Generated */ ARRAY_LOCAL(BodyPeriodTotal,5); /* Generated */ int i, outIdx, totIdx, BodyShortTrailingIdx, BodyLongTrailingIdx, lookbackTotal; /* Generated */ #ifndef TA_FUNC_NO_RANGE_CHECK /* Generated */ if( startIdx < 0 ) /* Generated */ return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_START_INDEX,OutOfRangeStartIndex); /* Generated */ if( (endIdx < 0) || (endIdx < startIdx)) /* Generated */ return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_END_INDEX,OutOfRangeEndIndex); /* Generated */ #if !defined(_JAVA) /* Generated */ if(!inOpen||!inHigh||!inLow||!inClose) /* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam); /* Generated */ #endif /* Generated */ if( optInPenetration == TA_REAL_DEFAULT ) /* Generated */ optInPenetration = 5.000000e-1; /* Generated */ else if( (optInPenetration < 0.000000e+0) || (optInPenetration > 3.000000e+37) ) /* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam); /* Generated */ #if !defined(_JAVA) /* Generated */ if( !outInteger ) /* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam); /* Generated */ #endif /* Generated */ #endif /* Generated */ lookbackTotal = LOOKBACK_CALL(CDLMATHOLD)(optInPenetration); /* Generated */ if( startIdx < lookbackTotal ) /* Generated */ startIdx = lookbackTotal; /* Generated */ if( startIdx > endIdx ) /* Generated */ { /* Generated */ VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx); /* Generated */ VALUE_HANDLE_DEREF_TO_ZERO(outNBElement); /* Generated */ return ENUM_VALUE(RetCode,TA_SUCCESS,Success); /* Generated */ } /* Generated */ BodyPeriodTotal[4] = 0; /* Generated */ BodyPeriodTotal[3] = 0; /* Generated */ BodyPeriodTotal[2] = 0; /* Generated */ BodyPeriodTotal[1] = 0; /* Generated */ BodyPeriodTotal[0] = 0; /* Generated */ BodyShortTrailingIdx = startIdx - TA_CANDLEAVGPERIOD(BodyShort); /* Generated */ BodyLongTrailingIdx = startIdx - TA_CANDLEAVGPERIOD(BodyLong); /* Generated */ i = BodyShortTrailingIdx; /* Generated */ while( i < startIdx ) { /* Generated */ BodyPeriodTotal[3] += TA_CANDLERANGE( BodyShort, i-3 ); /* Generated */ BodyPeriodTotal[2] += TA_CANDLERANGE( BodyShort, i-2 ); /* Generated */ BodyPeriodTotal[1] += TA_CANDLERANGE( BodyShort, i-1 ); /* Generated */ i++; /* Generated */ } /* Generated */ i = BodyLongTrailingIdx; /* Generated */ while( i < startIdx ) { /* Generated */ BodyPeriodTotal[4] += TA_CANDLERANGE( BodyLong, i-4 ); /* Generated */ i++; /* Generated */ } /* Generated */ i = startIdx; /* Generated */ outIdx = 0; /* Generated */ do /* Generated */ { /* Generated */ if( // 1st long, then 3 small /* Generated */ TA_REALBODY(i-4) > TA_CANDLEAVERAGE( BodyLong, BodyPeriodTotal[4], i-4 ) && /* Generated */ TA_REALBODY(i-3) < TA_CANDLEAVERAGE( BodyShort, BodyPeriodTotal[3], i-3 ) && /* Generated */ TA_REALBODY(i-2) < TA_CANDLEAVERAGE( BodyShort, BodyPeriodTotal[2], i-2 ) && /* Generated */ TA_REALBODY(i-1) < TA_CANDLEAVERAGE( BodyShort, BodyPeriodTotal[1], i-1 ) && /* Generated */ // white, black, 2 black or white, white /* Generated */ TA_CANDLECOLOR(i-4) == 1 && /* Generated */ TA_CANDLECOLOR(i-3) == -1 && /* Generated */ TA_CANDLECOLOR(i) == 1 && /* Generated */ // upside gap 1st to 2nd /* Generated */ TA_REALBODYGAPUP(i-3,i-4) && /* Generated */ // 3rd to 4th hold within 1st: a part of the real body must be within 1st real body /* Generated */ min(inOpen[i-2], inClose[i-2]) < inClose[i-4] && /* Generated */ min(inOpen[i-1], inClose[i-1]) < inClose[i-4] && /* Generated */ // reaction days penetrate first body less than optInPenetration percent /* Generated */ min(inOpen[i-2], inClose[i-2]) > inClose[i-4] - TA_REALBODY(i-4) * optInPenetration && /* Generated */ min(inOpen[i-1], inClose[i-1]) > inClose[i-4] - TA_REALBODY(i-4) * optInPenetration && /* Generated */ // 2nd to 4th are falling /* Generated */ max(inClose[i-2], inOpen[i-2]) < inOpen[i-3] && /* Generated */ max(inClose[i-1], inOpen[i-1]) < max(inClose[i-2], inOpen[i-2]) && /* Generated */ // 5th opens above the prior close /* Generated */ inOpen[i] > inClose[i-1] && /* Generated */ // 5th closes above the highest high of the reaction days /* Generated */ inClose[i] > max(max(inHigh[i-3], inHigh[i-2]), inHigh[i-1]) /* Generated */ ) /* Generated */ outInteger[outIdx++] = 100; /* Generated */ else /* Generated */ outInteger[outIdx++] = 0; /* Generated */ BodyPeriodTotal[4] += TA_CANDLERANGE( BodyLong, i-4 ) - TA_CANDLERANGE( BodyLong, BodyLongTrailingIdx-4 ); /* Generated */ for (totIdx = 3; totIdx >= 1; --totIdx) /* Generated */ BodyPeriodTotal[totIdx] += TA_CANDLERANGE( BodyShort, i-totIdx ) /* Generated */ - TA_CANDLERANGE( BodyShort, BodyShortTrailingIdx-totIdx ); /* Generated */ i++; /* Generated */ BodyShortTrailingIdx++; /* Generated */ BodyLongTrailingIdx++; /* Generated */ } while( i <= endIdx ); /* Generated */ VALUE_HANDLE_DEREF(outNBElement) = outIdx; /* Generated */ VALUE_HANDLE_DEREF(outBegIdx) = startIdx; /* Generated */ return ENUM_VALUE(RetCode,TA_SUCCESS,Success); /* Generated */ } /* Generated */ /* Generated */ #if defined( _MANAGED ) /* Generated */ }}} // Close namespace TicTacTec.TA.Lib /* Generated */ #endif /**** END GENCODE SECTION 5 - DO NOT DELETE THIS LINE ****/
{ "pile_set_name": "Github" }
<?xml version='1.0' encoding='UTF-8'?> <!-- This document was created with Syntext Serna Free. --><!DOCTYPE map PUBLIC "-//OASIS//DTD DITA Map//EN" "http://docs.oasis-open.org/dita/v1.1/OS/dtd/map.dtd" []> <map> <title>Requirement Specification</title> <topicmeta> <author>Ratnadip Choudhury</author> <copyright> <copyryear year="2011"/> <copyrholder>ROBERT BOSCH ENGINEERING AND BUSINESS SOLUTIONS LIMITED</copyrholder> </copyright> </topicmeta> <topicref href="topics/license_information.dita" type="topic" toc="no"/> <topicref href="topics/acknowledgement.dita" type="topic" toc="no"/> <topicref href="topics/abbreviations.dita" type="topic" toc="no"/> <topicref href="topics/prolegomena.dita" type="topic"> <topicref href="topics/purpose_of_the_document.dita" type="topic"/> <topicref href="topics/project_scope.dita" type="topic"/> <topicref href="topics/tagging.dita" type="topic"/> <topicref href="topics/definitions_acronyms_and_abbreviations.dita" type="topic"/> <topicref href="topics/references.dita" type="topic"/> </topicref> <topicref href="topics/software_requirements.dita" type="topic"> <topicref href="topics/operational_requirements.dita" type="topic"/> <topicref href="topics/functional_requirements.dita" type="topic"> <topicref href="topics/dil_interface.dita" type="topic"/> <topicref href="topics/dil_can.dita" type="topic"/> <topicref href="topics/simulation_engine_stub_component.dita" type="topic"/> <topicref href="topics/project_configuration_library.dita" type="topic"/> <topicref href="topics/frame_logger.dita" type="topic"/> <topicref href="topics/message_window.dita" type="topic"/> <topicref href="topics/node_simulation.dita" type="topic"/> <topicref href="topics/frame_transmission.dita" type="topic"/> <topicref href="topics/session_replay.dita" type="topic"/> <topicref href="topics/filter.dita" type="topic"/> <topicref href="topics/signal_watch_window.dita" type="topic"/> <topicref href="topics/signal_graph_window_fr.dita" type="topic"/> <topicref href="topics/j1939_basic.dita" type="topic"/> <topicref href="topics/test_automation_fr.dita" type="topic"/> <topicref href="topics/bus_statistics_window.dita" type="topic"/> <topicref href="topics/installer.dita" type="topic"/> </topicref> <topicref href="topics/user_interface_requirements.dita" type="topic"> <topicref href="topics/general_requirements.dita" type="topic"/> <topicref href="topics/test_automation_uir.dita" type="topic"/> </topicref> <topicref href="topics/external_interface_requirements.dita" type="topic"/> </topicref> <topicref href="topics/interface_details.dita" type="topic"> <topicref href="topics/simulation_engine.dita" type="topic"/> <topicref href="topics/signal_graph_window_id.dita" type="topic"/> <topicref href="topics/idil_can.dita" type="topic"/> <topicref href="topics/idil_j1939.dita" type="topic"/> </topicref> <topicref href="topics/project_execution_requirements.dita" type="topic"> <topicref href="topics/development_environment.dita" type="topic"/> <topicref href="topics/error_handling_requirements.dita" type="topic"/> <topicref href="topics/resource_requirements.dita" type="topic"/> </topicref> <topicref href="topics/testing_requirements.dita" type="topic"/> <topicref href="topics/performance_requirements.dita" type="topic"/> <topicref href="topics/software_release_criteria.dita" type="topic"/> <topicref href="topics/annexures.dita" type="topic"/> </map>
{ "pile_set_name": "Github" }
.. |br| raw:: html <br /> Configuration ------------- .. csv-table:: :header: "Variable", "Default", "Tunable", "Description" :align: left :widths: auto "frame_time", "0.03333333", "NO", "Inter frame time in seconds. The generated timestamps will have the specified |br|\ number of seconds in the generated timestamps for sequential frames. This can be |br|\ used to simulate a frame rate in a video stream application." "image_list_file", "(no default value)", "NO", "Name of file that contains list of image file names. Each line in the file |br|\ specifies the name of a single image file." "image_reader", "(no default value)", "NO", "Algorithm configuration subblock" "path", "(no default value)", "NO", "Path to search for image file. The format is the same as the standard path |br|\ specification, a set of directories separated by a colon (':')" Input Ports ----------- There are no input ports for this process. Output Ports ------------ .. csv-table:: :header: "Port name", "Data Type", "Flags", "Description" :align: left :widths: auto "image", "kwiver:image", "(none)", "Single frame image." "image_file_name", "kwiver:image_file_name", "(none)", "Name of an image file. The file name may contain leading path components." "timestamp", "kwiver:timestamp", "(none)", "Timestamp for input image." Pipefile Usage -------------- The following sections describe the blocks needed to use this process in a pipe file. Pipefile block -------------- .. code:: # ================================================================ process <this-proc> :: frame_list_input # Inter frame time in seconds. The generated timestamps will have the specified # number of seconds in the generated timestamps for sequential frames. This can # be used to simulate a frame rate in a video stream application. frame_time = 0.03333333 # Name of file that contains list of image file names. Each line in the file # specifies the name of a single image file. image_list_file = <value> # Algorithm configuration subblock image_reader = <value> # Path to search for image file. The format is the same as the standard path # specification, a set of directories separated by a colon (':') path = <value> # ================================================================ Process connections ~~~~~~~~~~~~~~~~~~~ The following Input ports will need to be set ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code:: # There are no input port's for this process The following Output ports will need to be set ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code:: # This process will produce the following output ports connect from <this-proc>.image to <downstream-proc>.image connect from <this-proc>.image_file_name to <downstream-proc>.image_file_name connect from <this-proc>.timestamp to <downstream-proc>.timestamp Class Description ----------------- .. doxygenclass:: kwiver::frame_list_process :project: kwiver :members:
{ "pile_set_name": "Github" }
/** * @fileoverview Rule to flag usage of __iterator__ property * @author Ian Christian Myers */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "disallow the use of the `__iterator__` property", category: "Best Practices", recommended: false, url: "https://eslint.org/docs/rules/no-iterator" }, schema: [] }, create(context) { return { MemberExpression(node) { if (node.property && (node.property.type === "Identifier" && node.property.name === "__iterator__" && !node.computed) || (node.property.type === "Literal" && node.property.value === "__iterator__")) { context.report({ node, message: "Reserved name '__iterator__'." }); } } }; } };
{ "pile_set_name": "Github" }
import unittest import uuid from datetime import datetime, timedelta from django.test import TestCase from mygpo.podcasts.models import Podcast, Episode def create_podcast(**kwargs): return Podcast.objects.create(id=uuid.uuid1(), **kwargs) class PodcastTests(unittest.TestCase): """ Test podcasts and their properties """ def test_next_update(self): """ Test calculation of Podcast.next_update """ last_update = datetime(2014, 3, 31, 11, 00) update_interval = 123 # hours # create an "old" podcast with update-information create_podcast(last_update=last_update, update_interval=update_interval) # the podcast should be the next to be updated p = Podcast.objects.all().order_by_next_update().first() # assert that the next_update property is calculated correctly self.assertEqual(p.next_update, last_update + timedelta(hours=update_interval)) def test_get_or_create_for_url(self): """ Test that get_or_create_for_url returns existing Podcast """ URL = 'http://example.com/get_or_create.rss' p1 = Podcast.objects.get_or_create_for_url(URL).object p2 = Podcast.objects.get_or_create_for_url(URL).object self.assertEqual(p1.pk, p2.pk) def test_episode_count(self): """ Test if Podcast.episode_count is updated correctly """ PODCAST_URL = 'http://example.com/podcast.rss' EPISODE_URL = 'http://example.com/episode%d.mp3' NUM_EPISODES = 3 p = Podcast.objects.get_or_create_for_url(PODCAST_URL).object for n in range(NUM_EPISODES): Episode.objects.get_or_create_for_url(p, EPISODE_URL % (n,)) p = Podcast.objects.get(pk=p.pk) self.assertEqual(p.episode_count, NUM_EPISODES) # the episodes already exist this time -- no episode is created for n in range(NUM_EPISODES): Episode.objects.get_or_create_for_url(p, EPISODE_URL % (n,)) p = Podcast.objects.get(pk=p.pk) self.assertEqual(p.episode_count, NUM_EPISODES) real_count = Episode.objects.filter(podcast=p).count() self.assertEqual(real_count, NUM_EPISODES) class PodcastGroupTests(unittest.TestCase): """ Test grouping of podcasts """ def test_group(self): self.podcast1 = create_podcast() self.podcast2 = create_podcast() group = self.podcast1.group_with(self.podcast2, 'My Group', 'p1', 'p2') self.assertIn(self.podcast1, group.podcast_set.all()) self.assertIn(self.podcast2, group.podcast_set.all()) self.assertEqual(len(group.podcast_set.all()), 2) self.assertEqual(group.title, 'My Group') self.assertEqual(self.podcast1.group_member_name, 'p1') self.assertEqual(self.podcast2.group_member_name, 'p2') # add to group self.podcast3 = create_podcast() group = self.podcast1.group_with(self.podcast3, 'My Group', 'p1', 'p3') self.assertIn(self.podcast3, group.podcast_set.all()) self.assertEqual(self.podcast3.group_member_name, 'p3') # add group to podcast self.podcast4 = create_podcast() group = self.podcast4.group_with(self.podcast1, 'My Group', 'p4', 'p1') self.assertIn(self.podcast4, group.podcast_set.all()) self.assertEqual(self.podcast4.group_member_name, 'p4') class SlugTests(TestCase): """ Test various slug functionality """ def test_update_slugs(self): # this is the current number of queries when writing the test; this has # not been optimized in any particular way, it should just be used to # alert when something changes podcast = create_podcast() with self.assertNumQueries(8): # set the canonical slug podcast.set_slug('podcast-1') self.assertEqual(podcast.slug, 'podcast-1') with self.assertNumQueries(9): # set a new list of slugs podcast.set_slugs(['podcast-2', 'podcast-1']) self.assertEqual(podcast.slug, 'podcast-2') with self.assertNumQueries(2): # remove the canonical slug podcast.remove_slug('podcast-2') self.assertEqual(podcast.slug, 'podcast-1') with self.assertNumQueries(3): # add a non-canonical slug podcast.add_slug('podcast-3') self.assertEqual(podcast.slug, 'podcast-1')
{ "pile_set_name": "Github" }
# Video Call App A one-to-one text, audio and video chat application built with WebRTC and [RatchetPHP](https://github.com/ratchetphp/Ratchet). # Requirements - PHP >= 5.4 - Composer # Features - Video call - Audio call - Recording - Text chat - Two participants only If you require more than two participants, check out [this](https://github.com/amirsanni/video-call-app-nodejs) and [this](https://github.com/amirsanni/conference-call-ratchet). # Getting Started To test this app on your local server: - Run `composer install` from the root directory to install dependencies. - Set your app root (base url) in `/js/config.js`. - Open __`/ws/bin/server.php`__ and add your `domain name` and/or `ip address` to __`$allowed_origins`__ array, then replace the `localhost` and `PORT` in `$app = new Ratchet\App('localhost', PORT, '0.0.0.0');` with either your `domain name` or `ip address` and `Port number` respectively. - Set your web socket url in `/js/config.js`. Ensure the `domain name` and `port` matches what you set above. Use `wss` for secured connection. - Start Ratchet server by executing `php ws/bin/server.php` from your CLI. - Blam! Good to go. Open the app on two different devices to start chatting. - Works best on Chrome, Firefox and the latest versions of Opera desktop browser. - Xirsys' free STUN/TURN servers were used. If interested, you can get a free [xirsys](https://xirsys.com/) account, rename `Server.example.php` to `Server.php` and update it with your free credentials. Alternatively, you can use any STUN/TURN of your choice. ## Note To host this online, you'll need to set up a few things: - Create Ratchet as a service so it can run persistently on your server. Check the file *create-ratchet-as-a-service-with-daemon.txt* for the guide on how to do this on linux servers. - If on SSL, Ratchet won't work unless you make some changes on your server. - Enable mod_proxy.so - Enable mod_proxy_wstunnel.so - Open your apache SSL config file and add this: `ProxyPass /wss-secured/ ws://WEB_SOCKET_DOMAIN:WEB_SOCKET_PORT/` e.g. `ProxyPass /wss-secured/ ws://www.abc.xyz:PORT/` Note that you can substitute the `wss-secured` above with any path of your choice but you have to use the same path while connecting from the front-end as shown below. - Update your web socket url in `/js/config.js`: `const wsUrl = 'wss://YOUR_WEB_SOCKET_DOMAIN/wss-secured';` - Please note that most browsers will not allow access to media devices except the application is running on SSL or localhost (127.0.0.1). # Demo You can test at https://1410inc.xyz/video-call-app.
{ "pile_set_name": "Github" }
#!/usr/bin/python # vim: set fileencoding=utf-8 import clang.cindex import asciitree # must be version 0.2 import sys def node_children(node): return (c for c in node.get_children() if c.location.file.name == sys.argv[1]) def print_node(node): text = node.spelling or node.displayname kind = str(node.kind)[str(node.kind).index('.')+1:] return '{} {}'.format(kind, text) if len(sys.argv) != 2: print("Usage: dump_ast.py [header file name]") sys.exit() clang.cindex.Config.set_library_file('/usr/local/lib/libclang.so') index = clang.cindex.Index.create() translation_unit = index.parse(sys.argv[1], ['-x', 'c++', '-std=c++11', '-D__CODE_GENERATOR__']) print(asciitree.draw_tree(translation_unit.cursor, node_children, print_node))
{ "pile_set_name": "Github" }
import curry2 from '../_internal/_curry2' export default curry2((cbs, data) => { for (var i = 0; i < cbs.length; i++) { if (!cbs[i](data)) return false } return true })
{ "pile_set_name": "Github" }
# -*- coding: utf-8; mode: tcl; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=tcl:et:sw=4:ts=4:sts=4 PortSystem 1.0 name dbusmenu-qt categories devel kde4 kde maintainers {gmail.com:rjvbertin @RJVB} license GPL-2 description expose menus on DBus long_description A DBus interface to expose notification area menus on DBus. homepage https://launchpad.net/libdbusmenu-qt subport dbusmenu-qt5 { description-append \ \; Qt5 version long_description-append \ Qt5 version. } if {${subport} eq "${name}"} { PortGroup kde4 1.1 version 0.9.2 revision 2 master_sites ${homepage}/trunk/${version}/+download/ use_bzip2 yes checksums rmd160 e50cbffbf57329a26742ddf32d0f54248fe672cc \ sha256 ae6c1cb6da3c683aefed39df3e859537a31d80caa04f3023315ff09e5e8919ec configure.args-append \ -DUSE_QT4=ON -DUSE_QT5=OFF post-destroot { # CMake is not installing all of the src headers; install them # manually here. Destination directory already exists. foreach header [exec find ${worksrcpath}/src -name "*.h" | \ sed -e "s@${worksrcpath}/src/@@g" | \ grep -v "_p\.h"] { xinstall -m 644 -W ${worksrcpath}/src ${header} \ ${destroot}${prefix}/include/${name} } } test.run yes } else { # this port is mostly used by KF5 ports so we indicate # that we'd prefer to use port:qt5-kde if it's available # (iow, installed, or installable because port:qt5 isn't). set qt5.prefer_kde 1 platform darwin { PortGroup cxx11 1.1 } PortGroup qt5 1.0 PortGroup cmake 1.1 set cmake.out_of_source \ yes fetch.type bzr bzr.url lp:~dbusmenu-team/libdbusmenu-qt/trunk bzr.revision 271 version 0.9.3.16.04 distname ldbusmenu-qt-0.9.3 worksrcdir ldbusmenu-qt-0.9.3 # libdbusmenu-qt5 use QtCore, QtWidgets and QtDBus all of which # are provided by port:qt5-qtbase if port:qt5-kde isn't being used. # (port:qt5-qtbase is pulled in by default in that case). configure.args-append \ -DUSE_QT4=OFF -DUSE_QT5=ON test.run no } platforms darwin # if {${os.platform} ne "linux"} { # depends_lib-append port:qjson # } distname lib${name}-${version} if {![variant_isset docs]} { configure.args-append -DWITH_DOC=Off } livecheck.type regex livecheck.url ${homepage} livecheck.regex "Latest version is (.*)"
{ "pile_set_name": "Github" }
'use strict'; const fsAutocomplete = require('vorpal-autocomplete-fs'); const delimiter = require('./../delimiter'); const interfacer = require('./../util/interfacer'); const preparser = require('./../preparser'); const cd = { exec(dir, options) { const self = this; const vpl = options.vorpal; options = options || {}; dir = (!dir) ? delimiter.getHomeDir() : dir; // Allow Windows drive letter changes dir = (dir && dir.length === 2 && dir[1] === '/') ? `${dir[0]}:` : dir; try { process.chdir(dir); if (vpl) { delimiter.refresh(vpl); } return 0; } catch (e) { return cd.error.call(self, e, dir); } }, error(e, dir) { let status; let stdout; if (e.code === 'ENOENT' && e.syscall === 'uv_chdir') { status = 1; stdout = `-bash: cd: ${dir}: No such file or directory`; } else { status = 2; stdout = e.stack; } this.log(stdout); return status; } }; module.exports = function (vorpal) { if (vorpal === undefined) { return cd; } vorpal.api.cd = cd; vorpal .command('cd [dir]') .parse(preparser) .autocomplete(fsAutocomplete({directory: true})) .action(function (args, callback) { args.options = args.options || {}; args.options.vorpal = vorpal; return interfacer.call(this, { command: cd, args: args.dir, options: args.options, callback }); }); };
{ "pile_set_name": "Github" }
namespace NBomber.FSharp open System open System.IO open System.Threading open System.Threading.Tasks open Serilog open CommandLine open FSharp.Control.Tasks.V2.ContextInsensitive open FsToolkit.ErrorHandling open Microsoft.Extensions.Configuration open NBomber open NBomber.Contracts open NBomber.Configuration open NBomber.Errors open NBomber.Domain open NBomber.Domain.DomainTypes open NBomber.Domain.ConnectionPool open NBomber.DomainServices type CommandLineArgs = { [<Option('c', "config", HelpText = "NBomber configuration")>] Config: string [<Option('i', "infra", HelpText = "NBomber infra configuration")>] InfraConfig: string } [<AutoOpen>] module TimeSpanApi = let inline milliseconds (value: int) = value |> float |> TimeSpan.FromMilliseconds let inline seconds (value: int) = value |> float |> TimeSpan.FromSeconds let inline minutes (value) = value |> float |> TimeSpan.FromMinutes type ConnectionPoolArgs = static member create (name: string, openConnection: int * CancellationToken -> Task<'TConnection>, closeConnection: 'TConnection * CancellationToken -> Task, ?connectionCount: int) = let count = defaultArg connectionCount Constants.DefaultConnectionCount ConnectionPoolArgs(name, count, openConnection, closeConnection) :> IConnectionPoolArgs<'TConnection> static member create (name: string, openConnection: int * CancellationToken -> Task<'TConnection>, closeConnection: 'TConnection * CancellationToken -> Task<unit>, ?connectionCount: int) = let close = fun (connection,token) -> closeConnection(connection,token) :> Task let count = defaultArg connectionCount Constants.DefaultConnectionCount ConnectionPoolArgs.create(name, openConnection, close, count) static member empty = ConnectionPoolArgs.create(Constants.EmptyPoolName, (fun _ -> Task.singleton()), (fun _ -> Task.singleton()), 0) type Step = static member create (name: string, connectionPoolArgs: IConnectionPoolArgs<'TConnection>, feed: IFeed<'TFeedItem>, execute: IStepContext<'TConnection,'TFeedItem> -> Task<Response>, ?doNotTrack: bool) = let poolArgs = if connectionPoolArgs.PoolName = Constants.EmptyPoolName then None else Some((connectionPoolArgs :?> ConnectionPoolArgs<'TConnection>).GetUntyped().Value) { StepName = name ConnectionPoolArgs = poolArgs ConnectionPool = None Execute = Step.toUntypedExec(execute) Context = None Feed = Feed.toUntypedFeed(feed) DoNotTrack = defaultArg doNotTrack Constants.DefaultDoNotTrack } :> IStep static member create (name: string, connectionPoolArgs: IConnectionPoolArgs<'TConnection>, execute: IStepContext<'TConnection,unit> -> Task<Response>, ?doNotTrack: bool) = Step.create(name, connectionPoolArgs, Feed.empty, execute, defaultArg doNotTrack Constants.DefaultDoNotTrack) static member create (name: string, feed: IFeed<'TFeedItem>, execute: IStepContext<unit,'TFeedItem> -> Task<Response>, ?doNotTrack: bool) = Step.create(name, ConnectionPoolArgs.empty, feed, execute, defaultArg doNotTrack Constants.DefaultDoNotTrack) static member create (name: string, execute: IStepContext<unit,unit> -> Task<Response>, ?doNotTrack: bool) = Step.create(name, ConnectionPoolArgs.empty, Feed.empty, execute, defaultArg doNotTrack Constants.DefaultDoNotTrack) /// Creates pause step with specified duration in lazy mode. /// It's useful when you want to fetch value from some configuration. static member createPause (getDuration: unit -> TimeSpan) = Step.create(name = "pause", execute = (fun _ -> task { do! Task.Delay(getDuration()) return Response.Ok() }), doNotTrack = true) /// Creates pause step in milliseconds in lazy mode. /// It's useful when you want to fetch value from some configuration. static member createPause (getDuration: unit -> int) = let func = getDuration >> float >> TimeSpan.FromMilliseconds Step.createPause(func) /// Creates pause step with specified duration. static member createPause (duration: TimeSpan) = Step.createPause(fun () -> duration) /// Creates pause step with specified duration in milliseconds. static member createPause (milliseconds: int) = Step.createPause(fun () -> milliseconds) /// Scenario helps to organize steps into sequential flow with different load simulations (concurrency control). module Scenario = /// Creates scenario with steps which will be executed sequentially. let create (name: string) (steps: IStep list): Contracts.Scenario = { ScenarioName = name Init = None Clean = None Steps = steps WarmUpDuration = Constants.DefaultWarmUpDuration LoadSimulations = [ LoadSimulation.InjectPerSec(rate = Constants.DefaultCopiesCount, during = Constants.DefaultSimulationDuration) ] } /// Initializes scenario. /// You can use it to for example to prepare your target system or to parse and apply configuration. let withInit (initFunc: IScenarioContext -> Task<unit>) (scenario: Contracts.Scenario) = { scenario with Init = Some(fun token -> initFunc(token) :> Task) } /// Cleans scenario's resources. let withClean (cleanFunc: IScenarioContext -> Task<unit>) (scenario: Contracts.Scenario) = { scenario with Clean = Some(fun token -> cleanFunc(token) :> Task) } /// Sets warm-up duration /// Warm-up will just simply start a scenario with a specified duration. let withWarmUpDuration (duration: TimeSpan) (scenario: Contracts.Scenario) = { scenario with WarmUpDuration = duration } let withoutWarmUp (scenario: Contracts.Scenario) = { scenario with WarmUpDuration = TimeSpan.Zero } /// Sets load simulations. /// Default value is: InjectPerSec(rate = 50, during = minutes 1) let withLoadSimulations (loadSimulations: LoadSimulation list) (scenario: Contracts.Scenario) = { scenario with LoadSimulations = loadSimulations } /// NBomberRunner is responsible for registering and running scenarios. /// Also it provides configuration points related to infrastructure, reporting, loading plugins. module NBomberRunner = /// Registers scenario in NBomber environment. let registerScenario (scenario: Contracts.Scenario) = { NBomberContext.empty with RegisteredScenarios = [scenario] } /// Registers scenarios in NBomber environment. /// Scenarios will be run in parallel. let registerScenarios (scenarios: Contracts.Scenario list) = { NBomberContext.empty with RegisteredScenarios = scenarios } /// Sets test suite name /// Default value is: nbomber_default_test_suite_name. let withTestSuite (testSuite: string) (context: NBomberContext) = { context with TestSuite = testSuite } /// Sets test name /// Default value is: nbomber_default_test_name. let withTestName (testName: string) (context: NBomberContext) = { context with TestName = testName } /// Sets output report name. /// Default name: nbomber_report. let withReportFileName (reportFileName: string) (context: NBomberContext) = { context with ReportFileName = Some reportFileName } let withReportFormats (reportFormats: ReportFormat list) (context: NBomberContext) = { context with ReportFormats = reportFormats } /// Sets to run without reports let withoutReports (context: NBomberContext) = { context with ReportFormats = List.empty } /// Sets reporting sinks. /// Reporting sink is used to save real-time metrics to correspond database let withReportingSinks (reportingSinks: IReportingSink list) (sendStatsInterval: TimeSpan) (context: NBomberContext) = { context with ReportingSinks = reportingSinks SendStatsInterval = sendStatsInterval } /// Sets worker plugins. /// Worker plugin is a plugin that starts at the test start and works as a background worker. let withWorkerPlugins (plugins: IWorkerPlugin list) (context: NBomberContext) = { context with WorkerPlugins = plugins } /// Loads configuration. /// The following formats are supported: /// - json (.json) let loadConfig (path: string) (context: NBomberContext) = let config = match Path.GetExtension(path) with | ".json" -> path |> File.ReadAllText |> JsonConfig.unsafeParse | _ -> failwith "unsupported config format" { context with NBomberConfig = Some config } /// Loads infrastructure configuration. /// The following formats are supported: /// - json (.json) let loadInfraConfig (path: string) (context: NBomberContext) = let config = match Path.GetExtension(path) with | ".json" -> ConfigurationBuilder().AddJsonFile(path).Build() :> IConfiguration | _ -> failwith "unsupported config format" { context with InfraConfig = Some config } /// Sets logger configuration. /// Make sure that you always return a new instance of LoggerConfiguration. /// You can also configure logger via configuration file. /// For this use NBomberRunner.loadInfraConfig let withLoggerConfig (createLoggerConfig: unit -> LoggerConfiguration) (context: NBomberContext) = try // this is limitation of Serilog // to invoke CreateLogger() twice on the same instance of LoggerConfiguration // it's why we can't just accept LoggerConfiguration createLoggerConfig().CreateLogger() |> ignore createLoggerConfig().CreateLogger() |> ignore with | :? InvalidOperationException -> failwith "createLoggerConfig should always return a new instance of LoggerConfiguration" { context with CreateLoggerConfig = Some createLoggerConfig } /// Sets application type. /// The following application types are supported: /// - Console: is suitable for interactive session (will display progress bar) /// - Process: is suitable for running tests under test runners (progress bar will not be shown) /// By default NBomber will automatically identify your environment: Process or Console. let withApplicationType (applicationType: ApplicationType) (context: NBomberContext) = { context with ApplicationType = Some applicationType } let internal executeCliArgs (args) (context: NBomberContext) = let invokeConfigLoader (configName) (configLoader) (config) (context) = if config = String.Empty then sprintf "%s is empty" configName |> failwith elif String.IsNullOrEmpty(config) then context else configLoader config context match CommandLine.Parser.Default.ParseArguments<CommandLineArgs>(args) with | :? Parsed<CommandLineArgs> as parsed -> let values = parsed.Value let execLoadConfigCmd = invokeConfigLoader "config" loadConfig values.Config let execLoadInfraConfigCmd = invokeConfigLoader "infra config" loadInfraConfig values.InfraConfig let execCmd = execLoadConfigCmd >> execLoadInfraConfigCmd context |> execCmd | _ -> context let internal runWithResult (args) (context: NBomberContext) = context |> executeCliArgs args |> NBomberRunner.run let run (context: NBomberContext) = context |> runWithResult Array.empty |> Result.mapError(AppError.toString) /// Runs scenarios with arguments. /// The following CLI commands are supported: /// -c or --config: loads configuration, /// -i or --infra: loads infrastructure configuration. /// Examples of possible args: /// [|"-c"; "config.yaml"; "-i"; "infra_config.yaml"|] /// [|"--config"; "config.yaml"; "--infra"; "infra_config.yaml"|] let runWithArgs (args) (context: NBomberContext) = context |> runWithResult args |> Result.mapError(AppError.toString)
{ "pile_set_name": "Github" }
// <auto-generated /> namespace IronJS.Tests.UnitTests.Sputnik.Conformance.NativeECMAScriptObjects.ObjectObjects.PropertiesOfTheObjectPrototypeObject { using System; using NUnit.Framework; [TestFixture] public class ObjectPrototypeToStringTests : SputnikTestFixture { public ObjectPrototypeToStringTests() : base(@"Conformance\15_Native_ECMA_Script_Objects\15.2_Object_Objects\15.2.4_Properties_of_the_Object_Prototype_Object\15.2.4.2_Object.prototype.toString") { } [Test] [Category("Sputnik Conformance")] [Category("ECMA 15.2.4.2")] [TestCase("S15.2.4.2_A1.js", Description = "When the toString method is called, the following steps are taken: i) Get the [[Class]] property of this object ii) Compute a string value by concatenating the three strings \"[object \", Result(1), and \"]\" iii) Return Result(2)")] public void WhenTheToStringMethodIsCalledTheFollowingStepsAreTakenIGetTheClassPropertyOfThisObjectIiComputeAStringValueByConcatenatingTheThreeStringsObjectResult1AndIiiReturnResult2(string file) { RunFile(file); } [Test] [Category("Sputnik Conformance")] [Category("ECMA 15.2.4.2")] [TestCase("S15.2.4.2_A10.js", Description = "The Object.prototype.toString.length property has the attribute ReadOnly")] public void TheObjectPrototypeToStringLengthPropertyHasTheAttributeReadOnly(string file) { RunFile(file); } [Test] [Category("Sputnik Conformance")] [Category("ECMA 15.2.4.2")] [TestCase("S15.2.4.2_A11.js", Description = "The length property of the toString method is 0")] public void TheLengthPropertyOfTheToStringMethodIs0(string file) { RunFile(file); } [Test] [Category("Sputnik Conformance")] [Category("ECMA 13.2")] [Category("ECMA 15.2.4.2")] [TestCase("S15.2.4.2_A6.js", Description = "Object.prototype.toString has not prototype property")] public void ObjectPrototypeToStringHasNotPrototypeProperty(string file) { RunFile(file); } [Test] [Category("Sputnik Conformance")] [Category("ECMA 13.2")] [Category("ECMA 15.2.4.2")] [TestCase("S15.2.4.2_A7.js", Description = "Object.prototype.toString can\'t be used as a constructor")] public void ObjectPrototypeToStringCanTBeUsedAsAConstructor(string file) { RunFile(file); } [Test] [Category("Sputnik Conformance")] [Category("ECMA 15.2.4.2")] [TestCase("S15.2.4.2_A8.js", Description = "The Object.prototype.toString.length property has the attribute DontEnum")] public void TheObjectPrototypeToStringLengthPropertyHasTheAttributeDontEnum(string file) { RunFile(file); } [Test] [Category("Sputnik Conformance")] [Category("ECMA 15.2.4.2")] [TestCase("S15.2.4.2_A9.js", Description = "The Object.prototype.toString.length property has the attribute DontDelete")] public void TheObjectPrototypeToStringLengthPropertyHasTheAttributeDontDelete(string file) { RunFile(file); } } }
{ "pile_set_name": "Github" }
# node-supervisor A little supervisor script for nodejs. It runs your program, and watches for code changes, so you can have hot-code reloading-ish behavior, without worrying about memory leaks and making sure you clean up all the inter-module references, and without a whole new `require` system. ## node-supervisor -? Node Supervisor is used to restart programs when they crash. It can also be used to restart programs when a *.js file changes. Usage: supervisor [options] <program> supervisor [options] -- <program> [args ...] Required: <program> The program to run. Options: -w|--watch <watchItems> A comma-delimited list of folders or js files to watch for changes. When a change to a js file occurs, reload the program Default is '.' -i|--ignore <ignoreItems> A comma-delimited list of folders to ignore for changes. No default -p|--poll-interval <milliseconds> How often to poll watched files for changes. Defaults to Node default. -e|--extensions <extensions> Specific file extensions to watch in addition to defaults. Used when --watch option includes folders Default is 'node|js' -x|--exec <executable> The executable that runs the specified program. Default is 'node' --debug Start node with --debug flag. --debug-brk Start node with --debug-brk flag. -n|--no-restart-on error|exit Don't automatically restart the supervised program if it ends. Supervisor will wait for a change in the source files. If "error", an exit code of 0 will still restart. If "exit", no restart regardless of exit code. -h|--help|-? Display these usage instructions. -q|--quiet Suppress DEBUG messages Examples: supervisor myapp.js supervisor myapp.coffee supervisor -w scripts -e myext -x myrunner myapp supervisor -w lib,server.js,config.js server.js supervisor -- server.js -h host -p port ## Simple Install Install npm, and then do this: npm install supervisor -g You don't even need to download or fork this repo at all. ## Fancy Install Get this code, install npm, and then do this: npm link ## todo 1. Re-attach to a process by pid. If the supervisor is backgrounded, and then disowned, the child will keep running. At that point, the supervisor may be killed, but the child will keep on running. It'd be nice to have two supervisors that kept each other up, and could also perhaps run a child program. 2. Run more types of programs than just "node blargh.js". 3. Be able to run more than one program, so that you can have two supervisors supervise each other, and then also keep some child server up. 4. When watching, it'd be good to perhaps bring up a new child and then kill the old one gently, rather than just crashing the child abruptly. 5. Keep the pid in a safe place, so another supervisor can pull it out if told to supervise the same program. 6. It'd be pretty cool if this program could be run just like doing `node blah.js`, but could somehow "know" which files had been loaded, and restart whenever a touched file changes.
{ "pile_set_name": "Github" }
#include <test/unit/math/test_ad.hpp> TEST(mathMixMatFun, real) { auto f = [](const auto& z) { return real(z); }; stan::test::expect_complex_common(f); }
{ "pile_set_name": "Github" }
debug = require('debug')('supersonic:auth:session') module.exports = (localStorage) -> new class Session RAW_SESSION_KEY: "__ag:data:session" storage: localStorage set: (rawSession) => validateSession rawSession debug "Setting session data", rawSession @storage.setItem @RAW_SESSION_KEY, rawSession get: => @storage.getItem @RAW_SESSION_KEY clear: => debug "Clearing session data" @storage.removeItem @RAW_SESSION_KEY getAccessToken: => @get()?.access_token getUserId: => @get()?.user_details?.id validateSession = (rawSession) -> unless isValidRawSession(rawSession) throw new SessionValidationError "Invalid data for session", rawSession isValidRawSession = (session) -> session.access_token? && session.user_details?.id? class SessionValidationError extends Error constructor: (@message, @errors) -> Error.call @ Error.captureStackTrace?(@, @constructor) @name = "SessionValidationError" toString: -> "#{@name}(#{@message}, #{JSON.stringify @errors})"
{ "pile_set_name": "Github" }
#pragma once #define USE_EDGEMODE_JSRT #include <jsrt.h> class WebGLActiveInfo { public: WebGLActiveInfo(); WebGLActiveInfo(GLenum type, const wchar_t * name, GLint size); static JsValueRef CALLBACK constructor(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState); static JsValueRef prototype; static std::map<const wchar_t *, JsNativeFunction> getMembers(); static std::map<const wchar_t *, JsValueRef> getProperties(); GLint size; GLenum type; const wchar_t * name; };
{ "pile_set_name": "Github" }
// Uyghur .group a a A .group b b b .group c ch tS .group d d d .group e e & .group é é e .group f f f .group g g g g'h gh gh Q" .group h h h .group i i I .group j j dZ .group k k k .group l l l .group m m m .group n n n n'g ng ng N .group o o o .group ö ö W .group p p p .group q q q .group r r R .group s s s s'h sh sh S .group t t t .group u u u .group ü ü y .group w w w .group x x X .group y y j .group z z z z'h zh zh Z .group ئ ئ ئا A ئە & ئې e ئى I ئو o ئۆ W ئۇ u ئۈ y .group ا ا A .group ب ب b .group چ چ tS .group د د d .group ە ە & .group ې ې e .group ف ف f .group گ گ g گھ gh .group غ غ Q" .group ھ ھ h .group ى ى I .group ج ج dZ .group ك ك k .group ل ل l .group م م m .group ن ن n نگ ng .group ڭ ڭ N .group و و o .group ۆ ۆ W .group پ پ p .group ق ق q .group ر ر R .group س س s سھ sh .group ش ش S .group ت ت t .group ۇ ۇ u .group ۈ ۈ y .group ۋ ۋ w .group خ خ X .group ي ي j .group ز ز z زھ zh .group ژ ژ Z
{ "pile_set_name": "Github" }
predicate fzn_if_then_else_var_opt_bool(array[int] of var bool: c, array[int] of var opt bool: x, var opt bool: y) = let { array[index_set(c)] of var bool: d; } in forall(i in index_set(c)) (if i > min(index_set(c)) then d[i] = (not c[i-1] /\ d[i-1]) else d[i] = true endif) /\ forall (i in index_set(c)) (c[i] /\ d[i] -> y=x[i]);
{ "pile_set_name": "Github" }
/*! Hammer.JS - v2.0.4 - 2014-09-28 * http://hammerjs.github.io/ * * Copyright (c) 2014 Jorik Tangelder; * Licensed under the MIT license */ (function(window, document, exportName, undefined) { 'use strict'; var VENDOR_PREFIXES = ['', 'webkit', 'moz', 'MS', 'ms', 'o']; var TEST_ELEMENT = document.createElement('div'); var TYPE_FUNCTION = 'function'; var round = Math.round; var abs = Math.abs; var now = Date.now; /** * set a timeout with a given scope * @param {Function} fn * @param {Number} timeout * @param {Object} context * @returns {number} */ function setTimeoutContext(fn, timeout, context) { return setTimeout(bindFn(fn, context), timeout); } /** * if the argument is an array, we want to execute the fn on each entry * if it aint an array we don't want to do a thing. * this is used by all the methods that accept a single and array argument. * @param {*|Array} arg * @param {String} fn * @param {Object} [context] * @returns {Boolean} */ function invokeArrayArg(arg, fn, context) { if (Array.isArray(arg)) { each(arg, context[fn], context); return true; } return false; } /** * walk objects and arrays * @param {Object} obj * @param {Function} iterator * @param {Object} context */ function each(obj, iterator, context) { var i; if (!obj) { return; } if (obj.forEach) { obj.forEach(iterator, context); } else if (obj.length !== undefined) { i = 0; while (i < obj.length) { iterator.call(context, obj[i], i, obj); i++; } } else { for (i in obj) { obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj); } } } /** * extend object. * means that properties in dest will be overwritten by the ones in src. * @param {Object} dest * @param {Object} src * @param {Boolean} [merge] * @returns {Object} dest */ function extend(dest, src, merge) { var keys = Object.keys(src); var i = 0; while (i < keys.length) { if (!merge || (merge && dest[keys[i]] === undefined)) { dest[keys[i]] = src[keys[i]]; } i++; } return dest; } /** * merge the values from src in the dest. * means that properties that exist in dest will not be overwritten by src * @param {Object} dest * @param {Object} src * @returns {Object} dest */ function merge(dest, src) { return extend(dest, src, true); } /** * simple class inheritance * @param {Function} child * @param {Function} base * @param {Object} [properties] */ function inherit(child, base, properties) { var baseP = base.prototype, childP; childP = child.prototype = Object.create(baseP); childP.constructor = child; childP._super = baseP; if (properties) { extend(childP, properties); } } /** * simple function bind * @param {Function} fn * @param {Object} context * @returns {Function} */ function bindFn(fn, context) { return function boundFn() { return fn.apply(context, arguments); }; } /** * let a boolean value also be a function that must return a boolean * this first item in args will be used as the context * @param {Boolean|Function} val * @param {Array} [args] * @returns {Boolean} */ function boolOrFn(val, args) { if (typeof val == TYPE_FUNCTION) { return val.apply(args ? args[0] || undefined : undefined, args); } return val; } /** * use the val2 when val1 is undefined * @param {*} val1 * @param {*} val2 * @returns {*} */ function ifUndefined(val1, val2) { return (val1 === undefined) ? val2 : val1; } /** * addEventListener with multiple events at once * @param {EventTarget} target * @param {String} types * @param {Function} handler */ function addEventListeners(target, types, handler) { each(splitStr(types), function(type) { target.addEventListener(type, handler, false); }); } /** * removeEventListener with multiple events at once * @param {EventTarget} target * @param {String} types * @param {Function} handler */ function removeEventListeners(target, types, handler) { each(splitStr(types), function(type) { target.removeEventListener(type, handler, false); }); } /** * find if a node is in the given parent * @method hasParent * @param {HTMLElement} node * @param {HTMLElement} parent * @return {Boolean} found */ function hasParent(node, parent) { while (node) { if (node == parent) { return true; } node = node.parentNode; } return false; } /** * small indexOf wrapper * @param {String} str * @param {String} find * @returns {Boolean} found */ function inStr(str, find) { return str.indexOf(find) > -1; } /** * split string on whitespace * @param {String} str * @returns {Array} words */ function splitStr(str) { return str.trim().split(/\s+/g); } /** * find if a array contains the object using indexOf or a simple polyFill * @param {Array} src * @param {String} find * @param {String} [findByKey] * @return {Boolean|Number} false when not found, or the index */ function inArray(src, find, findByKey) { if (src.indexOf && !findByKey) { return src.indexOf(find); } else { var i = 0; while (i < src.length) { if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) { return i; } i++; } return -1; } } /** * convert array-like objects to real arrays * @param {Object} obj * @returns {Array} */ function toArray(obj) { return Array.prototype.slice.call(obj, 0); } /** * unique array with objects based on a key (like 'id') or just by the array's value * @param {Array} src [{id:1},{id:2},{id:1}] * @param {String} [key] * @param {Boolean} [sort=False] * @returns {Array} [{id:1},{id:2}] */ function uniqueArray(src, key, sort) { var results = []; var values = []; var i = 0; while (i < src.length) { var val = key ? src[i][key] : src[i]; if (inArray(values, val) < 0) { results.push(src[i]); } values[i] = val; i++; } if (sort) { if (!key) { results = results.sort(); } else { results = results.sort(function sortUniqueArray(a, b) { return a[key] > b[key]; }); } } return results; } /** * get the prefixed property * @param {Object} obj * @param {String} property * @returns {String|Undefined} prefixed */ function prefixed(obj, property) { var prefix, prop; var camelProp = property[0].toUpperCase() + property.slice(1); var i = 0; while (i < VENDOR_PREFIXES.length) { prefix = VENDOR_PREFIXES[i]; prop = (prefix) ? prefix + camelProp : property; if (prop in obj) { return prop; } i++; } return undefined; } /** * get a unique id * @returns {number} uniqueId */ var _uniqueId = 1; function uniqueId() { return _uniqueId++; } /** * get the window object of an element * @param {HTMLElement} element * @returns {DocumentView|Window} */ function getWindowForElement(element) { var doc = element.ownerDocument; return (doc.defaultView || doc.parentWindow); } var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i; var SUPPORT_TOUCH = ('ontouchstart' in window); var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined; var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent); var INPUT_TYPE_TOUCH = 'touch'; var INPUT_TYPE_PEN = 'pen'; var INPUT_TYPE_MOUSE = 'mouse'; var INPUT_TYPE_KINECT = 'kinect'; var COMPUTE_INTERVAL = 25; var INPUT_START = 1; var INPUT_MOVE = 2; var INPUT_END = 4; var INPUT_CANCEL = 8; var DIRECTION_NONE = 1; var DIRECTION_LEFT = 2; var DIRECTION_RIGHT = 4; var DIRECTION_UP = 8; var DIRECTION_DOWN = 16; var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT; var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN; var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL; var PROPS_XY = ['x', 'y']; var PROPS_CLIENT_XY = ['clientX', 'clientY']; /** * create new input type manager * @param {Manager} manager * @param {Function} callback * @returns {Input} * @constructor */ function Input(manager, callback) { var self = this; this.manager = manager; this.callback = callback; this.element = manager.element; this.target = manager.options.inputTarget; // smaller wrapper around the handler, for the scope and the enabled state of the manager, // so when disabled the input events are completely bypassed. this.domHandler = function(ev) { if (boolOrFn(manager.options.enable, [manager])) { self.handler(ev); } }; this.init(); } Input.prototype = { /** * should handle the inputEvent data and trigger the callback * @virtual */ handler: function() { }, /** * bind the events */ init: function() { this.evEl && addEventListeners(this.element, this.evEl, this.domHandler); this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler); this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); }, /** * unbind the events */ destroy: function() { this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler); this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler); this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); } }; /** * create new input type manager * called by the Manager constructor * @param {Hammer} manager * @returns {Input} */ function createInputInstance(manager) { var Type; var inputClass = manager.options.inputClass; if (inputClass) { Type = inputClass; } else if (SUPPORT_POINTER_EVENTS) { Type = PointerEventInput; } else if (SUPPORT_ONLY_TOUCH) { Type = TouchInput; } else if (!SUPPORT_TOUCH) { Type = MouseInput; } else { Type = TouchMouseInput; } return new (Type)(manager, inputHandler); } /** * handle input events * @param {Manager} manager * @param {String} eventType * @param {Object} input */ function inputHandler(manager, eventType, input) { var pointersLen = input.pointers.length; var changedPointersLen = input.changedPointers.length; var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0)); var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0)); input.isFirst = !!isFirst; input.isFinal = !!isFinal; if (isFirst) { manager.session = {}; } // source event is the normalized value of the domEvents // like 'touchstart, mouseup, pointerdown' input.eventType = eventType; // compute scale, rotation etc computeInputData(manager, input); // emit secret event manager.emit('hammer.input', input); manager.recognize(input); manager.session.prevInput = input; } /** * extend the data with some usable properties like scale, rotate, velocity etc * @param {Object} manager * @param {Object} input */ function computeInputData(manager, input) { var session = manager.session; var pointers = input.pointers; var pointersLength = pointers.length; // store the first input to calculate the distance and direction if (!session.firstInput) { session.firstInput = simpleCloneInputData(input); } // to compute scale and rotation we need to store the multiple touches if (pointersLength > 1 && !session.firstMultiple) { session.firstMultiple = simpleCloneInputData(input); } else if (pointersLength === 1) { session.firstMultiple = false; } var firstInput = session.firstInput; var firstMultiple = session.firstMultiple; var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center; var center = input.center = getCenter(pointers); input.timeStamp = now(); input.deltaTime = input.timeStamp - firstInput.timeStamp; input.angle = getAngle(offsetCenter, center); input.distance = getDistance(offsetCenter, center); computeDeltaXY(session, input); input.offsetDirection = getDirection(input.deltaX, input.deltaY); input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1; input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0; computeIntervalInputData(session, input); // find the correct target var target = manager.element; if (hasParent(input.srcEvent.target, target)) { target = input.srcEvent.target; } input.target = target; } function computeDeltaXY(session, input) { var center = input.center; var offset = session.offsetDelta || {}; var prevDelta = session.prevDelta || {}; var prevInput = session.prevInput || {}; if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) { prevDelta = session.prevDelta = { x: prevInput.deltaX || 0, y: prevInput.deltaY || 0 }; offset = session.offsetDelta = { x: center.x, y: center.y }; } input.deltaX = prevDelta.x + (center.x - offset.x); input.deltaY = prevDelta.y + (center.y - offset.y); } /** * velocity is calculated every x ms * @param {Object} session * @param {Object} input */ function computeIntervalInputData(session, input) { var last = session.lastInterval || input, deltaTime = input.timeStamp - last.timeStamp, velocity, velocityX, velocityY, direction; if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) { var deltaX = last.deltaX - input.deltaX; var deltaY = last.deltaY - input.deltaY; var v = getVelocity(deltaTime, deltaX, deltaY); velocityX = v.x; velocityY = v.y; velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y; direction = getDirection(deltaX, deltaY); session.lastInterval = input; } else { // use latest velocity info if it doesn't overtake a minimum period velocity = last.velocity; velocityX = last.velocityX; velocityY = last.velocityY; direction = last.direction; } input.velocity = velocity; input.velocityX = velocityX; input.velocityY = velocityY; input.direction = direction; } /** * create a simple clone from the input used for storage of firstInput and firstMultiple * @param {Object} input * @returns {Object} clonedInputData */ function simpleCloneInputData(input) { // make a simple copy of the pointers because we will get a reference if we don't // we only need clientXY for the calculations var pointers = []; var i = 0; while (i < input.pointers.length) { pointers[i] = { clientX: round(input.pointers[i].clientX), clientY: round(input.pointers[i].clientY) }; i++; } return { timeStamp: now(), pointers: pointers, center: getCenter(pointers), deltaX: input.deltaX, deltaY: input.deltaY }; } /** * get the center of all the pointers * @param {Array} pointers * @return {Object} center contains `x` and `y` properties */ function getCenter(pointers) { var pointersLength = pointers.length; // no need to loop when only one touch if (pointersLength === 1) { return { x: round(pointers[0].clientX), y: round(pointers[0].clientY) }; } var x = 0, y = 0, i = 0; while (i < pointersLength) { x += pointers[i].clientX; y += pointers[i].clientY; i++; } return { x: round(x / pointersLength), y: round(y / pointersLength) }; } /** * calculate the velocity between two points. unit is in px per ms. * @param {Number} deltaTime * @param {Number} x * @param {Number} y * @return {Object} velocity `x` and `y` */ function getVelocity(deltaTime, x, y) { return { x: x / deltaTime || 0, y: y / deltaTime || 0 }; } /** * get the direction between two points * @param {Number} x * @param {Number} y * @return {Number} direction */ function getDirection(x, y) { if (x === y) { return DIRECTION_NONE; } if (abs(x) >= abs(y)) { return x > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; } return y > 0 ? DIRECTION_UP : DIRECTION_DOWN; } /** * calculate the absolute distance between two points * @param {Object} p1 {x, y} * @param {Object} p2 {x, y} * @param {Array} [props] containing x and y keys * @return {Number} distance */ function getDistance(p1, p2, props) { if (!props) { props = PROPS_XY; } var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]]; return Math.sqrt((x * x) + (y * y)); } /** * calculate the angle between two coordinates * @param {Object} p1 * @param {Object} p2 * @param {Array} [props] containing x and y keys * @return {Number} angle */ function getAngle(p1, p2, props) { if (!props) { props = PROPS_XY; } var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]]; return Math.atan2(y, x) * 180 / Math.PI; } /** * calculate the rotation degrees between two pointersets * @param {Array} start array of pointers * @param {Array} end array of pointers * @return {Number} rotation */ function getRotation(start, end) { return getAngle(end[1], end[0], PROPS_CLIENT_XY) - getAngle(start[1], start[0], PROPS_CLIENT_XY); } /** * calculate the scale factor between two pointersets * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @param {Array} start array of pointers * @param {Array} end array of pointers * @return {Number} scale */ function getScale(start, end) { return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY); } var MOUSE_INPUT_MAP = { mousedown: INPUT_START, mousemove: INPUT_MOVE, mouseup: INPUT_END }; var MOUSE_ELEMENT_EVENTS = 'mousedown'; var MOUSE_WINDOW_EVENTS = 'mousemove mouseup'; /** * Mouse events input * @constructor * @extends Input */ function MouseInput() { this.evEl = MOUSE_ELEMENT_EVENTS; this.evWin = MOUSE_WINDOW_EVENTS; this.allow = true; // used by Input.TouchMouse to disable mouse events this.pressed = false; // mousedown state Input.apply(this, arguments); } inherit(MouseInput, Input, { /** * handle mouse events * @param {Object} ev */ handler: function MEhandler(ev) { var eventType = MOUSE_INPUT_MAP[ev.type]; // on start we want to have the left mouse button down if (eventType & INPUT_START && ev.button === 0) { this.pressed = true; } if (eventType & INPUT_MOVE && ev.which !== 1) { eventType = INPUT_END; } // mouse must be down, and mouse events are allowed (see the TouchMouse input) if (!this.pressed || !this.allow) { return; } if (eventType & INPUT_END) { this.pressed = false; } this.callback(this.manager, eventType, { pointers: [ev], changedPointers: [ev], pointerType: INPUT_TYPE_MOUSE, srcEvent: ev }); } }); var POINTER_INPUT_MAP = { pointerdown: INPUT_START, pointermove: INPUT_MOVE, pointerup: INPUT_END, pointercancel: INPUT_CANCEL, pointerout: INPUT_CANCEL }; // in IE10 the pointer types is defined as an enum var IE10_POINTER_TYPE_ENUM = { 2: INPUT_TYPE_TOUCH, 3: INPUT_TYPE_PEN, 4: INPUT_TYPE_MOUSE, 5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816 }; var POINTER_ELEMENT_EVENTS = 'pointerdown'; var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel'; // IE10 has prefixed support, and case-sensitive if (window.MSPointerEvent) { POINTER_ELEMENT_EVENTS = 'MSPointerDown'; POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel'; } /** * Pointer events input * @constructor * @extends Input */ function PointerEventInput() { this.evEl = POINTER_ELEMENT_EVENTS; this.evWin = POINTER_WINDOW_EVENTS; Input.apply(this, arguments); this.store = (this.manager.session.pointerEvents = []); } inherit(PointerEventInput, Input, { /** * handle mouse events * @param {Object} ev */ handler: function PEhandler(ev) { var store = this.store; var removePointer = false; var eventTypeNormalized = ev.type.toLowerCase().replace('ms', ''); var eventType = POINTER_INPUT_MAP[eventTypeNormalized]; var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType; var isTouch = (pointerType == INPUT_TYPE_TOUCH); // get index of the event in the store var storeIndex = inArray(store, ev.pointerId, 'pointerId'); // start and mouse must be down if (eventType & INPUT_START && (ev.button === 0 || isTouch)) { if (storeIndex < 0) { store.push(ev); storeIndex = store.length - 1; } } else if (eventType & (INPUT_END | INPUT_CANCEL)) { removePointer = true; } // it not found, so the pointer hasn't been down (so it's probably a hover) if (storeIndex < 0) { return; } // update the event in the store store[storeIndex] = ev; this.callback(this.manager, eventType, { pointers: store, changedPointers: [ev], pointerType: pointerType, srcEvent: ev }); if (removePointer) { // remove from the store store.splice(storeIndex, 1); } } }); var SINGLE_TOUCH_INPUT_MAP = { touchstart: INPUT_START, touchmove: INPUT_MOVE, touchend: INPUT_END, touchcancel: INPUT_CANCEL }; var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart'; var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel'; /** * Touch events input * @constructor * @extends Input */ function SingleTouchInput() { this.evTarget = SINGLE_TOUCH_TARGET_EVENTS; this.evWin = SINGLE_TOUCH_WINDOW_EVENTS; this.started = false; Input.apply(this, arguments); } inherit(SingleTouchInput, Input, { handler: function TEhandler(ev) { var type = SINGLE_TOUCH_INPUT_MAP[ev.type]; // should we handle the touch events? if (type === INPUT_START) { this.started = true; } if (!this.started) { return; } var touches = normalizeSingleTouches.call(this, ev, type); // when done, reset the started state if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) { this.started = false; } this.callback(this.manager, type, { pointers: touches[0], changedPointers: touches[1], pointerType: INPUT_TYPE_TOUCH, srcEvent: ev }); } }); /** * @this {TouchInput} * @param {Object} ev * @param {Number} type flag * @returns {undefined|Array} [all, changed] */ function normalizeSingleTouches(ev, type) { var all = toArray(ev.touches); var changed = toArray(ev.changedTouches); if (type & (INPUT_END | INPUT_CANCEL)) { all = uniqueArray(all.concat(changed), 'identifier', true); } return [all, changed]; } var TOUCH_INPUT_MAP = { touchstart: INPUT_START, touchmove: INPUT_MOVE, touchend: INPUT_END, touchcancel: INPUT_CANCEL }; var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel'; /** * Multi-user touch events input * @constructor * @extends Input */ function TouchInput() { this.evTarget = TOUCH_TARGET_EVENTS; this.targetIds = {}; Input.apply(this, arguments); } inherit(TouchInput, Input, { handler: function MTEhandler(ev) { var type = TOUCH_INPUT_MAP[ev.type]; var touches = getTouches.call(this, ev, type); if (!touches) { return; } this.callback(this.manager, type, { pointers: touches[0], changedPointers: touches[1], pointerType: INPUT_TYPE_TOUCH, srcEvent: ev }); } }); /** * @this {TouchInput} * @param {Object} ev * @param {Number} type flag * @returns {undefined|Array} [all, changed] */ function getTouches(ev, type) { var allTouches = toArray(ev.touches); var targetIds = this.targetIds; // when there is only one touch, the process can be simplified if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) { targetIds[allTouches[0].identifier] = true; return [allTouches, allTouches]; } var i, targetTouches, changedTouches = toArray(ev.changedTouches), changedTargetTouches = [], target = this.target; // get target touches from touches targetTouches = allTouches.filter(function(touch) { return hasParent(touch.target, target); }); // collect touches if (type === INPUT_START) { i = 0; while (i < targetTouches.length) { targetIds[targetTouches[i].identifier] = true; i++; } } // filter changed touches to only contain touches that exist in the collected target ids i = 0; while (i < changedTouches.length) { if (targetIds[changedTouches[i].identifier]) { changedTargetTouches.push(changedTouches[i]); } // cleanup removed touches if (type & (INPUT_END | INPUT_CANCEL)) { delete targetIds[changedTouches[i].identifier]; } i++; } if (!changedTargetTouches.length) { return; } return [ // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel' uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true), changedTargetTouches ]; } /** * Combined touch and mouse input * * Touch has a higher priority then mouse, and while touching no mouse events are allowed. * This because touch devices also emit mouse events while doing a touch. * * @constructor * @extends Input */ function TouchMouseInput() { Input.apply(this, arguments); var handler = bindFn(this.handler, this); this.touch = new TouchInput(this.manager, handler); this.mouse = new MouseInput(this.manager, handler); } inherit(TouchMouseInput, Input, { /** * handle mouse and touch events * @param {Hammer} manager * @param {String} inputEvent * @param {Object} inputData */ handler: function TMEhandler(manager, inputEvent, inputData) { var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH), isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE); // when we're in a touch event, so block all upcoming mouse events // most mobile browser also emit mouseevents, right after touchstart if (isTouch) { this.mouse.allow = false; } else if (isMouse && !this.mouse.allow) { return; } // reset the allowMouse when we're done if (inputEvent & (INPUT_END | INPUT_CANCEL)) { this.mouse.allow = true; } this.callback(manager, inputEvent, inputData); }, /** * remove the event listeners */ destroy: function destroy() { this.touch.destroy(); this.mouse.destroy(); } }); var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction'); var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined; // magical touchAction value var TOUCH_ACTION_COMPUTE = 'compute'; var TOUCH_ACTION_AUTO = 'auto'; var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented var TOUCH_ACTION_NONE = 'none'; var TOUCH_ACTION_PAN_X = 'pan-x'; var TOUCH_ACTION_PAN_Y = 'pan-y'; /** * Touch Action * sets the touchAction property or uses the js alternative * @param {Manager} manager * @param {String} value * @constructor */ function TouchAction(manager, value) { this.manager = manager; this.set(value); } TouchAction.prototype = { /** * set the touchAction value on the element or enable the polyfill * @param {String} value */ set: function(value) { // find out the touch-action by the event handlers if (value == TOUCH_ACTION_COMPUTE) { value = this.compute(); } if (NATIVE_TOUCH_ACTION) { this.manager.element.style[PREFIXED_TOUCH_ACTION] = value; } this.actions = value.toLowerCase().trim(); }, /** * just re-set the touchAction value */ update: function() { this.set(this.manager.options.touchAction); }, /** * compute the value for the touchAction property based on the recognizer's settings * @returns {String} value */ compute: function() { var actions = []; each(this.manager.recognizers, function(recognizer) { if (boolOrFn(recognizer.options.enable, [recognizer])) { actions = actions.concat(recognizer.getTouchAction()); } }); return cleanTouchActions(actions.join(' ')); }, /** * this method is called on each input cycle and provides the preventing of the browser behavior * @param {Object} input */ preventDefaults: function(input) { // not needed with native support for the touchAction property if (NATIVE_TOUCH_ACTION) { return; } var srcEvent = input.srcEvent; var direction = input.offsetDirection; // if the touch action did prevented once this session if (this.manager.session.prevented) { srcEvent.preventDefault(); return; } var actions = this.actions; var hasNone = inStr(actions, TOUCH_ACTION_NONE); var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); if (hasNone || (hasPanY && direction & DIRECTION_HORIZONTAL) || (hasPanX && direction & DIRECTION_VERTICAL)) { return this.preventSrc(srcEvent); } }, /** * call preventDefault to prevent the browser's default behavior (scrolling in most cases) * @param {Object} srcEvent */ preventSrc: function(srcEvent) { this.manager.session.prevented = true; srcEvent.preventDefault(); } }; /** * when the touchActions are collected they are not a valid value, so we need to clean things up. * * @param {String} actions * @returns {*} */ function cleanTouchActions(actions) { // none if (inStr(actions, TOUCH_ACTION_NONE)) { return TOUCH_ACTION_NONE; } var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); // pan-x and pan-y can be combined if (hasPanX && hasPanY) { return TOUCH_ACTION_PAN_X + ' ' + TOUCH_ACTION_PAN_Y; } // pan-x OR pan-y if (hasPanX || hasPanY) { return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y; } // manipulation if (inStr(actions, TOUCH_ACTION_MANIPULATION)) { return TOUCH_ACTION_MANIPULATION; } return TOUCH_ACTION_AUTO; } /** * Recognizer flow explained; * * All recognizers have the initial state of POSSIBLE when a input session starts. * The definition of a input session is from the first input until the last input, with all it's movement in it. * * Example session for mouse-input: mousedown -> mousemove -> mouseup * * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed * which determines with state it should be. * * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to * POSSIBLE to give it another change on the next cycle. * * Possible * | * +-----+---------------+ * | | * +-----+-----+ | * | | | * Failed Cancelled | * +-------+------+ * | | * Recognized Began * | * Changed * | * Ended/Recognized */ var STATE_POSSIBLE = 1; var STATE_BEGAN = 2; var STATE_CHANGED = 4; var STATE_ENDED = 8; var STATE_RECOGNIZED = STATE_ENDED; var STATE_CANCELLED = 16; var STATE_FAILED = 32; /** * Recognizer * Every recognizer needs to extend from this class. * @constructor * @param {Object} options */ function Recognizer(options) { this.id = uniqueId(); this.manager = null; this.options = merge(options || {}, this.defaults); // default is enable true this.options.enable = ifUndefined(this.options.enable, true); this.state = STATE_POSSIBLE; this.simultaneous = {}; this.requireFail = []; } Recognizer.prototype = { /** * @virtual * @type {Object} */ defaults: {}, /** * set options * @param {Object} options * @return {Recognizer} */ set: function(options) { extend(this.options, options); // also update the touchAction, in case something changed about the directions/enabled state this.manager && this.manager.touchAction.update(); return this; }, /** * recognize simultaneous with an other recognizer. * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ recognizeWith: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) { return this; } var simultaneous = this.simultaneous; otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); if (!simultaneous[otherRecognizer.id]) { simultaneous[otherRecognizer.id] = otherRecognizer; otherRecognizer.recognizeWith(this); } return this; }, /** * drop the simultaneous link. it doesnt remove the link on the other recognizer. * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ dropRecognizeWith: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) { return this; } otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); delete this.simultaneous[otherRecognizer.id]; return this; }, /** * recognizer can only run when an other is failing * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ requireFailure: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) { return this; } var requireFail = this.requireFail; otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); if (inArray(requireFail, otherRecognizer) === -1) { requireFail.push(otherRecognizer); otherRecognizer.requireFailure(this); } return this; }, /** * drop the requireFailure link. it does not remove the link on the other recognizer. * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ dropRequireFailure: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) { return this; } otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); var index = inArray(this.requireFail, otherRecognizer); if (index > -1) { this.requireFail.splice(index, 1); } return this; }, /** * has require failures boolean * @returns {boolean} */ hasRequireFailures: function() { return this.requireFail.length > 0; }, /** * if the recognizer can recognize simultaneous with an other recognizer * @param {Recognizer} otherRecognizer * @returns {Boolean} */ canRecognizeWith: function(otherRecognizer) { return !!this.simultaneous[otherRecognizer.id]; }, /** * You should use `tryEmit` instead of `emit` directly to check * that all the needed recognizers has failed before emitting. * @param {Object} input */ emit: function(input) { var self = this; var state = this.state; function emit(withState) { self.manager.emit(self.options.event + (withState ? stateStr(state) : ''), input); } // 'panstart' and 'panmove' if (state < STATE_ENDED) { emit(true); } emit(); // simple 'eventName' events // panend and pancancel if (state >= STATE_ENDED) { emit(true); } }, /** * Check that all the require failure recognizers has failed, * if true, it emits a gesture event, * otherwise, setup the state to FAILED. * @param {Object} input */ tryEmit: function(input) { if (this.canEmit()) { return this.emit(input); } // it's failing anyway this.state = STATE_FAILED; }, /** * can we emit? * @returns {boolean} */ canEmit: function() { var i = 0; while (i < this.requireFail.length) { if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) { return false; } i++; } return true; }, /** * update the recognizer * @param {Object} inputData */ recognize: function(inputData) { // make a new copy of the inputData // so we can change the inputData without messing up the other recognizers var inputDataClone = extend({}, inputData); // is is enabled and allow recognizing? if (!boolOrFn(this.options.enable, [this, inputDataClone])) { this.reset(); this.state = STATE_FAILED; return; } // reset when we've reached the end if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) { this.state = STATE_POSSIBLE; } this.state = this.process(inputDataClone); // the recognizer has recognized a gesture // so trigger an event if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) { this.tryEmit(inputDataClone); } }, /** * return the state of the recognizer * the actual recognizing happens in this method * @virtual * @param {Object} inputData * @returns {Const} STATE */ process: function(inputData) { }, // jshint ignore:line /** * return the preferred touch-action * @virtual * @returns {Array} */ getTouchAction: function() { }, /** * called when the gesture isn't allowed to recognize * like when another is being recognized or it is disabled * @virtual */ reset: function() { } }; /** * get a usable string, used as event postfix * @param {Const} state * @returns {String} state */ function stateStr(state) { if (state & STATE_CANCELLED) { return 'cancel'; } else if (state & STATE_ENDED) { return 'end'; } else if (state & STATE_CHANGED) { return 'move'; } else if (state & STATE_BEGAN) { return 'start'; } return ''; } /** * direction cons to string * @param {Const} direction * @returns {String} */ function directionStr(direction) { if (direction == DIRECTION_DOWN) { return 'down'; } else if (direction == DIRECTION_UP) { return 'up'; } else if (direction == DIRECTION_LEFT) { return 'left'; } else if (direction == DIRECTION_RIGHT) { return 'right'; } return ''; } /** * get a recognizer by name if it is bound to a manager * @param {Recognizer|String} otherRecognizer * @param {Recognizer} recognizer * @returns {Recognizer} */ function getRecognizerByNameIfManager(otherRecognizer, recognizer) { var manager = recognizer.manager; if (manager) { return manager.get(otherRecognizer); } return otherRecognizer; } /** * This recognizer is just used as a base for the simple attribute recognizers. * @constructor * @extends Recognizer */ function AttrRecognizer() { Recognizer.apply(this, arguments); } inherit(AttrRecognizer, Recognizer, { /** * @namespace * @memberof AttrRecognizer */ defaults: { /** * @type {Number} * @default 1 */ pointers: 1 }, /** * Used to check if it the recognizer receives valid input, like input.distance > 10. * @memberof AttrRecognizer * @param {Object} input * @returns {Boolean} recognized */ attrTest: function(input) { var optionPointers = this.options.pointers; return optionPointers === 0 || input.pointers.length === optionPointers; }, /** * Process the input and return the state for the recognizer * @memberof AttrRecognizer * @param {Object} input * @returns {*} State */ process: function(input) { var state = this.state; var eventType = input.eventType; var isRecognized = state & (STATE_BEGAN | STATE_CHANGED); var isValid = this.attrTest(input); // on cancel input and we've recognized before, return STATE_CANCELLED if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) { return state | STATE_CANCELLED; } else if (isRecognized || isValid) { if (eventType & INPUT_END) { return state | STATE_ENDED; } else if (!(state & STATE_BEGAN)) { return STATE_BEGAN; } return state | STATE_CHANGED; } return STATE_FAILED; } }); /** * Pan * Recognized when the pointer is down and moved in the allowed direction. * @constructor * @extends AttrRecognizer */ function PanRecognizer() { AttrRecognizer.apply(this, arguments); this.pX = null; this.pY = null; } inherit(PanRecognizer, AttrRecognizer, { /** * @namespace * @memberof PanRecognizer */ defaults: { event: 'pan', threshold: 10, pointers: 1, direction: DIRECTION_ALL }, getTouchAction: function() { var direction = this.options.direction; var actions = []; if (direction & DIRECTION_HORIZONTAL) { actions.push(TOUCH_ACTION_PAN_Y); } if (direction & DIRECTION_VERTICAL) { actions.push(TOUCH_ACTION_PAN_X); } return actions; }, directionTest: function(input) { var options = this.options; var hasMoved = true; var distance = input.distance; var direction = input.direction; var x = input.deltaX; var y = input.deltaY; // lock to axis? if (!(direction & options.direction)) { if (options.direction & DIRECTION_HORIZONTAL) { direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT; hasMoved = x != this.pX; distance = Math.abs(input.deltaX); } else { direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN; hasMoved = y != this.pY; distance = Math.abs(input.deltaY); } } input.direction = direction; return hasMoved && distance > options.threshold && direction & options.direction; }, attrTest: function(input) { return AttrRecognizer.prototype.attrTest.call(this, input) && (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input))); }, emit: function(input) { this.pX = input.deltaX; this.pY = input.deltaY; var direction = directionStr(input.direction); if (direction) { this.manager.emit(this.options.event + direction, input); } this._super.emit.call(this, input); } }); /** * Pinch * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out). * @constructor * @extends AttrRecognizer */ function PinchRecognizer() { AttrRecognizer.apply(this, arguments); } inherit(PinchRecognizer, AttrRecognizer, { /** * @namespace * @memberof PinchRecognizer */ defaults: { event: 'pinch', threshold: 0, pointers: 2 }, getTouchAction: function() { return [TOUCH_ACTION_NONE]; }, attrTest: function(input) { return this._super.attrTest.call(this, input) && (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN); }, emit: function(input) { this._super.emit.call(this, input); if (input.scale !== 1) { var inOut = input.scale < 1 ? 'in' : 'out'; this.manager.emit(this.options.event + inOut, input); } } }); /** * Press * Recognized when the pointer is down for x ms without any movement. * @constructor * @extends Recognizer */ function PressRecognizer() { Recognizer.apply(this, arguments); this._timer = null; this._input = null; } inherit(PressRecognizer, Recognizer, { /** * @namespace * @memberof PressRecognizer */ defaults: { event: 'press', pointers: 1, time: 500, // minimal time of the pointer to be pressed threshold: 5 // a minimal movement is ok, but keep it low }, getTouchAction: function() { return [TOUCH_ACTION_AUTO]; }, process: function(input) { var options = this.options; var validPointers = input.pointers.length === options.pointers; var validMovement = input.distance < options.threshold; var validTime = input.deltaTime > options.time; this._input = input; // we only allow little movement // and we've reached an end event, so a tap is possible if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) { this.reset(); } else if (input.eventType & INPUT_START) { this.reset(); this._timer = setTimeoutContext(function() { this.state = STATE_RECOGNIZED; this.tryEmit(); }, options.time, this); } else if (input.eventType & INPUT_END) { return STATE_RECOGNIZED; } return STATE_FAILED; }, reset: function() { clearTimeout(this._timer); }, emit: function(input) { if (this.state !== STATE_RECOGNIZED) { return; } if (input && (input.eventType & INPUT_END)) { this.manager.emit(this.options.event + 'up', input); } else { this._input.timeStamp = now(); this.manager.emit(this.options.event, this._input); } } }); /** * Rotate * Recognized when two or more pointer are moving in a circular motion. * @constructor * @extends AttrRecognizer */ function RotateRecognizer() { AttrRecognizer.apply(this, arguments); } inherit(RotateRecognizer, AttrRecognizer, { /** * @namespace * @memberof RotateRecognizer */ defaults: { event: 'rotate', threshold: 0, pointers: 2 }, getTouchAction: function() { return [TOUCH_ACTION_NONE]; }, attrTest: function(input) { return this._super.attrTest.call(this, input) && (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN); } }); /** * Swipe * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction. * @constructor * @extends AttrRecognizer */ function SwipeRecognizer() { AttrRecognizer.apply(this, arguments); } inherit(SwipeRecognizer, AttrRecognizer, { /** * @namespace * @memberof SwipeRecognizer */ defaults: { event: 'swipe', threshold: 10, velocity: 0.65, direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL, pointers: 1 }, getTouchAction: function() { return PanRecognizer.prototype.getTouchAction.call(this); }, attrTest: function(input) { var direction = this.options.direction; var velocity; if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) { velocity = input.velocity; } else if (direction & DIRECTION_HORIZONTAL) { velocity = input.velocityX; } else if (direction & DIRECTION_VERTICAL) { velocity = input.velocityY; } return this._super.attrTest.call(this, input) && direction & input.direction && input.distance > this.options.threshold && abs(velocity) > this.options.velocity && input.eventType & INPUT_END; }, emit: function(input) { var direction = directionStr(input.direction); if (direction) { this.manager.emit(this.options.event + direction, input); } this.manager.emit(this.options.event, input); } }); /** * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur * between the given interval and position. The delay option can be used to recognize multi-taps without firing * a single tap. * * The eventData from the emitted event contains the property `tapCount`, which contains the amount of * multi-taps being recognized. * @constructor * @extends Recognizer */ function TapRecognizer() { Recognizer.apply(this, arguments); // previous time and center, // used for tap counting this.pTime = false; this.pCenter = false; this._timer = null; this._input = null; this.count = 0; } inherit(TapRecognizer, Recognizer, { /** * @namespace * @memberof PinchRecognizer */ defaults: { event: 'tap', pointers: 1, taps: 1, interval: 300, // max time between the multi-tap taps time: 250, // max time of the pointer to be down (like finger on the screen) threshold: 2, // a minimal movement is ok, but keep it low posThreshold: 10 // a multi-tap can be a bit off the initial position }, getTouchAction: function() { return [TOUCH_ACTION_MANIPULATION]; }, process: function(input) { var options = this.options; var validPointers = input.pointers.length === options.pointers; var validMovement = input.distance < options.threshold; var validTouchTime = input.deltaTime < options.time; this.reset(); if ((input.eventType & INPUT_START) && (this.count === 0)) { return this.failTimeout(); } // we only allow little movement // and we've reached an end event, so a tap is possible if (validMovement && validTouchTime && validPointers) { if (input.eventType != INPUT_END) { return this.failTimeout(); } var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true; var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold; this.pTime = input.timeStamp; this.pCenter = input.center; if (!validMultiTap || !validInterval) { this.count = 1; } else { this.count += 1; } this._input = input; // if tap count matches we have recognized it, // else it has began recognizing... var tapCount = this.count % options.taps; if (tapCount === 0) { // no failing requirements, immediately trigger the tap event // or wait as long as the multitap interval to trigger if (!this.hasRequireFailures()) { return STATE_RECOGNIZED; } else { this._timer = setTimeoutContext(function() { this.state = STATE_RECOGNIZED; this.tryEmit(); }, options.interval, this); return STATE_BEGAN; } } } return STATE_FAILED; }, failTimeout: function() { this._timer = setTimeoutContext(function() { this.state = STATE_FAILED; }, this.options.interval, this); return STATE_FAILED; }, reset: function() { clearTimeout(this._timer); }, emit: function() { if (this.state == STATE_RECOGNIZED ) { this._input.tapCount = this.count; this.manager.emit(this.options.event, this._input); } } }); /** * Simple way to create an manager with a default set of recognizers. * @param {HTMLElement} element * @param {Object} [options] * @constructor */ function Hammer(element, options) { options = options || {}; options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset); return new Manager(element, options); } /** * @const {string} */ Hammer.VERSION = '2.0.4'; /** * default settings * @namespace */ Hammer.defaults = { /** * set if DOM events are being triggered. * But this is slower and unused by simple implementations, so disabled by default. * @type {Boolean} * @default false */ domEvents: false, /** * The value for the touchAction property/fallback. * When set to `compute` it will magically set the correct value based on the added recognizers. * @type {String} * @default compute */ touchAction: TOUCH_ACTION_COMPUTE, /** * @type {Boolean} * @default true */ enable: true, /** * EXPERIMENTAL FEATURE -- can be removed/changed * Change the parent input target element. * If Null, then it is being set the to main element. * @type {Null|EventTarget} * @default null */ inputTarget: null, /** * force an input class * @type {Null|Function} * @default null */ inputClass: null, /** * Default recognizer setup when calling `Hammer()` * When creating a new Manager these will be skipped. * @type {Array} */ preset: [ // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...] [RotateRecognizer, { enable: false }], [PinchRecognizer, { enable: false }, ['rotate']], [SwipeRecognizer,{ direction: DIRECTION_HORIZONTAL }], [PanRecognizer, { direction: DIRECTION_HORIZONTAL }, ['swipe']], [TapRecognizer], [TapRecognizer, { event: 'doubletap', taps: 2 }, ['tap']], [PressRecognizer] ], /** * Some CSS properties can be used to improve the working of Hammer. * Add them to this method and they will be set when creating a new Manager. * @namespace */ cssProps: { /** * Disables text selection to improve the dragging gesture. Mainly for desktop browsers. * @type {String} * @default 'none' */ userSelect: 'none', /** * Disable the Windows Phone grippers when pressing an element. * @type {String} * @default 'none' */ touchSelect: 'none', /** * Disables the default callout shown when you touch and hold a touch target. * On iOS, when you touch and hold a touch target such as a link, Safari displays * a callout containing information about the link. This property allows you to disable that callout. * @type {String} * @default 'none' */ touchCallout: 'none', /** * Specifies whether zooming is enabled. Used by IE10> * @type {String} * @default 'none' */ contentZooming: 'none', /** * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers. * @type {String} * @default 'none' */ userDrag: 'none', /** * Overrides the highlight color shown when the user taps a link or a JavaScript * clickable element in iOS. This property obeys the alpha value, if specified. * @type {String} * @default 'rgba(0,0,0,0)' */ tapHighlightColor: 'rgba(0,0,0,0)' } }; var STOP = 1; var FORCED_STOP = 2; /** * Manager * @param {HTMLElement} element * @param {Object} [options] * @constructor */ function Manager(element, options) { options = options || {}; this.options = merge(options, Hammer.defaults); this.options.inputTarget = this.options.inputTarget || element; this.handlers = {}; this.session = {}; this.recognizers = []; this.element = element; this.input = createInputInstance(this); this.touchAction = new TouchAction(this, this.options.touchAction); toggleCssProps(this, true); each(options.recognizers, function(item) { var recognizer = this.add(new (item[0])(item[1])); item[2] && recognizer.recognizeWith(item[2]); item[3] && recognizer.requireFailure(item[3]); }, this); } Manager.prototype = { /** * set options * @param {Object} options * @returns {Manager} */ set: function(options) { extend(this.options, options); // Options that need a little more setup if (options.touchAction) { this.touchAction.update(); } if (options.inputTarget) { // Clean up existing event listeners and reinitialize this.input.destroy(); this.input.target = options.inputTarget; this.input.init(); } return this; }, /** * stop recognizing for this session. * This session will be discarded, when a new [input]start event is fired. * When forced, the recognizer cycle is stopped immediately. * @param {Boolean} [force] */ stop: function(force) { this.session.stopped = force ? FORCED_STOP : STOP; }, /** * run the recognizers! * called by the inputHandler function on every movement of the pointers (touches) * it walks through all the recognizers and tries to detect the gesture that is being made * @param {Object} inputData */ recognize: function(inputData) { var session = this.session; if (session.stopped) { return; } // run the touch-action polyfill this.touchAction.preventDefaults(inputData); var recognizer; var recognizers = this.recognizers; // this holds the recognizer that is being recognized. // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED // if no recognizer is detecting a thing, it is set to `null` var curRecognizer = session.curRecognizer; // reset when the last recognizer is recognized // or when we're in a new session if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) { curRecognizer = session.curRecognizer = null; } var i = 0; while (i < recognizers.length) { recognizer = recognizers[i]; // find out if we are allowed try to recognize the input for this one. // 1. allow if the session is NOT forced stopped (see the .stop() method) // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one // that is being recognized. // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer. // this can be setup with the `recognizeWith()` method on the recognizer. if (session.stopped !== FORCED_STOP && ( // 1 !curRecognizer || recognizer == curRecognizer || // 2 recognizer.canRecognizeWith(curRecognizer))) { // 3 recognizer.recognize(inputData); } else { recognizer.reset(); } // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the // current active recognizer. but only if we don't already have an active recognizer if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) { curRecognizer = session.curRecognizer = recognizer; } i++; } }, /** * get a recognizer by its event name. * @param {Recognizer|String} recognizer * @returns {Recognizer|Null} */ get: function(recognizer) { if (recognizer instanceof Recognizer) { return recognizer; } var recognizers = this.recognizers; for (var i = 0; i < recognizers.length; i++) { if (recognizers[i].options.event == recognizer) { return recognizers[i]; } } return null; }, /** * add a recognizer to the manager * existing recognizers with the same event name will be removed * @param {Recognizer} recognizer * @returns {Recognizer|Manager} */ add: function(recognizer) { if (invokeArrayArg(recognizer, 'add', this)) { return this; } // remove existing var existing = this.get(recognizer.options.event); if (existing) { this.remove(existing); } this.recognizers.push(recognizer); recognizer.manager = this; this.touchAction.update(); return recognizer; }, /** * remove a recognizer by name or instance * @param {Recognizer|String} recognizer * @returns {Manager} */ remove: function(recognizer) { if (invokeArrayArg(recognizer, 'remove', this)) { return this; } var recognizers = this.recognizers; recognizer = this.get(recognizer); recognizers.splice(inArray(recognizers, recognizer), 1); this.touchAction.update(); return this; }, /** * bind event * @param {String} events * @param {Function} handler * @returns {EventEmitter} this */ on: function(events, handler) { var handlers = this.handlers; each(splitStr(events), function(event) { handlers[event] = handlers[event] || []; handlers[event].push(handler); }); return this; }, /** * unbind event, leave emit blank to remove all handlers * @param {String} events * @param {Function} [handler] * @returns {EventEmitter} this */ off: function(events, handler) { var handlers = this.handlers; each(splitStr(events), function(event) { if (!handler) { delete handlers[event]; } else { handlers[event].splice(inArray(handlers[event], handler), 1); } }); return this; }, /** * emit event to the listeners * @param {String} event * @param {Object} data */ emit: function(event, data) { // we also want to trigger dom events if (this.options.domEvents) { triggerDomEvent(event, data); } // no handlers, so skip it all var handlers = this.handlers[event] && this.handlers[event].slice(); if (!handlers || !handlers.length) { return; } data.type = event; data.preventDefault = function() { data.srcEvent.preventDefault(); }; var i = 0; while (i < handlers.length) { handlers[i](data); i++; } }, /** * destroy the manager and unbinds all events * it doesn't unbind dom events, that is the user own responsibility */ destroy: function() { this.element && toggleCssProps(this, false); this.handlers = {}; this.session = {}; this.input.destroy(); this.element = null; } }; /** * add/remove the css properties as defined in manager.options.cssProps * @param {Manager} manager * @param {Boolean} add */ function toggleCssProps(manager, add) { var element = manager.element; each(manager.options.cssProps, function(value, name) { element.style[prefixed(element.style, name)] = add ? value : ''; }); } /** * trigger dom event * @param {String} event * @param {Object} data */ function triggerDomEvent(event, data) { var gestureEvent = document.createEvent('Event'); gestureEvent.initEvent(event, true, true); gestureEvent.gesture = data; data.target.dispatchEvent(gestureEvent); } extend(Hammer, { INPUT_START: INPUT_START, INPUT_MOVE: INPUT_MOVE, INPUT_END: INPUT_END, INPUT_CANCEL: INPUT_CANCEL, STATE_POSSIBLE: STATE_POSSIBLE, STATE_BEGAN: STATE_BEGAN, STATE_CHANGED: STATE_CHANGED, STATE_ENDED: STATE_ENDED, STATE_RECOGNIZED: STATE_RECOGNIZED, STATE_CANCELLED: STATE_CANCELLED, STATE_FAILED: STATE_FAILED, DIRECTION_NONE: DIRECTION_NONE, DIRECTION_LEFT: DIRECTION_LEFT, DIRECTION_RIGHT: DIRECTION_RIGHT, DIRECTION_UP: DIRECTION_UP, DIRECTION_DOWN: DIRECTION_DOWN, DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL, DIRECTION_VERTICAL: DIRECTION_VERTICAL, DIRECTION_ALL: DIRECTION_ALL, Manager: Manager, Input: Input, TouchAction: TouchAction, TouchInput: TouchInput, MouseInput: MouseInput, PointerEventInput: PointerEventInput, TouchMouseInput: TouchMouseInput, SingleTouchInput: SingleTouchInput, Recognizer: Recognizer, AttrRecognizer: AttrRecognizer, Tap: TapRecognizer, Pan: PanRecognizer, Swipe: SwipeRecognizer, Pinch: PinchRecognizer, Rotate: RotateRecognizer, Press: PressRecognizer, on: addEventListeners, off: removeEventListeners, each: each, merge: merge, extend: extend, inherit: inherit, bindFn: bindFn, prefixed: prefixed }); if (typeof define == TYPE_FUNCTION && define.amd) { define(function() { return Hammer; }); } else if (typeof module != 'undefined' && module.exports) { module.exports = Hammer; } else { window[exportName] = Hammer; } })(window, document, 'Hammer');
{ "pile_set_name": "Github" }
/* * (C) Copyright 2011 * Stefano Babic, DENX Software Engineering, [email protected] * * Based on Linux IPU driver for MX51 (ipu.h): * * (C) Copyright 2005-2010 Freescale Semiconductor, Inc. * * SPDX-License-Identifier: GPL-2.0+ */ #ifndef __IPU_PIXFMT_H__ #define __IPU_PIXFMT_H__ #include <linux/list.h> #include <linux/fb.h> /* IPU Pixel format definitions */ #define fourcc(a, b, c, d)\ (((__u32)(a)<<0)|((__u32)(b)<<8)|((__u32)(c)<<16)|((__u32)(d)<<24)) /* * Pixel formats are defined with ASCII FOURCC code. The pixel format codes are * the same used by V4L2 API. */ #define IPU_PIX_FMT_GENERIC fourcc('I', 'P', 'U', '0') #define IPU_PIX_FMT_GENERIC_32 fourcc('I', 'P', 'U', '1') #define IPU_PIX_FMT_LVDS666 fourcc('L', 'V', 'D', '6') #define IPU_PIX_FMT_LVDS888 fourcc('L', 'V', 'D', '8') #define IPU_PIX_FMT_RGB332 fourcc('R', 'G', 'B', '1') /*< 8 RGB-3-3-2 */ #define IPU_PIX_FMT_RGB555 fourcc('R', 'G', 'B', 'O') /*< 16 RGB-5-5-5 */ #define IPU_PIX_FMT_RGB565 fourcc('R', 'G', 'B', 'P') /*< 1 6 RGB-5-6-5 */ #define IPU_PIX_FMT_RGB666 fourcc('R', 'G', 'B', '6') /*< 18 RGB-6-6-6 */ #define IPU_PIX_FMT_BGR666 fourcc('B', 'G', 'R', '6') /*< 18 BGR-6-6-6 */ #define IPU_PIX_FMT_BGR24 fourcc('B', 'G', 'R', '3') /*< 24 BGR-8-8-8 */ #define IPU_PIX_FMT_RGB24 fourcc('R', 'G', 'B', '3') /*< 24 RGB-8-8-8 */ #define IPU_PIX_FMT_BGR32 fourcc('B', 'G', 'R', '4') /*< 32 BGR-8-8-8-8 */ #define IPU_PIX_FMT_BGRA32 fourcc('B', 'G', 'R', 'A') /*< 32 BGR-8-8-8-8 */ #define IPU_PIX_FMT_RGB32 fourcc('R', 'G', 'B', '4') /*< 32 RGB-8-8-8-8 */ #define IPU_PIX_FMT_RGBA32 fourcc('R', 'G', 'B', 'A') /*< 32 RGB-8-8-8-8 */ #define IPU_PIX_FMT_ABGR32 fourcc('A', 'B', 'G', 'R') /*< 32 ABGR-8-8-8-8 */ /* YUV Interleaved Formats */ #define IPU_PIX_FMT_YUYV fourcc('Y', 'U', 'Y', 'V') /*< 16 YUV 4:2:2 */ #define IPU_PIX_FMT_UYVY fourcc('U', 'Y', 'V', 'Y') /*< 16 YUV 4:2:2 */ #define IPU_PIX_FMT_Y41P fourcc('Y', '4', '1', 'P') /*< 12 YUV 4:1:1 */ #define IPU_PIX_FMT_YUV444 fourcc('Y', '4', '4', '4') /*< 24 YUV 4:4:4 */ /* two planes -- one Y, one Cb + Cr interleaved */ #define IPU_PIX_FMT_NV12 fourcc('N', 'V', '1', '2') /* 12 Y/CbCr 4:2:0 */ #define IPU_PIX_FMT_GREY fourcc('G', 'R', 'E', 'Y') /*< 8 Greyscale */ #define IPU_PIX_FMT_YVU410P fourcc('Y', 'V', 'U', '9') /*< 9 YVU 4:1:0 */ #define IPU_PIX_FMT_YUV410P fourcc('Y', 'U', 'V', '9') /*< 9 YUV 4:1:0 */ #define IPU_PIX_FMT_YVU420P fourcc('Y', 'V', '1', '2') /*< 12 YVU 4:2:0 */ #define IPU_PIX_FMT_YUV420P fourcc('I', '4', '2', '0') /*< 12 YUV 4:2:0 */ #define IPU_PIX_FMT_YUV420P2 fourcc('Y', 'U', '1', '2') /*< 12 YUV 4:2:0 */ #define IPU_PIX_FMT_YVU422P fourcc('Y', 'V', '1', '6') /*< 16 YVU 4:2:2 */ #define IPU_PIX_FMT_YUV422P fourcc('4', '2', '2', 'P') /*< 16 YUV 4:2:2 */ int ipuv3_fb_init(struct fb_videomode const *mode, uint8_t disp, uint32_t pixfmt); void ipuv3_fb_shutdown(void); #endif
{ "pile_set_name": "Github" }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_TEST_TEST_SUITE_H_ #define BASE_TEST_TEST_SUITE_H_ // Defines a basic test suite framework for running gtest based tests. You can // instantiate this class in your main function and call its Run method to run // any gtest based tests that are linked into your executable. #include <memory> #include <string> #include "base/at_exit.h" #include "base/macros.h" #include "base/test/trace_to_file.h" #include "build/build_config.h" namespace testing { class TestInfo; } namespace base { // Instantiates TestSuite, runs it and returns exit code. int RunUnitTestsUsingBaseTestSuite(int argc, char **argv); class TestSuite { public: // Match function used by the GetTestCount method. typedef bool (*TestMatch)(const testing::TestInfo&); TestSuite(int argc, char** argv); #if defined(OS_WIN) TestSuite(int argc, wchar_t** argv); #endif // defined(OS_WIN) virtual ~TestSuite(); // Returns true if the test is marked as "MAYBE_". // When using different prefixes depending on platform, we use MAYBE_ and // preprocessor directives to replace MAYBE_ with the target prefix. static bool IsMarkedMaybe(const testing::TestInfo& test); void CatchMaybeTests(); void ResetCommandLine(); void AddTestLauncherResultPrinter(); int Run(); protected: // By default fatal log messages (e.g. from DCHECKs) result in error dialogs // which gum up buildbots. Use a minimalistic assert handler which just // terminates the process. static void UnitTestAssertHandler(const std::string& str); // Disable crash dialogs so that it doesn't gum up the buildbot virtual void SuppressErrorDialogs(); // Override these for custom initialization and shutdown handling. Use these // instead of putting complex code in your constructor/destructor. virtual void Initialize(); virtual void Shutdown(); // Make sure that we setup an AtExitManager so Singleton objects will be // destroyed. std::unique_ptr<base::AtExitManager> at_exit_manager_; private: void InitializeFromCommandLine(int argc, char** argv); #if defined(OS_WIN) void InitializeFromCommandLine(int argc, wchar_t** argv); #endif // defined(OS_WIN) // Basic initialization for the test suite happens here. void PreInitialize(); test::TraceToFile trace_to_file_; bool initialized_command_line_; bool created_feature_list_; DISALLOW_COPY_AND_ASSIGN(TestSuite); }; } // namespace base #endif // BASE_TEST_TEST_SUITE_H_
{ "pile_set_name": "Github" }
package com.eveningoutpost.dexdrip.utils; public abstract class BytesGenerator { public byte[] produce() { return null; } }
{ "pile_set_name": "Github" }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred; import static java.util.concurrent.TimeUnit.MILLISECONDS; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.security.PrivilegedExceptionAction; import java.util.concurrent.ScheduledExecutorService; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.hadoop.fs.FSError; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocalDirAllocator; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.ClusterStorageCapacityExceededException; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.ipc.CallerContext; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.mapreduce.MRConfig; import org.apache.hadoop.mapreduce.MRJobConfig; import org.apache.hadoop.mapreduce.TaskType; import org.apache.hadoop.mapreduce.counters.Limits; import org.apache.hadoop.mapreduce.security.TokenCache; import org.apache.hadoop.mapreduce.security.token.JobTokenIdentifier; import org.apache.hadoop.mapreduce.security.token.JobTokenSecretManager; import org.apache.hadoop.mapreduce.v2.util.MRApps; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.metrics2.source.JvmMetrics; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.SecurityUtil; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.util.DiskChecker.DiskErrorException; import org.apache.hadoop.util.ShutdownHookManager; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.YarnUncaughtExceptionHandler; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.hadoop.yarn.api.ApplicationConstants.Environment; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.util.ConverterUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; /** * The main() for MapReduce task processes. */ class YarnChild { private static final Logger LOG = LoggerFactory.getLogger(YarnChild.class); static volatile TaskAttemptID taskid = null; public static void main(String[] args) throws Throwable { Thread.setDefaultUncaughtExceptionHandler(new YarnUncaughtExceptionHandler()); LOG.debug("Child starting"); final JobConf job = new JobConf(MRJobConfig.JOB_CONF_FILE); // Initing with our JobConf allows us to avoid loading confs twice Limits.init(job); UserGroupInformation.setConfiguration(job); // MAPREDUCE-6565: need to set configuration for SecurityUtil. SecurityUtil.setConfiguration(job); String host = args[0]; int port = Integer.parseInt(args[1]); final InetSocketAddress address = NetUtils.createSocketAddrForHost(host, port); final TaskAttemptID firstTaskid = TaskAttemptID.forName(args[2]); long jvmIdLong = Long.parseLong(args[3]); JVMId jvmId = new JVMId(firstTaskid.getJobID(), firstTaskid.getTaskType() == TaskType.MAP, jvmIdLong); CallerContext.setCurrent( new CallerContext.Builder("mr_" + firstTaskid.toString()).build()); // initialize metrics DefaultMetricsSystem.initialize( StringUtils.camelize(firstTaskid.getTaskType().name()) +"Task"); // Security framework already loaded the tokens into current ugi Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials(); LOG.info("Executing with tokens: {}", credentials.getAllTokens()); // Create TaskUmbilicalProtocol as actual task owner. UserGroupInformation taskOwner = UserGroupInformation.createRemoteUser(firstTaskid.getJobID().toString()); Token<JobTokenIdentifier> jt = TokenCache.getJobToken(credentials); SecurityUtil.setTokenService(jt, address); taskOwner.addToken(jt); final TaskUmbilicalProtocol umbilical = taskOwner.doAs(new PrivilegedExceptionAction<TaskUmbilicalProtocol>() { @Override public TaskUmbilicalProtocol run() throws Exception { return (TaskUmbilicalProtocol)RPC.getProxy(TaskUmbilicalProtocol.class, TaskUmbilicalProtocol.versionID, address, job); } }); // report non-pid to application master JvmContext context = new JvmContext(jvmId, "-1000"); LOG.debug("PID: " + System.getenv().get("JVM_PID")); Task task = null; UserGroupInformation childUGI = null; ScheduledExecutorService logSyncer = null; try { int idleLoopCount = 0; JvmTask myTask = null; // poll for new task for (int idle = 0; null == myTask; ++idle) { long sleepTimeMilliSecs = Math.min(idle * 500, 1500); LOG.info("Sleeping for " + sleepTimeMilliSecs + "ms before retrying again. Got null now."); MILLISECONDS.sleep(sleepTimeMilliSecs); myTask = umbilical.getTask(context); } if (myTask.shouldDie()) { return; } task = myTask.getTask(); YarnChild.taskid = task.getTaskID(); // Create the job-conf and set credentials configureTask(job, task, credentials, jt); // log the system properties String systemPropsToLog = MRApps.getSystemPropertiesToLog(job); if (systemPropsToLog != null) { LOG.info(systemPropsToLog); } // Initiate Java VM metrics JvmMetrics.initSingleton(jvmId.toString(), job.getSessionId()); childUGI = UserGroupInformation.createRemoteUser(System .getenv(ApplicationConstants.Environment.USER.toString())); // Add tokens to new user so that it may execute its task correctly. childUGI.addCredentials(credentials); // set job classloader if configured before invoking the task MRApps.setJobClassLoader(job); logSyncer = TaskLog.createLogSyncer(); // Create a final reference to the task for the doAs block final Task taskFinal = task; childUGI.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { // use job-specified working directory setEncryptedSpillKeyIfRequired(taskFinal); FileSystem.get(job).setWorkingDirectory(job.getWorkingDirectory()); taskFinal.run(job, umbilical); // run the task return null; } }); } catch (FSError e) { LOG.error("FSError from child", e); if (!ShutdownHookManager.get().isShutdownInProgress()) { umbilical.fsError(taskid, e.getMessage()); } } catch (Exception exception) { LOG.warn("Exception running child : " + StringUtils.stringifyException(exception)); try { if (task != null) { // do cleanup for the task if (childUGI == null) { // no need to job into doAs block task.taskCleanup(umbilical); } else { final Task taskFinal = task; childUGI.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { taskFinal.taskCleanup(umbilical); return null; } }); } } } catch (Exception e) { LOG.info("Exception cleaning up: " + StringUtils.stringifyException(e)); } // Report back any failures, for diagnostic purposes if (taskid != null) { if (!ShutdownHookManager.get().isShutdownInProgress()) { reportError(exception, task, umbilical); } } } catch (Throwable throwable) { LOG.error("Error running child : " + StringUtils.stringifyException(throwable)); if (taskid != null) { if (!ShutdownHookManager.get().isShutdownInProgress()) { Throwable tCause = throwable.getCause(); String cause = tCause == null ? throwable.getMessage() : StringUtils .stringifyException(tCause); umbilical.fatalError(taskid, cause, false); } } } finally { RPC.stopProxy(umbilical); DefaultMetricsSystem.shutdown(); TaskLog.syncLogsShutdown(logSyncer); } } @VisibleForTesting static void reportError(Exception exception, Task task, TaskUmbilicalProtocol umbilical) throws IOException { boolean fastFailJob = false; boolean hasClusterStorageCapacityExceededException = ExceptionUtils.indexOfType(exception, ClusterStorageCapacityExceededException.class) != -1; if (hasClusterStorageCapacityExceededException) { boolean killJobWhenExceedClusterStorageCapacity = task.getConf() .getBoolean(MRJobConfig.JOB_DFS_STORAGE_CAPACITY_KILL_LIMIT_EXCEED, MRJobConfig.DEFAULT_JOB_DFS_STORAGE_CAPACITY_KILL_LIMIT_EXCEED); if (killJobWhenExceedClusterStorageCapacity) { LOG.error( "Fast fail the job because the cluster storage capacity was exceeded."); fastFailJob = true; } } umbilical.fatalError(taskid, StringUtils.stringifyException(exception), fastFailJob); } /** * Utility method to check if the Encrypted Spill Key needs to be set into the * user credentials of the user running the Map / Reduce Task * @param task The Map / Reduce task to set the Encrypted Spill information in * @throws Exception */ public static void setEncryptedSpillKeyIfRequired(Task task) throws Exception { if ((task != null) && (task.getEncryptedSpillKey() != null) && (task .getEncryptedSpillKey().length > 1)) { Credentials creds = UserGroupInformation.getCurrentUser().getCredentials(); TokenCache.setEncryptedSpillKey(task.getEncryptedSpillKey(), creds); UserGroupInformation.getCurrentUser().addCredentials(creds); } } /** * Configure mapred-local dirs. This config is used by the task for finding * out an output directory. * @throws IOException */ private static void configureLocalDirs(Task task, JobConf job) throws IOException { String[] localSysDirs = StringUtils.getTrimmedStrings( System.getenv(Environment.LOCAL_DIRS.name())); job.setStrings(MRConfig.LOCAL_DIR, localSysDirs); LOG.info(MRConfig.LOCAL_DIR + " for child: " + job.get(MRConfig.LOCAL_DIR)); LocalDirAllocator lDirAlloc = new LocalDirAllocator(MRConfig.LOCAL_DIR); Path workDir = null; // First, try to find the JOB_LOCAL_DIR on this host. try { workDir = lDirAlloc.getLocalPathToRead("work", job); } catch (DiskErrorException e) { // DiskErrorException means dir not found. If not found, it will // be created below. } if (workDir == null) { // JOB_LOCAL_DIR doesn't exist on this host -- Create it. workDir = lDirAlloc.getLocalPathForWrite("work", job); FileSystem lfs = FileSystem.getLocal(job).getRaw(); boolean madeDir = false; try { madeDir = lfs.mkdirs(workDir); } catch (FileAlreadyExistsException e) { // Since all tasks will be running in their own JVM, the race condition // exists where multiple tasks could be trying to create this directory // at the same time. If this task loses the race, it's okay because // the directory already exists. madeDir = true; workDir = lDirAlloc.getLocalPathToRead("work", job); } if (!madeDir) { throw new IOException("Mkdirs failed to create " + workDir.toString()); } } job.set(MRJobConfig.JOB_LOCAL_DIR,workDir.toString()); } private static void configureTask(JobConf job, Task task, Credentials credentials, Token<JobTokenIdentifier> jt) throws IOException { job.setCredentials(credentials); ApplicationAttemptId appAttemptId = ContainerId.fromString( System.getenv(Environment.CONTAINER_ID.name())) .getApplicationAttemptId(); LOG.debug("APPLICATION_ATTEMPT_ID: " + appAttemptId); // Set it in conf, so as to be able to be used the the OutputCommitter. job.setInt(MRJobConfig.APPLICATION_ATTEMPT_ID, appAttemptId.getAttemptId()); // set tcp nodelay job.setBoolean("ipc.client.tcpnodelay", true); job.setClass(MRConfig.TASK_LOCAL_OUTPUT_CLASS, YarnOutputFiles.class, MapOutputFile.class); // set the jobToken and shuffle secrets into task task.setJobTokenSecret( JobTokenSecretManager.createSecretKey(jt.getPassword())); byte[] shuffleSecret = TokenCache.getShuffleSecretKey(credentials); if (shuffleSecret == null) { LOG.warn("Shuffle secret missing from task credentials." + " Using job token secret as shuffle secret."); shuffleSecret = jt.getPassword(); } task.setShuffleSecret( JobTokenSecretManager.createSecretKey(shuffleSecret)); // setup the child's MRConfig.LOCAL_DIR. configureLocalDirs(task, job); // setup the child's attempt directories // Do the task-type specific localization task.localizeConfiguration(job); // Set up the DistributedCache related configs MRApps.setupDistributedCacheLocal(job); // Overwrite the localized task jobconf which is linked to in the current // work-dir. Path localTaskFile = new Path(MRJobConfig.JOB_CONF_FILE); writeLocalJobFile(localTaskFile, job); task.setJobFile(localTaskFile.toString()); task.setConf(job); } private static final FsPermission urw_gr = FsPermission.createImmutable((short) 0640); /** * Write the task specific job-configuration file. * @throws IOException */ private static void writeLocalJobFile(Path jobFile, JobConf conf) throws IOException { FileSystem localFs = FileSystem.getLocal(conf); localFs.delete(jobFile); OutputStream out = null; try { out = FileSystem.create(localFs, jobFile, urw_gr); conf.writeXml(out); } finally { IOUtils.cleanupWithLogger(LOG, out); } } }
{ "pile_set_name": "Github" }
#!/bin/bash CONFIG_FILE="${BLOCK_INSTANCE:-~/.config/i3/config}" CONFIG_FILE=${CONFIG_FILE/\~/$HOME} LAUNCH_CMD=$(cat "${CONFIG_FILE}" | grep -v "^#" | grep -wi 'rofi\|dmenu' | awk -F 'exec ' '{print $2}') LAUNCH_NAME=$(echo "${LAUNCH_CMD}" | awk -F ' ' '{print $1}') VARIABLES=$(cat "${CONFIG_FILE}" | grep -E 'set\ \$' | awk -F ' ' '{$1 = "";print $0}') while read varPair; do varName=$(echo "${varPair}" | awk -F ' ' '{print $1}') varValue=$(echo "${varPair}" | awk -F ' ' '{print $2}') #echo "Replacing ${varName} with ${varValue}" LAUNCH_CMD=$(echo ${LAUNCH_CMD} | sed "s|$varName|$varValue|g") done <<< "$(echo -e "$VARIABLES")" #echo "${LAUNCH_CMD}" && exit echo "${LAUNCH_NAME}" echo "${LAUNCH_NAME}" echo "" if [[ "${BLOCK_BUTTON}" -gt 0 ]]; then eval ${LAUNCH_CMD} & fi
{ "pile_set_name": "Github" }
// Copyright 2015-present, Cyrill @ Schumacher.fm and the CoreStore contributors // // 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. // +build csall db package store_test import ( "context" "flag" "fmt" "testing" "github.com/corestoreio/pkg/sql/ddl" "github.com/corestoreio/pkg/sql/dmltest" "github.com/corestoreio/pkg/store" "github.com/corestoreio/pkg/store/scope" "github.com/corestoreio/pkg/util/assert" ) var ( runIntegration = flag.Bool("integration", false, "Enables MySQL/MariaDB integration tests, env var CS_DSN must be set") ) func TestWithLoadFromDB(t *testing.T) { if !*runIntegration { t.Skip("Skipping integration tests. You can enable them with via CLI option `-integration`") } dbc := dmltest.MustConnectDB(t) defer dmltest.Close(t, dbc) defer dmltest.SQLDumpLoad(t, "testdata/large_store*sql", &dmltest.SQLDumpOptions{ SkipDBCleanup: false, }).Deferred() tbls, err := store.NewTables(context.Background(), ddl.WithConnPool(dbc)) assert.NoError(t, err) srv, err := store.NewService(store.WithLoadFromDB(context.TODO(), tbls)) assert.NoError(t, err) // repr.Println(srv.Stores()) // repr.Println(srv.Groups()) // repr.Println(srv.Websites()) st, err := srv.DefaultStoreView() assert.NoError(t, err) assert.Exactly(t, "world_en", st.Code) websiteID, storeID, err := srv.DefaultStoreID(scope.Group.WithID(8)) assert.NoError(t, err) assert.Exactly(t, "StoreID 7 WebsiteID 1", fmt.Sprintf("StoreID %d WebsiteID %d", storeID, websiteID)) }
{ "pile_set_name": "Github" }
// // SE2AudioPlayerView.m // ios-v2-spika-enterprise // // Created by CloverField on 10/03/16. // Copyright © 2016 Clover Studio. All rights reserved. // #import "SE2AudioPlayerView.h" #import "CSUtils.h" #import "CSConfig.h" #import "CSDownloadManager.h" #import <AudioToolbox/AudioToolbox.h> #import <AVFoundation/AVFoundation.h> @interface SE2AudioPlayerView () <AVAudioPlayerDelegate> @property (strong, nonatomic) SE2MessageModel *message; @property ( nonatomic) CGRect rect; @property (nonatomic, strong) NSString* filePath; @property (nonatomic, strong) AVAudioPlayer* audioPlayer; @property (nonatomic, strong) NSTimer* updateTimer; @property (nonatomic, strong) NSString *url; @end @implementation SE2AudioPlayerView -(id)initWithFrame:(CGRect)frame url:(NSString*)url { if (self = [super initWithFrame:frame]) { self = [[[NSBundle mainBundle] loadNibNamed:[NSString stringWithFormat:@"%@", [self class]] owner:self options:nil] objectAtIndex:0]; _url = url; _rect = frame; [self initWithNib]; } return self; } - (IBAction)onViewInChat:(id)sender { if ([_delegate respondsToSelector:@selector(viewInChatSelected)]) { [_delegate viewInChatSelected]; } } - (void)layoutSubviews { [super layoutSubviews]; self.frame = _rect; } -(void)initWithNib { self.layer.cornerRadius = 5.0f; self.layer.borderWidth = 1.0f; self.layer.borderColor = kAppDefaultColor(1).CGColor; self.clipsToBounds = YES; self.playButton.alpha = 0; self.durationHolderView.layer.cornerRadius = self.durationHolderView.frame.size.height/2; self.durationHolderView.clipsToBounds = YES; self.durationHolderView.backgroundColor = kAppGrayLight(1); [self.durationSlider setMinimumTrackTintColor:[UIColor lightGrayColor]]; [self.durationSlider setMaximumTrackTintColor:kAppGrayLight(1)]; self.durationLabel.textColor = [UIColor grayColor]; self.separator.backgroundColor = kAppGrayLight(1); _filePath = _url; [self initAudio]; } - (void) initAudio { [UIView animateWithDuration:0.2 animations:^{ self.playButton.alpha = 1; }completion:^(BOOL finished) { }]; NSURL* soundFile = [NSURL fileURLWithPath:_filePath]; _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil]; _audioPlayer.delegate = self; self.durationSlider.maximumValue = self.audioPlayer.duration; } - (IBAction)onPlay:(id)sender { if([_audioPlayer isPlaying]){ [self pausePlaying]; }else{ [self startPlaying]; } } - (IBAction)onSlider:(id)sender { self.audioPlayer.currentTime = self.durationSlider.value; int currentTime = (int) self.audioPlayer.currentTime; NSString *time = [NSString stringWithFormat:@"%01d:%02d", currentTime / 60, currentTime % 60]; self.durationLabel.text = time; } -(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{ [self stopPlaying]; } -(void)pausePlaying { [_audioPlayer pause]; [_updateTimer invalidate]; _updateTimer = nil; self.playButton.selected = NO; } -(void) stopPlaying{ [_audioPlayer stop]; self.durationLabel.text = @"0:00"; self.durationSlider.value = 0; [self.updateTimer invalidate]; self.updateTimer = nil; self.playButton.selected = NO; } -(void) startPlaying{ [_audioPlayer play]; self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateSlider) userInfo:nil repeats:YES]; self.playButton.selected = YES; } - (void)updateSlider{ float progress = self.audioPlayer.currentTime; [self.durationSlider setValue:progress]; int currentTime = (int) progress; NSString *time = [NSString stringWithFormat:@"%01d:%02d", currentTime / 60, currentTime % 60]; self.durationLabel.text = time; } @end
{ "pile_set_name": "Github" }
package members import "github.com/gophercloud/gophercloud" func imageMembersURL(c *gophercloud.ServiceClient, imageID string) string { return c.ServiceURL("images", imageID, "members") } func listMembersURL(c *gophercloud.ServiceClient, imageID string) string { return imageMembersURL(c, imageID) } func createMemberURL(c *gophercloud.ServiceClient, imageID string) string { return imageMembersURL(c, imageID) } func imageMemberURL(c *gophercloud.ServiceClient, imageID string, memberID string) string { return c.ServiceURL("images", imageID, "members", memberID) } func getMemberURL(c *gophercloud.ServiceClient, imageID string, memberID string) string { return imageMemberURL(c, imageID, memberID) } func updateMemberURL(c *gophercloud.ServiceClient, imageID string, memberID string) string { return imageMemberURL(c, imageID, memberID) } func deleteMemberURL(c *gophercloud.ServiceClient, imageID string, memberID string) string { return imageMemberURL(c, imageID, memberID) }
{ "pile_set_name": "Github" }
//! moment.js locale configuration //! locale : Malay [ms-my] //! note : DEPRECATED, the correct one is [ms] //! author : Weldan Jamili : https://github.com/weldan import moment from '../moment'; export default moment.defineLocale('ms-my', { months : 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'), monthsShort : 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'), weekdays : 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'), weekdaysShort : 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'), weekdaysMin : 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'), longDateFormat : { LT : 'HH.mm', LTS : 'HH.mm.ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY [pukul] HH.mm', LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm' }, meridiemParse: /pagi|tengahari|petang|malam/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'pagi') { return hour; } else if (meridiem === 'tengahari') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === 'petang' || meridiem === 'malam') { return hour + 12; } }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'tengahari'; } else if (hours < 19) { return 'petang'; } else { return 'malam'; } }, calendar : { sameDay : '[Hari ini pukul] LT', nextDay : '[Esok pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kelmarin pukul] LT', lastWeek : 'dddd [lepas pukul] LT', sameElse : 'L' }, relativeTime : { future : 'dalam %s', past : '%s yang lepas', s : 'beberapa saat', m : 'seminit', mm : '%d minit', h : 'sejam', hh : '%d jam', d : 'sehari', dd : '%d hari', M : 'sebulan', MM : '%d bulan', y : 'setahun', yy : '%d tahun' }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } });
{ "pile_set_name": "Github" }
<template lang="html"> <report title="REPORTS.BALANCE.TITLE" color="danger" icon="fa-line-chart"> <p class="subtitle is-5">{{ 'REPORTS.COMMON.TIME_SPAN' | translate}}</p> <div class="field has-addons"> <div class="control"> <a class="button is-primary is-tag"> <icon fa="fa-calendar"/> </a> </div> <div class="control select is-primary"> <select v-model="options.period" @change="throwPeriod()"> <option v-for="time in timesSpan" :value="time.value">{{time.label | translate}}</option> </select> </div> </div> <p class="subtitle is-5">{{ 'REPORTS.COMMON.TIME_SPAN' | translate}}</p> <div class="field has-addons"> <div class="control"> <a class="button is-primary is-tag"> <icon fa="fa-arrows-h"/> </a> </div> <div class="control select is-primary"> <select v-model="options.aggreg" @change="throwAggreg()"> <option v-for="aggreg in aggregTypes" :value="aggreg.value">{{aggreg.label | translate}}</option> </select> </div> </div> <hr> <p class="subtitle is-5">{{ 'REPORTS.COMMON.CUSTOM_TIME_SPAN' | translate}}</p> <div class="field columns"> <div class="control field has-addons column"> <div class="control"> <a class="button is-primary is-tag"> <icon fa="fa-calendar-minus-o"/> </a> </div> <div class="control" style="width: 10vw"> <input class="input" type="text" v-model="firstCustomDate" @change="throwCustom()" @keydown.up="addOneDay('firstCustomDate')" @keydown.down="subtractOneDay('firstCustomDate')" :placeholder="'REPORTS.COMMON.PLACEHOLDERS.PICK_DATE' | translate"> </div> </div> <div class="control field has-addons column"> <div class="control"> <a class="button is-primary is-tag"> <icon fa="fa-calendar-plus-o"/> </a> </div> <div class="control" style="width: 10vw"> <input class="input" type="text" v-model="lastCustomDate" @change="throwCustom()" @keydown.up="addOneDay('lastCustomDate')" @keydown.down="subtractOneDay('lastCustomDate')" :placeholder="'REPORTS.COMMON.PLACEHOLDERS.PICK_DATE' | translate"> </div> </div> </div> </report> </template> <script> import icon from '@/components/common/icon' import report from '@/reports/components/report' import { ipcRenderer } from 'electron' import Database from '@/assets/Database.class' import chartJS from 'chart.js' // eslint-disable-line import moment from 'moment' import Vue from 'vue' import Migrator from '../../util/migrator' // Use datepart SQL to filter by week / month / day / quarter / // https://docs.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql?view=sql-server-2017 const colors = [ // eslint-disable-line {backgroundColor: 'rgba(50, 115, 221,0.2)', borderColor: '#3273dc'}, {backgroundColor: 'rgba(50, 221, 72, 0.2)', borderColor: '#32dd61'}, {backgroundColor: 'rgba(221, 188, 50, 0.2)', borderColor: '#d9dd32'}, // {backgroundColor: 'rgba(221, 50, 50, 0.2)', borderColor: '#dd3232'}, {backgroundColor: 'rgba(125, 50, 221, 0.2)', borderColor: '#5e32dd'} ] export default { components: {icon, report}, data: function () { return { db: null, myChart: null, firstCustomDate: null, lastCustomDate: null, accounts: [], options: { period: 'thismonth', aggreg: 'W', firstDate: moment().startOf('month').format('YYYY-MM-DD'), lastDate: moment().endOf('month').format('YYYY-MM-DD'), allDates: false }, aggregTypes: [ {value: 'Y', label: 'TIME.Y'}, {value: 'W', label: 'TIME.W'}, {value: 'm', label: 'TIME.M'} ], timesSpan: [ {value: 'thismonth', label: 'TIME.TM'}, {value: 'lastmonth', label: 'TIME.LM'}, {value: 'thisquarter', label: 'TIME.TQ'}, {value: 'lastquarter', label: 'TIME.LQ'}, {value: 'thisyear', label: 'TIME.TY'}, {value: 'lastyear', label: 'TIME.LY'}, {value: '', label: 'TIME.*'} ], config: { type: 'line', data: {datasets: []}, options: { legend: { position: 'bottom' }, fill: 'bottom', scales: { xAxes: [{ type: 'time', time: { parser: this.$root.settings.dateFormat, tooltipFormat: this.$root.settings.dateFormat }, scaleLabel: { display: true, labelString: Vue.filter('translate')('CHART.DATE') } }], yAxes: [{ scaleLabel: { display: true, labelString: Vue.filter('translate')('CHART.VALUE') } }] } } } } }, methods: { getAccounts: function (vm) { return new Promise(function (resolve, reject) { vm.accounts = [] let dbAccounts = null try { dbAccounts = vm.db.exec('SELECT * FROM Accounts') } catch (e) { dbAccounts = [] } finally { for (let i = 0; i < dbAccounts.length; i++) { vm.accounts.push(dbAccounts[i]) } resolve(vm) } }) }, updateConfig: function () { this.firstCustomDate = moment(this.options.firstDate, 'YYYY-MM-DD').format(this.$root.settings.dateFormat) this.lastCustomDate = moment(this.options.lastDate, 'YYYY-MM-DD').format(this.$root.settings.dateFormat) let tmpColors for (let i = 0; i < this.accounts.length; i++) { let data = null try { if (this.options.allDates) { data = this.db.exec(`SELECT date, SUM(amount) as amount FROM OPERATION WHERE account_name="${this.accounts[i].name}" GROUP BY strftime('%${this.options.aggreg}', date)`) } else { data = this.db.exec(`SELECT date, SUM(amount) as amount FROM OPERATION WHERE account_name="${this.accounts[i].name}" AND date BETWEEN "${this.options.firstDate}" AND "${this.options.lastDate}" GROUP BY strftime('%${this.options.aggreg}', date)`) } } catch (e) { data = [{date: moment().format('YYYY-MM-DD'), amount: 0}] } finally { tmpColors = this.getColors() if (typeof this.config.data.datasets[i] === 'undefined') { this.config.data.datasets.push({ label: this.accounts[i].name, backgroundColor: tmpColors.backgroundColor, borderColor: tmpColors.borderColor, borderWidth: 1, data: [] }) } else { this.config.data.datasets[i].data = [] } for (let j = 0; j < data.length; j++) { this.config.data.datasets[i].data.push({ x: moment(data[j].date, 'YYYY-MM-DD').format(this.$root.settings.dateFormat), y: data[j].amount.toFixed(2) }) } while (this.config.data.datasets[i].data.length !== data.length) { this.config.data.datasets[i].data.pop() } } } }, throwPeriod: function () { this.options.allDates = false switch (this.options.period) { case 'thismonth': this.options.firstDate = moment().startOf('month').format('YYYY-MM-DD') this.options.lastDate = moment().endOf('month').format('YYYY-MM-DD') break case 'lastmonth': this.options.firstDate = moment().subtract(1, 'month').startOf('month').format('YYYY-MM-DD') this.options.lastDate = moment().subtract(1, 'month').endOf('month').format('YYYY-MM-DD') break case 'thisquarter': this.options.firstDate = moment().startOf('quarter').format('YYYY-MM-DD') this.options.lastDate = moment().endOf('quarter').format('YYYY-MM-DD') break case 'lastquarter': this.options.firstDate = moment().subtract(1, 'quarter').startOf('quarter').format('YYYY-MM-DD') this.options.lastDate = moment().subtract(1, 'quarter').endOf('quarter').format('YYYY-MM-DD') break case 'thisyear': this.options.firstDate = moment().startOf('year').format('YYYY-MM-DD') this.options.lastDate = moment().endOf('year').format('YYYY-MM-DD') break case 'lastyear': this.options.firstDate = moment().subtract(1, 'year').startOf('year').format('YYYY-MM-DD') this.options.lastDate = moment().subtract(1, 'year').endOf('year').format('YYYY-MM-DD') break default: this.options.allDates = true } this.updateConfig() this.myChart.update() }, throwAggreg: function () { this.updateConfig() this.myChart.update() }, throwCustom: function () { this.options.firstDate = moment(this.firstCustomDate, this.$root.settings.dateFormat).format('YYYY-MM-DD') this.options.lastDate = moment(this.lastCustomDate, this.$root.settings.dateFormat).format('YYYY-MM-DD') this.updateConfig() this.myChart.update() }, addOneDay: function (date) { this[date] = moment(this[date], this.$root.settings.dateFormat).add(1, 'days').format(this.$root.settings.dateFormat) this.throwCustom() }, subtractOneDay: function (date) { this[date] = moment(this[date], this.$root.settings.dateFormat).subtract(1, 'days').format(this.$root.settings.dateFormat) this.throwCustom() }, getColors: function () { const tmp = colors.shift() colors.push(tmp) return tmp } }, mounted: function () { const ctx = document.getElementById('myChart') if (!this.$root.settings.lastfile) { this.db = new Database() } else { try { this.db = new Database(this.$root.settings.lastfile) } catch (e) { console.warn(e.message) this.db = new Database() } } // TODO only on app start Migrator.migrate(this.db) this.getAccounts(this).then(function (vm) { }) this.updateConfig() if (this.$root.settings.theme === 'dark') { this.config.options.legend.labels = {fontColor: 'rgb(237, 237, 237)'} } this.myChart = new Chart(ctx, this.config) // eslint-disable-line ipcRenderer.send('open-report', 'balanceWin') } } </script>
{ "pile_set_name": "Github" }
;;; ol-notmuch.el --- Links to notmuch messages ;; Copyright (C) 2010-2014 Matthieu Lemerre ;; Author: Matthieu Lemerre <[email protected]> ;; Keywords: outlines, hypermedia, calendar, wp ;; Homepage: https://orgmode.org ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 2, or (at your option) ;; any later version. ;; This file 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>. ;;; Commentary: ;; This file implements links to notmuch messages and "searches". A ;; search is a query to be performed by notmuch; it is the equivalent ;; to folders in other mail clients. Similarly, mails are referred to ;; by a query, so both a link can refer to several mails. ;; Links have one the following form ;; notmuch:<search terms> ;; notmuch-search:<search terms>. ;; The first form open the queries in notmuch-show mode, whereas the ;; second link open it in notmuch-search mode. Note that queries are ;; performed at the time the link is opened, and the result may be ;; different from when the link was stored. ;;; Code: (require 'ol) ;; customisable notmuch open functions (defcustom org-notmuch-open-function 'org-notmuch-follow-link "Function used to follow notmuch links. Should accept a notmuch search string as the sole argument." :group 'org-notmuch :version "24.4" :package-version '(Org . "8.0") :type 'function) (defcustom org-notmuch-search-open-function 'org-notmuch-search-follow-link "Function used to follow notmuch-search links. Should accept a notmuch search string as the sole argument." :group 'org-notmuch :version "24.4" :package-version '(Org . "8.0") :type 'function) (make-obsolete-variable 'org-notmuch-search-open-function nil "9.3") ;; Install the link type (org-link-set-parameters "notmuch" :follow #'org-notmuch-open :store #'org-notmuch-store-link) (defun org-notmuch-store-link () "Store a link to a notmuch search or message." (when (memq major-mode '(notmuch-show-mode notmuch-tree-mode)) (let* ((message-id (notmuch-show-get-message-id t)) (subject (notmuch-show-get-subject)) (to (notmuch-show-get-to)) (from (notmuch-show-get-from)) (date (org-trim (notmuch-show-get-date))) desc link) (org-link-store-props :type "notmuch" :from from :to to :date date :subject subject :message-id message-id) (setq desc (org-link-email-description)) (setq link (concat "notmuch:id:" message-id)) (org-link-add-props :link link :description desc) link))) (defun org-notmuch-open (path) "Follow a notmuch message link specified by PATH." (funcall org-notmuch-open-function path)) (defun org-notmuch-follow-link (search) "Follow a notmuch link to SEARCH. Can link to more than one message, if so all matching messages are shown." (require 'notmuch) (notmuch-show search)) (org-link-set-parameters "notmuch-search" :follow #'org-notmuch-search-open :store #'org-notmuch-search-store-link) (defun org-notmuch-search-store-link () "Store a link to a notmuch search or message." (when (eq major-mode 'notmuch-search-mode) (let ((link (concat "notmuch-search:" notmuch-search-query-string)) (desc (concat "Notmuch search: " notmuch-search-query-string))) (org-link-store-props :type "notmuch-search" :link link :description desc) link))) (defun org-notmuch-search-open (path) "Follow a notmuch message link specified by PATH." (message "%s" path) (org-notmuch-search-follow-link path)) (defun org-notmuch-search-follow-link (search) "Follow a notmuch link by displaying SEARCH in notmuch-search mode." (require 'notmuch) (notmuch-search search)) (org-link-set-parameters "notmuch-tree" :follow #'org-notmuch-tree-open :store #'org-notmuch-tree-store-link) (defun org-notmuch-tree-store-link () "Store a link to a notmuch search or message." (when (eq major-mode 'notmuch-tree-mode) (let ((link (concat "notmuch-tree:" (notmuch-tree-get-query))) (desc (concat "Notmuch tree: " (notmuch-tree-get-query)))) (org-link-store-props :type "notmuch-tree" :link link :description desc) link))) (defun org-notmuch-tree-open (path) "Follow a notmuch message link specified by PATH." (message "%s" path) (org-notmuch-tree-follow-link path)) (defun org-notmuch-tree-follow-link (search) "Follow a notmuch link by displaying SEARCH in notmuch-tree mode." (require 'notmuch) (notmuch-tree search)) (provide 'ol-notmuch) ;;; ol-notmuch.el ends here
{ "pile_set_name": "Github" }
* { p : v }
{ "pile_set_name": "Github" }
/* * * Copyright 2014 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "context" "errors" "io" "math" "strconv" "sync" "time" "golang.org/x/net/trace" "google.golang.org/grpc/balancer" "google.golang.org/grpc/codes" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/encoding" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal/binarylog" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcrand" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" ) // StreamHandler defines the handler called by gRPC server to complete the // execution of a streaming RPC. If a StreamHandler returns an error, it // should be produced by the status package, or else gRPC will use // codes.Unknown as the status code and err.Error() as the status message // of the RPC. type StreamHandler func(srv interface{}, stream ServerStream) error // StreamDesc represents a streaming RPC service's method specification. type StreamDesc struct { StreamName string Handler StreamHandler // At least one of these is true. ServerStreams bool ClientStreams bool } // Stream defines the common interface a client or server stream has to satisfy. // // Deprecated: See ClientStream and ServerStream documentation instead. type Stream interface { // Deprecated: See ClientStream and ServerStream documentation instead. Context() context.Context // Deprecated: See ClientStream and ServerStream documentation instead. SendMsg(m interface{}) error // Deprecated: See ClientStream and ServerStream documentation instead. RecvMsg(m interface{}) error } // ClientStream defines the client-side behavior of a streaming RPC. // // All errors returned from ClientStream methods are compatible with the // status package. type ClientStream interface { // Header returns the header metadata received from the server if there // is any. It blocks if the metadata is not ready to read. Header() (metadata.MD, error) // Trailer returns the trailer metadata from the server, if there is any. // It must only be called after stream.CloseAndRecv has returned, or // stream.Recv has returned a non-nil error (including io.EOF). Trailer() metadata.MD // CloseSend closes the send direction of the stream. It closes the stream // when non-nil error is met. It is also not safe to call CloseSend // concurrently with SendMsg. CloseSend() error // Context returns the context for this stream. // // It should not be called until after Header or RecvMsg has returned. Once // called, subsequent client-side retries are disabled. Context() context.Context // SendMsg is generally called by generated code. On error, SendMsg aborts // the stream. If the error was generated by the client, the status is // returned directly; otherwise, io.EOF is returned and the status of // the stream may be discovered using RecvMsg. // // SendMsg blocks until: // - There is sufficient flow control to schedule m with the transport, or // - The stream is done, or // - The stream breaks. // // SendMsg does not wait until the message is received by the server. An // untimely stream closure may result in lost messages. To ensure delivery, // users should ensure the RPC completed successfully using RecvMsg. // // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not safe // to call SendMsg on the same stream in different goroutines. It is also // not safe to call CloseSend concurrently with SendMsg. SendMsg(m interface{}) error // RecvMsg blocks until it receives a message into m or the stream is // done. It returns io.EOF when the stream completes successfully. On // any other error, the stream is aborted and the error contains the RPC // status. // // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not // safe to call RecvMsg on the same stream in different goroutines. RecvMsg(m interface{}) error } // NewStream creates a new Stream for the client side. This is typically // called by generated code. ctx is used for the lifetime of the stream. // // To ensure resources are not leaked due to the stream returned, one of the following // actions must be performed: // // 1. Call Close on the ClientConn. // 2. Cancel the context provided. // 3. Call RecvMsg until a non-nil error is returned. A protobuf-generated // client-streaming RPC, for instance, might use the helper function // CloseAndRecv (note that CloseSend does not Recv, therefore is not // guaranteed to release all resources). // 4. Receive a non-nil, non-io.EOF error from Header or SendMsg. // // If none of the above happen, a goroutine and a context will be leaked, and grpc // will not call the optionally-configured stats handler with a stats.End message. func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) { // allow interceptor to see all applicable call options, which means those // configured as defaults from dial option as well as per-call options opts = combine(cc.dopts.callOptions, opts) if cc.dopts.streamInt != nil { return cc.dopts.streamInt(ctx, desc, cc, method, newClientStream, opts...) } return newClientStream(ctx, desc, cc, method, opts...) } // NewClientStream is a wrapper for ClientConn.NewStream. func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) { return cc.NewStream(ctx, desc, method, opts...) } func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) { if channelz.IsOn() { cc.incrCallsStarted() defer func() { if err != nil { cc.incrCallsFailed() } }() } c := defaultCallInfo() // Provide an opportunity for the first RPC to see the first service config // provided by the resolver. if err := cc.waitForResolvedAddrs(ctx); err != nil { return nil, err } mc := cc.GetMethodConfig(method) if mc.WaitForReady != nil { c.failFast = !*mc.WaitForReady } // Possible context leak: // The cancel function for the child context we create will only be called // when RecvMsg returns a non-nil error, if the ClientConn is closed, or if // an error is generated by SendMsg. // https://github.com/grpc/grpc-go/issues/1818. var cancel context.CancelFunc if mc.Timeout != nil && *mc.Timeout >= 0 { ctx, cancel = context.WithTimeout(ctx, *mc.Timeout) } else { ctx, cancel = context.WithCancel(ctx) } defer func() { if err != nil { cancel() } }() for _, o := range opts { if err := o.before(c); err != nil { return nil, toRPCErr(err) } } c.maxSendMessageSize = getMaxSize(mc.MaxReqSize, c.maxSendMessageSize, defaultClientMaxSendMessageSize) c.maxReceiveMessageSize = getMaxSize(mc.MaxRespSize, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize) if err := setCallInfoCodec(c); err != nil { return nil, err } callHdr := &transport.CallHdr{ Host: cc.authority, Method: method, ContentSubtype: c.contentSubtype, } // Set our outgoing compression according to the UseCompressor CallOption, if // set. In that case, also find the compressor from the encoding package. // Otherwise, use the compressor configured by the WithCompressor DialOption, // if set. var cp Compressor var comp encoding.Compressor if ct := c.compressorType; ct != "" { callHdr.SendCompress = ct if ct != encoding.Identity { comp = encoding.GetCompressor(ct) if comp == nil { return nil, status.Errorf(codes.Internal, "grpc: Compressor is not installed for requested grpc-encoding %q", ct) } } } else if cc.dopts.cp != nil { callHdr.SendCompress = cc.dopts.cp.Type() cp = cc.dopts.cp } if c.creds != nil { callHdr.Creds = c.creds } var trInfo traceInfo if EnableTracing { trInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method) trInfo.firstLine.client = true if deadline, ok := ctx.Deadline(); ok { trInfo.firstLine.deadline = time.Until(deadline) } trInfo.tr.LazyLog(&trInfo.firstLine, false) ctx = trace.NewContext(ctx, trInfo.tr) } ctx = newContextWithRPCInfo(ctx, c.failFast) sh := cc.dopts.copts.StatsHandler var beginTime time.Time if sh != nil { ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: c.failFast}) beginTime = time.Now() begin := &stats.Begin{ Client: true, BeginTime: beginTime, FailFast: c.failFast, } sh.HandleRPC(ctx, begin) } cs := &clientStream{ callHdr: callHdr, ctx: ctx, methodConfig: &mc, opts: opts, callInfo: c, cc: cc, desc: desc, codec: c.codec, cp: cp, comp: comp, cancel: cancel, beginTime: beginTime, firstAttempt: true, } if !cc.dopts.disableRetry { cs.retryThrottler = cc.retryThrottler.Load().(*retryThrottler) } cs.binlog = binarylog.GetMethodLogger(method) cs.callInfo.stream = cs // Only this initial attempt has stats/tracing. // TODO(dfawley): move to newAttempt when per-attempt stats are implemented. if err := cs.newAttemptLocked(sh, trInfo); err != nil { cs.finish(err) return nil, err } op := func(a *csAttempt) error { return a.newStream() } if err := cs.withRetry(op, func() { cs.bufferForRetryLocked(0, op) }); err != nil { cs.finish(err) return nil, err } if cs.binlog != nil { md, _ := metadata.FromOutgoingContext(ctx) logEntry := &binarylog.ClientHeader{ OnClientSide: true, Header: md, MethodName: method, Authority: cs.cc.authority, } if deadline, ok := ctx.Deadline(); ok { logEntry.Timeout = time.Until(deadline) if logEntry.Timeout < 0 { logEntry.Timeout = 0 } } cs.binlog.Log(logEntry) } if desc != unaryStreamDesc { // Listen on cc and stream contexts to cleanup when the user closes the // ClientConn or cancels the stream context. In all other cases, an error // should already be injected into the recv buffer by the transport, which // the client will eventually receive, and then we will cancel the stream's // context in clientStream.finish. go func() { select { case <-cc.ctx.Done(): cs.finish(ErrClientConnClosing) case <-ctx.Done(): cs.finish(toRPCErr(ctx.Err())) } }() } return cs, nil } func (cs *clientStream) newAttemptLocked(sh stats.Handler, trInfo traceInfo) error { cs.attempt = &csAttempt{ cs: cs, dc: cs.cc.dopts.dc, statsHandler: sh, trInfo: trInfo, } if err := cs.ctx.Err(); err != nil { return toRPCErr(err) } t, done, err := cs.cc.getTransport(cs.ctx, cs.callInfo.failFast, cs.callHdr.Method) if err != nil { return err } cs.attempt.t = t cs.attempt.done = done return nil } func (a *csAttempt) newStream() error { cs := a.cs cs.callHdr.PreviousAttempts = cs.numRetries s, err := a.t.NewStream(cs.ctx, cs.callHdr) if err != nil { return toRPCErr(err) } cs.attempt.s = s cs.attempt.p = &parser{r: s} return nil } // clientStream implements a client side Stream. type clientStream struct { callHdr *transport.CallHdr opts []CallOption callInfo *callInfo cc *ClientConn desc *StreamDesc codec baseCodec cp Compressor comp encoding.Compressor cancel context.CancelFunc // cancels all attempts sentLast bool // sent an end stream beginTime time.Time methodConfig *MethodConfig ctx context.Context // the application's context, wrapped by stats/tracing retryThrottler *retryThrottler // The throttler active when the RPC began. binlog *binarylog.MethodLogger // Binary logger, can be nil. // serverHeaderBinlogged is a boolean for whether server header has been // logged. Server header will be logged when the first time one of those // happens: stream.Header(), stream.Recv(). // // It's only read and used by Recv() and Header(), so it doesn't need to be // synchronized. serverHeaderBinlogged bool mu sync.Mutex firstAttempt bool // if true, transparent retry is valid numRetries int // exclusive of transparent retry attempt(s) numRetriesSincePushback int // retries since pushback; to reset backoff finished bool // TODO: replace with atomic cmpxchg or sync.Once? attempt *csAttempt // the active client stream attempt // TODO(hedging): hedging will have multiple attempts simultaneously. committed bool // active attempt committed for retry? buffer []func(a *csAttempt) error // operations to replay on retry bufferSize int // current size of buffer } // csAttempt implements a single transport stream attempt within a // clientStream. type csAttempt struct { cs *clientStream t transport.ClientTransport s *transport.Stream p *parser done func(balancer.DoneInfo) finished bool dc Decompressor decomp encoding.Compressor decompSet bool mu sync.Mutex // guards trInfo.tr // trInfo.tr is set when created (if EnableTracing is true), // and cleared when the finish method is called. trInfo traceInfo statsHandler stats.Handler } func (cs *clientStream) commitAttemptLocked() { cs.committed = true cs.buffer = nil } func (cs *clientStream) commitAttempt() { cs.mu.Lock() cs.commitAttemptLocked() cs.mu.Unlock() } // shouldRetry returns nil if the RPC should be retried; otherwise it returns // the error that should be returned by the operation. func (cs *clientStream) shouldRetry(err error) error { if cs.attempt.s == nil && !cs.callInfo.failFast { // In the event of any error from NewStream (attempt.s == nil), we // never attempted to write anything to the wire, so we can retry // indefinitely for non-fail-fast RPCs. return nil } if cs.finished || cs.committed { // RPC is finished or committed; cannot retry. return err } // Wait for the trailers. if cs.attempt.s != nil { <-cs.attempt.s.Done() } if cs.firstAttempt && !cs.callInfo.failFast && (cs.attempt.s == nil || cs.attempt.s.Unprocessed()) { // First attempt, wait-for-ready, stream unprocessed: transparently retry. cs.firstAttempt = false return nil } cs.firstAttempt = false if cs.cc.dopts.disableRetry { return err } pushback := 0 hasPushback := false if cs.attempt.s != nil { if to, toErr := cs.attempt.s.TrailersOnly(); toErr != nil || !to { return err } // TODO(retry): Move down if the spec changes to not check server pushback // before considering this a failure for throttling. sps := cs.attempt.s.Trailer()["grpc-retry-pushback-ms"] if len(sps) == 1 { var e error if pushback, e = strconv.Atoi(sps[0]); e != nil || pushback < 0 { grpclog.Infof("Server retry pushback specified to abort (%q).", sps[0]) cs.retryThrottler.throttle() // This counts as a failure for throttling. return err } hasPushback = true } else if len(sps) > 1 { grpclog.Warningf("Server retry pushback specified multiple values (%q); not retrying.", sps) cs.retryThrottler.throttle() // This counts as a failure for throttling. return err } } var code codes.Code if cs.attempt.s != nil { code = cs.attempt.s.Status().Code() } else { code = status.Convert(err).Code() } rp := cs.methodConfig.retryPolicy if rp == nil || !rp.retryableStatusCodes[code] { return err } // Note: the ordering here is important; we count this as a failure // only if the code matched a retryable code. if cs.retryThrottler.throttle() { return err } if cs.numRetries+1 >= rp.maxAttempts { return err } var dur time.Duration if hasPushback { dur = time.Millisecond * time.Duration(pushback) cs.numRetriesSincePushback = 0 } else { fact := math.Pow(rp.backoffMultiplier, float64(cs.numRetriesSincePushback)) cur := float64(rp.initialBackoff) * fact if max := float64(rp.maxBackoff); cur > max { cur = max } dur = time.Duration(grpcrand.Int63n(int64(cur))) cs.numRetriesSincePushback++ } // TODO(dfawley): we could eagerly fail here if dur puts us past the // deadline, but unsure if it is worth doing. t := time.NewTimer(dur) select { case <-t.C: cs.numRetries++ return nil case <-cs.ctx.Done(): t.Stop() return status.FromContextError(cs.ctx.Err()).Err() } } // Returns nil if a retry was performed and succeeded; error otherwise. func (cs *clientStream) retryLocked(lastErr error) error { for { cs.attempt.finish(lastErr) if err := cs.shouldRetry(lastErr); err != nil { cs.commitAttemptLocked() return err } if err := cs.newAttemptLocked(nil, traceInfo{}); err != nil { return err } if lastErr = cs.replayBufferLocked(); lastErr == nil { return nil } } } func (cs *clientStream) Context() context.Context { cs.commitAttempt() // No need to lock before using attempt, since we know it is committed and // cannot change. return cs.attempt.s.Context() } func (cs *clientStream) withRetry(op func(a *csAttempt) error, onSuccess func()) error { cs.mu.Lock() for { if cs.committed { cs.mu.Unlock() return op(cs.attempt) } a := cs.attempt cs.mu.Unlock() err := op(a) cs.mu.Lock() if a != cs.attempt { // We started another attempt already. continue } if err == io.EOF { <-a.s.Done() } if err == nil || (err == io.EOF && a.s.Status().Code() == codes.OK) { onSuccess() cs.mu.Unlock() return err } if err := cs.retryLocked(err); err != nil { cs.mu.Unlock() return err } } } func (cs *clientStream) Header() (metadata.MD, error) { var m metadata.MD err := cs.withRetry(func(a *csAttempt) error { var err error m, err = a.s.Header() return toRPCErr(err) }, cs.commitAttemptLocked) if err != nil { cs.finish(err) return nil, err } if cs.binlog != nil && !cs.serverHeaderBinlogged { // Only log if binary log is on and header has not been logged. logEntry := &binarylog.ServerHeader{ OnClientSide: true, Header: m, PeerAddr: nil, } if peer, ok := peer.FromContext(cs.Context()); ok { logEntry.PeerAddr = peer.Addr } cs.binlog.Log(logEntry) cs.serverHeaderBinlogged = true } return m, err } func (cs *clientStream) Trailer() metadata.MD { // On RPC failure, we never need to retry, because usage requires that // RecvMsg() returned a non-nil error before calling this function is valid. // We would have retried earlier if necessary. // // Commit the attempt anyway, just in case users are not following those // directions -- it will prevent races and should not meaningfully impact // performance. cs.commitAttempt() if cs.attempt.s == nil { return nil } return cs.attempt.s.Trailer() } func (cs *clientStream) replayBufferLocked() error { a := cs.attempt for _, f := range cs.buffer { if err := f(a); err != nil { return err } } return nil } func (cs *clientStream) bufferForRetryLocked(sz int, op func(a *csAttempt) error) { // Note: we still will buffer if retry is disabled (for transparent retries). if cs.committed { return } cs.bufferSize += sz if cs.bufferSize > cs.callInfo.maxRetryRPCBufferSize { cs.commitAttemptLocked() return } cs.buffer = append(cs.buffer, op) } func (cs *clientStream) SendMsg(m interface{}) (err error) { defer func() { if err != nil && err != io.EOF { // Call finish on the client stream for errors generated by this SendMsg // call, as these indicate problems created by this client. (Transport // errors are converted to an io.EOF error in csAttempt.sendMsg; the real // error will be returned from RecvMsg eventually in that case, or be // retried.) cs.finish(err) } }() if cs.sentLast { return status.Errorf(codes.Internal, "SendMsg called after CloseSend") } if !cs.desc.ClientStreams { cs.sentLast = true } data, err := encode(cs.codec, m) if err != nil { return err } compData, err := compress(data, cs.cp, cs.comp) if err != nil { return err } hdr, payload := msgHeader(data, compData) // TODO(dfawley): should we be checking len(data) instead? if len(payload) > *cs.callInfo.maxSendMessageSize { return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), *cs.callInfo.maxSendMessageSize) } msgBytes := data // Store the pointer before setting to nil. For binary logging. op := func(a *csAttempt) error { err := a.sendMsg(m, hdr, payload, data) // nil out the message and uncomp when replaying; they are only needed for // stats which is disabled for subsequent attempts. m, data = nil, nil return err } err = cs.withRetry(op, func() { cs.bufferForRetryLocked(len(hdr)+len(payload), op) }) if cs.binlog != nil && err == nil { cs.binlog.Log(&binarylog.ClientMessage{ OnClientSide: true, Message: msgBytes, }) } return } func (cs *clientStream) RecvMsg(m interface{}) error { if cs.binlog != nil && !cs.serverHeaderBinlogged { // Call Header() to binary log header if it's not already logged. cs.Header() } var recvInfo *payloadInfo if cs.binlog != nil { recvInfo = &payloadInfo{} } err := cs.withRetry(func(a *csAttempt) error { return a.recvMsg(m, recvInfo) }, cs.commitAttemptLocked) if cs.binlog != nil && err == nil { cs.binlog.Log(&binarylog.ServerMessage{ OnClientSide: true, Message: recvInfo.uncompressedBytes, }) } if err != nil || !cs.desc.ServerStreams { // err != nil or non-server-streaming indicates end of stream. cs.finish(err) if cs.binlog != nil { // finish will not log Trailer. Log Trailer here. logEntry := &binarylog.ServerTrailer{ OnClientSide: true, Trailer: cs.Trailer(), Err: err, } if logEntry.Err == io.EOF { logEntry.Err = nil } if peer, ok := peer.FromContext(cs.Context()); ok { logEntry.PeerAddr = peer.Addr } cs.binlog.Log(logEntry) } } return err } func (cs *clientStream) CloseSend() error { if cs.sentLast { // TODO: return an error and finish the stream instead, due to API misuse? return nil } cs.sentLast = true op := func(a *csAttempt) error { a.t.Write(a.s, nil, nil, &transport.Options{Last: true}) // Always return nil; io.EOF is the only error that might make sense // instead, but there is no need to signal the client to call RecvMsg // as the only use left for the stream after CloseSend is to call // RecvMsg. This also matches historical behavior. return nil } cs.withRetry(op, func() { cs.bufferForRetryLocked(0, op) }) if cs.binlog != nil { cs.binlog.Log(&binarylog.ClientHalfClose{ OnClientSide: true, }) } // We never returned an error here for reasons. return nil } func (cs *clientStream) finish(err error) { if err == io.EOF { // Ending a stream with EOF indicates a success. err = nil } cs.mu.Lock() if cs.finished { cs.mu.Unlock() return } cs.finished = true cs.commitAttemptLocked() cs.mu.Unlock() // For binary logging. only log cancel in finish (could be caused by RPC ctx // canceled or ClientConn closed). Trailer will be logged in RecvMsg. // // Only one of cancel or trailer needs to be logged. In the cases where // users don't call RecvMsg, users must have already canceled the RPC. if cs.binlog != nil && status.Code(err) == codes.Canceled { cs.binlog.Log(&binarylog.Cancel{ OnClientSide: true, }) } if err == nil { cs.retryThrottler.successfulRPC() } if channelz.IsOn() { if err != nil { cs.cc.incrCallsFailed() } else { cs.cc.incrCallsSucceeded() } } if cs.attempt != nil { cs.attempt.finish(err) } // after functions all rely upon having a stream. if cs.attempt.s != nil { for _, o := range cs.opts { o.after(cs.callInfo) } } cs.cancel() } func (a *csAttempt) sendMsg(m interface{}, hdr, payld, data []byte) error { cs := a.cs if EnableTracing { a.mu.Lock() if a.trInfo.tr != nil { a.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true) } a.mu.Unlock() } if err := a.t.Write(a.s, hdr, payld, &transport.Options{Last: !cs.desc.ClientStreams}); err != nil { if !cs.desc.ClientStreams { // For non-client-streaming RPCs, we return nil instead of EOF on error // because the generated code requires it. finish is not called; RecvMsg() // will call it with the stream's status independently. return nil } return io.EOF } if a.statsHandler != nil { a.statsHandler.HandleRPC(cs.ctx, outPayload(true, m, data, payld, time.Now())) } if channelz.IsOn() { a.t.IncrMsgSent() } return nil } func (a *csAttempt) recvMsg(m interface{}, payInfo *payloadInfo) (err error) { cs := a.cs if a.statsHandler != nil && payInfo == nil { payInfo = &payloadInfo{} } if !a.decompSet { // Block until we receive headers containing received message encoding. if ct := a.s.RecvCompress(); ct != "" && ct != encoding.Identity { if a.dc == nil || a.dc.Type() != ct { // No configured decompressor, or it does not match the incoming // message encoding; attempt to find a registered compressor that does. a.dc = nil a.decomp = encoding.GetCompressor(ct) } } else { // No compression is used; disable our decompressor. a.dc = nil } // Only initialize this state once per stream. a.decompSet = true } err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.callInfo.maxReceiveMessageSize, payInfo, a.decomp) if err != nil { if err == io.EOF { if statusErr := a.s.Status().Err(); statusErr != nil { return statusErr } return io.EOF // indicates successful end of stream. } return toRPCErr(err) } if EnableTracing { a.mu.Lock() if a.trInfo.tr != nil { a.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true) } a.mu.Unlock() } if a.statsHandler != nil { a.statsHandler.HandleRPC(cs.ctx, &stats.InPayload{ Client: true, RecvTime: time.Now(), Payload: m, // TODO truncate large payload. Data: payInfo.uncompressedBytes, Length: len(payInfo.uncompressedBytes), }) } if channelz.IsOn() { a.t.IncrMsgRecv() } if cs.desc.ServerStreams { // Subsequent messages should be received by subsequent RecvMsg calls. return nil } // Special handling for non-server-stream rpcs. // This recv expects EOF or errors, so we don't collect inPayload. err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.callInfo.maxReceiveMessageSize, nil, a.decomp) if err == nil { return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>")) } if err == io.EOF { return a.s.Status().Err() // non-server streaming Recv returns nil on success } return toRPCErr(err) } func (a *csAttempt) finish(err error) { a.mu.Lock() if a.finished { a.mu.Unlock() return } a.finished = true if err == io.EOF { // Ending a stream with EOF indicates a success. err = nil } if a.s != nil { a.t.CloseStream(a.s, err) } if a.done != nil { br := false var tr metadata.MD if a.s != nil { br = a.s.BytesReceived() tr = a.s.Trailer() } a.done(balancer.DoneInfo{ Err: err, Trailer: tr, BytesSent: a.s != nil, BytesReceived: br, }) } if a.statsHandler != nil { end := &stats.End{ Client: true, BeginTime: a.cs.beginTime, EndTime: time.Now(), Error: err, } a.statsHandler.HandleRPC(a.cs.ctx, end) } if a.trInfo.tr != nil { if err == nil { a.trInfo.tr.LazyPrintf("RPC: [OK]") } else { a.trInfo.tr.LazyPrintf("RPC: [%v]", err) a.trInfo.tr.SetError() } a.trInfo.tr.Finish() a.trInfo.tr = nil } a.mu.Unlock() } func (ac *addrConn) newClientStream(ctx context.Context, desc *StreamDesc, method string, t transport.ClientTransport, opts ...CallOption) (_ ClientStream, err error) { ac.mu.Lock() if ac.transport != t { ac.mu.Unlock() return nil, status.Error(codes.Canceled, "the provided transport is no longer valid to use") } // transition to CONNECTING state when an attempt starts if ac.state != connectivity.Connecting { ac.updateConnectivityState(connectivity.Connecting) ac.cc.handleSubConnStateChange(ac.acbw, ac.state) } ac.mu.Unlock() if t == nil { // TODO: return RPC error here? return nil, errors.New("transport provided is nil") } // defaultCallInfo contains unnecessary info(i.e. failfast, maxRetryRPCBufferSize), so we just initialize an empty struct. c := &callInfo{} for _, o := range opts { if err := o.before(c); err != nil { return nil, toRPCErr(err) } } c.maxReceiveMessageSize = getMaxSize(nil, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize) c.maxSendMessageSize = getMaxSize(nil, c.maxSendMessageSize, defaultServerMaxSendMessageSize) // Possible context leak: // The cancel function for the child context we create will only be called // when RecvMsg returns a non-nil error, if the ClientConn is closed, or if // an error is generated by SendMsg. // https://github.com/grpc/grpc-go/issues/1818. ctx, cancel := context.WithCancel(ctx) defer func() { if err != nil { cancel() } }() if err := setCallInfoCodec(c); err != nil { return nil, err } callHdr := &transport.CallHdr{ Host: ac.cc.authority, Method: method, ContentSubtype: c.contentSubtype, } // Set our outgoing compression according to the UseCompressor CallOption, if // set. In that case, also find the compressor from the encoding package. // Otherwise, use the compressor configured by the WithCompressor DialOption, // if set. var cp Compressor var comp encoding.Compressor if ct := c.compressorType; ct != "" { callHdr.SendCompress = ct if ct != encoding.Identity { comp = encoding.GetCompressor(ct) if comp == nil { return nil, status.Errorf(codes.Internal, "grpc: Compressor is not installed for requested grpc-encoding %q", ct) } } } else if ac.cc.dopts.cp != nil { callHdr.SendCompress = ac.cc.dopts.cp.Type() cp = ac.cc.dopts.cp } if c.creds != nil { callHdr.Creds = c.creds } as := &addrConnStream{ callHdr: callHdr, ac: ac, ctx: ctx, cancel: cancel, opts: opts, callInfo: c, desc: desc, codec: c.codec, cp: cp, comp: comp, t: t, } as.callInfo.stream = as s, err := as.t.NewStream(as.ctx, as.callHdr) if err != nil { err = toRPCErr(err) return nil, err } as.s = s as.p = &parser{r: s} ac.incrCallsStarted() if desc != unaryStreamDesc { // Listen on cc and stream contexts to cleanup when the user closes the // ClientConn or cancels the stream context. In all other cases, an error // should already be injected into the recv buffer by the transport, which // the client will eventually receive, and then we will cancel the stream's // context in clientStream.finish. go func() { select { case <-ac.ctx.Done(): as.finish(status.Error(codes.Canceled, "grpc: the SubConn is closing")) case <-ctx.Done(): as.finish(toRPCErr(ctx.Err())) } }() } return as, nil } type addrConnStream struct { s *transport.Stream ac *addrConn callHdr *transport.CallHdr cancel context.CancelFunc opts []CallOption callInfo *callInfo t transport.ClientTransport ctx context.Context sentLast bool desc *StreamDesc codec baseCodec cp Compressor comp encoding.Compressor decompSet bool dc Decompressor decomp encoding.Compressor p *parser mu sync.Mutex finished bool } func (as *addrConnStream) Header() (metadata.MD, error) { m, err := as.s.Header() if err != nil { as.finish(toRPCErr(err)) } return m, err } func (as *addrConnStream) Trailer() metadata.MD { return as.s.Trailer() } func (as *addrConnStream) CloseSend() error { if as.sentLast { // TODO: return an error and finish the stream instead, due to API misuse? return nil } as.sentLast = true as.t.Write(as.s, nil, nil, &transport.Options{Last: true}) // Always return nil; io.EOF is the only error that might make sense // instead, but there is no need to signal the client to call RecvMsg // as the only use left for the stream after CloseSend is to call // RecvMsg. This also matches historical behavior. return nil } func (as *addrConnStream) Context() context.Context { return as.s.Context() } func (as *addrConnStream) SendMsg(m interface{}) (err error) { defer func() { if err != nil && err != io.EOF { // Call finish on the client stream for errors generated by this SendMsg // call, as these indicate problems created by this client. (Transport // errors are converted to an io.EOF error in csAttempt.sendMsg; the real // error will be returned from RecvMsg eventually in that case, or be // retried.) as.finish(err) } }() if as.sentLast { return status.Errorf(codes.Internal, "SendMsg called after CloseSend") } if !as.desc.ClientStreams { as.sentLast = true } data, err := encode(as.codec, m) if err != nil { return err } compData, err := compress(data, as.cp, as.comp) if err != nil { return err } hdr, payld := msgHeader(data, compData) // TODO(dfawley): should we be checking len(data) instead? if len(payld) > *as.callInfo.maxSendMessageSize { return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payld), *as.callInfo.maxSendMessageSize) } if err := as.t.Write(as.s, hdr, payld, &transport.Options{Last: !as.desc.ClientStreams}); err != nil { if !as.desc.ClientStreams { // For non-client-streaming RPCs, we return nil instead of EOF on error // because the generated code requires it. finish is not called; RecvMsg() // will call it with the stream's status independently. return nil } return io.EOF } if channelz.IsOn() { as.t.IncrMsgSent() } return nil } func (as *addrConnStream) RecvMsg(m interface{}) (err error) { defer func() { if err != nil || !as.desc.ServerStreams { // err != nil or non-server-streaming indicates end of stream. as.finish(err) } }() if !as.decompSet { // Block until we receive headers containing received message encoding. if ct := as.s.RecvCompress(); ct != "" && ct != encoding.Identity { if as.dc == nil || as.dc.Type() != ct { // No configured decompressor, or it does not match the incoming // message encoding; attempt to find a registered compressor that does. as.dc = nil as.decomp = encoding.GetCompressor(ct) } } else { // No compression is used; disable our decompressor. as.dc = nil } // Only initialize this state once per stream. as.decompSet = true } err = recv(as.p, as.codec, as.s, as.dc, m, *as.callInfo.maxReceiveMessageSize, nil, as.decomp) if err != nil { if err == io.EOF { if statusErr := as.s.Status().Err(); statusErr != nil { return statusErr } return io.EOF // indicates successful end of stream. } return toRPCErr(err) } if channelz.IsOn() { as.t.IncrMsgRecv() } if as.desc.ServerStreams { // Subsequent messages should be received by subsequent RecvMsg calls. return nil } // Special handling for non-server-stream rpcs. // This recv expects EOF or errors, so we don't collect inPayload. err = recv(as.p, as.codec, as.s, as.dc, m, *as.callInfo.maxReceiveMessageSize, nil, as.decomp) if err == nil { return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>")) } if err == io.EOF { return as.s.Status().Err() // non-server streaming Recv returns nil on success } return toRPCErr(err) } func (as *addrConnStream) finish(err error) { as.mu.Lock() if as.finished { as.mu.Unlock() return } as.finished = true if err == io.EOF { // Ending a stream with EOF indicates a success. err = nil } if as.s != nil { as.t.CloseStream(as.s, err) } if err != nil { as.ac.incrCallsFailed() } else { as.ac.incrCallsSucceeded() } as.cancel() as.mu.Unlock() } // ServerStream defines the server-side behavior of a streaming RPC. // // All errors returned from ServerStream methods are compatible with the // status package. type ServerStream interface { // SetHeader sets the header metadata. It may be called multiple times. // When call multiple times, all the provided metadata will be merged. // All the metadata will be sent out when one of the following happens: // - ServerStream.SendHeader() is called; // - The first response is sent out; // - An RPC status is sent out (error or success). SetHeader(metadata.MD) error // SendHeader sends the header metadata. // The provided md and headers set by SetHeader() will be sent. // It fails if called multiple times. SendHeader(metadata.MD) error // SetTrailer sets the trailer metadata which will be sent with the RPC status. // When called more than once, all the provided metadata will be merged. SetTrailer(metadata.MD) // Context returns the context for this stream. Context() context.Context // SendMsg sends a message. On error, SendMsg aborts the stream and the // error is returned directly. // // SendMsg blocks until: // - There is sufficient flow control to schedule m with the transport, or // - The stream is done, or // - The stream breaks. // // SendMsg does not wait until the message is received by the client. An // untimely stream closure may result in lost messages. // // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not safe // to call SendMsg on the same stream in different goroutines. SendMsg(m interface{}) error // RecvMsg blocks until it receives a message into m or the stream is // done. It returns io.EOF when the client has performed a CloseSend. On // any non-EOF error, the stream is aborted and the error contains the // RPC status. // // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not // safe to call RecvMsg on the same stream in different goroutines. RecvMsg(m interface{}) error } // serverStream implements a server side Stream. type serverStream struct { ctx context.Context t transport.ServerTransport s *transport.Stream p *parser codec baseCodec cp Compressor dc Decompressor comp encoding.Compressor decomp encoding.Compressor maxReceiveMessageSize int maxSendMessageSize int trInfo *traceInfo statsHandler stats.Handler binlog *binarylog.MethodLogger // serverHeaderBinlogged indicates whether server header has been logged. It // will happen when one of the following two happens: stream.SendHeader(), // stream.Send(). // // It's only checked in send and sendHeader, doesn't need to be // synchronized. serverHeaderBinlogged bool mu sync.Mutex // protects trInfo.tr after the service handler runs. } func (ss *serverStream) Context() context.Context { return ss.ctx } func (ss *serverStream) SetHeader(md metadata.MD) error { if md.Len() == 0 { return nil } return ss.s.SetHeader(md) } func (ss *serverStream) SendHeader(md metadata.MD) error { err := ss.t.WriteHeader(ss.s, md) if ss.binlog != nil && !ss.serverHeaderBinlogged { h, _ := ss.s.Header() ss.binlog.Log(&binarylog.ServerHeader{ Header: h, }) ss.serverHeaderBinlogged = true } return err } func (ss *serverStream) SetTrailer(md metadata.MD) { if md.Len() == 0 { return } ss.s.SetTrailer(md) } func (ss *serverStream) SendMsg(m interface{}) (err error) { defer func() { if ss.trInfo != nil { ss.mu.Lock() if ss.trInfo.tr != nil { if err == nil { ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true) } else { ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) ss.trInfo.tr.SetError() } } ss.mu.Unlock() } if err != nil && err != io.EOF { st, _ := status.FromError(toRPCErr(err)) ss.t.WriteStatus(ss.s, st) // Non-user specified status was sent out. This should be an error // case (as a server side Cancel maybe). // // This is not handled specifically now. User will return a final // status from the service handler, we will log that error instead. // This behavior is similar to an interceptor. } if channelz.IsOn() && err == nil { ss.t.IncrMsgSent() } }() data, err := encode(ss.codec, m) if err != nil { return err } compData, err := compress(data, ss.cp, ss.comp) if err != nil { return err } hdr, payload := msgHeader(data, compData) // TODO(dfawley): should we be checking len(data) instead? if len(payload) > ss.maxSendMessageSize { return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), ss.maxSendMessageSize) } if err := ss.t.Write(ss.s, hdr, payload, &transport.Options{Last: false}); err != nil { return toRPCErr(err) } if ss.binlog != nil { if !ss.serverHeaderBinlogged { h, _ := ss.s.Header() ss.binlog.Log(&binarylog.ServerHeader{ Header: h, }) ss.serverHeaderBinlogged = true } ss.binlog.Log(&binarylog.ServerMessage{ Message: data, }) } if ss.statsHandler != nil { ss.statsHandler.HandleRPC(ss.s.Context(), outPayload(false, m, data, payload, time.Now())) } return nil } func (ss *serverStream) RecvMsg(m interface{}) (err error) { defer func() { if ss.trInfo != nil { ss.mu.Lock() if ss.trInfo.tr != nil { if err == nil { ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true) } else if err != io.EOF { ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) ss.trInfo.tr.SetError() } } ss.mu.Unlock() } if err != nil && err != io.EOF { st, _ := status.FromError(toRPCErr(err)) ss.t.WriteStatus(ss.s, st) // Non-user specified status was sent out. This should be an error // case (as a server side Cancel maybe). // // This is not handled specifically now. User will return a final // status from the service handler, we will log that error instead. // This behavior is similar to an interceptor. } if channelz.IsOn() && err == nil { ss.t.IncrMsgRecv() } }() var payInfo *payloadInfo if ss.statsHandler != nil || ss.binlog != nil { payInfo = &payloadInfo{} } if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxReceiveMessageSize, payInfo, ss.decomp); err != nil { if err == io.EOF { if ss.binlog != nil { ss.binlog.Log(&binarylog.ClientHalfClose{}) } return err } if err == io.ErrUnexpectedEOF { err = status.Errorf(codes.Internal, io.ErrUnexpectedEOF.Error()) } return toRPCErr(err) } if ss.statsHandler != nil { ss.statsHandler.HandleRPC(ss.s.Context(), &stats.InPayload{ RecvTime: time.Now(), Payload: m, // TODO truncate large payload. Data: payInfo.uncompressedBytes, Length: len(payInfo.uncompressedBytes), }) } if ss.binlog != nil { ss.binlog.Log(&binarylog.ClientMessage{ Message: payInfo.uncompressedBytes, }) } return nil } // MethodFromServerStream returns the method string for the input stream. // The returned string is in the format of "/service/method". func MethodFromServerStream(stream ServerStream) (string, bool) { return Method(stream.Context()) }
{ "pile_set_name": "Github" }
/* * Copyright 2009-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.session.defaults; import java.sql.Connection; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.binding.BindingException; import org.apache.ibatis.exceptions.ExceptionFactory; import org.apache.ibatis.exceptions.TooManyResultsException; import org.apache.ibatis.executor.BatchResult; import org.apache.ibatis.executor.ErrorContext; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.executor.result.DefaultMapResultHandler; import org.apache.ibatis.executor.result.DefaultResultContext; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; /** * @author Clinton Begin */ /** * 默认SqlSession实现 * */ public class DefaultSqlSession implements SqlSession { private Configuration configuration; private Executor executor; /** * 是否自动提交 */ private boolean autoCommit; private boolean dirty; public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) { this.configuration = configuration; this.executor = executor; this.dirty = false; this.autoCommit = autoCommit; } public DefaultSqlSession(Configuration configuration, Executor executor) { this(configuration, executor, false); } @Override public <T> T selectOne(String statement) { return this.<T>selectOne(statement, null); } //核心selectOne @Override public <T> T selectOne(String statement, Object parameter) { // Popular vote was to return null on 0 results and throw exception on too many. //转而去调用selectList,很简单的,如果得到0条则返回null,得到1条则返回1条,得到多条报TooManyResultsException错 // 特别需要主要的是当没有查询到结果的时候就会返回null。因此一般建议在mapper中编写resultType的时候使用包装类型 //而不是基本类型,比如推荐使用Integer而不是int。这样就可以避免NPE List<T> list = this.<T>selectList(statement, parameter); if (list.size() == 1) { return list.get(0); } else if (list.size() > 1) { throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size()); } else { return null; } } @Override public <K, V> Map<K, V> selectMap(String statement, String mapKey) { return this.selectMap(statement, null, mapKey, RowBounds.DEFAULT); } @Override public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) { return this.selectMap(statement, parameter, mapKey, RowBounds.DEFAULT); } //核心selectMap @Override public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) { //转而去调用selectList final List<?> list = selectList(statement, parameter, rowBounds); final DefaultMapResultHandler<K, V> mapResultHandler = new DefaultMapResultHandler<K, V>(mapKey, configuration.getObjectFactory(), configuration.getObjectWrapperFactory()); final DefaultResultContext context = new DefaultResultContext(); for (Object o : list) { //循环用DefaultMapResultHandler处理每条记录 context.nextResultObject(o); mapResultHandler.handleResult(context); } //注意这个DefaultMapResultHandler里面存了所有已处理的记录(内部实现可能就是一个Map),最后再返回一个Map return mapResultHandler.getMappedResults(); } @Override public <E> List<E> selectList(String statement) { return this.selectList(statement, null); } @Override public <E> List<E> selectList(String statement, Object parameter) { return this.selectList(statement, parameter, RowBounds.DEFAULT); } //核心selectList @Override public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { try { //根据statement id找到对应的MappedStatement MappedStatement ms = configuration.getMappedStatement(statement); //转而用执行器来查询结果,注意这里传入的ResultHandler是null return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER); } catch (Exception e) { throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } } @Override public void select(String statement, Object parameter, ResultHandler handler) { select(statement, parameter, RowBounds.DEFAULT, handler); } @Override public void select(String statement, ResultHandler handler) { select(statement, null, RowBounds.DEFAULT, handler); } //核心select,带有ResultHandler,和selectList代码差不多的,区别就一个ResultHandler @Override public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) { try { MappedStatement ms = configuration.getMappedStatement(statement); executor.query(ms, wrapCollection(parameter), rowBounds, handler); } catch (Exception e) { throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } } @Override public int insert(String statement) { return insert(statement, null); } @Override public int insert(String statement, Object parameter) { //insert也是调用update return update(statement, parameter); } @Override public int update(String statement) { return update(statement, null); } //核心update @Override public int update(String statement, Object parameter) { try { //每次要更新之前,dirty标志设为true dirty = true; MappedStatement ms = configuration.getMappedStatement(statement); //转而用执行器来update结果 return executor.update(ms, wrapCollection(parameter)); } catch (Exception e) { throw ExceptionFactory.wrapException("Error updating database. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } } @Override public int delete(String statement) { //delete也是调用update return update(statement, null); } @Override public int delete(String statement, Object parameter) { return update(statement, parameter); } @Override public void commit() { commit(false); } //核心commit @Override public void commit(boolean force) { try { //转而用执行器来commit executor.commit(isCommitOrRollbackRequired(force)); //每次commit之后,dirty标志设为false dirty = false; } catch (Exception e) { throw ExceptionFactory.wrapException("Error committing transaction. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } } @Override public void rollback() { rollback(false); } //核心rollback @Override public void rollback(boolean force) { try { //转而用执行器来rollback executor.rollback(isCommitOrRollbackRequired(force)); //每次rollback之后,dirty标志设为false dirty = false; } catch (Exception e) { throw ExceptionFactory.wrapException("Error rolling back transaction. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } } //核心flushStatements @Override public List<BatchResult> flushStatements() { try { //转而用执行器来flushStatements return executor.flushStatements(); } catch (Exception e) { throw ExceptionFactory.wrapException("Error flushing statements. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } } //核心close @Override public void close() { try { //转而用执行器来close executor.close(isCommitOrRollbackRequired(false)); //每次close之后,dirty标志设为false dirty = false; } finally { ErrorContext.instance().reset(); } } @Override public Configuration getConfiguration() { return configuration; } @Override public <T> T getMapper(Class<T> type) { //最后会去调用MapperRegistry.getMapper return configuration.<T>getMapper(type, this); } @Override public Connection getConnection() { try { return executor.getTransaction().getConnection(); } catch (SQLException e) { throw ExceptionFactory.wrapException("Error getting a new connection. Cause: " + e, e); } } //核心clearCache @Override public void clearCache() { //转而用执行器来clearLocalCache executor.clearLocalCache(); } //检查是否需要强制commit或rollback private boolean isCommitOrRollbackRequired(boolean force) { return (!autoCommit && dirty) || force; } //把参数包装成Collection private Object wrapCollection(final Object object) { if (object instanceof Collection) { //参数若是Collection型,做collection标记 StrictMap<Object> map = new StrictMap<Object>(); map.put("collection", object); if (object instanceof List) { //参数若是List型,做list标记 map.put("list", object); } return map; } else if (object != null && object.getClass().isArray()) { //参数若是数组型,,做array标记 StrictMap<Object> map = new StrictMap<Object>(); map.put("array", object); return map; } //参数若不是集合型,直接返回原来值 return object; } //严格的Map,如果找不到对应的key,直接抛BindingException例外,而不是返回null public static class StrictMap<V> extends HashMap<String, V> { private static final long serialVersionUID = -5741767162221585340L; @Override public V get(Object key) { if (!super.containsKey(key)) { throw new BindingException("Parameter '" + key + "' not found. Available parameters are " + this.keySet()); } return super.get(key); } } }
{ "pile_set_name": "Github" }
# mach: crisv0 crisv3 crisv8 crisv10 crisv32 # output: ffffffff\n4\n80000000\nffff8000\n7f19f000\n80000000\n0\n0\n699fc67c\nffffffff\n4\n80000000\nffff8000\n7f19f000\nda670000\nda670000\nda670000\nda67c67c\nffffffff\nfffafffe\n4\nffff0000\nffff8000\n5a67f000\nda67f100\nda67f100\nda67f100\nda67f17c\nfff3faff\nfff3fafe\n4\nffffff00\nffffff00\nffffff80\n5a67f100\n5a67f1f0\n .include "testutils.inc" start moveq -1,r3 lslq 0,r3 test_move_cc 1 0 0 0 checkr3 ffffffff moveq 2,r3 lslq 1,r3 test_move_cc 0 0 0 0 checkr3 4 moveq -1,r3 lslq 31,r3 test_move_cc 1 0 0 0 checkr3 80000000 moveq -1,r3 lslq 15,r3 test_move_cc 1 0 0 0 checkr3 ffff8000 move.d 0x5a67f19f,r3 lslq 12,r3 test_move_cc 0 0 0 0 checkr3 7f19f000 move.d 0xda67f19f,r3 move.d 31,r4 lsl.d r4,r3 test_move_cc 1 0 0 0 checkr3 80000000 move.d 0xda67f19f,r3 move.d 32,r4 lsl.d r4,r3 test_move_cc 0 1 0 0 checkr3 0 move.d 0xda67f19f,r3 move.d 33,r4 lsl.d r4,r3 test_move_cc 0 1 0 0 checkr3 0 move.d 0xda67f19f,r3 move.d 66,r4 lsl.d r4,r3 test_move_cc 0 0 0 0 checkr3 699fc67c moveq -1,r3 moveq 0,r4 lsl.d r4,r3 test_move_cc 1 0 0 0 checkr3 ffffffff moveq 2,r3 moveq 1,r4 lsl.d r4,r3 test_move_cc 0 0 0 0 checkr3 4 moveq -1,r3 moveq 31,r4 lsl.d r4,r3 test_move_cc 1 0 0 0 checkr3 80000000 moveq -1,r3 moveq 15,r4 lsl.d r4,r3 test_move_cc 1 0 0 0 checkr3 ffff8000 move.d 0x5a67f19f,r3 moveq 12,r4 lsl.d r4,r3 test_move_cc 0 0 0 0 checkr3 7f19f000 move.d 0xda67f19f,r3 move.d 31,r4 lsl.w r4,r3 test_move_cc 0 1 0 0 checkr3 da670000 move.d 0xda67f19f,r3 move.d 32,r4 lsl.w r4,r3 test_move_cc 0 1 0 0 checkr3 da670000 move.d 0xda67f19f,r3 move.d 33,r4 lsl.w r4,r3 test_move_cc 0 1 0 0 checkr3 da670000 move.d 0xda67f19f,r3 move.d 66,r4 lsl.w r4,r3 test_move_cc 1 0 0 0 checkr3 da67c67c moveq -1,r3 moveq 0,r4 lsl.w r4,r3 test_move_cc 1 0 0 0 checkr3 ffffffff move.d 0xfffaffff,r3 moveq 1,r4 lsl.w r4,r3 test_move_cc 1 0 0 0 checkr3 fffafffe moveq 2,r3 moveq 1,r4 lsl.w r4,r3 test_move_cc 0 0 0 0 checkr3 4 moveq -1,r3 moveq 31,r4 lsl.w r4,r3 test_move_cc 0 1 0 0 checkr3 ffff0000 moveq -1,r3 moveq 15,r4 lsl.w r4,r3 test_move_cc 1 0 0 0 checkr3 ffff8000 move.d 0x5a67f19f,r3 moveq 12,r4 lsl.w r4,r3 test_move_cc 1 0 0 0 checkr3 5a67f000 move.d 0xda67f19f,r3 move.d 31,r4 lsl.b r4,r3 test_move_cc 0 1 0 0 checkr3 da67f100 move.d 0xda67f19f,r3 move.d 32,r4 lsl.b r4,r3 test_move_cc 0 1 0 0 checkr3 da67f100 move.d 0xda67f19f,r3 move.d 33,r4 lsl.b r4,r3 test_move_cc 0 1 0 0 checkr3 da67f100 move.d 0xda67f19f,r3 move.d 66,r4 lsl.b r4,r3 test_move_cc 0 0 0 0 checkr3 da67f17c move.d 0xfff3faff,r3 moveq 0,r4 lsl.b r4,r3 test_move_cc 1 0 0 0 checkr3 fff3faff move.d 0xfff3faff,r3 moveq 1,r4 lsl.b r4,r3 test_move_cc 1 0 0 0 checkr3 fff3fafe moveq 2,r3 moveq 1,r4 lsl.b r4,r3 test_move_cc 0 0 0 0 checkr3 4 moveq -1,r3 moveq 31,r4 lsl.b r4,r3 test_move_cc 0 1 0 0 checkr3 ffffff00 moveq -1,r3 moveq 15,r4 lsl.b r4,r3 test_move_cc 0 1 0 0 checkr3 ffffff00 moveq -1,r3 moveq 7,r4 lsl.b r4,r3 test_move_cc 1 0 0 0 checkr3 ffffff80 move.d 0x5a67f19f,r3 moveq 12,r4 lsl.b r4,r3 test_move_cc 0 1 0 0 checkr3 5a67f100 move.d 0x5a67f19f,r3 moveq 4,r4 lsl.b r4,r3 test_move_cc 1 0 0 0 checkr3 5a67f1f0 quit
{ "pile_set_name": "Github" }
# Actions, resources, and condition keys for AWS Ground Station<a name="list_awsgroundstation"></a> AWS Ground Station \(service prefix: `groundstation`\) provides the following service\-specific resources, actions, and condition context keys for use in IAM permission policies\. References: + Learn how to [configure this service](https://docs.aws.amazon.com/ground-station/latest/ug/introduction.html)\. + View a list of the [API operations available for this service](https://docs.aws.amazon.com/ground-station/latest/APIReference/welcome.html)\. + Learn how to secure this service and its resources by [using IAM](https://docs.aws.amazon.com/ground-station/latest/ug/auth-and-access-control.html) permission policies\. **Topics** + [Actions defined by AWS Ground Station](#awsgroundstation-actions-as-permissions) + [Resource types defined by AWS Ground Station](#awsgroundstation-resources-for-iam-policies) + [Condition keys for AWS Ground Station](#awsgroundstation-policy-keys) ## Actions defined by AWS Ground Station<a name="awsgroundstation-actions-as-permissions"></a> You can specify the following actions in the `Action` element of an IAM policy statement\. Use policies to grant permissions to perform an operation in AWS\. When you use an action in a policy, you usually allow or deny access to the API operation or CLI command with the same name\. However, in some cases, a single action controls access to more than one operation\. Alternatively, some operations require several different actions\. The **Resource types** column indicates whether each action supports resource\-level permissions\. If there is no value for this column, you must specify all resources \("\*"\) in the `Resource` element of your policy statement\. If the column includes a resource type, then you can specify an ARN of that type in a statement with that action\. Required resources are indicated in the table with an asterisk \(\*\)\. If you specify a resource\-level permission ARN in a statement using this action, then it must be of this type\. Some actions support multiple resource types\. If the resource type is optional \(not indicated as required\), then you can choose to use one but not the other\. For details about the columns in the following table, see [The actions table](reference_policies_actions-resources-contextkeys.md#actions_table)\. **** [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/list_awsgroundstation.html) ## Resource types defined by AWS Ground Station<a name="awsgroundstation-resources-for-iam-policies"></a> The following resource types are defined by this service and can be used in the `Resource` element of IAM permission policy statements\. Each action in the [Actions table](#awsgroundstation-actions-as-permissions) identifies the resource types that can be specified with that action\. A resource type can also define which condition keys you can include in a policy\. These keys are displayed in the last column of the table\. For details about the columns in the following table, see [The resource types table](reference_policies_actions-resources-contextkeys.md#resources_table)\. **** | Resource types | ARN | Condition keys | | --- | --- | --- | | [ Config ](https://docs.aws.amazon.com/ground-station/latest/APIReference/API_ConfigListItem.html) | arn:$\{Partition\}:groundstation:$\{Region\}:$\{Account\}:config/$\{configType\}/$\{configId\} | [ aws:ResourceTag/$\{TagKey\} ](#awsgroundstation-aws_ResourceTag___TagKey_) [ groundstation:configId ](#awsgroundstation-groundstation_configId) [ groundstation:configType ](#awsgroundstation-groundstation_configType) | | [ Contact ](https://docs.aws.amazon.com/ground-station/latest/APIReference/API_ContactData.html) | arn:$\{Partition\}:groundstation:$\{Region\}:$\{Account\}:contact/$\{contactId\} | [ aws:ResourceTag/$\{TagKey\} ](#awsgroundstation-aws_ResourceTag___TagKey_) [ groundstation:contactId ](#awsgroundstation-groundstation_contactId) | | [ DataflowEndpointGroup ](https://docs.aws.amazon.com/ground-station/latest/APIReference/API_DataflowEndpoint.html) | arn:$\{Partition\}:groundstation:$\{Region\}:$\{Account\}:dataflow\-endpoint\-group/$\{dataflowEndpointGroupId\} | [ aws:ResourceTag/$\{TagKey\} ](#awsgroundstation-aws_ResourceTag___TagKey_) [ groundstation:dataflowEndpointGroupId ](#awsgroundstation-groundstation_dataflowEndpointGroupId) | | [ GroundStationResource ](https://docs.aws.amazon.com/ground-station/latest/APIReference/API_GroundStationData.html) | arn:$\{Partition\}:groundstation:$\{Region\}:$\{Account\}:groundstation:$\{groundStationId\} | [ groundstation:groundStationId ](#awsgroundstation-groundstation_groundStationId) | | [ MissionProfile ](https://docs.aws.amazon.com/ground-station/latest/APIReference/API_MissionProfileListItem.html) | arn:$\{Partition\}:groundstation:$\{Region\}:$\{Account\}:mission\-profile/$\{missionProfileId\} | [ aws:ResourceTag/$\{TagKey\} ](#awsgroundstation-aws_ResourceTag___TagKey_) [ groundstation:missionProfileId ](#awsgroundstation-groundstation_missionProfileId) | | [ Satellite ](https://docs.aws.amazon.com/ground-station/latest/APIReference/API_SatelliteListItem.html) | arn:$\{Partition\}:groundstation:$\{Region\}:$\{Account\}:satellite/$\{satelliteId\} | [ groundstation:satelliteId ](#awsgroundstation-groundstation_satelliteId) | ## Condition keys for AWS Ground Station<a name="awsgroundstation-policy-keys"></a> AWS Ground Station defines the following condition keys that can be used in the `Condition` element of an IAM policy\. You can use these keys to further refine the conditions under which the policy statement applies\. For details about the columns in the following table, see [The condition keys table](reference_policies_actions-resources-contextkeys.md#context_keys_table)\. To view the global condition keys that are available to all services, see [Available global condition keys](reference_policies_condition-keys.html#AvailableKeys)\. **** | Condition keys | Description | Type | | --- | --- | --- | | aws:RequestTag/$\{TagKey\} | Filters access by a key that is present in the request the user makes to the Ground Station service\. | String | | aws:ResourceTag/$\{TagKey\} | Filters access by a tag key and value pair\. | String | | aws:TagKeys | Filters access by the list of all the tag key names present in the request the user makes to the Ground Station service\. | String | | groundstation:configId | Filters access by the ID of a config | String | | groundstation:configType | Filters access by the type of a config | String | | groundstation:contactId | Filters access by the ID of a contact | String | | groundstation:dataflowEndpointGroupId | Filters access by the ID of a dataflow endpoint group | String | | groundstation:groundStationId | Filters access by the ID of a ground station | String | | groundstation:missionProfileId | Filters access by the ID of a mission profile | String | | groundstation:satelliteId | Filters access by the ID of a satellite | String |
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>AD_TYPE_RESERVED &mdash; MIT Kerberos Documentation</title> <link rel="stylesheet" href="../../../_static/agogo.css" type="text/css" /> <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../../../_static/kerb.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../../../', VERSION: '1.11.3', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../../../_static/jquery.js"></script> <script type="text/javascript" src="../../../_static/underscore.js"></script> <script type="text/javascript" src="../../../_static/doctools.js"></script> <link rel="author" title="About these documents" href="../../../about.html" /> <link rel="copyright" title="Copyright" href="../../../copyright.html" /> <link rel="top" title="MIT Kerberos Documentation" href="../../../index.html" /> <link rel="up" title="krb5 simple macros" href="index.html" /> <link rel="next" title="AP_OPTS_ETYPE_NEGOTIATION" href="AP_OPTS_ETYPE_NEGOTIATION.html" /> <link rel="prev" title="AD_TYPE_REGISTERED" href="AD_TYPE_REGISTERED.html" /> </head> <body> <div class="header-wrapper"> <div class="header" style="padding-bottom: 0px;"> <h1><a href="../../../index.html" style="color: #5d1509; font-size: 120%; padding-top: 10px;">MIT Kerberos Documentation</a></h1> <div class="rel"> <a href="../../../index.html" title="Full Table of Contents" accesskey="C">Contents</a> | <a href="AD_TYPE_REGISTERED.html" title="AD_TYPE_REGISTERED" accesskey="P">previous</a> | <a href="AP_OPTS_ETYPE_NEGOTIATION.html" title="AP_OPTS_ETYPE_NEGOTIATION" accesskey="N">next</a> | <a href="../../../genindex.html" title="General Index" accesskey="I">index</a> | <a href="../../../search.html" title="Enter search criteria" accesskey="S">Search</a> | <a href="mailto:[email protected]?subject=Documentation__AD_TYPE_RESERVED">feedback</a> </div> </div> </div> <div class="content-wrapper"> <div class="content"> <div class="sidebar" style="float: right; background: #F9F9F9"> <h2>On this page </h2> <ul> <li><a class="reference internal" href="#">AD_TYPE_RESERVED</a></li> </ul> <br/> <h2>Table of contents</h2> <ul> <li class="toctree-l1"><a class="reference internal" href="../../../user/index.html">For users</a></li> <li class="toctree-l1"><a class="reference internal" href="../../../admin/index.html">For administrators</a></li> <li class="toctree-l1"><a class="reference internal" href="../../index.html">For application developers</a></li> <li class="toctree-l1"><a class="reference internal" href="../../../plugindev/index.html">For plugin module developers</a></li> <li class="toctree-l1"><a class="reference internal" href="../../../build/index.html">Building Kerberos V5</a></li> <li class="toctree-l1"><a class="reference internal" href="../../../basic/index.html">Kerberos V5 concepts</a></li> <li class="toctree-l1"><a class="reference internal" href="../../../mitK5features.html">MIT Kerberos features</a></li> <li class="toctree-l1"><a class="reference internal" href="../../../build_this.html">How to build this documentation from the source</a></li> <li class="toctree-l1"><a class="reference internal" href="../../../about.html">The Kerberos Documentation Set</a></li> <li class="toctree-l1"><a class="reference internal" href="../../../resources.html">Resources</a></li> </ul> <br/> <h4><a href="../../../index.html">Full Table of Contents </a></h4> <h4>Search</h4> <form class="search" action="../../../search.html" method="get"> <input type="text" name="q" size="18" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="ad-type-reserved"> <span id="ad-type-reserved-data"></span><h1>AD_TYPE_RESERVED<a class="headerlink" href="#ad-type-reserved" title="Permalink to this headline">¶</a></h1> <dl class="data"> <dt id="AD_TYPE_RESERVED"> <tt class="descname">AD_TYPE_RESERVED</tt><a class="headerlink" href="#AD_TYPE_RESERVED" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <table border="1" class="docutils"> <colgroup> <col width="51%" /> <col width="49%" /> </colgroup> <tbody valign="top"> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">AD_TYPE_RESERVED</span></tt></td> <td><tt class="docutils literal"><span class="pre">0x8000</span></tt></td> </tr> </tbody> </table> </div> </div> </div> </div> </div> <div class="clearer" ></div> </div> </div> <div class="footer-wrapper" > <div class="footer" > <div class="right" ><i>Release: 1.11.3</i><br /> &copy; <a href="../../../copyright.html">Copyright</a> 1985-2013, MIT. </div> <div class="left" > <a href="../../../index.html" title="Full Table of Contents" >Contents</a> | <a href="AD_TYPE_REGISTERED.html" title="AD_TYPE_REGISTERED" >previous</a> | <a href="AP_OPTS_ETYPE_NEGOTIATION.html" title="AP_OPTS_ETYPE_NEGOTIATION" >next</a> | <a href="../../../genindex.html" title="General Index" >index</a> | <a href="../../../search.html" title="Enter search criteria" >Search</a> | <a href="mailto:[email protected]?subject=Documentation__AD_TYPE_RESERVED">feedback</a> </div> </div> </div> </body> </html>
{ "pile_set_name": "Github" }
import { Rule } from "./rule"; import { Identifier } from "./types"; import { compatible } from "./constant"; import store, { getConfigByKey, Config } from "../store"; type Rules = Map<Identifier, Rule>; //类型别名 import { readFileSync, writeFileSync } from "fs"; class ConfigParser { rules: Rules = new Map<Identifier, Rule>(); file: string | undefined; constructor() {} config(): Config { return store.state.config; } keys() { return store.getters.keys; } setRule(key: Identifier, rule: Rule) { if (this.rules.has(key)) { throw `duplicate rule ${key}`; } this.rules.set(key, rule); } getRule(key: Identifier): Rule { return <Rule>this.rules.get(key); } get(key: Identifier) { return getConfigByKey(key); } set(key: Identifier, value: any, needCheck: boolean = true) { if (needCheck && !this.checkValid(key, value)) { return false; } const config = { [key]: value }; store.dispatch("updateConfig", config); return true; } checkValid(key: Identifier, value: any): boolean { const check = this.getRule(key).check; if ((check && !check(value)) || value == undefined) { return false; } return true; } getTooltip(key: Identifier) { return this.getRule(key).tooltip; } load(fileName: string): boolean { let status = true; try { const values = JSON.parse(readFileSync(fileName) as any); if (!values["version"] || !compatible(values["version"])) { throw "version incompatible, configs have been reset"; } const config: Config = {}; for (const key of this.rules.keys()) { let val = values[key]; if (!this.checkValid(key, val)) { //无效的话,就置为默认值 val = this.getRule(key).predefined; } config[key] = val; } store.dispatch("setConfig", config); } catch (e) { this.restoreDefault(fileName); status = false; } this.save(fileName); return status; } restoreDefault(fileName: string) { for (const [key, rule] of this.rules) { this.set(key, rule.predefined); } this.save(fileName); } save(fileName: string) { writeFileSync(fileName, JSON.stringify(store.state.config, null, 4)); } } export { ConfigParser };
{ "pile_set_name": "Github" }
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2002. # * Distributed under the Boost Software License, Version 1.0. (See # * accompanying file LICENSE_1_0.txt or copy at # * http://www.boost.org/LICENSE_1_0.txt) # * * # ************************************************************************** */ # # /* See http://www.boost.org for most recent version. */ # # ifndef MSGPACK_PREPROCESSOR_ITERATION_LOCAL_HPP # define MSGPACK_PREPROCESSOR_ITERATION_LOCAL_HPP # # include <msgpack/preprocessor/config/config.hpp> # include <msgpack/preprocessor/slot/slot.hpp> # include <msgpack/preprocessor/tuple/elem.hpp> # # /* MSGPACK_PP_LOCAL_ITERATE */ # # define MSGPACK_PP_LOCAL_ITERATE() <msgpack/preprocessor/iteration/detail/local.hpp> # # define MSGPACK_PP_LOCAL_C(n) (MSGPACK_PP_LOCAL_S) <= n && (MSGPACK_PP_LOCAL_F) >= n # define MSGPACK_PP_LOCAL_R(n) (MSGPACK_PP_LOCAL_F) <= n && (MSGPACK_PP_LOCAL_S) >= n # # endif
{ "pile_set_name": "Github" }
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package UnitTests * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ require_once 'Zend/Feed/Pubsubhubbub/Subscriber.php'; require_once 'Zend/Feed/Pubsubhubbub/Model/Subscription.php'; require_once 'Zend/Db/Table/Abstract.php'; /** * @category Zend * @package Zend_Feed * @subpackage UnitTests * @group Zend_Feed * @group Zend_Feed_Subsubhubbub * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Feed_Pubsubhubbub_SubscriberTest extends PHPUnit_Framework_TestCase { protected $_subscriber = null; protected $_adapter = null; protected $_tableGateway = null; public function setUp() { $client = new Zend_Http_Client; Zend_Feed_Pubsubhubbub::setHttpClient($client); $this->_subscriber = new Zend_Feed_Pubsubhubbub_Subscriber; $this->_adapter = $this->_getCleanMock( 'Zend_Db_Adapter_Abstract' ); $this->_tableGateway = $this->_getCleanMock( 'Zend_Db_Table_Abstract' ); $this->_tableGateway->expects($this->any())->method('getAdapter') ->will($this->returnValue($this->_adapter)); } public function testAddsHubServerUrl() { $this->_subscriber->addHubUrl('http://www.example.com/hub'); $this->assertEquals(array('http://www.example.com/hub'), $this->_subscriber->getHubUrls()); } public function testAddsHubServerUrlsFromArray() { $this->_subscriber->addHubUrls(array( 'http://www.example.com/hub', 'http://www.example.com/hub2' )); $this->assertEquals(array( 'http://www.example.com/hub', 'http://www.example.com/hub2' ), $this->_subscriber->getHubUrls()); } public function testAddsHubServerUrlsFromArrayUsingSetConfig() { $this->_subscriber->setConfig(array('hubUrls' => array( 'http://www.example.com/hub', 'http://www.example.com/hub2' ))); $this->assertEquals(array( 'http://www.example.com/hub', 'http://www.example.com/hub2' ), $this->_subscriber->getHubUrls()); } public function testRemovesHubServerUrl() { $this->_subscriber->addHubUrls(array( 'http://www.example.com/hub', 'http://www.example.com/hub2' )); $this->_subscriber->removeHubUrl('http://www.example.com/hub'); $this->assertEquals(array( 1 => 'http://www.example.com/hub2' ), $this->_subscriber->getHubUrls()); } public function testRetrievesUniqueHubServerUrlsOnly() { $this->_subscriber->addHubUrls(array( 'http://www.example.com/hub', 'http://www.example.com/hub2', 'http://www.example.com/hub' )); $this->assertEquals(array( 'http://www.example.com/hub', 'http://www.example.com/hub2' ), $this->_subscriber->getHubUrls()); } public function testThrowsExceptionOnSettingEmptyHubServerUrl() { try { $this->_subscriber->addHubUrl(''); $this->fail('Should not fail as an Exception would be raised and caught'); } catch (Zend_Feed_Pubsubhubbub_Exception $e) {} } public function testThrowsExceptionOnSettingNonStringHubServerUrl() { try { $this->_subscriber->addHubUrl(123); $this->fail('Should not fail as an Exception would be raised and caught'); } catch (Zend_Feed_Pubsubhubbub_Exception $e) {} } public function testThrowsExceptionOnSettingInvalidHubServerUrl() { try { $this->_subscriber->addHubUrl('http://'); $this->fail('Should not fail as an Exception would be raised and caught'); } catch (Zend_Feed_Pubsubhubbub_Exception $e) {} } public function testAddsParameter() { $this->_subscriber->setParameter('foo', 'bar'); $this->assertEquals(array('foo'=>'bar'), $this->_subscriber->getParameters()); } public function testAddsParametersFromArray() { $this->_subscriber->setParameters(array( 'foo' => 'bar', 'boo' => 'baz' )); $this->assertEquals(array( 'foo' => 'bar', 'boo' => 'baz' ), $this->_subscriber->getParameters()); } public function testAddsParametersFromArrayInSingleMethod() { $this->_subscriber->setParameter(array( 'foo' => 'bar', 'boo' => 'baz' )); $this->assertEquals(array( 'foo' => 'bar', 'boo' => 'baz' ), $this->_subscriber->getParameters()); } public function testAddsParametersFromArrayUsingSetConfig() { $this->_subscriber->setConfig(array('parameters' => array( 'foo' => 'bar', 'boo' => 'baz' ))); $this->assertEquals(array( 'foo' => 'bar', 'boo' => 'baz' ), $this->_subscriber->getParameters()); } public function testRemovesParameter() { $this->_subscriber->setParameters(array( 'foo' => 'bar', 'boo' => 'baz' )); $this->_subscriber->removeParameter('boo'); $this->assertEquals(array( 'foo' => 'bar' ), $this->_subscriber->getParameters()); } public function testRemovesParameterIfSetToNull() { $this->_subscriber->setParameters(array( 'foo' => 'bar', 'boo' => 'baz' )); $this->_subscriber->setParameter('boo', null); $this->assertEquals(array( 'foo' => 'bar' ), $this->_subscriber->getParameters()); } public function testCanSetTopicUrl() { $this->_subscriber->setTopicUrl('http://www.example.com/topic'); $this->assertEquals('http://www.example.com/topic', $this->_subscriber->getTopicUrl()); } public function testThrowsExceptionOnSettingEmptyTopicUrl() { try { $this->_subscriber->setTopicUrl(''); $this->fail('Should not fail as an Exception would be raised and caught'); } catch (Zend_Feed_Pubsubhubbub_Exception $e) {} } public function testThrowsExceptionOnSettingNonStringTopicUrl() { try { $this->_subscriber->setTopicUrl(123); $this->fail('Should not fail as an Exception would be raised and caught'); } catch (Zend_Feed_Pubsubhubbub_Exception $e) {} } public function testThrowsExceptionOnSettingInvalidTopicUrl() { try { $this->_subscriber->setTopicUrl('http://'); $this->fail('Should not fail as an Exception would be raised and caught'); } catch (Zend_Feed_Pubsubhubbub_Exception $e) {} } public function testThrowsExceptionOnMissingTopicUrl() { try { $this->_subscriber->getTopicUrl(); $this->fail('Should not fail as an Exception would be raised and caught'); } catch (Zend_Feed_Pubsubhubbub_Exception $e) {} } public function testCanSetCallbackUrl() { $this->_subscriber->setCallbackUrl('http://www.example.com/callback'); $this->assertEquals('http://www.example.com/callback', $this->_subscriber->getCallbackUrl()); } public function testThrowsExceptionOnSettingEmptyCallbackUrl() { try { $this->_subscriber->setCallbackUrl(''); $this->fail('Should not fail as an Exception would be raised and caught'); } catch (Zend_Feed_Pubsubhubbub_Exception $e) {} } public function testThrowsExceptionOnSettingNonStringCallbackUrl() { try { $this->_subscriber->setCallbackUrl(123); $this->fail('Should not fail as an Exception would be raised and caught'); } catch (Zend_Feed_Pubsubhubbub_Exception $e) {} } public function testThrowsExceptionOnSettingInvalidCallbackUrl() { try { $this->_subscriber->setCallbackUrl('http://'); $this->fail('Should not fail as an Exception would be raised and caught'); } catch (Zend_Feed_Pubsubhubbub_Exception $e) {} } public function testThrowsExceptionOnMissingCallbackUrl() { try { $this->_subscriber->getCallbackUrl(); $this->fail('Should not fail as an Exception would be raised and caught'); } catch (Zend_Feed_Pubsubhubbub_Exception $e) {} } public function testCanSetLeaseSeconds() { $this->_subscriber->setLeaseSeconds('10000'); $this->assertEquals(10000, $this->_subscriber->getLeaseSeconds()); } public function testThrowsExceptionOnSettingZeroAsLeaseSeconds() { try { $this->_subscriber->setLeaseSeconds(0); $this->fail('Should not fail as an Exception would be raised and caught'); } catch (Zend_Feed_Pubsubhubbub_Exception $e) {} } public function testThrowsExceptionOnSettingLessThanZeroAsLeaseSeconds() { try { $this->_subscriber->setLeaseSeconds(-1); $this->fail('Should not fail as an Exception would be raised and caught'); } catch (Zend_Feed_Pubsubhubbub_Exception $e) {} } public function testThrowsExceptionOnSettingAnyScalarTypeCastToAZeroOrLessIntegerAsLeaseSeconds() { try { $this->_subscriber->setLeaseSeconds('0aa'); $this->fail('Should not fail as an Exception would be raised and caught'); } catch (Zend_Feed_Pubsubhubbub_Exception $e) {} } public function testCanSetPreferredVerificationMode() { $this->_subscriber->setPreferredVerificationMode(Zend_Feed_Pubsubhubbub::VERIFICATION_MODE_ASYNC); $this->assertEquals(Zend_Feed_Pubsubhubbub::VERIFICATION_MODE_ASYNC, $this->_subscriber->getPreferredVerificationMode()); } public function testSetsPreferredVerificationModeThrowsExceptionOnSettingBadMode() { try { $this->_subscriber->setPreferredVerificationMode('abc'); $this->fail('Should not fail as an Exception would be raised and caught'); } catch (Zend_Feed_Pubsubhubbub_Exception $e) {} } public function testPreferredVerificationModeDefaultsToSync() { $this->assertEquals(Zend_Feed_Pubsubhubbub::VERIFICATION_MODE_SYNC, $this->_subscriber->getPreferredVerificationMode()); } public function testCanSetStorageImplementation() { $storage = new Zend_Feed_Pubsubhubbub_Model_Subscription($this->_tableGateway); $this->_subscriber->setStorage($storage); $this->assertThat($this->_subscriber->getStorage(), $this->identicalTo($storage)); } /** * @expectedException Zend_Feed_Pubsubhubbub_Exception */ public function testGetStorageThrowsExceptionIfNoneSet() { $this->_subscriber->getStorage(); } protected function _getCleanMock($className) { $class = new ReflectionClass($className); $methods = $class->getMethods(); $stubMethods = array(); foreach ($methods as $method) { if ($method->isPublic() || ($method->isProtected() && $method->isAbstract())) { $stubMethods[] = $method->getName(); } } $mocked = $this->getMock( $className, $stubMethods, array(), $className . '_PubsubSubscriberMock_' . uniqid(), false ); return $mocked; } }
{ "pile_set_name": "Github" }
; RUN: opt -S -consthoist < %s | FileCheck %s target datalayout = "E-m:e-i64:64-n32:64" target triple = "powerpc64-unknown-linux-gnu" %T = type { i32, i32, i32, i32 } ; Test if even cheap base addresses are hoisted. define i32 @test1() nounwind { ; CHECK-LABEL: @test1 ; CHECK: %const = bitcast i32 12345678 to i32 ; CHECK: %1 = inttoptr i32 %const to %T* ; CHECK: %addr1 = getelementptr %T, %T* %1, i32 0, i32 1 %addr1 = getelementptr %T, %T* inttoptr (i32 12345678 to %T*), i32 0, i32 1 %tmp1 = load i32, i32* %addr1 %addr2 = getelementptr %T, %T* inttoptr (i32 12345678 to %T*), i32 0, i32 2 %tmp2 = load i32, i32* %addr2 %addr3 = getelementptr %T, %T* inttoptr (i32 12345678 to %T*), i32 0, i32 3 %tmp3 = load i32, i32* %addr3 %tmp4 = add i32 %tmp1, %tmp2 %tmp5 = add i32 %tmp3, %tmp4 ret i32 %tmp5 }
{ "pile_set_name": "Github" }
/// The current protocol version pub const PROTOCOL_VERSION: u32 = 0; /// Maximum amount of friend operations sent in one move token message. pub const MAX_OPERATIONS_IN_BATCH: usize = 16; /// Maximum length of route used to pass credit. pub const MAX_ROUTE_LEN: usize = 32; /// Maximum length for a name of a currency. pub const MAX_CURRENCY_LEN: usize = 16; // TODO: Possibly convert TICK_MS to be u64? /// Amount of milliseconds in one tick: pub const TICK_MS: usize = 1000; /// Amount of ticks to wait before rekeying a secure channel. pub const TICKS_TO_REKEY: usize = 60 * 60 * (1000 / TICK_MS); // 1 hour /// If no message was sent for this amount of ticks, the connection will be closed pub const KEEPALIVE_TICKS: usize = 0x20; /// Relay server: The amount of ticks to wait before a relay connection from a client /// sends identification of which type of connection it is. pub const RELAY_CONN_TIMEOUT_TICKS: usize = 4; /// The stream TCP connection is split into prefix length frames. This is the maximum allowed /// length for such frame, measured in bytes. pub const MAX_FRAME_LENGTH: usize = 1 << 20; // 1[MB] /// Index server: The amount of ticks it takes for an idle node to be removed from the /// index server database. pub const INDEX_NODE_TIMEOUT_TICKS: usize = 60 * (1000 / TICK_MS); // 1 minute /// Maximum length for an address string used in NetAddress pub const MAX_NET_ADDRESS_LENGTH: usize = 256; /// Maximum amount of relays a node may use. /// We limit this number because sending many relays in a single move token message /// might exceed frame length pub const MAX_NODE_RELAYS: usize = 16;
{ "pile_set_name": "Github" }
<?php class MethodCallbackByReference { public function bar(&$a, &$b, $c) { Legacy::bar($a, $b, $c); } public function callback(&$a, &$b, $c) { $b = 1; } }
{ "pile_set_name": "Github" }
<?php /** * @author Lukáš Unger <[email protected]> * @copyright Copyright (c) Lukáš Unger * @license http://mit-license.org/ * * @link https://github.com/thephpleague/oauth2-server */ namespace League\OAuth2\Server\CodeChallengeVerifiers; class PlainVerifier implements CodeChallengeVerifierInterface { /** * Return code challenge method. * * @return string */ public function getMethod() { return 'plain'; } /** * Verify the code challenge. * * @param string $codeVerifier * @param string $codeChallenge * * @return bool */ public function verifyCodeChallenge($codeVerifier, $codeChallenge) { return \hash_equals($codeVerifier, $codeChallenge); } }
{ "pile_set_name": "Github" }
package com.netflix.hystrix.dashboard.stream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Utility class to work with InputStreams * * @author diegopacheco * */ public class UrlUtils { public static InputStream readXmlInputStream(String uri){ if (uri==null || "".equals(uri)) throw new IllegalArgumentException("Invalid uri. URI cannot be null or blank. "); try{ URL url = new URL(uri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); return connection.getInputStream(); }catch(Exception e){ throw new RuntimeException(e); } } }
{ "pile_set_name": "Github" }
extern float LibC1Func();
{ "pile_set_name": "Github" }
import Component from "@ember/component"; export default Component.extend({ tagName: "", expandDetails: false, actions: { toggleDetails() { this.toggleProperty("expandDetails"); }, filter(params) { this.set(`filters.${params.key}`, params.value); }, }, });
{ "pile_set_name": "Github" }
/** * This file has no copyright assigned and is placed in the Public Domain. * This file is part of the mingw-w64 runtime package. * No warranty is given; refer to the file DISCLAIMER.PD within this package. */ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 475 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error This stub requires an updated version of <rpcndr.h> #endif #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif #ifndef __scardssp_h__ #define __scardssp_h__ #ifndef __IByteBuffer_FWD_DEFINED__ #define __IByteBuffer_FWD_DEFINED__ typedef struct IByteBuffer IByteBuffer; #endif #ifndef __ISCardTypeConv_FWD_DEFINED__ #define __ISCardTypeConv_FWD_DEFINED__ typedef struct ISCardTypeConv ISCardTypeConv; #endif #ifndef __ISCardCmd_FWD_DEFINED__ #define __ISCardCmd_FWD_DEFINED__ typedef struct ISCardCmd ISCardCmd; #endif #ifndef __ISCardISO7816_FWD_DEFINED__ #define __ISCardISO7816_FWD_DEFINED__ typedef struct ISCardISO7816 ISCardISO7816; #endif #ifndef __ISCard_FWD_DEFINED__ #define __ISCard_FWD_DEFINED__ typedef struct ISCard ISCard; #endif #ifndef __ISCardDatabase_FWD_DEFINED__ #define __ISCardDatabase_FWD_DEFINED__ typedef struct ISCardDatabase ISCardDatabase; #endif #ifndef __ISCardLocate_FWD_DEFINED__ #define __ISCardLocate_FWD_DEFINED__ typedef struct ISCardLocate ISCardLocate; #endif #ifndef __CByteBuffer_FWD_DEFINED__ #define __CByteBuffer_FWD_DEFINED__ #ifdef __cplusplus typedef class CByteBuffer CByteBuffer; #else typedef struct CByteBuffer CByteBuffer; #endif #endif #ifndef __CSCardTypeConv_FWD_DEFINED__ #define __CSCardTypeConv_FWD_DEFINED__ #ifdef __cplusplus typedef class CSCardTypeConv CSCardTypeConv; #else typedef struct CSCardTypeConv CSCardTypeConv; #endif #endif #ifndef __CSCardCmd_FWD_DEFINED__ #define __CSCardCmd_FWD_DEFINED__ #ifdef __cplusplus typedef class CSCardCmd CSCardCmd; #else typedef struct CSCardCmd CSCardCmd; #endif #endif #ifndef __CSCardISO7816_FWD_DEFINED__ #define __CSCardISO7816_FWD_DEFINED__ #ifdef __cplusplus typedef class CSCardISO7816 CSCardISO7816; #else typedef struct CSCardISO7816 CSCardISO7816; #endif #endif #ifndef __CSCard_FWD_DEFINED__ #define __CSCard_FWD_DEFINED__ #ifdef __cplusplus typedef class CSCard CSCard; #else typedef struct CSCard CSCard; #endif #endif #ifndef __CSCardDatabase_FWD_DEFINED__ #define __CSCardDatabase_FWD_DEFINED__ #ifdef __cplusplus typedef class CSCardDatabase CSCardDatabase; #else typedef struct CSCardDatabase CSCardDatabase; #endif #endif #ifndef __CSCardLocate_FWD_DEFINED__ #define __CSCardLocate_FWD_DEFINED__ #ifdef __cplusplus typedef class CSCardLocate CSCardLocate; #else typedef struct CSCardLocate CSCardLocate; #endif #endif #include "oaidl.h" #include "ocidl.h" #ifdef __cplusplus extern "C" { #endif #ifndef __MIDL_user_allocate_free_DEFINED__ #define __MIDL_user_allocate_free_DEFINED__ void *__RPC_API MIDL_user_allocate(size_t); void __RPC_API MIDL_user_free(void *); #endif #ifndef _NULL_DEFINED #define _NULL_DEFINED #endif #ifndef _BYTE_DEFINED #define _BYTE_DEFINED typedef unsigned char BYTE; #endif #ifndef _LPBYTE_DEFINED #define _LPBYTE_DEFINED typedef BYTE *LPBYTE; #endif #ifndef _LPCBYTE_DEFINED #define _LPCBYTE_DEFINED typedef const BYTE *LPCBYTE; #endif #ifndef _HSCARD_DEFINED #define _HSCARD_DEFINED typedef ULONG_PTR HSCARD; #endif #ifndef _LPHSCARD_DEFINED #define _LPHSCARD_DEFINED typedef HSCARD *PHSCARD; typedef HSCARD *LPHSCARD; #endif #ifndef _HSCARDCONTEXT_DEFINED #define _HSCARDCONTEXT_DEFINED typedef ULONG_PTR HSCARDCONTEXT; #endif #ifndef _LPHSCARDCONTEXT_DEFINED #define _LPHSCARDCONTEXT_DEFINED typedef *PHSCARDCONTEXT; typedef *LPHSCARDCONTEXT; #endif #ifndef _BYTEARRAY_DEFINED #define _BYTEARRAY_DEFINED typedef struct tagBYTEARRAY { HGLOBAL hMem; DWORD dwSize; LPBYTE pbyData; } BYTEARRAY; #define _CB_BYTEARRAY_DEFINED #define CB_BYTEARRAY (sizeof(BYTEARRAY)) #define _PBYTEARRAY_DEFINED typedef BYTEARRAY *PBYTEARRAY; #define _PCBYTEARRAY_DEFINED typedef const BYTEARRAY *PCBYTEARRAY; #define _LPBYTEARRAY_DEFINED typedef BYTEARRAY *LPBYTEARRAY; #define _LPCBYTEARRAY_DEFINED typedef const BYTEARRAY *LPCBYTEARRAY; #endif #ifndef _STATSTRUCT #define _STATSTRUCT typedef struct tagSTATSTRUCT { LONG type; LONG cbSize; LONG grfMode; LONG grfLocksSupported; LONG grfStateBits; } STATSTRUCT; #define _CB_STATSTRUCT_DEFINED #define CB_STATSTRUCT (sizeof(STATSTRUCT)) #define _LPSTATSTRUCT_DEFINED typedef STATSTRUCT *LPSTATSTRUCT; #endif #ifndef _ISO_APDU_TYPE #define _ISO_APDU_TYPE typedef enum tagISO_APDU_TYPE { ISO_CASE_1 = 1,ISO_CASE_2 = 2,ISO_CASE_3 = 3,ISO_CASE_4 = 4 } ISO_APDU_TYPE; #endif #ifndef _SCARD_SHARE_MODES_DEFINED #define _SCARD_SHARE_MODES_DEFINED typedef enum tagSCARD_SHARE_MODES { EXCLUSIVE = 1,SHARED = 2 } SCARD_SHARE_MODES; #endif #ifndef _SCARD_DISPOSITIONS_DEFINED #define _SCARD_DISPOSITIONS_DEFINED typedef enum tagSCARD_DISPOSITIONS { LEAVE = 0,RESET = 1,UNPOWER = 2,EJECT = 3 } SCARD_DISPOSITIONS; #endif #ifndef _SCARD_STATES_DEFINED #define _SCARD_STATES_DEFINED typedef enum tagSCARD_STATES { ABSENT = 1,PRESENT = 2,SWALLOWED = 3,POWERED = 4,NEGOTIABLEMODE = 5,SPECIFICMODE = 6 } SCARD_STATES; #endif #ifndef _SCARD_PROTOCOLS_DEFINED #define _SCARD_PROTOCOLS_DEFINED typedef enum tagSCARD_PROTOCOLS { T0 = 0x1,T1 = 0x2,RAW = 0xff } SCARD_PROTOCOLS; #endif #ifndef _SCARD_INFO #define _SCARD_INFO typedef struct tagSCARDINFO { HSCARD hCard; HSCARDCONTEXT hContext; SCARD_PROTOCOLS ActiveProtocol; SCARD_SHARE_MODES ShareMode; LONG_PTR hwndOwner; LONG_PTR lpfnConnectProc; LONG_PTR lpfnCheckProc; LONG_PTR lpfnDisconnectProc; } SCARDINFO; #define _LPSCARDINFO typedef SCARDINFO *PSCARDINFO; typedef SCARDINFO *LPSCARDINFO; #endif #ifndef _LPBYTEBUFFER_DEFINED #define _LPBYTEBUFFER_DEFINED extern RPC_IF_HANDLE __MIDL_itf_scardssp_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_scardssp_0000_v0_0_s_ifspec; #ifndef __IByteBuffer_INTERFACE_DEFINED__ #define __IByteBuffer_INTERFACE_DEFINED__ typedef IByteBuffer *LPBYTEBUFFER; typedef const IByteBuffer *LPCBYTEBUFFER; EXTERN_C const IID IID_IByteBuffer; #if defined(__cplusplus) && !defined(CINTERFACE) struct IByteBuffer : public IDispatch { public: virtual HRESULT WINAPI get_Stream(LPSTREAM *ppStream) = 0; virtual HRESULT WINAPI put_Stream(LPSTREAM pStream) = 0; virtual HRESULT WINAPI Clone(LPBYTEBUFFER *ppByteBuffer) = 0; virtual HRESULT WINAPI Commit(LONG grfCommitFlags) = 0; virtual HRESULT WINAPI CopyTo(LPBYTEBUFFER *ppByteBuffer,LONG cb,LONG *pcbRead = 0,LONG *pcbWritten = 0) = 0; virtual HRESULT WINAPI Initialize(LONG lSize = 1,BYTE *pData = 0) = 0; virtual HRESULT WINAPI LockRegion(LONG libOffset,LONG cb,LONG dwLockType) = 0; virtual HRESULT WINAPI Read(BYTE *pByte,LONG cb,LONG *pcbRead = 0) = 0; virtual HRESULT WINAPI Revert(void) = 0; virtual HRESULT WINAPI Seek(LONG dLibMove,LONG dwOrigin,LONG *pLibnewPosition = 0) = 0; virtual HRESULT WINAPI SetSize(LONG libNewSize) = 0; virtual HRESULT WINAPI Stat(LPSTATSTRUCT pstatstg,LONG grfStatFlag) = 0; virtual HRESULT WINAPI UnlockRegion(LONG libOffset,LONG cb,LONG dwLockType) = 0; virtual HRESULT WINAPI Write(BYTE *pByte,LONG cb,LONG *pcbWritten) = 0; }; #else typedef struct IByteBufferVtbl { BEGIN_INTERFACE HRESULT (WINAPI *QueryInterface)(IByteBuffer *This,REFIID riid,void **ppvObject); ULONG (WINAPI *AddRef)(IByteBuffer *This); ULONG (WINAPI *Release)(IByteBuffer *This); HRESULT (WINAPI *GetTypeInfoCount)(IByteBuffer *This,UINT *pctinfo); HRESULT (WINAPI *GetTypeInfo)(IByteBuffer *This,UINT iTInfo,LCID lcid,ITypeInfo **ppTInfo); HRESULT (WINAPI *GetIDsOfNames)(IByteBuffer *This,REFIID riid,LPOLESTR *rgszNames,UINT cNames,LCID lcid,DISPID *rgDispId); HRESULT (WINAPI *Invoke)(IByteBuffer *This,DISPID dispIdMember,REFIID riid,LCID lcid,WORD wFlags,DISPPARAMS *pDispParams,VARIANT *pVarResult,EXCEPINFO *pExcepInfo,UINT *puArgErr); HRESULT (WINAPI *get_Stream)(IByteBuffer *This,LPSTREAM *ppStream); HRESULT (WINAPI *put_Stream)(IByteBuffer *This,LPSTREAM pStream); HRESULT (WINAPI *Clone)(IByteBuffer *This,LPBYTEBUFFER *ppByteBuffer); HRESULT (WINAPI *Commit)(IByteBuffer *This,LONG grfCommitFlags); HRESULT (WINAPI *CopyTo)(IByteBuffer *This,LPBYTEBUFFER *ppByteBuffer,LONG cb,LONG *pcbRead,LONG *pcbWritten); HRESULT (WINAPI *Initialize)(IByteBuffer *This,LONG lSize,BYTE *pData); HRESULT (WINAPI *LockRegion)(IByteBuffer *This,LONG libOffset,LONG cb,LONG dwLockType); HRESULT (WINAPI *Read)(IByteBuffer *This,BYTE *pByte,LONG cb,LONG *pcbRead); HRESULT (WINAPI *Revert)(IByteBuffer *This); HRESULT (WINAPI *Seek)(IByteBuffer *This,LONG dLibMove,LONG dwOrigin,LONG *pLibnewPosition); HRESULT (WINAPI *SetSize)(IByteBuffer *This,LONG libNewSize); HRESULT (WINAPI *Stat)(IByteBuffer *This,LPSTATSTRUCT pstatstg,LONG grfStatFlag); HRESULT (WINAPI *UnlockRegion)(IByteBuffer *This,LONG libOffset,LONG cb,LONG dwLockType); HRESULT (WINAPI *Write)(IByteBuffer *This,BYTE *pByte,LONG cb,LONG *pcbWritten); END_INTERFACE } IByteBufferVtbl; struct IByteBuffer { CONST_VTBL struct IByteBufferVtbl *lpVtbl; }; #ifdef COBJMACROS #define IByteBuffer_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) #define IByteBuffer_AddRef(This) (This)->lpVtbl->AddRef(This) #define IByteBuffer_Release(This) (This)->lpVtbl->Release(This) #define IByteBuffer_GetTypeInfoCount(This,pctinfo) (This)->lpVtbl->GetTypeInfoCount(This,pctinfo) #define IByteBuffer_GetTypeInfo(This,iTInfo,lcid,ppTInfo) (This)->lpVtbl->GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define IByteBuffer_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) (This)->lpVtbl->GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define IByteBuffer_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) (This)->lpVtbl->Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #define IByteBuffer_get_Stream(This,ppStream) (This)->lpVtbl->get_Stream(This,ppStream) #define IByteBuffer_put_Stream(This,pStream) (This)->lpVtbl->put_Stream(This,pStream) #define IByteBuffer_Clone(This,ppByteBuffer) (This)->lpVtbl->Clone(This,ppByteBuffer) #define IByteBuffer_Commit(This,grfCommitFlags) (This)->lpVtbl->Commit(This,grfCommitFlags) #define IByteBuffer_CopyTo(This,ppByteBuffer,cb,pcbRead,pcbWritten) (This)->lpVtbl->CopyTo(This,ppByteBuffer,cb,pcbRead,pcbWritten) #define IByteBuffer_Initialize(This,lSize,pData) (This)->lpVtbl->Initialize(This,lSize,pData) #define IByteBuffer_LockRegion(This,libOffset,cb,dwLockType) (This)->lpVtbl->LockRegion(This,libOffset,cb,dwLockType) #define IByteBuffer_Read(This,pByte,cb,pcbRead) (This)->lpVtbl->Read(This,pByte,cb,pcbRead) #define IByteBuffer_Revert(This) (This)->lpVtbl->Revert(This) #define IByteBuffer_Seek(This,dLibMove,dwOrigin,pLibnewPosition) (This)->lpVtbl->Seek(This,dLibMove,dwOrigin,pLibnewPosition) #define IByteBuffer_SetSize(This,libNewSize) (This)->lpVtbl->SetSize(This,libNewSize) #define IByteBuffer_Stat(This,pstatstg,grfStatFlag) (This)->lpVtbl->Stat(This,pstatstg,grfStatFlag) #define IByteBuffer_UnlockRegion(This,libOffset,cb,dwLockType) (This)->lpVtbl->UnlockRegion(This,libOffset,cb,dwLockType) #define IByteBuffer_Write(This,pByte,cb,pcbWritten) (This)->lpVtbl->Write(This,pByte,cb,pcbWritten) #endif #endif HRESULT WINAPI IByteBuffer_get_Stream_Proxy(IByteBuffer *This,LPSTREAM *ppStream); void __RPC_STUB IByteBuffer_get_Stream_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI IByteBuffer_put_Stream_Proxy(IByteBuffer *This,LPSTREAM pStream); void __RPC_STUB IByteBuffer_put_Stream_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI IByteBuffer_Clone_Proxy(IByteBuffer *This,LPBYTEBUFFER *ppByteBuffer); void __RPC_STUB IByteBuffer_Clone_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI IByteBuffer_Commit_Proxy(IByteBuffer *This,LONG grfCommitFlags); void __RPC_STUB IByteBuffer_Commit_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI IByteBuffer_CopyTo_Proxy(IByteBuffer *This,LPBYTEBUFFER *ppByteBuffer,LONG cb,LONG *pcbRead,LONG *pcbWritten); void __RPC_STUB IByteBuffer_CopyTo_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI IByteBuffer_Initialize_Proxy(IByteBuffer *This,LONG lSize,BYTE *pData); void __RPC_STUB IByteBuffer_Initialize_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI IByteBuffer_LockRegion_Proxy(IByteBuffer *This,LONG libOffset,LONG cb,LONG dwLockType); void __RPC_STUB IByteBuffer_LockRegion_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI IByteBuffer_Read_Proxy(IByteBuffer *This,BYTE *pByte,LONG cb,LONG *pcbRead); void __RPC_STUB IByteBuffer_Read_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI IByteBuffer_Revert_Proxy(IByteBuffer *This); void __RPC_STUB IByteBuffer_Revert_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI IByteBuffer_Seek_Proxy(IByteBuffer *This,LONG dLibMove,LONG dwOrigin,LONG *pLibnewPosition); void __RPC_STUB IByteBuffer_Seek_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI IByteBuffer_SetSize_Proxy(IByteBuffer *This,LONG libNewSize); void __RPC_STUB IByteBuffer_SetSize_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI IByteBuffer_Stat_Proxy(IByteBuffer *This,LPSTATSTRUCT pstatstg,LONG grfStatFlag); void __RPC_STUB IByteBuffer_Stat_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI IByteBuffer_UnlockRegion_Proxy(IByteBuffer *This,LONG libOffset,LONG cb,LONG dwLockType); void __RPC_STUB IByteBuffer_UnlockRegion_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI IByteBuffer_Write_Proxy(IByteBuffer *This,BYTE *pByte,LONG cb,LONG *pcbWritten); void __RPC_STUB IByteBuffer_Write_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); #endif #endif #ifndef _LPSCARDTYPECONV_DEFINED #define _LPSCARDTYPECONV_DEFINED extern RPC_IF_HANDLE __MIDL_itf_scardssp_0244_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_scardssp_0244_v0_0_s_ifspec; #ifndef __ISCardTypeConv_INTERFACE_DEFINED__ #define __ISCardTypeConv_INTERFACE_DEFINED__ typedef ISCardTypeConv *LPSCARDTYPECONV; EXTERN_C const IID IID_ISCardTypeConv; #if defined(__cplusplus) && !defined(CINTERFACE) struct ISCardTypeConv : public IDispatch { public: virtual HRESULT WINAPI ConvertByteArrayToByteBuffer(LPBYTE pbyArray,DWORD dwArraySize,LPBYTEBUFFER *ppbyBuffer) = 0; virtual HRESULT WINAPI ConvertByteBufferToByteArray(LPBYTEBUFFER pbyBuffer,LPBYTEARRAY *ppArray) = 0; virtual HRESULT WINAPI ConvertByteBufferToSafeArray(LPBYTEBUFFER pbyBuffer,LPSAFEARRAY *ppbyArray) = 0; virtual HRESULT WINAPI ConvertSafeArrayToByteBuffer(LPSAFEARRAY pbyArray,LPBYTEBUFFER *ppbyBuff) = 0; virtual HRESULT WINAPI CreateByteArray(DWORD dwAllocSize,LPBYTE *ppbyArray) = 0; virtual HRESULT WINAPI CreateByteBuffer(DWORD dwAllocSize,LPBYTEBUFFER *ppbyBuff) = 0; virtual HRESULT WINAPI CreateSafeArray(UINT nAllocSize,LPSAFEARRAY *ppArray) = 0; virtual HRESULT WINAPI FreeIStreamMemoryPtr(LPSTREAM pStrm,LPBYTE pMem) = 0; virtual HRESULT WINAPI GetAtIStreamMemory(LPSTREAM pStrm,LPBYTEARRAY *ppMem) = 0; virtual HRESULT WINAPI SizeOfIStream(LPSTREAM pStrm,ULARGE_INTEGER *puliSize) = 0; }; #else typedef struct ISCardTypeConvVtbl { BEGIN_INTERFACE HRESULT (WINAPI *QueryInterface)(ISCardTypeConv *This,REFIID riid,void **ppvObject); ULONG (WINAPI *AddRef)(ISCardTypeConv *This); ULONG (WINAPI *Release)(ISCardTypeConv *This); HRESULT (WINAPI *GetTypeInfoCount)(ISCardTypeConv *This,UINT *pctinfo); HRESULT (WINAPI *GetTypeInfo)(ISCardTypeConv *This,UINT iTInfo,LCID lcid,ITypeInfo **ppTInfo); HRESULT (WINAPI *GetIDsOfNames)(ISCardTypeConv *This,REFIID riid,LPOLESTR *rgszNames,UINT cNames,LCID lcid,DISPID *rgDispId); HRESULT (WINAPI *Invoke)(ISCardTypeConv *This,DISPID dispIdMember,REFIID riid,LCID lcid,WORD wFlags,DISPPARAMS *pDispParams,VARIANT *pVarResult,EXCEPINFO *pExcepInfo,UINT *puArgErr); HRESULT (WINAPI *ConvertByteArrayToByteBuffer)(ISCardTypeConv *This,LPBYTE pbyArray,DWORD dwArraySize,LPBYTEBUFFER *ppbyBuffer); HRESULT (WINAPI *ConvertByteBufferToByteArray)(ISCardTypeConv *This,LPBYTEBUFFER pbyBuffer,LPBYTEARRAY *ppArray); HRESULT (WINAPI *ConvertByteBufferToSafeArray)(ISCardTypeConv *This,LPBYTEBUFFER pbyBuffer,LPSAFEARRAY *ppbyArray); HRESULT (WINAPI *ConvertSafeArrayToByteBuffer)(ISCardTypeConv *This,LPSAFEARRAY pbyArray,LPBYTEBUFFER *ppbyBuff); HRESULT (WINAPI *CreateByteArray)(ISCardTypeConv *This,DWORD dwAllocSize,LPBYTE *ppbyArray); HRESULT (WINAPI *CreateByteBuffer)(ISCardTypeConv *This,DWORD dwAllocSize,LPBYTEBUFFER *ppbyBuff); HRESULT (WINAPI *CreateSafeArray)(ISCardTypeConv *This,UINT nAllocSize,LPSAFEARRAY *ppArray); HRESULT (WINAPI *FreeIStreamMemoryPtr)(ISCardTypeConv *This,LPSTREAM pStrm,LPBYTE pMem); HRESULT (WINAPI *GetAtIStreamMemory)(ISCardTypeConv *This,LPSTREAM pStrm,LPBYTEARRAY *ppMem); HRESULT (WINAPI *SizeOfIStream)(ISCardTypeConv *This,LPSTREAM pStrm,ULARGE_INTEGER *puliSize); END_INTERFACE } ISCardTypeConvVtbl; struct ISCardTypeConv { CONST_VTBL struct ISCardTypeConvVtbl *lpVtbl; }; #ifdef COBJMACROS #define ISCardTypeConv_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) #define ISCardTypeConv_AddRef(This) (This)->lpVtbl->AddRef(This) #define ISCardTypeConv_Release(This) (This)->lpVtbl->Release(This) #define ISCardTypeConv_GetTypeInfoCount(This,pctinfo) (This)->lpVtbl->GetTypeInfoCount(This,pctinfo) #define ISCardTypeConv_GetTypeInfo(This,iTInfo,lcid,ppTInfo) (This)->lpVtbl->GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define ISCardTypeConv_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) (This)->lpVtbl->GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define ISCardTypeConv_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) (This)->lpVtbl->Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #define ISCardTypeConv_ConvertByteArrayToByteBuffer(This,pbyArray,dwArraySize,ppbyBuffer) (This)->lpVtbl->ConvertByteArrayToByteBuffer(This,pbyArray,dwArraySize,ppbyBuffer) #define ISCardTypeConv_ConvertByteBufferToByteArray(This,pbyBuffer,ppArray) (This)->lpVtbl->ConvertByteBufferToByteArray(This,pbyBuffer,ppArray) #define ISCardTypeConv_ConvertByteBufferToSafeArray(This,pbyBuffer,ppbyArray) (This)->lpVtbl->ConvertByteBufferToSafeArray(This,pbyBuffer,ppbyArray) #define ISCardTypeConv_ConvertSafeArrayToByteBuffer(This,pbyArray,ppbyBuff) (This)->lpVtbl->ConvertSafeArrayToByteBuffer(This,pbyArray,ppbyBuff) #define ISCardTypeConv_CreateByteArray(This,dwAllocSize,ppbyArray) (This)->lpVtbl->CreateByteArray(This,dwAllocSize,ppbyArray) #define ISCardTypeConv_CreateByteBuffer(This,dwAllocSize,ppbyBuff) (This)->lpVtbl->CreateByteBuffer(This,dwAllocSize,ppbyBuff) #define ISCardTypeConv_CreateSafeArray(This,nAllocSize,ppArray) (This)->lpVtbl->CreateSafeArray(This,nAllocSize,ppArray) #define ISCardTypeConv_FreeIStreamMemoryPtr(This,pStrm,pMem) (This)->lpVtbl->FreeIStreamMemoryPtr(This,pStrm,pMem) #define ISCardTypeConv_GetAtIStreamMemory(This,pStrm,ppMem) (This)->lpVtbl->GetAtIStreamMemory(This,pStrm,ppMem) #define ISCardTypeConv_SizeOfIStream(This,pStrm,puliSize) (This)->lpVtbl->SizeOfIStream(This,pStrm,puliSize) #endif #endif HRESULT WINAPI ISCardTypeConv_ConvertByteArrayToByteBuffer_Proxy(ISCardTypeConv *This,LPBYTE pbyArray,DWORD dwArraySize,LPBYTEBUFFER *ppbyBuffer); void __RPC_STUB ISCardTypeConv_ConvertByteArrayToByteBuffer_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardTypeConv_ConvertByteBufferToByteArray_Proxy(ISCardTypeConv *This,LPBYTEBUFFER pbyBuffer,LPBYTEARRAY *ppArray); void __RPC_STUB ISCardTypeConv_ConvertByteBufferToByteArray_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardTypeConv_ConvertByteBufferToSafeArray_Proxy(ISCardTypeConv *This,LPBYTEBUFFER pbyBuffer,LPSAFEARRAY *ppbyArray); void __RPC_STUB ISCardTypeConv_ConvertByteBufferToSafeArray_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardTypeConv_ConvertSafeArrayToByteBuffer_Proxy(ISCardTypeConv *This,LPSAFEARRAY pbyArray,LPBYTEBUFFER *ppbyBuff); void __RPC_STUB ISCardTypeConv_ConvertSafeArrayToByteBuffer_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardTypeConv_CreateByteArray_Proxy(ISCardTypeConv *This,DWORD dwAllocSize,LPBYTE *ppbyArray); void __RPC_STUB ISCardTypeConv_CreateByteArray_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardTypeConv_CreateByteBuffer_Proxy(ISCardTypeConv *This,DWORD dwAllocSize,LPBYTEBUFFER *ppbyBuff); void __RPC_STUB ISCardTypeConv_CreateByteBuffer_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardTypeConv_CreateSafeArray_Proxy(ISCardTypeConv *This,UINT nAllocSize,LPSAFEARRAY *ppArray); void __RPC_STUB ISCardTypeConv_CreateSafeArray_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardTypeConv_FreeIStreamMemoryPtr_Proxy(ISCardTypeConv *This,LPSTREAM pStrm,LPBYTE pMem); void __RPC_STUB ISCardTypeConv_FreeIStreamMemoryPtr_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardTypeConv_GetAtIStreamMemory_Proxy(ISCardTypeConv *This,LPSTREAM pStrm,LPBYTEARRAY *ppMem); void __RPC_STUB ISCardTypeConv_GetAtIStreamMemory_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardTypeConv_SizeOfIStream_Proxy(ISCardTypeConv *This,LPSTREAM pStrm,ULARGE_INTEGER *puliSize); void __RPC_STUB ISCardTypeConv_SizeOfIStream_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); #endif #endif #ifndef _LPSCARDCMD_DEFINED #define _LPSCARDCMD_DEFINED extern RPC_IF_HANDLE __MIDL_itf_scardssp_0245_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_scardssp_0245_v0_0_s_ifspec; #ifndef __ISCardCmd_INTERFACE_DEFINED__ #define __ISCardCmd_INTERFACE_DEFINED__ typedef ISCardCmd *LPSCARDCMD; EXTERN_C const IID IID_ISCardCmd; #if defined(__cplusplus) && !defined(CINTERFACE) struct ISCardCmd : public IDispatch { public: virtual HRESULT WINAPI get_Apdu(LPBYTEBUFFER *ppApdu) = 0; virtual HRESULT WINAPI put_Apdu(LPBYTEBUFFER pApdu) = 0; virtual HRESULT WINAPI get_ApduLength(LONG *plSize) = 0; virtual HRESULT WINAPI get_ApduReply(LPBYTEBUFFER *ppReplyApdu) = 0; virtual HRESULT WINAPI put_ApduReply(LPBYTEBUFFER pReplyApdu) = 0; virtual HRESULT WINAPI get_ApduReplyLength(LONG *plSize) = 0; virtual HRESULT WINAPI put_ApduReplyLength(LONG lSize) = 0; virtual HRESULT WINAPI get_ClassId(BYTE *pbyClass) = 0; virtual HRESULT WINAPI put_ClassId(BYTE byClass = 0) = 0; virtual HRESULT WINAPI get_Data(LPBYTEBUFFER *ppData) = 0; virtual HRESULT WINAPI put_Data(LPBYTEBUFFER pData) = 0; virtual HRESULT WINAPI get_InstructionId(BYTE *pbyIns) = 0; virtual HRESULT WINAPI put_InstructionId(BYTE byIns) = 0; virtual HRESULT WINAPI get_LeField(LONG *plSize) = 0; virtual HRESULT WINAPI get_P1(BYTE *pbyP1) = 0; virtual HRESULT WINAPI put_P1(BYTE byP1) = 0; virtual HRESULT WINAPI get_P2(BYTE *pbyP2) = 0; virtual HRESULT WINAPI put_P2(BYTE byP2) = 0; virtual HRESULT WINAPI get_P3(BYTE *pbyP3) = 0; virtual HRESULT WINAPI get_ReplyStatus(LPWORD pwStatus) = 0; virtual HRESULT WINAPI put_ReplyStatus(WORD wStatus) = 0; virtual HRESULT WINAPI get_ReplyStatusSW1(BYTE *pbySW1) = 0; virtual HRESULT WINAPI get_ReplyStatusSW2(BYTE *pbySW2) = 0; virtual HRESULT WINAPI get_Type(ISO_APDU_TYPE *pType) = 0; virtual HRESULT WINAPI get_Nad(BYTE *pbNad) = 0; virtual HRESULT WINAPI put_Nad(BYTE bNad) = 0; virtual HRESULT WINAPI get_ReplyNad(BYTE *pbNad) = 0; virtual HRESULT WINAPI put_ReplyNad(BYTE bNad) = 0; virtual HRESULT WINAPI BuildCmd(BYTE byClassId,BYTE byInsId,BYTE byP1 = 0,BYTE byP2 = 0,LPBYTEBUFFER pbyData = 0,LONG *plLe = 0) = 0; virtual HRESULT WINAPI Clear(void) = 0; virtual HRESULT WINAPI Encapsulate(LPBYTEBUFFER pApdu,ISO_APDU_TYPE ApduType) = 0; virtual HRESULT WINAPI get_AlternateClassId(BYTE *pbyClass) = 0; virtual HRESULT WINAPI put_AlternateClassId(BYTE byClass) = 0; }; #else typedef struct ISCardCmdVtbl { BEGIN_INTERFACE HRESULT (WINAPI *QueryInterface)(ISCardCmd *This,REFIID riid,void **ppvObject); ULONG (WINAPI *AddRef)(ISCardCmd *This); ULONG (WINAPI *Release)(ISCardCmd *This); HRESULT (WINAPI *GetTypeInfoCount)(ISCardCmd *This,UINT *pctinfo); HRESULT (WINAPI *GetTypeInfo)(ISCardCmd *This,UINT iTInfo,LCID lcid,ITypeInfo **ppTInfo); HRESULT (WINAPI *GetIDsOfNames)(ISCardCmd *This,REFIID riid,LPOLESTR *rgszNames,UINT cNames,LCID lcid,DISPID *rgDispId); HRESULT (WINAPI *Invoke)(ISCardCmd *This,DISPID dispIdMember,REFIID riid,LCID lcid,WORD wFlags,DISPPARAMS *pDispParams,VARIANT *pVarResult,EXCEPINFO *pExcepInfo,UINT *puArgErr); HRESULT (WINAPI *get_Apdu)(ISCardCmd *This,LPBYTEBUFFER *ppApdu); HRESULT (WINAPI *put_Apdu)(ISCardCmd *This,LPBYTEBUFFER pApdu); HRESULT (WINAPI *get_ApduLength)(ISCardCmd *This,LONG *plSize); HRESULT (WINAPI *get_ApduReply)(ISCardCmd *This,LPBYTEBUFFER *ppReplyApdu); HRESULT (WINAPI *put_ApduReply)(ISCardCmd *This,LPBYTEBUFFER pReplyApdu); HRESULT (WINAPI *get_ApduReplyLength)(ISCardCmd *This,LONG *plSize); HRESULT (WINAPI *put_ApduReplyLength)(ISCardCmd *This,LONG lSize); HRESULT (WINAPI *get_ClassId)(ISCardCmd *This,BYTE *pbyClass); HRESULT (WINAPI *put_ClassId)(ISCardCmd *This,BYTE byClass); HRESULT (WINAPI *get_Data)(ISCardCmd *This,LPBYTEBUFFER *ppData); HRESULT (WINAPI *put_Data)(ISCardCmd *This,LPBYTEBUFFER pData); HRESULT (WINAPI *get_InstructionId)(ISCardCmd *This,BYTE *pbyIns); HRESULT (WINAPI *put_InstructionId)(ISCardCmd *This,BYTE byIns); HRESULT (WINAPI *get_LeField)(ISCardCmd *This,LONG *plSize); HRESULT (WINAPI *get_P1)(ISCardCmd *This,BYTE *pbyP1); HRESULT (WINAPI *put_P1)(ISCardCmd *This,BYTE byP1); HRESULT (WINAPI *get_P2)(ISCardCmd *This,BYTE *pbyP2); HRESULT (WINAPI *put_P2)(ISCardCmd *This,BYTE byP2); HRESULT (WINAPI *get_P3)(ISCardCmd *This,BYTE *pbyP3); HRESULT (WINAPI *get_ReplyStatus)(ISCardCmd *This,LPWORD pwStatus); HRESULT (WINAPI *put_ReplyStatus)(ISCardCmd *This,WORD wStatus); HRESULT (WINAPI *get_ReplyStatusSW1)(ISCardCmd *This,BYTE *pbySW1); HRESULT (WINAPI *get_ReplyStatusSW2)(ISCardCmd *This,BYTE *pbySW2); HRESULT (WINAPI *get_Type)(ISCardCmd *This,ISO_APDU_TYPE *pType); HRESULT (WINAPI *get_Nad)(ISCardCmd *This,BYTE *pbNad); HRESULT (WINAPI *put_Nad)(ISCardCmd *This,BYTE bNad); HRESULT (WINAPI *get_ReplyNad)(ISCardCmd *This,BYTE *pbNad); HRESULT (WINAPI *put_ReplyNad)(ISCardCmd *This,BYTE bNad); HRESULT (WINAPI *BuildCmd)(ISCardCmd *This,BYTE byClassId,BYTE byInsId,BYTE byP1,BYTE byP2,LPBYTEBUFFER pbyData,LONG *plLe); HRESULT (WINAPI *Clear)(ISCardCmd *This); HRESULT (WINAPI *Encapsulate)(ISCardCmd *This,LPBYTEBUFFER pApdu,ISO_APDU_TYPE ApduType); HRESULT (WINAPI *get_AlternateClassId)(ISCardCmd *This,BYTE *pbyClass); HRESULT (WINAPI *put_AlternateClassId)(ISCardCmd *This,BYTE byClass); END_INTERFACE } ISCardCmdVtbl; struct ISCardCmd { CONST_VTBL struct ISCardCmdVtbl *lpVtbl; }; #ifdef COBJMACROS #define ISCardCmd_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) #define ISCardCmd_AddRef(This) (This)->lpVtbl->AddRef(This) #define ISCardCmd_Release(This) (This)->lpVtbl->Release(This) #define ISCardCmd_GetTypeInfoCount(This,pctinfo) (This)->lpVtbl->GetTypeInfoCount(This,pctinfo) #define ISCardCmd_GetTypeInfo(This,iTInfo,lcid,ppTInfo) (This)->lpVtbl->GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define ISCardCmd_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) (This)->lpVtbl->GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define ISCardCmd_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) (This)->lpVtbl->Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #define ISCardCmd_get_Apdu(This,ppApdu) (This)->lpVtbl->get_Apdu(This,ppApdu) #define ISCardCmd_put_Apdu(This,pApdu) (This)->lpVtbl->put_Apdu(This,pApdu) #define ISCardCmd_get_ApduLength(This,plSize) (This)->lpVtbl->get_ApduLength(This,plSize) #define ISCardCmd_get_ApduReply(This,ppReplyApdu) (This)->lpVtbl->get_ApduReply(This,ppReplyApdu) #define ISCardCmd_put_ApduReply(This,pReplyApdu) (This)->lpVtbl->put_ApduReply(This,pReplyApdu) #define ISCardCmd_get_ApduReplyLength(This,plSize) (This)->lpVtbl->get_ApduReplyLength(This,plSize) #define ISCardCmd_put_ApduReplyLength(This,lSize) (This)->lpVtbl->put_ApduReplyLength(This,lSize) #define ISCardCmd_get_ClassId(This,pbyClass) (This)->lpVtbl->get_ClassId(This,pbyClass) #define ISCardCmd_put_ClassId(This,byClass) (This)->lpVtbl->put_ClassId(This,byClass) #define ISCardCmd_get_Data(This,ppData) (This)->lpVtbl->get_Data(This,ppData) #define ISCardCmd_put_Data(This,pData) (This)->lpVtbl->put_Data(This,pData) #define ISCardCmd_get_InstructionId(This,pbyIns) (This)->lpVtbl->get_InstructionId(This,pbyIns) #define ISCardCmd_put_InstructionId(This,byIns) (This)->lpVtbl->put_InstructionId(This,byIns) #define ISCardCmd_get_LeField(This,plSize) (This)->lpVtbl->get_LeField(This,plSize) #define ISCardCmd_get_P1(This,pbyP1) (This)->lpVtbl->get_P1(This,pbyP1) #define ISCardCmd_put_P1(This,byP1) (This)->lpVtbl->put_P1(This,byP1) #define ISCardCmd_get_P2(This,pbyP2) (This)->lpVtbl->get_P2(This,pbyP2) #define ISCardCmd_put_P2(This,byP2) (This)->lpVtbl->put_P2(This,byP2) #define ISCardCmd_get_P3(This,pbyP3) (This)->lpVtbl->get_P3(This,pbyP3) #define ISCardCmd_get_ReplyStatus(This,pwStatus) (This)->lpVtbl->get_ReplyStatus(This,pwStatus) #define ISCardCmd_put_ReplyStatus(This,wStatus) (This)->lpVtbl->put_ReplyStatus(This,wStatus) #define ISCardCmd_get_ReplyStatusSW1(This,pbySW1) (This)->lpVtbl->get_ReplyStatusSW1(This,pbySW1) #define ISCardCmd_get_ReplyStatusSW2(This,pbySW2) (This)->lpVtbl->get_ReplyStatusSW2(This,pbySW2) #define ISCardCmd_get_Type(This,pType) (This)->lpVtbl->get_Type(This,pType) #define ISCardCmd_get_Nad(This,pbNad) (This)->lpVtbl->get_Nad(This,pbNad) #define ISCardCmd_put_Nad(This,bNad) (This)->lpVtbl->put_Nad(This,bNad) #define ISCardCmd_get_ReplyNad(This,pbNad) (This)->lpVtbl->get_ReplyNad(This,pbNad) #define ISCardCmd_put_ReplyNad(This,bNad) (This)->lpVtbl->put_ReplyNad(This,bNad) #define ISCardCmd_BuildCmd(This,byClassId,byInsId,byP1,byP2,pbyData,plLe) (This)->lpVtbl->BuildCmd(This,byClassId,byInsId,byP1,byP2,pbyData,plLe) #define ISCardCmd_Clear(This) (This)->lpVtbl->Clear(This) #define ISCardCmd_Encapsulate(This,pApdu,ApduType) (This)->lpVtbl->Encapsulate(This,pApdu,ApduType) #define ISCardCmd_get_AlternateClassId(This,pbyClass) (This)->lpVtbl->get_AlternateClassId(This,pbyClass) #define ISCardCmd_put_AlternateClassId(This,byClass) (This)->lpVtbl->put_AlternateClassId(This,byClass) #endif #endif HRESULT WINAPI ISCardCmd_get_Apdu_Proxy(ISCardCmd *This,LPBYTEBUFFER *ppApdu); void __RPC_STUB ISCardCmd_get_Apdu_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_put_Apdu_Proxy(ISCardCmd *This,LPBYTEBUFFER pApdu); void __RPC_STUB ISCardCmd_put_Apdu_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_ApduLength_Proxy(ISCardCmd *This,LONG *plSize); void __RPC_STUB ISCardCmd_get_ApduLength_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_ApduReply_Proxy(ISCardCmd *This,LPBYTEBUFFER *ppReplyApdu); void __RPC_STUB ISCardCmd_get_ApduReply_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_put_ApduReply_Proxy(ISCardCmd *This,LPBYTEBUFFER pReplyApdu); void __RPC_STUB ISCardCmd_put_ApduReply_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_ApduReplyLength_Proxy(ISCardCmd *This,LONG *plSize); void __RPC_STUB ISCardCmd_get_ApduReplyLength_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_put_ApduReplyLength_Proxy(ISCardCmd *This,LONG lSize); void __RPC_STUB ISCardCmd_put_ApduReplyLength_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_ClassId_Proxy(ISCardCmd *This,BYTE *pbyClass); void __RPC_STUB ISCardCmd_get_ClassId_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_put_ClassId_Proxy(ISCardCmd *This,BYTE byClass); void __RPC_STUB ISCardCmd_put_ClassId_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_Data_Proxy(ISCardCmd *This,LPBYTEBUFFER *ppData); void __RPC_STUB ISCardCmd_get_Data_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_put_Data_Proxy(ISCardCmd *This,LPBYTEBUFFER pData); void __RPC_STUB ISCardCmd_put_Data_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_InstructionId_Proxy(ISCardCmd *This,BYTE *pbyIns); void __RPC_STUB ISCardCmd_get_InstructionId_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_put_InstructionId_Proxy(ISCardCmd *This,BYTE byIns); void __RPC_STUB ISCardCmd_put_InstructionId_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_LeField_Proxy(ISCardCmd *This,LONG *plSize); void __RPC_STUB ISCardCmd_get_LeField_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_P1_Proxy(ISCardCmd *This,BYTE *pbyP1); void __RPC_STUB ISCardCmd_get_P1_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_put_P1_Proxy(ISCardCmd *This,BYTE byP1); void __RPC_STUB ISCardCmd_put_P1_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_P2_Proxy(ISCardCmd *This,BYTE *pbyP2); void __RPC_STUB ISCardCmd_get_P2_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_put_P2_Proxy(ISCardCmd *This,BYTE byP2); void __RPC_STUB ISCardCmd_put_P2_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_P3_Proxy(ISCardCmd *This,BYTE *pbyP3); void __RPC_STUB ISCardCmd_get_P3_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_ReplyStatus_Proxy(ISCardCmd *This,LPWORD pwStatus); void __RPC_STUB ISCardCmd_get_ReplyStatus_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_put_ReplyStatus_Proxy(ISCardCmd *This,WORD wStatus); void __RPC_STUB ISCardCmd_put_ReplyStatus_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_ReplyStatusSW1_Proxy(ISCardCmd *This,BYTE *pbySW1); void __RPC_STUB ISCardCmd_get_ReplyStatusSW1_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_ReplyStatusSW2_Proxy(ISCardCmd *This,BYTE *pbySW2); void __RPC_STUB ISCardCmd_get_ReplyStatusSW2_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_Type_Proxy(ISCardCmd *This,ISO_APDU_TYPE *pType); void __RPC_STUB ISCardCmd_get_Type_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_Nad_Proxy(ISCardCmd *This,BYTE *pbNad); void __RPC_STUB ISCardCmd_get_Nad_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_put_Nad_Proxy(ISCardCmd *This,BYTE bNad); void __RPC_STUB ISCardCmd_put_Nad_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_ReplyNad_Proxy(ISCardCmd *This,BYTE *pbNad); void __RPC_STUB ISCardCmd_get_ReplyNad_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_put_ReplyNad_Proxy(ISCardCmd *This,BYTE bNad); void __RPC_STUB ISCardCmd_put_ReplyNad_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_BuildCmd_Proxy(ISCardCmd *This,BYTE byClassId,BYTE byInsId,BYTE byP1,BYTE byP2,LPBYTEBUFFER pbyData,LONG *plLe); void __RPC_STUB ISCardCmd_BuildCmd_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_Clear_Proxy(ISCardCmd *This); void __RPC_STUB ISCardCmd_Clear_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_Encapsulate_Proxy(ISCardCmd *This,LPBYTEBUFFER pApdu,ISO_APDU_TYPE ApduType); void __RPC_STUB ISCardCmd_Encapsulate_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_get_AlternateClassId_Proxy(ISCardCmd *This,BYTE *pbyClass); void __RPC_STUB ISCardCmd_get_AlternateClassId_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardCmd_put_AlternateClassId_Proxy(ISCardCmd *This,BYTE byClass); void __RPC_STUB ISCardCmd_put_AlternateClassId_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); #endif #endif #ifndef _LPSCARDISO7816_DEFINED #define _LPSCARDISO7816_DEFINED extern RPC_IF_HANDLE __MIDL_itf_scardssp_0246_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_scardssp_0246_v0_0_s_ifspec; #ifndef __ISCardISO7816_INTERFACE_DEFINED__ #define __ISCardISO7816_INTERFACE_DEFINED__ typedef ISCardISO7816 *LPSCARDISO; typedef LPSCARDISO LPSCARDISO7816; EXTERN_C const IID IID_ISCardISO7816; #if defined(__cplusplus) && !defined(CINTERFACE) struct ISCardISO7816 : public IDispatch { public: virtual HRESULT WINAPI AppendRecord(BYTE byRefCtrl,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI EraseBinary(BYTE byP1,BYTE byP2,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI ExternalAuthenticate(BYTE byAlgorithmRef,BYTE bySecretRef,LPBYTEBUFFER pChallenge,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI GetChallenge(LONG lBytesExpected,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI GetData(BYTE byP1,BYTE byP2,LONG lBytesToGet,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI GetResponse(BYTE byP1,BYTE byP2,LONG lDataLength,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI InternalAuthenticate(BYTE byAlgorithmRef,BYTE bySecretRef,LPBYTEBUFFER pChallenge,LONG lReplyBytes,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI ManageChannel(BYTE byChannelState,BYTE byChannel,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI PutData(BYTE byP1,BYTE byP2,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI ReadBinary(BYTE byP1,BYTE byP2,LONG lBytesToRead,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI ReadRecord(BYTE byRecordId,BYTE byRefCtrl,LONG lBytesToRead,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI SelectFile(BYTE byP1,BYTE byP2,LPBYTEBUFFER pData,LONG lBytesToRead,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI SetDefaultClassId(BYTE byClass) = 0; virtual HRESULT WINAPI UpdateBinary(BYTE byP1,BYTE byP2,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI UpdateRecord(BYTE byRecordId,BYTE byRefCtrl,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI Verify(BYTE byRefCtrl,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI WriteBinary(BYTE byP1,BYTE byP2,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI WriteRecord(BYTE byRecordId,BYTE byRefCtrl,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd) = 0; }; #else typedef struct ISCardISO7816Vtbl { BEGIN_INTERFACE HRESULT (WINAPI *QueryInterface)(ISCardISO7816 *This,REFIID riid,void **ppvObject); ULONG (WINAPI *AddRef)(ISCardISO7816 *This); ULONG (WINAPI *Release)(ISCardISO7816 *This); HRESULT (WINAPI *GetTypeInfoCount)(ISCardISO7816 *This,UINT *pctinfo); HRESULT (WINAPI *GetTypeInfo)(ISCardISO7816 *This,UINT iTInfo,LCID lcid,ITypeInfo **ppTInfo); HRESULT (WINAPI *GetIDsOfNames)(ISCardISO7816 *This,REFIID riid,LPOLESTR *rgszNames,UINT cNames,LCID lcid,DISPID *rgDispId); HRESULT (WINAPI *Invoke)(ISCardISO7816 *This,DISPID dispIdMember,REFIID riid,LCID lcid,WORD wFlags,DISPPARAMS *pDispParams,VARIANT *pVarResult,EXCEPINFO *pExcepInfo,UINT *puArgErr); HRESULT (WINAPI *AppendRecord)(ISCardISO7816 *This,BYTE byRefCtrl,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); HRESULT (WINAPI *EraseBinary)(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); HRESULT (WINAPI *ExternalAuthenticate)(ISCardISO7816 *This,BYTE byAlgorithmRef,BYTE bySecretRef,LPBYTEBUFFER pChallenge,LPSCARDCMD *ppCmd); HRESULT (WINAPI *GetChallenge)(ISCardISO7816 *This,LONG lBytesExpected,LPSCARDCMD *ppCmd); HRESULT (WINAPI *GetData)(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LONG lBytesToGet,LPSCARDCMD *ppCmd); HRESULT (WINAPI *GetResponse)(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LONG lDataLength,LPSCARDCMD *ppCmd); HRESULT (WINAPI *InternalAuthenticate)(ISCardISO7816 *This,BYTE byAlgorithmRef,BYTE bySecretRef,LPBYTEBUFFER pChallenge,LONG lReplyBytes,LPSCARDCMD *ppCmd); HRESULT (WINAPI *ManageChannel)(ISCardISO7816 *This,BYTE byChannelState,BYTE byChannel,LPSCARDCMD *ppCmd); HRESULT (WINAPI *PutData)(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); HRESULT (WINAPI *ReadBinary)(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LONG lBytesToRead,LPSCARDCMD *ppCmd); HRESULT (WINAPI *ReadRecord)(ISCardISO7816 *This,BYTE byRecordId,BYTE byRefCtrl,LONG lBytesToRead,LPSCARDCMD *ppCmd); HRESULT (WINAPI *SelectFile)(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LPBYTEBUFFER pData,LONG lBytesToRead,LPSCARDCMD *ppCmd); HRESULT (WINAPI *SetDefaultClassId)(ISCardISO7816 *This,BYTE byClass); HRESULT (WINAPI *UpdateBinary)(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); HRESULT (WINAPI *UpdateRecord)(ISCardISO7816 *This,BYTE byRecordId,BYTE byRefCtrl,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); HRESULT (WINAPI *Verify)(ISCardISO7816 *This,BYTE byRefCtrl,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); HRESULT (WINAPI *WriteBinary)(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); HRESULT (WINAPI *WriteRecord)(ISCardISO7816 *This,BYTE byRecordId,BYTE byRefCtrl,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); END_INTERFACE } ISCardISO7816Vtbl; struct ISCardISO7816 { CONST_VTBL struct ISCardISO7816Vtbl *lpVtbl; }; #ifdef COBJMACROS #define ISCardISO7816_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) #define ISCardISO7816_AddRef(This) (This)->lpVtbl->AddRef(This) #define ISCardISO7816_Release(This) (This)->lpVtbl->Release(This) #define ISCardISO7816_GetTypeInfoCount(This,pctinfo) (This)->lpVtbl->GetTypeInfoCount(This,pctinfo) #define ISCardISO7816_GetTypeInfo(This,iTInfo,lcid,ppTInfo) (This)->lpVtbl->GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define ISCardISO7816_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) (This)->lpVtbl->GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define ISCardISO7816_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) (This)->lpVtbl->Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #define ISCardISO7816_AppendRecord(This,byRefCtrl,pData,ppCmd) (This)->lpVtbl->AppendRecord(This,byRefCtrl,pData,ppCmd) #define ISCardISO7816_EraseBinary(This,byP1,byP2,pData,ppCmd) (This)->lpVtbl->EraseBinary(This,byP1,byP2,pData,ppCmd) #define ISCardISO7816_ExternalAuthenticate(This,byAlgorithmRef,bySecretRef,pChallenge,ppCmd) (This)->lpVtbl->ExternalAuthenticate(This,byAlgorithmRef,bySecretRef,pChallenge,ppCmd) #define ISCardISO7816_GetChallenge(This,lBytesExpected,ppCmd) (This)->lpVtbl->GetChallenge(This,lBytesExpected,ppCmd) #define ISCardISO7816_GetData(This,byP1,byP2,lBytesToGet,ppCmd) (This)->lpVtbl->GetData(This,byP1,byP2,lBytesToGet,ppCmd) #define ISCardISO7816_GetResponse(This,byP1,byP2,lDataLength,ppCmd) (This)->lpVtbl->GetResponse(This,byP1,byP2,lDataLength,ppCmd) #define ISCardISO7816_InternalAuthenticate(This,byAlgorithmRef,bySecretRef,pChallenge,lReplyBytes,ppCmd) (This)->lpVtbl->InternalAuthenticate(This,byAlgorithmRef,bySecretRef,pChallenge,lReplyBytes,ppCmd) #define ISCardISO7816_ManageChannel(This,byChannelState,byChannel,ppCmd) (This)->lpVtbl->ManageChannel(This,byChannelState,byChannel,ppCmd) #define ISCardISO7816_PutData(This,byP1,byP2,pData,ppCmd) (This)->lpVtbl->PutData(This,byP1,byP2,pData,ppCmd) #define ISCardISO7816_ReadBinary(This,byP1,byP2,lBytesToRead,ppCmd) (This)->lpVtbl->ReadBinary(This,byP1,byP2,lBytesToRead,ppCmd) #define ISCardISO7816_ReadRecord(This,byRecordId,byRefCtrl,lBytesToRead,ppCmd) (This)->lpVtbl->ReadRecord(This,byRecordId,byRefCtrl,lBytesToRead,ppCmd) #define ISCardISO7816_SelectFile(This,byP1,byP2,pData,lBytesToRead,ppCmd) (This)->lpVtbl->SelectFile(This,byP1,byP2,pData,lBytesToRead,ppCmd) #define ISCardISO7816_SetDefaultClassId(This,byClass) (This)->lpVtbl->SetDefaultClassId(This,byClass) #define ISCardISO7816_UpdateBinary(This,byP1,byP2,pData,ppCmd) (This)->lpVtbl->UpdateBinary(This,byP1,byP2,pData,ppCmd) #define ISCardISO7816_UpdateRecord(This,byRecordId,byRefCtrl,pData,ppCmd) (This)->lpVtbl->UpdateRecord(This,byRecordId,byRefCtrl,pData,ppCmd) #define ISCardISO7816_Verify(This,byRefCtrl,pData,ppCmd) (This)->lpVtbl->Verify(This,byRefCtrl,pData,ppCmd) #define ISCardISO7816_WriteBinary(This,byP1,byP2,pData,ppCmd) (This)->lpVtbl->WriteBinary(This,byP1,byP2,pData,ppCmd) #define ISCardISO7816_WriteRecord(This,byRecordId,byRefCtrl,pData,ppCmd) (This)->lpVtbl->WriteRecord(This,byRecordId,byRefCtrl,pData,ppCmd) #endif #endif HRESULT WINAPI ISCardISO7816_AppendRecord_Proxy(ISCardISO7816 *This,BYTE byRefCtrl,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_AppendRecord_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_EraseBinary_Proxy(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_EraseBinary_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_ExternalAuthenticate_Proxy(ISCardISO7816 *This,BYTE byAlgorithmRef,BYTE bySecretRef,LPBYTEBUFFER pChallenge,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_ExternalAuthenticate_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_GetChallenge_Proxy(ISCardISO7816 *This,LONG lBytesExpected,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_GetChallenge_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_GetData_Proxy(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LONG lBytesToGet,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_GetData_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_GetResponse_Proxy(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LONG lDataLength,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_GetResponse_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_InternalAuthenticate_Proxy(ISCardISO7816 *This,BYTE byAlgorithmRef,BYTE bySecretRef,LPBYTEBUFFER pChallenge,LONG lReplyBytes,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_InternalAuthenticate_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_ManageChannel_Proxy(ISCardISO7816 *This,BYTE byChannelState,BYTE byChannel,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_ManageChannel_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_PutData_Proxy(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_PutData_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_ReadBinary_Proxy(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LONG lBytesToRead,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_ReadBinary_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_ReadRecord_Proxy(ISCardISO7816 *This,BYTE byRecordId,BYTE byRefCtrl,LONG lBytesToRead,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_ReadRecord_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_SelectFile_Proxy(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LPBYTEBUFFER pData,LONG lBytesToRead,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_SelectFile_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_SetDefaultClassId_Proxy(ISCardISO7816 *This,BYTE byClass); void __RPC_STUB ISCardISO7816_SetDefaultClassId_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_UpdateBinary_Proxy(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_UpdateBinary_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_UpdateRecord_Proxy(ISCardISO7816 *This,BYTE byRecordId,BYTE byRefCtrl,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_UpdateRecord_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_Verify_Proxy(ISCardISO7816 *This,BYTE byRefCtrl,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_Verify_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_WriteBinary_Proxy(ISCardISO7816 *This,BYTE byP1,BYTE byP2,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_WriteBinary_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardISO7816_WriteRecord_Proxy(ISCardISO7816 *This,BYTE byRecordId,BYTE byRefCtrl,LPBYTEBUFFER pData,LPSCARDCMD *ppCmd); void __RPC_STUB ISCardISO7816_WriteRecord_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); #endif #endif #ifndef _LPSCARD_DEFINED #define _LPSCARD_DEFINED extern RPC_IF_HANDLE __MIDL_itf_scardssp_0247_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_scardssp_0247_v0_0_s_ifspec; #ifndef __ISCard_INTERFACE_DEFINED__ #define __ISCard_INTERFACE_DEFINED__ typedef ISCard *LPSCARD; typedef LPSCARD LPSMARTCARD; EXTERN_C const IID IID_ISCard; #if defined(__cplusplus) && !defined(CINTERFACE) struct ISCard : public IDispatch { public: virtual HRESULT WINAPI get_Atr(LPBYTEBUFFER *ppAtr) = 0; virtual HRESULT WINAPI get_CardHandle(HSCARD *pHandle) = 0; virtual HRESULT WINAPI get_Context(HSCARDCONTEXT *pContext) = 0; virtual HRESULT WINAPI get_Protocol(SCARD_PROTOCOLS *pProtocol) = 0; virtual HRESULT WINAPI get_Status(SCARD_STATES *pStatus) = 0; virtual HRESULT WINAPI AttachByHandle(HSCARD hCard) = 0; virtual HRESULT WINAPI AttachByReader(BSTR bstrReaderName,SCARD_SHARE_MODES ShareMode = EXCLUSIVE,SCARD_PROTOCOLS PrefProtocol = T0) = 0; virtual HRESULT WINAPI Detach(SCARD_DISPOSITIONS Disposition = LEAVE) = 0; virtual HRESULT WINAPI LockSCard(void) = 0; virtual HRESULT WINAPI ReAttach(SCARD_SHARE_MODES ShareMode = EXCLUSIVE,SCARD_DISPOSITIONS InitState = LEAVE) = 0; virtual HRESULT WINAPI Transaction(LPSCARDCMD *ppCmd) = 0; virtual HRESULT WINAPI UnlockSCard(SCARD_DISPOSITIONS Disposition = LEAVE) = 0; }; #else typedef struct ISCardVtbl { BEGIN_INTERFACE HRESULT (WINAPI *QueryInterface)(ISCard *This,REFIID riid,void **ppvObject); ULONG (WINAPI *AddRef)(ISCard *This); ULONG (WINAPI *Release)(ISCard *This); HRESULT (WINAPI *GetTypeInfoCount)(ISCard *This,UINT *pctinfo); HRESULT (WINAPI *GetTypeInfo)(ISCard *This,UINT iTInfo,LCID lcid,ITypeInfo **ppTInfo); HRESULT (WINAPI *GetIDsOfNames)(ISCard *This,REFIID riid,LPOLESTR *rgszNames,UINT cNames,LCID lcid,DISPID *rgDispId); HRESULT (WINAPI *Invoke)(ISCard *This,DISPID dispIdMember,REFIID riid,LCID lcid,WORD wFlags,DISPPARAMS *pDispParams,VARIANT *pVarResult,EXCEPINFO *pExcepInfo,UINT *puArgErr); HRESULT (WINAPI *get_Atr)(ISCard *This,LPBYTEBUFFER *ppAtr); HRESULT (WINAPI *get_CardHandle)(ISCard *This,HSCARD *pHandle); HRESULT (WINAPI *get_Context)(ISCard *This,HSCARDCONTEXT *pContext); HRESULT (WINAPI *get_Protocol)(ISCard *This,SCARD_PROTOCOLS *pProtocol); HRESULT (WINAPI *get_Status)(ISCard *This,SCARD_STATES *pStatus); HRESULT (WINAPI *AttachByHandle)(ISCard *This,HSCARD hCard); HRESULT (WINAPI *AttachByReader)(ISCard *This,BSTR bstrReaderName,SCARD_SHARE_MODES ShareMode,SCARD_PROTOCOLS PrefProtocol); HRESULT (WINAPI *Detach)(ISCard *This,SCARD_DISPOSITIONS Disposition); HRESULT (WINAPI *LockSCard)(ISCard *This); HRESULT (WINAPI *ReAttach)(ISCard *This,SCARD_SHARE_MODES ShareMode,SCARD_DISPOSITIONS InitState); HRESULT (WINAPI *Transaction)(ISCard *This,LPSCARDCMD *ppCmd); HRESULT (WINAPI *UnlockSCard)(ISCard *This,SCARD_DISPOSITIONS Disposition); END_INTERFACE } ISCardVtbl; struct ISCard { CONST_VTBL struct ISCardVtbl *lpVtbl; }; #ifdef COBJMACROS #define ISCard_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) #define ISCard_AddRef(This) (This)->lpVtbl->AddRef(This) #define ISCard_Release(This) (This)->lpVtbl->Release(This) #define ISCard_GetTypeInfoCount(This,pctinfo) (This)->lpVtbl->GetTypeInfoCount(This,pctinfo) #define ISCard_GetTypeInfo(This,iTInfo,lcid,ppTInfo) (This)->lpVtbl->GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define ISCard_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) (This)->lpVtbl->GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define ISCard_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) (This)->lpVtbl->Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #define ISCard_get_Atr(This,ppAtr) (This)->lpVtbl->get_Atr(This,ppAtr) #define ISCard_get_CardHandle(This,pHandle) (This)->lpVtbl->get_CardHandle(This,pHandle) #define ISCard_get_Context(This,pContext) (This)->lpVtbl->get_Context(This,pContext) #define ISCard_get_Protocol(This,pProtocol) (This)->lpVtbl->get_Protocol(This,pProtocol) #define ISCard_get_Status(This,pStatus) (This)->lpVtbl->get_Status(This,pStatus) #define ISCard_AttachByHandle(This,hCard) (This)->lpVtbl->AttachByHandle(This,hCard) #define ISCard_AttachByReader(This,bstrReaderName,ShareMode,PrefProtocol) (This)->lpVtbl->AttachByReader(This,bstrReaderName,ShareMode,PrefProtocol) #define ISCard_Detach(This,Disposition) (This)->lpVtbl->Detach(This,Disposition) #define ISCard_LockSCard(This) (This)->lpVtbl->LockSCard(This) #define ISCard_ReAttach(This,ShareMode,InitState) (This)->lpVtbl->ReAttach(This,ShareMode,InitState) #define ISCard_Transaction(This,ppCmd) (This)->lpVtbl->Transaction(This,ppCmd) #define ISCard_UnlockSCard(This,Disposition) (This)->lpVtbl->UnlockSCard(This,Disposition) #endif #endif HRESULT WINAPI ISCard_get_Atr_Proxy(ISCard *This,LPBYTEBUFFER *ppAtr); void __RPC_STUB ISCard_get_Atr_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCard_get_CardHandle_Proxy(ISCard *This,HSCARD *pHandle); void __RPC_STUB ISCard_get_CardHandle_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCard_get_Context_Proxy(ISCard *This,HSCARDCONTEXT *pContext); void __RPC_STUB ISCard_get_Context_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCard_get_Protocol_Proxy(ISCard *This,SCARD_PROTOCOLS *pProtocol); void __RPC_STUB ISCard_get_Protocol_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCard_get_Status_Proxy(ISCard *This,SCARD_STATES *pStatus); void __RPC_STUB ISCard_get_Status_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCard_AttachByHandle_Proxy(ISCard *This,HSCARD hCard); void __RPC_STUB ISCard_AttachByHandle_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCard_AttachByReader_Proxy(ISCard *This,BSTR bstrReaderName,SCARD_SHARE_MODES ShareMode,SCARD_PROTOCOLS PrefProtocol); void __RPC_STUB ISCard_AttachByReader_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCard_Detach_Proxy(ISCard *This,SCARD_DISPOSITIONS Disposition); void __RPC_STUB ISCard_Detach_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCard_LockSCard_Proxy(ISCard *This); void __RPC_STUB ISCard_LockSCard_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCard_ReAttach_Proxy(ISCard *This,SCARD_SHARE_MODES ShareMode,SCARD_DISPOSITIONS InitState); void __RPC_STUB ISCard_ReAttach_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCard_Transaction_Proxy(ISCard *This,LPSCARDCMD *ppCmd); void __RPC_STUB ISCard_Transaction_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCard_UnlockSCard_Proxy(ISCard *This,SCARD_DISPOSITIONS Disposition); void __RPC_STUB ISCard_UnlockSCard_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); #endif #endif #ifndef _LPSCARDDATABASE_DEFINED #define _LPSCARDDATABASE_DEFINED extern RPC_IF_HANDLE __MIDL_itf_scardssp_0248_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_scardssp_0248_v0_0_s_ifspec; #ifndef __ISCardDatabase_INTERFACE_DEFINED__ #define __ISCardDatabase_INTERFACE_DEFINED__ typedef ISCardDatabase *LPSCARDDATABASE; EXTERN_C const IID IID_ISCardDatabase; #if defined(__cplusplus) && !defined(CINTERFACE) struct ISCardDatabase : public IDispatch { public: virtual HRESULT WINAPI GetProviderCardId(BSTR bstrCardName,LPGUID *ppguidProviderId) = 0; virtual HRESULT WINAPI ListCardInterfaces(BSTR bstrCardName,LPSAFEARRAY *ppInterfaceGuids) = 0; virtual HRESULT WINAPI ListCards(LPBYTEBUFFER pAtr,LPSAFEARRAY pInterfaceGuids,__LONG32 localeId,LPSAFEARRAY *ppCardNames) = 0; virtual HRESULT WINAPI ListReaderGroups(__LONG32 localeId,LPSAFEARRAY *ppReaderGroups) = 0; virtual HRESULT WINAPI ListReaders(__LONG32 localeId,LPSAFEARRAY *ppReaders) = 0; }; #else typedef struct ISCardDatabaseVtbl { BEGIN_INTERFACE HRESULT (WINAPI *QueryInterface)(ISCardDatabase *This,REFIID riid,void **ppvObject); ULONG (WINAPI *AddRef)(ISCardDatabase *This); ULONG (WINAPI *Release)(ISCardDatabase *This); HRESULT (WINAPI *GetTypeInfoCount)(ISCardDatabase *This,UINT *pctinfo); HRESULT (WINAPI *GetTypeInfo)(ISCardDatabase *This,UINT iTInfo,LCID lcid,ITypeInfo **ppTInfo); HRESULT (WINAPI *GetIDsOfNames)(ISCardDatabase *This,REFIID riid,LPOLESTR *rgszNames,UINT cNames,LCID lcid,DISPID *rgDispId); HRESULT (WINAPI *Invoke)(ISCardDatabase *This,DISPID dispIdMember,REFIID riid,LCID lcid,WORD wFlags,DISPPARAMS *pDispParams,VARIANT *pVarResult,EXCEPINFO *pExcepInfo,UINT *puArgErr); HRESULT (WINAPI *GetProviderCardId)(ISCardDatabase *This,BSTR bstrCardName,LPGUID *ppguidProviderId); HRESULT (WINAPI *ListCardInterfaces)(ISCardDatabase *This,BSTR bstrCardName,LPSAFEARRAY *ppInterfaceGuids); HRESULT (WINAPI *ListCards)(ISCardDatabase *This,LPBYTEBUFFER pAtr,LPSAFEARRAY pInterfaceGuids,__LONG32 localeId,LPSAFEARRAY *ppCardNames); HRESULT (WINAPI *ListReaderGroups)(ISCardDatabase *This,__LONG32 localeId,LPSAFEARRAY *ppReaderGroups); HRESULT (WINAPI *ListReaders)(ISCardDatabase *This,__LONG32 localeId,LPSAFEARRAY *ppReaders); END_INTERFACE } ISCardDatabaseVtbl; struct ISCardDatabase { CONST_VTBL struct ISCardDatabaseVtbl *lpVtbl; }; #ifdef COBJMACROS #define ISCardDatabase_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) #define ISCardDatabase_AddRef(This) (This)->lpVtbl->AddRef(This) #define ISCardDatabase_Release(This) (This)->lpVtbl->Release(This) #define ISCardDatabase_GetTypeInfoCount(This,pctinfo) (This)->lpVtbl->GetTypeInfoCount(This,pctinfo) #define ISCardDatabase_GetTypeInfo(This,iTInfo,lcid,ppTInfo) (This)->lpVtbl->GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define ISCardDatabase_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) (This)->lpVtbl->GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define ISCardDatabase_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) (This)->lpVtbl->Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #define ISCardDatabase_GetProviderCardId(This,bstrCardName,ppguidProviderId) (This)->lpVtbl->GetProviderCardId(This,bstrCardName,ppguidProviderId) #define ISCardDatabase_ListCardInterfaces(This,bstrCardName,ppInterfaceGuids) (This)->lpVtbl->ListCardInterfaces(This,bstrCardName,ppInterfaceGuids) #define ISCardDatabase_ListCards(This,pAtr,pInterfaceGuids,localeId,ppCardNames) (This)->lpVtbl->ListCards(This,pAtr,pInterfaceGuids,localeId,ppCardNames) #define ISCardDatabase_ListReaderGroups(This,localeId,ppReaderGroups) (This)->lpVtbl->ListReaderGroups(This,localeId,ppReaderGroups) #define ISCardDatabase_ListReaders(This,localeId,ppReaders) (This)->lpVtbl->ListReaders(This,localeId,ppReaders) #endif #endif HRESULT WINAPI ISCardDatabase_GetProviderCardId_Proxy(ISCardDatabase *This,BSTR bstrCardName,LPGUID *ppguidProviderId); void __RPC_STUB ISCardDatabase_GetProviderCardId_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardDatabase_ListCardInterfaces_Proxy(ISCardDatabase *This,BSTR bstrCardName,LPSAFEARRAY *ppInterfaceGuids); void __RPC_STUB ISCardDatabase_ListCardInterfaces_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardDatabase_ListCards_Proxy(ISCardDatabase *This,LPBYTEBUFFER pAtr,LPSAFEARRAY pInterfaceGuids,__LONG32 localeId,LPSAFEARRAY *ppCardNames); void __RPC_STUB ISCardDatabase_ListCards_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardDatabase_ListReaderGroups_Proxy(ISCardDatabase *This,__LONG32 localeId,LPSAFEARRAY *ppReaderGroups); void __RPC_STUB ISCardDatabase_ListReaderGroups_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardDatabase_ListReaders_Proxy(ISCardDatabase *This,__LONG32 localeId,LPSAFEARRAY *ppReaders); void __RPC_STUB ISCardDatabase_ListReaders_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); #endif #endif #ifndef _LPSCARDLOCATE_DEFINED #define _LPSCARDLOCATE_DEFINED extern RPC_IF_HANDLE __MIDL_itf_scardssp_0249_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_scardssp_0249_v0_0_s_ifspec; #ifndef __ISCardLocate_INTERFACE_DEFINED__ #define __ISCardLocate_INTERFACE_DEFINED__ typedef ISCardLocate *LPSCARDLOCATE; typedef LPSCARDLOCATE LPSCARDLOC; EXTERN_C const IID IID_ISCardLocate; #if defined(__cplusplus) && !defined(CINTERFACE) struct ISCardLocate : public IDispatch { public: virtual HRESULT WINAPI ConfigureCardGuidSearch(LPSAFEARRAY pCardGuids,LPSAFEARRAY pGroupNames = 0,BSTR bstrTitle = L"",LONG lFlags = 1) = 0; virtual HRESULT WINAPI ConfigureCardNameSearch(LPSAFEARRAY pCardNames,LPSAFEARRAY pGroupNames = 0,BSTR bstrTitle = L"",LONG lFlags = 1) = 0; virtual HRESULT WINAPI FindCard(SCARD_SHARE_MODES ShareMode,SCARD_PROTOCOLS Protocols,LONG lFlags,LPSCARDINFO *ppCardInfo) = 0; }; #else typedef struct ISCardLocateVtbl { BEGIN_INTERFACE HRESULT (WINAPI *QueryInterface)(ISCardLocate *This,REFIID riid,void **ppvObject); ULONG (WINAPI *AddRef)(ISCardLocate *This); ULONG (WINAPI *Release)(ISCardLocate *This); HRESULT (WINAPI *GetTypeInfoCount)(ISCardLocate *This,UINT *pctinfo); HRESULT (WINAPI *GetTypeInfo)(ISCardLocate *This,UINT iTInfo,LCID lcid,ITypeInfo **ppTInfo); HRESULT (WINAPI *GetIDsOfNames)(ISCardLocate *This,REFIID riid,LPOLESTR *rgszNames,UINT cNames,LCID lcid,DISPID *rgDispId); HRESULT (WINAPI *Invoke)(ISCardLocate *This,DISPID dispIdMember,REFIID riid,LCID lcid,WORD wFlags,DISPPARAMS *pDispParams,VARIANT *pVarResult,EXCEPINFO *pExcepInfo,UINT *puArgErr); HRESULT (WINAPI *ConfigureCardGuidSearch)(ISCardLocate *This,LPSAFEARRAY pCardGuids,LPSAFEARRAY pGroupNames,BSTR bstrTitle,LONG lFlags); HRESULT (WINAPI *ConfigureCardNameSearch)(ISCardLocate *This,LPSAFEARRAY pCardNames,LPSAFEARRAY pGroupNames,BSTR bstrTitle,LONG lFlags); HRESULT (WINAPI *FindCard)(ISCardLocate *This,SCARD_SHARE_MODES ShareMode,SCARD_PROTOCOLS Protocols,LONG lFlags,LPSCARDINFO *ppCardInfo); END_INTERFACE } ISCardLocateVtbl; struct ISCardLocate { CONST_VTBL struct ISCardLocateVtbl *lpVtbl; }; #ifdef COBJMACROS #define ISCardLocate_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) #define ISCardLocate_AddRef(This) (This)->lpVtbl->AddRef(This) #define ISCardLocate_Release(This) (This)->lpVtbl->Release(This) #define ISCardLocate_GetTypeInfoCount(This,pctinfo) (This)->lpVtbl->GetTypeInfoCount(This,pctinfo) #define ISCardLocate_GetTypeInfo(This,iTInfo,lcid,ppTInfo) (This)->lpVtbl->GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define ISCardLocate_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) (This)->lpVtbl->GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define ISCardLocate_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) (This)->lpVtbl->Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #define ISCardLocate_ConfigureCardGuidSearch(This,pCardGuids,pGroupNames,bstrTitle,lFlags) (This)->lpVtbl->ConfigureCardGuidSearch(This,pCardGuids,pGroupNames,bstrTitle,lFlags) #define ISCardLocate_ConfigureCardNameSearch(This,pCardNames,pGroupNames,bstrTitle,lFlags) (This)->lpVtbl->ConfigureCardNameSearch(This,pCardNames,pGroupNames,bstrTitle,lFlags) #define ISCardLocate_FindCard(This,ShareMode,Protocols,lFlags,ppCardInfo) (This)->lpVtbl->FindCard(This,ShareMode,Protocols,lFlags,ppCardInfo) #endif #endif HRESULT WINAPI ISCardLocate_ConfigureCardGuidSearch_Proxy(ISCardLocate *This,LPSAFEARRAY pCardGuids,LPSAFEARRAY pGroupNames,BSTR bstrTitle,LONG lFlags); void __RPC_STUB ISCardLocate_ConfigureCardGuidSearch_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardLocate_ConfigureCardNameSearch_Proxy(ISCardLocate *This,LPSAFEARRAY pCardNames,LPSAFEARRAY pGroupNames,BSTR bstrTitle,LONG lFlags); void __RPC_STUB ISCardLocate_ConfigureCardNameSearch_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); HRESULT WINAPI ISCardLocate_FindCard_Proxy(ISCardLocate *This,SCARD_SHARE_MODES ShareMode,SCARD_PROTOCOLS Protocols,LONG lFlags,LPSCARDINFO *ppCardInfo); void __RPC_STUB ISCardLocate_FindCard_Stub(IRpcStubBuffer *This,IRpcChannelBuffer *_pRpcChannelBuffer,PRPC_MESSAGE _pRpcMessage,DWORD *_pdwStubPhase); #endif #endif extern RPC_IF_HANDLE __MIDL_itf_scardssp_0250_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_scardssp_0250_v0_0_s_ifspec; #ifndef __SCARDSSPLib_LIBRARY_DEFINED__ #define __SCARDSSPLib_LIBRARY_DEFINED__ EXTERN_C const IID LIBID_SCARDSSPLib; EXTERN_C const CLSID CLSID_CByteBuffer; #ifdef __cplusplus class CByteBuffer; #endif EXTERN_C const CLSID CLSID_CSCardTypeConv; #ifdef __cplusplus class CSCardTypeConv; #endif EXTERN_C const CLSID CLSID_CSCardCmd; #ifdef __cplusplus class CSCardCmd; #endif EXTERN_C const CLSID CLSID_CSCardISO7816; #ifdef __cplusplus class CSCardISO7816; #endif EXTERN_C const CLSID CLSID_CSCard; #ifdef __cplusplus class CSCard; #endif EXTERN_C const CLSID CLSID_CSCardDatabase; #ifdef __cplusplus class CSCardDatabase; #endif EXTERN_C const CLSID CLSID_CSCardLocate; #ifdef __cplusplus class CSCardLocate; #endif #endif ULONG __RPC_API BSTR_UserSize(ULONG *,ULONG,BSTR *); unsigned char *__RPC_API BSTR_UserMarshal(ULONG *,unsigned char *,BSTR *); unsigned char *__RPC_API BSTR_UserUnmarshal(ULONG *,unsigned char *,BSTR *); void __RPC_API BSTR_UserFree(ULONG *,BSTR *); ULONG __RPC_API HGLOBAL_UserSize(ULONG *,ULONG,HGLOBAL *); unsigned char *__RPC_API HGLOBAL_UserMarshal(ULONG *,unsigned char *,HGLOBAL *); unsigned char *__RPC_API HGLOBAL_UserUnmarshal(ULONG *,unsigned char *,HGLOBAL *); void __RPC_API HGLOBAL_UserFree(ULONG *,HGLOBAL *); ULONG __RPC_API LPSAFEARRAY_UserSize(ULONG *,ULONG,LPSAFEARRAY *); unsigned char *__RPC_API LPSAFEARRAY_UserMarshal(ULONG *,unsigned char *,LPSAFEARRAY *); unsigned char *__RPC_API LPSAFEARRAY_UserUnmarshal(ULONG *,unsigned char *,LPSAFEARRAY *); void __RPC_API LPSAFEARRAY_UserFree(ULONG *,LPSAFEARRAY *); #ifdef __cplusplus } #endif #endif
{ "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. */ export { discriminators, AadAuthenticationParameters, AddressSpace, ApplicationGateway, ApplicationGatewayAuthenticationCertificate, ApplicationGatewayAutoscaleConfiguration, ApplicationGatewayAvailableSslOptions, ApplicationGatewayBackendAddress, ApplicationGatewayBackendAddressPool, ApplicationGatewayBackendHttpSettings, ApplicationGatewayClientAuthConfiguration, ApplicationGatewayConnectionDraining, ApplicationGatewayCustomError, ApplicationGatewayFirewallDisabledRuleGroup, ApplicationGatewayFirewallExclusion, ApplicationGatewayFirewallRule, ApplicationGatewayFirewallRuleGroup, ApplicationGatewayFirewallRuleSet, ApplicationGatewayFrontendIPConfiguration, ApplicationGatewayFrontendPort, ApplicationGatewayHeaderConfiguration, ApplicationGatewayHttpListener, ApplicationGatewayIPConfiguration, ApplicationGatewayPathRule, ApplicationGatewayPrivateEndpointConnection, ApplicationGatewayPrivateLinkConfiguration, ApplicationGatewayPrivateLinkIpConfiguration, ApplicationGatewayPrivateLinkResource, ApplicationGatewayProbe, ApplicationGatewayProbeHealthResponseMatch, ApplicationGatewayRedirectConfiguration, ApplicationGatewayRequestRoutingRule, ApplicationGatewayRewriteRule, ApplicationGatewayRewriteRuleActionSet, ApplicationGatewayRewriteRuleCondition, ApplicationGatewayRewriteRuleSet, ApplicationGatewaySku, ApplicationGatewaySslCertificate, ApplicationGatewaySslPolicy, ApplicationGatewaySslPredefinedPolicy, ApplicationGatewaySslProfile, ApplicationGatewayTrustedClientCertificate, ApplicationGatewayTrustedRootCertificate, ApplicationGatewayUrlConfiguration, ApplicationGatewayUrlPathMap, ApplicationGatewayWebApplicationFirewallConfiguration, ApplicationRule, ApplicationSecurityGroup, AzureFirewall, AzureFirewallApplicationRule, AzureFirewallApplicationRuleCollection, AzureFirewallApplicationRuleProtocol, AzureFirewallFqdnTag, AzureFirewallIPConfiguration, AzureFirewallIpGroups, AzureFirewallNatRCAction, AzureFirewallNatRule, AzureFirewallNatRuleCollection, AzureFirewallNetworkRule, AzureFirewallNetworkRuleCollection, AzureFirewallPublicIPAddress, AzureFirewallRCAction, AzureFirewallSku, BackendAddressPool, BaseResource, BastionHost, BastionHostIPConfiguration, BGPCommunity, BgpConnection, BgpServiceCommunity, BgpSettings, BreakOutCategoryPolicies, CloudError, ConnectionMonitorDestination, ConnectionMonitorEndpoint, ConnectionMonitorEndpointFilter, ConnectionMonitorEndpointFilterItem, ConnectionMonitorEndpointScope, ConnectionMonitorEndpointScopeItem, ConnectionMonitorHttpConfiguration, ConnectionMonitorIcmpConfiguration, ConnectionMonitorOutput, ConnectionMonitorResult, ConnectionMonitorSource, ConnectionMonitorSuccessThreshold, ConnectionMonitorTcpConfiguration, ConnectionMonitorTestConfiguration, ConnectionMonitorTestGroup, ConnectionMonitorWorkspaceSettings, ConnectionSharedKey, Container, ContainerNetworkInterface, ContainerNetworkInterfaceConfiguration, ContainerNetworkInterfaceIpConfiguration, CustomDnsConfigPropertiesFormat, CustomIpPrefix, DdosCustomPolicy, DdosProtectionPlan, DdosSettings, Delegation, DeviceProperties, DhcpOptions, DnsSettings, DscpConfiguration, EndpointServiceResult, ExpressRouteCircuit, ExpressRouteCircuitAuthorization, ExpressRouteCircuitConnection, ExpressRouteCircuitPeering, ExpressRouteCircuitPeeringConfig, ExpressRouteCircuitPeeringId, ExpressRouteCircuitReference, ExpressRouteCircuitServiceProviderProperties, ExpressRouteCircuitSku, ExpressRouteCircuitStats, ExpressRouteConnection, ExpressRouteConnectionId, ExpressRouteCrossConnection, ExpressRouteCrossConnectionPeering, ExpressRouteGateway, ExpressRouteGatewayPropertiesAutoScaleConfiguration, ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds, ExpressRouteLink, ExpressRouteLinkMacSecConfig, ExpressRoutePort, ExpressRoutePortsLocation, ExpressRoutePortsLocationBandwidths, ExpressRouteServiceProvider, ExpressRouteServiceProviderBandwidthsOffered, FirewallPolicy, FirewallPolicyFilterRuleCollection, FirewallPolicyFilterRuleCollectionAction, FirewallPolicyNatRuleCollection, FirewallPolicyNatRuleCollectionAction, FirewallPolicyRule, FirewallPolicyRuleApplicationProtocol, FirewallPolicyRuleCollection, FirewallPolicyRuleCollectionGroup, FirewallPolicyThreatIntelWhitelist, FlowLog, FlowLogFormatParameters, FrontendIPConfiguration, HTTPHeader, HubIPAddresses, HubIpConfiguration, HubPublicIPAddresses, HubRoute, HubRouteTable, HubVirtualNetworkConnection, InboundNatPool, InboundNatRule, InboundSecurityRule, InboundSecurityRules, IpAllocation, IPConfiguration, IPConfigurationBgpPeeringAddress, IPConfigurationProfile, IpGroup, IpsecPolicy, IpTag, Ipv6CircuitConnectionConfig, Ipv6ExpressRouteCircuitPeeringConfig, LoadBalancer, LoadBalancerBackendAddress, LoadBalancerSku, LoadBalancingRule, LocalNetworkGateway, ManagedRuleGroupOverride, ManagedRuleOverride, ManagedRulesDefinition, ManagedRuleSet, ManagedServiceIdentity, ManagedServiceIdentityUserAssignedIdentitiesValue, MatchCondition, MatchVariable, NatGateway, NatGatewaySku, NatRule, NetworkIntentPolicy, NetworkInterface, NetworkInterfaceDnsSettings, NetworkInterfaceIPConfiguration, NetworkInterfaceIPConfigurationPrivateLinkConnectionProperties, NetworkInterfaceTapConfiguration, NetworkProfile, NetworkRule, NetworkSecurityGroup, NetworkVirtualAppliance, NetworkVirtualApplianceSku, NetworkVirtualApplianceSkuInstances, NetworkWatcher, O365BreakOutCategoryPolicies, O365PolicyProperties, Office365PolicyProperties, OutboundRule, OwaspCrsExclusionEntry, P2SConnectionConfiguration, P2SVpnGateway, PatchRouteFilter, PatchRouteFilterRule, PeerExpressRouteCircuitConnection, PolicySettings, PrivateDnsZoneConfig, PrivateDnsZoneGroup, PrivateEndpoint, PrivateEndpointConnection, PrivateLinkService, PrivateLinkServiceConnection, PrivateLinkServiceConnectionState, PrivateLinkServiceIpConfiguration, PrivateLinkServicePropertiesAutoApproval, PrivateLinkServicePropertiesVisibility, Probe, PropagatedRouteTable, ProtocolCustomSettingsFormat, PublicIPAddress, PublicIPAddressDnsSettings, PublicIPAddressSku, PublicIPPrefix, PublicIPPrefixSku, QosIpRange, QosPortRange, RadiusServer, RecordSet, ReferencedPublicIpAddress, Resource, ResourceNavigationLink, ResourceSet, RetentionPolicyParameters, Route, RouteFilter, RouteFilterRule, RouteTable, RoutingConfiguration, SecurityPartnerProvider, SecurityRule, ServiceAssociationLink, ServiceEndpointPolicy, ServiceEndpointPolicyDefinition, ServiceEndpointPropertiesFormat, StaticRoute, Subnet, SubResource, TrafficAnalyticsConfigurationProperties, TrafficAnalyticsProperties, TrafficSelectorPolicy, TunnelConnectionHealth, VirtualApplianceNicProperties, VirtualApplianceSite, VirtualApplianceSkuProperties, VirtualHub, VirtualHubId, VirtualHubRoute, VirtualHubRouteTable, VirtualHubRouteTableV2, VirtualHubRouteV2, VirtualNetwork, VirtualNetworkBgpCommunities, VirtualNetworkConnectionGatewayReference, VirtualNetworkGateway, VirtualNetworkGatewayConnection, VirtualNetworkGatewayConnectionListEntity, VirtualNetworkGatewayIPConfiguration, VirtualNetworkGatewaySku, VirtualNetworkPeering, VirtualNetworkTap, VirtualRouter, VirtualRouterPeering, VirtualWAN, VM, VnetRoute, VpnClientConfiguration, VpnClientConnectionHealth, VpnClientRevokedCertificate, VpnClientRootCertificate, VpnConnection, VpnGateway, VpnGatewayIpConfiguration, VpnLinkBgpSettings, VpnLinkProviderProperties, VpnServerConfigRadiusClientRootCertificate, VpnServerConfigRadiusServerRootCertificate, VpnServerConfiguration, VpnServerConfigVpnClientRevokedCertificate, VpnServerConfigVpnClientRootCertificate, VpnSite, VpnSiteLink, VpnSiteLinkConnection, WebApplicationFirewallCustomRule, WebApplicationFirewallPolicy } from "../models/mappers";
{ "pile_set_name": "Github" }