code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
/*
* Copyright 2012-2017 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.springframework.boot.autoconfigure.web;
import org.springframework.beans.factory.annotation.Value;
/**
* Configuration properties for web error handling.
*
* @author Michael Stummvoll
* @author Stephane Nicoll
* @author Vedran Pavic
* @since 1.3.0
*/
public class ErrorProperties {
/**
* Path of the error controller.
*/
@Value("${error.path:/error}")
private String path = "/error";
/**
* Include the "exception" attribute.
*/
private boolean includeException;
/**
* When to include a "stacktrace" attribute.
*/
private IncludeStacktrace includeStacktrace = IncludeStacktrace.NEVER;
public String getPath() {
return this.path;
}
public void setPath(String path) {
this.path = path;
}
public boolean isIncludeException() {
return this.includeException;
}
public void setIncludeException(boolean includeException) {
this.includeException = includeException;
}
public IncludeStacktrace getIncludeStacktrace() {
return this.includeStacktrace;
}
public void setIncludeStacktrace(IncludeStacktrace includeStacktrace) {
this.includeStacktrace = includeStacktrace;
}
/**
* Include Stacktrace attribute options.
*/
public enum IncludeStacktrace {
/**
* Never add stacktrace information.
*/
NEVER,
/**
* Always add stacktrace information.
*/
ALWAYS,
/**
* Add stacktrace information when the "trace" request parameter is "true".
*/
ON_TRACE_PARAM
}
}
| bbrouwer/spring-boot | spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ErrorProperties.java | Java | apache-2.0 | 2,080 |
using NUnit.Framework;
using Nest.Tests.MockData.Domain;
namespace Nest.Tests.Unit.Search.Query.Singles
{
[TestFixture]
public class ConditionlessQueryJson
{
[Test]
public void FallbackTerm()
{
var s = new SearchDescriptor<ElasticsearchProject>().From(0).Size(10)
.Query(q=>q
.Conditionless(qs=>qs
.Query(qcq=>qcq.Term("this_term_is_conditionless", ""))
.Fallback(qcf=>qcf.Term("name", "do_me_instead")
)
)
);
var json = TestElasticClient.Serialize(s);
var expected = @"{ from: 0, size: 10,
query : {
term : {
name : { value : ""do_me_instead"" }
}
}
}";
Assert.True(json.JsonEquals(expected), json);
}
[Test]
public void FallbackMatch()
{
var s = new SearchDescriptor<ElasticsearchProject>().From(0).Size(10)
.Query(q => q
.Conditionless(qs => qs
.Query(qcq => qcq
.Match(m => m
.OnField(p => p.Name)
.Query("")
)
)
.Fallback(qcf=>qcf
.Match(m => m
.OnField(p => p.Name)
.Query("do_me_instead")
)
)
)
);
var json = TestElasticClient.Serialize(s);
var expected = @"{ from: 0, size: 10,
query : {
match : {
name : {
query: ""do_me_instead""
}
}
}
}";
Assert.True(json.JsonEquals(expected), json);
}
[Test]
public void UseQuery()
{
var s = new SearchDescriptor<ElasticsearchProject>().From(0).Size(10)
.Query(q => q
.Conditionless(qs => qs
.Query(qcq => qcq.Term("name", "NEST"))
.Fallback(qcf => qcf.Term("name", "do_me_instead")
)
)
);
var json = TestElasticClient.Serialize(s);
var expected = @"{ from: 0, size: 10,
query : {
term : {
name : { value : ""NEST"" }
}
}
}";
Assert.True(json.JsonEquals(expected), json);
}
[Test]
public void BothConditionless()
{
var s = new SearchDescriptor<ElasticsearchProject>().From(0).Size(10)
.Query(q => q
.Conditionless(qs => qs
.Query(qcq => qcq.Term("name", ""))
.Fallback(qcf => qcf.Term("name", "")
)
)
);
var json = TestElasticClient.Serialize(s);
var expected = @"{ from: 0, size: 10 }";
Assert.True(json.JsonEquals(expected), json);
}
}
}
| joehmchan/elasticsearch-net | src/Tests/Nest.Tests.Unit/Search/Query/Modes/ConditionlessQueryJson.cs | C# | apache-2.0 | 2,302 |
require "formula"
class Xplanetfx < Formula
desc "Configure, run or daemonize xplanet for HQ Earth wallpapers"
homepage "http://mein-neues-blog.de/xplanetFX/"
url "http://repository.mein-neues-blog.de:9000/archive/xplanetfx-2.6.6_all.tar.gz"
sha256 "59c49af68b6cafcbe4ebfd65979181a7f1e4416e024505b5b0d46f1cc04b082a"
version "2.6.6"
bottle do
cellar :any
sha256 "ec54be513691a25a873f0f59da03a20843670885bac4c2626a526a5e57c2e501" => :yosemite
sha256 "61be399a9f715a4541592e819963d24d41d739b9f57a6fc5f012fc4802627dda" => :mavericks
sha256 "37b09a20a17d6e713a662a83c5e17c782a25af167b0b2ac161c48b0bd3b1b9e0" => :mountain_lion
end
option "without-gui", "Build to run xplanetFX from the command-line only"
option "with-gnu-sed", "Build to use GNU sed instead of OS X sed"
depends_on "xplanet"
depends_on "imagemagick"
depends_on "wget"
depends_on "coreutils"
depends_on "gnu-sed" => :optional
if build.with? "gui"
depends_on "librsvg"
depends_on "pygtk" => "with-libglade"
end
skip_clean "share/xplanetFX"
def install
inreplace "bin/xplanetFX", "WORKDIR=/usr/share/xplanetFX", "WORKDIR=#{HOMEBREW_PREFIX}/share/xplanetFX"
prefix.install "bin", "share"
path = "#{Formula["coreutils"].opt_libexec}/gnubin"
path += ":#{Formula["gnu-sed"].opt_libexec}/gnubin" if build.with?("gnu-sed")
if build.with?("gui")
ENV.prepend_create_path "PYTHONPATH", "#{HOMEBREW_PREFIX}/lib/python2.7/site-packages/gtk-2.0"
ENV.prepend_create_path "GDK_PIXBUF_MODULEDIR", "#{HOMEBREW_PREFIX}/lib/gdk-pixbuf-2.0/2.10.0/loaders"
end
bin.env_script_all_files(libexec+'bin', :PATH => "#{path}:$PATH", :PYTHONPATH => ENV["PYTHONPATH"], :GDK_PIXBUF_MODULEDIR => ENV["GDK_PIXBUF_MODULEDIR"])
end
def post_install
if build.with?("gui")
# Change the version directory below with any future update
ENV["GDK_PIXBUF_MODULEDIR"]="#{HOMEBREW_PREFIX}/lib/gdk-pixbuf-2.0/2.10.0/loaders"
system "#{HOMEBREW_PREFIX}/bin/gdk-pixbuf-query-loaders", "--update-cache"
end
end
end
| karlhigley/homebrew | Library/Formula/xplanetfx.rb | Ruby | bsd-2-clause | 2,068 |
#
# OpenSSL/crypto/rc4/Makefile
#
DIR= rc4
TOP= ../..
CC= cc
CPP= $(CC) -E
INCLUDES=
CFLAG=-g
AR= ar r
RC4_ENC=rc4_enc.o rc4_skey.o
CFLAGS= $(INCLUDES) $(CFLAG)
ASFLAGS= $(INCLUDES) $(ASFLAG)
AFLAGS= $(ASFLAGS)
GENERAL=Makefile
TEST=rc4test.c
APPS=
LIB=$(TOP)/libcrypto.a
LIBSRC=rc4_skey.c rc4_enc.c rc4_utl.c
LIBOBJ=$(RC4_ENC) rc4_utl.o
SRC= $(LIBSRC)
EXHEADER= rc4.h
HEADER= $(EXHEADER) rc4_locl.h
ALL= $(GENERAL) $(SRC) $(HEADER)
top:
(cd ../..; $(MAKE) DIRS=crypto SDIRS=$(DIR) sub_all)
all: lib
lib: $(LIBOBJ)
$(AR) $(LIB) $(LIBOBJ)
$(RANLIB) $(LIB) || echo Never mind.
@touch lib
rc4-586.s: asm/rc4-586.pl ../perlasm/x86asm.pl
$(PERL) asm/rc4-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(PROCESSOR) > $@
rc4-x86_64.s: asm/rc4-x86_64.pl
$(PERL) asm/rc4-x86_64.pl $(PERLASM_SCHEME) > $@
rc4-md5-x86_64.s: asm/rc4-md5-x86_64.pl
$(PERL) asm/rc4-md5-x86_64.pl $(PERLASM_SCHEME) > $@
rc4-ia64.S: asm/rc4-ia64.pl
$(PERL) asm/rc4-ia64.pl $(CFLAGS) > $@
rc4-parisc.s: asm/rc4-parisc.pl
$(PERL) asm/rc4-parisc.pl $(PERLASM_SCHEME) $@
rc4-ia64.s: rc4-ia64.S
@case `awk '/^#define RC4_INT/{print$$NF}' $(TOP)/include/openssl/opensslconf.h` in \
int) set -x; $(CC) $(CFLAGS) -DSZ=4 -E rc4-ia64.S > $@ ;; \
char) set -x; $(CC) $(CFLAGS) -DSZ=1 -E rc4-ia64.S > $@ ;; \
*) exit 1 ;; \
esac
# GNU make "catch all"
rc4-%.s: asm/rc4-%.pl; $(PERL) $< $(PERLASM_SCHEME) $@
files:
$(PERL) $(TOP)/util/files.pl "RC4_ENC=$(RC4_ENC)" Makefile >> $(TOP)/MINFO
links:
@$(PERL) $(TOP)/util/mklink.pl ../../include/openssl $(EXHEADER)
@$(PERL) $(TOP)/util/mklink.pl ../../test $(TEST)
@$(PERL) $(TOP)/util/mklink.pl ../../apps $(APPS)
install:
@[ -n "$(INSTALLTOP)" ] # should be set by top Makefile...
@headerlist="$(EXHEADER)"; for i in $$headerlist ; \
do \
(cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \
chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \
done;
tags:
ctags $(SRC)
tests:
lint:
lint -DLINT $(INCLUDES) $(SRC)>fluff
update: depend
depend:
@[ -n "$(MAKEDEPEND)" ] # should be set by upper Makefile...
$(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(PROGS) $(LIBSRC)
dclean:
$(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new
mv -f Makefile.new $(MAKEFILE)
clean:
rm -f *.s *.S *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff
# DO NOT DELETE THIS LINE -- make depend depends on it.
rc4_enc.o: ../../e_os.h ../../include/openssl/bio.h
rc4_enc.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
rc4_enc.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
rc4_enc.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
rc4_enc.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
rc4_enc.o: ../../include/openssl/rc4.h ../../include/openssl/safestack.h
rc4_enc.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
rc4_enc.o: ../cryptlib.h rc4_enc.c rc4_locl.h
rc4_skey.o: ../../e_os.h ../../include/openssl/bio.h
rc4_skey.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
rc4_skey.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
rc4_skey.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
rc4_skey.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
rc4_skey.o: ../../include/openssl/rc4.h ../../include/openssl/safestack.h
rc4_skey.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
rc4_skey.o: ../cryptlib.h rc4_locl.h rc4_skey.c
rc4_utl.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
rc4_utl.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
rc4_utl.o: ../../include/openssl/ossl_typ.h ../../include/openssl/rc4.h
rc4_utl.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
rc4_utl.o: ../../include/openssl/symhacks.h rc4_utl.c
| LomoX-Offical/nginx-openresty-windows | src/nginx/objs/lib_x64/openssl/crypto/rc4/Makefile | Makefile | bsd-2-clause | 3,862 |
@media screen and (max-width: 991px), screen and (min-device-width: 768px) and (max-device-width: 1024px) and (-webkit-min-device-pixel-ratio: 2), screen and (min-device-width: 320px) and (max-device-width: 568px) and (-webkit-min-device-pixel-ratio: 2) {
.row-offcanvas {
position: relative;
-webkit-transition: all 0.25s ease-out;
-moz-transition: all 0.25s ease-out;
transition: all 0.25s ease-out;
}
.row-offcanvas-right .sidebar-offcanvas {
right: -85%;
}
.row-offcanvas-right.active {
right: 85%;
}
.sidebar-offcanvas {
position: fixed;
top: 0;
width: 85%;
}
}
#menu-btn {
display: none;
}
@media screen and (max-width: 991px), only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 13/10), only screen and (min-resolution: 120dpi) {
#menu-btn {
display: block;
position: absolute;
right: 15px;
padding-bottom: 3px;
}
}
#menu-btn .btn-back {
display: none;
}
#menu-btn .btn-text {
display: none;
font-size: 1.2em;
}
#menu-btn .active {
display: inline !important;
}
#sidebar {
overflow-y: scroll;
height: 85%;
max-width: 400px;
}
#sidebar .list-group {
background-color: transparent;
border: 0;
}
#sidebar .list-group .list-group-item {
border: 0;
margin-left: 20px;
color: #666;
}
@media screen and (max-width: 991px), only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 13/10), only screen and (min-resolution: 120dpi) {
#sidebar {
position: absolute;
margin-left: 185%;
top: 20px;
}
}
.btn-blue {
background-color: #7eb5d3;
color: #fff;
}
.btn-blue:hover,
.btn-blue:focus {
background-color: #a4cbe0;
color: #000;
outline: none !important;
}
| state-hiu/GeoGit | doc/themes/geogit_docs/static/offcanvas.css | CSS | bsd-3-clause | 1,766 |
// Copyright 2013 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.
#include <map>
#include <string>
#include "base/memory/scoped_ptr.h"
#include "chrome/renderer/extensions/extension_localization_peer.h"
#include "extensions/common/message_bundle.h"
#include "ipc/ipc_sender.h"
#include "ipc/ipc_sync_message.h"
#include "net/base/net_errors.h"
#include "net/url_request/redirect_info.h"
#include "net/url_request/url_request_status.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
using testing::DoAll;
using testing::Invoke;
using testing::StrEq;
using testing::Return;
static const char* const kExtensionUrl_1 =
"chrome-extension://some_id/popup.css";
static const char* const kExtensionUrl_2 =
"chrome-extension://some_id2/popup.css";
static const char* const kExtensionUrl_3 =
"chrome-extension://some_id3/popup.css";
void MessageDeleter(IPC::Message* message) {
delete message;
}
class MockIpcMessageSender : public IPC::Sender {
public:
MockIpcMessageSender() {
ON_CALL(*this, Send(_))
.WillByDefault(DoAll(Invoke(MessageDeleter), Return(true)));
}
virtual ~MockIpcMessageSender() {}
MOCK_METHOD1(Send, bool(IPC::Message* message));
private:
DISALLOW_COPY_AND_ASSIGN(MockIpcMessageSender);
};
class MockRequestPeer : public content::RequestPeer {
public:
MockRequestPeer() {}
virtual ~MockRequestPeer() {}
MOCK_METHOD2(OnUploadProgress, void(uint64 position, uint64 size));
MOCK_METHOD2(OnReceivedRedirect,
bool(const net::RedirectInfo& redirect_info,
const content::ResourceResponseInfo& info));
MOCK_METHOD1(OnReceivedResponse,
void(const content::ResourceResponseInfo& info));
MOCK_METHOD2(OnDownloadedData, void(int len, int encoded_data_length));
MOCK_METHOD3(OnReceivedData, void(const char* data,
int data_length,
int encoded_data_length));
MOCK_METHOD6(OnCompletedRequest, void(
int error_code,
bool was_ignored_by_handler,
bool stale_copy_in_cache,
const std::string& security_info,
const base::TimeTicks& completion_time,
int64_t total_transfer_size));
private:
DISALLOW_COPY_AND_ASSIGN(MockRequestPeer);
};
class ExtensionLocalizationPeerTest : public testing::Test {
protected:
void SetUp() override {
sender_.reset(new MockIpcMessageSender());
original_peer_.reset(new MockRequestPeer());
filter_peer_.reset(
ExtensionLocalizationPeer::CreateExtensionLocalizationPeer(
original_peer_.get(), sender_.get(), "text/css",
GURL(kExtensionUrl_1)));
}
ExtensionLocalizationPeer* CreateExtensionLocalizationPeer(
const std::string& mime_type,
const GURL& request_url) {
return ExtensionLocalizationPeer::CreateExtensionLocalizationPeer(
original_peer_.get(), sender_.get(), mime_type, request_url);
}
std::string GetData(ExtensionLocalizationPeer* filter_peer) {
EXPECT_TRUE(NULL != filter_peer);
return filter_peer->data_;
}
void SetData(ExtensionLocalizationPeer* filter_peer,
const std::string& data) {
EXPECT_TRUE(NULL != filter_peer);
filter_peer->data_ = data;
}
scoped_ptr<MockIpcMessageSender> sender_;
scoped_ptr<MockRequestPeer> original_peer_;
scoped_ptr<ExtensionLocalizationPeer> filter_peer_;
};
TEST_F(ExtensionLocalizationPeerTest, CreateWithWrongMimeType) {
filter_peer_.reset(
CreateExtensionLocalizationPeer("text/html", GURL(kExtensionUrl_1)));
EXPECT_TRUE(NULL == filter_peer_.get());
}
TEST_F(ExtensionLocalizationPeerTest, CreateWithValidInput) {
EXPECT_TRUE(NULL != filter_peer_.get());
}
TEST_F(ExtensionLocalizationPeerTest, OnReceivedData) {
EXPECT_TRUE(GetData(filter_peer_.get()).empty());
const std::string data_chunk("12345");
filter_peer_->OnReceivedData(data_chunk.c_str(), data_chunk.length(), -1);
EXPECT_EQ(data_chunk, GetData(filter_peer_.get()));
filter_peer_->OnReceivedData(data_chunk.c_str(), data_chunk.length(), -1);
EXPECT_EQ(data_chunk + data_chunk, GetData(filter_peer_.get()));
}
MATCHER_P(IsURLRequestEqual, status, "") { return arg.status() == status; }
TEST_F(ExtensionLocalizationPeerTest, OnCompletedRequestBadURLRequestStatus) {
// It will self-delete once it exits OnCompletedRequest.
ExtensionLocalizationPeer* filter_peer = filter_peer_.release();
EXPECT_CALL(*original_peer_, OnReceivedResponse(_));
EXPECT_CALL(*original_peer_, OnCompletedRequest(
net::ERR_ABORTED, false, false, "", base::TimeTicks(), -1));
filter_peer->OnCompletedRequest(
net::ERR_FAILED, false, false, std::string(), base::TimeTicks(), -1);
}
TEST_F(ExtensionLocalizationPeerTest, OnCompletedRequestEmptyData) {
// It will self-delete once it exits OnCompletedRequest.
ExtensionLocalizationPeer* filter_peer = filter_peer_.release();
EXPECT_CALL(*original_peer_, OnReceivedData(_, _, _)).Times(0);
EXPECT_CALL(*sender_, Send(_)).Times(0);
EXPECT_CALL(*original_peer_, OnReceivedResponse(_));
EXPECT_CALL(*original_peer_, OnCompletedRequest(
net::OK, false, false, "", base::TimeTicks(), -1));
filter_peer->OnCompletedRequest(
net::OK, false, false, std::string(), base::TimeTicks(), -1);
}
TEST_F(ExtensionLocalizationPeerTest, OnCompletedRequestNoCatalogs) {
// It will self-delete once it exits OnCompletedRequest.
ExtensionLocalizationPeer* filter_peer = filter_peer_.release();
SetData(filter_peer, "some text");
EXPECT_CALL(*sender_, Send(_));
std::string data = GetData(filter_peer);
EXPECT_CALL(*original_peer_,
OnReceivedData(StrEq(data.data()), data.length(), -1)).Times(2);
EXPECT_CALL(*original_peer_, OnReceivedResponse(_)).Times(2);
EXPECT_CALL(*original_peer_, OnCompletedRequest(
net::OK, false, false, "", base::TimeTicks(), -1)).Times(2);
filter_peer->OnCompletedRequest(
net::OK, false, false, std::string(), base::TimeTicks(), -1);
// Test if Send gets called again (it shouldn't be) when first call returned
// an empty dictionary.
filter_peer =
CreateExtensionLocalizationPeer("text/css", GURL(kExtensionUrl_1));
SetData(filter_peer, "some text");
filter_peer->OnCompletedRequest(
net::OK, false, false, std::string(), base::TimeTicks(), -1);
}
TEST_F(ExtensionLocalizationPeerTest, OnCompletedRequestWithCatalogs) {
// It will self-delete once it exits OnCompletedRequest.
ExtensionLocalizationPeer* filter_peer =
CreateExtensionLocalizationPeer("text/css", GURL(kExtensionUrl_2));
extensions::L10nMessagesMap messages;
messages.insert(std::make_pair("text", "new text"));
extensions::ExtensionToL10nMessagesMap& l10n_messages_map =
*extensions::GetExtensionToL10nMessagesMap();
l10n_messages_map["some_id2"] = messages;
SetData(filter_peer, "some __MSG_text__");
// We already have messages in memory, Send will be skipped.
EXPECT_CALL(*sender_, Send(_)).Times(0);
// __MSG_text__ gets replaced with "new text".
std::string data("some new text");
EXPECT_CALL(*original_peer_,
OnReceivedData(StrEq(data.data()), data.length(), -1));
EXPECT_CALL(*original_peer_, OnReceivedResponse(_));
EXPECT_CALL(*original_peer_, OnCompletedRequest(
net::OK, false, false, "", base::TimeTicks(), -1));
filter_peer->OnCompletedRequest(
net::OK, false, false, std::string(), base::TimeTicks(), -1);
}
TEST_F(ExtensionLocalizationPeerTest, OnCompletedRequestReplaceMessagesFails) {
// It will self-delete once it exits OnCompletedRequest.
ExtensionLocalizationPeer* filter_peer =
CreateExtensionLocalizationPeer("text/css", GURL(kExtensionUrl_3));
extensions::L10nMessagesMap messages;
messages.insert(std::make_pair("text", "new text"));
extensions::ExtensionToL10nMessagesMap& l10n_messages_map =
*extensions::GetExtensionToL10nMessagesMap();
l10n_messages_map["some_id3"] = messages;
std::string message("some __MSG_missing_message__");
SetData(filter_peer, message);
// We already have messages in memory, Send will be skipped.
EXPECT_CALL(*sender_, Send(_)).Times(0);
// __MSG_missing_message__ is missing, so message stays the same.
EXPECT_CALL(*original_peer_,
OnReceivedData(StrEq(message.data()), message.length(), -1));
EXPECT_CALL(*original_peer_, OnReceivedResponse(_));
EXPECT_CALL(*original_peer_, OnCompletedRequest(
net::OK, false, false, "", base::TimeTicks(), -1));
filter_peer->OnCompletedRequest(
net::OK, false, false, std::string(), base::TimeTicks(), -1);
}
| mohamed--abdel-maksoud/chromium.src | chrome/renderer/extensions/extension_localization_peer_unittest.cc | C++ | bsd-3-clause | 8,756 |
// 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 PPAPI_PROXY_PLUGIN_RESOURCE_H_
#define PPAPI_PROXY_PLUGIN_RESOURCE_H_
#include <map>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_sender.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/proxy/connection.h"
#include "ppapi/proxy/plugin_resource_callback.h"
#include "ppapi/proxy/ppapi_message_utils.h"
#include "ppapi/proxy/ppapi_proxy_export.h"
#include "ppapi/proxy/resource_message_params.h"
#include "ppapi/proxy/resource_reply_thread_registrar.h"
#include "ppapi/shared_impl/resource.h"
#include "ppapi/shared_impl/tracked_callback.h"
namespace ppapi {
namespace proxy {
class PluginDispatcher;
class PPAPI_PROXY_EXPORT PluginResource : public Resource {
public:
enum Destination {
RENDERER = 0,
BROWSER = 1
};
PluginResource(Connection connection, PP_Instance instance);
~PluginResource() override;
// Returns true if we've previously sent a create message to the browser
// or renderer. Generally resources will use these to tell if they should
// lazily send create messages.
bool sent_create_to_browser() const { return sent_create_to_browser_; }
bool sent_create_to_renderer() const { return sent_create_to_renderer_; }
// This handles a reply to a resource call. It works by looking up the
// callback that was registered when CallBrowser/CallRenderer was called
// and calling it with |params| and |msg|.
void OnReplyReceived(const proxy::ResourceMessageReplyParams& params,
const IPC::Message& msg) override;
// Resource overrides.
// Note: Subclasses shouldn't override these methods directly. Instead, they
// should implement LastPluginRefWasDeleted() or InstanceWasDeleted() to get
// notified.
void NotifyLastPluginRefWasDeleted() override;
void NotifyInstanceWasDeleted() override;
// Sends a create message to the browser or renderer for the current resource.
void SendCreate(Destination dest, const IPC::Message& msg);
// When the host returnes a resource to the plugin, it will create a pending
// ResourceHost and send an ID back to the plugin that identifies the pending
// object. The plugin uses this function to connect the plugin resource with
// the pending host resource. See also PpapiHostMsg_AttachToPendingHost. This
// is in lieu of sending a create message.
void AttachToPendingHost(Destination dest, int pending_host_id);
// Sends the given IPC message as a resource request to the host
// corresponding to this resource object and does not expect a reply.
void Post(Destination dest, const IPC::Message& msg);
// Like Post() but expects a response. |callback| is a |base::Callback| that
// will be run when a reply message with a sequence number matching that of
// the call is received. |ReplyMsgClass| is the type of the reply message that
// is expected. An example of usage:
//
// Call<PpapiPluginMsg_MyResourceType_MyReplyMessage>(
// BROWSER,
// PpapiHostMsg_MyResourceType_MyRequestMessage(),
// base::Bind(&MyPluginResource::ReplyHandler, base::Unretained(this)));
//
// If a reply message to this call is received whose type does not match
// |ReplyMsgClass| (for example, in the case of an error), the callback will
// still be invoked but with the default values of the message parameters.
//
// Returns the new request's sequence number which can be used to identify
// the callback. This value will never be 0, which you can use to identify
// an invalid callback.
//
// Note: 1) When all plugin references to this resource are gone or the
// corresponding plugin instance is deleted, all pending callbacks
// are abandoned.
// 2) It is *not* recommended to let |callback| hold any reference to
// |this|, in which it will be stored. Otherwise, this object will
// live forever if we fail to clean up the callback. It is safe to
// use base::Unretained(this) or a weak pointer, because this object
// will outlive the callback.
template<typename ReplyMsgClass, typename CallbackType>
int32_t Call(Destination dest,
const IPC::Message& msg,
const CallbackType& callback);
// Comparing with the previous Call() method, this method takes
// |reply_thread_hint| as a hint to determine which thread to handle the reply
// message.
//
// If |reply_thread_hint| is non-blocking, the reply message will be handled
// on the target thread of the callback; otherwise, it will be handled on the
// main thread.
//
// If handling a reply message will cause a TrackedCallback to be run, it is
// recommended to use this version of Call(). It eliminates unnecessary
// thread switching and therefore has better performance.
template<typename ReplyMsgClass, typename CallbackType>
int32_t Call(Destination dest,
const IPC::Message& msg,
const CallbackType& callback,
scoped_refptr<TrackedCallback> reply_thread_hint);
// Calls the browser/renderer with sync messages. Returns the pepper error
// code from the call.
// |ReplyMsgClass| is the type of the reply message that is expected. If it
// carries x parameters, then the method with x out parameters should be used.
// An example of usage:
//
// // Assuming the reply message carries a string and an integer.
// std::string param_1;
// int param_2 = 0;
// int32_t result = SyncCall<PpapiPluginMsg_MyResourceType_MyReplyMessage>(
// RENDERER, PpapiHostMsg_MyResourceType_MyRequestMessage(),
// ¶m_1, ¶m_2);
template <class ReplyMsgClass>
int32_t SyncCall(Destination dest, const IPC::Message& msg);
template <class ReplyMsgClass, class A>
int32_t SyncCall(Destination dest, const IPC::Message& msg, A* a);
template <class ReplyMsgClass, class A, class B>
int32_t SyncCall(Destination dest, const IPC::Message& msg, A* a, B* b);
template <class ReplyMsgClass, class A, class B, class C>
int32_t SyncCall(Destination dest, const IPC::Message& msg, A* a, B* b, C* c);
template <class ReplyMsgClass, class A, class B, class C, class D>
int32_t SyncCall(
Destination dest, const IPC::Message& msg, A* a, B* b, C* c, D* d);
template <class ReplyMsgClass, class A, class B, class C, class D, class E>
int32_t SyncCall(
Destination dest, const IPC::Message& msg, A* a, B* b, C* c, D* d, E* e);
int32_t GenericSyncCall(Destination dest,
const IPC::Message& msg,
IPC::Message* reply_msg,
ResourceMessageReplyParams* reply_params);
const Connection& connection() { return connection_; }
private:
IPC::Sender* GetSender(Destination dest) {
return dest == RENDERER ? connection_.renderer_sender :
connection_.browser_sender;
}
// Helper function to send a |PpapiHostMsg_ResourceCall| to the given
// destination with |nested_msg| and |call_params|.
bool SendResourceCall(Destination dest,
const ResourceMessageCallParams& call_params,
const IPC::Message& nested_msg);
int32_t GetNextSequence();
Connection connection_;
// Use GetNextSequence to retrieve the next value.
int32_t next_sequence_number_;
bool sent_create_to_browser_;
bool sent_create_to_renderer_;
typedef std::map<int32_t, scoped_refptr<PluginResourceCallbackBase> >
CallbackMap;
CallbackMap callbacks_;
scoped_refptr<ResourceReplyThreadRegistrar> resource_reply_thread_registrar_;
DISALLOW_COPY_AND_ASSIGN(PluginResource);
};
template<typename ReplyMsgClass, typename CallbackType>
int32_t PluginResource::Call(Destination dest,
const IPC::Message& msg,
const CallbackType& callback) {
return Call<ReplyMsgClass>(dest, msg, callback, NULL);
}
template<typename ReplyMsgClass, typename CallbackType>
int32_t PluginResource::Call(
Destination dest,
const IPC::Message& msg,
const CallbackType& callback,
scoped_refptr<TrackedCallback> reply_thread_hint) {
TRACE_EVENT2("ppapi proxy", "PluginResource::Call",
"Class", IPC_MESSAGE_ID_CLASS(msg.type()),
"Line", IPC_MESSAGE_ID_LINE(msg.type()));
ResourceMessageCallParams params(pp_resource(), next_sequence_number_++);
// Stash the |callback| in |callbacks_| identified by the sequence number of
// the call.
scoped_refptr<PluginResourceCallbackBase> plugin_callback(
new PluginResourceCallback<ReplyMsgClass, CallbackType>(callback));
callbacks_.insert(std::make_pair(params.sequence(), plugin_callback));
params.set_has_callback();
if (resource_reply_thread_registrar_.get()) {
resource_reply_thread_registrar_->Register(
pp_resource(), params.sequence(), reply_thread_hint);
}
SendResourceCall(dest, params, msg);
return params.sequence();
}
template <class ReplyMsgClass>
int32_t PluginResource::SyncCall(Destination dest, const IPC::Message& msg) {
IPC::Message reply;
ResourceMessageReplyParams reply_params;
return GenericSyncCall(dest, msg, &reply, &reply_params);
}
template <class ReplyMsgClass, class A>
int32_t PluginResource::SyncCall(
Destination dest, const IPC::Message& msg, A* a) {
IPC::Message reply;
ResourceMessageReplyParams reply_params;
int32_t result = GenericSyncCall(dest, msg, &reply, &reply_params);
if (UnpackMessage<ReplyMsgClass>(reply, a))
return result;
return PP_ERROR_FAILED;
}
template <class ReplyMsgClass, class A, class B>
int32_t PluginResource::SyncCall(
Destination dest, const IPC::Message& msg, A* a, B* b) {
IPC::Message reply;
ResourceMessageReplyParams reply_params;
int32_t result = GenericSyncCall(dest, msg, &reply, &reply_params);
if (UnpackMessage<ReplyMsgClass>(reply, a, b))
return result;
return PP_ERROR_FAILED;
}
template <class ReplyMsgClass, class A, class B, class C>
int32_t PluginResource::SyncCall(
Destination dest, const IPC::Message& msg, A* a, B* b, C* c) {
IPC::Message reply;
ResourceMessageReplyParams reply_params;
int32_t result = GenericSyncCall(dest, msg, &reply, &reply_params);
if (UnpackMessage<ReplyMsgClass>(reply, a, b, c))
return result;
return PP_ERROR_FAILED;
}
template <class ReplyMsgClass, class A, class B, class C, class D>
int32_t PluginResource::SyncCall(
Destination dest, const IPC::Message& msg, A* a, B* b, C* c, D* d) {
IPC::Message reply;
ResourceMessageReplyParams reply_params;
int32_t result = GenericSyncCall(dest, msg, &reply, &reply_params);
if (UnpackMessage<ReplyMsgClass>(reply, a, b, c, d))
return result;
return PP_ERROR_FAILED;
}
template <class ReplyMsgClass, class A, class B, class C, class D, class E>
int32_t PluginResource::SyncCall(
Destination dest, const IPC::Message& msg, A* a, B* b, C* c, D* d, E* e) {
IPC::Message reply;
ResourceMessageReplyParams reply_params;
int32_t result = GenericSyncCall(dest, msg, &reply, &reply_params);
if (UnpackMessage<ReplyMsgClass>(reply, a, b, c, d, e))
return result;
return PP_ERROR_FAILED;
}
} // namespace proxy
} // namespace ppapi
#endif // PPAPI_PROXY_PLUGIN_RESOURCE_H_
| Chilledheart/chromium | ppapi/proxy/plugin_resource.h | C | bsd-3-clause | 11,487 |
/*
* Copyright (c) 2007, Michael Feathers, James Grenning, Bas Vodde and Timo Puronen
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "CppUTest/TestHarness.h"
#include <e32def.h>
#include <e32std.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include "CppUTest/PlatformSpecificFunctions.h"
static jmp_buf test_exit_jmp_buf[10];
static int jmp_buf_index = 0;
int PlatformSpecificSetJmp(void (*function) (void* data), void* data)
{
if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {
jmp_buf_index++;
function(data);
jmp_buf_index--;
return 1;
}
return 0;
}
void PlatformSpecificLongJmp()
{
jmp_buf_index--;
longjmp(test_exit_jmp_buf[jmp_buf_index], 1);
}
void PlatformSpecificRestoreJumpBuffer()
{
jmp_buf_index--;
}
void PlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result)
{
printf("-p doesn't work on this platform as it is not implemented. Running inside the process\b");
shell->runOneTest(plugin, *result);
}
static long TimeInMillisImplementation() {
struct timeval tv;
struct timezone tz;
::gettimeofday(&tv, &tz);
return (tv.tv_sec * 1000) + (long)(tv.tv_usec * 0.001);
}
long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation;
TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()
{
return TestOutput::eclipse;
}
static SimpleString TimeStringImplementation() {
time_t tm = time(NULL);
return ctime(&tm);
}
SimpleString GetPlatformSpecificTimeString() = TimeStringImplementation;
int PlatformSpecificVSNprintf(char* str, size_t size, const char* format, va_list args) {
return vsnprintf(str, size, format, args);
}
void PlatformSpecificFlush() {
fflush(stdout);
}
int PlatformSpecificPutchar(int c) {
return putchar(c);
}
double PlatformSpecificFabs(double d) {
return fabs(d);
}
void* PlatformSpecificMalloc(size_t size) {
return malloc(size);
}
void* PlatformSpecificRealloc (void* memory, size_t size) {
return realloc(memory, size);
}
void PlatformSpecificFree(void* memory) {
free(memory);
}
void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) {
return memcpy(s1, s2, size);
}
void* PlatformSpecificMemset(void* mem, int c, size_t size)
{
return memset(mem, c, size);
}
PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) {
return fopen(filename, flag);
}
void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) {
fputs(str, (FILE*)file);
}
void PlatformSpecificFClose(PlatformSpecificFile file) {
fclose((FILE*)file);
}
extern "C" {
static int IsNanImplementation(double d)
{
return isnan(d);
}
static int IsInfImplementation(double d)
{
return isinf(d);
}
int (*PlatformSpecificIsNan)(double) = IsNanImplementation;
int (*PlatformSpecificIsInf)(double) = IsInfImplementation;
}
static PlatformSpecificMutex DummyMutexCreate(void)
{
FAIL("PlatformSpecificMutexCreate is not implemented");
return 0;
}
static void DummyMutexLock(PlatformSpecificMutex mtx)
{
FAIL("PlatformSpecificMutexLock is not implemented");
}
static void DummyMutexUnlock(PlatformSpecificMutex mtx)
{
FAIL("PlatformSpecificMutexUnlock is not implemented");
}
static void DummyMutexDestroy(PlatformSpecificMutex mtx)
{
FAIL("PlatformSpecificMutexDestroy is not implemented");
}
PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = DummyMutexCreate;
void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = DummyMutexLock;
void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = DummyMutexUnlock;
void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = DummyMutexDestroy;
| cpputest/cpputest | src/Platforms/Symbian/UtestPlatform.cpp | C++ | bsd-3-clause | 5,287 |
/**
* @license Highstock JS v2.1.4 (2015-03-10)
* Plugin for displaying a message when there is no data visible in chart.
*
* (c) 2010-2014 Highsoft AS
* Author: Oystein Moseng
*
* License: www.highcharts.com/license
*/
(function (H) {
var seriesTypes = H.seriesTypes,
chartPrototype = H.Chart.prototype,
defaultOptions = H.getOptions(),
extend = H.extend,
each = H.each;
// Add language option
extend(defaultOptions.lang, {
noData: 'No data to display'
});
// Add default display options for message
defaultOptions.noData = {
position: {
x: 0,
y: 0,
align: 'center',
verticalAlign: 'middle'
},
attr: {
},
style: {
fontWeight: 'bold',
fontSize: '12px',
color: '#60606a'
}
};
/**
* Define hasData functions for series. These return true if there are data points on this series within the plot area
*/
function hasDataPie() {
return !!this.points.length; /* != 0 */
}
each(['pie', 'gauge', 'waterfall', 'bubble'], function (type) {
if (seriesTypes[type]) {
seriesTypes[type].prototype.hasData = hasDataPie;
}
});
H.Series.prototype.hasData = function () {
return this.visible && this.dataMax !== undefined && this.dataMin !== undefined; // #3703
};
/**
* Display a no-data message.
*
* @param {String} str An optional message to show in place of the default one
*/
chartPrototype.showNoData = function (str) {
var chart = this,
options = chart.options,
text = str || options.lang.noData,
noDataOptions = options.noData;
if (!chart.noDataLabel) {
chart.noDataLabel = chart.renderer.label(text, 0, 0, null, null, null, null, null, 'no-data')
.attr(noDataOptions.attr)
.css(noDataOptions.style)
.add();
chart.noDataLabel.align(extend(chart.noDataLabel.getBBox(), noDataOptions.position), false, 'plotBox');
}
};
/**
* Hide no-data message
*/
chartPrototype.hideNoData = function () {
var chart = this;
if (chart.noDataLabel) {
chart.noDataLabel = chart.noDataLabel.destroy();
}
};
/**
* Returns true if there are data points within the plot area now
*/
chartPrototype.hasData = function () {
var chart = this,
series = chart.series,
i = series.length;
while (i--) {
if (series[i].hasData() && !series[i].options.isInternal) {
return true;
}
}
return false;
};
/**
* Show no-data message if there is no data in sight. Otherwise, hide it.
*/
function handleNoData() {
var chart = this;
if (chart.hasData()) {
chart.hideNoData();
} else {
chart.showNoData();
}
}
/**
* Add event listener to handle automatic display of no-data message
*/
chartPrototype.callbacks.push(function (chart) {
H.addEvent(chart, 'load', handleNoData);
H.addEvent(chart, 'redraw', handleNoData);
});
}(Highcharts));
| syscart/syscart | web/media/js/jquery/plugins/Highstock/2.1.4/js/modules/no-data-to-display.src.js | JavaScript | gpl-2.0 | 2,826 |
#!/usr/bin/env node
/* global cat:true, cd:true, echo:true, exec:true, exit:true */
// Usage:
// stable release: node release.js
// pre-release: node release.js --pre-release {version}
// test run: node release.js --remote={repo}
// - repo: "/tmp/repo" (filesystem), "user/repo" (github), "http://mydomain/repo.git" (another domain)
"use strict";
var baseDir, downloadBuilder, repoDir, prevVersion, newVersion, nextVersion, tagTime, preRelease, repo,
fs = require( "fs" ),
path = require( "path" ),
rnewline = /\r?\n/,
branch = "master";
walk([
bootstrap,
section( "setting up repo" ),
cloneRepo,
checkState,
section( "calculating versions" ),
getVersions,
confirm,
section( "building release" ),
buildReleaseBranch,
buildPackage,
section( "pushing tag" ),
confirmReview,
pushRelease,
section( "updating branch version" ),
updateBranchVersion,
section( "pushing " + branch ),
confirmReview,
pushBranch,
section( "generating changelog" ),
generateChangelog,
section( "gathering contributors" ),
gatherContributors,
section( "updating trac" ),
updateTrac,
confirm
]);
function cloneRepo() {
echo( "Cloning " + repo.cyan + "..." );
git( "clone " + repo + " " + repoDir, "Error cloning repo." );
cd( repoDir );
echo( "Checking out " + branch.cyan + " branch..." );
git( "checkout " + branch, "Error checking out branch." );
echo();
echo( "Installing dependencies..." );
if ( exec( "npm install" ).code !== 0 ) {
abort( "Error installing dependencies." );
}
echo();
}
function checkState() {
echo( "Checking AUTHORS.txt..." );
var result, lastActualAuthor,
lastListedAuthor = cat( "AUTHORS.txt" ).trim().split( rnewline ).pop();
result = exec( "grunt authors", { silent: true });
if ( result.code !== 0 ) {
abort( "Error getting list of authors." );
}
lastActualAuthor = result.output.split( rnewline ).splice( -4, 1 )[ 0 ];
if ( lastListedAuthor !== lastActualAuthor ) {
echo( "Last listed author is " + lastListedAuthor.red + "." );
echo( "Last actual author is " + lastActualAuthor.green + "." );
abort( "Please update AUTHORS.txt." );
}
echo( "Last listed author (" + lastListedAuthor.cyan + ") is correct." );
}
function getVersions() {
// prevVersion, newVersion, nextVersion are defined in the parent scope
var parts, major, minor, patch,
currentVersion = readPackage().version;
echo( "Validating current version..." );
if ( currentVersion.substr( -3, 3 ) !== "pre" ) {
echo( "The current version is " + currentVersion.red + "." );
abort( "The version must be a pre version." );
}
if ( preRelease ) {
newVersion = preRelease;
// Note: prevVersion is not currently used for pre-releases.
prevVersion = nextVersion = currentVersion;
} else {
newVersion = currentVersion.substr( 0, currentVersion.length - 3 );
parts = newVersion.split( "." );
major = parseInt( parts[ 0 ], 10 );
minor = parseInt( parts[ 1 ], 10 );
patch = parseInt( parts[ 2 ], 10 );
if ( minor === 0 && patch === 0 ) {
abort( "This script is not smart enough to handle major release (eg. 2.0.0)." );
} else if ( patch === 0 ) {
prevVersion = git( "for-each-ref --count=1 --sort=-authordate --format='%(refname:short)' refs/tags/" + [ major, minor - 1 ].join( "." ) + "*" ).trim();
} else {
prevVersion = [ major, minor, patch - 1 ].join( "." );
}
nextVersion = [ major, minor, patch + 1 ].join( "." ) + "pre";
}
echo( "We are going from " + prevVersion.cyan + " to " + newVersion.cyan + "." );
echo( "After the release, the version will be " + nextVersion.cyan + "." );
}
function buildReleaseBranch() {
var pkg;
echo( "Creating " + "release".cyan + " branch..." );
git( "checkout -b release", "Error creating release branch." );
echo();
echo( "Updating package.json..." );
pkg = readPackage();
pkg.version = newVersion;
pkg.author.url = pkg.author.url.replace( "master", newVersion );
pkg.licenses.forEach(function( license ) {
license.url = license.url.replace( "master", newVersion );
});
writePackage( pkg );
echo( "Generating manifest files..." );
if ( exec( "grunt manifest" ).code !== 0 ) {
abort( "Error generating manifest files." );
}
echo();
echo( "Committing release artifacts..." );
git( "add *.jquery.json", "Error adding manifest files to git." );
git( "commit -am 'Tagging the " + newVersion + " release.'",
"Error committing release changes." );
echo();
echo( "Tagging release..." );
git( "tag " + newVersion, "Error tagging " + newVersion + "." );
tagTime = git( "log -1 --format='%ad'", "Error getting tag timestamp." ).trim();
}
function buildPackage( callback ) {
if( preRelease ) {
return buildPreReleasePackage( callback );
} else {
return buildCDNPackage( callback );
}
}
function buildPreReleasePackage( callback ) {
var build, files, jqueryUi, packer, target, targetZip;
echo( "Build pre-release Package" );
jqueryUi = new downloadBuilder.JqueryUi( path.resolve( "." ) );
build = new downloadBuilder.Builder( jqueryUi, ":all:" );
packer = new downloadBuilder.Packer( build, null, {
addTests: true,
bundleSuffix: "",
skipDocs: true,
skipTheme: true
});
target = "../" + jqueryUi.pkg.name + "-" + jqueryUi.pkg.version;
targetZip = target + ".zip";
return walk([
function( callback ) {
echo( "Building release files" );
packer.pack(function( error, _files ) {
if( error ) {
abort( error.stack );
}
files = _files.map(function( file ) {
// Strip first path
file.path = file.path.replace( /^[^\/]*\//, "" );
return file;
}).filter(function( file ) {
// Filter development-bundle content only
return (/^development-bundle/).test( file.path );
}).map(function( file ) {
// Strip development-bundle
file.path = file.path.replace( /^development-bundle\//, "" );
return file;
});
return callback();
});
},
function() {
downloadBuilder.util.createZip( files, targetZip, function( error ) {
if ( error ) {
abort( error.stack );
}
echo( "Built zip package at " + path.relative( "../..", targetZip ).cyan );
return callback();
});
}
]);
}
function buildCDNPackage( callback ) {
var build, output, target, targetZip,
add = function( file ) {
output.push( file );
},
jqueryUi = new downloadBuilder.JqueryUi( path.resolve( "." ) ),
themeGallery = downloadBuilder.themeGallery( jqueryUi );
echo( "Build CDN Package" );
build = new downloadBuilder.Builder( jqueryUi, ":all:" );
output = [];
target = "../" + jqueryUi.pkg.name + "-" + jqueryUi.pkg.version + "-cdn";
targetZip = target + ".zip";
[ "AUTHORS.txt", "MIT-LICENSE.txt", "package.json" ].map(function( name ) {
return build.get( name );
}).forEach( add );
// "ui/*.js"
build.componentFiles.filter(function( file ) {
return (/^ui\//).test( file.path );
}).forEach( add );
// "ui/*.min.js"
build.componentMinFiles.filter(function( file ) {
return (/^ui\//).test( file.path );
}).forEach( add );
// "i18n/*.js"
build.i18nFiles.rename( /^ui\//, "" ).forEach( add );
build.i18nMinFiles.rename( /^ui\//, "" ).forEach( add );
build.bundleI18n.into( "i18n/" ).forEach( add );
build.bundleI18nMin.into( "i18n/" ).forEach( add );
build.bundleJs.forEach( add );
build.bundleJsMin.forEach( add );
walk( themeGallery.map(function( theme ) {
return function( callback ) {
var themeCssOnlyRe, themeDirRe,
folderName = theme.folderName(),
packer = new downloadBuilder.Packer( build, theme, {
skipDocs: true
});
// TODO improve code by using custom packer instead of download packer (Packer)
themeCssOnlyRe = new RegExp( "development-bundle/themes/" + folderName + "/jquery.ui.theme.css" );
themeDirRe = new RegExp( "css/" + folderName );
packer.pack(function( error, files ) {
if ( error ) {
abort( error.stack );
}
// Add theme files.
files
// Pick only theme files we need on the bundle.
.filter(function( file ) {
if ( themeCssOnlyRe.test( file.path ) || themeDirRe.test( file.path ) ) {
return true;
}
return false;
})
// Convert paths the way bundle needs
.map(function( file ) {
file.path = file.path
// Remove initial package name eg. "jquery-ui-1.10.0.custom"
.split( "/" ).slice( 1 ).join( "/" )
.replace( /development-bundle\/themes/, "css" )
.replace( /css/, "themes" )
// Make jquery-ui-1.10.0.custom.css into jquery-ui.css, or jquery-ui-1.10.0.custom.min.css into jquery-ui.min.css
.replace( /jquery-ui-.*?(\.min)*\.css/, "jquery-ui$1.css" );
return file;
}).forEach( add );
return callback();
});
};
}).concat([function() {
var crypto = require( "crypto" );
// Create MD5 manifest
output.push({
path: "MANIFEST",
data: output.sort(function( a, b ) {
return a.path.localeCompare( b.path );
}).map(function( file ) {
var md5 = crypto.createHash( "md5" );
md5.update( file.data );
return file.path + " " + md5.digest( "hex" );
}).join( "\n" )
});
downloadBuilder.util.createZip( output, targetZip, function( error ) {
if ( error ) {
abort( error.stack );
}
echo( "Built zip CDN package at " + path.relative( "../..", targetZip ).cyan );
return callback();
});
}]));
}
function pushRelease() {
echo( "Pushing release to GitHub..." );
git( "push --tags", "Error pushing tags to GitHub." );
}
function updateBranchVersion() {
// Pre-releases don't change the master version
if ( preRelease ) {
return;
}
var pkg;
echo( "Checking out " + branch.cyan + " branch..." );
git( "checkout " + branch, "Error checking out " + branch + " branch." );
echo( "Updating package.json..." );
pkg = readPackage();
pkg.version = nextVersion;
writePackage( pkg );
echo( "Committing version update..." );
git( "commit -am 'Updating the " + branch + " version to " + nextVersion + ".'",
"Error committing package.json." );
}
function pushBranch() {
// Pre-releases don't change the master version
if ( preRelease ) {
return;
}
echo( "Pushing " + branch.cyan + " to GitHub..." );
git( "push", "Error pushing to GitHub." );
}
function generateChangelog() {
if ( preRelease ) {
return;
}
var commits,
changelogPath = baseDir + "/changelog",
changelog = cat( "build/release/changelog-shell" ) + "\n",
fullFormat = "* %s (TICKETREF, [%h](http://github.com/jquery/jquery-ui/commit/%H))";
changelog = changelog.replace( "{title}", "jQuery UI " + newVersion + " Changelog" );
echo ( "Adding commits..." );
commits = gitLog( fullFormat );
echo( "Adding links to tickets..." );
changelog += commits
// Add ticket references
.map(function( commit ) {
var tickets = [];
commit.replace( /Fixe[sd] #(\d+)/g, function( match, ticket ) {
tickets.push( ticket );
});
return tickets.length ?
commit.replace( "TICKETREF", tickets.map(function( ticket ) {
return "[#" + ticket + "](http://bugs.jqueryui.com/ticket/" + ticket + ")";
}).join( ", " ) ) :
// Leave TICKETREF token in place so it's easy to find commits without tickets
commit;
})
// Sort commits so that they're grouped by component
.sort()
.join( "\n" ) + "\n";
echo( "Adding Trac tickets..." );
changelog += trac( "/query?milestone=" + newVersion + "&resolution=fixed" +
"&col=id&col=component&col=summary&order=component" ) + "\n";
fs.writeFileSync( changelogPath, changelog );
echo( "Stored changelog in " + changelogPath.cyan + "." );
}
function gatherContributors() {
if ( preRelease ) {
return;
}
var contributors,
contributorsPath = baseDir + "/contributors";
echo( "Adding committers and authors..." );
contributors = gitLog( "%aN%n%cN" );
echo( "Adding reporters and commenters from Trac..." );
contributors = contributors.concat(
trac( "/report/22?V=" + newVersion + "&max=-1" )
.split( rnewline )
// Remove header and trailing newline
.slice( 1, -1 ) );
echo( "Sorting contributors..." );
contributors = unique( contributors ).sort(function( a, b ) {
return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
});
echo ( "Adding people thanked in commits..." );
contributors = contributors.concat(
gitLog( "%b%n%s" ).filter(function( line ) {
return (/thank/i).test( line );
}));
fs.writeFileSync( contributorsPath, contributors.join( "\n" ) );
echo( "Stored contributors in " + contributorsPath.cyan + "." );
}
function updateTrac() {
echo( newVersion.cyan + " was tagged at " + tagTime.cyan + "." );
if ( !preRelease ) {
echo( "Close the " + newVersion.cyan + " Milestone." );
}
echo( "Create the " + newVersion.cyan + " Version." );
echo( "When Trac asks for date and time, match the above. Should only change minutes and seconds." );
echo( "Create a Milestone for the next minor release." );
}
// ===== HELPER FUNCTIONS ======================================================
function git( command, errorMessage ) {
var result = exec( "git " + command );
if ( result.code !== 0 ) {
abort( errorMessage );
}
return result.output;
}
function gitLog( format ) {
var result = exec( "git log " + prevVersion + ".." + newVersion + " " +
"--format='" + format + "'",
{ silent: true });
if ( result.code !== 0 ) {
abort( "Error getting git log." );
}
result = result.output.split( rnewline );
if ( result[ result.length - 1 ] === "" ) {
result.pop();
}
return result;
}
function trac( path ) {
var result = exec( "curl -s 'http://bugs.jqueryui.com" + path + "&format=tab'",
{ silent: true });
if ( result.code !== 0 ) {
abort( "Error getting Trac data." );
}
return result.output;
}
function unique( arr ) {
var obj = {};
arr.forEach(function( item ) {
obj[ item ] = 1;
});
return Object.keys( obj );
}
function readPackage() {
return JSON.parse( fs.readFileSync( repoDir + "/package.json" ) );
}
function writePackage( pkg ) {
fs.writeFileSync( repoDir + "/package.json",
JSON.stringify( pkg, null, "\t" ) + "\n" );
}
function bootstrap( fn ) {
getRemote(function( remote ) {
if ( (/:/).test( remote ) || fs.existsSync( remote ) ) {
repo = remote;
} else {
repo = "git@github.com:" + remote + ".git";
}
_bootstrap( fn );
});
}
function getRemote( fn ) {
var matches, remote;
console.log( "Determining remote repo..." );
process.argv.forEach(function( arg ) {
matches = /--remote=(.+)/.exec( arg );
if ( matches ) {
remote = matches[ 1 ];
}
});
if ( remote ) {
fn( remote );
return;
}
console.log();
console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
console.log( " !! !!" );
console.log( " !! Using jquery/jquery-ui !!" );
console.log( " !! !!" );
console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
console.log();
console.log( "Press enter to continue, or ctrl+c to cancel." );
prompt(function() {
fn( "jquery/jquery-ui" );
});
}
function _bootstrap( fn ) {
console.log( "Determining release type..." );
preRelease = process.argv.indexOf( "--pre-release" );
if ( preRelease !== -1 ) {
preRelease = process.argv[ preRelease + 1 ];
console.log( "pre-release" );
} else {
preRelease = null;
console.log( "stable release" );
}
console.log( "Determining directories..." );
baseDir = process.cwd() + "/__release";
repoDir = baseDir + "/repo";
if ( fs.existsSync( baseDir ) ) {
console.log( "The directory '" + baseDir + "' already exists." );
console.log( "Aborting." );
process.exit( 1 );
}
console.log( "Creating directory..." );
fs.mkdirSync( baseDir );
console.log( "Installing dependencies..." );
require( "child_process" ).exec( "npm install shelljs colors download.jqueryui.com@1.10.3-4", function( error ) {
if ( error ) {
console.log( error );
return process.exit( 1 );
}
require( "shelljs/global" );
require( "colors" );
downloadBuilder = require( "download.jqueryui.com" );
fn();
});
}
function section( name ) {
return function() {
echo();
echo( "##" );
echo( "## " + name.toUpperCase().magenta );
echo( "##" );
echo();
};
}
function prompt( fn ) {
process.stdin.once( "data", function( chunk ) {
process.stdin.pause();
fn( chunk.toString().trim() );
});
process.stdin.resume();
}
function confirm( fn ) {
echo( "Press enter to continue, or ctrl+c to cancel.".yellow );
prompt( fn );
}
function confirmReview( fn ) {
echo( "Please review the output and generated files as a sanity check.".yellow );
confirm( fn );
}
function abort( msg ) {
echo( msg.red );
echo( "Aborting.".red );
exit( 1 );
}
function walk( methods ) {
var method = methods.shift();
function next() {
if ( methods.length ) {
walk( methods );
}
}
if ( !method.length ) {
method();
next();
} else {
method( next );
}
}
| yuyang545262477/Resume | 项目三jQueryMobile/bower_components/jquery-ui/build/release/release.js | JavaScript | mit | 16,898 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Behat\Page\Admin\ExchangeRate;
use Sylius\Behat\Page\Admin\Crud\UpdatePageInterface as BaseUpdatePageInterface;
/**
* @author Jan Góralski <jan.goralski@lakion.com>
*/
interface UpdatePageInterface extends BaseUpdatePageInterface
{
/**
* @return string
*/
public function getRatio();
/**
* @param string $ratio
*/
public function changeRatio($ratio);
/**
* @return bool
*/
public function isSourceCurrencyDisabled();
/**
* @return bool
*/
public function isTargetCurrencyDisabled();
}
| MichaelKubovic/Sylius | src/Sylius/Behat/Page/Admin/ExchangeRate/UpdatePageInterface.php | PHP | mit | 802 |
(function ($) {
$.Redactor.opts.langs['el'] = {
html: 'HTML',
video: 'Εισαγωγή βίντεο...',
image: 'Εισαγωγή εικόνας...',
table: 'Πίνακας',
link: 'Σύνδεσμος',
link_insert: 'Εισαγωγή συνδέσμου...',
link_edit: 'Edit link',
unlink: 'Ακύρωση συνδέσμου',
formatting: 'Μορφοποίηση',
paragraph: 'Παράγραφος',
quote: 'Παράθεση',
code: 'Κώδικας',
header1: 'Κεφαλίδα 1',
header2: 'Κεφαλίδα 2',
header3: 'Κεφαλίδα 3',
header4: 'Κεφαλίδα 4',
bold: 'Έντονα',
italic: 'Πλάγια',
fontcolor: 'Χρώμα γραμματοσειράς',
backcolor: 'Χρώμα επισήμανσης κειμένου',
unorderedlist: 'Κουκκίδες',
orderedlist: 'Αρίθμηση',
outdent: 'Μείωση εσοχής',
indent: 'Αύξηση εσοχής',
cancel: 'Ακύρωση',
insert: 'Εισαγωγή',
save: 'Αποθήκευση',
_delete: 'Διαγραφή',
insert_table: 'Εισαγωγή πίνακα...',
insert_row_above: 'Προσθήκη σειράς επάνω',
insert_row_below: 'Προσθήκη σειράς κάτω',
insert_column_left: 'Προσθήκη στήλης αριστερά',
insert_column_right: 'Προσθήκη στήλης δεξιά',
delete_column: 'Διαγραφή στήλης',
delete_row: 'Διαγραφή σειράς',
delete_table: 'Διαγραφή πίνακα',
rows: 'Γραμμές',
columns: 'Στήλες',
add_head: 'Προσθήκη κεφαλίδας',
delete_head: 'Διαγραφή κεφαλίδας',
title: 'Τίτλος',
image_position: 'Θέση',
none: 'Καμία',
left: 'Αριστερά',
right: 'Δεξιά',
image_web_link: 'Υπερσύνδεσμος εικόνας',
text: 'Κείμενο',
mailto: 'Email',
web: 'URL',
video_html_code: 'Video Embed Code',
file: 'Εισαγωγή αρχείου...',
upload: 'Upload',
download: 'Download',
choose: 'Επέλεξε',
or_choose: 'ή επέλεξε',
drop_file_here: 'Σύρατε αρχεία εδώ',
align_left: 'Στοίχιση αριστερά',
align_center: 'Στοίχιση στο κέντρο',
align_right: 'Στοίχιση δεξιά',
align_justify: 'Πλήρησ στοίχηση',
horizontalrule: 'Εισαγωγή οριζόντιας γραμμής',
deleted: 'Διαγράφτηκε',
anchor: 'Anchor',
link_new_tab: 'Open link in new tab',
underline: 'Underline',
alignment: 'Alignment',
filename: 'Name (optional)',
edit: 'Edit'
};
})( jQuery );
| sho-wtag/catarse-2.0 | vendor/cache/redactor-rails-e79c3b8359b4/vendor/assets/javascripts/redactor-rails/langs/el.js | JavaScript | mit | 2,592 |
import Ember from 'ember-metal/core';
import { get } from 'ember-metal/property_get';
import { internal } from 'htmlbars-runtime';
import { read } from 'ember-metal/streams/utils';
export default {
setupState(state, env, scope, params, hash) {
var controller = hash.controller;
if (controller) {
if (!state.controller) {
var context = params[0];
var controllerFactory = env.container.lookupFactory('controller:' + controller);
var parentController = null;
if (scope.locals.controller) {
parentController = read(scope.locals.controller);
} else if (scope.locals.view) {
parentController = get(read(scope.locals.view), 'context');
}
var controllerInstance = controllerFactory.create({
model: env.hooks.getValue(context),
parentController: parentController,
target: parentController
});
params[0] = controllerInstance;
return { controller: controllerInstance };
}
return state;
}
return { controller: null };
},
isStable() {
return true;
},
isEmpty(state) {
return false;
},
render(morph, env, scope, params, hash, template, inverse, visitor) {
if (morph.state.controller) {
morph.addDestruction(morph.state.controller);
hash.controller = morph.state.controller;
}
Ember.assert(
'{{#with foo}} must be called with a single argument or the use the ' +
'{{#with foo as |bar|}} syntax',
params.length === 1
);
Ember.assert(
'The {{#with}} helper must be called with a block',
!!template
);
internal.continueBlock(morph, env, scope, 'with', params, hash, template, inverse, visitor);
},
rerender(morph, env, scope, params, hash, template, inverse, visitor) {
internal.continueBlock(morph, env, scope, 'with', params, hash, template, inverse, visitor);
}
};
| cjc343/ember.js | packages/ember-htmlbars/lib/keywords/with.js | JavaScript | mit | 1,930 |
/***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2007 INRIA, France Telecom
* All rights reserved.
*
* 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 above 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. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.mockito.asm.util;
import org.mockito.asm.AnnotationVisitor;
import org.mockito.asm.Attribute;
import org.mockito.asm.FieldVisitor;
/**
* A {@link FieldVisitor} that checks that its methods are properly used.
*/
public class CheckFieldAdapter implements FieldVisitor {
private final FieldVisitor fv;
private boolean end;
public CheckFieldAdapter(final FieldVisitor fv) {
this.fv = fv;
}
public AnnotationVisitor visitAnnotation(
final String desc,
final boolean visible)
{
checkEnd();
CheckMethodAdapter.checkDesc(desc, false);
return new CheckAnnotationAdapter(fv.visitAnnotation(desc, visible));
}
public void visitAttribute(final Attribute attr) {
checkEnd();
if (attr == null) {
throw new IllegalArgumentException("Invalid attribute (must not be null)");
}
fv.visitAttribute(attr);
}
public void visitEnd() {
checkEnd();
end = true;
fv.visitEnd();
}
private void checkEnd() {
if (end) {
throw new IllegalStateException("Cannot call a visit method after visitEnd has been called");
}
}
}
| wxcandy/Mahjong | org/mockito/asm/util/CheckFieldAdapter.java | Java | mit | 2,946 |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventLogPermissionHolder
**
** Purpose:
** Internal class that defines the permissions that are used
** throughout the Event Log classes of this namespace.
**
============================================================*/
using System;
using System.Security.Permissions;
namespace System.Diagnostics.Eventing.Reader {
internal class EventLogPermissionHolder {
public EventLogPermissionHolder() {
}
public static EventLogPermission GetEventLogPermission() {
EventLogPermission logPermission = new EventLogPermission();
EventLogPermissionEntry permEntry =
new EventLogPermissionEntry(EventLogPermissionAccess.Administer, ".");
logPermission.PermissionEntries.Add(permEntry);
return logPermission;
}
}
}
| sekcheong/referencesource | System.Core/System/Diagnostics/Eventing/Reader/EventLogPermissionHolder.cs | C# | mit | 983 |
# GENERATED FROM XML -- DO NOT EDIT
URI: index.html.en
Content-Language: en
Content-type: text/html; charset=ISO-8859-1
URI: index.html.fr
Content-Language: fr
Content-type: text/html; charset=ISO-8859-1
URI: index.html.ko.euc-kr
Content-Language: ko
Content-type: text/html; charset=EUC-KR
URI: index.html.tr.utf8
Content-Language: tr
Content-type: text/html; charset=UTF-8
URI: index.html.zh-cn.utf8
Content-Language: zh-cn
Content-type: text/html; charset=UTF-8
| Dokaponteam/ITF_Project | xampp/apache/manual/misc/index.html | HTML | mit | 470 |
/*
* 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.catalina.loader;
public class Constants {
public static final String Package = "org.apache.catalina.loader";
}
| plumer/codana | tomcat_files/7.0.61/Constants (2).java | Java | mit | 945 |
/*
* Copyright 2009 The Apache Software Foundation
*
* 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.mybatis.generator.logging;
/**
* Defines the interface for creating Log implementations.
*
* @author Jeff Butler
*
*/
public interface AbstractLogFactory {
Log getLog(Class<?> aClass);
}
| NanYoMy/mybatis-generator | src/main/java/org/mybatis/generator/logging/AbstractLogFactory.java | Java | mit | 836 |
/*
Simple DirectMedia Layer
Copyright (C) 1997-2017 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../SDL_internal.h"
/* Useful functions and variables from SDL_pixel.c */
#include "SDL_blit.h"
/* Pixel format functions */
extern int SDL_InitFormat(SDL_PixelFormat * format, Uint32 pixel_format);
/* Blit mapping functions */
extern SDL_BlitMap *SDL_AllocBlitMap(void);
extern void SDL_InvalidateMap(SDL_BlitMap * map);
extern int SDL_MapSurface(SDL_Surface * src, SDL_Surface * dst);
extern void SDL_FreeBlitMap(SDL_BlitMap * map);
/* Miscellaneous functions */
extern int SDL_CalculatePitch(SDL_Surface * surface);
extern void SDL_DitherColors(SDL_Color * colors, int bpp);
extern Uint8 SDL_FindColor(SDL_Palette * pal, Uint8 r, Uint8 g, Uint8 b, Uint8 a);
/* vi: set ts=4 sw=4 expandtab: */
| cmaughan/imgui | zep/m3rdparty/sdl/src/video/SDL_pixels_c.h | C | mit | 1,650 |
<md-menu md-offset="40 25">
<div ng-click="$mdOpenMenu($event)" class="navbar-notification-container" ng-disabled="navbarNotificationController.getNotificationsCount() === 0">
<i class="fa fa-bell-o fa-2x navbar-notification-icon"></i>
<div class="navbar-notification-count" ng-if="navbarNotificationController.getNotificationsCount() > 0">
{{navbarNotificationController.getNotificationsCount()}}
</div>
</div>
<md-menu-content>
<md-menu-item layout="column" class="navbar-notification" ng-repeat="notification in navbarNotificationController.getNotifications()">
<div class="navbar-notification-title-{{notification.type}} navbar-notification-title" layout="row" layout-align="start center">
<i ng-if="!notification.icon"
ng-class="{'fa-exclamation-triangle' : (notification.type === 'warning' || notification.type === 'error'), 'fa-info-circle': notification.type === 'info'}"
class="fa fa-2x navbar-notification-title-icon"></i>
<i ng-if="notification.icon" class="fa {{notification.icon}} fa-2x navbar-notification-title-icon"></i>
<div>{{notification.title}}</div>
</div>
<div class="navbar-notification-content">
{{notification.content}}
</div>
</md-menu-item>
</md-menu-content>
</md-menu>
| Mirage20/che | dashboard/src/app/navbar/notification/navbar-notification.html | HTML | epl-1.0 | 1,313 |
/*
* Support for Intel Camera Imaging ISP subsystem.
*
* Copyright (c) 2010 - 2014 Intel Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU 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 __IA_CSS_ANR_HOST_H
#define __IA_CSS_ANR_HOST_H
#include "ia_css_anr_types.h"
#include "ia_css_anr_param.h"
extern const struct ia_css_anr_config default_anr_config;
void
ia_css_anr_encode(
struct sh_css_isp_anr_params *to,
const struct ia_css_anr_config *from);
void
ia_css_anr_dump(
const struct sh_css_isp_anr_params *anr,
unsigned level);
void
ia_css_anr_debug_dtrace(
const struct ia_css_anr_config *config, unsigned level)
;
#endif /* __IA_CSS_ANR_HOST_H */
| paulalesius/kernel-3.10.20-lenovo-tablet | drivers/external_drivers/camera/pci/atomisp2/css2401a0_v21_build/css/isp/kernels/anr/anr_1.0/ia_css_anr.host.h | C | gpl-2.0 | 1,276 |
/* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD 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, version 2.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file script_info_dummy.cpp Implementation of a dummy Script. */
#include "../stdafx.h"
#include <squirrel.h>
#include "../string_func.h"
#include "../strings_func.h"
#include "../safeguards.h"
/* The reason this exists in C++, is that a user can trash his ai/ or game/ dir,
* leaving no Scripts available. The complexity to solve this is insane, and
* therefore the alternative is used, and make sure there is always a Script
* available, no matter what the situation is. By defining it in C++, there
* is simply no way a user can delete it, and therefore safe to use. It has
* to be noted that this Script is complete invisible for the user, and impossible
* to select manual. It is a fail-over in case no Scripts are available.
*/
/** Run the dummy info.nut. */
void Script_CreateDummyInfo(HSQUIRRELVM vm, const char *type, const char *dir)
{
char dummy_script[4096];
char *dp = dummy_script;
dp += seprintf(dp, lastof(dummy_script), "class Dummy%s extends %sInfo {\n", type, type);
dp += seprintf(dp, lastof(dummy_script), "function GetAuthor() { return \"OpenTTD Developers Team\"; }\n");
dp += seprintf(dp, lastof(dummy_script), "function GetName() { return \"Dummy%s\"; }\n", type);
dp += seprintf(dp, lastof(dummy_script), "function GetShortName() { return \"DUMM\"; }\n");
dp += seprintf(dp, lastof(dummy_script), "function GetDescription() { return \"A Dummy %s that is loaded when your %s/ dir is empty\"; }\n", type, dir);
dp += seprintf(dp, lastof(dummy_script), "function GetVersion() { return 1; }\n");
dp += seprintf(dp, lastof(dummy_script), "function GetDate() { return \"2008-07-26\"; }\n");
dp += seprintf(dp, lastof(dummy_script), "function CreateInstance() { return \"Dummy%s\"; }\n", type);
dp += seprintf(dp, lastof(dummy_script), "} RegisterDummy%s(Dummy%s());\n", type, type);
const SQChar *sq_dummy_script = dummy_script;
sq_pushroottable(vm);
/* Load and run the script */
if (SQ_SUCCEEDED(sq_compilebuffer(vm, sq_dummy_script, strlen(sq_dummy_script), "dummy", SQTrue))) {
sq_push(vm, -2);
if (SQ_SUCCEEDED(sq_call(vm, 1, SQFalse, SQTrue))) {
sq_pop(vm, 1);
return;
}
}
NOT_REACHED();
}
/** Run the dummy AI and let it generate an error message. */
void Script_CreateDummy(HSQUIRRELVM vm, StringID string, const char *type)
{
/* We want to translate the error message.
* We do this in three steps:
* 1) We get the error message
*/
char error_message[1024];
GetString(error_message, string, lastof(error_message));
/* Make escapes for all quotes and slashes. */
char safe_error_message[1024];
char *q = safe_error_message;
for (const char *p = error_message; *p != '\0' && q < lastof(safe_error_message) - 2; p++, q++) {
if (*p == '"' || *p == '\\') *q++ = '\\';
*q = *p;
}
*q = '\0';
/* 2) We construct the AI's code. This is done by merging a header, body and footer */
char dummy_script[4096];
char *dp = dummy_script;
dp += seprintf(dp, lastof(dummy_script), "class Dummy%s extends %sController {\n function Start()\n {\n", type, type);
/* As special trick we need to split the error message on newlines and
* emit each newline as a separate error printing string. */
char *newline;
char *p = safe_error_message;
do {
newline = strchr(p, '\n');
if (newline != NULL) *newline = '\0';
dp += seprintf(dp, lastof(dummy_script), " %sLog.Error(\"%s\");\n", type, p);
p = newline + 1;
} while (newline != NULL);
dp = strecpy(dp, " }\n}\n", lastof(dummy_script));
/* 3) We translate the error message in the character format that Squirrel wants.
* We can use the fact that the wchar string printing also uses %s to print
* old style char strings, which is what was generated during the script generation. */
const SQChar *sq_dummy_script = dummy_script;
/* And finally we load and run the script */
sq_pushroottable(vm);
if (SQ_SUCCEEDED(sq_compilebuffer(vm, sq_dummy_script, strlen(sq_dummy_script), "dummy", SQTrue))) {
sq_push(vm, -2);
if (SQ_SUCCEEDED(sq_call(vm, 1, SQFalse, SQTrue))) {
sq_pop(vm, 1);
return;
}
}
NOT_REACHED();
}
| alex34567/openttd-emscripten | src/script/script_info_dummy.cpp | C++ | gpl-2.0 | 4,715 |
/*
* LPC32xx SSP interface (SPI mode)
*
* (C) Copyright 2014 DENX Software Engineering GmbH
* Written-by: Albert ARIBAUD <albert.aribaud@3adev.fr>
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <linux/compat.h>
#include <asm/io.h>
#include <malloc.h>
#include <spi.h>
#include <asm/arch/clk.h>
/* SSP chip registers */
struct ssp_regs {
u32 cr0;
u32 cr1;
u32 data;
u32 sr;
u32 cpsr;
u32 imsc;
u32 ris;
u32 mis;
u32 icr;
u32 dmacr;
};
/* CR1 register defines */
#define SSP_CR1_SSP_ENABLE 0x0002
/* SR register defines */
#define SSP_SR_TNF 0x0002
/* SSP status RX FIFO not empty bit */
#define SSP_SR_RNE 0x0004
/* lpc32xx spi slave */
struct lpc32xx_spi_slave {
struct spi_slave slave;
struct ssp_regs *regs;
};
static inline struct lpc32xx_spi_slave *to_lpc32xx_spi_slave(
struct spi_slave *slave)
{
return container_of(slave, struct lpc32xx_spi_slave, slave);
}
/* spi_init is called during boot when CONFIG_CMD_SPI is defined */
void spi_init(void)
{
/*
* nothing to do: clocking was enabled in lpc32xx_ssp_enable()
* and configuration will be done in spi_setup_slave()
*/
}
/* the following is called in sequence by do_spi_xfer() */
struct spi_slave *spi_setup_slave(uint bus, uint cs, uint max_hz, uint mode)
{
struct lpc32xx_spi_slave *lslave;
/* we only set up SSP0 for now, so ignore bus */
if (mode & SPI_3WIRE) {
error("3-wire mode not supported");
return NULL;
}
if (mode & SPI_SLAVE) {
error("slave mode not supported\n");
return NULL;
}
if (mode & SPI_PREAMBLE) {
error("preamble byte skipping not supported\n");
return NULL;
}
lslave = spi_alloc_slave(struct lpc32xx_spi_slave, bus, cs);
if (!lslave) {
printf("SPI_error: Fail to allocate lpc32xx_spi_slave\n");
return NULL;
}
lslave->regs = (struct ssp_regs *)SSP0_BASE;
/*
* 8 bit frame, SPI fmt, 500kbps -> clock divider is 26.
* Set SCR to 0 and CPSDVSR to 26.
*/
writel(0x7, &lslave->regs->cr0); /* 8-bit chunks, SPI, 1 clk/bit */
writel(26, &lslave->regs->cpsr); /* SSP clock = HCLK/26 = 500kbps */
writel(0, &lslave->regs->imsc); /* do not raise any interrupts */
writel(0, &lslave->regs->icr); /* clear any pending interrupt */
writel(0, &lslave->regs->dmacr); /* do not do DMAs */
writel(SSP_CR1_SSP_ENABLE, &lslave->regs->cr1); /* enable SSP0 */
return &lslave->slave;
}
void spi_free_slave(struct spi_slave *slave)
{
struct lpc32xx_spi_slave *lslave = to_lpc32xx_spi_slave(slave);
debug("(lpc32xx) spi_free_slave: 0x%08x\n", (u32)lslave);
free(lslave);
}
int spi_claim_bus(struct spi_slave *slave)
{
/* only one bus and slave so far, always available */
return 0;
}
int spi_xfer(struct spi_slave *slave, unsigned int bitlen,
const void *dout, void *din, unsigned long flags)
{
struct lpc32xx_spi_slave *lslave = to_lpc32xx_spi_slave(slave);
int bytelen = bitlen >> 3;
int idx_out = 0;
int idx_in = 0;
int start_time;
start_time = get_timer(0);
while ((idx_out < bytelen) || (idx_in < bytelen)) {
int status = readl(&lslave->regs->sr);
if ((idx_out < bytelen) && (status & SSP_SR_TNF))
writel(((u8 *)dout)[idx_out++], &lslave->regs->data);
if ((idx_in < bytelen) && (status & status & SSP_SR_RNE))
((u8 *)din)[idx_in++] = readl(&lslave->regs->data);
if (get_timer(start_time) >= CONFIG_LPC32XX_SSP_TIMEOUT)
return -1;
}
return 0;
}
void spi_release_bus(struct spi_slave *slave)
{
/* do nothing */
}
| mdxy2010/forlinux-ok6410 | u-boot15/drivers/spi/lpc32xx_ssp.c | C | gpl-2.0 | 3,430 |
class CfgUnitInsignia {
class ACE_insignia_logo {
displayName = "ACE3";
author = CSTRING(ACETeam);
texture = PATHTOF(data\Insignia_ace3logo_ca.paa);
textureVehicle = "";
};
class ACE_insignia_banana {
displayName = "ABE3";
author = CSTRING(ACETeam);
texture = PATHTOF(data\insignia_banana_ca.paa);
textureVehicle = "";
};
};
| MikeMatrix/ACE3 | addons/common/CfgUnitInsignia.hpp | C++ | gpl-2.0 | 406 |
/*
* TI OMAP I2C master mode driver
*
* Copyright (C) 2003 MontaVista Software, Inc.
* Copyright (C) 2004 Texas Instruments.
*
* Updated to work with multiple I2C interfaces on 24xx by
* Tony Lindgren <tony@atomide.com> and Imre Deak <imre.deak@nokia.com>
* Copyright (C) 2005 Nokia Corporation
*
* Cleaned up by Juha Yrjölä <juha.yrjola@nokia.com>
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/completion.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <asm/io.h>
/* timeout waiting for the controller to respond */
#define OMAP_I2C_TIMEOUT (msecs_to_jiffies(1000))
#define OMAP_I2C_REV_REG 0x00
#define OMAP_I2C_IE_REG 0x04
#define OMAP_I2C_STAT_REG 0x08
#define OMAP_I2C_IV_REG 0x0c
#define OMAP_I2C_SYSS_REG 0x10
#define OMAP_I2C_BUF_REG 0x14
#define OMAP_I2C_CNT_REG 0x18
#define OMAP_I2C_DATA_REG 0x1c
#define OMAP_I2C_SYSC_REG 0x20
#define OMAP_I2C_CON_REG 0x24
#define OMAP_I2C_OA_REG 0x28
#define OMAP_I2C_SA_REG 0x2c
#define OMAP_I2C_PSC_REG 0x30
#define OMAP_I2C_SCLL_REG 0x34
#define OMAP_I2C_SCLH_REG 0x38
#define OMAP_I2C_SYSTEST_REG 0x3c
/* I2C Interrupt Enable Register (OMAP_I2C_IE): */
#define OMAP_I2C_IE_XRDY (1 << 4) /* TX data ready int enable */
#define OMAP_I2C_IE_RRDY (1 << 3) /* RX data ready int enable */
#define OMAP_I2C_IE_ARDY (1 << 2) /* Access ready int enable */
#define OMAP_I2C_IE_NACK (1 << 1) /* No ack interrupt enable */
#define OMAP_I2C_IE_AL (1 << 0) /* Arbitration lost int ena */
/* I2C Status Register (OMAP_I2C_STAT): */
#define OMAP_I2C_STAT_SBD (1 << 15) /* Single byte data */
#define OMAP_I2C_STAT_BB (1 << 12) /* Bus busy */
#define OMAP_I2C_STAT_ROVR (1 << 11) /* Receive overrun */
#define OMAP_I2C_STAT_XUDF (1 << 10) /* Transmit underflow */
#define OMAP_I2C_STAT_AAS (1 << 9) /* Address as slave */
#define OMAP_I2C_STAT_AD0 (1 << 8) /* Address zero */
#define OMAP_I2C_STAT_XRDY (1 << 4) /* Transmit data ready */
#define OMAP_I2C_STAT_RRDY (1 << 3) /* Receive data ready */
#define OMAP_I2C_STAT_ARDY (1 << 2) /* Register access ready */
#define OMAP_I2C_STAT_NACK (1 << 1) /* No ack interrupt enable */
#define OMAP_I2C_STAT_AL (1 << 0) /* Arbitration lost int ena */
/* I2C Buffer Configuration Register (OMAP_I2C_BUF): */
#define OMAP_I2C_BUF_RDMA_EN (1 << 15) /* RX DMA channel enable */
#define OMAP_I2C_BUF_XDMA_EN (1 << 7) /* TX DMA channel enable */
/* I2C Configuration Register (OMAP_I2C_CON): */
#define OMAP_I2C_CON_EN (1 << 15) /* I2C module enable */
#define OMAP_I2C_CON_BE (1 << 14) /* Big endian mode */
#define OMAP_I2C_CON_STB (1 << 11) /* Start byte mode (master) */
#define OMAP_I2C_CON_MST (1 << 10) /* Master/slave mode */
#define OMAP_I2C_CON_TRX (1 << 9) /* TX/RX mode (master only) */
#define OMAP_I2C_CON_XA (1 << 8) /* Expand address */
#define OMAP_I2C_CON_RM (1 << 2) /* Repeat mode (master only) */
#define OMAP_I2C_CON_STP (1 << 1) /* Stop cond (master only) */
#define OMAP_I2C_CON_STT (1 << 0) /* Start condition (master) */
/* I2C System Test Register (OMAP_I2C_SYSTEST): */
#ifdef DEBUG
#define OMAP_I2C_SYSTEST_ST_EN (1 << 15) /* System test enable */
#define OMAP_I2C_SYSTEST_FREE (1 << 14) /* Free running mode */
#define OMAP_I2C_SYSTEST_TMODE_MASK (3 << 12) /* Test mode select */
#define OMAP_I2C_SYSTEST_TMODE_SHIFT (12) /* Test mode select */
#define OMAP_I2C_SYSTEST_SCL_I (1 << 3) /* SCL line sense in */
#define OMAP_I2C_SYSTEST_SCL_O (1 << 2) /* SCL line drive out */
#define OMAP_I2C_SYSTEST_SDA_I (1 << 1) /* SDA line sense in */
#define OMAP_I2C_SYSTEST_SDA_O (1 << 0) /* SDA line drive out */
#endif
/* I2C System Status register (OMAP_I2C_SYSS): */
#define OMAP_I2C_SYSS_RDONE (1 << 0) /* Reset Done */
/* I2C System Configuration Register (OMAP_I2C_SYSC): */
#define OMAP_I2C_SYSC_SRST (1 << 1) /* Soft Reset */
/* REVISIT: Use platform_data instead of module parameters */
/* Fast Mode = 400 kHz, Standard = 100 kHz */
static int clock = 100; /* Default: 100 kHz */
module_param(clock, int, 0);
MODULE_PARM_DESC(clock, "Set I2C clock in kHz: 400=fast mode (default == 100)");
struct omap_i2c_dev {
struct device *dev;
void __iomem *base; /* virtual */
int irq;
struct clk *iclk; /* Interface clock */
struct clk *fclk; /* Functional clock */
struct completion cmd_complete;
struct resource *ioarea;
u16 cmd_err;
u8 *buf;
size_t buf_len;
struct i2c_adapter adapter;
unsigned rev1:1;
};
static inline void omap_i2c_write_reg(struct omap_i2c_dev *i2c_dev,
int reg, u16 val)
{
__raw_writew(val, i2c_dev->base + reg);
}
static inline u16 omap_i2c_read_reg(struct omap_i2c_dev *i2c_dev, int reg)
{
return __raw_readw(i2c_dev->base + reg);
}
static int omap_i2c_get_clocks(struct omap_i2c_dev *dev)
{
if (cpu_is_omap16xx() || cpu_is_omap24xx()) {
dev->iclk = clk_get(dev->dev, "i2c_ick");
if (IS_ERR(dev->iclk)) {
dev->iclk = NULL;
return -ENODEV;
}
}
dev->fclk = clk_get(dev->dev, "i2c_fck");
if (IS_ERR(dev->fclk)) {
if (dev->iclk != NULL) {
clk_put(dev->iclk);
dev->iclk = NULL;
}
dev->fclk = NULL;
return -ENODEV;
}
return 0;
}
static void omap_i2c_put_clocks(struct omap_i2c_dev *dev)
{
clk_put(dev->fclk);
dev->fclk = NULL;
if (dev->iclk != NULL) {
clk_put(dev->iclk);
dev->iclk = NULL;
}
}
static void omap_i2c_enable_clocks(struct omap_i2c_dev *dev)
{
if (dev->iclk != NULL)
clk_enable(dev->iclk);
clk_enable(dev->fclk);
}
static void omap_i2c_disable_clocks(struct omap_i2c_dev *dev)
{
if (dev->iclk != NULL)
clk_disable(dev->iclk);
clk_disable(dev->fclk);
}
static int omap_i2c_init(struct omap_i2c_dev *dev)
{
u16 psc = 0;
unsigned long fclk_rate = 12000000;
unsigned long timeout;
if (!dev->rev1) {
omap_i2c_write_reg(dev, OMAP_I2C_SYSC_REG, OMAP_I2C_SYSC_SRST);
/* For some reason we need to set the EN bit before the
* reset done bit gets set. */
timeout = jiffies + OMAP_I2C_TIMEOUT;
omap_i2c_write_reg(dev, OMAP_I2C_CON_REG, OMAP_I2C_CON_EN);
while (!(omap_i2c_read_reg(dev, OMAP_I2C_SYSS_REG) &
OMAP_I2C_SYSS_RDONE)) {
if (time_after(jiffies, timeout)) {
dev_warn(dev->dev, "timeout waiting "
"for controller reset\n");
return -ETIMEDOUT;
}
msleep(1);
}
}
omap_i2c_write_reg(dev, OMAP_I2C_CON_REG, 0);
if (cpu_class_is_omap1()) {
struct clk *armxor_ck;
armxor_ck = clk_get(NULL, "armxor_ck");
if (IS_ERR(armxor_ck))
dev_warn(dev->dev, "Could not get armxor_ck\n");
else {
fclk_rate = clk_get_rate(armxor_ck);
clk_put(armxor_ck);
}
/* TRM for 5912 says the I2C clock must be prescaled to be
* between 7 - 12 MHz. The XOR input clock is typically
* 12, 13 or 19.2 MHz. So we should have code that produces:
*
* XOR MHz Divider Prescaler
* 12 1 0
* 13 2 1
* 19.2 2 1
*/
if (fclk_rate > 12000000)
psc = fclk_rate / 12000000;
}
/* Setup clock prescaler to obtain approx 12MHz I2C module clock: */
omap_i2c_write_reg(dev, OMAP_I2C_PSC_REG, psc);
/* Program desired operating rate */
fclk_rate /= (psc + 1) * 1000;
if (psc > 2)
psc = 2;
omap_i2c_write_reg(dev, OMAP_I2C_SCLL_REG,
fclk_rate / (clock * 2) - 7 + psc);
omap_i2c_write_reg(dev, OMAP_I2C_SCLH_REG,
fclk_rate / (clock * 2) - 7 + psc);
/* Take the I2C module out of reset: */
omap_i2c_write_reg(dev, OMAP_I2C_CON_REG, OMAP_I2C_CON_EN);
/* Enable interrupts */
omap_i2c_write_reg(dev, OMAP_I2C_IE_REG,
(OMAP_I2C_IE_XRDY | OMAP_I2C_IE_RRDY |
OMAP_I2C_IE_ARDY | OMAP_I2C_IE_NACK |
OMAP_I2C_IE_AL));
return 0;
}
/*
* Waiting on Bus Busy
*/
static int omap_i2c_wait_for_bb(struct omap_i2c_dev *dev)
{
unsigned long timeout;
timeout = jiffies + OMAP_I2C_TIMEOUT;
while (omap_i2c_read_reg(dev, OMAP_I2C_STAT_REG) & OMAP_I2C_STAT_BB) {
if (time_after(jiffies, timeout)) {
dev_warn(dev->dev, "timeout waiting for bus ready\n");
return -ETIMEDOUT;
}
msleep(1);
}
return 0;
}
/*
* Low level master read/write transaction.
*/
static int omap_i2c_xfer_msg(struct i2c_adapter *adap,
struct i2c_msg *msg, int stop)
{
struct omap_i2c_dev *dev = i2c_get_adapdata(adap);
int r;
u16 w;
dev_dbg(dev->dev, "addr: 0x%04x, len: %d, flags: 0x%x, stop: %d\n",
msg->addr, msg->len, msg->flags, stop);
if (msg->len == 0)
return -EINVAL;
omap_i2c_write_reg(dev, OMAP_I2C_SA_REG, msg->addr);
/* REVISIT: Could the STB bit of I2C_CON be used with probing? */
dev->buf = msg->buf;
dev->buf_len = msg->len;
omap_i2c_write_reg(dev, OMAP_I2C_CNT_REG, dev->buf_len);
init_completion(&dev->cmd_complete);
dev->cmd_err = 0;
w = OMAP_I2C_CON_EN | OMAP_I2C_CON_MST | OMAP_I2C_CON_STT;
if (msg->flags & I2C_M_TEN)
w |= OMAP_I2C_CON_XA;
if (!(msg->flags & I2C_M_RD))
w |= OMAP_I2C_CON_TRX;
if (stop)
w |= OMAP_I2C_CON_STP;
omap_i2c_write_reg(dev, OMAP_I2C_CON_REG, w);
r = wait_for_completion_interruptible_timeout(&dev->cmd_complete,
OMAP_I2C_TIMEOUT);
dev->buf_len = 0;
if (r < 0)
return r;
if (r == 0) {
dev_err(dev->dev, "controller timed out\n");
omap_i2c_init(dev);
return -ETIMEDOUT;
}
if (likely(!dev->cmd_err))
return 0;
/* We have an error */
if (dev->cmd_err & (OMAP_I2C_STAT_AL | OMAP_I2C_STAT_ROVR |
OMAP_I2C_STAT_XUDF)) {
omap_i2c_init(dev);
return -EIO;
}
if (dev->cmd_err & OMAP_I2C_STAT_NACK) {
if (msg->flags & I2C_M_IGNORE_NAK)
return 0;
if (stop) {
w = omap_i2c_read_reg(dev, OMAP_I2C_CON_REG);
w |= OMAP_I2C_CON_STP;
omap_i2c_write_reg(dev, OMAP_I2C_CON_REG, w);
}
return -EREMOTEIO;
}
return -EIO;
}
/*
* Prepare controller for a transaction and call omap_i2c_xfer_msg
* to do the work during IRQ processing.
*/
static int
omap_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msgs[], int num)
{
struct omap_i2c_dev *dev = i2c_get_adapdata(adap);
int i;
int r;
omap_i2c_enable_clocks(dev);
/* REVISIT: initialize and use adap->retries. This is an optional
* feature */
if ((r = omap_i2c_wait_for_bb(dev)) < 0)
goto out;
for (i = 0; i < num; i++) {
r = omap_i2c_xfer_msg(adap, &msgs[i], (i == (num - 1)));
if (r != 0)
break;
}
if (r == 0)
r = num;
out:
omap_i2c_disable_clocks(dev);
return r;
}
static u32
omap_i2c_func(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C | (I2C_FUNC_SMBUS_EMUL & ~I2C_FUNC_SMBUS_QUICK);
}
static inline void
omap_i2c_complete_cmd(struct omap_i2c_dev *dev, u16 err)
{
dev->cmd_err |= err;
complete(&dev->cmd_complete);
}
static inline void
omap_i2c_ack_stat(struct omap_i2c_dev *dev, u16 stat)
{
omap_i2c_write_reg(dev, OMAP_I2C_STAT_REG, stat);
}
static irqreturn_t
omap_i2c_rev1_isr(int this_irq, void *dev_id)
{
struct omap_i2c_dev *dev = dev_id;
u16 iv, w;
iv = omap_i2c_read_reg(dev, OMAP_I2C_IV_REG);
switch (iv) {
case 0x00: /* None */
break;
case 0x01: /* Arbitration lost */
dev_err(dev->dev, "Arbitration lost\n");
omap_i2c_complete_cmd(dev, OMAP_I2C_STAT_AL);
break;
case 0x02: /* No acknowledgement */
omap_i2c_complete_cmd(dev, OMAP_I2C_STAT_NACK);
omap_i2c_write_reg(dev, OMAP_I2C_CON_REG, OMAP_I2C_CON_STP);
break;
case 0x03: /* Register access ready */
omap_i2c_complete_cmd(dev, 0);
break;
case 0x04: /* Receive data ready */
if (dev->buf_len) {
w = omap_i2c_read_reg(dev, OMAP_I2C_DATA_REG);
*dev->buf++ = w;
dev->buf_len--;
if (dev->buf_len) {
*dev->buf++ = w >> 8;
dev->buf_len--;
}
} else
dev_err(dev->dev, "RRDY IRQ while no data requested\n");
break;
case 0x05: /* Transmit data ready */
if (dev->buf_len) {
w = *dev->buf++;
dev->buf_len--;
if (dev->buf_len) {
w |= *dev->buf++ << 8;
dev->buf_len--;
}
omap_i2c_write_reg(dev, OMAP_I2C_DATA_REG, w);
} else
dev_err(dev->dev, "XRDY IRQ while no data to send\n");
break;
default:
return IRQ_NONE;
}
return IRQ_HANDLED;
}
static irqreturn_t
omap_i2c_isr(int this_irq, void *dev_id)
{
struct omap_i2c_dev *dev = dev_id;
u16 bits;
u16 stat, w;
int count = 0;
bits = omap_i2c_read_reg(dev, OMAP_I2C_IE_REG);
while ((stat = (omap_i2c_read_reg(dev, OMAP_I2C_STAT_REG))) & bits) {
dev_dbg(dev->dev, "IRQ (ISR = 0x%04x)\n", stat);
if (count++ == 100) {
dev_warn(dev->dev, "Too much work in one IRQ\n");
break;
}
omap_i2c_write_reg(dev, OMAP_I2C_STAT_REG, stat);
if (stat & OMAP_I2C_STAT_ARDY) {
omap_i2c_complete_cmd(dev, 0);
continue;
}
if (stat & OMAP_I2C_STAT_RRDY) {
w = omap_i2c_read_reg(dev, OMAP_I2C_DATA_REG);
if (dev->buf_len) {
*dev->buf++ = w;
dev->buf_len--;
if (dev->buf_len) {
*dev->buf++ = w >> 8;
dev->buf_len--;
}
} else
dev_err(dev->dev, "RRDY IRQ while no data "
"requested\n");
omap_i2c_ack_stat(dev, OMAP_I2C_STAT_RRDY);
continue;
}
if (stat & OMAP_I2C_STAT_XRDY) {
w = 0;
if (dev->buf_len) {
w = *dev->buf++;
dev->buf_len--;
if (dev->buf_len) {
w |= *dev->buf++ << 8;
dev->buf_len--;
}
} else
dev_err(dev->dev, "XRDY IRQ while no "
"data to send\n");
omap_i2c_write_reg(dev, OMAP_I2C_DATA_REG, w);
omap_i2c_ack_stat(dev, OMAP_I2C_STAT_XRDY);
continue;
}
if (stat & OMAP_I2C_STAT_ROVR) {
dev_err(dev->dev, "Receive overrun\n");
dev->cmd_err |= OMAP_I2C_STAT_ROVR;
}
if (stat & OMAP_I2C_STAT_XUDF) {
dev_err(dev->dev, "Transmit overflow\n");
dev->cmd_err |= OMAP_I2C_STAT_XUDF;
}
if (stat & OMAP_I2C_STAT_NACK) {
omap_i2c_complete_cmd(dev, OMAP_I2C_STAT_NACK);
omap_i2c_write_reg(dev, OMAP_I2C_CON_REG,
OMAP_I2C_CON_STP);
}
if (stat & OMAP_I2C_STAT_AL) {
dev_err(dev->dev, "Arbitration lost\n");
omap_i2c_complete_cmd(dev, OMAP_I2C_STAT_AL);
}
}
return count ? IRQ_HANDLED : IRQ_NONE;
}
static const struct i2c_algorithm omap_i2c_algo = {
.master_xfer = omap_i2c_xfer,
.functionality = omap_i2c_func,
};
static int
omap_i2c_probe(struct platform_device *pdev)
{
struct omap_i2c_dev *dev;
struct i2c_adapter *adap;
struct resource *mem, *irq, *ioarea;
int r;
/* NOTE: driver uses the static register mapping */
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem) {
dev_err(&pdev->dev, "no mem resource?\n");
return -ENODEV;
}
irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!irq) {
dev_err(&pdev->dev, "no irq resource?\n");
return -ENODEV;
}
ioarea = request_mem_region(mem->start, (mem->end - mem->start) + 1,
pdev->name);
if (!ioarea) {
dev_err(&pdev->dev, "I2C region already claimed\n");
return -EBUSY;
}
if (clock > 200)
clock = 400; /* Fast mode */
else
clock = 100; /* Standard mode */
dev = kzalloc(sizeof(struct omap_i2c_dev), GFP_KERNEL);
if (!dev) {
r = -ENOMEM;
goto err_release_region;
}
dev->dev = &pdev->dev;
dev->irq = irq->start;
dev->base = (void __iomem *) IO_ADDRESS(mem->start);
platform_set_drvdata(pdev, dev);
if ((r = omap_i2c_get_clocks(dev)) != 0)
goto err_free_mem;
omap_i2c_enable_clocks(dev);
if (cpu_is_omap15xx())
dev->rev1 = omap_i2c_read_reg(dev, OMAP_I2C_REV_REG) < 0x20;
/* reset ASAP, clearing any IRQs */
omap_i2c_init(dev);
r = request_irq(dev->irq, dev->rev1 ? omap_i2c_rev1_isr : omap_i2c_isr,
0, pdev->name, dev);
if (r) {
dev_err(dev->dev, "failure requesting irq %i\n", dev->irq);
goto err_unuse_clocks;
}
r = omap_i2c_read_reg(dev, OMAP_I2C_REV_REG) & 0xff;
dev_info(dev->dev, "bus %d rev%d.%d at %d kHz\n",
pdev->id, r >> 4, r & 0xf, clock);
adap = &dev->adapter;
i2c_set_adapdata(adap, dev);
adap->owner = THIS_MODULE;
adap->class = I2C_CLASS_HWMON;
strncpy(adap->name, "OMAP I2C adapter", sizeof(adap->name));
adap->algo = &omap_i2c_algo;
adap->dev.parent = &pdev->dev;
/* i2c device drivers may be active on return from add_adapter() */
adap->nr = pdev->id;
r = i2c_add_numbered_adapter(adap);
if (r) {
dev_err(dev->dev, "failure adding adapter\n");
goto err_free_irq;
}
omap_i2c_disable_clocks(dev);
return 0;
err_free_irq:
free_irq(dev->irq, dev);
err_unuse_clocks:
omap_i2c_write_reg(dev, OMAP_I2C_CON_REG, 0);
omap_i2c_disable_clocks(dev);
omap_i2c_put_clocks(dev);
err_free_mem:
platform_set_drvdata(pdev, NULL);
kfree(dev);
err_release_region:
release_mem_region(mem->start, (mem->end - mem->start) + 1);
return r;
}
static int
omap_i2c_remove(struct platform_device *pdev)
{
struct omap_i2c_dev *dev = platform_get_drvdata(pdev);
struct resource *mem;
platform_set_drvdata(pdev, NULL);
free_irq(dev->irq, dev);
i2c_del_adapter(&dev->adapter);
omap_i2c_write_reg(dev, OMAP_I2C_CON_REG, 0);
omap_i2c_put_clocks(dev);
kfree(dev);
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(mem->start, (mem->end - mem->start) + 1);
return 0;
}
static struct platform_driver omap_i2c_driver = {
.probe = omap_i2c_probe,
.remove = omap_i2c_remove,
.driver = {
.name = "i2c_omap",
.owner = THIS_MODULE,
},
};
/* I2C may be needed to bring up other drivers */
static int __init
omap_i2c_init_driver(void)
{
return platform_driver_register(&omap_i2c_driver);
}
subsys_initcall(omap_i2c_init_driver);
static void __exit omap_i2c_exit_driver(void)
{
platform_driver_unregister(&omap_i2c_driver);
}
module_exit(omap_i2c_exit_driver);
MODULE_AUTHOR("MontaVista Software, Inc. (and others)");
MODULE_DESCRIPTION("TI OMAP I2C bus adapter");
MODULE_LICENSE("GPL");
| janrinze/loox7xxport.loox2624 | drivers/i2c/busses/i2c-omap.c | C | gpl-2.0 | 18,070 |
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_ASM_CODEBUFFER_HPP
#define SHARE_VM_ASM_CODEBUFFER_HPP
#include "code/oopRecorder.hpp"
#include "code/relocInfo.hpp"
class CodeStrings;
class PhaseCFG;
class Compile;
class BufferBlob;
class CodeBuffer;
class Label;
class CodeOffsets: public StackObj {
public:
enum Entries { Entry,
Verified_Entry,
Frame_Complete, // Offset in the code where the frame setup is (for forte stackwalks) is complete
OSR_Entry,
Dtrace_trap = OSR_Entry, // dtrace probes can never have an OSR entry so reuse it
Exceptions, // Offset where exception handler lives
Deopt, // Offset where deopt handler lives
DeoptMH, // Offset where MethodHandle deopt handler lives
UnwindHandler, // Offset to default unwind handler
max_Entries };
// special value to note codeBlobs where profile (forte) stack walking is
// always dangerous and suspect.
enum { frame_never_safe = -1 };
private:
int _values[max_Entries];
public:
CodeOffsets() {
_values[Entry ] = 0;
_values[Verified_Entry] = 0;
_values[Frame_Complete] = frame_never_safe;
_values[OSR_Entry ] = 0;
_values[Exceptions ] = -1;
_values[Deopt ] = -1;
_values[DeoptMH ] = -1;
_values[UnwindHandler ] = -1;
}
int value(Entries e) { return _values[e]; }
void set_value(Entries e, int val) { _values[e] = val; }
};
// This class represents a stream of code and associated relocations.
// There are a few in each CodeBuffer.
// They are filled concurrently, and concatenated at the end.
class CodeSection VALUE_OBJ_CLASS_SPEC {
friend class CodeBuffer;
public:
typedef int csize_t; // code size type; would be size_t except for history
private:
address _start; // first byte of contents (instructions)
address _mark; // user mark, usually an instruction beginning
address _end; // current end address
address _limit; // last possible (allocated) end address
relocInfo* _locs_start; // first byte of relocation information
relocInfo* _locs_end; // first byte after relocation information
relocInfo* _locs_limit; // first byte after relocation information buf
address _locs_point; // last relocated position (grows upward)
bool _locs_own; // did I allocate the locs myself?
bool _frozen; // no more expansion of this section
char _index; // my section number (SECT_INST, etc.)
CodeBuffer* _outer; // enclosing CodeBuffer
// (Note: _locs_point used to be called _last_reloc_offset.)
CodeSection() {
_start = NULL;
_mark = NULL;
_end = NULL;
_limit = NULL;
_locs_start = NULL;
_locs_end = NULL;
_locs_limit = NULL;
_locs_point = NULL;
_locs_own = false;
_frozen = false;
debug_only(_index = (char)-1);
debug_only(_outer = (CodeBuffer*)badAddress);
}
void initialize_outer(CodeBuffer* outer, int index) {
_outer = outer;
_index = index;
}
void initialize(address start, csize_t size = 0) {
assert(_start == NULL, "only one init step, please");
_start = start;
_mark = NULL;
_end = start;
_limit = start + size;
_locs_point = start;
}
void initialize_locs(int locs_capacity);
void expand_locs(int new_capacity);
void initialize_locs_from(const CodeSection* source_cs);
// helper for CodeBuffer::expand()
void take_over_code_from(CodeSection* cs) {
_start = cs->_start;
_mark = cs->_mark;
_end = cs->_end;
_limit = cs->_limit;
_locs_point = cs->_locs_point;
}
public:
address start() const { return _start; }
address mark() const { return _mark; }
address end() const { return _end; }
address limit() const { return _limit; }
csize_t size() const { return (csize_t)(_end - _start); }
csize_t mark_off() const { assert(_mark != NULL, "not an offset");
return (csize_t)(_mark - _start); }
csize_t capacity() const { return (csize_t)(_limit - _start); }
csize_t remaining() const { return (csize_t)(_limit - _end); }
relocInfo* locs_start() const { return _locs_start; }
relocInfo* locs_end() const { return _locs_end; }
int locs_count() const { return (int)(_locs_end - _locs_start); }
relocInfo* locs_limit() const { return _locs_limit; }
address locs_point() const { return _locs_point; }
csize_t locs_point_off() const{ return (csize_t)(_locs_point - _start); }
csize_t locs_capacity() const { return (csize_t)(_locs_limit - _locs_start); }
csize_t locs_remaining()const { return (csize_t)(_locs_limit - _locs_end); }
int index() const { return _index; }
bool is_allocated() const { return _start != NULL; }
bool is_empty() const { return _start == _end; }
bool is_frozen() const { return _frozen; }
bool has_locs() const { return _locs_end != NULL; }
CodeBuffer* outer() const { return _outer; }
// is a given address in this section? (2nd version is end-inclusive)
bool contains(address pc) const { return pc >= _start && pc < _end; }
bool contains2(address pc) const { return pc >= _start && pc <= _end; }
bool allocates(address pc) const { return pc >= _start && pc < _limit; }
bool allocates2(address pc) const { return pc >= _start && pc <= _limit; }
void set_end(address pc) { assert(allocates2(pc), err_msg("not in CodeBuffer memory: " PTR_FORMAT " <= " PTR_FORMAT " <= " PTR_FORMAT, _start, pc, _limit)); _end = pc; }
void set_mark(address pc) { assert(contains2(pc), "not in codeBuffer");
_mark = pc; }
void set_mark_off(int offset) { assert(contains2(offset+_start),"not in codeBuffer");
_mark = offset + _start; }
void set_mark() { _mark = _end; }
void clear_mark() { _mark = NULL; }
void set_locs_end(relocInfo* p) {
assert(p <= locs_limit(), "locs data fits in allocated buffer");
_locs_end = p;
}
void set_locs_point(address pc) {
assert(pc >= locs_point(), "relocation addr may not decrease");
assert(allocates2(pc), "relocation addr must be in this section");
_locs_point = pc;
}
// Code emission
void emit_int8 ( int8_t x) { *((int8_t*) end()) = x; set_end(end() + sizeof(int8_t)); }
void emit_int16( int16_t x) { *((int16_t*) end()) = x; set_end(end() + sizeof(int16_t)); }
void emit_int32( int32_t x) { *((int32_t*) end()) = x; set_end(end() + sizeof(int32_t)); }
void emit_int64( int64_t x) { *((int64_t*) end()) = x; set_end(end() + sizeof(int64_t)); }
void emit_float( jfloat x) { *((jfloat*) end()) = x; set_end(end() + sizeof(jfloat)); }
void emit_double(jdouble x) { *((jdouble*) end()) = x; set_end(end() + sizeof(jdouble)); }
void emit_address(address x) { *((address*) end()) = x; set_end(end() + sizeof(address)); }
// Share a scratch buffer for relocinfo. (Hacky; saves a resource allocation.)
void initialize_shared_locs(relocInfo* buf, int length);
// Manage labels and their addresses.
address target(Label& L, address branch_pc);
// Emit a relocation.
void relocate(address at, RelocationHolder const& rspec, int format = 0);
void relocate(address at, relocInfo::relocType rtype, int format = 0) {
if (rtype != relocInfo::none)
relocate(at, Relocation::spec_simple(rtype), format);
}
// alignment requirement for starting offset
// Requirements are that the instruction area and the
// stubs area must start on CodeEntryAlignment, and
// the ctable on sizeof(jdouble)
int alignment() const { return MAX2((int)sizeof(jdouble), (int)CodeEntryAlignment); }
// Slop between sections, used only when allocating temporary BufferBlob buffers.
static csize_t end_slop() { return MAX2((int)sizeof(jdouble), (int)CodeEntryAlignment); }
csize_t align_at_start(csize_t off) const { return (csize_t) align_size_up(off, alignment()); }
// Mark a section frozen. Assign its remaining space to
// the following section. It will never expand after this point.
inline void freeze(); // { _outer->freeze_section(this); }
// Ensure there's enough space left in the current section.
// Return true if there was an expansion.
bool maybe_expand_to_ensure_remaining(csize_t amount);
#ifndef PRODUCT
void decode();
void dump();
void print(const char* name);
#endif //PRODUCT
};
class CodeString;
class CodeStrings VALUE_OBJ_CLASS_SPEC {
private:
#ifndef PRODUCT
CodeString* _strings;
#endif
CodeString* find(intptr_t offset) const;
CodeString* find_last(intptr_t offset) const;
public:
CodeStrings() {
#ifndef PRODUCT
_strings = NULL;
#endif
}
const char* add_string(const char * string) PRODUCT_RETURN_(return NULL;);
void add_comment(intptr_t offset, const char * comment) PRODUCT_RETURN;
void print_block_comment(outputStream* stream, intptr_t offset) const PRODUCT_RETURN;
void assign(CodeStrings& other) PRODUCT_RETURN;
void free() PRODUCT_RETURN;
};
// A CodeBuffer describes a memory space into which assembly
// code is generated. This memory space usually occupies the
// interior of a single BufferBlob, but in some cases it may be
// an arbitrary span of memory, even outside the code cache.
//
// A code buffer comes in two variants:
//
// (1) A CodeBuffer referring to an already allocated piece of memory:
// This is used to direct 'static' code generation (e.g. for interpreter
// or stubroutine generation, etc.). This code comes with NO relocation
// information.
//
// (2) A CodeBuffer referring to a piece of memory allocated when the
// CodeBuffer is allocated. This is used for nmethod generation.
//
// The memory can be divided up into several parts called sections.
// Each section independently accumulates code (or data) an relocations.
// Sections can grow (at the expense of a reallocation of the BufferBlob
// and recopying of all active sections). When the buffered code is finally
// written to an nmethod (or other CodeBlob), the contents (code, data,
// and relocations) of the sections are padded to an alignment and concatenated.
// Instructions and data in one section can contain relocatable references to
// addresses in a sibling section.
class CodeBuffer: public StackObj {
friend class CodeSection;
private:
// CodeBuffers must be allocated on the stack except for a single
// special case during expansion which is handled internally. This
// is done to guarantee proper cleanup of resources.
void* operator new(size_t size) throw() { return ResourceObj::operator new(size); }
void operator delete(void* p) { ShouldNotCallThis(); }
public:
typedef int csize_t; // code size type; would be size_t except for history
enum {
// Here is the list of all possible sections. The order reflects
// the final layout.
SECT_FIRST = 0,
SECT_CONSTS = SECT_FIRST, // Non-instruction data: Floats, jump tables, etc.
SECT_INSTS, // Executable instructions.
SECT_STUBS, // Outbound trampolines for supporting call sites.
SECT_LIMIT, SECT_NONE = -1
};
private:
enum {
sect_bits = 2, // assert (SECT_LIMIT <= (1<<sect_bits))
sect_mask = (1<<sect_bits)-1
};
const char* _name;
CodeSection _consts; // constants, jump tables
CodeSection _insts; // instructions (the main section)
CodeSection _stubs; // stubs (call site support), deopt, exception handling
CodeBuffer* _before_expand; // dead buffer, from before the last expansion
BufferBlob* _blob; // optional buffer in CodeCache for generated code
address _total_start; // first address of combined memory buffer
csize_t _total_size; // size in bytes of combined memory buffer
OopRecorder* _oop_recorder;
CodeStrings _strings;
OopRecorder _default_oop_recorder; // override with initialize_oop_recorder
Arena* _overflow_arena;
address _decode_begin; // start address for decode
address decode_begin();
void initialize_misc(const char * name) {
// all pointers other than code_start/end and those inside the sections
assert(name != NULL, "must have a name");
_name = name;
_before_expand = NULL;
_blob = NULL;
_oop_recorder = NULL;
_decode_begin = NULL;
_overflow_arena = NULL;
}
void initialize(address code_start, csize_t code_size) {
_consts.initialize_outer(this, SECT_CONSTS);
_insts.initialize_outer(this, SECT_INSTS);
_stubs.initialize_outer(this, SECT_STUBS);
_total_start = code_start;
_total_size = code_size;
// Initialize the main section:
_insts.initialize(code_start, code_size);
assert(!_stubs.is_allocated(), "no garbage here");
assert(!_consts.is_allocated(), "no garbage here");
_oop_recorder = &_default_oop_recorder;
}
void initialize_section_size(CodeSection* cs, csize_t size);
void freeze_section(CodeSection* cs);
// helper for CodeBuffer::expand()
void take_over_code_from(CodeBuffer* cs);
// ensure sections are disjoint, ordered, and contained in the blob
void verify_section_allocation();
// copies combined relocations to the blob, returns bytes copied
// (if target is null, it is a dry run only, just for sizing)
csize_t copy_relocations_to(CodeBlob* blob) const;
// copies combined code to the blob (assumes relocs are already in there)
void copy_code_to(CodeBlob* blob);
// moves code sections to new buffer (assumes relocs are already in there)
void relocate_code_to(CodeBuffer* cb) const;
// set up a model of the final layout of my contents
void compute_final_layout(CodeBuffer* dest) const;
// Expand the given section so at least 'amount' is remaining.
// Creates a new, larger BufferBlob, and rewrites the code & relocs.
void expand(CodeSection* which_cs, csize_t amount);
// Helper for expand.
csize_t figure_expanded_capacities(CodeSection* which_cs, csize_t amount, csize_t* new_capacity);
public:
// (1) code buffer referring to pre-allocated instruction memory
CodeBuffer(address code_start, csize_t code_size) {
assert(code_start != NULL, "sanity");
initialize_misc("static buffer");
initialize(code_start, code_size);
verify_section_allocation();
}
// (2) CodeBuffer referring to pre-allocated CodeBlob.
CodeBuffer(CodeBlob* blob);
// (3) code buffer allocating codeBlob memory for code & relocation
// info but with lazy initialization. The name must be something
// informative.
CodeBuffer(const char* name) {
initialize_misc(name);
}
// (4) code buffer allocating codeBlob memory for code & relocation
// info. The name must be something informative and code_size must
// include both code and stubs sizes.
CodeBuffer(const char* name, csize_t code_size, csize_t locs_size) {
initialize_misc(name);
initialize(code_size, locs_size);
}
~CodeBuffer();
// Initialize a CodeBuffer constructed using constructor 3. Using
// constructor 4 is equivalent to calling constructor 3 and then
// calling this method. It's been factored out for convenience of
// construction.
void initialize(csize_t code_size, csize_t locs_size);
CodeSection* consts() { return &_consts; }
CodeSection* insts() { return &_insts; }
CodeSection* stubs() { return &_stubs; }
// present sections in order; return NULL at end; consts is #0, etc.
CodeSection* code_section(int n) {
// This makes the slightly questionable but portable assumption
// that the various members (_consts, _insts, _stubs, etc.) are
// adjacent in the layout of CodeBuffer.
CodeSection* cs = &_consts + n;
assert(cs->index() == n || !cs->is_allocated(), "sanity");
return cs;
}
const CodeSection* code_section(int n) const { // yucky const stuff
return ((CodeBuffer*)this)->code_section(n);
}
static const char* code_section_name(int n);
int section_index_of(address addr) const;
bool contains(address addr) const {
// handy for debugging
return section_index_of(addr) > SECT_NONE;
}
// A stable mapping between 'locators' (small ints) and addresses.
static int locator_pos(int locator) { return locator >> sect_bits; }
static int locator_sect(int locator) { return locator & sect_mask; }
static int locator(int pos, int sect) { return (pos << sect_bits) | sect; }
int locator(address addr) const;
address locator_address(int locator) const;
// Heuristic for pre-packing the taken/not-taken bit of a predicted branch.
bool is_backward_branch(Label& L);
// Properties
const char* name() const { return _name; }
CodeBuffer* before_expand() const { return _before_expand; }
BufferBlob* blob() const { return _blob; }
void set_blob(BufferBlob* blob);
void free_blob(); // Free the blob, if we own one.
// Properties relative to the insts section:
address insts_begin() const { return _insts.start(); }
address insts_end() const { return _insts.end(); }
void set_insts_end(address end) { _insts.set_end(end); }
address insts_limit() const { return _insts.limit(); }
address insts_mark() const { return _insts.mark(); }
void set_insts_mark() { _insts.set_mark(); }
void clear_insts_mark() { _insts.clear_mark(); }
// is there anything in the buffer other than the current section?
bool is_pure() const { return insts_size() == total_content_size(); }
// size in bytes of output so far in the insts sections
csize_t insts_size() const { return _insts.size(); }
// same as insts_size(), except that it asserts there is no non-code here
csize_t pure_insts_size() const { assert(is_pure(), "no non-code");
return insts_size(); }
// capacity in bytes of the insts sections
csize_t insts_capacity() const { return _insts.capacity(); }
// number of bytes remaining in the insts section
csize_t insts_remaining() const { return _insts.remaining(); }
// is a given address in the insts section? (2nd version is end-inclusive)
bool insts_contains(address pc) const { return _insts.contains(pc); }
bool insts_contains2(address pc) const { return _insts.contains2(pc); }
// Record any extra oops required to keep embedded metadata alive
void finalize_oop_references(methodHandle method);
// Allocated size in all sections, when aligned and concatenated
// (this is the eventual state of the content in its final
// CodeBlob).
csize_t total_content_size() const;
// Combined offset (relative to start of first section) of given
// section, as eventually found in the final CodeBlob.
csize_t total_offset_of(CodeSection* cs) const;
// allocated size of all relocation data, including index, rounded up
csize_t total_relocation_size() const;
// allocated size of any and all recorded oops
csize_t total_oop_size() const {
OopRecorder* recorder = oop_recorder();
return (recorder == NULL)? 0: recorder->oop_size();
}
// allocated size of any and all recorded metadata
csize_t total_metadata_size() const {
OopRecorder* recorder = oop_recorder();
return (recorder == NULL)? 0: recorder->metadata_size();
}
// Configuration functions, called immediately after the CB is constructed.
// The section sizes are subtracted from the original insts section.
// Note: Call them in reverse section order, because each steals from insts.
void initialize_consts_size(csize_t size) { initialize_section_size(&_consts, size); }
void initialize_stubs_size(csize_t size) { initialize_section_size(&_stubs, size); }
// Override default oop recorder.
void initialize_oop_recorder(OopRecorder* r);
OopRecorder* oop_recorder() const { return _oop_recorder; }
CodeStrings& strings() { return _strings; }
// Code generation
void relocate(address at, RelocationHolder const& rspec, int format = 0) {
_insts.relocate(at, rspec, format);
}
void relocate(address at, relocInfo::relocType rtype, int format = 0) {
_insts.relocate(at, rtype, format);
}
// Management of overflow storage for binding of Labels.
GrowableArray<int>* create_patch_overflow();
// NMethod generation
void copy_code_and_locs_to(CodeBlob* blob) {
assert(blob != NULL, "sane");
copy_relocations_to(blob);
copy_code_to(blob);
}
void copy_values_to(nmethod* nm) {
if (!oop_recorder()->is_unused()) {
oop_recorder()->copy_values_to(nm);
}
}
// Transform an address from the code in this code buffer to a specified code buffer
address transform_address(const CodeBuffer &cb, address addr) const;
void block_comment(intptr_t offset, const char * comment) PRODUCT_RETURN;
const char* code_string(const char* str) PRODUCT_RETURN_(return NULL;);
// Log a little info about section usage in the CodeBuffer
void log_section_sizes(const char* name);
#ifndef PRODUCT
public:
// Printing / Decoding
// decodes from decode_begin() to code_end() and sets decode_begin to end
void decode();
void decode_all(); // decodes all the code
void skip_decode(); // sets decode_begin to code_end();
void print();
#endif
// The following header contains architecture-specific implementations
#ifdef TARGET_ARCH_x86
# include "codeBuffer_x86.hpp"
#endif
#ifdef TARGET_ARCH_sparc
# include "codeBuffer_sparc.hpp"
#endif
#ifdef TARGET_ARCH_zero
# include "codeBuffer_zero.hpp"
#endif
#ifdef TARGET_ARCH_arm
# include "codeBuffer_arm.hpp"
#endif
#ifdef TARGET_ARCH_ppc
# include "codeBuffer_ppc.hpp"
#endif
};
inline void CodeSection::freeze() {
_outer->freeze_section(this);
}
inline bool CodeSection::maybe_expand_to_ensure_remaining(csize_t amount) {
if (remaining() < amount) { _outer->expand(this, amount); return true; }
return false;
}
#endif // SHARE_VM_ASM_CODEBUFFER_HPP
| TobiHartmann/hotspot | src/share/vm/asm/codeBuffer.hpp | C++ | gpl-2.0 | 23,840 |
# Auto Shift: Why Do We Need a Shift Key?
Tap a key and you get its character. Tap a key, but hold it *slightly* longer
and you get its shifted state. Voilà! No shift key needed!
## Why Auto Shift?
Many people suffer from various forms of RSI. A common cause is stretching your
fingers repetitively long distances. For us on the keyboard, the pinky does that
all too often when reaching for the shift key. Auto Shift looks to alleviate that
problem.
## How Does It Work?
When you tap a key, it stays depressed for a short period of time before it is
then released. This depressed time is a different length for everyone. Auto Shift
defines a constant `AUTO_SHIFT_TIMEOUT` which is typically set to twice your
normal pressed state time. When you press a key, a timer starts and then stops
when you release the key. If the time depressed is greater than or equal to the
`AUTO_SHIFT_TIMEOUT`, then a shifted version of the key is emitted. If the time
is less than the `AUTO_SHIFT_TIMEOUT` time, then the normal state is emitted.
## Are There Limitations to Auto Shift?
Yes, unfortunately.
1. Key repeat will cease to work. For example, before if you wanted 20 'a'
characters, you could press and hold the 'a' key for a second or two. This no
longer works with Auto Shift because it is timing your depressed time instead
of emitting a depressed key state to your operating system.
2. You will have characters that are shifted when you did not intend on shifting, and
other characters you wanted shifted, but were not. This simply comes down to
practice. As we get in a hurry, we think we have hit the key long enough
for a shifted version, but we did not. On the other hand, we may think we are
tapping the keys, but really we have held it for a little longer than
anticipated.
## How Do I Enable Auto Shift?
Add to your `rules.mk` in the keymap folder:
AUTO_SHIFT_ENABLE = yes
If no `rules.mk` exists, you can create one.
Then compile and install your new firmware with Auto Key enabled! That's it!
## Modifiers
By default, Auto Shift is disabled for any key press that is accompanied by one or more
modifiers. Thus, Ctrl+A that you hold for a really long time is not the same
as Ctrl+Shift+A.
You can re-enable Auto Shift for modifiers by adding a define to your `config.h`
```c
#define AUTO_SHIFT_MODIFIERS
```
In which case, Ctrl+A held past the `AUTO_SHIFT_TIMEOUT` will be sent as Ctrl+Shift+A
## Configuring Auto Shift
If desired, there is some configuration that can be done to change the
behavior of Auto Shift. This is done by setting various variables the
`config.h` file located in your keymap folder. If no `config.h` file exists, you can create one.
A sample is
```c
#pragma once
#define AUTO_SHIFT_TIMEOUT 150
#define NO_AUTO_SHIFT_SPECIAL
```
### AUTO_SHIFT_TIMEOUT (Value in ms)
This controls how long you have to hold a key before you get the shifted state.
Obviously, this is different for everyone. For the common person, a setting of
135 to 150 works great. However, one should start with a value of at least 175, which
is the default value. Then work down from there. The idea is to have the shortest time required to get the shifted state without having false positives.
Play with this value until things are perfect. Many find that all will work well
at a given value, but one or two keys will still emit the shifted state on
occasion. This is simply due to habit and holding some keys a little longer
than others. Once you find this value, work on tapping your problem keys a little
quicker than normal and you will be set.
?> Auto Shift has three special keys that can help you get this value right very quick. See "Auto Shift Setup" for more details!
### NO_AUTO_SHIFT_SPECIAL (simple define)
Do not Auto Shift special keys, which include -\_, =+, [{, ]}, ;:, '", ,<, .>,
and /?
### NO_AUTO_SHIFT_NUMERIC (simple define)
Do not Auto Shift numeric keys, zero through nine.
### NO_AUTO_SHIFT_ALPHA (simple define)
Do not Auto Shift alpha characters, which include A through Z.
## Using Auto Shift Setup
This will enable you to define three keys temporarily to increase, decrease and report your `AUTO_SHIFT_TIMEOUT`.
### Setup
Map three keys temporarily in your keymap:
| Key Name | Description |
|----------|-----------------------------------------------------|
| KC_ASDN | Lower the Auto Shift timeout variable (down) |
| KC_ASUP | Raise the Auto Shift timeout variable (up) |
| KC_ASRP | Report your current Auto Shift timeout value |
| KC_ASON | Turns on the Auto Shift Function |
| KC_ASOFF | Turns off the Auto Shift Function |
| KC_ASTG | Toggles the state of the Auto Shift feature |
Compile and upload your new firmware.
### Use
It is important to note that during these tests, you should be typing
completely normal and with no intention of shifted keys.
1. Type multiple sentences of alphabetical letters.
2. Observe any upper case letters.
3. If there are none, press the key you have mapped to `KC_ASDN` to decrease
time Auto Shift timeout value and go back to step 1.
4. If there are some upper case letters, decide if you need to work on tapping
those keys with less down time, or if you need to increase the timeout.
5. If you decide to increase the timeout, press the key you have mapped to
`KC_ASUP` and go back to step 1.
6. Once you are happy with your results, press the key you have mapped to
`KC_ASRP`. The keyboard will type by itself the value of your
`AUTO_SHIFT_TIMEOUT`.
7. Update `AUTO_SHIFT_TIMEOUT` in your `config.h` with the value reported.
8. Remove `AUTO_SHIFT_SETUP` from your `config.h`.
9. Remove the key bindings `KC_ASDN`, `KC_ASUP` and `KC_ASRP`.
10. Compile and upload your new firmware.
#### An Example Run
hello world. my name is john doe. i am a computer programmer playing with
keyboards right now.
[PRESS KC_ASDN quite a few times]
heLLo woRLd. mY nAMe is JOHn dOE. i AM A compUTeR proGRaMMER PlAYiNG witH
KEYboArDS RiGHT NOw.
[PRESS KC_ASUP a few times]
hello world. my name is john Doe. i am a computer programmer playing with
keyboarDs right now.
[PRESS KC_ASRP]
115
The keyboard typed `115` which represents your current `AUTO_SHIFT_TIMEOUT`
value. You are now set! Practice on the *D* key a little bit that showed up
in the testing and you'll be golden.
| chancegrissom/qmk_firmware | docs/feature_auto_shift.md | Markdown | gpl-2.0 | 6,477 |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package patch
import (
"bytes"
"compress/zlib"
"crypto/sha1"
"encoding/git85"
"fmt"
"io"
"os"
)
func gitSHA1(data []byte) []byte {
if len(data) == 0 {
// special case: 0 length is all zeros sum
return make([]byte, 20)
}
h := sha1.New()
fmt.Fprintf(h, "blob %d\x00", len(data))
h.Write(data)
return h.Sum()
}
// BUG(rsc): The Git binary delta format is not implemented, only Git binary literals.
// GitBinaryLiteral represents a Git binary literal diff.
type GitBinaryLiteral struct {
OldSHA1 []byte // if non-empty, the SHA1 hash of the original
New []byte // the new contents
}
// Apply implements the Diff interface's Apply method.
func (d *GitBinaryLiteral) Apply(old []byte) ([]byte, os.Error) {
if sum := gitSHA1(old); !bytes.HasPrefix(sum, d.OldSHA1) {
return nil, ErrPatchFailure
}
return d.New, nil
}
func unhex(c byte) uint8 {
switch {
case '0' <= c && c <= '9':
return c - '0'
case 'a' <= c && c <= 'f':
return c - 'a' + 10
case 'A' <= c && c <= 'F':
return c - 'A' + 10
}
return 255
}
func getHex(s []byte) (data []byte, rest []byte) {
n := 0
for n < len(s) && unhex(s[n]) != 255 {
n++
}
n &^= 1 // Only take an even number of hex digits.
data = make([]byte, n/2)
for i := range data {
data[i] = unhex(s[2*i])<<4 | unhex(s[2*i+1])
}
rest = s[n:]
return
}
// ParseGitBinary parses raw as a Git binary patch.
func ParseGitBinary(raw []byte) (Diff, os.Error) {
var oldSHA1, newSHA1 []byte
var sawBinary bool
for {
var first []byte
first, raw, _ = getLine(raw, 1)
first = bytes.TrimSpace(first)
if s, ok := skip(first, "index "); ok {
oldSHA1, s = getHex(s)
if s, ok = skip(s, ".."); !ok {
continue
}
newSHA1, s = getHex(s)
continue
}
if _, ok := skip(first, "GIT binary patch"); ok {
sawBinary = true
continue
}
if n, _, ok := atoi(first, "literal ", 10); ok && sawBinary {
data := make([]byte, n)
d := git85.NewDecoder(bytes.NewBuffer(raw))
z, err := zlib.NewReader(d)
if err != nil {
return nil, err
}
defer z.Close()
if _, err = io.ReadFull(z, data); err != nil {
if err == os.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
}
var buf [1]byte
m, err := z.Read(buf[0:])
if m != 0 || err != os.EOF {
return nil, os.NewError("Git binary literal longer than expected")
}
if sum := gitSHA1(data); !bytes.HasPrefix(sum, newSHA1) {
return nil, os.NewError("Git binary literal SHA1 mismatch")
}
return &GitBinaryLiteral{oldSHA1, data}, nil
}
if !sawBinary {
return nil, os.NewError("unexpected Git patch header: " + string(first))
}
}
panic("unreachable")
}
| SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/libgo/go/patch/git.go | GO | gpl-2.0 | 2,816 |
# encoding: utf-8
require 'spec_helper'
require_dependency 'post_creator'
describe CategoryUser do
it 'allows batch set' do
user = Fabricate(:user)
category1 = Fabricate(:category)
category2 = Fabricate(:category)
watching = CategoryUser.where(user_id: user.id, notification_level: CategoryUser.notification_levels[:watching])
CategoryUser.batch_set(user, :watching, [category1.id, category2.id])
expect(watching.pluck(:category_id).sort).to eq [category1.id, category2.id]
CategoryUser.batch_set(user, :watching, [])
expect(watching.count).to eq 0
CategoryUser.batch_set(user, :watching, [category2.id])
expect(watching.count).to eq 1
end
context 'integration' do
before do
ActiveRecord::Base.observers.enable :all
end
it 'should operate correctly' do
watched_category = Fabricate(:category)
muted_category = Fabricate(:category)
tracked_category = Fabricate(:category)
user = Fabricate(:user)
CategoryUser.create!(user: user, category: watched_category, notification_level: CategoryUser.notification_levels[:watching])
CategoryUser.create!(user: user, category: muted_category, notification_level: CategoryUser.notification_levels[:muted])
CategoryUser.create!(user: user, category: tracked_category, notification_level: CategoryUser.notification_levels[:tracking])
watched_post = create_post(category: watched_category)
muted_post = create_post(category: muted_category)
tracked_post = create_post(category: tracked_category)
expect(Notification.where(user_id: user.id, topic_id: watched_post.topic_id).count).to eq 1
expect(Notification.where(user_id: user.id, topic_id: tracked_post.topic_id).count).to eq 0
tu = TopicUser.get(tracked_post.topic, user)
expect(tu.notification_level).to eq TopicUser.notification_levels[:tracking]
expect(tu.notifications_reason_id).to eq TopicUser.notification_reasons[:auto_track_category]
end
it "watches categories that have been changed" do
user = Fabricate(:user)
watched_category = Fabricate(:category)
CategoryUser.create!(user: user, category: watched_category, notification_level: CategoryUser.notification_levels[:watching])
post = create_post
expect(TopicUser.get(post.topic, user)).to be_blank
# Now, change the topic's category
post.topic.change_category_to_id(watched_category.id)
tu = TopicUser.get(post.topic, user)
expect(tu.notification_level).to eq TopicUser.notification_levels[:watching]
end
it "unwatches categories that have been changed" do
user = Fabricate(:user)
watched_category = Fabricate(:category)
CategoryUser.create!(user: user, category: watched_category, notification_level: CategoryUser.notification_levels[:watching])
post = create_post(category: watched_category)
tu = TopicUser.get(post.topic, user)
expect(tu.notification_level).to eq TopicUser.notification_levels[:watching]
# Now, change the topic's category
unwatched_category = Fabricate(:category)
post.topic.change_category_to_id(unwatched_category.id)
expect(TopicUser.get(post.topic, user)).to be_blank
end
end
end
| Procurem/Contraints | spec/models/category_user_spec.rb | Ruby | gpl-2.0 | 3,264 |
/*
* Copyright 2015 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <drm/amdgpu_drm.h>
#include "pp_instance.h"
#include "smumgr.h"
#include "cgs_common.h"
#include "linux/delay.h"
int smum_init(struct amd_pp_init *pp_init, struct pp_instance *handle)
{
struct pp_smumgr *smumgr;
if ((handle == NULL) || (pp_init == NULL))
return -EINVAL;
smumgr = kzalloc(sizeof(struct pp_smumgr), GFP_KERNEL);
if (smumgr == NULL)
return -ENOMEM;
smumgr->device = pp_init->device;
smumgr->chip_family = pp_init->chip_family;
smumgr->chip_id = pp_init->chip_id;
smumgr->usec_timeout = AMD_MAX_USEC_TIMEOUT;
smumgr->reload_fw = 1;
handle->smu_mgr = smumgr;
switch (smumgr->chip_family) {
case AMDGPU_FAMILY_CZ:
cz_smum_init(smumgr);
break;
case AMDGPU_FAMILY_VI:
switch (smumgr->chip_id) {
case CHIP_TOPAZ:
iceland_smum_init(smumgr);
break;
case CHIP_TONGA:
tonga_smum_init(smumgr);
break;
case CHIP_FIJI:
fiji_smum_init(smumgr);
break;
case CHIP_POLARIS11:
case CHIP_POLARIS10:
case CHIP_POLARIS12:
polaris10_smum_init(smumgr);
break;
default:
return -EINVAL;
}
break;
default:
kfree(smumgr);
return -EINVAL;
}
return 0;
}
int smum_fini(struct pp_smumgr *smumgr)
{
kfree(smumgr->device);
kfree(smumgr);
return 0;
}
int smum_thermal_avfs_enable(struct pp_hwmgr *hwmgr,
void *input, void *output, void *storage, int result)
{
if (NULL != hwmgr->smumgr->smumgr_funcs->thermal_avfs_enable)
return hwmgr->smumgr->smumgr_funcs->thermal_avfs_enable(hwmgr);
return 0;
}
int smum_thermal_setup_fan_table(struct pp_hwmgr *hwmgr,
void *input, void *output, void *storage, int result)
{
if (NULL != hwmgr->smumgr->smumgr_funcs->thermal_setup_fan_table)
return hwmgr->smumgr->smumgr_funcs->thermal_setup_fan_table(hwmgr);
return 0;
}
int smum_update_sclk_threshold(struct pp_hwmgr *hwmgr)
{
if (NULL != hwmgr->smumgr->smumgr_funcs->update_sclk_threshold)
return hwmgr->smumgr->smumgr_funcs->update_sclk_threshold(hwmgr);
return 0;
}
int smum_update_smc_table(struct pp_hwmgr *hwmgr, uint32_t type)
{
if (NULL != hwmgr->smumgr->smumgr_funcs->update_smc_table)
return hwmgr->smumgr->smumgr_funcs->update_smc_table(hwmgr, type);
return 0;
}
uint32_t smum_get_offsetof(struct pp_smumgr *smumgr, uint32_t type, uint32_t member)
{
if (NULL != smumgr->smumgr_funcs->get_offsetof)
return smumgr->smumgr_funcs->get_offsetof(type, member);
return 0;
}
int smum_process_firmware_header(struct pp_hwmgr *hwmgr)
{
if (NULL != hwmgr->smumgr->smumgr_funcs->process_firmware_header)
return hwmgr->smumgr->smumgr_funcs->process_firmware_header(hwmgr);
return 0;
}
int smum_get_argument(struct pp_smumgr *smumgr)
{
if (NULL != smumgr->smumgr_funcs->get_argument)
return smumgr->smumgr_funcs->get_argument(smumgr);
return 0;
}
uint32_t smum_get_mac_definition(struct pp_smumgr *smumgr, uint32_t value)
{
if (NULL != smumgr->smumgr_funcs->get_mac_definition)
return smumgr->smumgr_funcs->get_mac_definition(value);
return 0;
}
int smum_download_powerplay_table(struct pp_smumgr *smumgr,
void **table)
{
if (NULL != smumgr->smumgr_funcs->download_pptable_settings)
return smumgr->smumgr_funcs->download_pptable_settings(smumgr,
table);
return 0;
}
int smum_upload_powerplay_table(struct pp_smumgr *smumgr)
{
if (NULL != smumgr->smumgr_funcs->upload_pptable_settings)
return smumgr->smumgr_funcs->upload_pptable_settings(smumgr);
return 0;
}
int smum_send_msg_to_smc(struct pp_smumgr *smumgr, uint16_t msg)
{
if (smumgr == NULL || smumgr->smumgr_funcs->send_msg_to_smc == NULL)
return -EINVAL;
return smumgr->smumgr_funcs->send_msg_to_smc(smumgr, msg);
}
int smum_send_msg_to_smc_with_parameter(struct pp_smumgr *smumgr,
uint16_t msg, uint32_t parameter)
{
if (smumgr == NULL ||
smumgr->smumgr_funcs->send_msg_to_smc_with_parameter == NULL)
return -EINVAL;
return smumgr->smumgr_funcs->send_msg_to_smc_with_parameter(
smumgr, msg, parameter);
}
/*
* Returns once the part of the register indicated by the mask has
* reached the given value.
*/
int smum_wait_on_register(struct pp_smumgr *smumgr,
uint32_t index,
uint32_t value, uint32_t mask)
{
uint32_t i;
uint32_t cur_value;
if (smumgr == NULL || smumgr->device == NULL)
return -EINVAL;
for (i = 0; i < smumgr->usec_timeout; i++) {
cur_value = cgs_read_register(smumgr->device, index);
if ((cur_value & mask) == (value & mask))
break;
udelay(1);
}
/* timeout means wrong logic*/
if (i == smumgr->usec_timeout)
return -1;
return 0;
}
int smum_wait_for_register_unequal(struct pp_smumgr *smumgr,
uint32_t index,
uint32_t value, uint32_t mask)
{
uint32_t i;
uint32_t cur_value;
if (smumgr == NULL)
return -EINVAL;
for (i = 0; i < smumgr->usec_timeout; i++) {
cur_value = cgs_read_register(smumgr->device,
index);
if ((cur_value & mask) != (value & mask))
break;
udelay(1);
}
/* timeout means wrong logic */
if (i == smumgr->usec_timeout)
return -1;
return 0;
}
/*
* Returns once the part of the register indicated by the mask
* has reached the given value.The indirect space is described by
* giving the memory-mapped index of the indirect index register.
*/
int smum_wait_on_indirect_register(struct pp_smumgr *smumgr,
uint32_t indirect_port,
uint32_t index,
uint32_t value,
uint32_t mask)
{
if (smumgr == NULL || smumgr->device == NULL)
return -EINVAL;
cgs_write_register(smumgr->device, indirect_port, index);
return smum_wait_on_register(smumgr, indirect_port + 1,
mask, value);
}
void smum_wait_for_indirect_register_unequal(
struct pp_smumgr *smumgr,
uint32_t indirect_port,
uint32_t index,
uint32_t value,
uint32_t mask)
{
if (smumgr == NULL || smumgr->device == NULL)
return;
cgs_write_register(smumgr->device, indirect_port, index);
smum_wait_for_register_unequal(smumgr, indirect_port + 1,
value, mask);
}
int smu_allocate_memory(void *device, uint32_t size,
enum cgs_gpu_mem_type type,
uint32_t byte_align, uint64_t *mc_addr,
void **kptr, void *handle)
{
int ret = 0;
cgs_handle_t cgs_handle;
if (device == NULL || handle == NULL ||
mc_addr == NULL || kptr == NULL)
return -EINVAL;
ret = cgs_alloc_gpu_mem(device, type, size, byte_align,
0, 0, (cgs_handle_t *)handle);
if (ret)
return -ENOMEM;
cgs_handle = *(cgs_handle_t *)handle;
ret = cgs_gmap_gpu_mem(device, cgs_handle, mc_addr);
if (ret)
goto error_gmap;
ret = cgs_kmap_gpu_mem(device, cgs_handle, kptr);
if (ret)
goto error_kmap;
return 0;
error_kmap:
cgs_gunmap_gpu_mem(device, cgs_handle);
error_gmap:
cgs_free_gpu_mem(device, cgs_handle);
return ret;
}
int smu_free_memory(void *device, void *handle)
{
cgs_handle_t cgs_handle = (cgs_handle_t)handle;
if (device == NULL || handle == NULL)
return -EINVAL;
cgs_kunmap_gpu_mem(device, cgs_handle);
cgs_gunmap_gpu_mem(device, cgs_handle);
cgs_free_gpu_mem(device, cgs_handle);
return 0;
}
int smum_init_smc_table(struct pp_hwmgr *hwmgr)
{
if (NULL != hwmgr->smumgr->smumgr_funcs->init_smc_table)
return hwmgr->smumgr->smumgr_funcs->init_smc_table(hwmgr);
return 0;
}
int smum_populate_all_graphic_levels(struct pp_hwmgr *hwmgr)
{
if (NULL != hwmgr->smumgr->smumgr_funcs->populate_all_graphic_levels)
return hwmgr->smumgr->smumgr_funcs->populate_all_graphic_levels(hwmgr);
return 0;
}
int smum_populate_all_memory_levels(struct pp_hwmgr *hwmgr)
{
if (NULL != hwmgr->smumgr->smumgr_funcs->populate_all_memory_levels)
return hwmgr->smumgr->smumgr_funcs->populate_all_memory_levels(hwmgr);
return 0;
}
/*this interface is needed by island ci/vi */
int smum_initialize_mc_reg_table(struct pp_hwmgr *hwmgr)
{
if (NULL != hwmgr->smumgr->smumgr_funcs->initialize_mc_reg_table)
return hwmgr->smumgr->smumgr_funcs->initialize_mc_reg_table(hwmgr);
return 0;
}
bool smum_is_dpm_running(struct pp_hwmgr *hwmgr)
{
if (NULL != hwmgr->smumgr->smumgr_funcs->is_dpm_running)
return hwmgr->smumgr->smumgr_funcs->is_dpm_running(hwmgr);
return true;
}
| endocode/linux | drivers/gpu/drm/amd/powerplay/smumgr/smumgr.c | C | gpl-2.0 | 9,245 |
shadowsocks-libev
=================
[shadowsocks-libev][1] is a lightweight secured socks5 proxy for embedded
devices and low end boxes. It is a port of [shadowsocks][2] created by
@clowwindy maintained by @madeye and @linusyang.
Suppose we have a VPS running Debian or Ubuntu.
To deploy the service quickly, we can use [docker][3].
## Install docker
```
$ curl -sSL https://get.docker.com/ | sh
$ docker --version
```
## Build docker image
```bash
$ curl -sSL https://github.com/shadowsocks/shadowsocks-libev/raw/master/docker/alpine/Dockerfile | docker build -t shadowsocks-libev .
$ docker images
```
> You can also use a pre-built docker image: [vimagick/shadowsocks-libev][4] ![][5].
## Run docker container
```bash
$ docker run -d -e METHOD=aes-256-cfb -e PASSWORD=9MLSpPmNt -p 8388:8388 --restart always shadowsocks-libev
$ docker ps
```
> :warning: Click [here][6] to generate a strong password to protect your server.
## Use docker-compose to manage (optional)
It is very handy to use [docker-compose][7] to manage docker containers.
You can download the binary at <https://github.com/docker/compose/releases>.
This is a sample `docker-compose.yml` file.
```yaml
shadowsocks:
image: shadowsocks-libev
ports:
- "8388:8388"
environment:
- METHOD=aes-256-cfb
- PASSWORD=9MLSpPmNt
restart: always
```
It is highly recommended that you setup a directory tree to make things easy to manage.
```bash
$ mkdir -p ~/fig/shadowsocks/
$ cd ~/fig/shadowsocks/
$ curl -sSLO https://github.com/shadowsocks/shadowsocks-libev/raw/master/docker/alpine/docker-compose.yml
$ docker-compose up -d
$ docker-compose ps
```
## Finish
At last, download shadowsocks client [here][8].
Don't forget to share internet with your friends.
```yaml
{
"server": "your-vps-ip",
"server_port": 8388,
"local_address": "0.0.0.0",
"local_port": 1080,
"password": "9MLSpPmNt",
"timeout": 600,
"method": "aes-256-cfb"
}
```
[1]: https://github.com/shadowsocks/shadowsocks-libev
[2]: https://shadowsocks.org/en/index.html
[3]: https://github.com/docker/docker
[4]: https://hub.docker.com/r/vimagick/shadowsocks-libev/
[5]: https://badge.imagelayers.io/vimagick/shadowsocks-libev:latest.svg
[6]: https://duckduckgo.com/?q=password+12&t=ffsb&ia=answer
[7]: https://github.com/docker/compose
[8]: https://shadowsocks.org/en/download/clients.html
| TkYu/Dockerfiles | ss/README.md | Markdown | gpl-3.0 | 2,379 |
#!/bin/bash
#set -x
source $LIBMESH_DIR/examples/run_common.sh
example_name=adjoints_ex3
example_dir=examples/adjoints/$example_name
run_example "$example_name"
| paulthulstrup/moose | libmesh/examples/adjoints/adjoints_ex3/run.sh | Shell | lgpl-2.1 | 166 |
/**
* Copyright (C) 2011 JTalks.org Team
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jtalks.jcommune.plugin.api.web.validation.validators;
import org.jtalks.jcommune.plugin.api.service.PluginBbCodeService;
import org.jtalks.jcommune.plugin.api.web.validation.annotations.BbCodeAwareSize;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Extends default @Size annotation to ignore BB codes in string.
* As for now, applicable to string values only.
*
* @author Evgeniy Naumenko
*/
public class BbCodeAwareSizeValidator implements ConstraintValidator<BbCodeAwareSize, String>, ApplicationContextAware {
public static final String NEW_LINE_HTML = "<br/>";
public static final String QUOTE_HTML = """;
public static final String EMPTY_LIST_BB_REGEXP = "\\[list\\][\n\r\\s]*(\\[\\*\\][\n\r\\s]*)*\\[\\/list\\]";
private int min;
private int max;
private ApplicationContext context;
private PluginBbCodeService bbCodeService;
@Autowired
public BbCodeAwareSizeValidator(PluginBbCodeService bbCodeService) {
this.bbCodeService = bbCodeService;
}
/**
* {@inheritDoc}
*/
@Override
public void initialize(BbCodeAwareSize constraintAnnotation) {
this.min = constraintAnnotation.min();
this.max = constraintAnnotation.max();
}
/**
* The database stores both bb codes and symbols visible for users.
* Post length with bb codes can't be greater than max value.
* {@inheritDoc}
*/
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value != null) {
String emptyListRemoved = removeEmptyListBb(value);
String trimed = removeBBCodes(emptyListRemoved).trim();
int plainTextLength = getDisplayedLength(trimed);
return plainTextLength >= min && value.length() <= max;
}
return false;
}
/**
* Removes all BB codes from the text given, simply cutting
* out all [...]-style tags found
*
* @param source text to cleanup
* @return plain text without BB tags
*/
private String removeBBCodes(String source) {
return getBBCodeService().stripBBCodes(source);
}
@Override
public void setApplicationContext(ApplicationContext ac) throws BeansException {
this.context = ac;
}
private PluginBbCodeService getBBCodeService() {
if (bbCodeService == null) {
bbCodeService = this.context.getBean(PluginBbCodeService.class);
}
return bbCodeService;
}
/**
* Calculate length of string which be displayed.
* Needed because method <b>removeBBCodes</b> leaves """ and "<br/>" symbols.
* @param s String to calculate length.
* @return Length of string which be displayed.
*/
private int getDisplayedLength(String s) {
return s.replaceAll(QUOTE_HTML, "\"").replaceAll(NEW_LINE_HTML, "\n\r").length();
}
/**
* Removes all empty lists from text. Needed because <b>removeBBCodes</b> deletes
* bb codes for list but not deletes bb codes for list elements.
* @param text Text to remove empty lists.
* @return Text without empty lists.
*/
private String removeEmptyListBb(String text) {
return text.replaceAll(EMPTY_LIST_BB_REGEXP, "");
}
}
| Noctrunal/jcommune | jcommune-plugin-api/src/main/java/org/jtalks/jcommune/plugin/api/web/validation/validators/BbCodeAwareSizeValidator.java | Java | lgpl-2.1 | 4,375 |
/*
* Copyright 2011 The Closure Compiler 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 com.google.javascript.jscomp;
import com.google.common.collect.Lists;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.List;
/**
* <p>Compiler pass that converts all calls to:
* goog.object.create(key1, val1, key2, val2, ...) where all of the keys
* are literals into object literals.</p>
*
* @author agrieve@google.com (Andrew Grieve)
*/
final class ClosureOptimizePrimitives implements CompilerPass {
/** Reference to the JS compiler */
private final AbstractCompiler compiler;
/**
* Identifies all calls to goog.object.create.
*/
private class FindObjectCreateCalls extends AbstractPostOrderCallback {
List<Node> callNodes = Lists.newArrayList();
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isCall()) {
String fnName = n.getFirstChild().getQualifiedName();
if ("goog$object$create".equals(fnName) ||
"goog.object.create".equals(fnName)) {
callNodes.add(n);
}
}
}
}
/**
* @param compiler The AbstractCompiler
*/
ClosureOptimizePrimitives(AbstractCompiler compiler) {
this.compiler = compiler;
}
@Override
public void process(Node externs, Node root) {
FindObjectCreateCalls pass = new FindObjectCreateCalls();
NodeTraversal.traverse(compiler, root, pass);
processObjectCreateCalls(pass.callNodes);
}
/**
* Converts all of the given call nodes to object literals that are safe to
* do so.
*/
private void processObjectCreateCalls(List<Node> callNodes) {
for (Node callNode : callNodes) {
Node curParam = callNode.getFirstChild().getNext();
if (canOptimizeObjectCreate(curParam)) {
Node objNode = IR.objectlit().srcref(callNode);
while (curParam != null) {
Node keyNode = curParam;
Node valueNode = curParam.getNext();
curParam = valueNode.getNext();
callNode.removeChild(keyNode);
callNode.removeChild(valueNode);
if (!keyNode.isString()) {
keyNode = IR.string(NodeUtil.getStringValue(keyNode))
.srcref(keyNode);
}
keyNode.setType(Token.STRING_KEY);
keyNode.setQuotedString();
objNode.addChildToBack(IR.propdef(keyNode, valueNode));
}
callNode.getParent().replaceChild(callNode, objNode);
compiler.reportCodeChange();
}
}
}
/**
* Returns whether the given call to goog.object.create can be converted to an
* object literal.
*/
private boolean canOptimizeObjectCreate(Node firstParam) {
Node curParam = firstParam;
while (curParam != null) {
// All keys must be strings or numbers.
if (!curParam.isString() && !curParam.isNumber()) {
return false;
}
curParam = curParam.getNext();
// Check for an odd number of parameters.
if (curParam == null) {
return false;
}
curParam = curParam.getNext();
}
return true;
}
}
| jhiswin/idiil-closure-compiler | src/com/google/javascript/jscomp/ClosureOptimizePrimitives.java | Java | apache-2.0 | 3,783 |
Prism.languages.bbcode={tag:{pattern:/\[\/?[^\s=\]]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'"\]=]+))?(?:\s+[^\s=\]]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'"\]=]+))*\s*\]/,inside:{tag:{pattern:/^\[\/?[^\s=\]]+/,inside:{punctuation:/^\[\/?/}},"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'"\]=]+)/i,inside:{punctuation:[/^=/,{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\]/,"attr-name":/[^\s=\]]+/}}},Prism.languages.shortcode=Prism.languages.bbcode; | BigBoss424/portfolio | v7/development/node_modules/prismjs/components/prism-bbcode.min.js | JavaScript | apache-2.0 | 453 |
/**
* Copyright 2017 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const POST_PARAMS = {
'embedtype': 'post',
'hash': 'Yc8_Z9pnpg8aKMZbVcD-jK45eAk',
'owner-id': '1',
'post-id': '45616',
};
const POLL_PARAMS = {
'embedtype': 'poll',
'api-id': '6183531',
'poll-id': '274086843_1a2a465f60fff4699f',
};
import '../amp-vk';
import {Layout} from '../../../../src/layout';
import {Resource} from '../../../../src/service/resource';
describes.realWin('amp-vk', {
amp: {
extensions: ['amp-vk'],
},
}, env => {
let win, doc;
beforeEach(() => {
win = env.win;
doc = win.document;
});
function createAmpVkElement(dataParams, layout) {
const element = doc.createElement('amp-vk');
for (const param in dataParams) {
element.setAttribute(`data-${param}`, dataParams[param]);
}
element.setAttribute('width', 500);
element.setAttribute('height', 300);
if (layout) {
element.setAttribute('layout', layout);
}
doc.body.appendChild(element);
return element.build().then(() => {
const resource = Resource.forElement(element);
resource.measure();
return element.layoutCallback();
}).then(() => element);
}
it('requires data-embedtype', () => {
const params = Object.assign({}, POST_PARAMS);
delete params['embedtype'];
return createAmpVkElement(params).should.eventually.be.rejectedWith(
/The data-embedtype attribute is required for/);
});
it('removes iframe after unlayoutCallback', () => {
return createAmpVkElement(POST_PARAMS).then(vkPost => {
const iframe = vkPost.querySelector('iframe');
expect(iframe).to.not.be.null;
const obj = vkPost.implementation_;
obj.unlayoutCallback();
expect(vkPost.querySelector('iframe')).to.be.null;
expect(obj.iframe_).to.be.null;
expect(obj.unlayoutOnPause()).to.be.true;
});
});
// Post tests
it('post::requires data-hash', () => {
const params = Object.assign({}, POST_PARAMS);
delete params['hash'];
return createAmpVkElement(params).should.eventually.be.rejectedWith(
/The data-hash attribute is required for/);
});
it('post::requires data-owner-id', () => {
const params = Object.assign({}, POST_PARAMS);
delete params['owner-id'];
return createAmpVkElement(params).should.eventually.be.rejectedWith(
/The data-owner-id attribute is required for/);
});
it('post::requires data-post-id', () => {
const params = Object.assign({}, POST_PARAMS);
delete params['post-id'];
return createAmpVkElement(params).should.eventually.be.rejectedWith(
/The data-post-id attribute is required for/);
});
it('post::renders iframe in amp-vk', () => {
return createAmpVkElement(POST_PARAMS).then(vkPost => {
const iframe = vkPost.querySelector('iframe');
expect(iframe).to.not.be.null;
});
});
it('post::renders responsively', () => {
return createAmpVkElement(POST_PARAMS, Layout.RESPONSIVE).then(vkPost => {
const iframe = vkPost.querySelector('iframe');
expect(iframe).to.not.be.null;
expect(iframe.className).to.match(/i-amphtml-fill-content/);
});
});
it('post::sets correct src url to the vk iFrame', () => {
return createAmpVkElement(POST_PARAMS, Layout.RESPONSIVE).then(vkPost => {
const impl = vkPost.implementation_;
const iframe = vkPost.querySelector('iframe');
const referrer = encodeURIComponent(vkPost.ownerDocument.referrer);
const url = encodeURIComponent(
vkPost.ownerDocument.location.href.replace(/#.*$/, '')
);
impl.onLayoutMeasure();
const startWidth = impl.getLayoutWidth();
const correctIFrameSrc = `https://vk.com/widget_post.php?app=0&width=100%25\
&_ver=1&owner_id=1&post_id=45616&hash=Yc8_Z9pnpg8aKMZbVcD-jK45eAk&=1\
&startWidth=${startWidth}&url=${url}&referrer=${referrer}&title=AMP%20Post`;
expect(iframe).to.not.be.null;
const timeArgPosition = iframe.src.lastIndexOf('&');
const iframeSrcWithoutTime = iframe.src.substr(0, timeArgPosition);
expect(iframeSrcWithoutTime).to.equal(correctIFrameSrc);
});
});
// Poll tests
it('poll::requires data-api-id', () => {
const params = Object.assign({}, POLL_PARAMS);
delete params['api-id'];
return createAmpVkElement(params).should.eventually.be.rejectedWith(
/The data-api-id attribute is required for/);
});
it('poll::requires data-poll-id', () => {
const params = Object.assign({}, POLL_PARAMS);
delete params['poll-id'];
return createAmpVkElement(params).should.eventually.be.rejectedWith(
/The data-poll-id attribute is required for/);
});
it('poll::renders iframe in amp-vk', () => {
return createAmpVkElement(POLL_PARAMS).then(vkPoll => {
const iframe = vkPoll.querySelector('iframe');
expect(iframe).to.not.be.null;
});
});
it('poll::renders responsively', () => {
return createAmpVkElement(POLL_PARAMS, Layout.RESPONSIVE).then(vkPoll => {
const iframe = vkPoll.querySelector('iframe');
expect(iframe).to.not.be.null;
expect(iframe.className).to.match(/i-amphtml-fill-content/);
});
});
it('poll::sets correct src url to the vk iFrame', () => {
return createAmpVkElement(POLL_PARAMS, Layout.RESPONSIVE).then(vkPoll => {
const iframe = vkPoll.querySelector('iframe');
const referrer = encodeURIComponent(vkPoll.ownerDocument.referrer);
const url = encodeURIComponent(
vkPoll.ownerDocument.location.href.replace(/#.*$/, '')
);
const correctIFrameSrc = `https://vk.com/al_widget_poll.php?\
app=6183531&width=100%25&_ver=1&poll_id=274086843_1a2a465f60fff4699f&=1\
&url=${url}&title=AMP%20Poll&description=&referrer=${referrer}`;
expect(iframe).to.not.be.null;
const timeArgPosition = iframe.src.lastIndexOf('&');
const iframeSrcWithoutTime = iframe.src.substr(0, timeArgPosition);
expect(iframeSrcWithoutTime).to.equal(correctIFrameSrc);
});
});
it('both::resizes amp-vk element in response to postmessages', () => {
return createAmpVkElement(POLL_PARAMS).then(vkPoll => {
const impl = vkPoll.implementation_;
const iframe = vkPoll.querySelector('iframe');
const changeHeight = sandbox.spy(impl, 'changeHeight');
const fakeHeight = 555;
expect(iframe).to.not.be.null;
generatePostMessage(vkPoll, iframe, fakeHeight);
expect(changeHeight).to.be.calledOnce;
expect(changeHeight.firstCall.args[0]).to.equal(fakeHeight);
});
});
function generatePostMessage(ins, iframe, height) {
ins.implementation_.handleVkIframeMessage_({
origin: 'https://vk.com',
source: iframe.contentWindow,
data: JSON.stringify([
'resize',
[height],
]),
});
}
});
| engtat/amphtml | extensions/amp-vk/0.1/test/test-amp-vk.js | JavaScript | apache-2.0 | 7,420 |
/*
Copyright 2014 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package userspace
import (
"fmt"
"net"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/golang/glog"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/proxy"
"k8s.io/kubernetes/pkg/types"
"k8s.io/kubernetes/pkg/util"
"k8s.io/kubernetes/pkg/util/errors"
"k8s.io/kubernetes/pkg/util/iptables"
)
type portal struct {
ip net.IP
port int
isExternal bool
}
type serviceInfo struct {
isAliveAtomic int32 // Only access this with atomic ops
portal portal
protocol api.Protocol
proxyPort int
socket proxySocket
timeout time.Duration
activeClients *clientCache
nodePort int
loadBalancerStatus api.LoadBalancerStatus
sessionAffinityType api.ServiceAffinity
stickyMaxAgeMinutes int
// Deprecated, but required for back-compat (including e2e)
externalIPs []string
}
func (info *serviceInfo) setAlive(b bool) {
var i int32
if b {
i = 1
}
atomic.StoreInt32(&info.isAliveAtomic, i)
}
func (info *serviceInfo) isAlive() bool {
return atomic.LoadInt32(&info.isAliveAtomic) != 0
}
func logTimeout(err error) bool {
if e, ok := err.(net.Error); ok {
if e.Timeout() {
glog.V(3).Infof("connection to endpoint closed due to inactivity")
return true
}
}
return false
}
// Proxier is a simple proxy for TCP connections between a localhost:lport
// and services that provide the actual implementations.
type Proxier struct {
loadBalancer LoadBalancer
mu sync.Mutex // protects serviceMap
serviceMap map[proxy.ServicePortName]*serviceInfo
syncPeriod time.Duration
portMapMutex sync.Mutex
portMap map[portMapKey]*portMapValue
numProxyLoops int32 // use atomic ops to access this; mostly for testing
listenIP net.IP
iptables iptables.Interface
hostIP net.IP
proxyPorts PortAllocator
}
// assert Proxier is a ProxyProvider
var _ proxy.ProxyProvider = &Proxier{}
// A key for the portMap. The ip has to be a tring because slices can't be map
// keys.
type portMapKey struct {
ip string
port int
protocol api.Protocol
}
func (k *portMapKey) String() string {
return fmt.Sprintf("%s:%d/%s", k.ip, k.port, k.protocol)
}
// A value for the portMap
type portMapValue struct {
owner proxy.ServicePortName
socket interface {
Close() error
}
}
var (
// ErrProxyOnLocalhost is returned by NewProxier if the user requests a proxier on
// the loopback address. May be checked for by callers of NewProxier to know whether
// the caller provided invalid input.
ErrProxyOnLocalhost = fmt.Errorf("cannot proxy on localhost")
)
// IsProxyLocked returns true if the proxy could not acquire the lock on iptables.
func IsProxyLocked(err error) bool {
return strings.Contains(err.Error(), "holding the xtables lock")
}
// NewProxier returns a new Proxier given a LoadBalancer and an address on
// which to listen. Because of the iptables logic, It is assumed that there
// is only a single Proxier active on a machine. An error will be returned if
// the proxier cannot be started due to an invalid ListenIP (loopback) or
// if iptables fails to update or acquire the initial lock. Once a proxier is
// created, it will keep iptables up to date in the background and will not
// terminate if a particular iptables call fails.
func NewProxier(loadBalancer LoadBalancer, listenIP net.IP, iptables iptables.Interface, pr util.PortRange, syncPeriod time.Duration) (*Proxier, error) {
if listenIP.Equal(localhostIPv4) || listenIP.Equal(localhostIPv6) {
return nil, ErrProxyOnLocalhost
}
hostIP, err := util.ChooseHostInterface()
if err != nil {
return nil, fmt.Errorf("failed to select a host interface: %v", err)
}
err = setRLimit(64 * 1000)
if err != nil {
return nil, fmt.Errorf("failed to set open file handler limit", err)
}
proxyPorts := newPortAllocator(pr)
glog.V(2).Infof("Setting proxy IP to %v and initializing iptables", hostIP)
return createProxier(loadBalancer, listenIP, iptables, hostIP, proxyPorts, syncPeriod)
}
func setRLimit(limit uint64) error {
return syscall.Setrlimit(syscall.RLIMIT_NOFILE, &syscall.Rlimit{Max: limit, Cur: limit})
}
func createProxier(loadBalancer LoadBalancer, listenIP net.IP, iptables iptables.Interface, hostIP net.IP, proxyPorts PortAllocator, syncPeriod time.Duration) (*Proxier, error) {
// convenient to pass nil for tests..
if proxyPorts == nil {
proxyPorts = newPortAllocator(util.PortRange{})
}
// Set up the iptables foundations we need.
if err := iptablesInit(iptables); err != nil {
return nil, fmt.Errorf("failed to initialize iptables: %v", err)
}
// Flush old iptables rules (since the bound ports will be invalid after a restart).
// When OnUpdate() is first called, the rules will be recreated.
if err := iptablesFlush(iptables); err != nil {
return nil, fmt.Errorf("failed to flush iptables: %v", err)
}
return &Proxier{
loadBalancer: loadBalancer,
serviceMap: make(map[proxy.ServicePortName]*serviceInfo),
portMap: make(map[portMapKey]*portMapValue),
syncPeriod: syncPeriod,
listenIP: listenIP,
iptables: iptables,
hostIP: hostIP,
proxyPorts: proxyPorts,
}, nil
}
// CleanupLeftovers removes all iptables rules and chains created by the Proxier
// It returns true if an error was encountered. Errors are logged.
func CleanupLeftovers(ipt iptables.Interface) (encounteredError bool) {
// NOTE: Warning, this needs to be kept in sync with the userspace Proxier,
// we want to ensure we remove all of the iptables rules it creates.
// Currently they are all in iptablesInit()
// Delete Rules first, then Flush and Delete Chains
args := []string{"-m", "comment", "--comment", "handle ClusterIPs; NOTE: this must be before the NodePort rules"}
if err := ipt.DeleteRule(iptables.TableNAT, iptables.ChainOutput, append(args, "-j", string(iptablesHostPortalChain))...); err != nil {
glog.Errorf("Error removing userspace rule: %v", err)
encounteredError = true
}
if err := ipt.DeleteRule(iptables.TableNAT, iptables.ChainPrerouting, append(args, "-j", string(iptablesContainerPortalChain))...); err != nil {
glog.Errorf("Error removing userspace rule: %v", err)
encounteredError = true
}
args = []string{"-m", "addrtype", "--dst-type", "LOCAL"}
args = append(args, "-m", "comment", "--comment", "handle service NodePorts; NOTE: this must be the last rule in the chain")
if err := ipt.DeleteRule(iptables.TableNAT, iptables.ChainOutput, append(args, "-j", string(iptablesHostNodePortChain))...); err != nil {
glog.Errorf("Error removing userspace rule: %v", err)
encounteredError = true
}
if err := ipt.DeleteRule(iptables.TableNAT, iptables.ChainPrerouting, append(args, "-j", string(iptablesContainerNodePortChain))...); err != nil {
glog.Errorf("Error removing userspace rule: %v", err)
encounteredError = true
}
// flush and delete chains.
chains := []iptables.Chain{iptablesContainerPortalChain, iptablesHostPortalChain, iptablesHostNodePortChain, iptablesContainerNodePortChain}
for _, c := range chains {
// flush chain, then if sucessful delete, delete will fail if flush fails.
if err := ipt.FlushChain(iptables.TableNAT, c); err != nil {
glog.Errorf("Error flushing userspace chain: %v", err)
encounteredError = true
} else {
if err = ipt.DeleteChain(iptables.TableNAT, c); err != nil {
glog.Errorf("Error deleting userspace chain: %v", err)
encounteredError = true
}
}
}
return encounteredError
}
// Sync is called to immediately synchronize the proxier state to iptables
func (proxier *Proxier) Sync() {
if err := iptablesInit(proxier.iptables); err != nil {
glog.Errorf("Failed to ensure iptables: %v", err)
}
proxier.ensurePortals()
proxier.cleanupStaleStickySessions()
}
// SyncLoop runs periodic work. This is expected to run as a goroutine or as the main loop of the app. It does not return.
func (proxier *Proxier) SyncLoop() {
t := time.NewTicker(proxier.syncPeriod)
defer t.Stop()
for {
<-t.C
glog.V(6).Infof("Periodic sync")
proxier.Sync()
}
}
// Ensure that portals exist for all services.
func (proxier *Proxier) ensurePortals() {
proxier.mu.Lock()
defer proxier.mu.Unlock()
// NB: This does not remove rules that should not be present.
for name, info := range proxier.serviceMap {
err := proxier.openPortal(name, info)
if err != nil {
glog.Errorf("Failed to ensure portal for %q: %v", name, err)
}
}
}
// clean up any stale sticky session records in the hash map.
func (proxier *Proxier) cleanupStaleStickySessions() {
proxier.mu.Lock()
defer proxier.mu.Unlock()
for name := range proxier.serviceMap {
proxier.loadBalancer.CleanupStaleStickySessions(name)
}
}
// This assumes proxier.mu is not locked.
func (proxier *Proxier) stopProxy(service proxy.ServicePortName, info *serviceInfo) error {
proxier.mu.Lock()
defer proxier.mu.Unlock()
return proxier.stopProxyInternal(service, info)
}
// This assumes proxier.mu is locked.
func (proxier *Proxier) stopProxyInternal(service proxy.ServicePortName, info *serviceInfo) error {
delete(proxier.serviceMap, service)
info.setAlive(false)
err := info.socket.Close()
port := info.socket.ListenPort()
proxier.proxyPorts.Release(port)
return err
}
func (proxier *Proxier) getServiceInfo(service proxy.ServicePortName) (*serviceInfo, bool) {
proxier.mu.Lock()
defer proxier.mu.Unlock()
info, ok := proxier.serviceMap[service]
return info, ok
}
func (proxier *Proxier) setServiceInfo(service proxy.ServicePortName, info *serviceInfo) {
proxier.mu.Lock()
defer proxier.mu.Unlock()
proxier.serviceMap[service] = info
}
// addServiceOnPort starts listening for a new service, returning the serviceInfo.
// Pass proxyPort=0 to allocate a random port. The timeout only applies to UDP
// connections, for now.
func (proxier *Proxier) addServiceOnPort(service proxy.ServicePortName, protocol api.Protocol, proxyPort int, timeout time.Duration) (*serviceInfo, error) {
sock, err := newProxySocket(protocol, proxier.listenIP, proxyPort)
if err != nil {
return nil, err
}
_, portStr, err := net.SplitHostPort(sock.Addr().String())
if err != nil {
sock.Close()
return nil, err
}
portNum, err := strconv.Atoi(portStr)
if err != nil {
sock.Close()
return nil, err
}
si := &serviceInfo{
isAliveAtomic: 1,
proxyPort: portNum,
protocol: protocol,
socket: sock,
timeout: timeout,
activeClients: newClientCache(),
sessionAffinityType: api.ServiceAffinityNone, // default
stickyMaxAgeMinutes: 180, // TODO: parameterize this in the API.
}
proxier.setServiceInfo(service, si)
glog.V(2).Infof("Proxying for service %q on %s port %d", service, protocol, portNum)
go func(service proxy.ServicePortName, proxier *Proxier) {
defer util.HandleCrash()
atomic.AddInt32(&proxier.numProxyLoops, 1)
sock.ProxyLoop(service, si, proxier)
atomic.AddInt32(&proxier.numProxyLoops, -1)
}(service, proxier)
return si, nil
}
// How long we leave idle UDP connections open.
const udpIdleTimeout = 1 * time.Second
// OnUpdate manages the active set of service proxies.
// Active service proxies are reinitialized if found in the update set or
// shutdown if missing from the update set.
func (proxier *Proxier) OnServiceUpdate(services []api.Service) {
glog.V(4).Infof("Received update notice: %+v", services)
activeServices := make(map[proxy.ServicePortName]bool) // use a map as a set
for i := range services {
service := &services[i]
// if ClusterIP is "None" or empty, skip proxying
if !api.IsServiceIPSet(service) {
glog.V(3).Infof("Skipping service %s due to clusterIP = %q", types.NamespacedName{Namespace: service.Namespace, Name: service.Name}, service.Spec.ClusterIP)
continue
}
for i := range service.Spec.Ports {
servicePort := &service.Spec.Ports[i]
serviceName := proxy.ServicePortName{NamespacedName: types.NamespacedName{Namespace: service.Namespace, Name: service.Name}, Port: servicePort.Name}
activeServices[serviceName] = true
serviceIP := net.ParseIP(service.Spec.ClusterIP)
info, exists := proxier.getServiceInfo(serviceName)
// TODO: check health of the socket? What if ProxyLoop exited?
if exists && sameConfig(info, service, servicePort) {
// Nothing changed.
continue
}
if exists {
glog.V(4).Infof("Something changed for service %q: stopping it", serviceName)
err := proxier.closePortal(serviceName, info)
if err != nil {
glog.Errorf("Failed to close portal for %q: %v", serviceName, err)
}
err = proxier.stopProxy(serviceName, info)
if err != nil {
glog.Errorf("Failed to stop service %q: %v", serviceName, err)
}
}
proxyPort, err := proxier.proxyPorts.AllocateNext()
if err != nil {
glog.Errorf("failed to allocate proxy port for service %q: %v", serviceName, err)
continue
}
glog.V(1).Infof("Adding new service %q at %s:%d/%s", serviceName, serviceIP, servicePort.Port, servicePort.Protocol)
info, err = proxier.addServiceOnPort(serviceName, servicePort.Protocol, proxyPort, udpIdleTimeout)
if err != nil {
glog.Errorf("Failed to start proxy for %q: %v", serviceName, err)
continue
}
info.portal.ip = serviceIP
info.portal.port = servicePort.Port
info.externalIPs = service.Spec.ExternalIPs
// Deep-copy in case the service instance changes
info.loadBalancerStatus = *api.LoadBalancerStatusDeepCopy(&service.Status.LoadBalancer)
info.nodePort = servicePort.NodePort
info.sessionAffinityType = service.Spec.SessionAffinity
glog.V(4).Infof("info: %+v", info)
err = proxier.openPortal(serviceName, info)
if err != nil {
glog.Errorf("Failed to open portal for %q: %v", serviceName, err)
}
proxier.loadBalancer.NewService(serviceName, info.sessionAffinityType, info.stickyMaxAgeMinutes)
}
}
proxier.mu.Lock()
defer proxier.mu.Unlock()
for name, info := range proxier.serviceMap {
if !activeServices[name] {
glog.V(1).Infof("Stopping service %q", name)
err := proxier.closePortal(name, info)
if err != nil {
glog.Errorf("Failed to close portal for %q: %v", name, err)
}
err = proxier.stopProxyInternal(name, info)
if err != nil {
glog.Errorf("Failed to stop service %q: %v", name, err)
}
}
}
}
func sameConfig(info *serviceInfo, service *api.Service, port *api.ServicePort) bool {
if info.protocol != port.Protocol || info.portal.port != port.Port || info.nodePort != port.NodePort {
return false
}
if !info.portal.ip.Equal(net.ParseIP(service.Spec.ClusterIP)) {
return false
}
if !ipsEqual(info.externalIPs, service.Spec.ExternalIPs) {
return false
}
if !api.LoadBalancerStatusEqual(&info.loadBalancerStatus, &service.Status.LoadBalancer) {
return false
}
if info.sessionAffinityType != service.Spec.SessionAffinity {
return false
}
return true
}
func ipsEqual(lhs, rhs []string) bool {
if len(lhs) != len(rhs) {
return false
}
for i := range lhs {
if lhs[i] != rhs[i] {
return false
}
}
return true
}
func (proxier *Proxier) openPortal(service proxy.ServicePortName, info *serviceInfo) error {
err := proxier.openOnePortal(info.portal, info.protocol, proxier.listenIP, info.proxyPort, service)
if err != nil {
return err
}
for _, publicIP := range info.externalIPs {
err = proxier.openOnePortal(portal{net.ParseIP(publicIP), info.portal.port, true}, info.protocol, proxier.listenIP, info.proxyPort, service)
if err != nil {
return err
}
}
for _, ingress := range info.loadBalancerStatus.Ingress {
if ingress.IP != "" {
err = proxier.openOnePortal(portal{net.ParseIP(ingress.IP), info.portal.port, false}, info.protocol, proxier.listenIP, info.proxyPort, service)
if err != nil {
return err
}
}
}
if info.nodePort != 0 {
err = proxier.openNodePort(info.nodePort, info.protocol, proxier.listenIP, info.proxyPort, service)
if err != nil {
return err
}
}
return nil
}
func (proxier *Proxier) openOnePortal(portal portal, protocol api.Protocol, proxyIP net.IP, proxyPort int, name proxy.ServicePortName) error {
if local, err := isLocalIP(portal.ip); err != nil {
return fmt.Errorf("can't determine if IP is local, assuming not: %v", err)
} else if local {
err := proxier.claimNodePort(portal.ip, portal.port, protocol, name)
if err != nil {
return err
}
}
// Handle traffic from containers.
args := proxier.iptablesContainerPortalArgs(portal.ip, portal.isExternal, false, portal.port, protocol, proxyIP, proxyPort, name)
existed, err := proxier.iptables.EnsureRule(iptables.Append, iptables.TableNAT, iptablesContainerPortalChain, args...)
if err != nil {
glog.Errorf("Failed to install iptables %s rule for service %q, args:%v", iptablesContainerPortalChain, name, args)
return err
}
if !existed {
glog.V(3).Infof("Opened iptables from-containers portal for service %q on %s %s:%d", name, protocol, portal.ip, portal.port)
}
if portal.isExternal {
args := proxier.iptablesContainerPortalArgs(portal.ip, false, true, portal.port, protocol, proxyIP, proxyPort, name)
existed, err := proxier.iptables.EnsureRule(iptables.Append, iptables.TableNAT, iptablesContainerPortalChain, args...)
if err != nil {
glog.Errorf("Failed to install iptables %s rule that opens service %q for local traffic, args:%v", iptablesContainerPortalChain, name, args)
return err
}
if !existed {
glog.V(3).Infof("Opened iptables from-containers portal for service %q on %s %s:%d for local traffic", name, protocol, portal.ip, portal.port)
}
args = proxier.iptablesHostPortalArgs(portal.ip, true, portal.port, protocol, proxyIP, proxyPort, name)
existed, err = proxier.iptables.EnsureRule(iptables.Append, iptables.TableNAT, iptablesHostPortalChain, args...)
if err != nil {
glog.Errorf("Failed to install iptables %s rule for service %q for dst-local traffic", iptablesHostPortalChain, name)
return err
}
if !existed {
glog.V(3).Infof("Opened iptables from-host portal for service %q on %s %s:%d for dst-local traffic", name, protocol, portal.ip, portal.port)
}
return nil
}
// Handle traffic from the host.
args = proxier.iptablesHostPortalArgs(portal.ip, false, portal.port, protocol, proxyIP, proxyPort, name)
existed, err = proxier.iptables.EnsureRule(iptables.Append, iptables.TableNAT, iptablesHostPortalChain, args...)
if err != nil {
glog.Errorf("Failed to install iptables %s rule for service %q", iptablesHostPortalChain, name)
return err
}
if !existed {
glog.V(3).Infof("Opened iptables from-host portal for service %q on %s %s:%d", name, protocol, portal.ip, portal.port)
}
return nil
}
// Marks a port as being owned by a particular service, or returns error if already claimed.
// Idempotent: reclaiming with the same owner is not an error
func (proxier *Proxier) claimNodePort(ip net.IP, port int, protocol api.Protocol, owner proxy.ServicePortName) error {
proxier.portMapMutex.Lock()
defer proxier.portMapMutex.Unlock()
// TODO: We could pre-populate some reserved ports into portMap and/or blacklist some well-known ports
key := portMapKey{ip: ip.String(), port: port, protocol: protocol}
existing, found := proxier.portMap[key]
if !found {
// Hold the actual port open, even though we use iptables to redirect
// it. This ensures that a) it's safe to take and b) that stays true.
// NOTE: We should not need to have a real listen()ing socket - bind()
// should be enough, but I can't figure out a way to e2e test without
// it. Tools like 'ss' and 'netstat' do not show sockets that are
// bind()ed but not listen()ed, and at least the default debian netcat
// has no way to avoid about 10 seconds of retries.
socket, err := newProxySocket(protocol, ip, port)
if err != nil {
return fmt.Errorf("can't open node port for %s: %v", key.String(), err)
}
proxier.portMap[key] = &portMapValue{owner: owner, socket: socket}
glog.V(2).Infof("Claimed local port %s", key.String())
return nil
}
if existing.owner == owner {
// We are idempotent
return nil
}
return fmt.Errorf("Port conflict detected on port %s. %v vs %v", key.String(), owner, existing)
}
// Release a claim on a port. Returns an error if the owner does not match the claim.
// Tolerates release on an unclaimed port, to simplify .
func (proxier *Proxier) releaseNodePort(ip net.IP, port int, protocol api.Protocol, owner proxy.ServicePortName) error {
proxier.portMapMutex.Lock()
defer proxier.portMapMutex.Unlock()
key := portMapKey{ip: ip.String(), port: port, protocol: protocol}
existing, found := proxier.portMap[key]
if !found {
// We tolerate this, it happens if we are cleaning up a failed allocation
glog.Infof("Ignoring release on unowned port: %v", key)
return nil
}
if existing.owner != owner {
return fmt.Errorf("Port conflict detected on port %v (unowned unlock). %v vs %v", key, owner, existing)
}
delete(proxier.portMap, key)
existing.socket.Close()
return nil
}
func (proxier *Proxier) openNodePort(nodePort int, protocol api.Protocol, proxyIP net.IP, proxyPort int, name proxy.ServicePortName) error {
// TODO: Do we want to allow containers to access public services? Probably yes.
// TODO: We could refactor this to be the same code as portal, but with IP == nil
err := proxier.claimNodePort(nil, nodePort, protocol, name)
if err != nil {
return err
}
// Handle traffic from containers.
args := proxier.iptablesContainerNodePortArgs(nodePort, protocol, proxyIP, proxyPort, name)
existed, err := proxier.iptables.EnsureRule(iptables.Append, iptables.TableNAT, iptablesContainerNodePortChain, args...)
if err != nil {
glog.Errorf("Failed to install iptables %s rule for service %q", iptablesContainerNodePortChain, name)
return err
}
if !existed {
glog.Infof("Opened iptables from-containers public port for service %q on %s port %d", name, protocol, nodePort)
}
// Handle traffic from the host.
args = proxier.iptablesHostNodePortArgs(nodePort, protocol, proxyIP, proxyPort, name)
existed, err = proxier.iptables.EnsureRule(iptables.Append, iptables.TableNAT, iptablesHostNodePortChain, args...)
if err != nil {
glog.Errorf("Failed to install iptables %s rule for service %q", iptablesHostNodePortChain, name)
return err
}
if !existed {
glog.Infof("Opened iptables from-host public port for service %q on %s port %d", name, protocol, nodePort)
}
return nil
}
func (proxier *Proxier) closePortal(service proxy.ServicePortName, info *serviceInfo) error {
// Collect errors and report them all at the end.
el := proxier.closeOnePortal(info.portal, info.protocol, proxier.listenIP, info.proxyPort, service)
for _, publicIP := range info.externalIPs {
el = append(el, proxier.closeOnePortal(portal{net.ParseIP(publicIP), info.portal.port, true}, info.protocol, proxier.listenIP, info.proxyPort, service)...)
}
for _, ingress := range info.loadBalancerStatus.Ingress {
if ingress.IP != "" {
el = append(el, proxier.closeOnePortal(portal{net.ParseIP(ingress.IP), info.portal.port, false}, info.protocol, proxier.listenIP, info.proxyPort, service)...)
}
}
if info.nodePort != 0 {
el = append(el, proxier.closeNodePort(info.nodePort, info.protocol, proxier.listenIP, info.proxyPort, service)...)
}
if len(el) == 0 {
glog.V(3).Infof("Closed iptables portals for service %q", service)
} else {
glog.Errorf("Some errors closing iptables portals for service %q", service)
}
return errors.NewAggregate(el)
}
func (proxier *Proxier) closeOnePortal(portal portal, protocol api.Protocol, proxyIP net.IP, proxyPort int, name proxy.ServicePortName) []error {
el := []error{}
if local, err := isLocalIP(portal.ip); err != nil {
el = append(el, fmt.Errorf("can't determine if IP is local, assuming not: %v", err))
} else if local {
if err := proxier.releaseNodePort(nil, portal.port, protocol, name); err != nil {
el = append(el, err)
}
}
// Handle traffic from containers.
args := proxier.iptablesContainerPortalArgs(portal.ip, portal.isExternal, false, portal.port, protocol, proxyIP, proxyPort, name)
if err := proxier.iptables.DeleteRule(iptables.TableNAT, iptablesContainerPortalChain, args...); err != nil {
glog.Errorf("Failed to delete iptables %s rule for service %q", iptablesContainerPortalChain, name)
el = append(el, err)
}
if portal.isExternal {
args := proxier.iptablesContainerPortalArgs(portal.ip, false, true, portal.port, protocol, proxyIP, proxyPort, name)
if err := proxier.iptables.DeleteRule(iptables.TableNAT, iptablesContainerPortalChain, args...); err != nil {
glog.Errorf("Failed to delete iptables %s rule for service %q", iptablesContainerPortalChain, name)
el = append(el, err)
}
args = proxier.iptablesHostPortalArgs(portal.ip, true, portal.port, protocol, proxyIP, proxyPort, name)
if err := proxier.iptables.DeleteRule(iptables.TableNAT, iptablesHostPortalChain, args...); err != nil {
glog.Errorf("Failed to delete iptables %s rule for service %q", iptablesHostPortalChain, name)
el = append(el, err)
}
return el
}
// Handle traffic from the host (portalIP is not external).
args = proxier.iptablesHostPortalArgs(portal.ip, false, portal.port, protocol, proxyIP, proxyPort, name)
if err := proxier.iptables.DeleteRule(iptables.TableNAT, iptablesHostPortalChain, args...); err != nil {
glog.Errorf("Failed to delete iptables %s rule for service %q", iptablesHostPortalChain, name)
el = append(el, err)
}
return el
}
func (proxier *Proxier) closeNodePort(nodePort int, protocol api.Protocol, proxyIP net.IP, proxyPort int, name proxy.ServicePortName) []error {
el := []error{}
// Handle traffic from containers.
args := proxier.iptablesContainerNodePortArgs(nodePort, protocol, proxyIP, proxyPort, name)
if err := proxier.iptables.DeleteRule(iptables.TableNAT, iptablesContainerNodePortChain, args...); err != nil {
glog.Errorf("Failed to delete iptables %s rule for service %q", iptablesContainerNodePortChain, name)
el = append(el, err)
}
// Handle traffic from the host.
args = proxier.iptablesHostNodePortArgs(nodePort, protocol, proxyIP, proxyPort, name)
if err := proxier.iptables.DeleteRule(iptables.TableNAT, iptablesHostNodePortChain, args...); err != nil {
glog.Errorf("Failed to delete iptables %s rule for service %q", iptablesHostNodePortChain, name)
el = append(el, err)
}
if err := proxier.releaseNodePort(nil, nodePort, protocol, name); err != nil {
el = append(el, err)
}
return el
}
func isLocalIP(ip net.IP) (bool, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return false, err
}
for i := range addrs {
intf, _, err := net.ParseCIDR(addrs[i].String())
if err != nil {
return false, err
}
if ip.Equal(intf) {
return true, nil
}
}
return false, nil
}
// See comments in the *PortalArgs() functions for some details about why we
// use two chains for portals.
var iptablesContainerPortalChain iptables.Chain = "KUBE-PORTALS-CONTAINER"
var iptablesHostPortalChain iptables.Chain = "KUBE-PORTALS-HOST"
// Chains for NodePort services
var iptablesContainerNodePortChain iptables.Chain = "KUBE-NODEPORT-CONTAINER"
var iptablesHostNodePortChain iptables.Chain = "KUBE-NODEPORT-HOST"
// Ensure that the iptables infrastructure we use is set up. This can safely be called periodically.
func iptablesInit(ipt iptables.Interface) error {
// TODO: There is almost certainly room for optimization here. E.g. If
// we knew the service-cluster-ip-range CIDR we could fast-track outbound packets not
// destined for a service. There's probably more, help wanted.
// Danger - order of these rules matters here:
//
// We match portal rules first, then NodePort rules. For NodePort rules, we filter primarily on --dst-type LOCAL,
// because we want to listen on all local addresses, but don't match internet traffic with the same dst port number.
//
// There is one complication (per thockin):
// -m addrtype --dst-type LOCAL is what we want except that it is broken (by intent without foresight to our usecase)
// on at least GCE. Specifically, GCE machines have a daemon which learns what external IPs are forwarded to that
// machine, and configure a local route for that IP, making a match for --dst-type LOCAL when we don't want it to.
// Removing the route gives correct behavior until the daemon recreates it.
// Killing the daemon is an option, but means that any non-kubernetes use of the machine with external IP will be broken.
//
// This applies to IPs on GCE that are actually from a load-balancer; they will be categorized as LOCAL.
// _If_ the chains were in the wrong order, and the LB traffic had dst-port == a NodePort on some other service,
// the NodePort would take priority (incorrectly).
// This is unlikely (and would only affect outgoing traffic from the cluster to the load balancer, which seems
// doubly-unlikely), but we need to be careful to keep the rules in the right order.
args := []string{ /* service-cluster-ip-range matching could go here */ }
args = append(args, "-m", "comment", "--comment", "handle ClusterIPs; NOTE: this must be before the NodePort rules")
if _, err := ipt.EnsureChain(iptables.TableNAT, iptablesContainerPortalChain); err != nil {
return err
}
if _, err := ipt.EnsureRule(iptables.Prepend, iptables.TableNAT, iptables.ChainPrerouting, append(args, "-j", string(iptablesContainerPortalChain))...); err != nil {
return err
}
if _, err := ipt.EnsureChain(iptables.TableNAT, iptablesHostPortalChain); err != nil {
return err
}
if _, err := ipt.EnsureRule(iptables.Prepend, iptables.TableNAT, iptables.ChainOutput, append(args, "-j", string(iptablesHostPortalChain))...); err != nil {
return err
}
// This set of rules matches broadly (addrtype & destination port), and therefore must come after the portal rules
args = []string{"-m", "addrtype", "--dst-type", "LOCAL"}
args = append(args, "-m", "comment", "--comment", "handle service NodePorts; NOTE: this must be the last rule in the chain")
if _, err := ipt.EnsureChain(iptables.TableNAT, iptablesContainerNodePortChain); err != nil {
return err
}
if _, err := ipt.EnsureRule(iptables.Append, iptables.TableNAT, iptables.ChainPrerouting, append(args, "-j", string(iptablesContainerNodePortChain))...); err != nil {
return err
}
if _, err := ipt.EnsureChain(iptables.TableNAT, iptablesHostNodePortChain); err != nil {
return err
}
if _, err := ipt.EnsureRule(iptables.Append, iptables.TableNAT, iptables.ChainOutput, append(args, "-j", string(iptablesHostNodePortChain))...); err != nil {
return err
}
// TODO: Verify order of rules.
return nil
}
// Flush all of our custom iptables rules.
func iptablesFlush(ipt iptables.Interface) error {
el := []error{}
if err := ipt.FlushChain(iptables.TableNAT, iptablesContainerPortalChain); err != nil {
el = append(el, err)
}
if err := ipt.FlushChain(iptables.TableNAT, iptablesHostPortalChain); err != nil {
el = append(el, err)
}
if err := ipt.FlushChain(iptables.TableNAT, iptablesContainerNodePortChain); err != nil {
el = append(el, err)
}
if err := ipt.FlushChain(iptables.TableNAT, iptablesHostNodePortChain); err != nil {
el = append(el, err)
}
if len(el) != 0 {
glog.Errorf("Some errors flushing old iptables portals: %v", el)
}
return errors.NewAggregate(el)
}
// Used below.
var zeroIPv4 = net.ParseIP("0.0.0.0")
var localhostIPv4 = net.ParseIP("127.0.0.1")
var zeroIPv6 = net.ParseIP("::0")
var localhostIPv6 = net.ParseIP("::1")
// Build a slice of iptables args that are common to from-container and from-host portal rules.
func iptablesCommonPortalArgs(destIP net.IP, addPhysicalInterfaceMatch bool, addDstLocalMatch bool, destPort int, protocol api.Protocol, service proxy.ServicePortName) []string {
// This list needs to include all fields as they are eventually spit out
// by iptables-save. This is because some systems do not support the
// 'iptables -C' arg, and so fall back on parsing iptables-save output.
// If this does not match, it will not pass the check. For example:
// adding the /32 on the destination IP arg is not strictly required,
// but causes this list to not match the final iptables-save output.
// This is fragile and I hope one day we can stop supporting such old
// iptables versions.
args := []string{
"-m", "comment",
"--comment", service.String(),
"-p", strings.ToLower(string(protocol)),
"-m", strings.ToLower(string(protocol)),
"--dport", fmt.Sprintf("%d", destPort),
}
if destIP != nil {
args = append(args, "-d", fmt.Sprintf("%s/32", destIP.String()))
}
if addPhysicalInterfaceMatch {
args = append(args, "-m", "physdev", "!", "--physdev-is-in")
}
if addDstLocalMatch {
args = append(args, "-m", "addrtype", "--dst-type", "LOCAL")
}
return args
}
// Build a slice of iptables args for a from-container portal rule.
func (proxier *Proxier) iptablesContainerPortalArgs(destIP net.IP, addPhysicalInterfaceMatch bool, addDstLocalMatch bool, destPort int, protocol api.Protocol, proxyIP net.IP, proxyPort int, service proxy.ServicePortName) []string {
args := iptablesCommonPortalArgs(destIP, addPhysicalInterfaceMatch, addDstLocalMatch, destPort, protocol, service)
// This is tricky.
//
// If the proxy is bound (see Proxier.listenIP) to 0.0.0.0 ("any
// interface") we want to use REDIRECT, which sends traffic to the
// "primary address of the incoming interface" which means the container
// bridge, if there is one. When the response comes, it comes from that
// same interface, so the NAT matches and the response packet is
// correct. This matters for UDP, since there is no per-connection port
// number.
//
// The alternative would be to use DNAT, except that it doesn't work
// (empirically):
// * DNAT to 127.0.0.1 = Packets just disappear - this seems to be a
// well-known limitation of iptables.
// * DNAT to eth0's IP = Response packets come from the bridge, which
// breaks the NAT, and makes things like DNS not accept them. If
// this could be resolved, it would simplify all of this code.
//
// If the proxy is bound to a specific IP, then we have to use DNAT to
// that IP. Unlike the previous case, this works because the proxy is
// ONLY listening on that IP, not the bridge.
//
// Why would anyone bind to an address that is not inclusive of
// localhost? Apparently some cloud environments have their public IP
// exposed as a real network interface AND do not have firewalling. We
// don't want to expose everything out to the world.
//
// Unfortunately, I don't know of any way to listen on some (N > 1)
// interfaces but not ALL interfaces, short of doing it manually, and
// this is simpler than that.
//
// If the proxy is bound to localhost only, all of this is broken. Not
// allowed.
if proxyIP.Equal(zeroIPv4) || proxyIP.Equal(zeroIPv6) {
// TODO: Can we REDIRECT with IPv6?
args = append(args, "-j", "REDIRECT", "--to-ports", fmt.Sprintf("%d", proxyPort))
} else {
// TODO: Can we DNAT with IPv6?
args = append(args, "-j", "DNAT", "--to-destination", net.JoinHostPort(proxyIP.String(), strconv.Itoa(proxyPort)))
}
return args
}
// Build a slice of iptables args for a from-host portal rule.
func (proxier *Proxier) iptablesHostPortalArgs(destIP net.IP, addDstLocalMatch bool, destPort int, protocol api.Protocol, proxyIP net.IP, proxyPort int, service proxy.ServicePortName) []string {
args := iptablesCommonPortalArgs(destIP, false, addDstLocalMatch, destPort, protocol, service)
// This is tricky.
//
// If the proxy is bound (see Proxier.listenIP) to 0.0.0.0 ("any
// interface") we want to do the same as from-container traffic and use
// REDIRECT. Except that it doesn't work (empirically). REDIRECT on
// localpackets sends the traffic to localhost (special case, but it is
// documented) but the response comes from the eth0 IP (not sure why,
// truthfully), which makes DNS unhappy.
//
// So we have to use DNAT. DNAT to 127.0.0.1 can't work for the same
// reason.
//
// So we do our best to find an interface that is not a loopback and
// DNAT to that. This works (again, empirically).
//
// If the proxy is bound to a specific IP, then we have to use DNAT to
// that IP. Unlike the previous case, this works because the proxy is
// ONLY listening on that IP, not the bridge.
//
// If the proxy is bound to localhost only, this should work, but we
// don't allow it for now.
if proxyIP.Equal(zeroIPv4) || proxyIP.Equal(zeroIPv6) {
proxyIP = proxier.hostIP
}
// TODO: Can we DNAT with IPv6?
args = append(args, "-j", "DNAT", "--to-destination", net.JoinHostPort(proxyIP.String(), strconv.Itoa(proxyPort)))
return args
}
// Build a slice of iptables args for a from-container public-port rule.
// See iptablesContainerPortalArgs
// TODO: Should we just reuse iptablesContainerPortalArgs?
func (proxier *Proxier) iptablesContainerNodePortArgs(nodePort int, protocol api.Protocol, proxyIP net.IP, proxyPort int, service proxy.ServicePortName) []string {
args := iptablesCommonPortalArgs(nil, false, false, nodePort, protocol, service)
if proxyIP.Equal(zeroIPv4) || proxyIP.Equal(zeroIPv6) {
// TODO: Can we REDIRECT with IPv6?
args = append(args, "-j", "REDIRECT", "--to-ports", fmt.Sprintf("%d", proxyPort))
} else {
// TODO: Can we DNAT with IPv6?
args = append(args, "-j", "DNAT", "--to-destination", net.JoinHostPort(proxyIP.String(), strconv.Itoa(proxyPort)))
}
return args
}
// Build a slice of iptables args for a from-host public-port rule.
// See iptablesHostPortalArgs
// TODO: Should we just reuse iptablesHostPortalArgs?
func (proxier *Proxier) iptablesHostNodePortArgs(nodePort int, protocol api.Protocol, proxyIP net.IP, proxyPort int, service proxy.ServicePortName) []string {
args := iptablesCommonPortalArgs(nil, false, false, nodePort, protocol, service)
if proxyIP.Equal(zeroIPv4) || proxyIP.Equal(zeroIPv6) {
proxyIP = proxier.hostIP
}
// TODO: Can we DNAT with IPv6?
args = append(args, "-j", "DNAT", "--to-destination", net.JoinHostPort(proxyIP.String(), strconv.Itoa(proxyPort)))
return args
}
func isTooManyFDsError(err error) bool {
return strings.Contains(err.Error(), "too many open files")
}
func isClosedError(err error) bool {
// A brief discussion about handling closed error here:
// https://code.google.com/p/go/issues/detail?id=4373#c14
// TODO: maybe create a stoppable TCP listener that returns a StoppedError
return strings.HasSuffix(err.Error(), "use of closed network connection")
}
| socaa/kubernetes | pkg/proxy/userspace/proxier.go | GO | apache-2.0 | 39,220 |
// +build go1.9
// Copyright 2019 Microsoft Corporation
//
// 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.
// This code was auto-generated by:
// github.com/Azure/azure-sdk-for-go/tools/profileBuilder
package marketplaceorderingapi
import original "github.com/Azure/azure-sdk-for-go/services/marketplaceordering/mgmt/2015-06-01/marketplaceordering/marketplaceorderingapi"
type MarketplaceAgreementsClientAPI = original.MarketplaceAgreementsClientAPI
type OperationsClientAPI = original.OperationsClientAPI
| ironcladlou/origin | vendor/github.com/Azure/azure-sdk-for-go/profiles/preview/marketplaceordering/mgmt/marketplaceordering/marketplaceorderingapi/models.go | GO | apache-2.0 | 1,018 |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/client/padding.h"
#include <algorithm>
#include "tensorflow/core/lib/math/math_util.h"
#include "tensorflow/core/platform/logging.h"
namespace xla {
std::vector<std::pair<int64, int64>> MakePadding(
tensorflow::gtl::ArraySlice<int64> input_dimensions,
tensorflow::gtl::ArraySlice<int64> window_dimensions,
tensorflow::gtl::ArraySlice<int64> window_strides, Padding padding) {
CHECK_EQ(input_dimensions.size(), window_dimensions.size());
CHECK_EQ(input_dimensions.size(), window_strides.size());
std::vector<std::pair<int64, int64>> low_high_padding;
switch (padding) {
case Padding::kValid:
low_high_padding.resize(window_dimensions.size(), {0, 0});
return low_high_padding;
case Padding::kSame:
for (int64 i = 0; i < input_dimensions.size(); ++i) {
int64 input_dimension = input_dimensions[i];
int64 window_dimension = window_dimensions[i];
int64 window_stride = window_strides[i];
// We follow the same convention as in Tensorflow, such that
// output dimension := ceil(input_dimension / window_stride).
// See tensorflow/tensorflow/python/ops/nn.py
// for the reference. See also tensorflow/core/kernels/ops_util.cc
// for the part where we avoid negative padding using max(0, x).
//
//
// For an odd sized window dimension 2N+1 with stride 1, the middle
// element is always inside the base area, so we can see it as N + 1 +
// N elements. In the example below, we have a kernel of size
// 2*3+1=7 so that the center element is 4 with 123 to the
// left and 567 to the right.
//
// base area: ------------------------
// kernel at left: 1234567
// kernel at right: 1234567
//
// We can see visually here that we need to pad the base area
// by 3 on each side:
//
// padded base area: 000------------------------000
//
// For an even number 2N, there are two options:
//
// *** Option A
//
// We view 2N as (N - 1) + 1 + N, so for N=3 we have 12 to the
// left, 3 is the center and 456 is to the right, like this:
//
// base area: ------------------------
// kernel at left: 123456
// kernel at right: 123456
// padded base area: 00------------------------000
//
// Note how we pad by one more to the right than to the left.
//
// *** Option B
//
// We view 2N as N + 1 + (N - 1), so for N=3 we have 123 to
// the left, 4 is the center and 56 is to the right, like
// this:
//
// base area: ------------------------
// kernel at left: 123456
// kernel at right: 123456
// padded base area: 000------------------------00
//
// The choice here is arbitrary. We choose option A as this is
// what DistBelief and Tensorflow do.
//
// When the stride is greater than 1, the output size is smaller than
// the input base size. The base area is padded such that the last
// window fully fits in the padded base area, and the padding amount is
// evenly divided between the left and the right (or 1 more on the right
// if odd size padding is required). The example below shows the
// required padding when the base size is 10, the kernel size is 5, and
// the stride is 3. In this example, the output size is 4.
//
// base area: ----------
// 1'st kernel: 12345
// 2'nd kernel: 12345
// 3'rd kernel: 12345
// 4'th kernel: 12345
// padded base area: 00----------00
int64 output_dimension =
tensorflow::MathUtil::CeilOfRatio(input_dimension, window_stride);
int64 padding_size =
std::max<int64>((output_dimension - 1) * window_stride +
window_dimension - input_dimension,
0);
low_high_padding.emplace_back(
tensorflow::MathUtil::FloorOfRatio(padding_size, 2ll),
tensorflow::MathUtil::CeilOfRatio(padding_size, 2ll));
}
break;
}
return low_high_padding;
}
} // namespace xla
| AsimmHirani/ISpyPi | tensorflow/contrib/tensorflow-master/tensorflow/compiler/xla/client/padding.cc | C++ | apache-2.0 | 5,186 |
/**
* 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.hdfs.server.namenode;
import java.io.File;
import java.io.IOException;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.fs.permission.PermissionStatus;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfo;
import org.apache.hadoop.hdfs.server.common.GenerationStamp;
import org.apache.hadoop.hdfs.server.common.Storage;
/**
*
* CreateEditsLog
* Synopsis: CreateEditsLog -f numFiles StartingBlockId numBlocksPerFile
* [-r replicafactor] [-d editsLogDirectory]
* Default replication factor is 1
* Default edits log directory is /tmp/EditsLogOut
*
* Create a name node's edits log in /tmp/EditsLogOut.
* The file /tmp/EditsLogOut/current/edits can be copied to a name node's
* dfs.namenode.name.dir/current direcotry and the name node can be started as usual.
*
* The files are created in /createdViaInjectingInEditsLog
* The file names contain the starting and ending blockIds; hence once can
* create multiple edits logs using this command using non overlapping
* block ids and feed the files to a single name node.
*
* See Also @link #DataNodeCluster for injecting a set of matching
* blocks created with this command into a set of simulated data nodes.
*
*/
public class CreateEditsLog {
static final String BASE_PATH = "/createdViaInjectingInEditsLog";
static final String EDITS_DIR = "/tmp/EditsLogOut";
static String edits_dir = EDITS_DIR;
static final public long BLOCK_GENERATION_STAMP =
GenerationStamp.LAST_RESERVED_STAMP;
static void addFiles(FSEditLog editLog, int numFiles, short replication,
int blocksPerFile, long startingBlockId, long blockSize,
FileNameGenerator nameGenerator) {
PermissionStatus p = new PermissionStatus("joeDoe", "people",
new FsPermission((short)0777));
INodeId inodeId = new INodeId();
INodeDirectory dirInode = new INodeDirectory(inodeId.nextValue(), null, p,
0L);
editLog.logMkDir(BASE_PATH, dirInode);
BlockInfo[] blocks = new BlockInfo[blocksPerFile];
for (int iB = 0; iB < blocksPerFile; ++iB) {
blocks[iB] =
new BlockInfo(new Block(0, blockSize, BLOCK_GENERATION_STAMP),
replication);
}
long currentBlockId = startingBlockId;
long bidAtSync = startingBlockId;
for (int iF = 0; iF < numFiles; iF++) {
for (int iB = 0; iB < blocksPerFile; ++iB) {
blocks[iB].setBlockId(currentBlockId++);
}
final INodeFile inode = new INodeFile(inodeId.nextValue(), null,
p, 0L, 0L, blocks, replication, blockSize, (byte)0);
inode.toUnderConstruction("", "");
// Append path to filename with information about blockIDs
String path = "_" + iF + "_B" + blocks[0].getBlockId() +
"_to_B" + blocks[blocksPerFile-1].getBlockId() + "_";
String filePath = nameGenerator.getNextFileName("");
filePath = filePath + path;
// Log the new sub directory in edits
if ((iF % nameGenerator.getFilesPerDirectory()) == 0) {
String currentDir = nameGenerator.getCurrentDir();
dirInode = new INodeDirectory(inodeId.nextValue(), null, p, 0L);
editLog.logMkDir(currentDir, dirInode);
}
INodeFile fileUc = new INodeFile(inodeId.nextValue(), null,
p, 0L, 0L, BlockInfo.EMPTY_ARRAY, replication, blockSize, (byte)0);
fileUc.toUnderConstruction("", "");
editLog.logOpenFile(filePath, fileUc, false, false);
editLog.logCloseFile(filePath, inode);
if (currentBlockId - bidAtSync >= 2000) { // sync every 2K blocks
editLog.logSync();
bidAtSync = currentBlockId;
}
}
System.out.println("Created edits log in directory " + edits_dir);
System.out.println(" containing " +
numFiles + " File-Creates, each file with " + blocksPerFile + " blocks");
System.out.println(" blocks range: " +
startingBlockId + " to " + (currentBlockId-1));
}
static final String usage = "Usage: createditlogs " +
" -f numFiles startingBlockIds NumBlocksPerFile [-r replicafactor] " +
"[-d editsLogDirectory]\n" +
" Default replication factor is 1\n" +
" Default edits log direcory is " + EDITS_DIR + "\n";
static void printUsageExit() {
System.out.println(usage);
System.exit(-1);
}
static void printUsageExit(String err) {
System.out.println(err);
printUsageExit();
}
/**
* @param args arguments
* @throws IOException
*/
public static void main(String[] args) throws IOException {
long startingBlockId = 1;
int numFiles = 0;
short replication = 1;
int numBlocksPerFile = 0;
long blockSize = 10;
if (args.length == 0) {
printUsageExit();
}
for (int i = 0; i < args.length; i++) { // parse command line
if (args[i].equals("-h"))
printUsageExit();
if (args[i].equals("-f")) {
if (i + 3 >= args.length || args[i+1].startsWith("-") ||
args[i+2].startsWith("-") || args[i+3].startsWith("-")) {
printUsageExit(
"Missing num files, starting block and/or number of blocks");
}
numFiles = Integer.parseInt(args[++i]);
startingBlockId = Integer.parseInt(args[++i]);
numBlocksPerFile = Integer.parseInt(args[++i]);
if (numFiles <=0 || numBlocksPerFile <= 0) {
printUsageExit("numFiles and numBlocksPerFile most be greater than 0");
}
} else if (args[i].equals("-l")) {
if (i + 1 >= args.length) {
printUsageExit(
"Missing block length");
}
blockSize = Long.parseLong(args[++i]);
} else if (args[i].equals("-r") || args[i+1].startsWith("-")) {
if (i + 1 >= args.length) {
printUsageExit(
"Missing replication factor");
}
replication = Short.parseShort(args[++i]);
} else if (args[i].equals("-d")) {
if (i + 1 >= args.length || args[i+1].startsWith("-")) {
printUsageExit("Missing edits logs directory");
}
edits_dir = args[++i];
} else {
printUsageExit();
}
}
File editsLogDir = new File(edits_dir);
File subStructureDir = new File(edits_dir + "/" +
Storage.STORAGE_DIR_CURRENT);
if ( !editsLogDir.exists() ) {
if ( !editsLogDir.mkdir()) {
System.out.println("cannot create " + edits_dir);
System.exit(-1);
}
}
if ( !subStructureDir.exists() ) {
if ( !subStructureDir.mkdir()) {
System.out.println("cannot create subdirs of " + edits_dir);
System.exit(-1);
}
}
FileNameGenerator nameGenerator = new FileNameGenerator(BASE_PATH, 100);
FSEditLog editLog = FSImageTestUtil.createStandaloneEditLog(editsLogDir);
editLog.openForWrite();
addFiles(editLog, numFiles, replication, numBlocksPerFile, startingBlockId,
blockSize, nameGenerator);
editLog.logSync();
editLog.close();
}
}
| ZhangXFeng/hadoop | src/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/CreateEditsLog.java | Java | apache-2.0 | 8,019 |
// Package storage provides access to the Cloud Storage JSON API.
//
// See https://developers.google.com/storage/docs/json_api/
//
// Usage example:
//
// import "google.golang.org/api/storage/v1"
// ...
// storageService, err := storage.New(oauthHttpClient)
package storage // import "google.golang.org/api/storage/v1"
import (
"bytes"
"encoding/json"
"errors"
"fmt"
context "golang.org/x/net/context"
ctxhttp "golang.org/x/net/context/ctxhttp"
gensupport "google.golang.org/api/gensupport"
googleapi "google.golang.org/api/googleapi"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = gensupport.MarshalJSON
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
var _ = context.Canceled
var _ = ctxhttp.Do
const apiId = "storage:v1"
const apiName = "storage"
const apiVersion = "v1"
const basePath = "https://www.googleapis.com/storage/v1/"
// OAuth2 scopes used by this API.
const (
// View and manage your data across Google Cloud Platform services
CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"
// View your data across Google Cloud Platform services
CloudPlatformReadOnlyScope = "https://www.googleapis.com/auth/cloud-platform.read-only"
// Manage your data and permissions in Google Cloud Storage
DevstorageFullControlScope = "https://www.googleapis.com/auth/devstorage.full_control"
// View your data in Google Cloud Storage
DevstorageReadOnlyScope = "https://www.googleapis.com/auth/devstorage.read_only"
// Manage your data in Google Cloud Storage
DevstorageReadWriteScope = "https://www.googleapis.com/auth/devstorage.read_write"
)
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.BucketAccessControls = NewBucketAccessControlsService(s)
s.Buckets = NewBucketsService(s)
s.Channels = NewChannelsService(s)
s.DefaultObjectAccessControls = NewDefaultObjectAccessControlsService(s)
s.ObjectAccessControls = NewObjectAccessControlsService(s)
s.Objects = NewObjectsService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
UserAgent string // optional additional User-Agent fragment
BucketAccessControls *BucketAccessControlsService
Buckets *BucketsService
Channels *ChannelsService
DefaultObjectAccessControls *DefaultObjectAccessControlsService
ObjectAccessControls *ObjectAccessControlsService
Objects *ObjectsService
}
func (s *Service) userAgent() string {
if s.UserAgent == "" {
return googleapi.UserAgent
}
return googleapi.UserAgent + " " + s.UserAgent
}
func NewBucketAccessControlsService(s *Service) *BucketAccessControlsService {
rs := &BucketAccessControlsService{s: s}
return rs
}
type BucketAccessControlsService struct {
s *Service
}
func NewBucketsService(s *Service) *BucketsService {
rs := &BucketsService{s: s}
return rs
}
type BucketsService struct {
s *Service
}
func NewChannelsService(s *Service) *ChannelsService {
rs := &ChannelsService{s: s}
return rs
}
type ChannelsService struct {
s *Service
}
func NewDefaultObjectAccessControlsService(s *Service) *DefaultObjectAccessControlsService {
rs := &DefaultObjectAccessControlsService{s: s}
return rs
}
type DefaultObjectAccessControlsService struct {
s *Service
}
func NewObjectAccessControlsService(s *Service) *ObjectAccessControlsService {
rs := &ObjectAccessControlsService{s: s}
return rs
}
type ObjectAccessControlsService struct {
s *Service
}
func NewObjectsService(s *Service) *ObjectsService {
rs := &ObjectsService{s: s}
return rs
}
type ObjectsService struct {
s *Service
}
// Bucket: A bucket.
type Bucket struct {
// Acl: Access controls on the bucket.
Acl []*BucketAccessControl `json:"acl,omitempty"`
// Cors: The bucket's Cross-Origin Resource Sharing (CORS)
// configuration.
Cors []*BucketCors `json:"cors,omitempty"`
// DefaultObjectAcl: Default access controls to apply to new objects
// when no ACL is provided.
DefaultObjectAcl []*ObjectAccessControl `json:"defaultObjectAcl,omitempty"`
// Etag: HTTP 1.1 Entity tag for the bucket.
Etag string `json:"etag,omitempty"`
// Id: The ID of the bucket. For buckets, the id and name properities
// are the same.
Id string `json:"id,omitempty"`
// Kind: The kind of item this is. For buckets, this is always
// storage#bucket.
Kind string `json:"kind,omitempty"`
// Lifecycle: The bucket's lifecycle configuration. See lifecycle
// management for more information.
Lifecycle *BucketLifecycle `json:"lifecycle,omitempty"`
// Location: The location of the bucket. Object data for objects in the
// bucket resides in physical storage within this region. Defaults to
// US. See the developer's guide for the authoritative list.
Location string `json:"location,omitempty"`
// Logging: The bucket's logging configuration, which defines the
// destination bucket and optional name prefix for the current bucket's
// logs.
Logging *BucketLogging `json:"logging,omitempty"`
// Metageneration: The metadata generation of this bucket.
Metageneration int64 `json:"metageneration,omitempty,string"`
// Name: The name of the bucket.
Name string `json:"name,omitempty"`
// Owner: The owner of the bucket. This is always the project team's
// owner group.
Owner *BucketOwner `json:"owner,omitempty"`
// ProjectNumber: The project number of the project the bucket belongs
// to.
ProjectNumber uint64 `json:"projectNumber,omitempty,string"`
// SelfLink: The URI of this bucket.
SelfLink string `json:"selfLink,omitempty"`
// StorageClass: The bucket's default storage class, used whenever no
// storageClass is specified for a newly-created object. This defines
// how objects in the bucket are stored and determines the SLA and the
// cost of storage. Values include MULTI_REGIONAL, REGIONAL, STANDARD,
// NEARLINE, COLDLINE, and DURABLE_REDUCED_AVAILABILITY. If this value
// is not specified when the bucket is created, it will default to
// STANDARD. For more information, see storage classes.
StorageClass string `json:"storageClass,omitempty"`
// TimeCreated: The creation time of the bucket in RFC 3339 format.
TimeCreated string `json:"timeCreated,omitempty"`
// Updated: The modification time of the bucket in RFC 3339 format.
Updated string `json:"updated,omitempty"`
// Versioning: The bucket's versioning configuration.
Versioning *BucketVersioning `json:"versioning,omitempty"`
// Website: The bucket's website configuration, controlling how the
// service behaves when accessing bucket contents as a web site. See the
// Static Website Examples for more information.
Website *BucketWebsite `json:"website,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Acl") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Acl") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Bucket) MarshalJSON() ([]byte, error) {
type noMethod Bucket
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type BucketCors struct {
// MaxAgeSeconds: The value, in seconds, to return in the
// Access-Control-Max-Age header used in preflight responses.
MaxAgeSeconds int64 `json:"maxAgeSeconds,omitempty"`
// Method: The list of HTTP methods on which to include CORS response
// headers, (GET, OPTIONS, POST, etc) Note: "*" is permitted in the list
// of methods, and means "any method".
Method []string `json:"method,omitempty"`
// Origin: The list of Origins eligible to receive CORS response
// headers. Note: "*" is permitted in the list of origins, and means
// "any Origin".
Origin []string `json:"origin,omitempty"`
// ResponseHeader: The list of HTTP headers other than the simple
// response headers to give permission for the user-agent to share
// across domains.
ResponseHeader []string `json:"responseHeader,omitempty"`
// ForceSendFields is a list of field names (e.g. "MaxAgeSeconds") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "MaxAgeSeconds") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketCors) MarshalJSON() ([]byte, error) {
type noMethod BucketCors
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketLifecycle: The bucket's lifecycle configuration. See lifecycle
// management for more information.
type BucketLifecycle struct {
// Rule: A lifecycle management rule, which is made of an action to take
// and the condition(s) under which the action will be taken.
Rule []*BucketLifecycleRule `json:"rule,omitempty"`
// ForceSendFields is a list of field names (e.g. "Rule") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Rule") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketLifecycle) MarshalJSON() ([]byte, error) {
type noMethod BucketLifecycle
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type BucketLifecycleRule struct {
// Action: The action to take.
Action *BucketLifecycleRuleAction `json:"action,omitempty"`
// Condition: The condition(s) under which the action will be taken.
Condition *BucketLifecycleRuleCondition `json:"condition,omitempty"`
// ForceSendFields is a list of field names (e.g. "Action") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Action") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketLifecycleRule) MarshalJSON() ([]byte, error) {
type noMethod BucketLifecycleRule
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketLifecycleRuleAction: The action to take.
type BucketLifecycleRuleAction struct {
// StorageClass: Target storage class. Required iff the type of the
// action is SetStorageClass.
StorageClass string `json:"storageClass,omitempty"`
// Type: Type of the action. Currently, only Delete and SetStorageClass
// are supported.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "StorageClass") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "StorageClass") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketLifecycleRuleAction) MarshalJSON() ([]byte, error) {
type noMethod BucketLifecycleRuleAction
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketLifecycleRuleCondition: The condition(s) under which the action
// will be taken.
type BucketLifecycleRuleCondition struct {
// Age: Age of an object (in days). This condition is satisfied when an
// object reaches the specified age.
Age int64 `json:"age,omitempty"`
// CreatedBefore: A date in RFC 3339 format with only the date part (for
// instance, "2013-01-15"). This condition is satisfied when an object
// is created before midnight of the specified date in UTC.
CreatedBefore string `json:"createdBefore,omitempty"`
// IsLive: Relevant only for versioned objects. If the value is true,
// this condition matches live objects; if the value is false, it
// matches archived objects.
IsLive bool `json:"isLive,omitempty"`
// MatchesStorageClass: Objects having any of the storage classes
// specified by this condition will be matched. Values include
// MULTI_REGIONAL, REGIONAL, NEARLINE, COLDLINE, STANDARD, and
// DURABLE_REDUCED_AVAILABILITY.
MatchesStorageClass []string `json:"matchesStorageClass,omitempty"`
// NumNewerVersions: Relevant only for versioned objects. If the value
// is N, this condition is satisfied when there are at least N versions
// (including the live version) newer than this version of the object.
NumNewerVersions int64 `json:"numNewerVersions,omitempty"`
// ForceSendFields is a list of field names (e.g. "Age") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Age") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketLifecycleRuleCondition) MarshalJSON() ([]byte, error) {
type noMethod BucketLifecycleRuleCondition
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketLogging: The bucket's logging configuration, which defines the
// destination bucket and optional name prefix for the current bucket's
// logs.
type BucketLogging struct {
// LogBucket: The destination bucket where the current bucket's logs
// should be placed.
LogBucket string `json:"logBucket,omitempty"`
// LogObjectPrefix: A prefix for log object names.
LogObjectPrefix string `json:"logObjectPrefix,omitempty"`
// ForceSendFields is a list of field names (e.g. "LogBucket") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LogBucket") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketLogging) MarshalJSON() ([]byte, error) {
type noMethod BucketLogging
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketOwner: The owner of the bucket. This is always the project
// team's owner group.
type BucketOwner struct {
// Entity: The entity, in the form project-owner-projectId.
Entity string `json:"entity,omitempty"`
// EntityId: The ID for the entity.
EntityId string `json:"entityId,omitempty"`
// ForceSendFields is a list of field names (e.g. "Entity") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Entity") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketOwner) MarshalJSON() ([]byte, error) {
type noMethod BucketOwner
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketVersioning: The bucket's versioning configuration.
type BucketVersioning struct {
// Enabled: While set to true, versioning is fully enabled for this
// bucket.
Enabled bool `json:"enabled,omitempty"`
// ForceSendFields is a list of field names (e.g. "Enabled") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Enabled") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketVersioning) MarshalJSON() ([]byte, error) {
type noMethod BucketVersioning
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketWebsite: The bucket's website configuration, controlling how
// the service behaves when accessing bucket contents as a web site. See
// the Static Website Examples for more information.
type BucketWebsite struct {
// MainPageSuffix: If the requested object path is missing, the service
// will ensure the path has a trailing '/', append this suffix, and
// attempt to retrieve the resulting object. This allows the creation of
// index.html objects to represent directory pages.
MainPageSuffix string `json:"mainPageSuffix,omitempty"`
// NotFoundPage: If the requested object path is missing, and any
// mainPageSuffix object is missing, if applicable, the service will
// return the named object from this bucket as the content for a 404 Not
// Found result.
NotFoundPage string `json:"notFoundPage,omitempty"`
// ForceSendFields is a list of field names (e.g. "MainPageSuffix") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "MainPageSuffix") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *BucketWebsite) MarshalJSON() ([]byte, error) {
type noMethod BucketWebsite
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketAccessControl: An access-control entry.
type BucketAccessControl struct {
// Bucket: The name of the bucket.
Bucket string `json:"bucket,omitempty"`
// Domain: The domain associated with the entity, if any.
Domain string `json:"domain,omitempty"`
// Email: The email address associated with the entity, if any.
Email string `json:"email,omitempty"`
// Entity: The entity holding the permission, in one of the following
// forms:
// - user-userId
// - user-email
// - group-groupId
// - group-email
// - domain-domain
// - project-team-projectId
// - allUsers
// - allAuthenticatedUsers Examples:
// - The user liz@example.com would be user-liz@example.com.
// - The group example@googlegroups.com would be
// group-example@googlegroups.com.
// - To refer to all members of the Google Apps for Business domain
// example.com, the entity would be domain-example.com.
Entity string `json:"entity,omitempty"`
// EntityId: The ID for the entity, if any.
EntityId string `json:"entityId,omitempty"`
// Etag: HTTP 1.1 Entity tag for the access-control entry.
Etag string `json:"etag,omitempty"`
// Id: The ID of the access-control entry.
Id string `json:"id,omitempty"`
// Kind: The kind of item this is. For bucket access control entries,
// this is always storage#bucketAccessControl.
Kind string `json:"kind,omitempty"`
// ProjectTeam: The project team associated with the entity, if any.
ProjectTeam *BucketAccessControlProjectTeam `json:"projectTeam,omitempty"`
// Role: The access permission for the entity.
Role string `json:"role,omitempty"`
// SelfLink: The link to this access-control entry.
SelfLink string `json:"selfLink,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Bucket") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Bucket") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketAccessControl) MarshalJSON() ([]byte, error) {
type noMethod BucketAccessControl
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketAccessControlProjectTeam: The project team associated with the
// entity, if any.
type BucketAccessControlProjectTeam struct {
// ProjectNumber: The project number.
ProjectNumber string `json:"projectNumber,omitempty"`
// Team: The team.
Team string `json:"team,omitempty"`
// ForceSendFields is a list of field names (e.g. "ProjectNumber") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ProjectNumber") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketAccessControlProjectTeam) MarshalJSON() ([]byte, error) {
type noMethod BucketAccessControlProjectTeam
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketAccessControls: An access-control list.
type BucketAccessControls struct {
// Items: The list of items.
Items []*BucketAccessControl `json:"items,omitempty"`
// Kind: The kind of item this is. For lists of bucket access control
// entries, this is always storage#bucketAccessControls.
Kind string `json:"kind,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Items") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Items") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketAccessControls) MarshalJSON() ([]byte, error) {
type noMethod BucketAccessControls
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Buckets: A list of buckets.
type Buckets struct {
// Items: The list of items.
Items []*Bucket `json:"items,omitempty"`
// Kind: The kind of item this is. For lists of buckets, this is always
// storage#buckets.
Kind string `json:"kind,omitempty"`
// NextPageToken: The continuation token, used to page through large
// result sets. Provide this value in a subsequent request to return the
// next page of results.
NextPageToken string `json:"nextPageToken,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Items") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Items") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Buckets) MarshalJSON() ([]byte, error) {
type noMethod Buckets
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Channel: An notification channel used to watch for resource changes.
type Channel struct {
// Address: The address where notifications are delivered for this
// channel.
Address string `json:"address,omitempty"`
// Expiration: Date and time of notification channel expiration,
// expressed as a Unix timestamp, in milliseconds. Optional.
Expiration int64 `json:"expiration,omitempty,string"`
// Id: A UUID or similar unique string that identifies this channel.
Id string `json:"id,omitempty"`
// Kind: Identifies this as a notification channel used to watch for
// changes to a resource. Value: the fixed string "api#channel".
Kind string `json:"kind,omitempty"`
// Params: Additional parameters controlling delivery channel behavior.
// Optional.
Params map[string]string `json:"params,omitempty"`
// Payload: A Boolean value to indicate whether payload is wanted.
// Optional.
Payload bool `json:"payload,omitempty"`
// ResourceId: An opaque ID that identifies the resource being watched
// on this channel. Stable across different API versions.
ResourceId string `json:"resourceId,omitempty"`
// ResourceUri: A version-specific identifier for the watched resource.
ResourceUri string `json:"resourceUri,omitempty"`
// Token: An arbitrary string delivered to the target address with each
// notification delivered over this channel. Optional.
Token string `json:"token,omitempty"`
// Type: The type of delivery mechanism used for this channel.
Type string `json:"type,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Address") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Address") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Channel) MarshalJSON() ([]byte, error) {
type noMethod Channel
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ComposeRequest: A Compose request.
type ComposeRequest struct {
// Destination: Properties of the resulting object.
Destination *Object `json:"destination,omitempty"`
// Kind: The kind of item this is.
Kind string `json:"kind,omitempty"`
// SourceObjects: The list of source objects that will be concatenated
// into a single object.
SourceObjects []*ComposeRequestSourceObjects `json:"sourceObjects,omitempty"`
// ForceSendFields is a list of field names (e.g. "Destination") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Destination") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ComposeRequest) MarshalJSON() ([]byte, error) {
type noMethod ComposeRequest
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type ComposeRequestSourceObjects struct {
// Generation: The generation of this object to use as the source.
Generation int64 `json:"generation,omitempty,string"`
// Name: The source object's name. The source object's bucket is
// implicitly the destination bucket.
Name string `json:"name,omitempty"`
// ObjectPreconditions: Conditions that must be met for this operation
// to execute.
ObjectPreconditions *ComposeRequestSourceObjectsObjectPreconditions `json:"objectPreconditions,omitempty"`
// ForceSendFields is a list of field names (e.g. "Generation") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Generation") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ComposeRequestSourceObjects) MarshalJSON() ([]byte, error) {
type noMethod ComposeRequestSourceObjects
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ComposeRequestSourceObjectsObjectPreconditions: Conditions that must
// be met for this operation to execute.
type ComposeRequestSourceObjectsObjectPreconditions struct {
// IfGenerationMatch: Only perform the composition if the generation of
// the source object that would be used matches this value. If this
// value and a generation are both specified, they must be the same
// value or the call will fail.
IfGenerationMatch int64 `json:"ifGenerationMatch,omitempty,string"`
// ForceSendFields is a list of field names (e.g. "IfGenerationMatch")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IfGenerationMatch") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *ComposeRequestSourceObjectsObjectPreconditions) MarshalJSON() ([]byte, error) {
type noMethod ComposeRequestSourceObjectsObjectPreconditions
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Object: An object.
type Object struct {
// Acl: Access controls on the object.
Acl []*ObjectAccessControl `json:"acl,omitempty"`
// Bucket: The name of the bucket containing this object.
Bucket string `json:"bucket,omitempty"`
// CacheControl: Cache-Control directive for the object data. If
// omitted, and the object is accessible to all anonymous users, the
// default will be public, max-age=3600.
CacheControl string `json:"cacheControl,omitempty"`
// ComponentCount: Number of underlying components that make up this
// object. Components are accumulated by compose operations.
ComponentCount int64 `json:"componentCount,omitempty"`
// ContentDisposition: Content-Disposition of the object data.
ContentDisposition string `json:"contentDisposition,omitempty"`
// ContentEncoding: Content-Encoding of the object data.
ContentEncoding string `json:"contentEncoding,omitempty"`
// ContentLanguage: Content-Language of the object data.
ContentLanguage string `json:"contentLanguage,omitempty"`
// ContentType: Content-Type of the object data. If contentType is not
// specified, object downloads will be served as
// application/octet-stream.
ContentType string `json:"contentType,omitempty"`
// Crc32c: CRC32c checksum, as described in RFC 4960, Appendix B;
// encoded using base64 in big-endian byte order. For more information
// about using the CRC32c checksum, see Hashes and ETags: Best
// Practices.
Crc32c string `json:"crc32c,omitempty"`
// CustomerEncryption: Metadata of customer-supplied encryption key, if
// the object is encrypted by such a key.
CustomerEncryption *ObjectCustomerEncryption `json:"customerEncryption,omitempty"`
// Etag: HTTP 1.1 Entity tag for the object.
Etag string `json:"etag,omitempty"`
// Generation: The content generation of this object. Used for object
// versioning.
Generation int64 `json:"generation,omitempty,string"`
// Id: The ID of the object, including the bucket name, object name, and
// generation number.
Id string `json:"id,omitempty"`
// Kind: The kind of item this is. For objects, this is always
// storage#object.
Kind string `json:"kind,omitempty"`
// Md5Hash: MD5 hash of the data; encoded using base64. For more
// information about using the MD5 hash, see Hashes and ETags: Best
// Practices.
Md5Hash string `json:"md5Hash,omitempty"`
// MediaLink: Media download link.
MediaLink string `json:"mediaLink,omitempty"`
// Metadata: User-provided metadata, in key/value pairs.
Metadata map[string]string `json:"metadata,omitempty"`
// Metageneration: The version of the metadata for this object at this
// generation. Used for preconditions and for detecting changes in
// metadata. A metageneration number is only meaningful in the context
// of a particular generation of a particular object.
Metageneration int64 `json:"metageneration,omitempty,string"`
// Name: The name of the object. Required if not specified by URL
// parameter.
Name string `json:"name,omitempty"`
// Owner: The owner of the object. This will always be the uploader of
// the object.
Owner *ObjectOwner `json:"owner,omitempty"`
// SelfLink: The link to this object.
SelfLink string `json:"selfLink,omitempty"`
// Size: Content-Length of the data in bytes.
Size uint64 `json:"size,omitempty,string"`
// StorageClass: Storage class of the object.
StorageClass string `json:"storageClass,omitempty"`
// TimeCreated: The creation time of the object in RFC 3339 format.
TimeCreated string `json:"timeCreated,omitempty"`
// TimeDeleted: The deletion time of the object in RFC 3339 format. Will
// be returned if and only if this version of the object has been
// deleted.
TimeDeleted string `json:"timeDeleted,omitempty"`
// TimeStorageClassUpdated: The time at which the object's storage class
// was last changed. When the object is initially created, it will be
// set to timeCreated.
TimeStorageClassUpdated string `json:"timeStorageClassUpdated,omitempty"`
// Updated: The modification time of the object metadata in RFC 3339
// format.
Updated string `json:"updated,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Acl") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Acl") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Object) MarshalJSON() ([]byte, error) {
type noMethod Object
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ObjectCustomerEncryption: Metadata of customer-supplied encryption
// key, if the object is encrypted by such a key.
type ObjectCustomerEncryption struct {
// EncryptionAlgorithm: The encryption algorithm.
EncryptionAlgorithm string `json:"encryptionAlgorithm,omitempty"`
// KeySha256: SHA256 hash value of the encryption key.
KeySha256 string `json:"keySha256,omitempty"`
// ForceSendFields is a list of field names (e.g. "EncryptionAlgorithm")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "EncryptionAlgorithm") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *ObjectCustomerEncryption) MarshalJSON() ([]byte, error) {
type noMethod ObjectCustomerEncryption
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ObjectOwner: The owner of the object. This will always be the
// uploader of the object.
type ObjectOwner struct {
// Entity: The entity, in the form user-userId.
Entity string `json:"entity,omitempty"`
// EntityId: The ID for the entity.
EntityId string `json:"entityId,omitempty"`
// ForceSendFields is a list of field names (e.g. "Entity") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Entity") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ObjectOwner) MarshalJSON() ([]byte, error) {
type noMethod ObjectOwner
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ObjectAccessControl: An access-control entry.
type ObjectAccessControl struct {
// Bucket: The name of the bucket.
Bucket string `json:"bucket,omitempty"`
// Domain: The domain associated with the entity, if any.
Domain string `json:"domain,omitempty"`
// Email: The email address associated with the entity, if any.
Email string `json:"email,omitempty"`
// Entity: The entity holding the permission, in one of the following
// forms:
// - user-userId
// - user-email
// - group-groupId
// - group-email
// - domain-domain
// - project-team-projectId
// - allUsers
// - allAuthenticatedUsers Examples:
// - The user liz@example.com would be user-liz@example.com.
// - The group example@googlegroups.com would be
// group-example@googlegroups.com.
// - To refer to all members of the Google Apps for Business domain
// example.com, the entity would be domain-example.com.
Entity string `json:"entity,omitempty"`
// EntityId: The ID for the entity, if any.
EntityId string `json:"entityId,omitempty"`
// Etag: HTTP 1.1 Entity tag for the access-control entry.
Etag string `json:"etag,omitempty"`
// Generation: The content generation of the object, if applied to an
// object.
Generation int64 `json:"generation,omitempty,string"`
// Id: The ID of the access-control entry.
Id string `json:"id,omitempty"`
// Kind: The kind of item this is. For object access control entries,
// this is always storage#objectAccessControl.
Kind string `json:"kind,omitempty"`
// Object: The name of the object, if applied to an object.
Object string `json:"object,omitempty"`
// ProjectTeam: The project team associated with the entity, if any.
ProjectTeam *ObjectAccessControlProjectTeam `json:"projectTeam,omitempty"`
// Role: The access permission for the entity.
Role string `json:"role,omitempty"`
// SelfLink: The link to this access-control entry.
SelfLink string `json:"selfLink,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Bucket") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Bucket") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ObjectAccessControl) MarshalJSON() ([]byte, error) {
type noMethod ObjectAccessControl
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ObjectAccessControlProjectTeam: The project team associated with the
// entity, if any.
type ObjectAccessControlProjectTeam struct {
// ProjectNumber: The project number.
ProjectNumber string `json:"projectNumber,omitempty"`
// Team: The team.
Team string `json:"team,omitempty"`
// ForceSendFields is a list of field names (e.g. "ProjectNumber") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ProjectNumber") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ObjectAccessControlProjectTeam) MarshalJSON() ([]byte, error) {
type noMethod ObjectAccessControlProjectTeam
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ObjectAccessControls: An access-control list.
type ObjectAccessControls struct {
// Items: The list of items.
Items []*ObjectAccessControl `json:"items,omitempty"`
// Kind: The kind of item this is. For lists of object access control
// entries, this is always storage#objectAccessControls.
Kind string `json:"kind,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Items") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Items") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ObjectAccessControls) MarshalJSON() ([]byte, error) {
type noMethod ObjectAccessControls
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Objects: A list of objects.
type Objects struct {
// Items: The list of items.
Items []*Object `json:"items,omitempty"`
// Kind: The kind of item this is. For lists of objects, this is always
// storage#objects.
Kind string `json:"kind,omitempty"`
// NextPageToken: The continuation token, used to page through large
// result sets. Provide this value in a subsequent request to return the
// next page of results.
NextPageToken string `json:"nextPageToken,omitempty"`
// Prefixes: The list of prefixes of objects matching-but-not-listed up
// to and including the requested delimiter.
Prefixes []string `json:"prefixes,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Items") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Items") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Objects) MarshalJSON() ([]byte, error) {
type noMethod Objects
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Policy: A bucket/object IAM policy.
type Policy struct {
// Bindings: An association between a role, which comes with a set of
// permissions, and members who may assume that role.
Bindings []*PolicyBindings `json:"bindings,omitempty"`
// Etag: HTTP 1.1 Entity tag for the policy.
Etag string `json:"etag,omitempty"`
// Kind: The kind of item this is. For policies, this is always
// storage#policy. This field is ignored on input.
Kind string `json:"kind,omitempty"`
// ResourceId: The ID of the resource to which this policy belongs. Will
// be of the form buckets/bucket for buckets, and
// buckets/bucket/objects/object for objects. A specific generation may
// be specified by appending #generationNumber to the end of the object
// name, e.g. buckets/my-bucket/objects/data.txt#17. The current
// generation can be denoted with #0. This field is ignored on input.
ResourceId string `json:"resourceId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Bindings") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Bindings") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Policy) MarshalJSON() ([]byte, error) {
type noMethod Policy
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type PolicyBindings struct {
// Members: A collection of identifiers for members who may assume the
// provided role. Recognized identifiers are as follows:
// - allUsers — A special identifier that represents anyone on the
// internet; with or without a Google account.
// - allAuthenticatedUsers — A special identifier that represents
// anyone who is authenticated with a Google account or a service
// account.
// - user:emailid — An email address that represents a specific
// account. For example, user:alice@gmail.com or user:joe@example.com.
//
// - serviceAccount:emailid — An email address that represents a
// service account. For example,
// serviceAccount:my-other-app@appspot.gserviceaccount.com .
// - group:emailid — An email address that represents a Google group.
// For example, group:admins@example.com.
// - domain:domain — A Google Apps domain name that represents all the
// users of that domain. For example, domain:google.com or
// domain:example.com.
// - projectOwner:projectid — Owners of the given project. For
// example, projectOwner:my-example-project
// - projectEditor:projectid — Editors of the given project. For
// example, projectEditor:my-example-project
// - projectViewer:projectid — Viewers of the given project. For
// example, projectViewer:my-example-project
Members []string `json:"members,omitempty"`
// Role: The role to which members belong. Two types of roles are
// supported: new IAM roles, which grant permissions that do not map
// directly to those provided by ACLs, and legacy IAM roles, which do
// map directly to ACL permissions. All roles are of the format
// roles/storage.specificRole.
// The new IAM roles are:
// - roles/storage.admin — Full control of Google Cloud Storage
// resources.
// - roles/storage.objectViewer — Read-Only access to Google Cloud
// Storage objects.
// - roles/storage.objectCreator — Access to create objects in Google
// Cloud Storage.
// - roles/storage.objectAdmin — Full control of Google Cloud Storage
// objects. The legacy IAM roles are:
// - roles/storage.legacyObjectReader — Read-only access to objects
// without listing. Equivalent to an ACL entry on an object with the
// READER role.
// - roles/storage.legacyObjectOwner — Read/write access to existing
// objects without listing. Equivalent to an ACL entry on an object with
// the OWNER role.
// - roles/storage.legacyBucketReader — Read access to buckets with
// object listing. Equivalent to an ACL entry on a bucket with the
// READER role.
// - roles/storage.legacyBucketWriter — Read access to buckets with
// object listing/creation/deletion. Equivalent to an ACL entry on a
// bucket with the WRITER role.
// - roles/storage.legacyBucketOwner — Read and write access to
// existing buckets with object listing/creation/deletion. Equivalent to
// an ACL entry on a bucket with the OWNER role.
Role string `json:"role,omitempty"`
// ForceSendFields is a list of field names (e.g. "Members") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Members") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *PolicyBindings) MarshalJSON() ([]byte, error) {
type noMethod PolicyBindings
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// RewriteResponse: A rewrite response.
type RewriteResponse struct {
// Done: true if the copy is finished; otherwise, false if the copy is
// in progress. This property is always present in the response.
Done bool `json:"done,omitempty"`
// Kind: The kind of item this is.
Kind string `json:"kind,omitempty"`
// ObjectSize: The total size of the object being copied in bytes. This
// property is always present in the response.
ObjectSize uint64 `json:"objectSize,omitempty,string"`
// Resource: A resource containing the metadata for the copied-to
// object. This property is present in the response only when copying
// completes.
Resource *Object `json:"resource,omitempty"`
// RewriteToken: A token to use in subsequent requests to continue
// copying data. This token is present in the response only when there
// is more data to copy.
RewriteToken string `json:"rewriteToken,omitempty"`
// TotalBytesRewritten: The total bytes written so far, which can be
// used to provide a waiting user with a progress indicator. This
// property is always present in the response.
TotalBytesRewritten uint64 `json:"totalBytesRewritten,omitempty,string"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Done") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Done") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *RewriteResponse) MarshalJSON() ([]byte, error) {
type noMethod RewriteResponse
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// TestIamPermissionsResponse: A
// storage.(buckets|objects).testIamPermissions response.
type TestIamPermissionsResponse struct {
// Kind: The kind of item this is.
Kind string `json:"kind,omitempty"`
// Permissions: The permissions held by the caller. Permissions are
// always of the format storage.resource.capability, where resource is
// one of buckets or objects. The supported permissions are as follows:
//
// - storage.buckets.delete — Delete bucket.
// - storage.buckets.get — Read bucket metadata.
// - storage.buckets.getIamPolicy — Read bucket IAM policy.
// - storage.buckets.create — Create bucket.
// - storage.buckets.list — List buckets.
// - storage.buckets.setIamPolicy — Update bucket IAM policy.
// - storage.buckets.update — Update bucket metadata.
// - storage.objects.delete — Delete object.
// - storage.objects.get — Read object data and metadata.
// - storage.objects.getIamPolicy — Read object IAM policy.
// - storage.objects.create — Create object.
// - storage.objects.list — List objects.
// - storage.objects.setIamPolicy — Update object IAM policy.
// - storage.objects.update — Update object metadata.
Permissions []string `json:"permissions,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Kind") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Kind") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *TestIamPermissionsResponse) MarshalJSON() ([]byte, error) {
type noMethod TestIamPermissionsResponse
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// method id "storage.bucketAccessControls.delete":
type BucketAccessControlsDeleteCall struct {
s *Service
bucket string
entity string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Permanently deletes the ACL entry for the specified entity on
// the specified bucket.
func (r *BucketAccessControlsService) Delete(bucket string, entity string) *BucketAccessControlsDeleteCall {
c := &BucketAccessControlsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketAccessControlsDeleteCall) Fields(s ...googleapi.Field) *BucketAccessControlsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketAccessControlsDeleteCall) Context(ctx context.Context) *BucketAccessControlsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketAccessControlsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketAccessControlsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.bucketAccessControls.delete" call.
func (c *BucketAccessControlsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Permanently deletes the ACL entry for the specified entity on the specified bucket.",
// "httpMethod": "DELETE",
// "id": "storage.bucketAccessControls.delete",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/acl/{entity}",
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.bucketAccessControls.get":
type BucketAccessControlsGetCall struct {
s *Service
bucket string
entity string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Returns the ACL entry for the specified entity on the specified
// bucket.
func (r *BucketAccessControlsService) Get(bucket string, entity string) *BucketAccessControlsGetCall {
c := &BucketAccessControlsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketAccessControlsGetCall) Fields(s ...googleapi.Field) *BucketAccessControlsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *BucketAccessControlsGetCall) IfNoneMatch(entityTag string) *BucketAccessControlsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketAccessControlsGetCall) Context(ctx context.Context) *BucketAccessControlsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketAccessControlsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketAccessControlsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.bucketAccessControls.get" call.
// Exactly one of *BucketAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *BucketAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *BucketAccessControlsGetCall) Do(opts ...googleapi.CallOption) (*BucketAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BucketAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns the ACL entry for the specified entity on the specified bucket.",
// "httpMethod": "GET",
// "id": "storage.bucketAccessControls.get",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/acl/{entity}",
// "response": {
// "$ref": "BucketAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.bucketAccessControls.insert":
type BucketAccessControlsInsertCall struct {
s *Service
bucket string
bucketaccesscontrol *BucketAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Creates a new ACL entry on the specified bucket.
func (r *BucketAccessControlsService) Insert(bucket string, bucketaccesscontrol *BucketAccessControl) *BucketAccessControlsInsertCall {
c := &BucketAccessControlsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.bucketaccesscontrol = bucketaccesscontrol
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketAccessControlsInsertCall) Fields(s ...googleapi.Field) *BucketAccessControlsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketAccessControlsInsertCall) Context(ctx context.Context) *BucketAccessControlsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketAccessControlsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketAccessControlsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.bucketaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/acl")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.bucketAccessControls.insert" call.
// Exactly one of *BucketAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *BucketAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *BucketAccessControlsInsertCall) Do(opts ...googleapi.CallOption) (*BucketAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BucketAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a new ACL entry on the specified bucket.",
// "httpMethod": "POST",
// "id": "storage.bucketAccessControls.insert",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/acl",
// "request": {
// "$ref": "BucketAccessControl"
// },
// "response": {
// "$ref": "BucketAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.bucketAccessControls.list":
type BucketAccessControlsListCall struct {
s *Service
bucket string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Retrieves ACL entries on the specified bucket.
func (r *BucketAccessControlsService) List(bucket string) *BucketAccessControlsListCall {
c := &BucketAccessControlsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketAccessControlsListCall) Fields(s ...googleapi.Field) *BucketAccessControlsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *BucketAccessControlsListCall) IfNoneMatch(entityTag string) *BucketAccessControlsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketAccessControlsListCall) Context(ctx context.Context) *BucketAccessControlsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketAccessControlsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketAccessControlsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/acl")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.bucketAccessControls.list" call.
// Exactly one of *BucketAccessControls or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *BucketAccessControls.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *BucketAccessControlsListCall) Do(opts ...googleapi.CallOption) (*BucketAccessControls, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BucketAccessControls{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves ACL entries on the specified bucket.",
// "httpMethod": "GET",
// "id": "storage.bucketAccessControls.list",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/acl",
// "response": {
// "$ref": "BucketAccessControls"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.bucketAccessControls.patch":
type BucketAccessControlsPatchCall struct {
s *Service
bucket string
entity string
bucketaccesscontrol *BucketAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates an ACL entry on the specified bucket. This method
// supports patch semantics.
func (r *BucketAccessControlsService) Patch(bucket string, entity string, bucketaccesscontrol *BucketAccessControl) *BucketAccessControlsPatchCall {
c := &BucketAccessControlsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
c.bucketaccesscontrol = bucketaccesscontrol
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketAccessControlsPatchCall) Fields(s ...googleapi.Field) *BucketAccessControlsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketAccessControlsPatchCall) Context(ctx context.Context) *BucketAccessControlsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketAccessControlsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketAccessControlsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.bucketaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PATCH", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.bucketAccessControls.patch" call.
// Exactly one of *BucketAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *BucketAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *BucketAccessControlsPatchCall) Do(opts ...googleapi.CallOption) (*BucketAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BucketAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an ACL entry on the specified bucket. This method supports patch semantics.",
// "httpMethod": "PATCH",
// "id": "storage.bucketAccessControls.patch",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/acl/{entity}",
// "request": {
// "$ref": "BucketAccessControl"
// },
// "response": {
// "$ref": "BucketAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.bucketAccessControls.update":
type BucketAccessControlsUpdateCall struct {
s *Service
bucket string
entity string
bucketaccesscontrol *BucketAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Updates an ACL entry on the specified bucket.
func (r *BucketAccessControlsService) Update(bucket string, entity string, bucketaccesscontrol *BucketAccessControl) *BucketAccessControlsUpdateCall {
c := &BucketAccessControlsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
c.bucketaccesscontrol = bucketaccesscontrol
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketAccessControlsUpdateCall) Fields(s ...googleapi.Field) *BucketAccessControlsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketAccessControlsUpdateCall) Context(ctx context.Context) *BucketAccessControlsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketAccessControlsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketAccessControlsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.bucketaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.bucketAccessControls.update" call.
// Exactly one of *BucketAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *BucketAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *BucketAccessControlsUpdateCall) Do(opts ...googleapi.CallOption) (*BucketAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BucketAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an ACL entry on the specified bucket.",
// "httpMethod": "PUT",
// "id": "storage.bucketAccessControls.update",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/acl/{entity}",
// "request": {
// "$ref": "BucketAccessControl"
// },
// "response": {
// "$ref": "BucketAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.buckets.delete":
type BucketsDeleteCall struct {
s *Service
bucket string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Permanently deletes an empty bucket.
func (r *BucketsService) Delete(bucket string) *BucketsDeleteCall {
c := &BucketsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": If set, only deletes the bucket if its
// metageneration matches this value.
func (c *BucketsDeleteCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *BucketsDeleteCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": If set, only deletes the bucket if its
// metageneration does not match this value.
func (c *BucketsDeleteCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *BucketsDeleteCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsDeleteCall) Fields(s ...googleapi.Field) *BucketsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsDeleteCall) Context(ctx context.Context) *BucketsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.delete" call.
func (c *BucketsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Permanently deletes an empty bucket.",
// "httpMethod": "DELETE",
// "id": "storage.buckets.delete",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "If set, only deletes the bucket if its metageneration matches this value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "If set, only deletes the bucket if its metageneration does not match this value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}",
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.buckets.get":
type BucketsGetCall struct {
s *Service
bucket string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Returns metadata for the specified bucket.
func (r *BucketsService) Get(bucket string) *BucketsGetCall {
c := &BucketsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the return of the bucket metadata
// conditional on whether the bucket's current metageneration matches
// the given value.
func (c *BucketsGetCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *BucketsGetCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the return of the bucket metadata
// conditional on whether the bucket's current metageneration does not
// match the given value.
func (c *BucketsGetCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *BucketsGetCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit owner, acl and defaultObjectAcl properties.
func (c *BucketsGetCall) Projection(projection string) *BucketsGetCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsGetCall) Fields(s ...googleapi.Field) *BucketsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *BucketsGetCall) IfNoneMatch(entityTag string) *BucketsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsGetCall) Context(ctx context.Context) *BucketsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.get" call.
// Exactly one of *Bucket or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Bucket.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *BucketsGetCall) Do(opts ...googleapi.CallOption) (*Bucket, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Bucket{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns metadata for the specified bucket.",
// "httpMethod": "GET",
// "id": "storage.buckets.get",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit owner, acl and defaultObjectAcl properties."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}",
// "response": {
// "$ref": "Bucket"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.buckets.getIamPolicy":
type BucketsGetIamPolicyCall struct {
s *Service
bucket string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// GetIamPolicy: Returns an IAM policy for the specified bucket.
func (r *BucketsService) GetIamPolicy(bucket string) *BucketsGetIamPolicyCall {
c := &BucketsGetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsGetIamPolicyCall) Fields(s ...googleapi.Field) *BucketsGetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *BucketsGetIamPolicyCall) IfNoneMatch(entityTag string) *BucketsGetIamPolicyCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsGetIamPolicyCall) Context(ctx context.Context) *BucketsGetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsGetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsGetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/iam")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.getIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *BucketsGetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns an IAM policy for the specified bucket.",
// "httpMethod": "GET",
// "id": "storage.buckets.getIamPolicy",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/iam",
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.buckets.insert":
type BucketsInsertCall struct {
s *Service
bucket *Bucket
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Creates a new bucket.
func (r *BucketsService) Insert(projectid string, bucket *Bucket) *BucketsInsertCall {
c := &BucketsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("project", projectid)
c.bucket = bucket
return c
}
// PredefinedAcl sets the optional parameter "predefinedAcl": Apply a
// predefined set of access controls to this bucket.
//
// Possible values:
// "authenticatedRead" - Project team owners get OWNER access, and
// allAuthenticatedUsers get READER access.
// "private" - Project team owners get OWNER access.
// "projectPrivate" - Project team members get access according to
// their roles.
// "publicRead" - Project team owners get OWNER access, and allUsers
// get READER access.
// "publicReadWrite" - Project team owners get OWNER access, and
// allUsers get WRITER access.
func (c *BucketsInsertCall) PredefinedAcl(predefinedAcl string) *BucketsInsertCall {
c.urlParams_.Set("predefinedAcl", predefinedAcl)
return c
}
// PredefinedDefaultObjectAcl sets the optional parameter
// "predefinedDefaultObjectAcl": Apply a predefined set of default
// object access controls to this bucket.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *BucketsInsertCall) PredefinedDefaultObjectAcl(predefinedDefaultObjectAcl string) *BucketsInsertCall {
c.urlParams_.Set("predefinedDefaultObjectAcl", predefinedDefaultObjectAcl)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl, unless the bucket resource
// specifies acl or defaultObjectAcl properties, when it defaults to
// full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit owner, acl and defaultObjectAcl properties.
func (c *BucketsInsertCall) Projection(projection string) *BucketsInsertCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsInsertCall) Fields(s ...googleapi.Field) *BucketsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsInsertCall) Context(ctx context.Context) *BucketsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.bucket)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.insert" call.
// Exactly one of *Bucket or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Bucket.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *BucketsInsertCall) Do(opts ...googleapi.CallOption) (*Bucket, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Bucket{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a new bucket.",
// "httpMethod": "POST",
// "id": "storage.buckets.insert",
// "parameterOrder": [
// "project"
// ],
// "parameters": {
// "predefinedAcl": {
// "description": "Apply a predefined set of access controls to this bucket.",
// "enum": [
// "authenticatedRead",
// "private",
// "projectPrivate",
// "publicRead",
// "publicReadWrite"
// ],
// "enumDescriptions": [
// "Project team owners get OWNER access, and allAuthenticatedUsers get READER access.",
// "Project team owners get OWNER access.",
// "Project team members get access according to their roles.",
// "Project team owners get OWNER access, and allUsers get READER access.",
// "Project team owners get OWNER access, and allUsers get WRITER access."
// ],
// "location": "query",
// "type": "string"
// },
// "predefinedDefaultObjectAcl": {
// "description": "Apply a predefined set of default object access controls to this bucket.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "project": {
// "description": "A valid API project identifier.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit owner, acl and defaultObjectAcl properties."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b",
// "request": {
// "$ref": "Bucket"
// },
// "response": {
// "$ref": "Bucket"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.buckets.list":
type BucketsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Retrieves a list of buckets for a given project.
func (r *BucketsService) List(projectid string) *BucketsListCall {
c := &BucketsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("project", projectid)
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum number
// of buckets to return in a single response. The service will use this
// parameter or 1,000 items, whichever is smaller.
func (c *BucketsListCall) MaxResults(maxResults int64) *BucketsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// PageToken sets the optional parameter "pageToken": A
// previously-returned page token representing part of the larger set of
// results to view.
func (c *BucketsListCall) PageToken(pageToken string) *BucketsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Prefix sets the optional parameter "prefix": Filter results to
// buckets whose names begin with this prefix.
func (c *BucketsListCall) Prefix(prefix string) *BucketsListCall {
c.urlParams_.Set("prefix", prefix)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit owner, acl and defaultObjectAcl properties.
func (c *BucketsListCall) Projection(projection string) *BucketsListCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsListCall) Fields(s ...googleapi.Field) *BucketsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *BucketsListCall) IfNoneMatch(entityTag string) *BucketsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsListCall) Context(ctx context.Context) *BucketsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.list" call.
// Exactly one of *Buckets or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Buckets.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *BucketsListCall) Do(opts ...googleapi.CallOption) (*Buckets, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Buckets{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves a list of buckets for a given project.",
// "httpMethod": "GET",
// "id": "storage.buckets.list",
// "parameterOrder": [
// "project"
// ],
// "parameters": {
// "maxResults": {
// "default": "1000",
// "description": "Maximum number of buckets to return in a single response. The service will use this parameter or 1,000 items, whichever is smaller.",
// "format": "uint32",
// "location": "query",
// "minimum": "0",
// "type": "integer"
// },
// "pageToken": {
// "description": "A previously-returned page token representing part of the larger set of results to view.",
// "location": "query",
// "type": "string"
// },
// "prefix": {
// "description": "Filter results to buckets whose names begin with this prefix.",
// "location": "query",
// "type": "string"
// },
// "project": {
// "description": "A valid API project identifier.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit owner, acl and defaultObjectAcl properties."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b",
// "response": {
// "$ref": "Buckets"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *BucketsListCall) Pages(ctx context.Context, f func(*Buckets) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "storage.buckets.patch":
type BucketsPatchCall struct {
s *Service
bucket string
bucket2 *Bucket
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates a bucket. Changes to the bucket will be readable
// immediately after writing, but configuration changes may take time to
// propagate. This method supports patch semantics.
func (r *BucketsService) Patch(bucket string, bucket2 *Bucket) *BucketsPatchCall {
c := &BucketsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.bucket2 = bucket2
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the return of the bucket metadata
// conditional on whether the bucket's current metageneration matches
// the given value.
func (c *BucketsPatchCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *BucketsPatchCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the return of the bucket metadata
// conditional on whether the bucket's current metageneration does not
// match the given value.
func (c *BucketsPatchCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *BucketsPatchCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// PredefinedAcl sets the optional parameter "predefinedAcl": Apply a
// predefined set of access controls to this bucket.
//
// Possible values:
// "authenticatedRead" - Project team owners get OWNER access, and
// allAuthenticatedUsers get READER access.
// "private" - Project team owners get OWNER access.
// "projectPrivate" - Project team members get access according to
// their roles.
// "publicRead" - Project team owners get OWNER access, and allUsers
// get READER access.
// "publicReadWrite" - Project team owners get OWNER access, and
// allUsers get WRITER access.
func (c *BucketsPatchCall) PredefinedAcl(predefinedAcl string) *BucketsPatchCall {
c.urlParams_.Set("predefinedAcl", predefinedAcl)
return c
}
// PredefinedDefaultObjectAcl sets the optional parameter
// "predefinedDefaultObjectAcl": Apply a predefined set of default
// object access controls to this bucket.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *BucketsPatchCall) PredefinedDefaultObjectAcl(predefinedDefaultObjectAcl string) *BucketsPatchCall {
c.urlParams_.Set("predefinedDefaultObjectAcl", predefinedDefaultObjectAcl)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit owner, acl and defaultObjectAcl properties.
func (c *BucketsPatchCall) Projection(projection string) *BucketsPatchCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsPatchCall) Fields(s ...googleapi.Field) *BucketsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsPatchCall) Context(ctx context.Context) *BucketsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.bucket2)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PATCH", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.patch" call.
// Exactly one of *Bucket or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Bucket.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *BucketsPatchCall) Do(opts ...googleapi.CallOption) (*Bucket, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Bucket{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a bucket. Changes to the bucket will be readable immediately after writing, but configuration changes may take time to propagate. This method supports patch semantics.",
// "httpMethod": "PATCH",
// "id": "storage.buckets.patch",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "predefinedAcl": {
// "description": "Apply a predefined set of access controls to this bucket.",
// "enum": [
// "authenticatedRead",
// "private",
// "projectPrivate",
// "publicRead",
// "publicReadWrite"
// ],
// "enumDescriptions": [
// "Project team owners get OWNER access, and allAuthenticatedUsers get READER access.",
// "Project team owners get OWNER access.",
// "Project team members get access according to their roles.",
// "Project team owners get OWNER access, and allUsers get READER access.",
// "Project team owners get OWNER access, and allUsers get WRITER access."
// ],
// "location": "query",
// "type": "string"
// },
// "predefinedDefaultObjectAcl": {
// "description": "Apply a predefined set of default object access controls to this bucket.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit owner, acl and defaultObjectAcl properties."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}",
// "request": {
// "$ref": "Bucket"
// },
// "response": {
// "$ref": "Bucket"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.buckets.setIamPolicy":
type BucketsSetIamPolicyCall struct {
s *Service
bucket string
policy *Policy
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// SetIamPolicy: Updates an IAM policy for the specified bucket.
func (r *BucketsService) SetIamPolicy(bucket string, policy *Policy) *BucketsSetIamPolicyCall {
c := &BucketsSetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.policy = policy
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsSetIamPolicyCall) Fields(s ...googleapi.Field) *BucketsSetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsSetIamPolicyCall) Context(ctx context.Context) *BucketsSetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsSetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsSetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.policy)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/iam")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.setIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *BucketsSetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an IAM policy for the specified bucket.",
// "httpMethod": "PUT",
// "id": "storage.buckets.setIamPolicy",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/iam",
// "request": {
// "$ref": "Policy"
// },
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.buckets.testIamPermissions":
type BucketsTestIamPermissionsCall struct {
s *Service
bucket string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// TestIamPermissions: Tests a set of permissions on the given bucket to
// see which, if any, are held by the caller.
func (r *BucketsService) TestIamPermissions(bucket string, permissions []string) *BucketsTestIamPermissionsCall {
c := &BucketsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.urlParams_.SetMulti("permissions", append([]string{}, permissions...))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsTestIamPermissionsCall) Fields(s ...googleapi.Field) *BucketsTestIamPermissionsCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *BucketsTestIamPermissionsCall) IfNoneMatch(entityTag string) *BucketsTestIamPermissionsCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsTestIamPermissionsCall) Context(ctx context.Context) *BucketsTestIamPermissionsCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsTestIamPermissionsCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsTestIamPermissionsCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/iam/testPermissions")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.testIamPermissions" call.
// Exactly one of *TestIamPermissionsResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *TestIamPermissionsResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *BucketsTestIamPermissionsCall) Do(opts ...googleapi.CallOption) (*TestIamPermissionsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &TestIamPermissionsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Tests a set of permissions on the given bucket to see which, if any, are held by the caller.",
// "httpMethod": "GET",
// "id": "storage.buckets.testIamPermissions",
// "parameterOrder": [
// "bucket",
// "permissions"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "permissions": {
// "description": "Permissions to test.",
// "location": "query",
// "repeated": true,
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/iam/testPermissions",
// "response": {
// "$ref": "TestIamPermissionsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.buckets.update":
type BucketsUpdateCall struct {
s *Service
bucket string
bucket2 *Bucket
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Updates a bucket. Changes to the bucket will be readable
// immediately after writing, but configuration changes may take time to
// propagate.
func (r *BucketsService) Update(bucket string, bucket2 *Bucket) *BucketsUpdateCall {
c := &BucketsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.bucket2 = bucket2
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the return of the bucket metadata
// conditional on whether the bucket's current metageneration matches
// the given value.
func (c *BucketsUpdateCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *BucketsUpdateCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the return of the bucket metadata
// conditional on whether the bucket's current metageneration does not
// match the given value.
func (c *BucketsUpdateCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *BucketsUpdateCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// PredefinedAcl sets the optional parameter "predefinedAcl": Apply a
// predefined set of access controls to this bucket.
//
// Possible values:
// "authenticatedRead" - Project team owners get OWNER access, and
// allAuthenticatedUsers get READER access.
// "private" - Project team owners get OWNER access.
// "projectPrivate" - Project team members get access according to
// their roles.
// "publicRead" - Project team owners get OWNER access, and allUsers
// get READER access.
// "publicReadWrite" - Project team owners get OWNER access, and
// allUsers get WRITER access.
func (c *BucketsUpdateCall) PredefinedAcl(predefinedAcl string) *BucketsUpdateCall {
c.urlParams_.Set("predefinedAcl", predefinedAcl)
return c
}
// PredefinedDefaultObjectAcl sets the optional parameter
// "predefinedDefaultObjectAcl": Apply a predefined set of default
// object access controls to this bucket.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *BucketsUpdateCall) PredefinedDefaultObjectAcl(predefinedDefaultObjectAcl string) *BucketsUpdateCall {
c.urlParams_.Set("predefinedDefaultObjectAcl", predefinedDefaultObjectAcl)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit owner, acl and defaultObjectAcl properties.
func (c *BucketsUpdateCall) Projection(projection string) *BucketsUpdateCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsUpdateCall) Fields(s ...googleapi.Field) *BucketsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsUpdateCall) Context(ctx context.Context) *BucketsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.bucket2)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.update" call.
// Exactly one of *Bucket or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Bucket.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *BucketsUpdateCall) Do(opts ...googleapi.CallOption) (*Bucket, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Bucket{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a bucket. Changes to the bucket will be readable immediately after writing, but configuration changes may take time to propagate.",
// "httpMethod": "PUT",
// "id": "storage.buckets.update",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "predefinedAcl": {
// "description": "Apply a predefined set of access controls to this bucket.",
// "enum": [
// "authenticatedRead",
// "private",
// "projectPrivate",
// "publicRead",
// "publicReadWrite"
// ],
// "enumDescriptions": [
// "Project team owners get OWNER access, and allAuthenticatedUsers get READER access.",
// "Project team owners get OWNER access.",
// "Project team members get access according to their roles.",
// "Project team owners get OWNER access, and allUsers get READER access.",
// "Project team owners get OWNER access, and allUsers get WRITER access."
// ],
// "location": "query",
// "type": "string"
// },
// "predefinedDefaultObjectAcl": {
// "description": "Apply a predefined set of default object access controls to this bucket.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit owner, acl and defaultObjectAcl properties."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}",
// "request": {
// "$ref": "Bucket"
// },
// "response": {
// "$ref": "Bucket"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.channels.stop":
type ChannelsStopCall struct {
s *Service
channel *Channel
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Stop: Stop watching resources through this channel
func (r *ChannelsService) Stop(channel *Channel) *ChannelsStopCall {
c := &ChannelsStopCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.channel = channel
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ChannelsStopCall) Fields(s ...googleapi.Field) *ChannelsStopCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ChannelsStopCall) Context(ctx context.Context) *ChannelsStopCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ChannelsStopCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ChannelsStopCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.channel)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "channels/stop")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.channels.stop" call.
func (c *ChannelsStopCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Stop watching resources through this channel",
// "httpMethod": "POST",
// "id": "storage.channels.stop",
// "path": "channels/stop",
// "request": {
// "$ref": "Channel",
// "parameterName": "resource"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.defaultObjectAccessControls.delete":
type DefaultObjectAccessControlsDeleteCall struct {
s *Service
bucket string
entity string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Permanently deletes the default object ACL entry for the
// specified entity on the specified bucket.
func (r *DefaultObjectAccessControlsService) Delete(bucket string, entity string) *DefaultObjectAccessControlsDeleteCall {
c := &DefaultObjectAccessControlsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *DefaultObjectAccessControlsDeleteCall) Fields(s ...googleapi.Field) *DefaultObjectAccessControlsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *DefaultObjectAccessControlsDeleteCall) Context(ctx context.Context) *DefaultObjectAccessControlsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *DefaultObjectAccessControlsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *DefaultObjectAccessControlsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/defaultObjectAcl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.defaultObjectAccessControls.delete" call.
func (c *DefaultObjectAccessControlsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Permanently deletes the default object ACL entry for the specified entity on the specified bucket.",
// "httpMethod": "DELETE",
// "id": "storage.defaultObjectAccessControls.delete",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/defaultObjectAcl/{entity}",
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.defaultObjectAccessControls.get":
type DefaultObjectAccessControlsGetCall struct {
s *Service
bucket string
entity string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Returns the default object ACL entry for the specified entity on
// the specified bucket.
func (r *DefaultObjectAccessControlsService) Get(bucket string, entity string) *DefaultObjectAccessControlsGetCall {
c := &DefaultObjectAccessControlsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *DefaultObjectAccessControlsGetCall) Fields(s ...googleapi.Field) *DefaultObjectAccessControlsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *DefaultObjectAccessControlsGetCall) IfNoneMatch(entityTag string) *DefaultObjectAccessControlsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *DefaultObjectAccessControlsGetCall) Context(ctx context.Context) *DefaultObjectAccessControlsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *DefaultObjectAccessControlsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *DefaultObjectAccessControlsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/defaultObjectAcl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.defaultObjectAccessControls.get" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *DefaultObjectAccessControlsGetCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns the default object ACL entry for the specified entity on the specified bucket.",
// "httpMethod": "GET",
// "id": "storage.defaultObjectAccessControls.get",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/defaultObjectAcl/{entity}",
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.defaultObjectAccessControls.insert":
type DefaultObjectAccessControlsInsertCall struct {
s *Service
bucket string
objectaccesscontrol *ObjectAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Creates a new default object ACL entry on the specified
// bucket.
func (r *DefaultObjectAccessControlsService) Insert(bucket string, objectaccesscontrol *ObjectAccessControl) *DefaultObjectAccessControlsInsertCall {
c := &DefaultObjectAccessControlsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.objectaccesscontrol = objectaccesscontrol
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *DefaultObjectAccessControlsInsertCall) Fields(s ...googleapi.Field) *DefaultObjectAccessControlsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *DefaultObjectAccessControlsInsertCall) Context(ctx context.Context) *DefaultObjectAccessControlsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *DefaultObjectAccessControlsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *DefaultObjectAccessControlsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.objectaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/defaultObjectAcl")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.defaultObjectAccessControls.insert" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *DefaultObjectAccessControlsInsertCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a new default object ACL entry on the specified bucket.",
// "httpMethod": "POST",
// "id": "storage.defaultObjectAccessControls.insert",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/defaultObjectAcl",
// "request": {
// "$ref": "ObjectAccessControl"
// },
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.defaultObjectAccessControls.list":
type DefaultObjectAccessControlsListCall struct {
s *Service
bucket string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Retrieves default object ACL entries on the specified bucket.
func (r *DefaultObjectAccessControlsService) List(bucket string) *DefaultObjectAccessControlsListCall {
c := &DefaultObjectAccessControlsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": If present, only return default ACL listing
// if the bucket's current metageneration matches this value.
func (c *DefaultObjectAccessControlsListCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *DefaultObjectAccessControlsListCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": If present, only return default ACL
// listing if the bucket's current metageneration does not match the
// given value.
func (c *DefaultObjectAccessControlsListCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *DefaultObjectAccessControlsListCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *DefaultObjectAccessControlsListCall) Fields(s ...googleapi.Field) *DefaultObjectAccessControlsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *DefaultObjectAccessControlsListCall) IfNoneMatch(entityTag string) *DefaultObjectAccessControlsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *DefaultObjectAccessControlsListCall) Context(ctx context.Context) *DefaultObjectAccessControlsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *DefaultObjectAccessControlsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *DefaultObjectAccessControlsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/defaultObjectAcl")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.defaultObjectAccessControls.list" call.
// Exactly one of *ObjectAccessControls or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControls.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *DefaultObjectAccessControlsListCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControls, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControls{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves default object ACL entries on the specified bucket.",
// "httpMethod": "GET",
// "id": "storage.defaultObjectAccessControls.list",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "If present, only return default ACL listing if the bucket's current metageneration matches this value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "If present, only return default ACL listing if the bucket's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}/defaultObjectAcl",
// "response": {
// "$ref": "ObjectAccessControls"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.defaultObjectAccessControls.patch":
type DefaultObjectAccessControlsPatchCall struct {
s *Service
bucket string
entity string
objectaccesscontrol *ObjectAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates a default object ACL entry on the specified bucket.
// This method supports patch semantics.
func (r *DefaultObjectAccessControlsService) Patch(bucket string, entity string, objectaccesscontrol *ObjectAccessControl) *DefaultObjectAccessControlsPatchCall {
c := &DefaultObjectAccessControlsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
c.objectaccesscontrol = objectaccesscontrol
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *DefaultObjectAccessControlsPatchCall) Fields(s ...googleapi.Field) *DefaultObjectAccessControlsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *DefaultObjectAccessControlsPatchCall) Context(ctx context.Context) *DefaultObjectAccessControlsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *DefaultObjectAccessControlsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *DefaultObjectAccessControlsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.objectaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/defaultObjectAcl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PATCH", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.defaultObjectAccessControls.patch" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *DefaultObjectAccessControlsPatchCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a default object ACL entry on the specified bucket. This method supports patch semantics.",
// "httpMethod": "PATCH",
// "id": "storage.defaultObjectAccessControls.patch",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/defaultObjectAcl/{entity}",
// "request": {
// "$ref": "ObjectAccessControl"
// },
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.defaultObjectAccessControls.update":
type DefaultObjectAccessControlsUpdateCall struct {
s *Service
bucket string
entity string
objectaccesscontrol *ObjectAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Updates a default object ACL entry on the specified bucket.
func (r *DefaultObjectAccessControlsService) Update(bucket string, entity string, objectaccesscontrol *ObjectAccessControl) *DefaultObjectAccessControlsUpdateCall {
c := &DefaultObjectAccessControlsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
c.objectaccesscontrol = objectaccesscontrol
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *DefaultObjectAccessControlsUpdateCall) Fields(s ...googleapi.Field) *DefaultObjectAccessControlsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *DefaultObjectAccessControlsUpdateCall) Context(ctx context.Context) *DefaultObjectAccessControlsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *DefaultObjectAccessControlsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *DefaultObjectAccessControlsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.objectaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/defaultObjectAcl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.defaultObjectAccessControls.update" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *DefaultObjectAccessControlsUpdateCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a default object ACL entry on the specified bucket.",
// "httpMethod": "PUT",
// "id": "storage.defaultObjectAccessControls.update",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/defaultObjectAcl/{entity}",
// "request": {
// "$ref": "ObjectAccessControl"
// },
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objectAccessControls.delete":
type ObjectAccessControlsDeleteCall struct {
s *Service
bucket string
object string
entity string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Permanently deletes the ACL entry for the specified entity on
// the specified object.
func (r *ObjectAccessControlsService) Delete(bucket string, object string, entity string) *ObjectAccessControlsDeleteCall {
c := &ObjectAccessControlsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.entity = entity
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectAccessControlsDeleteCall) Generation(generation int64) *ObjectAccessControlsDeleteCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectAccessControlsDeleteCall) Fields(s ...googleapi.Field) *ObjectAccessControlsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectAccessControlsDeleteCall) Context(ctx context.Context) *ObjectAccessControlsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectAccessControlsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectAccessControlsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objectAccessControls.delete" call.
func (c *ObjectAccessControlsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Permanently deletes the ACL entry for the specified entity on the specified object.",
// "httpMethod": "DELETE",
// "id": "storage.objectAccessControls.delete",
// "parameterOrder": [
// "bucket",
// "object",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/acl/{entity}",
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objectAccessControls.get":
type ObjectAccessControlsGetCall struct {
s *Service
bucket string
object string
entity string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Returns the ACL entry for the specified entity on the specified
// object.
func (r *ObjectAccessControlsService) Get(bucket string, object string, entity string) *ObjectAccessControlsGetCall {
c := &ObjectAccessControlsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.entity = entity
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectAccessControlsGetCall) Generation(generation int64) *ObjectAccessControlsGetCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectAccessControlsGetCall) Fields(s ...googleapi.Field) *ObjectAccessControlsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ObjectAccessControlsGetCall) IfNoneMatch(entityTag string) *ObjectAccessControlsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectAccessControlsGetCall) Context(ctx context.Context) *ObjectAccessControlsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectAccessControlsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectAccessControlsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objectAccessControls.get" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ObjectAccessControlsGetCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns the ACL entry for the specified entity on the specified object.",
// "httpMethod": "GET",
// "id": "storage.objectAccessControls.get",
// "parameterOrder": [
// "bucket",
// "object",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/acl/{entity}",
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objectAccessControls.insert":
type ObjectAccessControlsInsertCall struct {
s *Service
bucket string
object string
objectaccesscontrol *ObjectAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Creates a new ACL entry on the specified object.
func (r *ObjectAccessControlsService) Insert(bucket string, object string, objectaccesscontrol *ObjectAccessControl) *ObjectAccessControlsInsertCall {
c := &ObjectAccessControlsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.objectaccesscontrol = objectaccesscontrol
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectAccessControlsInsertCall) Generation(generation int64) *ObjectAccessControlsInsertCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectAccessControlsInsertCall) Fields(s ...googleapi.Field) *ObjectAccessControlsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectAccessControlsInsertCall) Context(ctx context.Context) *ObjectAccessControlsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectAccessControlsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectAccessControlsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.objectaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/acl")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objectAccessControls.insert" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ObjectAccessControlsInsertCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a new ACL entry on the specified object.",
// "httpMethod": "POST",
// "id": "storage.objectAccessControls.insert",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/acl",
// "request": {
// "$ref": "ObjectAccessControl"
// },
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objectAccessControls.list":
type ObjectAccessControlsListCall struct {
s *Service
bucket string
object string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Retrieves ACL entries on the specified object.
func (r *ObjectAccessControlsService) List(bucket string, object string) *ObjectAccessControlsListCall {
c := &ObjectAccessControlsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectAccessControlsListCall) Generation(generation int64) *ObjectAccessControlsListCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectAccessControlsListCall) Fields(s ...googleapi.Field) *ObjectAccessControlsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ObjectAccessControlsListCall) IfNoneMatch(entityTag string) *ObjectAccessControlsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectAccessControlsListCall) Context(ctx context.Context) *ObjectAccessControlsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectAccessControlsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectAccessControlsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/acl")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objectAccessControls.list" call.
// Exactly one of *ObjectAccessControls or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControls.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ObjectAccessControlsListCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControls, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControls{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves ACL entries on the specified object.",
// "httpMethod": "GET",
// "id": "storage.objectAccessControls.list",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/acl",
// "response": {
// "$ref": "ObjectAccessControls"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objectAccessControls.patch":
type ObjectAccessControlsPatchCall struct {
s *Service
bucket string
object string
entity string
objectaccesscontrol *ObjectAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates an ACL entry on the specified object. This method
// supports patch semantics.
func (r *ObjectAccessControlsService) Patch(bucket string, object string, entity string, objectaccesscontrol *ObjectAccessControl) *ObjectAccessControlsPatchCall {
c := &ObjectAccessControlsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.entity = entity
c.objectaccesscontrol = objectaccesscontrol
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectAccessControlsPatchCall) Generation(generation int64) *ObjectAccessControlsPatchCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectAccessControlsPatchCall) Fields(s ...googleapi.Field) *ObjectAccessControlsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectAccessControlsPatchCall) Context(ctx context.Context) *ObjectAccessControlsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectAccessControlsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectAccessControlsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.objectaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PATCH", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objectAccessControls.patch" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ObjectAccessControlsPatchCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an ACL entry on the specified object. This method supports patch semantics.",
// "httpMethod": "PATCH",
// "id": "storage.objectAccessControls.patch",
// "parameterOrder": [
// "bucket",
// "object",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/acl/{entity}",
// "request": {
// "$ref": "ObjectAccessControl"
// },
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objectAccessControls.update":
type ObjectAccessControlsUpdateCall struct {
s *Service
bucket string
object string
entity string
objectaccesscontrol *ObjectAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Updates an ACL entry on the specified object.
func (r *ObjectAccessControlsService) Update(bucket string, object string, entity string, objectaccesscontrol *ObjectAccessControl) *ObjectAccessControlsUpdateCall {
c := &ObjectAccessControlsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.entity = entity
c.objectaccesscontrol = objectaccesscontrol
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectAccessControlsUpdateCall) Generation(generation int64) *ObjectAccessControlsUpdateCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectAccessControlsUpdateCall) Fields(s ...googleapi.Field) *ObjectAccessControlsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectAccessControlsUpdateCall) Context(ctx context.Context) *ObjectAccessControlsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectAccessControlsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectAccessControlsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.objectaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objectAccessControls.update" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ObjectAccessControlsUpdateCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an ACL entry on the specified object.",
// "httpMethod": "PUT",
// "id": "storage.objectAccessControls.update",
// "parameterOrder": [
// "bucket",
// "object",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/acl/{entity}",
// "request": {
// "$ref": "ObjectAccessControl"
// },
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objects.compose":
type ObjectsComposeCall struct {
s *Service
destinationBucket string
destinationObject string
composerequest *ComposeRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Compose: Concatenates a list of existing objects into a new object in
// the same bucket.
func (r *ObjectsService) Compose(destinationBucket string, destinationObject string, composerequest *ComposeRequest) *ObjectsComposeCall {
c := &ObjectsComposeCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.destinationBucket = destinationBucket
c.destinationObject = destinationObject
c.composerequest = composerequest
return c
}
// DestinationPredefinedAcl sets the optional parameter
// "destinationPredefinedAcl": Apply a predefined set of access controls
// to the destination object.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *ObjectsComposeCall) DestinationPredefinedAcl(destinationPredefinedAcl string) *ObjectsComposeCall {
c.urlParams_.Set("destinationPredefinedAcl", destinationPredefinedAcl)
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the object's current
// generation matches the given value.
func (c *ObjectsComposeCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsComposeCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the object's current metageneration matches the given value.
func (c *ObjectsComposeCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsComposeCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsComposeCall) Fields(s ...googleapi.Field) *ObjectsComposeCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do and Download
// methods. Any pending HTTP request will be aborted if the provided
// context is canceled.
func (c *ObjectsComposeCall) Context(ctx context.Context) *ObjectsComposeCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsComposeCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsComposeCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.composerequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{destinationBucket}/o/{destinationObject}/compose")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"destinationBucket": c.destinationBucket,
"destinationObject": c.destinationObject,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Download fetches the API endpoint's "media" value, instead of the normal
// API response value. If the returned error is nil, the Response is guaranteed to
// have a 2xx status code. Callers must close the Response.Body as usual.
func (c *ObjectsComposeCall) Download(opts ...googleapi.CallOption) (*http.Response, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("media")
if err != nil {
return nil, err
}
if err := googleapi.CheckMediaResponse(res); err != nil {
res.Body.Close()
return nil, err
}
return res, nil
}
// Do executes the "storage.objects.compose" call.
// Exactly one of *Object or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Object.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsComposeCall) Do(opts ...googleapi.CallOption) (*Object, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Object{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Concatenates a list of existing objects into a new object in the same bucket.",
// "httpMethod": "POST",
// "id": "storage.objects.compose",
// "parameterOrder": [
// "destinationBucket",
// "destinationObject"
// ],
// "parameters": {
// "destinationBucket": {
// "description": "Name of the bucket in which to store the new object.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "destinationObject": {
// "description": "Name of the new object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "destinationPredefinedAcl": {
// "description": "Apply a predefined set of access controls to the destination object.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{destinationBucket}/o/{destinationObject}/compose",
// "request": {
// "$ref": "ComposeRequest"
// },
// "response": {
// "$ref": "Object"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ],
// "supportsMediaDownload": true,
// "useMediaDownloadService": true
// }
}
// method id "storage.objects.copy":
type ObjectsCopyCall struct {
s *Service
sourceBucket string
sourceObject string
destinationBucket string
destinationObject string
object *Object
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Copy: Copies a source object to a destination object. Optionally
// overrides metadata.
func (r *ObjectsService) Copy(sourceBucket string, sourceObject string, destinationBucket string, destinationObject string, object *Object) *ObjectsCopyCall {
c := &ObjectsCopyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.sourceBucket = sourceBucket
c.sourceObject = sourceObject
c.destinationBucket = destinationBucket
c.destinationObject = destinationObject
c.object = object
return c
}
// DestinationPredefinedAcl sets the optional parameter
// "destinationPredefinedAcl": Apply a predefined set of access controls
// to the destination object.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *ObjectsCopyCall) DestinationPredefinedAcl(destinationPredefinedAcl string) *ObjectsCopyCall {
c.urlParams_.Set("destinationPredefinedAcl", destinationPredefinedAcl)
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the destination object's
// current generation matches the given value.
func (c *ObjectsCopyCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfGenerationNotMatch sets the optional parameter
// "ifGenerationNotMatch": Makes the operation conditional on whether
// the destination object's current generation does not match the given
// value.
func (c *ObjectsCopyCall) IfGenerationNotMatch(ifGenerationNotMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifGenerationNotMatch", fmt.Sprint(ifGenerationNotMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the destination object's current metageneration matches the given
// value.
func (c *ObjectsCopyCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the operation conditional on
// whether the destination object's current metageneration does not
// match the given value.
func (c *ObjectsCopyCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// IfSourceGenerationMatch sets the optional parameter
// "ifSourceGenerationMatch": Makes the operation conditional on whether
// the source object's generation matches the given value.
func (c *ObjectsCopyCall) IfSourceGenerationMatch(ifSourceGenerationMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifSourceGenerationMatch", fmt.Sprint(ifSourceGenerationMatch))
return c
}
// IfSourceGenerationNotMatch sets the optional parameter
// "ifSourceGenerationNotMatch": Makes the operation conditional on
// whether the source object's generation does not match the given
// value.
func (c *ObjectsCopyCall) IfSourceGenerationNotMatch(ifSourceGenerationNotMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifSourceGenerationNotMatch", fmt.Sprint(ifSourceGenerationNotMatch))
return c
}
// IfSourceMetagenerationMatch sets the optional parameter
// "ifSourceMetagenerationMatch": Makes the operation conditional on
// whether the source object's current metageneration matches the given
// value.
func (c *ObjectsCopyCall) IfSourceMetagenerationMatch(ifSourceMetagenerationMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifSourceMetagenerationMatch", fmt.Sprint(ifSourceMetagenerationMatch))
return c
}
// IfSourceMetagenerationNotMatch sets the optional parameter
// "ifSourceMetagenerationNotMatch": Makes the operation conditional on
// whether the source object's current metageneration does not match the
// given value.
func (c *ObjectsCopyCall) IfSourceMetagenerationNotMatch(ifSourceMetagenerationNotMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifSourceMetagenerationNotMatch", fmt.Sprint(ifSourceMetagenerationNotMatch))
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl, unless the object resource
// specifies the acl property, when it defaults to full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsCopyCall) Projection(projection string) *ObjectsCopyCall {
c.urlParams_.Set("projection", projection)
return c
}
// SourceGeneration sets the optional parameter "sourceGeneration": If
// present, selects a specific revision of the source object (as opposed
// to the latest version, the default).
func (c *ObjectsCopyCall) SourceGeneration(sourceGeneration int64) *ObjectsCopyCall {
c.urlParams_.Set("sourceGeneration", fmt.Sprint(sourceGeneration))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsCopyCall) Fields(s ...googleapi.Field) *ObjectsCopyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do and Download
// methods. Any pending HTTP request will be aborted if the provided
// context is canceled.
func (c *ObjectsCopyCall) Context(ctx context.Context) *ObjectsCopyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsCopyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsCopyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.object)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{sourceBucket}/o/{sourceObject}/copyTo/b/{destinationBucket}/o/{destinationObject}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"sourceBucket": c.sourceBucket,
"sourceObject": c.sourceObject,
"destinationBucket": c.destinationBucket,
"destinationObject": c.destinationObject,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Download fetches the API endpoint's "media" value, instead of the normal
// API response value. If the returned error is nil, the Response is guaranteed to
// have a 2xx status code. Callers must close the Response.Body as usual.
func (c *ObjectsCopyCall) Download(opts ...googleapi.CallOption) (*http.Response, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("media")
if err != nil {
return nil, err
}
if err := googleapi.CheckMediaResponse(res); err != nil {
res.Body.Close()
return nil, err
}
return res, nil
}
// Do executes the "storage.objects.copy" call.
// Exactly one of *Object or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Object.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsCopyCall) Do(opts ...googleapi.CallOption) (*Object, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Object{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Copies a source object to a destination object. Optionally overrides metadata.",
// "httpMethod": "POST",
// "id": "storage.objects.copy",
// "parameterOrder": [
// "sourceBucket",
// "sourceObject",
// "destinationBucket",
// "destinationObject"
// ],
// "parameters": {
// "destinationBucket": {
// "description": "Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "destinationObject": {
// "description": "Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "destinationPredefinedAcl": {
// "description": "Apply a predefined set of access controls to the destination object.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the destination object's current generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the destination object's current generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the destination object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the destination object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceGenerationMatch": {
// "description": "Makes the operation conditional on whether the source object's generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the source object's generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the source object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the source object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// },
// "sourceBucket": {
// "description": "Name of the bucket in which to find the source object.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "sourceGeneration": {
// "description": "If present, selects a specific revision of the source object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "sourceObject": {
// "description": "Name of the source object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{sourceBucket}/o/{sourceObject}/copyTo/b/{destinationBucket}/o/{destinationObject}",
// "request": {
// "$ref": "Object"
// },
// "response": {
// "$ref": "Object"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ],
// "supportsMediaDownload": true,
// "useMediaDownloadService": true
// }
}
// method id "storage.objects.delete":
type ObjectsDeleteCall struct {
s *Service
bucket string
object string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes an object and its metadata. Deletions are permanent
// if versioning is not enabled for the bucket, or if the generation
// parameter is used.
func (r *ObjectsService) Delete(bucket string, object string) *ObjectsDeleteCall {
c := &ObjectsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
return c
}
// Generation sets the optional parameter "generation": If present,
// permanently deletes a specific revision of this object (as opposed to
// the latest version, the default).
func (c *ObjectsDeleteCall) Generation(generation int64) *ObjectsDeleteCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the object's current
// generation matches the given value.
func (c *ObjectsDeleteCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsDeleteCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfGenerationNotMatch sets the optional parameter
// "ifGenerationNotMatch": Makes the operation conditional on whether
// the object's current generation does not match the given value.
func (c *ObjectsDeleteCall) IfGenerationNotMatch(ifGenerationNotMatch int64) *ObjectsDeleteCall {
c.urlParams_.Set("ifGenerationNotMatch", fmt.Sprint(ifGenerationNotMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the object's current metageneration matches the given value.
func (c *ObjectsDeleteCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsDeleteCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the operation conditional on
// whether the object's current metageneration does not match the given
// value.
func (c *ObjectsDeleteCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *ObjectsDeleteCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsDeleteCall) Fields(s ...googleapi.Field) *ObjectsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsDeleteCall) Context(ctx context.Context) *ObjectsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.delete" call.
func (c *ObjectsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes an object and its metadata. Deletions are permanent if versioning is not enabled for the bucket, or if the generation parameter is used.",
// "httpMethod": "DELETE",
// "id": "storage.objects.delete",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which the object resides.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, permanently deletes a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}",
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.objects.get":
type ObjectsGetCall struct {
s *Service
bucket string
object string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Retrieves an object or its metadata.
func (r *ObjectsService) Get(bucket string, object string) *ObjectsGetCall {
c := &ObjectsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectsGetCall) Generation(generation int64) *ObjectsGetCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the object's generation
// matches the given value.
func (c *ObjectsGetCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsGetCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfGenerationNotMatch sets the optional parameter
// "ifGenerationNotMatch": Makes the operation conditional on whether
// the object's generation does not match the given value.
func (c *ObjectsGetCall) IfGenerationNotMatch(ifGenerationNotMatch int64) *ObjectsGetCall {
c.urlParams_.Set("ifGenerationNotMatch", fmt.Sprint(ifGenerationNotMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the object's current metageneration matches the given value.
func (c *ObjectsGetCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsGetCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the operation conditional on
// whether the object's current metageneration does not match the given
// value.
func (c *ObjectsGetCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *ObjectsGetCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsGetCall) Projection(projection string) *ObjectsGetCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsGetCall) Fields(s ...googleapi.Field) *ObjectsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ObjectsGetCall) IfNoneMatch(entityTag string) *ObjectsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do and Download
// methods. Any pending HTTP request will be aborted if the provided
// context is canceled.
func (c *ObjectsGetCall) Context(ctx context.Context) *ObjectsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Download fetches the API endpoint's "media" value, instead of the normal
// API response value. If the returned error is nil, the Response is guaranteed to
// have a 2xx status code. Callers must close the Response.Body as usual.
func (c *ObjectsGetCall) Download(opts ...googleapi.CallOption) (*http.Response, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("media")
if err != nil {
return nil, err
}
if err := googleapi.CheckMediaResponse(res); err != nil {
res.Body.Close()
return nil, err
}
return res, nil
}
// Do executes the "storage.objects.get" call.
// Exactly one of *Object or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Object.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsGetCall) Do(opts ...googleapi.CallOption) (*Object, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Object{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves an object or its metadata.",
// "httpMethod": "GET",
// "id": "storage.objects.get",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which the object resides.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the object's generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}",
// "response": {
// "$ref": "Object"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ],
// "supportsMediaDownload": true,
// "useMediaDownloadService": true
// }
}
// method id "storage.objects.getIamPolicy":
type ObjectsGetIamPolicyCall struct {
s *Service
bucket string
object string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// GetIamPolicy: Returns an IAM policy for the specified object.
func (r *ObjectsService) GetIamPolicy(bucket string, object string) *ObjectsGetIamPolicyCall {
c := &ObjectsGetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectsGetIamPolicyCall) Generation(generation int64) *ObjectsGetIamPolicyCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsGetIamPolicyCall) Fields(s ...googleapi.Field) *ObjectsGetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ObjectsGetIamPolicyCall) IfNoneMatch(entityTag string) *ObjectsGetIamPolicyCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsGetIamPolicyCall) Context(ctx context.Context) *ObjectsGetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsGetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsGetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/iam")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.getIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsGetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns an IAM policy for the specified object.",
// "httpMethod": "GET",
// "id": "storage.objects.getIamPolicy",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which the object resides.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/iam",
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.objects.insert":
type ObjectsInsertCall struct {
s *Service
bucket string
object *Object
urlParams_ gensupport.URLParams
media_ io.Reader
mediaBuffer_ *gensupport.MediaBuffer
mediaType_ string
mediaSize_ int64 // mediaSize, if known. Used only for calls to progressUpdater_.
progressUpdater_ googleapi.ProgressUpdater
ctx_ context.Context
header_ http.Header
}
// Insert: Stores a new object and metadata.
func (r *ObjectsService) Insert(bucket string, object *Object) *ObjectsInsertCall {
c := &ObjectsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
return c
}
// ContentEncoding sets the optional parameter "contentEncoding": If
// set, sets the contentEncoding property of the final object to this
// value. Setting this parameter is equivalent to setting the
// contentEncoding metadata property. This can be useful when uploading
// an object with uploadType=media to indicate the encoding of the
// content being uploaded.
func (c *ObjectsInsertCall) ContentEncoding(contentEncoding string) *ObjectsInsertCall {
c.urlParams_.Set("contentEncoding", contentEncoding)
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the object's current
// generation matches the given value.
func (c *ObjectsInsertCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsInsertCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfGenerationNotMatch sets the optional parameter
// "ifGenerationNotMatch": Makes the operation conditional on whether
// the object's current generation does not match the given value.
func (c *ObjectsInsertCall) IfGenerationNotMatch(ifGenerationNotMatch int64) *ObjectsInsertCall {
c.urlParams_.Set("ifGenerationNotMatch", fmt.Sprint(ifGenerationNotMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the object's current metageneration matches the given value.
func (c *ObjectsInsertCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsInsertCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the operation conditional on
// whether the object's current metageneration does not match the given
// value.
func (c *ObjectsInsertCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *ObjectsInsertCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// Name sets the optional parameter "name": Name of the object. Required
// when the object metadata is not otherwise provided. Overrides the
// object metadata's name value, if any. For information about how to
// URL encode object names to be path safe, see Encoding URI Path Parts.
func (c *ObjectsInsertCall) Name(name string) *ObjectsInsertCall {
c.urlParams_.Set("name", name)
return c
}
// PredefinedAcl sets the optional parameter "predefinedAcl": Apply a
// predefined set of access controls to this object.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *ObjectsInsertCall) PredefinedAcl(predefinedAcl string) *ObjectsInsertCall {
c.urlParams_.Set("predefinedAcl", predefinedAcl)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl, unless the object resource
// specifies the acl property, when it defaults to full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsInsertCall) Projection(projection string) *ObjectsInsertCall {
c.urlParams_.Set("projection", projection)
return c
}
// Media specifies the media to upload in one or more chunks. The chunk
// size may be controlled by supplying a MediaOption generated by
// googleapi.ChunkSize. The chunk size defaults to
// googleapi.DefaultUploadChunkSize.The Content-Type header used in the
// upload request will be determined by sniffing the contents of r,
// unless a MediaOption generated by googleapi.ContentType is
// supplied.
// At most one of Media and ResumableMedia may be set.
func (c *ObjectsInsertCall) Media(r io.Reader, options ...googleapi.MediaOption) *ObjectsInsertCall {
if ct := c.object.ContentType; ct != "" {
options = append([]googleapi.MediaOption{googleapi.ContentType(ct)}, options...)
}
opts := googleapi.ProcessMediaOptions(options)
chunkSize := opts.ChunkSize
if !opts.ForceEmptyContentType {
r, c.mediaType_ = gensupport.DetermineContentType(r, opts.ContentType)
}
c.media_, c.mediaBuffer_ = gensupport.PrepareUpload(r, chunkSize)
return c
}
// ResumableMedia specifies the media to upload in chunks and can be
// canceled with ctx.
//
// Deprecated: use Media instead.
//
// At most one of Media and ResumableMedia may be set. mediaType
// identifies the MIME media type of the upload, such as "image/png". If
// mediaType is "", it will be auto-detected. The provided ctx will
// supersede any context previously provided to the Context method.
func (c *ObjectsInsertCall) ResumableMedia(ctx context.Context, r io.ReaderAt, size int64, mediaType string) *ObjectsInsertCall {
c.ctx_ = ctx
rdr := gensupport.ReaderAtToReader(r, size)
rdr, c.mediaType_ = gensupport.DetermineContentType(rdr, mediaType)
c.mediaBuffer_ = gensupport.NewMediaBuffer(rdr, googleapi.DefaultUploadChunkSize)
c.media_ = nil
c.mediaSize_ = size
return c
}
// ProgressUpdater provides a callback function that will be called
// after every chunk. It should be a low-latency function in order to
// not slow down the upload operation. This should only be called when
// using ResumableMedia (as opposed to Media).
func (c *ObjectsInsertCall) ProgressUpdater(pu googleapi.ProgressUpdater) *ObjectsInsertCall {
c.progressUpdater_ = pu
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsInsertCall) Fields(s ...googleapi.Field) *ObjectsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
// This context will supersede any context previously provided to the
// ResumableMedia method.
func (c *ObjectsInsertCall) Context(ctx context.Context) *ObjectsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.object)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o")
if c.media_ != nil || c.mediaBuffer_ != nil {
urls = strings.Replace(urls, "https://www.googleapis.com/", "https://www.googleapis.com/upload/", 1)
protocol := "multipart"
if c.mediaBuffer_ != nil {
protocol = "resumable"
}
c.urlParams_.Set("uploadType", protocol)
}
if body == nil {
body = new(bytes.Buffer)
reqHeaders.Set("Content-Type", "application/json")
}
if c.media_ != nil {
combined, ctype := gensupport.CombineBodyMedia(body, "application/json", c.media_, c.mediaType_)
defer combined.Close()
reqHeaders.Set("Content-Type", ctype)
body = combined
}
if c.mediaBuffer_ != nil && c.mediaType_ != "" {
reqHeaders.Set("X-Upload-Content-Type", c.mediaType_)
}
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.insert" call.
// Exactly one of *Object or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Object.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsInsertCall) Do(opts ...googleapi.CallOption) (*Object, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
if c.mediaBuffer_ != nil {
loc := res.Header.Get("Location")
rx := &gensupport.ResumableUpload{
Client: c.s.client,
UserAgent: c.s.userAgent(),
URI: loc,
Media: c.mediaBuffer_,
MediaType: c.mediaType_,
Callback: func(curr int64) {
if c.progressUpdater_ != nil {
c.progressUpdater_(curr, c.mediaSize_)
}
},
}
ctx := c.ctx_
if ctx == nil {
ctx = context.TODO()
}
res, err = rx.Upload(ctx)
if err != nil {
return nil, err
}
defer res.Body.Close()
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
}
ret := &Object{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Stores a new object and metadata.",
// "httpMethod": "POST",
// "id": "storage.objects.insert",
// "mediaUpload": {
// "accept": [
// "*/*"
// ],
// "protocols": {
// "resumable": {
// "multipart": true,
// "path": "/resumable/upload/storage/v1/b/{bucket}/o"
// },
// "simple": {
// "multipart": true,
// "path": "/upload/storage/v1/b/{bucket}/o"
// }
// }
// },
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "contentEncoding": {
// "description": "If set, sets the contentEncoding property of the final object to this value. Setting this parameter is equivalent to setting the contentEncoding metadata property. This can be useful when uploading an object with uploadType=media to indicate the encoding of the content being uploaded.",
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "name": {
// "description": "Name of the object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "query",
// "type": "string"
// },
// "predefinedAcl": {
// "description": "Apply a predefined set of access controls to this object.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}/o",
// "request": {
// "$ref": "Object"
// },
// "response": {
// "$ref": "Object"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ],
// "supportsMediaDownload": true,
// "supportsMediaUpload": true,
// "useMediaDownloadService": true
// }
}
// method id "storage.objects.list":
type ObjectsListCall struct {
s *Service
bucket string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Retrieves a list of objects matching the criteria.
func (r *ObjectsService) List(bucket string) *ObjectsListCall {
c := &ObjectsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
return c
}
// Delimiter sets the optional parameter "delimiter": Returns results in
// a directory-like mode. items will contain only objects whose names,
// aside from the prefix, do not contain delimiter. Objects whose names,
// aside from the prefix, contain delimiter will have their name,
// truncated after the delimiter, returned in prefixes. Duplicate
// prefixes are omitted.
func (c *ObjectsListCall) Delimiter(delimiter string) *ObjectsListCall {
c.urlParams_.Set("delimiter", delimiter)
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum number
// of items plus prefixes to return in a single page of responses. As
// duplicate prefixes are omitted, fewer total results may be returned
// than requested. The service will use this parameter or 1,000 items,
// whichever is smaller.
func (c *ObjectsListCall) MaxResults(maxResults int64) *ObjectsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// PageToken sets the optional parameter "pageToken": A
// previously-returned page token representing part of the larger set of
// results to view.
func (c *ObjectsListCall) PageToken(pageToken string) *ObjectsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Prefix sets the optional parameter "prefix": Filter results to
// objects whose names begin with this prefix.
func (c *ObjectsListCall) Prefix(prefix string) *ObjectsListCall {
c.urlParams_.Set("prefix", prefix)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsListCall) Projection(projection string) *ObjectsListCall {
c.urlParams_.Set("projection", projection)
return c
}
// Versions sets the optional parameter "versions": If true, lists all
// versions of an object as distinct results. The default is false. For
// more information, see Object Versioning.
func (c *ObjectsListCall) Versions(versions bool) *ObjectsListCall {
c.urlParams_.Set("versions", fmt.Sprint(versions))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsListCall) Fields(s ...googleapi.Field) *ObjectsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ObjectsListCall) IfNoneMatch(entityTag string) *ObjectsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsListCall) Context(ctx context.Context) *ObjectsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.list" call.
// Exactly one of *Objects or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Objects.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsListCall) Do(opts ...googleapi.CallOption) (*Objects, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Objects{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves a list of objects matching the criteria.",
// "httpMethod": "GET",
// "id": "storage.objects.list",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which to look for objects.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "delimiter": {
// "description": "Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "1000",
// "description": "Maximum number of items plus prefixes to return in a single page of responses. As duplicate prefixes are omitted, fewer total results may be returned than requested. The service will use this parameter or 1,000 items, whichever is smaller.",
// "format": "uint32",
// "location": "query",
// "minimum": "0",
// "type": "integer"
// },
// "pageToken": {
// "description": "A previously-returned page token representing part of the larger set of results to view.",
// "location": "query",
// "type": "string"
// },
// "prefix": {
// "description": "Filter results to objects whose names begin with this prefix.",
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// },
// "versions": {
// "description": "If true, lists all versions of an object as distinct results. The default is false. For more information, see Object Versioning.",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "b/{bucket}/o",
// "response": {
// "$ref": "Objects"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ],
// "supportsSubscription": true
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ObjectsListCall) Pages(ctx context.Context, f func(*Objects) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "storage.objects.patch":
type ObjectsPatchCall struct {
s *Service
bucket string
object string
object2 *Object
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates an object's metadata. This method supports patch
// semantics.
func (r *ObjectsService) Patch(bucket string, object string, object2 *Object) *ObjectsPatchCall {
c := &ObjectsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.object2 = object2
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectsPatchCall) Generation(generation int64) *ObjectsPatchCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the object's current
// generation matches the given value.
func (c *ObjectsPatchCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsPatchCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfGenerationNotMatch sets the optional parameter
// "ifGenerationNotMatch": Makes the operation conditional on whether
// the object's current generation does not match the given value.
func (c *ObjectsPatchCall) IfGenerationNotMatch(ifGenerationNotMatch int64) *ObjectsPatchCall {
c.urlParams_.Set("ifGenerationNotMatch", fmt.Sprint(ifGenerationNotMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the object's current metageneration matches the given value.
func (c *ObjectsPatchCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsPatchCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the operation conditional on
// whether the object's current metageneration does not match the given
// value.
func (c *ObjectsPatchCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *ObjectsPatchCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// PredefinedAcl sets the optional parameter "predefinedAcl": Apply a
// predefined set of access controls to this object.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *ObjectsPatchCall) PredefinedAcl(predefinedAcl string) *ObjectsPatchCall {
c.urlParams_.Set("predefinedAcl", predefinedAcl)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsPatchCall) Projection(projection string) *ObjectsPatchCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsPatchCall) Fields(s ...googleapi.Field) *ObjectsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsPatchCall) Context(ctx context.Context) *ObjectsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.object2)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PATCH", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.patch" call.
// Exactly one of *Object or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Object.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsPatchCall) Do(opts ...googleapi.CallOption) (*Object, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Object{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an object's metadata. This method supports patch semantics.",
// "httpMethod": "PATCH",
// "id": "storage.objects.patch",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which the object resides.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "predefinedAcl": {
// "description": "Apply a predefined set of access controls to this object.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}",
// "request": {
// "$ref": "Object"
// },
// "response": {
// "$ref": "Object"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objects.rewrite":
type ObjectsRewriteCall struct {
s *Service
sourceBucket string
sourceObject string
destinationBucket string
destinationObject string
object *Object
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Rewrite: Rewrites a source object to a destination object. Optionally
// overrides metadata.
func (r *ObjectsService) Rewrite(sourceBucket string, sourceObject string, destinationBucket string, destinationObject string, object *Object) *ObjectsRewriteCall {
c := &ObjectsRewriteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.sourceBucket = sourceBucket
c.sourceObject = sourceObject
c.destinationBucket = destinationBucket
c.destinationObject = destinationObject
c.object = object
return c
}
// DestinationPredefinedAcl sets the optional parameter
// "destinationPredefinedAcl": Apply a predefined set of access controls
// to the destination object.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *ObjectsRewriteCall) DestinationPredefinedAcl(destinationPredefinedAcl string) *ObjectsRewriteCall {
c.urlParams_.Set("destinationPredefinedAcl", destinationPredefinedAcl)
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the destination object's
// current generation matches the given value.
func (c *ObjectsRewriteCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfGenerationNotMatch sets the optional parameter
// "ifGenerationNotMatch": Makes the operation conditional on whether
// the destination object's current generation does not match the given
// value.
func (c *ObjectsRewriteCall) IfGenerationNotMatch(ifGenerationNotMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifGenerationNotMatch", fmt.Sprint(ifGenerationNotMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the destination object's current metageneration matches the given
// value.
func (c *ObjectsRewriteCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the operation conditional on
// whether the destination object's current metageneration does not
// match the given value.
func (c *ObjectsRewriteCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// IfSourceGenerationMatch sets the optional parameter
// "ifSourceGenerationMatch": Makes the operation conditional on whether
// the source object's generation matches the given value.
func (c *ObjectsRewriteCall) IfSourceGenerationMatch(ifSourceGenerationMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifSourceGenerationMatch", fmt.Sprint(ifSourceGenerationMatch))
return c
}
// IfSourceGenerationNotMatch sets the optional parameter
// "ifSourceGenerationNotMatch": Makes the operation conditional on
// whether the source object's generation does not match the given
// value.
func (c *ObjectsRewriteCall) IfSourceGenerationNotMatch(ifSourceGenerationNotMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifSourceGenerationNotMatch", fmt.Sprint(ifSourceGenerationNotMatch))
return c
}
// IfSourceMetagenerationMatch sets the optional parameter
// "ifSourceMetagenerationMatch": Makes the operation conditional on
// whether the source object's current metageneration matches the given
// value.
func (c *ObjectsRewriteCall) IfSourceMetagenerationMatch(ifSourceMetagenerationMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifSourceMetagenerationMatch", fmt.Sprint(ifSourceMetagenerationMatch))
return c
}
// IfSourceMetagenerationNotMatch sets the optional parameter
// "ifSourceMetagenerationNotMatch": Makes the operation conditional on
// whether the source object's current metageneration does not match the
// given value.
func (c *ObjectsRewriteCall) IfSourceMetagenerationNotMatch(ifSourceMetagenerationNotMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifSourceMetagenerationNotMatch", fmt.Sprint(ifSourceMetagenerationNotMatch))
return c
}
// MaxBytesRewrittenPerCall sets the optional parameter
// "maxBytesRewrittenPerCall": The maximum number of bytes that will be
// rewritten per rewrite request. Most callers shouldn't need to specify
// this parameter - it is primarily in place to support testing. If
// specified the value must be an integral multiple of 1 MiB (1048576).
// Also, this only applies to requests where the source and destination
// span locations and/or storage classes. Finally, this value must not
// change across rewrite calls else you'll get an error that the
// rewriteToken is invalid.
func (c *ObjectsRewriteCall) MaxBytesRewrittenPerCall(maxBytesRewrittenPerCall int64) *ObjectsRewriteCall {
c.urlParams_.Set("maxBytesRewrittenPerCall", fmt.Sprint(maxBytesRewrittenPerCall))
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl, unless the object resource
// specifies the acl property, when it defaults to full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsRewriteCall) Projection(projection string) *ObjectsRewriteCall {
c.urlParams_.Set("projection", projection)
return c
}
// RewriteToken sets the optional parameter "rewriteToken": Include this
// field (from the previous rewrite response) on each rewrite request
// after the first one, until the rewrite response 'done' flag is true.
// Calls that provide a rewriteToken can omit all other request fields,
// but if included those fields must match the values provided in the
// first rewrite request.
func (c *ObjectsRewriteCall) RewriteToken(rewriteToken string) *ObjectsRewriteCall {
c.urlParams_.Set("rewriteToken", rewriteToken)
return c
}
// SourceGeneration sets the optional parameter "sourceGeneration": If
// present, selects a specific revision of the source object (as opposed
// to the latest version, the default).
func (c *ObjectsRewriteCall) SourceGeneration(sourceGeneration int64) *ObjectsRewriteCall {
c.urlParams_.Set("sourceGeneration", fmt.Sprint(sourceGeneration))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsRewriteCall) Fields(s ...googleapi.Field) *ObjectsRewriteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsRewriteCall) Context(ctx context.Context) *ObjectsRewriteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsRewriteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsRewriteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.object)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{sourceBucket}/o/{sourceObject}/rewriteTo/b/{destinationBucket}/o/{destinationObject}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"sourceBucket": c.sourceBucket,
"sourceObject": c.sourceObject,
"destinationBucket": c.destinationBucket,
"destinationObject": c.destinationObject,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.rewrite" call.
// Exactly one of *RewriteResponse or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *RewriteResponse.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ObjectsRewriteCall) Do(opts ...googleapi.CallOption) (*RewriteResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &RewriteResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Rewrites a source object to a destination object. Optionally overrides metadata.",
// "httpMethod": "POST",
// "id": "storage.objects.rewrite",
// "parameterOrder": [
// "sourceBucket",
// "sourceObject",
// "destinationBucket",
// "destinationObject"
// ],
// "parameters": {
// "destinationBucket": {
// "description": "Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "destinationObject": {
// "description": "Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "destinationPredefinedAcl": {
// "description": "Apply a predefined set of access controls to the destination object.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the destination object's current generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the destination object's current generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the destination object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the destination object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceGenerationMatch": {
// "description": "Makes the operation conditional on whether the source object's generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the source object's generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the source object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the source object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "maxBytesRewrittenPerCall": {
// "description": "The maximum number of bytes that will be rewritten per rewrite request. Most callers shouldn't need to specify this parameter - it is primarily in place to support testing. If specified the value must be an integral multiple of 1 MiB (1048576). Also, this only applies to requests where the source and destination span locations and/or storage classes. Finally, this value must not change across rewrite calls else you'll get an error that the rewriteToken is invalid.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// },
// "rewriteToken": {
// "description": "Include this field (from the previous rewrite response) on each rewrite request after the first one, until the rewrite response 'done' flag is true. Calls that provide a rewriteToken can omit all other request fields, but if included those fields must match the values provided in the first rewrite request.",
// "location": "query",
// "type": "string"
// },
// "sourceBucket": {
// "description": "Name of the bucket in which to find the source object.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "sourceGeneration": {
// "description": "If present, selects a specific revision of the source object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "sourceObject": {
// "description": "Name of the source object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{sourceBucket}/o/{sourceObject}/rewriteTo/b/{destinationBucket}/o/{destinationObject}",
// "request": {
// "$ref": "Object"
// },
// "response": {
// "$ref": "RewriteResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.objects.setIamPolicy":
type ObjectsSetIamPolicyCall struct {
s *Service
bucket string
object string
policy *Policy
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// SetIamPolicy: Updates an IAM policy for the specified object.
func (r *ObjectsService) SetIamPolicy(bucket string, object string, policy *Policy) *ObjectsSetIamPolicyCall {
c := &ObjectsSetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.policy = policy
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectsSetIamPolicyCall) Generation(generation int64) *ObjectsSetIamPolicyCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsSetIamPolicyCall) Fields(s ...googleapi.Field) *ObjectsSetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsSetIamPolicyCall) Context(ctx context.Context) *ObjectsSetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsSetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsSetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.policy)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/iam")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.setIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsSetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an IAM policy for the specified object.",
// "httpMethod": "PUT",
// "id": "storage.objects.setIamPolicy",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which the object resides.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/iam",
// "request": {
// "$ref": "Policy"
// },
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.objects.testIamPermissions":
type ObjectsTestIamPermissionsCall struct {
s *Service
bucket string
object string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// TestIamPermissions: Tests a set of permissions on the given object to
// see which, if any, are held by the caller.
func (r *ObjectsService) TestIamPermissions(bucket string, object string, permissions []string) *ObjectsTestIamPermissionsCall {
c := &ObjectsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.urlParams_.SetMulti("permissions", append([]string{}, permissions...))
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectsTestIamPermissionsCall) Generation(generation int64) *ObjectsTestIamPermissionsCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsTestIamPermissionsCall) Fields(s ...googleapi.Field) *ObjectsTestIamPermissionsCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ObjectsTestIamPermissionsCall) IfNoneMatch(entityTag string) *ObjectsTestIamPermissionsCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsTestIamPermissionsCall) Context(ctx context.Context) *ObjectsTestIamPermissionsCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsTestIamPermissionsCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsTestIamPermissionsCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/iam/testPermissions")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.testIamPermissions" call.
// Exactly one of *TestIamPermissionsResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *TestIamPermissionsResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ObjectsTestIamPermissionsCall) Do(opts ...googleapi.CallOption) (*TestIamPermissionsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &TestIamPermissionsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Tests a set of permissions on the given object to see which, if any, are held by the caller.",
// "httpMethod": "GET",
// "id": "storage.objects.testIamPermissions",
// "parameterOrder": [
// "bucket",
// "object",
// "permissions"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which the object resides.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "permissions": {
// "description": "Permissions to test.",
// "location": "query",
// "repeated": true,
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/iam/testPermissions",
// "response": {
// "$ref": "TestIamPermissionsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.objects.update":
type ObjectsUpdateCall struct {
s *Service
bucket string
object string
object2 *Object
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Updates an object's metadata.
func (r *ObjectsService) Update(bucket string, object string, object2 *Object) *ObjectsUpdateCall {
c := &ObjectsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.object2 = object2
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectsUpdateCall) Generation(generation int64) *ObjectsUpdateCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the object's current
// generation matches the given value.
func (c *ObjectsUpdateCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsUpdateCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfGenerationNotMatch sets the optional parameter
// "ifGenerationNotMatch": Makes the operation conditional on whether
// the object's current generation does not match the given value.
func (c *ObjectsUpdateCall) IfGenerationNotMatch(ifGenerationNotMatch int64) *ObjectsUpdateCall {
c.urlParams_.Set("ifGenerationNotMatch", fmt.Sprint(ifGenerationNotMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the object's current metageneration matches the given value.
func (c *ObjectsUpdateCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsUpdateCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the operation conditional on
// whether the object's current metageneration does not match the given
// value.
func (c *ObjectsUpdateCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *ObjectsUpdateCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// PredefinedAcl sets the optional parameter "predefinedAcl": Apply a
// predefined set of access controls to this object.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *ObjectsUpdateCall) PredefinedAcl(predefinedAcl string) *ObjectsUpdateCall {
c.urlParams_.Set("predefinedAcl", predefinedAcl)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsUpdateCall) Projection(projection string) *ObjectsUpdateCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsUpdateCall) Fields(s ...googleapi.Field) *ObjectsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do and Download
// methods. Any pending HTTP request will be aborted if the provided
// context is canceled.
func (c *ObjectsUpdateCall) Context(ctx context.Context) *ObjectsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.object2)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Download fetches the API endpoint's "media" value, instead of the normal
// API response value. If the returned error is nil, the Response is guaranteed to
// have a 2xx status code. Callers must close the Response.Body as usual.
func (c *ObjectsUpdateCall) Download(opts ...googleapi.CallOption) (*http.Response, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("media")
if err != nil {
return nil, err
}
if err := googleapi.CheckMediaResponse(res); err != nil {
res.Body.Close()
return nil, err
}
return res, nil
}
// Do executes the "storage.objects.update" call.
// Exactly one of *Object or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Object.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsUpdateCall) Do(opts ...googleapi.CallOption) (*Object, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Object{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an object's metadata.",
// "httpMethod": "PUT",
// "id": "storage.objects.update",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which the object resides.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "predefinedAcl": {
// "description": "Apply a predefined set of access controls to this object.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}",
// "request": {
// "$ref": "Object"
// },
// "response": {
// "$ref": "Object"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ],
// "supportsMediaDownload": true,
// "useMediaDownloadService": true
// }
}
// method id "storage.objects.watchAll":
type ObjectsWatchAllCall struct {
s *Service
bucket string
channel *Channel
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// WatchAll: Watch for changes on all objects in a bucket.
func (r *ObjectsService) WatchAll(bucket string, channel *Channel) *ObjectsWatchAllCall {
c := &ObjectsWatchAllCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.channel = channel
return c
}
// Delimiter sets the optional parameter "delimiter": Returns results in
// a directory-like mode. items will contain only objects whose names,
// aside from the prefix, do not contain delimiter. Objects whose names,
// aside from the prefix, contain delimiter will have their name,
// truncated after the delimiter, returned in prefixes. Duplicate
// prefixes are omitted.
func (c *ObjectsWatchAllCall) Delimiter(delimiter string) *ObjectsWatchAllCall {
c.urlParams_.Set("delimiter", delimiter)
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum number
// of items plus prefixes to return in a single page of responses. As
// duplicate prefixes are omitted, fewer total results may be returned
// than requested. The service will use this parameter or 1,000 items,
// whichever is smaller.
func (c *ObjectsWatchAllCall) MaxResults(maxResults int64) *ObjectsWatchAllCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// PageToken sets the optional parameter "pageToken": A
// previously-returned page token representing part of the larger set of
// results to view.
func (c *ObjectsWatchAllCall) PageToken(pageToken string) *ObjectsWatchAllCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Prefix sets the optional parameter "prefix": Filter results to
// objects whose names begin with this prefix.
func (c *ObjectsWatchAllCall) Prefix(prefix string) *ObjectsWatchAllCall {
c.urlParams_.Set("prefix", prefix)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsWatchAllCall) Projection(projection string) *ObjectsWatchAllCall {
c.urlParams_.Set("projection", projection)
return c
}
// Versions sets the optional parameter "versions": If true, lists all
// versions of an object as distinct results. The default is false. For
// more information, see Object Versioning.
func (c *ObjectsWatchAllCall) Versions(versions bool) *ObjectsWatchAllCall {
c.urlParams_.Set("versions", fmt.Sprint(versions))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsWatchAllCall) Fields(s ...googleapi.Field) *ObjectsWatchAllCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsWatchAllCall) Context(ctx context.Context) *ObjectsWatchAllCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsWatchAllCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsWatchAllCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.channel)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/watch")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.watchAll" call.
// Exactly one of *Channel or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Channel.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsWatchAllCall) Do(opts ...googleapi.CallOption) (*Channel, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Channel{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Watch for changes on all objects in a bucket.",
// "httpMethod": "POST",
// "id": "storage.objects.watchAll",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which to look for objects.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "delimiter": {
// "description": "Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "1000",
// "description": "Maximum number of items plus prefixes to return in a single page of responses. As duplicate prefixes are omitted, fewer total results may be returned than requested. The service will use this parameter or 1,000 items, whichever is smaller.",
// "format": "uint32",
// "location": "query",
// "minimum": "0",
// "type": "integer"
// },
// "pageToken": {
// "description": "A previously-returned page token representing part of the larger set of results to view.",
// "location": "query",
// "type": "string"
// },
// "prefix": {
// "description": "Filter results to objects whose names begin with this prefix.",
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// },
// "versions": {
// "description": "If true, lists all versions of an object as distinct results. The default is false. For more information, see Object Versioning.",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "b/{bucket}/o/watch",
// "request": {
// "$ref": "Channel",
// "parameterName": "resource"
// },
// "response": {
// "$ref": "Channel"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ],
// "supportsSubscription": true
// }
}
| mpl/camlistore | vendor/google.golang.org/api/storage/v1/storage-gen.go | GO | apache-2.0 | 338,935 |
/*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef V8GCController_h
#define V8GCController_h
#include <v8.h>
namespace WebCore {
#ifndef NDEBUG
#define GlobalHandleTypeList(V) \
V(PROXY) \
V(NPOBJECT) \
V(SCHEDULED_ACTION) \
V(EVENT_LISTENER) \
V(NODE_FILTER) \
V(SCRIPTINSTANCE) \
V(SCRIPTVALUE) \
V(DATASOURCE)
// Host information of persistent handles.
enum GlobalHandleType {
#define ENUM(name) name,
GlobalHandleTypeList(ENUM)
#undef ENUM
};
class GlobalHandleInfo {
public:
GlobalHandleInfo(void* host, GlobalHandleType type) : m_host(host), m_type(type) { }
void* m_host;
GlobalHandleType m_type;
};
#endif // NDEBUG
class V8GCController {
public:
#ifndef NDEBUG
// For debugging and leak detection purpose.
static void registerGlobalHandle(GlobalHandleType, void*, v8::Persistent<v8::Value>);
static void unregisterGlobalHandle(void*, v8::Persistent<v8::Value>);
#endif
static void gcPrologue();
static void gcEpilogue();
static void checkMemoryUsage();
private:
// Estimate of current working set.
static int workingSetEstimateMB;
};
}
#endif // V8GCController_h
| mogoweb/webkit_for_android5.1 | webkit/Source/WebCore/bindings/v8/V8GCController.h | C | apache-2.0 | 2,883 |
/* Copyright 2013 10gen 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.
*/
/* global describe, expect, it, mongo */
describe('The const module', function () {
it('stores keycode constants', function () {
var key = mongo.config.keycodes;
expect(key.enter).toBe(13);
expect(key.left).toBe(37);
expect(key.up).toBe(38);
expect(key.right).toBe(39);
expect(key.down).toBe(40);
});
it('stores the keep alive timeout', function () {
expect(mongo.config.keepAliveTime).toBeDefined();
});
it('stores the root element CSS selector', function () {
expect(mongo.config.rootElementSelector).toBeDefined();
});
it('stores the script name', function () {
expect(mongo.config.scriptName).toBeDefined();
});
it('stores the shell batch size', function () {
expect(mongo.config.shellBatchSize).toBeDefined();
});
it('gets and stores the MWS host', function () {
expect(mongo.config.mwsHost).toEqual('http://mwshost.example.com');
});
it('generates and stores the baseUrl', function(){
expect(mongo.config.baseUrl).toBeDefined();
expect(mongo.config.baseUrl.indexOf(mongo.config.mwsHost) > -1).toBe(true);
});
});
| greinerb/mongo-web-shell | frontend/spec/mws/config.spec.js | JavaScript | apache-2.0 | 1,723 |
/* Try writing a file in the most normal way. */
#include <syscall.h>
#include "tests/userprog/sample.inc"
#include "tests/lib.h"
#include "tests/main.h"
void
test_main (void)
{
int handle, byte_cnt;
CHECK (create ("test.txt", sizeof sample - 1), "create \"test.txt\"");
CHECK ((handle = open ("test.txt")) > 1, "open \"test.txt\"");
byte_cnt = write (handle, sample, sizeof sample - 1);
if (byte_cnt != sizeof sample - 1)
fail ("write() returned %d instead of %zu", byte_cnt, sizeof sample - 1);
}
| pindexis/pintos-tn | src/tests/userprog/write-normal.c | C | apache-2.0 | 519 |
package org.wso2.carbon.stratos.common.util;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.stratos.common.config.CloudServiceConfig;
import org.wso2.carbon.stratos.common.config.CloudServicesDescConfig;
import org.wso2.carbon.stratos.common.config.PermissionConfig;
import org.wso2.carbon.stratos.common.constants.StratosConstants;
import org.wso2.carbon.stratos.common.internal.CloudCommonServiceComponent;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
public class CloudServicesUtil {
private static final Log log = LogFactory.getLog(CloudServicesUtil.class);
// TODO protect using Java security
public static void activateAllServices(CloudServicesDescConfig cloudServicesDesc, int tenantId) throws Exception {
java.util.Collection<CloudServiceConfig> cloudServiceConfigList =
cloudServicesDesc.getCloudServiceConfigs().
values();
if (cloudServiceConfigList != null) {
for (CloudServiceConfig cloudServiceConfig : cloudServiceConfigList) {
if (cloudServiceConfig.isDefaultActive()) {
String cloudServiceName = cloudServiceConfig.getName();
try {
if (!CloudServicesUtil.isCloudServiceActive(cloudServiceName, tenantId)) {
CloudServicesUtil.setCloudServiceActive(true,
cloudServiceName,
tenantId,
cloudServicesDesc.getCloudServiceConfigs().
get(cloudServiceName));
}
} catch (Exception e) {
String msg = "Error in activating the cloud service at the tenant" +
"creation. tenant id: " + tenantId + ", service name: " +
cloudServiceName;
log.error(msg, e);
throw new UserStoreException(msg, e);
}
}
}
}
}
public static void activateOriginalAndCompulsoryServices(CloudServicesDescConfig cloudServicesDesc,
String originalService,
int tenantId) throws Exception {
Map<String, CloudServiceConfig> cloudServiceConfigs =
cloudServicesDesc.getCloudServiceConfigs();
if (CloudServicesUtil.isServiceNameValid(cloudServicesDesc, originalService)) {
if (!CloudServicesUtil.isCloudServiceActive(originalService, tenantId)) {
CloudServicesUtil.setCloudServiceActive(true, originalService, tenantId,
cloudServiceConfigs.get(originalService));
log.info("Successfully activated the " + originalService + " for the tenant " +
tenantId);
}
// register the compulsory services
if (!CloudServicesUtil.isCloudServiceActive(StratosConstants.CLOUD_IDENTITY_SERVICE,
tenantId)) {
CloudServicesUtil.setCloudServiceActive(true,
StratosConstants.CLOUD_IDENTITY_SERVICE,
tenantId,
cloudServiceConfigs.get(StratosConstants.CLOUD_IDENTITY_SERVICE));
}
if (!CloudServicesUtil.isCloudServiceActive(StratosConstants.CLOUD_GOVERNANCE_SERVICE,
tenantId)) {
CloudServicesUtil.setCloudServiceActive(true,
StratosConstants.CLOUD_GOVERNANCE_SERVICE,
tenantId,
cloudServiceConfigs.get(StratosConstants.CLOUD_GOVERNANCE_SERVICE));
}
} else {
log.warn("Unable to activate the " + originalService + " for the tenant " + tenantId);
}
}
public static void setCloudServiceActive(boolean active,
String cloudServiceName,
int tenantId, CloudServiceConfig cloudServiceConfig)
throws Exception {
if (cloudServiceConfig.getLabel() == null) {
// for the non-labled services, we are not setting/unsetting the
// service active
return;
}
UserRegistry govRegistry =
CloudCommonServiceComponent.getGovernanceSystemRegistry(
MultitenantConstants.SUPER_TENANT_ID);
UserRegistry configRegistry = CloudCommonServiceComponent.getConfigSystemRegistry(tenantId);
String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
RegistryConstants.PATH_SEPARATOR + tenantId +
RegistryConstants.PATH_SEPARATOR + cloudServiceName;
Resource cloudServiceInfoResource;
if (govRegistry.resourceExists(cloudServiceInfoPath)) {
cloudServiceInfoResource = govRegistry.get(cloudServiceInfoPath);
} else {
cloudServiceInfoResource = govRegistry.newCollection();
}
cloudServiceInfoResource.setProperty(StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY,
active ? "true" : "false");
govRegistry.put(cloudServiceInfoPath, cloudServiceInfoResource);
// then we will copy the permissions
List<PermissionConfig> permissionConfigs = cloudServiceConfig.getPermissionConfigs();
for (PermissionConfig permissionConfig : permissionConfigs) {
String path = permissionConfig.getPath();
String name = permissionConfig.getName();
if (active) {
if (!configRegistry.resourceExists(path)) {
Collection collection = configRegistry.newCollection();
collection.setProperty(StratosConstants.DISPLAY_NAME, name);
configRegistry.put(path, collection);
}
} else {
if (configRegistry.resourceExists(path)) {
configRegistry.delete(path);
}
}
}
}
public static boolean isCloudServiceActive(String cloudServiceName,
int tenantId) throws Exception {
UserRegistry govRegistry = CloudCommonServiceComponent.getGovernanceSystemRegistry(
MultitenantConstants.SUPER_TENANT_ID);
return isCloudServiceActive(cloudServiceName, tenantId, govRegistry);
}
public static boolean isCloudServiceActive(String cloudServiceName,
int tenantId, UserRegistry govRegistry)
throws Exception {
// The cloud manager is always active
if (StratosConstants.CLOUD_MANAGER_SERVICE.equals(cloudServiceName)) {
return true;
}
String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
RegistryConstants.PATH_SEPARATOR + tenantId +
RegistryConstants.PATH_SEPARATOR + cloudServiceName;
Resource cloudServiceInfoResource;
if (govRegistry.resourceExists(cloudServiceInfoPath)) {
cloudServiceInfoResource = govRegistry.get(cloudServiceInfoPath);
String isActiveStr =
cloudServiceInfoResource.getProperty(
StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY);
return "true".equals(isActiveStr);
}
return false;
}
public static boolean isServiceNameValid(CloudServicesDescConfig cloudServicesDesc,
String cloudServiceName) {
if(cloudServiceName == null) {
return false;
}
java.util.Collection<CloudServiceConfig> cloudServiceConfigList =
cloudServicesDesc.getCloudServiceConfigs().values();
if (cloudServiceName.equals(StratosConstants.CLOUD_MANAGER_SERVICE)) {
return false;
}
for (CloudServiceConfig cloudServiceConfig : cloudServiceConfigList) {
if (cloudServiceConfig.getName().equals(cloudServiceName)) {
return true;
}
}
return false;
}
}
| madhawa-gunasekara/carbon-commons | components/tenant-mgt-common/org.wso2.carbon.tenant.common/src/main/java/org/wso2/carbon/stratos/common/util/CloudServicesUtil.java | Java | apache-2.0 | 9,738 |
class A[+T, -U]
val z: A[T, U] forSome {type T <: Int; type U >: Int} = new A[Int, Int]
val o: A[Int, Float] = z
//False | consulo/consulo-scala | testdata/typeConformance/existential/BadLowerUpper.scala | Scala | apache-2.0 | 120 |
/*
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 fake
import (
api "k8s.io/client-go/pkg/api"
unversioned "k8s.io/client-go/pkg/api/unversioned"
v1 "k8s.io/client-go/pkg/api/v1"
labels "k8s.io/client-go/pkg/labels"
watch "k8s.io/client-go/pkg/watch"
testing "k8s.io/client-go/testing"
)
// FakeResourceQuotas implements ResourceQuotaInterface
type FakeResourceQuotas struct {
Fake *FakeCore
ns string
}
var resourcequotasResource = unversioned.GroupVersionResource{Group: "", Version: "v1", Resource: "resourcequotas"}
func (c *FakeResourceQuotas) Create(resourceQuota *v1.ResourceQuota) (result *v1.ResourceQuota, err error) {
obj, err := c.Fake.
Invokes(testing.NewCreateAction(resourcequotasResource, c.ns, resourceQuota), &v1.ResourceQuota{})
if obj == nil {
return nil, err
}
return obj.(*v1.ResourceQuota), err
}
func (c *FakeResourceQuotas) Update(resourceQuota *v1.ResourceQuota) (result *v1.ResourceQuota, err error) {
obj, err := c.Fake.
Invokes(testing.NewUpdateAction(resourcequotasResource, c.ns, resourceQuota), &v1.ResourceQuota{})
if obj == nil {
return nil, err
}
return obj.(*v1.ResourceQuota), err
}
func (c *FakeResourceQuotas) UpdateStatus(resourceQuota *v1.ResourceQuota) (*v1.ResourceQuota, error) {
obj, err := c.Fake.
Invokes(testing.NewUpdateSubresourceAction(resourcequotasResource, "status", c.ns, resourceQuota), &v1.ResourceQuota{})
if obj == nil {
return nil, err
}
return obj.(*v1.ResourceQuota), err
}
func (c *FakeResourceQuotas) Delete(name string, options *v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewDeleteAction(resourcequotasResource, c.ns, name), &v1.ResourceQuota{})
return err
}
func (c *FakeResourceQuotas) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
action := testing.NewDeleteCollectionAction(resourcequotasResource, c.ns, listOptions)
_, err := c.Fake.Invokes(action, &v1.ResourceQuotaList{})
return err
}
func (c *FakeResourceQuotas) Get(name string) (result *v1.ResourceQuota, err error) {
obj, err := c.Fake.
Invokes(testing.NewGetAction(resourcequotasResource, c.ns, name), &v1.ResourceQuota{})
if obj == nil {
return nil, err
}
return obj.(*v1.ResourceQuota), err
}
func (c *FakeResourceQuotas) List(opts v1.ListOptions) (result *v1.ResourceQuotaList, err error) {
obj, err := c.Fake.
Invokes(testing.NewListAction(resourcequotasResource, c.ns, opts), &v1.ResourceQuotaList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &v1.ResourceQuotaList{}
for _, item := range obj.(*v1.ResourceQuotaList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
}
// Watch returns a watch.Interface that watches the requested resourceQuotas.
func (c *FakeResourceQuotas) Watch(opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewWatchAction(resourcequotasResource, c.ns, opts))
}
// Patch applies the patch and returns the patched resourceQuota.
func (c *FakeResourceQuotas) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *v1.ResourceQuota, err error) {
obj, err := c.Fake.
Invokes(testing.NewPatchSubresourceAction(resourcequotasResource, c.ns, name, data, subresources...), &v1.ResourceQuota{})
if obj == nil {
return nil, err
}
return obj.(*v1.ResourceQuota), err
}
| craigyam/amalgam8 | vendor/k8s.io/client-go/kubernetes/typed/core/v1/fake/fake_resourcequota.go | GO | apache-2.0 | 4,021 |
//===- unittest/Support/RemarksAPITest.cpp - C++ API tests ----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/Remarks/Remark.h"
#include "llvm/Remarks/RemarkStringTable.h"
#include "gtest/gtest.h"
using namespace llvm;
TEST(RemarksAPI, Comparison) {
remarks::Remark R;
R.RemarkType = remarks::Type::Missed;
R.PassName = "pass";
R.RemarkName = "name";
R.FunctionName = "func";
R.Loc = remarks::RemarkLocation{"path", 3, 4};
R.Hotness = 5;
R.Args.emplace_back();
R.Args.back().Key = "key";
R.Args.back().Val = "value";
R.Args.emplace_back();
R.Args.back().Key = "keydebug";
R.Args.back().Val = "valuedebug";
R.Args.back().Loc = remarks::RemarkLocation{"argpath", 6, 7};
// Check that == works.
EXPECT_EQ(R, R);
// Check that != works.
remarks::Remark R2 = R.clone();
R2.FunctionName = "func0";
EXPECT_NE(R, R2);
// Check that we iterate through all the arguments.
remarks::Remark R3 = R.clone();
R3.Args.back().Val = "not";
EXPECT_NE(R, R3);
}
TEST(RemarksAPI, Clone) {
remarks::Remark R;
R.RemarkType = remarks::Type::Missed;
R.PassName = "pass";
R.RemarkName = "name";
R.FunctionName = "func";
R.Loc = remarks::RemarkLocation{"path", 3, 4};
R.Hotness = 5;
R.Args.emplace_back();
R.Args.back().Key = "key";
R.Args.back().Val = "value";
R.Args.emplace_back();
R.Args.back().Key = "keydebug";
R.Args.back().Val = "valuedebug";
R.Args.back().Loc = remarks::RemarkLocation{"argpath", 6, 7};
// Check that clone works.
remarks::Remark R2 = R.clone();
EXPECT_EQ(R, R2);
}
TEST(RemarksAPI, ArgsAsMsg) {
remarks::Remark R;
R.RemarkType = remarks::Type::Missed;
R.Args.emplace_back();
R.Args.back().Key = "key";
R.Args.back().Val = "can not do this ";
R.Args.emplace_back();
R.Args.back().Key = "keydebug";
R.Args.back().Val = "because of that.";
R.Args.back().Loc = remarks::RemarkLocation{"argpath", 6, 7};
EXPECT_EQ(R.getArgsAsMsg(), "can not do this because of that.");
}
TEST(RemarksAPI, StringTableInternalize) {
remarks::StringTable StrTab;
// Empty table.
EXPECT_EQ(StrTab.SerializedSize, 0UL);
remarks::Remark R;
R.RemarkType = remarks::Type::Missed;
R.PassName = "pass";
R.RemarkName = "name";
R.FunctionName = "func";
R.Loc = remarks::RemarkLocation{"path", 3, 4};
R.Args.emplace_back();
R.Args.back().Key = "keydebug";
R.Args.back().Val = "valuedebug";
R.Args.back().Loc = remarks::RemarkLocation{"argpath", 6, 7};
// Check that internalize starts using the strings from the string table.
remarks::Remark R2 = R.clone();
StrTab.internalize(R2);
// Check that the pointers in the remarks are different.
EXPECT_NE(R.PassName.data(), R2.PassName.data());
EXPECT_NE(R.RemarkName.data(), R2.RemarkName.data());
EXPECT_NE(R.FunctionName.data(), R2.FunctionName.data());
EXPECT_NE(R.Loc->SourceFilePath.data(), R2.Loc->SourceFilePath.data());
EXPECT_NE(R.Args.back().Key.data(), R2.Args.back().Key.data());
EXPECT_NE(R.Args.back().Val.data(), R2.Args.back().Val.data());
EXPECT_NE(R.Args.back().Loc->SourceFilePath.data(),
R2.Args.back().Loc->SourceFilePath.data());
// Check that the internalized remark is using the pointers from the string table.
EXPECT_EQ(StrTab.add(R.PassName).second.data(), R2.PassName.data());
EXPECT_EQ(StrTab.add(R.RemarkName).second.data(), R2.RemarkName.data());
EXPECT_EQ(StrTab.add(R.FunctionName).second.data(), R2.FunctionName.data());
EXPECT_EQ(StrTab.add(R.Loc->SourceFilePath).second.data(),
R2.Loc->SourceFilePath.data());
EXPECT_EQ(StrTab.add(R.Args.back().Key).second.data(),
R2.Args.back().Key.data());
EXPECT_EQ(StrTab.add(R.Args.back().Val).second.data(),
R2.Args.back().Val.data());
EXPECT_EQ(StrTab.add(R.Args.back().Loc->SourceFilePath).second.data(),
R2.Args.back().Loc->SourceFilePath.data());
}
| GPUOpen-Drivers/llvm | unittests/Remarks/RemarksAPITest.cpp | C++ | apache-2.0 | 4,154 |
<?php
include_once dirname(__FILE__).'/../../bootstrap/unit.php';
class myQuery extends opDoctrineQuery
{
public static $lastQueryCacheHash = '';
public function calculateQueryCacheHash()
{
self::$lastQueryCacheHash = parent::calculateQueryCacheHash();
return self::$lastQueryCacheHash;
}
}
$_app = 'pc_frontend';
$_env = 'test';
$configuration = ProjectConfiguration::getApplicationConfiguration($_app, $_env, true);
new sfDatabaseManager($configuration);
Doctrine_Manager::getInstance()->setAttribute(Doctrine::ATTR_QUERY_CLASS, 'myQuery');
$t = new lime_test(null, new lime_output_color());
// --
$keys = array();
Doctrine::getTable('AdminUser')->find(1);
$keys['find'] = myQuery::$lastQueryCacheHash;
Doctrine::getTable('AdminUser')->findAll();
$keys['find_all'] = myQuery::$lastQueryCacheHash;
Doctrine::getTable('AdminUser')->findById(1);
$keys['find_by_id'] = myQuery::$lastQueryCacheHash;
Doctrine::getTable('AdminUser')->findOneById(1);
$keys['find_one_by_id'] = myQuery::$lastQueryCacheHash;
Doctrine::getTable('AdminUser')->findByIdAndUsername(1, 'admin');
$keys['find_by_id_and_username'] = myQuery::$lastQueryCacheHash;
Doctrine::getTable('AdminUser')->findOneByIdAndUsername(1, 'admin');
$keys['find_one_by_id_and_username'] = myQuery::$lastQueryCacheHash;
Doctrine::getTable('AdminUser')->findByUsernameAndPassword('admin', 'password');
$keys['find_by_username_and_password'] = myQuery::$lastQueryCacheHash;
Doctrine::getTable('AdminUser')->findOneByUsernameAndPassword('admin', 'password');
$keys['find_one_by_username_and_password'] = myQuery::$lastQueryCacheHash;
$t->isnt($keys['find'], $keys['find_all'], '->find() and ->findAll() generates different query cache keys');
$t->isnt($keys['find'], $keys['find_by_id'], '->find() and ->findById() generates different query cache keys');
$t->is($keys['find'], $keys['find_one_by_id'], '->find() and ->findOneById() generates same query cache keys');
$t->isnt($keys['find'], $keys['find_by_id_and_username'], '->find() and ->findByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find'], $keys['find_one_by_id_and_username'], '->find() and ->findOneByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find'], $keys['find_by_username_and_password'], '->find() and ->findByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find'], $keys['find_one_by_username_and_password'], '->find() and ->findOneByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_all'], $keys['find_by_id'], '->findAll() and ->findById() generates different query cache keys');
$t->isnt($keys['find_all'], $keys['find_one_by_id'], '->findAll() and ->findOneById() generates different query cache keys');
$t->isnt($keys['find_all'], $keys['find_by_id_and_username'], '->findAll() and ->findByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find_all'], $keys['find_one_by_id_and_username'], '->findAll() and ->findOneByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find_all'], $keys['find_by_username_and_password'], '->findAll() and ->findByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_all'], $keys['find_one_by_username_and_password'], '->findAll() and ->findOneByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_by_id'], $keys['find_one_by_id'], '->findById() and ->findOneById() generates different query cache keys');
$t->isnt($keys['find_by_id'], $keys['find_by_id_and_username'], '->findById() and ->findByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find_by_id'], $keys['find_one_by_id_and_username'], '->findById() and ->findOneById() generates different query cache keys');
$t->isnt($keys['find_by_id'], $keys['find_by_username_and_password'], '->findById() and ->findByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_by_id'], $keys['find_one_by_username_and_password'], '->findById() and ->findOneByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_one_by_id'], $keys['find_by_id_and_username'], '->findOneById() and ->findByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find_one_by_id'], $keys['find_one_by_id_and_username'], '->findOneById() and ->findOneByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find_one_by_id'], $keys['find_by_username_and_password'], '->findOneById() and ->findByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_one_by_id'], $keys['find_one_by_username_and_password'], '->findOneById() and ->findOneByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_by_id_and_username'], $keys['find_one_by_id_and_username'], '->findByIdAndUsername() and ->findOneByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find_by_id_and_username'], $keys['find_by_username_and_password'], '->findByIdAndUsername() and ->findByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_by_id_and_username'], $keys['find_one_by_username_and_password'], '->findByIdAndUsername() and ->findOneByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_one_by_id_and_username'], $keys['find_by_username_and_password'], '->findOneByIdAndUsername() and ->findByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_one_by_id_and_username'], $keys['find_one_by_username_and_password'], '->findOneByIdAndUsername() and ->findOneByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_by_username_and_password'], $keys['find_one_by_username_and_password'], '->findByUsernameAndPassword() and ->findOneByUsernameAndPassword() generates different query cache keys');
| imamura623/OpenPNE38x_PluginBundledVersion | test/unit/util/opDoctrineQueryTest.php | PHP | apache-2.0 | 5,917 |
cask 'wifispoof' do
version '3.4.3'
sha256 '31465240307e6e2f36f9345c0600489e3458d81922f3a4ded66fe9881503f606'
# sweetpproductions.com/products was verified as official when first introduced to the cask
url "https://sweetpproductions.com/products/wifispoof#{version.major}/WiFiSpoof#{version.major}.dmg"
appcast "https://sweetpproductions.com/products/wifispoof#{version.major}/appcast.xml"
name 'WiFiSpoof'
homepage 'https://wifispoof.com/'
auto_updates true
app 'WiFiSpoof.app'
end
| gyndav/homebrew-cask | Casks/wifispoof.rb | Ruby | bsd-2-clause | 504 |
# -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
| ashawnbandy-te-tfb/FrameworkBenchmarks | frameworks/Python/web2py/app/standard/modules/database.py | Python | bsd-3-clause | 2,330 |
<!DOCTYPE html>
<!--
Copyright (c) 2012 Intel Corporation.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of works must retain the original copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this work without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "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 INTEL CORPORATION 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.
Authors:
Cao, Jun <junx.cao@intel.com>
-->
<html>
<head>
<title>WebGL Test: webglrenderingcontext_RENDERBUFFER_STENCIL_SIZE_exists</title>
<link rel="author" title="Intel" href="http://www.intel.com" />
<link rel="help" href="https://www.khronos.org/registry/webgl/specs/1.0/" />
<meta name="flags" content="" />
<meta name="assert" content="Check if WebGLRenderingContext.RENDERBUFFER_STENCIL_SIZE exists"/>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script src="support/webgl.js"></script>
</head>
<body>
<div id="log"></div>
<canvas id="canvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script>
getwebgl();
webgl_property_exists(webgl, 'RENDERBUFFER_STENCIL_SIZE');
</script>
</body>
</html>
| hgl888/web-testing-service | wts/tests/webgl/webglrenderingcontext_RENDERBUFFER_STENCIL_SIZE_exists.html | HTML | bsd-3-clause | 2,382 |
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* Copyright (C) 2003, 2006, 2009, 2012 Apple Inc. All rights reserved.
*
* 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 library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "core/rendering/RenderApplet.h"
#include "core/frame/UseCounter.h"
#include "core/html/HTMLAppletElement.h"
namespace blink {
RenderApplet::RenderApplet(HTMLAppletElement* applet)
: RenderEmbeddedObject(applet)
{
setInline(true);
UseCounter::count(document(), UseCounter::HTMLAppletElement);
}
RenderApplet::~RenderApplet()
{
}
} // namespace blink
| mxOBS/deb-pkg_trusty_chromium-browser | third_party/WebKit/Source/core/rendering/RenderApplet.cpp | C++ | bsd-3-clause | 1,302 |
<!DOCTYPE html>
<!-- this file is auto-generated. DO NOT EDIT.
/*
** Copyright (c) 2012 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
-->
<html>
<head>
<meta charset="utf-8">
<title>WebGL GLSL conformance test: swizzlers_073_to_080.html</title>
<link rel="stylesheet" href="../../../../resources/js-test-style.css" />
<link rel="stylesheet" href="../../../resources/ogles-tests.css" />
<script src="../../../../resources/js-test-pre.js"></script>
<script src="../../../resources/webgl-test-utils.js"></script>
<script src="../../ogles-utils.js"></script>
</head>
<body>
<canvas id="example" width="500" height="500" style="width: 16px; height: 16px;"></canvas>
<div id="description"></div>
<div id="console"></div>
</body>
<script>
"use strict";
OpenGLESTestRunner.run({
"tests": [
{
"referenceProgram": {
"vertexShader": "../default/default.vert",
"fragmentShader": "../default/default.frag"
},
"model": null,
"testProgram": {
"vertexShader": "../default/default.vert",
"fragmentShader": "vec3_rg_b_1vec2_1float_frag.frag"
},
"name": "vec3_rg_b_1vec2_1float_frag.test.html",
"pattern": "compare"
},
{
"referenceProgram": {
"vertexShader": "../default/default.vert",
"fragmentShader": "../default/default.frag"
},
"model": "grid",
"testProgram": {
"vertexShader": "vec3_rg_b_1vec2_1float_vert.vert",
"fragmentShader": "../default/default.frag"
},
"name": "vec3_rg_b_1vec2_1float_vert.test.html",
"pattern": "compare"
},
{
"referenceProgram": {
"vertexShader": "../default/default.vert",
"fragmentShader": "../default/default.frag"
},
"model": null,
"testProgram": {
"vertexShader": "../default/default.vert",
"fragmentShader": "vec3_rb_g_1vec2_1float_frag.frag"
},
"name": "vec3_rb_g_1vec2_1float_frag.test.html",
"pattern": "compare"
},
{
"referenceProgram": {
"vertexShader": "../default/default.vert",
"fragmentShader": "../default/default.frag"
},
"model": "grid",
"testProgram": {
"vertexShader": "vec3_rb_g_1vec2_1float_vert.vert",
"fragmentShader": "../default/default.frag"
},
"name": "vec3_rb_g_1vec2_1float_vert.test.html",
"pattern": "compare"
},
{
"referenceProgram": {
"vertexShader": "../default/default.vert",
"fragmentShader": "../default/default.frag"
},
"model": null,
"testProgram": {
"vertexShader": "../default/default.vert",
"fragmentShader": "vec3_gb_r_1vec2_1float_frag.frag"
},
"name": "vec3_gb_r_1vec2_1float_frag.test.html",
"pattern": "compare"
},
{
"referenceProgram": {
"vertexShader": "../default/default.vert",
"fragmentShader": "../default/default.frag"
},
"model": "grid",
"testProgram": {
"vertexShader": "vec3_gb_r_1vec2_1float_vert.vert",
"fragmentShader": "../default/default.frag"
},
"name": "vec3_gb_r_1vec2_1float_vert.test.html",
"pattern": "compare"
},
{
"referenceProgram": {
"vertexShader": "../default/default.vert",
"fragmentShader": "../default/default.frag"
},
"model": null,
"testProgram": {
"vertexShader": "../default/default.vert",
"fragmentShader": "vec3_br_g_1vec2_1float_frag.frag"
},
"name": "vec3_br_g_1vec2_1float_frag.test.html",
"pattern": "compare"
},
{
"referenceProgram": {
"vertexShader": "../default/default.vert",
"fragmentShader": "../default/default.frag"
},
"model": "grid",
"testProgram": {
"vertexShader": "vec3_br_g_1vec2_1float_vert.vert",
"fragmentShader": "../default/default.frag"
},
"name": "vec3_br_g_1vec2_1float_vert.test.html",
"pattern": "compare"
}
]
});
var successfullyParsed = true;
</script>
</html>
| crosswalk-project/web-testing-service | wts/tests/webgl/khronos/conformance/ogles/GL/swizzlers/swizzlers_073_to_080.html | HTML | bsd-3-clause | 5,121 |
<!doctype html>
<meta charset="utf-8">
<title>@layer rule parsing / serialization</title>
<link rel="author" title="Emilio Cobos Álvarez" href="mailto:emilio@crisal.io">
<link rel="author" title="Mozilla" href="https://mozilla.org">
<link rel="help" href="https://drafts.csswg.org/css-cascade-5/#layering">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/css/support/parsing-testcommon.js"></script>
<script>
test_valid_rule("@layer A;");
test_valid_rule("@layer A, B, C;");
test_valid_rule("@layer A.A;");
test_valid_rule("@layer A, B.C.D, C;");
test_invalid_rule("@layer;");
test_invalid_rule("@layer A . A;");
test_valid_rule("@layer {\n}");
test_valid_rule("@layer A {\n}");
test_valid_rule("@layer A.B {\n}");
test_invalid_rule("@layer A . B {\n}");
test_invalid_rule("@layer A, B, C {\n}");
</script>
| chromium/chromium | third_party/blink/web_tests/external/wpt/css/css-cascade/parsing/layer.html | HTML | bsd-3-clause | 905 |
// Copyright 2013 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.
#include "ui/compositor/test/test_compositor_host.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/thread_task_runner_handle.h"
#include "ui/compositor/compositor.h"
#include "ui/gfx/geometry/rect.h"
namespace ui {
class TestCompositorHostOzone : public TestCompositorHost {
public:
TestCompositorHostOzone(const gfx::Rect& bounds,
ui::ContextFactory* context_factory);
~TestCompositorHostOzone() override;
private:
// Overridden from TestCompositorHost:
void Show() override;
ui::Compositor* GetCompositor() override;
gfx::Rect bounds_;
ui::ContextFactory* context_factory_;
scoped_ptr<ui::Compositor> compositor_;
DISALLOW_COPY_AND_ASSIGN(TestCompositorHostOzone);
};
TestCompositorHostOzone::TestCompositorHostOzone(
const gfx::Rect& bounds,
ui::ContextFactory* context_factory)
: bounds_(bounds),
context_factory_(context_factory) {}
TestCompositorHostOzone::~TestCompositorHostOzone() {}
void TestCompositorHostOzone::Show() {
// Ozone should rightly have a backing native framebuffer
// An in-memory array draw into by OSMesa is a reasonble
// fascimile of a dumb framebuffer at present.
// GLSurface will allocate the array so long as it is provided
// with a non-0 widget.
// TODO(rjkroege): Use a "real" ozone widget when it is
// available: http://crbug.com/255128
compositor_.reset(new ui::Compositor(1,
context_factory_,
base::ThreadTaskRunnerHandle::Get()));
compositor_->SetScaleAndSize(1.0f, bounds_.size());
}
ui::Compositor* TestCompositorHostOzone::GetCompositor() {
return compositor_.get();
}
// static
TestCompositorHost* TestCompositorHost::Create(
const gfx::Rect& bounds,
ui::ContextFactory* context_factory) {
return new TestCompositorHostOzone(bounds, context_factory);
}
} // namespace ui
| ltilve/chromium | ui/compositor/test/test_compositor_host_ozone.cc | C++ | bsd-3-clause | 2,222 |
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
// This file relies on the fact that the following declaration has been made
// in runtime.js:
// var $Array = global.Array;
// -------------------------------------------------------------------
// Proposed for ES7
// https://github.com/tc39/Array.prototype.includes
// 6e3b78c927aeda20b9d40e81303f9d44596cd904
function ArrayIncludes(searchElement, fromIndex) {
var array = ToObject(this);
var len = ToLength(array.length);
if (len === 0) {
return false;
}
var n = ToInteger(fromIndex);
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {
k = 0;
}
}
while (k < len) {
var elementK = array[k];
if (SameValueZero(searchElement, elementK)) {
return true;
}
++k;
}
return false;
}
// -------------------------------------------------------------------
function HarmonyArrayIncludesExtendArrayPrototype() {
%CheckIsBootstrapping();
%FunctionSetLength(ArrayIncludes, 1);
// Set up the non-enumerable functions on the Array prototype object.
InstallFunctions($Array.prototype, DONT_ENUM, $Array(
"includes", ArrayIncludes
));
}
HarmonyArrayIncludesExtendArrayPrototype();
| sgraham/nope | v8/src/harmony-array-includes.js | JavaScript | bsd-3-clause | 1,359 |
<!--
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
Copyright (c) Microsoft Corporation. All rights reserved
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>News</title>
<!-- WinJS references -->
<link href="/Microsoft.WinJS.4.0/css/ui-dark.css" rel="stylesheet" />
<script src="/Microsoft.WinJS.4.0/js/WinJS.js"></script>
<link href="/css/default.css" rel="stylesheet" />
<link href="/pages/news/news.css" rel="stylesheet" />
<script src="/pages/news/news.js"></script>
</head>
<body>
<!-- Template for the feed header -->
<div id="feedHeaderTemplate" data-win-control="WinJS.Binding.Template" data-win-options="{extractChild: true}">
<button class="group-header win-type-x-large win-type-interactive" data-win-bind="groupKey: key" role="link">
<span class="group-title win-type-x-large win-type-ellipsis" data-win-bind="innerText: title;" ></span>
<span class="group-chevron"></span>
</button>
</div>
<!-- Template for the image article item -->
<div id="imageArticleTemplate" data-win-control="WinJS.Binding.Template" data-win-options="{extractChild: true}">
<div data-win-bind="className: tileType">
<div class="image" data-win-bind="style.background: imageBackground"></div>
<div class="overlay">
<h4 class="title" data-win-bind="innerText: title"></h4>
</div>
</div>
</div>
<!-- Template for the text article item -->
<div id="textArticleTemplate" data-win-control="WinJS.Binding.Template" data-win-options="{extractChild: true}">
<div data-win-bind="className: tileType">
<h2 class="title" data-win-bind="innerText: title"></h2>
</div>
</div>
<!-- Template for feed error -->
<div id="errorTemplate" data-win-control="WinJS.Binding.Template">
<div data-win-bind="className: tileType">
<h2 class="error" data-win-bind="innerText: error"></h2>
</div>
</div>
<!-- Template for the feed item -->
<div id="feedTileTemplate" data-win-control="WinJS.Binding.Template" data-win-options="{extractChild: true}">
<div class="feedTile">
<h2 class="title" data-win-bind="innerText: title"></h2>
</div>
</div>
<!-- The content that will be loaded and displayed. -->
<div id="news" class="fragment">
<header aria-label="Header content" role="banner">
<h1 class="titlearea win-type-ellipsis">
<span class="pagetitle">News</span>
</h1>
</header>
<section aria-label="Main content" role="main">
<div id="errorDiv"></div>
<div id="articlesListViewArea" data-win-control="WinJS.UI.SemanticZoom">
<!-- The control that provides the zoomed-in view. -->
<div id="articlesListView-in" aria-label="List of articles" data-win-control="WinJS.UI.ListView" data-win-options="{ selectionMode: 'none' }"></div>
<!-- The control that provides the zoomed-out view. -->
<div id="articlesListView-out" aria-label="List of feeds" data-win-control="WinJS.UI.ListView"
data-win-options="{ selectionMode: 'none', tapBehavior: 'invokeOnly' }">
</div>
</div>
</section>
</div>
</body>
</html>
| gforguru/Windows-universal-samples | FeedReader/js/pages/news/news.html | HTML | mit | 3,590 |
<!DOCTYPE html>
<!--
#######################################
- THE HEAD PART -
######################################
-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>SLIDER REVOLUTION - The Responsive Slider jQuery Plugin</title>
<link rel="icon" type="image/png" href="images/sitelogo.png" />
<!-- commented, remove this line to use IE & iOS favicons -->
<link rel="shortcut icon" href="images/favicon.ico" />
<!-- get jQuery from the google apis -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.js?ver=3.4.2'></script>
<!-- CSS STYLE -->
<link rel="stylesheet" type="text/css" href="css/style.css" media="screen" />
<link rel="stylesheet" type="text/css" href="css/preview.css" media="screen" />
<!-- jQuery KenBurn Slider -->
<script type="text/javascript" src="rs-plugin/js/jquery.themepunch.plugins.min.js"></script>
<script type="text/javascript" src="rs-plugin/js/jquery.themepunch.revolution.min.js"></script>
<!-- MODULES ONLY FOR THE DEMONSTATION -->
<script type="text/javascript" src="previewjs/preview-normal.js"></script>
<!-- REVOLUTION BANNER CSS SETTINGS -->
<link rel="stylesheet" type="text/css" href="rs-plugin/css/settings.css" media="screen" />
<link rel="stylesheet" type="text/css" href="rs-plugin/css/captions.css" media="screen" />
<!-- GOOGLE FONTS -->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,800,300,600' rel='stylesheet' type='text/css'>
</head>
<!--
#######################################
- THE BODY PART -
######################################
-->
<body class="body-dark">
<!--
<div id="debug" style="position:fixed; top:10px; left:10px; background:#000; color:#efefef; width:100px; height:100px;z-index:10000;"></div>
-->
<div class="header">
<!-- LOGO AND BUY BUTTON -->
<div class="left">
<div class="logo"></div>
</div>
<div class="right">
<a href="http://codecanyon.net/item/slider-revolution-responsive-jquery-plugin/2580848"><div class="purchase"><div class="purchase-inside">BUY NOW <strong>FOR $15</strong></div></div></a>
</div>
<div class="clear"></div>
<div class="divider"></div>
<!-- MENU -->
<div class="menu">
<div class="left">
<a class="menupoint red"href="index.html">RESPONSIVE</a>
<a class="menupoint"href="index-fullwidth.html">FULL-WIDTH</a>
<a class="menupoint"href="index-static.html">FIXED</a>
</div>
<div class="right">
<a class="menupoint red"href="index.html">HOW TO GET STARTED?</a>
</div>
<div class="clear"></div>
</div>
<div class="divider"></div>
</div>
<div class="space30"></div>
<!--
#################################
- THEMEPUNCH BANNER -
#################################
-->
<div class="bannercontainer responsive">
<div class="banner">
<ul>
<!-- THE FIRST SLIDE -->
<li data-transition="3dcurtain-vertical" data-slotamount="10" data-masterspeed="300" data-thumb="images/thumbs/thumb1.jpg">
<!-- THE MAIN IMAGE IN THE SLIDE -->
<img src="images/slides/slide13.jpg" >
<!-- THE CAPTIONS OF THE FIRST SLIDE -->
<div class="caption large_text sfb"
data-x="44"
data-y="47"
data-speed="300"
data-start="800"
data-easing="easeOutExpo" >OVER <span style="color: #ffcc00;">1000</span> SATISFIED CUSTOMERS</div>
<div class="caption randomrotate"
data-x="48"
data-y="131"
data-speed="600"
data-start="1100"
data-easing="easeOutExpo" ><img src="images/slides/p1.jpg" alt="Image 2"></div>
<div class="caption randomrotate"
data-x="90"
data-y="206"
data-speed="600"
data-start="1200"
data-easing="easeOutExpo" ><img src="images/slides/p2.jpg" alt="Image 3"></div>
<div class="caption randomrotate"
data-x="205"
data-y="140"
data-speed="600"
data-start="1300"
data-easing="easeOutExpo" ><img src="images/slides/p3.jpg" alt="Image 4"></div>
<div class="caption randomrotate"
data-x="188"
data-y="246"
data-speed="300"
data-start="1400"
data-easing="easeOutExpo" ><img src="images/slides/p4.jpg" alt="Image 5"></div>
<div class="caption randomrotate"
data-x="55"
data-y="316"
data-speed="600"
data-start="1500"
data-easing="easeOutExpo" ><img src="images/slides/p5.jpg" alt="Image 6"></div>
<div class="caption randomrotate"
data-x="173"
data-y="329"
data-speed="300"
data-start="1600"
data-easing="easeOutExpo" ><img src="images/slides/p6.jpg" alt="Image 7"></div>
<div class="caption randomrotate"
data-x="255"
data-y="294"
data-speed="300"
data-start="1700"
data-easing="easeOutExpo" ><img src="images/slides/p7.jpg" alt="Image 8"></div>
<div class="caption randomrotate"
data-x="275"
data-y="166"
data-speed="300"
data-start="1800"
data-easing="easeOutExpo" ><img src="images/slides/p8.jpg" alt="Image 9"></div>
<div class="caption randomrotate"
data-x="84"
data-y="113"
data-speed="300"
data-start="1900"
data-easing="easeOutExpo" ><img src="images/slides/p9.jpg" alt="Image 10"></div>
<div class="caption randomrotate"
data-x="26"
data-y="225"
data-speed="300"
data-start="2000"
data-easing="easeOutExpo" ><img src="images/slides/p10.jpg" alt="Image 11"></div>
<div class="caption randomrotate"
data-x="110"
data-y="187"
data-speed="300"
data-start="2100"
data-easing="easeOutExpo" ><img src="images/slides/p11.jpg" alt="Image 12"></div>
<div class="caption randomrotate"
data-x="183"
data-y="221"
data-speed="300"
data-start="2200"
data-easing="easeOutExpo" ><img src="images/slides/p12.jpg" alt="Image 13"></div>
</li>
<!-- THE SECOND SLIDE -->
<li data-transition="papercut" data-slotamount="15" data-masterspeed="300" data-delay="9400" data-thumb="images/thumbs/thumb2.jpg">
<img src="images/slides/slide21.jpg" >
<div class="caption very_big_white lfl stl"
data-x="18"
data-y="293"
data-speed="300"
data-start="500"
data-easing="easeOutExpo" data-end="8800" data-endspeed="300" data-endeasing="easeInSine" >TIMELINED CAPTIONS</div>
<div class="caption big_white lfl stl"
data-x="18"
data-y="333"
data-speed="300"
data-start="800"
data-easing="easeOutExpo" data-end="9100" data-endspeed="300" data-endeasing="easeInSine" >MOVE CAPTIONS IN AND OUT ON ONE SLIDE</div>
<div class="caption lft ltb"
data-x="500"
data-y="0"
data-speed="600"
data-start="1100"
data-easing="easeOutExpo" data-end="3100" data-endspeed="600" data-endeasing="easeInSine" ><img src="images/slides/drink1.jpg" alt="Image 3"></div>
<div class="caption bold_red_text sft stb"
data-x="720"
data-y="290"
data-speed="300"
data-start="1400"
data-easing="easeOutExpo" data-end="3300" data-endspeed="300" data-endeasing="easeInSine" >STRAWBERRY COCTAIL</div>
<div class="caption big_black sfb stb"
data-x="720"
data-y="320"
data-speed="300"
data-start="1700"
data-easing="easeOutExpo" data-end="3200" data-endspeed="300" data-endeasing="easeInSine" >$ 7.49</div>
<div class="caption lft ltb"
data-x="500"
data-y="0"
data-speed="600"
data-start="3600"
data-easing="easeOutExpo" data-end="5600" data-endspeed="600" data-endeasing="easeInSine" ><img src="images/slides/drink2.jpg" alt="Image 6"></div>
<div class="caption bold_brown_text sft stb"
data-x="720"
data-y="290"
data-speed="300"
data-start="3900"
data-easing="easeOutExpo" data-end="5800" data-endspeed="300" data-endeasing="easeInSine" >COKE & RUM</div>
<div class="caption big_black sfb stb"
data-x="720"
data-y="320"
data-speed="300"
data-start="4200"
data-easing="easeOutExpo" data-end="5700" data-endspeed="300" data-endeasing="easeInSine" >$ 5.99</div>
<div class="caption lft ltb"
data-x="500"
data-y="0"
data-speed="600"
data-start="6100"
data-easing="easeOutExpo" data-end="8100" data-endspeed="300" data-endeasing="easeInSine" ><img src="images/slides/drink3.jpg" alt="Image 9"></div>
<div class="caption bold_green_text sft stb"
data-x="720"
data-y="290"
data-speed="300"
data-start="6400"
data-easing="easeOutExpo" data-end="8300" data-endspeed="300" data-endeasing="easeInSine" >MOJITO COCTAIL</div>
<div class="caption big_black sfb stb"
data-x="720"
data-y="320"
data-speed="300"
data-start="6700"
data-easing="easeOutExpo" data-end="8200" data-endspeed="300" data-endeasing="easeInSine" >$ 6.79</div>
</li>
<li data-transition="turnoff" data-slotamount="1" data-masterspeed="300" >
<img src="images/slides/slide31.jpg" >
<div class="caption large_text fade"
data-x="509"
data-y="290"
data-speed="300"
data-start="800"
data-easing="easeOutExpo" ></div>
<div class="caption very_large_black_text randomrotate"
data-x="641"
data-y="95"
data-speed="300"
data-start="1100"
data-easing="easeOutExpo" >SLIDER</div>
<div class="caption large_black_text randomrotate"
data-x="642"
data-y="161"
data-speed="300"
data-start="1400"
data-easing="easeOutExpo" >REVOLUTION</div>
<div class="caption bold_red_text randomrotate"
data-x="645"
data-y="201"
data-speed="300"
data-start="1700"
data-easing="easeOutExpo" >GOT FULLSCREEN VIDEO</div>
<div class="caption sfb"
data-x="640"
data-y="223"
data-speed="300"
data-start="2000"
data-easing="easeOutBack" ><img src="images/slides/video.jpg" alt="Image 7"></div>
<div class="caption sft"
data-x="639"
data-y="383"
data-speed="300"
data-start="2300"
data-easing="easeOutExpo" data-linktoslide="4" ><img src="images/slides/videobutton.jpg" alt="Image 8"></div>
</li>
<!-- THE THIRD SLIDE -->
<li data-transition="slidedown" data-slotamount="7" data-masterspeed="300" data-thumb="images/thumbs/thumb4.jpg">
<img src="images/slides/black.jpg" >
<div class="caption fade fullscreenvideo" data-autoplay="false" data-x="0" data-y="0" data-speed="500" data-start="10" data-easing="easeOutBack"><iframe src="http://player.vimeo.com/video/22775048?title=0&byline=0&portrait=0;api=1" width="100%" height="100%"></iframe></div>
<div class="caption big_white sft stt"
data-x="327"
data-y="25"
data-speed="300"
data-start="500"
data-easing="easeOutExpo" data-end="4000" data-endspeed="300" data-endeasing="easeInSine" >Have Fun Watching the Video</div>
</li>
<!-- THE FOURTH SLIDE -->
<li data-transition="slideleft" data-slotamount="1" data-masterspeed="300" data-thumb="images/thumbs/thumb5.jpg">
<img src="images/slides/slide4.jpg" >
<div class="caption large_text sft"
data-x="50"
data-y="44"
data-speed="300"
data-start="800"
data-easing="easeOutExpo" >TOUCH ENABLED</div>
<div class="caption medium_text sfl"
data-x="79"
data-y="82"
data-speed="300"
data-start="1100"
data-easing="easeOutExpo" >AND</div>
<div class="caption large_text sfr"
data-x="128"
data-y="78"
data-speed="300"
data-start="1100"
data-easing="easeOutExpo" ><span style="color: #ffc600;">RESPONSIVE</span></div>
<div class="caption lfl"
data-x="53"
data-y="192"
data-speed="300"
data-start="1400"
data-easing="easeOutExpo" ><img src="images/slides/imac.png" alt="Image 4"></div>
<div class="caption lfl"
data-x="253"
data-y="282"
data-speed="300"
data-start="1500"
data-easing="easeOutExpo" ><img src="images/slides/ipad.png" alt="Image 5"></div>
<div class="caption lfl"
data-x="322"
data-y="313"
data-speed="300"
data-start="1600"
data-easing="easeOutExpo" ><img src="images/slides/iphone.png" alt="Image 6"></div>
</li>
<!-- THE FIFTH SLIDE -->
<li data-transition="flyin" data-slotamount="1" data-masterspeed="300" data-thumb="images/thumbs/thumb6.jpg">
<img src="images/slides/slide51.jpg" >
<div class="caption large_text sfl"
data-x="38"
data-y="200"
data-speed="300"
data-start="1000"
data-easing="easeOutExpo" >A Happy</div>
<div class="caption large_text sfl"
data-x="37"
data-y="243"
data-speed="300"
data-start="1300"
data-easing="easeOutExpo" >Holiday Season</div>
<div class="caption randomrotate"
data-x="610"
data-y="174"
data-speed="800"
data-start="1600"
data-easing="easeOutExpo" ><img src="images/slides/TP_logo.png" alt="Image 4"></div>
</li>
</ul>
<div class="tp-bannertimer"></div>
</div>
</div>
<div id="unvisible_button"></div>
<div class="space30"></div>
<div class="configurator">
<!-- THE 1ST CONFIG FIELD -- TRANSITIONS -->
<div class="one_third">
<table>
<tbody>
<tr>
<td class="config_title">1</td>
<td class="divider"></td>
</tr>
</tbody>
</table>
<div class="space15"></div>
<div class="conftitle">TRANSITION <span>(TAKES IMMEDIATE EFFECT)</span></div>
<div class="selecter">
<div class="dropdown">
<div class="dropcontent">Select a Transition Type</div>
<div class="dropbutton"></div>
<div class="clear"></div>
</div>
<select class="selecttransition">
<option value="Demo">ORIGINAL PREVIEW</option>
<option value="random"> Random Transitions</option>
<option value="random-standard">STANDARD</option>
<option value="boxslide"> Box Mask</option>
<option value="boxfade"> Box Mask Mosaic</option>
<option value="slotzoom-horizontal"> Slot Zoom Horizontal</option>
<option value="slotslide-horizontal"> Slot Slide Horizontal</option>
<option value="slotfade-horizontal"> Slot Fade Horizontal</option>
<option value="slotzoom-vertical"> Slot Zoom Vertical</option>
<option value="slotslide-vertical"> Slot Slide Vertical</option>
<option value="slotfade-vertical"> Slot Fade Vertical</option>
<option value="curtain-1"> Curtain One</option>
<option value="curtain-2"> Curtain Two</option>
<option value="curtain-3"> Curtain Three</option>
<option value="slideleft"> Slide Left</option>
<option value="slideright"> Slide Right</option>
<option value="slideup"> Slide Up</option>
<option value="slidedown"> Slide Down</option>
<option value="fade"> Fade</option>
<option value="random-premium">PREMIUM</option>
<option value="flyin"> Fly In</option>
<option value="cubic"> Cubic</option>
<option value="turnoff"> Turn Off</option>
<option value="3dcurtain-horizontal"> 3D Curtain Horizontal</option>
<option value="3dcurtain-vertical"> 3D Curtain Vertical</option>
<option value="papercut"> Paper Cut</option>
</select>
</div>
</div>
<!-- THE 2ND CONFIG FIELD -- ROTATOR -->
<div class="one_third">
<table>
<tbody>
<tr>
<td class="config_title">2</td>
<td class="divider"></td>
</tr>
</tbody>
</table>
<div class="space15"></div>
<div class="rotbutcont">
<div style="float:left">
<div class="rotator"><div class="rotator-line"></div></div>
</div>
<div style="float:left">
<div class="conftitle">ROTATION <span>(SIMPLE TRANSITIONS)</span></div>
<div class="rotatefield inputfield">0 degrees</div>
</div>
<div class="clear"></div>
</div>
</div>
<!-- THE 3thd CONFIG FIELD -- SLOT AMOUNT -->
<div class="one_third last">
<table>
<tbody>
<tr>
<td class="config_title">3</td>
<td class="divider"></td>
</tr>
</tbody>
</table>
<div class="space15"></div>
<div class="conftitle">SLOT AMOUNT <span>(USED IN TRANSITIONS)</span></div>
<div class="pmbutcont">
<div class="slotamount inputfield" style="float:left;margin-right:5px;width:130px;">Pre Defined Slots</div>
<div class="slot plus"></div><div class="slot minus"></div>
<div class="clear"></div>
</div>
</div>
<div class="clear"></div>
<div class="space10"></div>
<table>
<tbody>
<tr>
<td class="config_title">4</td>
<td class="divider"></td>
</tr>
</tbody>
</table>
<!-- THE 4th CONFIGS WITH THREE DROP DOWN LISTS -->
<div class="one_third">
<div class="space15"></div>
<div class="conftitle">NAVIGATION STYLE</div>
<div class="selecter">
<div class="dropdown">
<div class="dropcontent">Select a Navigation Style</div>
<div class="dropbutton"></div>
<div class="clear"></div>
</div>
<select class="selectnavstyle dselect">
<option value="round">Round Bullets</option>
<option value="navbar">NavBar with Bullets</option>
<option value="round-old">Round Bullets (old version)</option>
<option value="square-old">Square Bullets (old version)</option>
<option value="navbar-old">NavBar with Bullets (old version)</option>
</select>
</div>
</div>
<div class="one_third">
<div class="space15"></div>
<div class="conftitle">NAVIGATION ARROWS</div>
<div class="selecter">
<div class="dropdown">
<div class="dropcontent">Select Position of Arrows</div>
<div class="dropbutton"></div>
<div class="clear"></div>
</div>
<select class="selectnavarrows dselect">
<option value="verticalcentered">Vertical Centered</option>
<option value="nexttobullets">Next to Bullets</option>
<option value="none">Hide Arrows</option>
</select>
</div>
</div>
<div class="one_third last">
<div class="space15"></div>
<div class="conftitle">NAVIGATION THUMBS</div>
<div class="selecter">
<div class="dropdown">
<div class="dropcontent">Select Navigation Type</div>
<div class="dropbutton"></div>
<div class="clear"></div>
</div>
<select class="selectnavtype dselect">
<option value="bullet">Bullets</option>
<option value="thumb">Thumbnails</option>
<option value="none">No Navigation</option>
</select>
</select>
</div>
</div>
<div class="clear"></div>
<div style="width:100%;height:75px;"></div>
<!-- What Else do we have ? -->
<table>
<tbody>
<tr>
<td class="config_title small">What else can you set ?</td>
<td class="divider small"></td>
</tr>
</tbody>
</table>
<div class="space15"></div>
<div class="one_third">
<div class="infofield">
<ul>
<li>Change <span>Speed of Transitions</span></li>
<li>Set <span>Countdown time per slide</span> and/or Global</li>
<li>Turn on / off <span>Visibility of Countdown</span></li>
<li>Set the <span>Position of Contdown</span></li>
<li>Set per slide <span>Link and Target</span></li>
<li>Add <span>Unlimited</span> amount of <span>Captions</span></li>
<li>Set <span>Start time and speed</span> of Captions</li>
<li>Set <span>End time and speed</span> of Captions</li>
</ul>
</div>
</div>
<div class="one_third">
<div class="infofield">
<ul>
<li>Set different<span>End and Start Transitions</span> of Captions</li>
<li><span>Randomrotate, slide, fade</span> Caption Transitions</li>
<li>Turn on/off <span>Hiding Navigation</span> and set delay</li>
<li>Set <span>link</span> per Captions</li>
<li>Add <span>YouTube and Vimeo</span> Captions</li>
<li>Set <span>Fullscreen</span> YouTube and Vimeo Videos</li>
<li>Set <span>AutoStart</span> for Videos</li>
<li>Video Playback stops Countdown</li>
</ul>
</div>
</div>
<div class="one_third last">
<div class="infofield">
<ul>
<li>Turn on/off <span>Hover functions</span></li>
<li>Set <span>Size and Amount</span> of visible Thumbs</li>
<li>Turn on / off <span>Touch</span> functions</li>
<li>Choose between 3 different <span>Shadows</span></li>
<li>Use <span>Api</span> to stop, play, swap slides, and many more.</li>
<li>Set <span>FullWidth</span>,<span>Responsive</span> or <span>Static</span> size.</li>
<li>Turn on/off <span>on Hover Stop</span> function</li>
<li>Option to <span>Link within the slides</span> via Captions</li>
</ul>
</div>
</div>
<div class="clear"></div>
<div style="width:100%;height:60px;"></div>
<!-- SOME INFORMATIONS HERE -->
<table>
<tbody>
<tr>
<td class="config_title small">Why Use Slider Revolution</td>
<td class="divider small"></td>
</tr>
</tbody>
</table>
<div class="space15"></div>
<div class="infofield">
<span>With an abundance of sliders and banner rotators available on the web, why exactly should you chose Slider Revolution over other products?</span><br>Slider Revolution is a fully developed slide displaying system offering the capability to show images, videos and captions paired with simple, modern and fancy 3D transitions. On top of that, Slider Revolution is fully responsive and mobile optimized and can take on any dimensions.
</div>
<div style="width:100%;height:60px;"></div>
<!-- SOME INFORMATIONS HERE -->
<table>
<tbody>
<tr>
<td class="config_title small">Slider Compatibility</td>
<td class="divider small"></td>
</tr>
</tbody>
</table>
<table class="features">
<tbody>
<tr class="titles">
<td></td>
<td>BASIC SLIDER FEATURES</td>
<td>SIMPLE TRANSITIONS</td>
<td>PREMIUM TRANSITIONS</td>
<td>ROTATION</td>
</tr>
<tr>
<td>FIREFOX<span> 10+</span></td>
<td><div class="yo"></div></td>
<td><div class="yo"></div></td>
<td><div class="yo"></div></td>
<td><div class="yo"></div></td>
</tr>
<tr>
<td>WEBKIT<br><span> CHROME,SAFARI,OPERA</td>
<td><div class="yo"></div></td>
<td><div class="yo"></div></td>
<td><div class="yo"></div></td>
<td><div class="yo"></div></td>
</tr>
<tr>
<td>IE9</td>
<td><div class="yo"></div></td>
<td><div class="yo"></div></td>
<td><div class="nop"></div></td>
<td><div class="nop"></div></td>
</tr>
<tr>
<td>IE7 + 8</td>
<td><div class="yo"></div></td>
<td><div class="yo"></div></td>
<td><div class="nop"></div></td>
<td><div class="nop"></div></td>
</tr>
</tbody>
</table>
<div style="width:100%;height:60px;"></div>
<!-- SOME INFORMATIONS HERE -->
<table>
<tbody>
<tr>
<td class="config_title small">Testimonials</td>
<td class="divider small"></td>
</tr>
</tbody>
</table>
<div class="space15"></div>
<div class="slogan">Over 1000+ happy buyers can‘t be wrong!</div>
<div class="space40"></div>
<div class="testimonials">
<span>Nicolas-Gilles</span> says:<br>
<i>Just to let my testimony of appreciation for the support. Efficiency and speed ! 5/5<br>Good Work<br>Nicolas-Gilles</i>
</div>
<div class="testimonials">
<span>rhj123456</span> says:<br>
<i>Wow, you did a really great job on this. I have a whole slider built without looking at the docs. I love that.<br>Nice work!!!.</i>
</div>
<div class="testimonials">
<span>tverdouw</span> says:<br>
<i>Awesome slider, with awesome options. Thanks!</i>
</div>
<div class="testimonials">
<span>dervish01</span> says:<br>
<i>Hi just purchased the plugin and I have to say a great plugin.<br>You can see it at www.acornwebstudio.co.uk<br>really makes websites look great.<br>THANKS .</i>
</div>
<div class="testimonials">
<span>themesplugins</span> says:<br>
<i>We selected your plugin as Top 100 Plugins for WordPress.</i>
</div>
<div class="testimonials">
<span>sailo</span> says:<br>
<i>Perfect, thanks themepunch </i>
</div>
</div> <!-- END OF CONFIGURATOR -->
<div style="width:100%;height:60px;"></div>
<script>
var api;
jQuery(document).ready(function() {
api = jQuery('.banner').revolution(
{
delay:5000,
startheight:500,
startwidth:960,
hideThumbs:300,
thumbWidth:100, // Thumb With and Height and Amount (only if navigation Tyope set to thumb !)
thumbHeight:50,
thumbAmount:5,
navigationType:"bullet", // bullet, thumb, none
navigationArrows:"nexttobullets", // nexttobullets, solo (old name verticalcentered), none
navigationStyle:"round", // round,square,navbar,round-old,square-old,navbar-old, or any from the list in the docu (choose between 50+ different item), custom
navigationHAlign:"center", // Vertical Align top,center,bottom
navigationVAlign:"bottom", // Horizontal Align left,center,right
navigationHOffset:0,
navigationVOffset:20,
soloArrowLeftHalign:"left",
soloArrowLeftValign:"center",
soloArrowLeftHOffset:20,
soloArrowLeftVOffset:0,
soloArrowRightHalign:"right",
soloArrowRightValign:"center",
soloArrowRightHOffset:20,
soloArrowRightVOffset:0,
touchenabled:"on", // Enable Swipe Function : on/off
onHoverStop:"on", // Stop Banner Timet at Hover on Slide on/off
stopAtSlide:-1,
stopAfterLoops:-1,
shadow:1, //0 = no Shadow, 1,2,3 = 3 Different Art of Shadows (No Shadow in Fullwidth Version !)
fullWidth:"off" // Turns On or Off the Fullwidth Image Centering in FullWidth Modus
});
});
</script>
</body>
</html>
| EssamKhaled/es-blog | web/bundles/layout/Frontend/assets/plugins/revolution_slider/index.html | HTML | mit | 30,077 |
<!DOCTYPE html>
<html>
<head>
<title>Use resetView to reset the header width</title>
<meta charset="utf-8">
<link rel="stylesheet" href="../assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="../assets/bootstrap-table/src/bootstrap-table.css">
<link rel="stylesheet" href="../assets/examples.css">
<script src="../assets/jquery.min.js"></script>
<script src="../assets/bootstrap/js/bootstrap.min.js"></script>
<script src="../assets/bootstrap-table/src/bootstrap-table.js"></script>
<script src="../ga.js"></script>
<style>
.div-table {
/*display: table;*/
border: 1px solid #ccc;
}
.cell-left {
/*display: table-cell;*/
float: left;
width:80%;
}
.cell-right {
/*display: table-cell;*/
float: right;
width:20%;
}
</style>
</head>
<body>
<div class="container">
<h1>Use resetView to reset the header width(<a href="https://github.com/wenzhixin/bootstrap-table/issues/283" target="_blank">#283</a>).</h1>
<p>
<button id="b" type="button" class="btn btn-default">Larger</button>
<button id="s" type="button" class="btn btn-default">Smaller</button>
</p>
<div id="d" class="div-table">
<div class="cell-left">
<table id="table" data-height="500"></table>
</div>
<div class="cell-right">
RRR
</div>
<div class="clearfix"></div>
</div>
</div>
<script>
var $table = $('#table');
$(function () {
buildTable($('#table'), 10, 50);
var $d = $('#d');
var width = $d.width();
$('#b').click(function(){
width = width + 100;
$d.css('width', width + 'px');
$('#table').bootstrapTable('resetView');
});
$('#s').click(function(){
width = width - 100;
$d.css('width', width + 'px');
$('#table').bootstrapTable('resetView');
});
});
function buildTable($el, cells, rows) {
var i, j, row,
columns = [],
data = [];
for (i = 0; i < cells; i++) {
columns.push({
field: 'field' + i,
title: 'Cell' + i
});
}
for (i = 0; i < rows; i++) {
row = {};
for (j = 0; j < cells; j++) {
row['field' + j] = 'Row-' + i + '-' + j;
}
data.push(row);
}
$el.bootstrapTable('destroy').bootstrapTable({
columns: columns,
data: data
});
}
</script>
</body>
</html> | weidongwanga/framework | static/bootstrap/issues/283.html | HTML | mit | 2,773 |
/*
LumX v1.5.14
(c) 2014-2017 LumApps http://ui.lumapps.com
License: MIT
*/
(function()
{
'use strict';
angular.module('lumx.utils.depth', []);
angular.module('lumx.utils.event-scheduler', []);
angular.module('lumx.utils.transclude-replace', []);
angular.module('lumx.utils.utils', []);
angular.module('lumx.utils', [
'lumx.utils.depth',
'lumx.utils.event-scheduler',
'lumx.utils.transclude-replace',
'lumx.utils.utils'
]);
angular.module('lumx.button', []);
angular.module('lumx.checkbox', []);
angular.module('lumx.data-table', []);
angular.module('lumx.date-picker', []);
angular.module('lumx.dialog', ['lumx.utils.event-scheduler']);
angular.module('lumx.dropdown', ['lumx.utils.event-scheduler']);
angular.module('lumx.fab', []);
angular.module('lumx.file-input', []);
angular.module('lumx.icon', []);
angular.module('lumx.notification', ['lumx.utils.event-scheduler']);
angular.module('lumx.progress', []);
angular.module('lumx.radio-button', []);
angular.module('lumx.ripple', []);
angular.module('lumx.search-filter', []);
angular.module('lumx.select', []);
angular.module('lumx.stepper', []);
angular.module('lumx.switch', []);
angular.module('lumx.tabs', []);
angular.module('lumx.text-field', []);
angular.module('lumx.tooltip', []);
angular.module('lumx', [
'lumx.button',
'lumx.checkbox',
'lumx.data-table',
'lumx.date-picker',
'lumx.dialog',
'lumx.dropdown',
'lumx.fab',
'lumx.file-input',
'lumx.icon',
'lumx.notification',
'lumx.progress',
'lumx.radio-button',
'lumx.ripple',
'lumx.search-filter',
'lumx.select',
'lumx.stepper',
'lumx.switch',
'lumx.tabs',
'lumx.text-field',
'lumx.tooltip',
'lumx.utils'
]);
})();
(function()
{
'use strict';
angular
.module('lumx.utils.depth')
.service('LxDepthService', LxDepthService);
function LxDepthService()
{
var service = this;
var depth = 1000;
service.getDepth = getDepth;
service.register = register;
////////////
function getDepth()
{
return depth;
}
function register()
{
depth++;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.utils.event-scheduler')
.service('LxEventSchedulerService', LxEventSchedulerService);
LxEventSchedulerService.$inject = ['$document', 'LxUtils'];
function LxEventSchedulerService($document, LxUtils)
{
var service = this;
var handlers = {};
var schedule = {};
service.register = register;
service.unregister = unregister;
////////////
function handle(event)
{
var scheduler = schedule[event.type];
if (angular.isDefined(scheduler))
{
for (var i = 0, length = scheduler.length; i < length; i++)
{
var handler = scheduler[i];
if (angular.isDefined(handler) && angular.isDefined(handler.callback) && angular.isFunction(handler.callback))
{
handler.callback(event);
if (event.isPropagationStopped())
{
break;
}
}
}
}
}
function register(eventName, callback)
{
var handler = {
eventName: eventName,
callback: callback
};
var id = LxUtils.generateUUID();
handlers[id] = handler;
if (angular.isUndefined(schedule[eventName]))
{
schedule[eventName] = [];
$document.on(eventName, handle);
}
schedule[eventName].unshift(handlers[id]);
return id;
}
function unregister(id)
{
var found = false;
var handler = handlers[id];
if (angular.isDefined(handler) && angular.isDefined(schedule[handler.eventName]))
{
var index = schedule[handler.eventName].indexOf(handler);
if (angular.isDefined(index) && index > -1)
{
schedule[handler.eventName].splice(index, 1);
delete handlers[id];
found = true;
}
if (schedule[handler.eventName].length === 0)
{
delete schedule[handler.eventName];
$document.off(handler.eventName, handle);
}
}
return found;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.utils.transclude-replace')
.directive('ngTranscludeReplace', ngTranscludeReplace);
ngTranscludeReplace.$inject = ['$log'];
function ngTranscludeReplace($log)
{
return {
terminal: true,
restrict: 'EA',
link: link
};
function link(scope, element, attrs, ctrl, transclude)
{
if (!transclude)
{
$log.error('orphan',
'Illegal use of ngTranscludeReplace directive in the template! ' +
'No parent directive that requires a transclusion found. ');
return;
}
transclude(function(clone)
{
if (clone.length)
{
element.replaceWith(clone);
}
else
{
element.remove();
}
});
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.utils.utils')
.service('LxUtils', LxUtils);
function LxUtils()
{
var service = this;
service.debounce = debounce;
service.generateUUID = generateUUID;
service.disableBodyScroll = disableBodyScroll;
////////////
// http://underscorejs.org/#debounce (1.8.3)
function debounce(func, wait, immediate)
{
var timeout, args, context, timestamp, result;
wait = wait || 500;
var later = function()
{
var last = Date.now() - timestamp;
if (last < wait && last >= 0)
{
timeout = setTimeout(later, wait - last);
}
else
{
timeout = null;
if (!immediate)
{
result = func.apply(context, args);
if (!timeout)
{
context = args = null;
}
}
}
};
var debounced = function()
{
context = this;
args = arguments;
timestamp = Date.now();
var callNow = immediate && !timeout;
if (!timeout)
{
timeout = setTimeout(later, wait);
}
if (callNow)
{
result = func.apply(context, args);
context = args = null;
}
return result;
};
debounced.clear = function()
{
clearTimeout(timeout);
timeout = context = args = null;
};
return debounced;
}
function generateUUID()
{
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c)
{
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8))
.toString(16);
});
return uuid.toUpperCase();
}
function disableBodyScroll()
{
var body = document.body;
var documentElement = document.documentElement;
var prevDocumentStyle = documentElement.style.cssText || '';
var prevBodyStyle = body.style.cssText || '';
var viewportTop = window.scrollY || window.pageYOffset || 0;
var clientWidth = body.clientWidth;
var hasVerticalScrollbar = body.scrollHeight > window.innerHeight + 1;
if (hasVerticalScrollbar)
{
angular.element('body').css({
position: 'fixed',
width: '100%',
top: -viewportTop + 'px'
});
}
if (body.clientWidth < clientWidth)
{
body.style.overflow = 'hidden';
}
// This should be applied after the manipulation to the body, because
// adding a scrollbar can potentially resize it, causing the measurement
// to change.
if (hasVerticalScrollbar)
{
documentElement.style.overflowY = 'scroll';
}
return function restoreScroll()
{
// Reset the inline style CSS to the previous.
body.style.cssText = prevBodyStyle;
documentElement.style.cssText = prevDocumentStyle;
// The body loses its scroll position while being fixed.
body.scrollTop = viewportTop;
};
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.button')
.directive('lxButton', lxButton);
function lxButton()
{
var buttonClass;
return {
restrict: 'E',
templateUrl: getTemplateUrl,
compile: compile,
replace: true,
transclude: true
};
function compile(element, attrs)
{
setButtonStyle(element, attrs.lxSize, attrs.lxColor, attrs.lxType);
return function(scope, element, attrs)
{
attrs.$observe('lxSize', function(lxSize)
{
setButtonStyle(element, lxSize, attrs.lxColor, attrs.lxType);
});
attrs.$observe('lxColor', function(lxColor)
{
setButtonStyle(element, attrs.lxSize, lxColor, attrs.lxType);
});
attrs.$observe('lxType', function(lxType)
{
setButtonStyle(element, attrs.lxSize, attrs.lxColor, lxType);
});
element.on('click', function(event)
{
if (attrs.disabled === true)
{
event.preventDefault();
event.stopImmediatePropagation();
}
});
};
}
function getTemplateUrl(element, attrs)
{
return isAnchor(attrs) ? 'link.html' : 'button.html';
}
function isAnchor(attrs)
{
return angular.isDefined(attrs.href) || angular.isDefined(attrs.ngHref) || angular.isDefined(attrs.ngLink) || angular.isDefined(attrs.uiSref);
}
function setButtonStyle(element, size, color, type)
{
var buttonBase = 'btn';
var buttonSize = angular.isDefined(size) ? size : 'm';
var buttonColor = angular.isDefined(color) ? color : 'primary';
var buttonType = angular.isDefined(type) ? type : 'raised';
element.removeClass(buttonClass);
buttonClass = buttonBase + ' btn--' + buttonSize + ' btn--' + buttonColor + ' btn--' + buttonType;
element.addClass(buttonClass);
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.checkbox')
.directive('lxCheckbox', lxCheckbox)
.directive('lxCheckboxLabel', lxCheckboxLabel)
.directive('lxCheckboxHelp', lxCheckboxHelp);
function lxCheckbox()
{
return {
restrict: 'E',
templateUrl: 'checkbox.html',
scope:
{
lxColor: '@?',
name: '@?',
ngChange: '&?',
ngDisabled: '=?',
ngFalseValue: '@?',
ngModel: '=',
ngTrueValue: '@?',
theme: '@?lxTheme'
},
controller: LxCheckboxController,
controllerAs: 'lxCheckbox',
bindToController: true,
transclude: true,
replace: true
};
}
LxCheckboxController.$inject = ['$scope', '$timeout', 'LxUtils'];
function LxCheckboxController($scope, $timeout, LxUtils)
{
var lxCheckbox = this;
var checkboxId;
var checkboxHasChildren;
var timer;
lxCheckbox.getCheckboxId = getCheckboxId;
lxCheckbox.getCheckboxHasChildren = getCheckboxHasChildren;
lxCheckbox.setCheckboxId = setCheckboxId;
lxCheckbox.setCheckboxHasChildren = setCheckboxHasChildren;
lxCheckbox.triggerNgChange = triggerNgChange;
$scope.$on('$destroy', function()
{
$timeout.cancel(timer);
});
init();
////////////
function getCheckboxId()
{
return checkboxId;
}
function getCheckboxHasChildren()
{
return checkboxHasChildren;
}
function init()
{
setCheckboxId(LxUtils.generateUUID());
setCheckboxHasChildren(false);
lxCheckbox.ngTrueValue = angular.isUndefined(lxCheckbox.ngTrueValue) ? true : lxCheckbox.ngTrueValue;
lxCheckbox.ngFalseValue = angular.isUndefined(lxCheckbox.ngFalseValue) ? false : lxCheckbox.ngFalseValue;
lxCheckbox.lxColor = angular.isUndefined(lxCheckbox.lxColor) ? 'accent' : lxCheckbox.lxColor;
}
function setCheckboxId(_checkboxId)
{
checkboxId = _checkboxId;
}
function setCheckboxHasChildren(_checkboxHasChildren)
{
checkboxHasChildren = _checkboxHasChildren;
}
function triggerNgChange()
{
timer = $timeout(lxCheckbox.ngChange);
}
}
function lxCheckboxLabel()
{
return {
restrict: 'AE',
require: ['^lxCheckbox', '^lxCheckboxLabel'],
templateUrl: 'checkbox-label.html',
link: link,
controller: LxCheckboxLabelController,
controllerAs: 'lxCheckboxLabel',
bindToController: true,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].setCheckboxHasChildren(true);
ctrls[1].setCheckboxId(ctrls[0].getCheckboxId());
}
}
function LxCheckboxLabelController()
{
var lxCheckboxLabel = this;
var checkboxId;
lxCheckboxLabel.getCheckboxId = getCheckboxId;
lxCheckboxLabel.setCheckboxId = setCheckboxId;
////////////
function getCheckboxId()
{
return checkboxId;
}
function setCheckboxId(_checkboxId)
{
checkboxId = _checkboxId;
}
}
function lxCheckboxHelp()
{
return {
restrict: 'AE',
require: '^lxCheckbox',
templateUrl: 'checkbox-help.html',
transclude: true,
replace: true
};
}
})();
(function()
{
'use strict';
angular
.module('lumx.data-table')
.directive('lxDataTable', lxDataTable);
function lxDataTable()
{
return {
restrict: 'E',
templateUrl: 'data-table.html',
scope:
{
border: '=?lxBorder',
selectable: '=?lxSelectable',
thumbnail: '=?lxThumbnail',
tbody: '=lxTbody',
thead: '=lxThead'
},
link: link,
controller: LxDataTableController,
controllerAs: 'lxDataTable',
bindToController: true,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrl)
{
attrs.$observe('id', function(_newId)
{
ctrl.id = _newId;
});
}
}
LxDataTableController.$inject = ['$rootScope', '$sce', '$scope'];
function LxDataTableController($rootScope, $sce, $scope)
{
var lxDataTable = this;
lxDataTable.areAllRowsSelected = areAllRowsSelected;
lxDataTable.border = angular.isUndefined(lxDataTable.border) ? true : lxDataTable.border;
lxDataTable.sort = sort;
lxDataTable.toggle = toggle;
lxDataTable.toggleAllSelected = toggleAllSelected;
lxDataTable.$sce = $sce;
lxDataTable.allRowsSelected = false;
lxDataTable.selectedRows = [];
$scope.$on('lx-data-table__select', function(event, id, row)
{
if (id === lxDataTable.id && angular.isDefined(row))
{
if (angular.isArray(row) && row.length > 0)
{
row = row[0];
}
_select(row);
}
});
$scope.$on('lx-data-table__select-all', function(event, id)
{
if (id === lxDataTable.id)
{
_selectAll();
}
});
$scope.$on('lx-data-table__unselect', function(event, id, row)
{
if (id === lxDataTable.id && angular.isDefined(row))
{
if (angular.isArray(row) && row.length > 0)
{
row = row[0];
}
_unselect(row);
}
});
$scope.$on('lx-data-table__unselect-all', function(event, id)
{
if (id === lxDataTable.id)
{
_unselectAll();
}
});
////////////
function _selectAll()
{
lxDataTable.selectedRows.length = 0;
for (var i = 0, len = lxDataTable.tbody.length; i < len; i++)
{
if (!lxDataTable.tbody[i].lxDataTableDisabled)
{
lxDataTable.tbody[i].lxDataTableSelected = true;
lxDataTable.selectedRows.push(lxDataTable.tbody[i]);
}
}
lxDataTable.allRowsSelected = true;
$rootScope.$broadcast('lx-data-table__unselected', lxDataTable.id, lxDataTable.selectedRows);
}
function _select(row)
{
toggle(row, true);
}
function _unselectAll()
{
for (var i = 0, len = lxDataTable.tbody.length; i < len; i++)
{
if (!lxDataTable.tbody[i].lxDataTableDisabled)
{
lxDataTable.tbody[i].lxDataTableSelected = false;
}
}
lxDataTable.allRowsSelected = false;
lxDataTable.selectedRows.length = 0;
$rootScope.$broadcast('lx-data-table__selected', lxDataTable.id, lxDataTable.selectedRows);
}
function _unselect(row)
{
toggle(row, false);
}
////////////
function areAllRowsSelected()
{
var displayedRows = 0;
for (var i = 0, len = lxDataTable.tbody.length; i < len; i++)
{
if (!lxDataTable.tbody[i].lxDataTableDisabled)
{
displayedRows++;
}
}
if (displayedRows === lxDataTable.selectedRows.length)
{
lxDataTable.allRowsSelected = true;
}
else
{
lxDataTable.allRowsSelected = false;
}
}
function sort(_column)
{
if (!_column.sortable)
{
return;
}
for (var i = 0, len = lxDataTable.thead.length; i < len; i++)
{
if (lxDataTable.thead[i].sortable && lxDataTable.thead[i].name !== _column.name)
{
lxDataTable.thead[i].sort = undefined;
}
}
if (!_column.sort || _column.sort === 'desc')
{
_column.sort = 'asc';
}
else
{
_column.sort = 'desc';
}
$rootScope.$broadcast('lx-data-table__sorted', lxDataTable.id, _column);
}
function toggle(_row, _newSelectedStatus)
{
if (_row.lxDataTableDisabled || !lxDataTable.selectable)
{
return;
}
_row.lxDataTableSelected = angular.isDefined(_newSelectedStatus) ? _newSelectedStatus : !_row.lxDataTableSelected;
if (_row.lxDataTableSelected)
{
// Make sure it's not already in.
if (lxDataTable.selectedRows.length === 0 || (lxDataTable.selectedRows.length && lxDataTable.selectedRows.indexOf(_row) === -1))
{
lxDataTable.selectedRows.push(_row);
lxDataTable.areAllRowsSelected();
$rootScope.$broadcast('lx-data-table__selected', lxDataTable.id, lxDataTable.selectedRows);
}
}
else
{
if (lxDataTable.selectedRows.length && lxDataTable.selectedRows.indexOf(_row) > -1)
{
lxDataTable.selectedRows.splice(lxDataTable.selectedRows.indexOf(_row), 1);
lxDataTable.allRowsSelected = false;
$rootScope.$broadcast('lx-data-table__unselected', lxDataTable.id, lxDataTable.selectedRows);
}
}
}
function toggleAllSelected()
{
if (lxDataTable.allRowsSelected)
{
_unselectAll();
}
else
{
_selectAll();
}
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.data-table')
.service('LxDataTableService', LxDataTableService);
LxDataTableService.$inject = ['$rootScope'];
function LxDataTableService($rootScope)
{
var service = this;
service.select = select;
service.selectAll = selectAll;
service.unselect = unselect;
service.unselectAll = unselectAll;
////////////
function select(_dataTableId, row)
{
$rootScope.$broadcast('lx-data-table__select', _dataTableId, row);
}
function selectAll(_dataTableId)
{
$rootScope.$broadcast('lx-data-table__select-all', _dataTableId);
}
function unselect(_dataTableId, row)
{
$rootScope.$broadcast('lx-data-table__unselect', _dataTableId, row);
}
function unselectAll(_dataTableId)
{
$rootScope.$broadcast('lx-data-table__unselect-all', _dataTableId);
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.date-picker')
.directive('lxDatePicker', lxDatePicker);
lxDatePicker.$inject = ['LxDatePickerService', 'LxUtils'];
function lxDatePicker(LxDatePickerService, LxUtils)
{
return {
restrict: 'AE',
templateUrl: 'date-picker.html',
scope:
{
autoClose: '=?lxAutoClose',
callback: '&?lxCallback',
color: '@?lxColor',
escapeClose: '=?lxEscapeClose',
inputFormat: '@?lxInputFormat',
maxDate: '=?lxMaxDate',
ngModel: '=',
minDate: '=?lxMinDate',
locale: '@lxLocale'
},
link: link,
controller: LxDatePickerController,
controllerAs: 'lxDatePicker',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs)
{
if (angular.isDefined(attrs.id))
{
attrs.$observe('id', function(_newId)
{
scope.lxDatePicker.pickerId = _newId;
LxDatePickerService.registerScope(scope.lxDatePicker.pickerId, scope);
});
}
else
{
scope.lxDatePicker.pickerId = LxUtils.generateUUID();
LxDatePickerService.registerScope(scope.lxDatePicker.pickerId, scope);
}
}
}
LxDatePickerController.$inject = ['$element', '$scope', '$timeout', '$transclude', 'LxDatePickerService', 'LxUtils'];
function LxDatePickerController($element, $scope, $timeout, $transclude, LxDatePickerService, LxUtils)
{
var lxDatePicker = this;
var input;
var modelController;
var timer1;
var timer2;
var watcher1;
var watcher2;
lxDatePicker.closeDatePicker = closeDatePicker;
lxDatePicker.displayYearSelection = displayYearSelection;
lxDatePicker.hideYearSelection = hideYearSelection;
lxDatePicker.getDateFormatted = getDateFormatted;
lxDatePicker.nextMonth = nextMonth;
lxDatePicker.openDatePicker = openDatePicker;
lxDatePicker.previousMonth = previousMonth;
lxDatePicker.select = select;
lxDatePicker.selectYear = selectYear;
lxDatePicker.autoClose = angular.isDefined(lxDatePicker.autoClose) ? lxDatePicker.autoClose : true;
lxDatePicker.color = angular.isDefined(lxDatePicker.color) ? lxDatePicker.color : 'primary';
lxDatePicker.element = $element.find('.lx-date-picker');
lxDatePicker.escapeClose = angular.isDefined(lxDatePicker.escapeClose) ? lxDatePicker.escapeClose : true;
lxDatePicker.isOpen = false;
lxDatePicker.moment = moment;
lxDatePicker.yearSelection = false;
lxDatePicker.uuid = LxUtils.generateUUID();
$transclude(function(clone)
{
if (clone.length)
{
lxDatePicker.hasInput = true;
timer1 = $timeout(function()
{
input = $element.find('.lx-date-input input');
modelController = input.data('$ngModelController');
watcher2 = $scope.$watch(function()
{
return modelController.$viewValue;
}, function(newValue, oldValue)
{
if (angular.isUndefined(newValue))
{
lxDatePicker.ngModel = undefined;
}
});
});
}
});
watcher1 = $scope.$watch(function()
{
return lxDatePicker.ngModel;
}, init);
$scope.$on('$destroy', function()
{
$timeout.cancel(timer1);
$timeout.cancel(timer2);
if (angular.isFunction(watcher1))
{
watcher1();
}
if (angular.isFunction(watcher2))
{
watcher2();
}
});
////////////
function closeDatePicker()
{
LxDatePickerService.close(lxDatePicker.pickerId);
}
function displayYearSelection()
{
lxDatePicker.yearSelection = true;
timer2 = $timeout(function()
{
var yearSelector = angular.element('.lx-date-picker__year-selector');
var activeYear = yearSelector.find('.lx-date-picker__year--is-active');
yearSelector.scrollTop(yearSelector.scrollTop() + activeYear.position().top - yearSelector.height() / 2 + activeYear.height() / 2);
});
}
function hideYearSelection()
{
lxDatePicker.yearSelection = false;
}
function generateCalendar()
{
lxDatePicker.days = [];
var previousDay = angular.copy(lxDatePicker.ngModelMoment).date(0);
var firstDayOfMonth = angular.copy(lxDatePicker.ngModelMoment).date(1);
var lastDayOfMonth = firstDayOfMonth.clone().endOf('month');
var maxDays = lastDayOfMonth.date();
lxDatePicker.emptyFirstDays = [];
for (var i = firstDayOfMonth.day() === 0 ? 6 : firstDayOfMonth.day() - 1; i > 0; i--)
{
lxDatePicker.emptyFirstDays.push(
{});
}
for (var j = 0; j < maxDays; j++)
{
var date = angular.copy(previousDay.add(1, 'days'));
date.selected = angular.isDefined(lxDatePicker.ngModel) && date.isSame(lxDatePicker.ngModel, 'day');
date.today = date.isSame(moment(), 'day');
if (angular.isDefined(lxDatePicker.minDate) && date.toDate() < lxDatePicker.minDate)
{
date.disabled = true;
}
if (angular.isDefined(lxDatePicker.maxDate) && date.toDate() > lxDatePicker.maxDate)
{
date.disabled = true;
}
lxDatePicker.days.push(date);
}
lxDatePicker.emptyLastDays = [];
for (var k = 7 - (lastDayOfMonth.day() === 0 ? 7 : lastDayOfMonth.day()); k > 0; k--)
{
lxDatePicker.emptyLastDays.push(
{});
}
}
function getDateFormatted()
{
var dateFormatted = lxDatePicker.ngModelMoment.format('llll').replace(lxDatePicker.ngModelMoment.format('LT'), '').trim().replace(lxDatePicker.ngModelMoment.format('YYYY'), '').trim();
var dateFormattedLastChar = dateFormatted.slice(-1);
if (dateFormattedLastChar === ',')
{
dateFormatted = dateFormatted.slice(0, -1);
}
return dateFormatted;
}
function init()
{
moment.locale(lxDatePicker.locale);
lxDatePicker.ngModelMoment = angular.isDefined(lxDatePicker.ngModel) ? moment(angular.copy(lxDatePicker.ngModel)) : moment();
lxDatePicker.days = [];
lxDatePicker.daysOfWeek = [moment.weekdaysMin(1), moment.weekdaysMin(2), moment.weekdaysMin(3), moment.weekdaysMin(4), moment.weekdaysMin(5), moment.weekdaysMin(6), moment.weekdaysMin(0)];
lxDatePicker.years = [];
for (var y = moment().year() - 100; y <= moment().year() + 100; y++)
{
lxDatePicker.years.push(y);
}
generateCalendar();
}
function nextMonth()
{
lxDatePicker.ngModelMoment = lxDatePicker.ngModelMoment.add(1, 'month');
generateCalendar();
}
function openDatePicker()
{
LxDatePickerService.open(lxDatePicker.pickerId);
}
function previousMonth()
{
lxDatePicker.ngModelMoment = lxDatePicker.ngModelMoment.subtract(1, 'month');
generateCalendar();
}
function select(_day)
{
if (!_day.disabled)
{
lxDatePicker.ngModel = _day.toDate();
lxDatePicker.ngModelMoment = angular.copy(_day);
if (angular.isDefined(lxDatePicker.callback))
{
lxDatePicker.callback(
{
newDate: lxDatePicker.ngModel
});
}
if (angular.isDefined(modelController) && lxDatePicker.inputFormat)
{
modelController.$setViewValue(angular.copy(_day).format(lxDatePicker.inputFormat));
modelController.$render();
}
generateCalendar();
}
}
function selectYear(_year)
{
lxDatePicker.yearSelection = false;
lxDatePicker.ngModelMoment = lxDatePicker.ngModelMoment.year(_year);
generateCalendar();
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.date-picker')
.service('LxDatePickerService', LxDatePickerService);
LxDatePickerService.$inject = ['$rootScope', '$timeout', 'LxDepthService', 'LxEventSchedulerService'];
function LxDatePickerService($rootScope, $timeout, LxDepthService, LxEventSchedulerService)
{
var service = this;
var activeDatePickerId;
var datePickerFilter;
var idEventScheduler;
var scopeMap = {};
service.close = closeDatePicker;
service.open = openDatePicker;
service.registerScope = registerScope;
////////////
function closeDatePicker(_datePickerId)
{
if (angular.isDefined(idEventScheduler))
{
LxEventSchedulerService.unregister(idEventScheduler);
idEventScheduler = undefined;
}
activeDatePickerId = undefined;
$rootScope.$broadcast('lx-date-picker__close-start', _datePickerId);
datePickerFilter.removeClass('lx-date-picker-filter--is-shown');
scopeMap[_datePickerId].element.removeClass('lx-date-picker--is-shown');
$timeout(function()
{
angular.element('body').removeClass('no-scroll-date-picker-' + scopeMap[_datePickerId].uuid);
datePickerFilter.remove();
scopeMap[_datePickerId].element
.hide()
.appendTo(scopeMap[_datePickerId].elementParent);
scopeMap[_datePickerId].isOpen = false;
$rootScope.$broadcast('lx-date-picker__close-end', _datePickerId);
}, 600);
}
function onKeyUp(_event)
{
if (_event.keyCode == 27 && angular.isDefined(activeDatePickerId))
{
closeDatePicker(activeDatePickerId);
}
_event.stopPropagation();
}
function openDatePicker(_datePickerId)
{
LxDepthService.register();
activeDatePickerId = _datePickerId;
angular.element('body').addClass('no-scroll-date-picker-' + scopeMap[_datePickerId].uuid);
datePickerFilter = angular.element('<div/>',
{
class: 'lx-date-picker-filter'
});
datePickerFilter
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
if (scopeMap[activeDatePickerId].autoClose)
{
datePickerFilter.on('click', function()
{
closeDatePicker(activeDatePickerId);
});
}
if (scopeMap[activeDatePickerId].escapeClose)
{
idEventScheduler = LxEventSchedulerService.register('keyup', onKeyUp);
}
scopeMap[activeDatePickerId].element
.css('z-index', LxDepthService.getDepth() + 1)
.appendTo('body')
.show();
$timeout(function()
{
$rootScope.$broadcast('lx-date-picker__open-start', activeDatePickerId);
scopeMap[activeDatePickerId].isOpen = true;
datePickerFilter.addClass('lx-date-picker-filter--is-shown');
scopeMap[activeDatePickerId].element.addClass('lx-date-picker--is-shown');
}, 100);
$timeout(function()
{
$rootScope.$broadcast('lx-date-picker__open-end', activeDatePickerId);
}, 700);
}
function registerScope(_datePickerId, _datePickerScope)
{
scopeMap[_datePickerId] = _datePickerScope.lxDatePicker;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.dialog')
.directive('lxDialog', lxDialog)
.directive('lxDialogHeader', lxDialogHeader)
.directive('lxDialogContent', lxDialogContent)
.directive('lxDialogFooter', lxDialogFooter)
.directive('lxDialogClose', lxDialogClose);
function lxDialog()
{
return {
restrict: 'E',
template: '<div class="dialog" ng-class="{ \'dialog--l\': !lxDialog.size || lxDialog.size === \'l\', \'dialog--s\': lxDialog.size === \'s\', \'dialog--m\': lxDialog.size === \'m\' }"><div ng-if="lxDialog.isOpen" ng-transclude></div></div>',
scope:
{
autoClose: '=?lxAutoClose',
escapeClose: '=?lxEscapeClose',
size: '@?lxSize'
},
link: link,
controller: LxDialogController,
controllerAs: 'lxDialog',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrl)
{
attrs.$observe('id', function(_newId)
{
ctrl.id = _newId;
});
}
}
LxDialogController.$inject = ['$element', '$interval', '$rootScope', '$scope', '$timeout', '$window', 'LxDepthService', 'LxEventSchedulerService', 'LxUtils'];
function LxDialogController($element, $interval, $rootScope, $scope, $timeout, $window, LxDepthService, LxEventSchedulerService, LxUtils)
{
var lxDialog = this;
var dialogFilter = angular.element('<div/>',
{
class: 'dialog-filter'
});
var dialogHeight;
var dialogInterval;
var dialogScrollable;
var elementParent = $element.parent();
var idEventScheduler;
var resizeDebounce;
var windowHeight;
lxDialog.autoClose = angular.isDefined(lxDialog.autoClose) ? lxDialog.autoClose : true;
lxDialog.escapeClose = angular.isDefined(lxDialog.escapeClose) ? lxDialog.escapeClose : true;
lxDialog.isOpen = false;
lxDialog.uuid = LxUtils.generateUUID();
$scope.$on('lx-dialog__open', function(event, id)
{
if (id === lxDialog.id)
{
open();
}
});
$scope.$on('lx-dialog__close', function(event, id)
{
if (id === lxDialog.id)
{
close();
}
});
$scope.$on('$destroy', function()
{
close();
});
////////////
function checkDialogHeight()
{
var dialog = $element;
var dialogHeader = dialog.find('.dialog__header');
var dialogContent = dialog.find('.dialog__content');
var dialogFooter = dialog.find('.dialog__footer');
if (!dialogFooter.length)
{
dialogFooter = dialog.find('.dialog__actions');
}
if (angular.isUndefined(dialogHeader))
{
return;
}
var heightToCheck = 60 + dialogHeader.outerHeight() + dialogContent.outerHeight() + dialogFooter.outerHeight();
if (dialogHeight === heightToCheck && windowHeight === $window.innerHeight)
{
return;
}
dialogHeight = heightToCheck;
windowHeight = $window.innerHeight;
if (heightToCheck >= $window.innerHeight)
{
dialog.addClass('dialog--is-fixed');
dialogScrollable
.css(
{
top: dialogHeader.outerHeight(),
bottom: dialogFooter.outerHeight()
})
.off('scroll', checkScrollEnd)
.on('scroll', checkScrollEnd);
}
else
{
dialog.removeClass('dialog--is-fixed');
dialogScrollable
.removeAttr('style')
.off('scroll', checkScrollEnd);
}
}
function checkDialogHeightOnResize()
{
if (resizeDebounce)
{
$timeout.cancel(resizeDebounce);
}
resizeDebounce = $timeout(function()
{
checkDialogHeight();
}, 200);
}
function checkScrollEnd()
{
if (dialogScrollable.scrollTop() + dialogScrollable.innerHeight() >= dialogScrollable[0].scrollHeight)
{
$rootScope.$broadcast('lx-dialog__scroll-end', lxDialog.id);
dialogScrollable.off('scroll', checkScrollEnd);
$timeout(function()
{
dialogScrollable.on('scroll', checkScrollEnd);
}, 500);
}
}
function onKeyUp(_event)
{
if (_event.keyCode == 27)
{
close();
}
_event.stopPropagation();
}
function open()
{
if (lxDialog.isOpen)
{
return;
}
LxDepthService.register();
angular.element('body').addClass('no-scroll-dialog-' + lxDialog.uuid);
dialogFilter
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
if (lxDialog.autoClose)
{
dialogFilter.on('click', function()
{
close();
});
}
if (lxDialog.escapeClose)
{
idEventScheduler = LxEventSchedulerService.register('keyup', onKeyUp);
}
$element
.css('z-index', LxDepthService.getDepth() + 1)
.appendTo('body')
.show();
$timeout(function()
{
$rootScope.$broadcast('lx-dialog__open-start', lxDialog.id);
lxDialog.isOpen = true;
dialogFilter.addClass('dialog-filter--is-shown');
$element.addClass('dialog--is-shown');
}, 100);
$timeout(function()
{
if ($element.find('.dialog__scrollable').length === 0)
{
$element.find('.dialog__content').wrap(angular.element('<div/>',
{
class: 'dialog__scrollable'
}));
}
dialogScrollable = $element.find('.dialog__scrollable');
}, 200);
$timeout(function()
{
$rootScope.$broadcast('lx-dialog__open-end', lxDialog.id);
}, 700);
dialogInterval = $interval(function()
{
checkDialogHeight();
}, 500);
angular.element($window).on('resize', checkDialogHeightOnResize);
}
function close()
{
if (!lxDialog.isOpen)
{
return;
}
if (angular.isDefined(idEventScheduler))
{
LxEventSchedulerService.unregister(idEventScheduler);
idEventScheduler = undefined;
}
angular.element($window).off('resize', checkDialogHeightOnResize);
$element.find('.dialog__scrollable').off('scroll', checkScrollEnd);
$rootScope.$broadcast('lx-dialog__close-start', lxDialog.id);
if (resizeDebounce)
{
$timeout.cancel(resizeDebounce);
}
$interval.cancel(dialogInterval);
dialogFilter.removeClass('dialog-filter--is-shown');
$element.removeClass('dialog--is-shown');
$timeout(function()
{
angular.element('body').removeClass('no-scroll-dialog-' + lxDialog.uuid);
dialogFilter.remove();
$element
.hide()
.removeClass('dialog--is-fixed')
.appendTo(elementParent);
lxDialog.isOpen = false;
dialogHeight = undefined;
$rootScope.$broadcast('lx-dialog__close-end', lxDialog.id);
}, 600);
}
}
function lxDialogHeader()
{
return {
restrict: 'E',
template: '<div class="dialog__header" ng-transclude></div>',
replace: true,
transclude: true
};
}
function lxDialogContent()
{
return {
restrict: 'E',
template: '<div class="dialog__scrollable"><div class="dialog__content" ng-transclude></div></div>',
replace: true,
transclude: true
};
}
function lxDialogFooter()
{
return {
restrict: 'E',
template: '<div class="dialog__footer" ng-transclude></div>',
replace: true,
transclude: true
};
}
lxDialogClose.$inject = ['LxDialogService'];
function lxDialogClose(LxDialogService)
{
return {
restrict: 'A',
link: function(scope, element)
{
element.on('click', function()
{
LxDialogService.close(element.parents('.dialog').attr('id'));
});
scope.$on('$destroy', function()
{
element.off();
});
}
};
}
})();
(function()
{
'use strict';
angular
.module('lumx.dialog')
.service('LxDialogService', LxDialogService);
LxDialogService.$inject = ['$rootScope'];
function LxDialogService($rootScope)
{
var service = this;
service.open = open;
service.close = close;
////////////
function open(_dialogId)
{
$rootScope.$broadcast('lx-dialog__open', _dialogId);
}
function close(_dialogId)
{
$rootScope.$broadcast('lx-dialog__close', _dialogId);
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.dropdown')
.directive('lxDropdown', lxDropdown)
.directive('lxDropdownToggle', lxDropdownToggle)
.directive('lxDropdownMenu', lxDropdownMenu)
.directive('lxDropdownFilter', lxDropdownFilter);
function lxDropdown()
{
return {
restrict: 'E',
templateUrl: 'dropdown.html',
scope:
{
depth: '@?lxDepth',
effect: '@?lxEffect',
escapeClose: '=?lxEscapeClose',
hover: '=?lxHover',
hoverDelay: '=?lxHoverDelay',
offset: '@?lxOffset',
overToggle: '=?lxOverToggle',
position: '@?lxPosition',
width: '@?lxWidth'
},
link: link,
controller: LxDropdownController,
controllerAs: 'lxDropdown',
bindToController: true,
transclude: true
};
function link(scope, element, attrs, ctrl)
{
var backwardOneWay = ['position', 'width'];
var backwardTwoWay = ['escapeClose', 'overToggle'];
angular.forEach(backwardOneWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
attrs.$observe(attribute, function(newValue)
{
scope.lxDropdown[attribute] = newValue;
});
}
});
angular.forEach(backwardTwoWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
scope.$watch(function()
{
return scope.$parent.$eval(attrs[attribute]);
}, function(newValue)
{
scope.lxDropdown[attribute] = newValue;
});
}
});
attrs.$observe('id', function(_newId)
{
ctrl.uuid = _newId;
});
scope.$on('$destroy', function()
{
if (ctrl.isOpen)
{
ctrl.closeDropdownMenu();
}
});
}
}
LxDropdownController.$inject = ['$element', '$interval', '$scope', '$timeout', '$window', 'LxDepthService',
'LxDropdownService', 'LxEventSchedulerService', 'LxUtils'
];
function LxDropdownController($element, $interval, $scope, $timeout, $window, LxDepthService,
LxDropdownService, LxEventSchedulerService, LxUtils)
{
var lxDropdown = this;
var dropdownInterval;
var dropdownMenu;
var dropdownToggle;
var idEventScheduler;
var openTimeout;
var positionTarget;
var scrollMask = angular.element('<div/>',
{
class: 'scroll-mask'
});
var enableBodyScroll;
lxDropdown.closeDropdownMenu = closeDropdownMenu;
lxDropdown.openDropdownMenu = openDropdownMenu;
lxDropdown.registerDropdownMenu = registerDropdownMenu;
lxDropdown.registerDropdownToggle = registerDropdownToggle;
lxDropdown.toggle = toggle;
lxDropdown.uuid = LxUtils.generateUUID();
lxDropdown.effect = angular.isDefined(lxDropdown.effect) ? lxDropdown.effect : 'expand';
lxDropdown.escapeClose = angular.isDefined(lxDropdown.escapeClose) ? lxDropdown.escapeClose : true;
lxDropdown.hasToggle = false;
lxDropdown.isOpen = false;
lxDropdown.overToggle = angular.isDefined(lxDropdown.overToggle) ? lxDropdown.overToggle : false;
lxDropdown.position = angular.isDefined(lxDropdown.position) ? lxDropdown.position : 'left';
$scope.$on('lx-dropdown__open', function(_event, _params)
{
if (_params.uuid === lxDropdown.uuid && !lxDropdown.isOpen)
{
LxDropdownService.closeActiveDropdown();
LxDropdownService.registerActiveDropdownUuid(lxDropdown.uuid);
positionTarget = _params.target;
registerDropdownToggle(angular.element(positionTarget));
openDropdownMenu();
}
});
$scope.$on('lx-dropdown__close', function(_event, _params)
{
if (_params.uuid === lxDropdown.uuid && lxDropdown.isOpen)
{
closeDropdownMenu();
}
});
$scope.$on('$destroy', function()
{
$timeout.cancel(openTimeout);
});
////////////
function closeDropdownMenu()
{
$interval.cancel(dropdownInterval);
LxDropdownService.resetActiveDropdownUuid();
var velocityProperties;
var velocityEasing;
scrollMask.remove();
if (angular.isFunction(enableBodyScroll)) {
enableBodyScroll();
}
enableBodyScroll = undefined;
if (lxDropdown.hasToggle)
{
dropdownToggle
.off('wheel')
.css('z-index', '');
}
dropdownMenu
.off('wheel')
.css(
{
overflow: 'hidden'
});
if (lxDropdown.effect === 'expand')
{
velocityProperties = {
width: 0,
height: 0
};
velocityEasing = 'easeOutQuint';
}
else if (lxDropdown.effect === 'fade')
{
velocityProperties = {
opacity: 0
};
velocityEasing = 'linear';
}
if (lxDropdown.effect === 'expand' || lxDropdown.effect === 'fade')
{
dropdownMenu.velocity(velocityProperties,
{
duration: 200,
easing: velocityEasing,
complete: function()
{
dropdownMenu
.removeAttr('style')
.removeClass('dropdown-menu--is-open')
.appendTo($element.find('.dropdown'));
$scope.$apply(function()
{
lxDropdown.isOpen = false;
if (lxDropdown.escapeClose)
{
LxEventSchedulerService.unregister(idEventScheduler);
idEventScheduler = undefined;
}
});
}
});
}
else if (lxDropdown.effect === 'none')
{
dropdownMenu
.removeAttr('style')
.removeClass('dropdown-menu--is-open')
.appendTo($element.find('.dropdown'));
lxDropdown.isOpen = false;
if (lxDropdown.escapeClose)
{
LxEventSchedulerService.unregister(idEventScheduler);
idEventScheduler = undefined;
}
}
}
function getAvailableHeight()
{
var availableHeightOnTop;
var availableHeightOnBottom;
var direction;
var dropdownToggleHeight = dropdownToggle.outerHeight();
var dropdownToggleTop = dropdownToggle.offset().top - angular.element($window).scrollTop();
var windowHeight = $window.innerHeight;
if (lxDropdown.overToggle)
{
availableHeightOnTop = dropdownToggleTop + dropdownToggleHeight;
availableHeightOnBottom = windowHeight - dropdownToggleTop;
}
else
{
availableHeightOnTop = dropdownToggleTop;
availableHeightOnBottom = windowHeight - (dropdownToggleTop + dropdownToggleHeight);
}
if (availableHeightOnTop > availableHeightOnBottom)
{
direction = 'top';
}
else
{
direction = 'bottom';
}
return {
top: availableHeightOnTop,
bottom: availableHeightOnBottom,
direction: direction
};
}
function initDropdownPosition()
{
var availableHeight = getAvailableHeight();
var dropdownMenuWidth;
var dropdownMenuLeft;
var dropdownMenuRight;
var dropdownToggleWidth = dropdownToggle.outerWidth();
var dropdownToggleHeight = dropdownToggle.outerHeight();
var dropdownToggleTop = dropdownToggle.offset().top - angular.element($window).scrollTop();
var windowWidth = $window.innerWidth;
var windowHeight = $window.innerHeight;
if (angular.isDefined(lxDropdown.width))
{
if (lxDropdown.width.indexOf('%') > -1)
{
dropdownMenuWidth = dropdownToggleWidth * (lxDropdown.width.slice(0, -1) / 100);
}
else
{
dropdownMenuWidth = lxDropdown.width;
}
}
else
{
dropdownMenuWidth = 'auto';
}
if (lxDropdown.position === 'left')
{
dropdownMenuLeft = dropdownToggle.offset().left;
dropdownMenuRight = 'auto';
}
else if (lxDropdown.position === 'right')
{
dropdownMenuLeft = 'auto';
dropdownMenuRight = windowWidth - dropdownToggle.offset().left - dropdownToggleWidth;
}
else if (lxDropdown.position === 'center')
{
dropdownMenuLeft = (dropdownToggle.offset().left + (dropdownToggleWidth / 2)) - (dropdownMenuWidth / 2);
dropdownMenuRight = 'auto';
}
dropdownMenu.css(
{
left: dropdownMenuLeft,
right: dropdownMenuRight,
width: dropdownMenuWidth
});
if (availableHeight.direction === 'top')
{
dropdownMenu.css(
{
bottom: lxDropdown.overToggle ? (windowHeight - dropdownToggleTop - dropdownToggleHeight) : (windowHeight - dropdownToggleTop + ~~lxDropdown.offset)
});
return availableHeight.top;
}
else if (availableHeight.direction === 'bottom')
{
dropdownMenu.css(
{
top: lxDropdown.overToggle ? dropdownToggleTop : (dropdownToggleTop + dropdownToggleHeight + ~~lxDropdown.offset)
});
return availableHeight.bottom;
}
}
function openDropdownMenu()
{
lxDropdown.isOpen = true;
LxDepthService.register();
scrollMask
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
scrollMask.on('wheel', function preventDefault(e) {
e.preventDefault();
});
enableBodyScroll = LxUtils.disableBodyScroll();
if (lxDropdown.hasToggle)
{
dropdownToggle
.css('z-index', LxDepthService.getDepth() + 1)
.on('wheel', function preventDefault(e) {
e.preventDefault();
});
}
dropdownMenu
.addClass('dropdown-menu--is-open')
.css('z-index', LxDepthService.getDepth() + 1)
.appendTo('body');
dropdownMenu.on('wheel', function preventDefault(e) {
var d = e.originalEvent.deltaY;
if (d < 0 && dropdownMenu.scrollTop() === 0) {
e.preventDefault();
}
else {
if (d > 0 && (dropdownMenu.scrollTop() == dropdownMenu.get(0).scrollHeight - dropdownMenu.innerHeight())) {
e.preventDefault();
}
}
});
if (lxDropdown.escapeClose)
{
idEventScheduler = LxEventSchedulerService.register('keyup', onKeyUp);
}
openTimeout = $timeout(function()
{
var availableHeight = initDropdownPosition() - ~~lxDropdown.offset;
var dropdownMenuHeight = dropdownMenu.outerHeight();
var dropdownMenuWidth = dropdownMenu.outerWidth();
var enoughHeight = true;
if (availableHeight < dropdownMenuHeight)
{
enoughHeight = false;
dropdownMenuHeight = availableHeight;
}
if (lxDropdown.effect === 'expand')
{
dropdownMenu.css(
{
width: 0,
height: 0,
opacity: 1,
overflow: 'hidden'
});
dropdownMenu.find('.dropdown-menu__content').css(
{
width: dropdownMenuWidth,
height: dropdownMenuHeight
});
dropdownMenu.velocity(
{
width: dropdownMenuWidth
},
{
duration: 200,
easing: 'easeOutQuint',
queue: false
});
dropdownMenu.velocity(
{
height: dropdownMenuHeight
},
{
duration: 500,
easing: 'easeOutQuint',
queue: false,
complete: function()
{
dropdownMenu.css(
{
overflow: 'auto'
});
if (angular.isUndefined(lxDropdown.width))
{
dropdownMenu.css(
{
width: 'auto'
});
}
$timeout(updateDropdownMenuHeight);
dropdownMenu.find('.dropdown-menu__content').removeAttr('style');
dropdownInterval = $interval(updateDropdownMenuHeight, 500);
}
});
}
else if (lxDropdown.effect === 'fade')
{
dropdownMenu.css(
{
height: dropdownMenuHeight
});
dropdownMenu.velocity(
{
opacity: 1,
},
{
duration: 200,
easing: 'linear',
queue: false,
complete: function()
{
$timeout(updateDropdownMenuHeight);
dropdownInterval = $interval(updateDropdownMenuHeight, 500);
}
});
}
else if (lxDropdown.effect === 'none')
{
dropdownMenu.css(
{
opacity: 1
});
$timeout(updateDropdownMenuHeight);
dropdownInterval = $interval(updateDropdownMenuHeight, 500);
}
});
}
function onKeyUp(_event)
{
if (_event.keyCode == 27)
{
closeDropdownMenu();
}
_event.stopPropagation();
}
function registerDropdownMenu(_dropdownMenu)
{
dropdownMenu = _dropdownMenu;
}
function registerDropdownToggle(_dropdownToggle)
{
if (!positionTarget)
{
lxDropdown.hasToggle = true;
}
dropdownToggle = _dropdownToggle;
}
function toggle()
{
if (!lxDropdown.isOpen)
{
openDropdownMenu();
}
else
{
closeDropdownMenu();
}
}
function updateDropdownMenuHeight()
{
if (positionTarget)
{
registerDropdownToggle(angular.element(positionTarget));
}
var availableHeight = getAvailableHeight();
var dropdownMenuHeight = dropdownMenu.find('.dropdown-menu__content').outerHeight();
dropdownMenu.css(
{
height: 'auto'
});
if ((availableHeight[availableHeight.direction] - ~~lxDropdown.offset) < dropdownMenuHeight)
{
if (availableHeight.direction === 'top')
{
dropdownMenu.css(
{
top: 0
});
}
else if (availableHeight.direction === 'bottom')
{
dropdownMenu.css(
{
bottom: 0
});
}
}
else
{
if (availableHeight.direction === 'top')
{
dropdownMenu.css(
{
top: 'auto'
});
}
else if (availableHeight.direction === 'bottom')
{
dropdownMenu.css(
{
bottom: 'auto'
});
}
}
}
}
lxDropdownToggle.$inject = ['$timeout', 'LxDropdownService'];
function lxDropdownToggle($timeout, LxDropdownService)
{
return {
restrict: 'AE',
templateUrl: 'dropdown-toggle.html',
require: '^lxDropdown',
scope: true,
link: link,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrl)
{
var hoverTimeout = [];
var mouseEvent = ctrl.hover ? 'mouseenter' : 'click';
ctrl.registerDropdownToggle(element);
element.on(mouseEvent, function(_event)
{
if (mouseEvent === 'mouseenter' && 'ontouchstart' in window) {
return;
}
if (!ctrl.hover)
{
_event.stopPropagation();
}
LxDropdownService.closeActiveDropdown();
LxDropdownService.registerActiveDropdownUuid(ctrl.uuid);
if (ctrl.hover)
{
ctrl.mouseOnToggle = true;
if (!ctrl.isOpen)
{
hoverTimeout[0] = $timeout(function()
{
scope.$apply(function()
{
ctrl.openDropdownMenu();
});
}, ctrl.hoverDelay);
}
}
else
{
scope.$apply(function()
{
ctrl.toggle();
});
}
});
if (ctrl.hover)
{
element.on('mouseleave', function()
{
ctrl.mouseOnToggle = false;
$timeout.cancel(hoverTimeout[0]);
hoverTimeout[1] = $timeout(function()
{
if (!ctrl.mouseOnMenu)
{
scope.$apply(function()
{
ctrl.closeDropdownMenu();
});
}
}, ctrl.hoverDelay);
});
}
scope.$on('$destroy', function()
{
element.off();
if (ctrl.hover)
{
$timeout.cancel(hoverTimeout[0]);
$timeout.cancel(hoverTimeout[1]);
}
});
}
}
lxDropdownMenu.$inject = ['$timeout'];
function lxDropdownMenu($timeout)
{
return {
restrict: 'E',
templateUrl: 'dropdown-menu.html',
require: ['lxDropdownMenu', '^lxDropdown'],
scope: true,
link: link,
controller: LxDropdownMenuController,
controllerAs: 'lxDropdownMenu',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrls)
{
var hoverTimeout;
ctrls[1].registerDropdownMenu(element);
ctrls[0].setParentController(ctrls[1]);
if (ctrls[1].hover)
{
element.on('mouseenter', function()
{
ctrls[1].mouseOnMenu = true;
});
element.on('mouseleave', function()
{
ctrls[1].mouseOnMenu = false;
hoverTimeout = $timeout(function()
{
if (!ctrls[1].mouseOnToggle)
{
scope.$apply(function()
{
ctrls[1].closeDropdownMenu();
});
}
}, ctrls[1].hoverDelay);
});
}
scope.$on('$destroy', function()
{
if (ctrls[1].hover)
{
element.off();
$timeout.cancel(hoverTimeout);
}
});
}
}
LxDropdownMenuController.$inject = ['$element'];
function LxDropdownMenuController($element)
{
var lxDropdownMenu = this;
lxDropdownMenu.setParentController = setParentController;
////////////
function addDropdownDepth()
{
if (lxDropdownMenu.parentCtrl.depth)
{
$element.addClass('dropdown-menu--depth-' + lxDropdownMenu.parentCtrl.depth);
}
else
{
$element.addClass('dropdown-menu--depth-1');
}
}
function setParentController(_parentCtrl)
{
lxDropdownMenu.parentCtrl = _parentCtrl;
addDropdownDepth();
}
}
lxDropdownFilter.$inject = ['$timeout'];
function lxDropdownFilter($timeout)
{
return {
restrict: 'A',
link: link
};
function link(scope, element)
{
var focusTimeout;
element.on('click', function(_event)
{
_event.stopPropagation();
});
focusTimeout = $timeout(function()
{
element.find('input').focus();
}, 200);
scope.$on('$destroy', function()
{
$timeout.cancel(focusTimeout);
element.off();
});
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.dropdown')
.service('LxDropdownService', LxDropdownService);
LxDropdownService.$inject = ['$document', '$rootScope', '$timeout'];
function LxDropdownService($document, $rootScope, $timeout)
{
var service = this;
var activeDropdownUuid;
service.close = close;
service.closeActiveDropdown = closeActiveDropdown;
service.open = open;
service.isOpen = isOpen;
service.registerActiveDropdownUuid = registerActiveDropdownUuid;
service.resetActiveDropdownUuid = resetActiveDropdownUuid;
$document.on('click', closeActiveDropdown);
////////////
function close(_uuid)
{
$rootScope.$broadcast('lx-dropdown__close',
{
uuid: _uuid
});
}
function closeActiveDropdown()
{
$rootScope.$broadcast('lx-dropdown__close',
{
uuid: activeDropdownUuid
});
}
function open(_uuid, _target)
{
$rootScope.$broadcast('lx-dropdown__open',
{
uuid: _uuid,
target: _target
});
}
function isOpen(_uuid)
{
return activeDropdownUuid === _uuid;
}
function registerActiveDropdownUuid(_uuid)
{
activeDropdownUuid = _uuid;
}
function resetActiveDropdownUuid()
{
activeDropdownUuid = undefined;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.fab')
.directive('lxFab', lxFab)
.directive('lxFabTrigger', lxFabTrigger)
.directive('lxFabActions', lxFabActions);
function lxFab()
{
return {
restrict: 'E',
templateUrl: 'fab.html',
scope: true,
link: link,
controller: LxFabController,
controllerAs: 'lxFab',
bindToController: true,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrl)
{
attrs.$observe('lxDirection', function(newDirection)
{
ctrl.setFabDirection(newDirection);
});
}
}
function LxFabController()
{
var lxFab = this;
lxFab.setFabDirection = setFabDirection;
////////////
function setFabDirection(_direction)
{
lxFab.lxDirection = _direction;
}
}
function lxFabTrigger()
{
return {
restrict: 'E',
require: '^lxFab',
templateUrl: 'fab-trigger.html',
transclude: true,
replace: true
};
}
function lxFabActions()
{
return {
restrict: 'E',
require: '^lxFab',
templateUrl: 'fab-actions.html',
link: link,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrl)
{
scope.parentCtrl = ctrl;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.file-input')
.directive('lxFileInput', lxFileInput);
function lxFileInput()
{
return {
restrict: 'E',
templateUrl: 'file-input.html',
scope:
{
label: '@lxLabel',
callback: '&?lxCallback'
},
link: link,
controller: LxFileInputController,
controllerAs: 'lxFileInput',
bindToController: true,
replace: true
};
function link(scope, element, attrs, ctrl)
{
var input = element.find('input');
input
.on('change', ctrl.updateModel)
.on('blur', function()
{
element.removeClass('input-file--is-focus');
});
scope.$on('$destroy', function()
{
input.off();
});
}
}
LxFileInputController.$inject = ['$element', '$scope', '$timeout'];
function LxFileInputController($element, $scope, $timeout)
{
var lxFileInput = this;
var input = $element.find('input');
var timer;
lxFileInput.updateModel = updateModel;
$scope.$on('$destroy', function()
{
$timeout.cancel(timer);
});
////////////
function setFileName()
{
if (input.val())
{
lxFileInput.fileName = input.val().replace(/C:\\fakepath\\/i, '');
$element.addClass('input-file--is-focus');
$element.addClass('input-file--is-active');
}
else
{
lxFileInput.fileName = undefined;
$element.removeClass('input-file--is-active');
}
input.val(undefined);
}
function updateModel()
{
if (angular.isDefined(lxFileInput.callback))
{
lxFileInput.callback(
{
newFile: input[0].files[0]
});
}
timer = $timeout(setFileName);
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.icon')
.directive('lxIcon', lxIcon);
function lxIcon()
{
return {
restrict: 'E',
templateUrl: 'icon.html',
scope:
{
color: '@?lxColor',
id: '@lxId',
size: '@?lxSize',
type: '@?lxType'
},
controller: LxIconController,
controllerAs: 'lxIcon',
bindToController: true,
replace: true
};
}
function LxIconController()
{
var lxIcon = this;
lxIcon.getClass = getClass;
////////////
function getClass()
{
var iconClass = [];
iconClass.push('mdi-' + lxIcon.id);
if (angular.isDefined(lxIcon.size))
{
iconClass.push('icon--' + lxIcon.size);
}
if (angular.isDefined(lxIcon.color))
{
iconClass.push('icon--' + lxIcon.color);
}
if (angular.isDefined(lxIcon.type))
{
iconClass.push('icon--' + lxIcon.type);
}
return iconClass;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.notification')
.service('LxNotificationService', LxNotificationService);
LxNotificationService.$inject = ['$injector', '$rootScope', '$timeout', 'LxDepthService', 'LxEventSchedulerService'];
function LxNotificationService($injector, $rootScope, $timeout, LxDepthService, LxEventSchedulerService)
{
var service = this;
var dialogFilter;
var dialog;
var idEventScheduler;
var notificationList = [];
var actionClicked = false;
service.alert = showAlertDialog;
service.confirm = showConfirmDialog;
service.error = notifyError;
service.info = notifyInfo;
service.notify = notify;
service.success = notifySuccess;
service.warning = notifyWarning;
////////////
//
// NOTIFICATION
//
function deleteNotification(_notification, _callback)
{
_callback = (!angular.isFunction(_callback)) ? angular.noop : _callback;
var notifIndex = notificationList.indexOf(_notification);
var dnOffset = angular.isDefined(notificationList[notifIndex]) ? 24 + notificationList[notifIndex].height : 24;
for (var idx = 0; idx < notifIndex; idx++)
{
if (notificationList.length > 1)
{
notificationList[idx].margin -= dnOffset;
notificationList[idx].elem.css('marginBottom', notificationList[idx].margin + 'px');
}
}
_notification.elem.removeClass('notification--is-shown');
$timeout(function()
{
_notification.elem.remove();
// Find index again because notificationList may have changed
notifIndex = notificationList.indexOf(_notification);
if (notifIndex != -1)
{
notificationList.splice(notifIndex, 1);
}
_callback(actionClicked);
actionClicked = false
}, 400);
}
function getElementHeight(_elem)
{
return parseFloat(window.getComputedStyle(_elem, null).height);
}
function moveNotificationUp()
{
var newNotifIndex = notificationList.length - 1;
notificationList[newNotifIndex].height = getElementHeight(notificationList[newNotifIndex].elem[0]);
var upOffset = 0;
for (var idx = newNotifIndex; idx >= 0; idx--)
{
if (notificationList.length > 1 && idx !== newNotifIndex)
{
upOffset = 24 + notificationList[newNotifIndex].height;
notificationList[idx].margin += upOffset;
notificationList[idx].elem.css('marginBottom', notificationList[idx].margin + 'px');
}
}
}
function notify(_text, _icon, _sticky, _color, _action, _callback, _delay)
{
var $compile = $injector.get('$compile');
LxDepthService.register();
var notification = angular.element('<div/>',
{
class: 'notification'
});
var notificationText = angular.element('<span/>',
{
class: 'notification__content',
html: _text
});
var notificationTimeout;
var notificationDelay = _delay || 6000;
if (angular.isDefined(_icon))
{
var notificationIcon = angular.element('<i/>',
{
class: 'notification__icon mdi mdi-' + _icon
});
notification
.addClass('notification--has-icon')
.append(notificationIcon);
}
if (angular.isDefined(_color))
{
notification.addClass('notification--' + _color);
}
notification.append(notificationText);
if (angular.isDefined(_action))
{
var notificationAction = angular.element('<button/>',
{
class: 'notification__action btn btn--m btn--flat',
html: _action
});
if (angular.isDefined(_color))
{
notificationAction.addClass('btn--' + _color);
}
else
{
notificationAction.addClass('btn--white');
}
notificationAction.attr('lx-ripple', '');
$compile(notificationAction)($rootScope);
notificationAction.bind('click', function()
{
actionClicked = true;
});
notification
.addClass('notification--has-action')
.append(notificationAction);
}
notification
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
$timeout(function()
{
notification.addClass('notification--is-shown');
}, 100);
var data = {
elem: notification,
margin: 0
};
notificationList.push(data);
moveNotificationUp();
notification.bind('click', function()
{
deleteNotification(data, _callback);
if (angular.isDefined(notificationTimeout))
{
$timeout.cancel(notificationTimeout);
}
});
if (angular.isUndefined(_sticky) || !_sticky)
{
notificationTimeout = $timeout(function()
{
deleteNotification(data, _callback);
}, notificationDelay);
}
}
function notifyError(_text, _sticky)
{
notify(_text, 'alert-circle', _sticky, 'red');
}
function notifyInfo(_text, _sticky)
{
notify(_text, 'information-outline', _sticky, 'blue');
}
function notifySuccess(_text, _sticky)
{
notify(_text, 'check', _sticky, 'green');
}
function notifyWarning(_text, _sticky)
{
notify(_text, 'alert', _sticky, 'orange');
}
//
// ALERT & CONFIRM
//
function buildDialogActions(_buttons, _callback, _unbind)
{
var $compile = $injector.get('$compile');
var dialogActions = angular.element('<div/>',
{
class: 'dialog__actions'
});
var dialogLastBtn = angular.element('<button/>',
{
class: 'btn btn--m btn--blue btn--flat',
text: _buttons.ok
});
if (angular.isDefined(_buttons.cancel))
{
var dialogFirstBtn = angular.element('<button/>',
{
class: 'btn btn--m btn--red btn--flat',
text: _buttons.cancel
});
dialogFirstBtn.attr('lx-ripple', '');
$compile(dialogFirstBtn)($rootScope);
dialogActions.append(dialogFirstBtn);
dialogFirstBtn.bind('click', function()
{
_callback(false);
closeDialog();
});
}
dialogLastBtn.attr('lx-ripple', '');
$compile(dialogLastBtn)($rootScope);
dialogActions.append(dialogLastBtn);
dialogLastBtn.bind('click', function()
{
_callback(true);
closeDialog();
});
if (!_unbind)
{
idEventScheduler = LxEventSchedulerService.register('keyup', function(event)
{
if (event.keyCode == 13)
{
_callback(true);
closeDialog();
}
else if (event.keyCode == 27)
{
_callback(angular.isUndefined(_buttons.cancel));
closeDialog();
}
event.stopPropagation();
});
}
return dialogActions;
}
function buildDialogContent(_text)
{
var dialogContent = angular.element('<div/>',
{
class: 'dialog__content p++ pt0 tc-black-2',
text: _text
});
return dialogContent;
}
function buildDialogHeader(_title)
{
var dialogHeader = angular.element('<div/>',
{
class: 'dialog__header p++ fs-title',
text: _title
});
return dialogHeader;
}
function closeDialog()
{
if (angular.isDefined(idEventScheduler))
{
$timeout(function()
{
LxEventSchedulerService.unregister(idEventScheduler);
idEventScheduler = undefined;
}, 1);
}
dialogFilter.removeClass('dialog-filter--is-shown');
dialog.removeClass('dialog--is-shown');
$timeout(function()
{
dialogFilter.remove();
dialog.remove();
}, 600);
}
function showAlertDialog(_title, _text, _button, _callback, _unbind)
{
LxDepthService.register();
dialogFilter = angular.element('<div/>',
{
class: 'dialog-filter'
});
dialog = angular.element('<div/>',
{
class: 'dialog dialog--alert'
});
var dialogHeader = buildDialogHeader(_title);
var dialogContent = buildDialogContent(_text);
var dialogActions = buildDialogActions(
{
ok: _button
}, _callback, _unbind);
dialogFilter
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
dialog
.append(dialogHeader)
.append(dialogContent)
.append(dialogActions)
.css('z-index', LxDepthService.getDepth() + 1)
.appendTo('body')
.show()
.focus();
$timeout(function()
{
angular.element(document.activeElement).blur();
dialogFilter.addClass('dialog-filter--is-shown');
dialog.addClass('dialog--is-shown');
}, 100);
}
function showConfirmDialog(_title, _text, _buttons, _callback, _unbind)
{
LxDepthService.register();
dialogFilter = angular.element('<div/>',
{
class: 'dialog-filter'
});
dialog = angular.element('<div/>',
{
class: 'dialog dialog--alert'
});
var dialogHeader = buildDialogHeader(_title);
var dialogContent = buildDialogContent(_text);
var dialogActions = buildDialogActions(_buttons, _callback, _unbind);
dialogFilter
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
dialog
.append(dialogHeader)
.append(dialogContent)
.append(dialogActions)
.css('z-index', LxDepthService.getDepth() + 1)
.appendTo('body')
.show()
.focus();
$timeout(function()
{
angular.element(document.activeElement).blur();
dialogFilter.addClass('dialog-filter--is-shown');
dialog.addClass('dialog--is-shown');
}, 100);
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.progress')
.directive('lxProgress', lxProgress);
function lxProgress()
{
return {
restrict: 'E',
templateUrl: 'progress.html',
scope:
{
lxColor: '@?',
lxDiameter: '@?',
lxType: '@',
lxValue: '@'
},
controller: LxProgressController,
controllerAs: 'lxProgress',
bindToController: true,
replace: true
};
}
function LxProgressController()
{
var lxProgress = this;
lxProgress.getCircularProgressValue = getCircularProgressValue;
lxProgress.getLinearProgressValue = getLinearProgressValue;
lxProgress.getProgressDiameter = getProgressDiameter;
init();
////////////
function getCircularProgressValue()
{
if (angular.isDefined(lxProgress.lxValue))
{
return {
'stroke-dasharray': lxProgress.lxValue * 1.26 + ',200'
};
}
}
function getLinearProgressValue()
{
if (angular.isDefined(lxProgress.lxValue))
{
return {
'transform': 'scale(' + lxProgress.lxValue / 100 + ', 1)'
};
}
}
function getProgressDiameter()
{
if (lxProgress.lxType === 'circular')
{
return {
'transform': 'scale(' + parseInt(lxProgress.lxDiameter) / 100 + ')'
};
}
return;
}
function init()
{
lxProgress.lxDiameter = angular.isDefined(lxProgress.lxDiameter) ? lxProgress.lxDiameter : 100;
lxProgress.lxColor = angular.isDefined(lxProgress.lxColor) ? lxProgress.lxColor : 'primary';
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.radio-button')
.directive('lxRadioGroup', lxRadioGroup)
.directive('lxRadioButton', lxRadioButton)
.directive('lxRadioButtonLabel', lxRadioButtonLabel)
.directive('lxRadioButtonHelp', lxRadioButtonHelp);
function lxRadioGroup()
{
return {
restrict: 'E',
templateUrl: 'radio-group.html',
transclude: true,
replace: true
};
}
function lxRadioButton()
{
return {
restrict: 'E',
templateUrl: 'radio-button.html',
scope:
{
lxColor: '@?',
name: '@',
ngChange: '&?',
ngDisabled: '=?',
ngModel: '=',
ngValue: '=?',
value: '@?'
},
controller: LxRadioButtonController,
controllerAs: 'lxRadioButton',
bindToController: true,
transclude: true,
replace: true
};
}
LxRadioButtonController.$inject = ['$scope', '$timeout', 'LxUtils'];
function LxRadioButtonController($scope, $timeout, LxUtils)
{
var lxRadioButton = this;
var radioButtonId;
var radioButtonHasChildren;
var timer;
lxRadioButton.getRadioButtonId = getRadioButtonId;
lxRadioButton.getRadioButtonHasChildren = getRadioButtonHasChildren;
lxRadioButton.setRadioButtonId = setRadioButtonId;
lxRadioButton.setRadioButtonHasChildren = setRadioButtonHasChildren;
lxRadioButton.triggerNgChange = triggerNgChange;
$scope.$on('$destroy', function()
{
$timeout.cancel(timer);
});
init();
////////////
function getRadioButtonId()
{
return radioButtonId;
}
function getRadioButtonHasChildren()
{
return radioButtonHasChildren;
}
function init()
{
setRadioButtonId(LxUtils.generateUUID());
setRadioButtonHasChildren(false);
if (angular.isDefined(lxRadioButton.value) && angular.isUndefined(lxRadioButton.ngValue))
{
lxRadioButton.ngValue = lxRadioButton.value;
}
lxRadioButton.lxColor = angular.isUndefined(lxRadioButton.lxColor) ? 'accent' : lxRadioButton.lxColor;
}
function setRadioButtonId(_radioButtonId)
{
radioButtonId = _radioButtonId;
}
function setRadioButtonHasChildren(_radioButtonHasChildren)
{
radioButtonHasChildren = _radioButtonHasChildren;
}
function triggerNgChange()
{
timer = $timeout(lxRadioButton.ngChange);
}
}
function lxRadioButtonLabel()
{
return {
restrict: 'AE',
require: ['^lxRadioButton', '^lxRadioButtonLabel'],
templateUrl: 'radio-button-label.html',
link: link,
controller: LxRadioButtonLabelController,
controllerAs: 'lxRadioButtonLabel',
bindToController: true,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].setRadioButtonHasChildren(true);
ctrls[1].setRadioButtonId(ctrls[0].getRadioButtonId());
}
}
function LxRadioButtonLabelController()
{
var lxRadioButtonLabel = this;
var radioButtonId;
lxRadioButtonLabel.getRadioButtonId = getRadioButtonId;
lxRadioButtonLabel.setRadioButtonId = setRadioButtonId;
////////////
function getRadioButtonId()
{
return radioButtonId;
}
function setRadioButtonId(_radioButtonId)
{
radioButtonId = _radioButtonId;
}
}
function lxRadioButtonHelp()
{
return {
restrict: 'AE',
require: '^lxRadioButton',
templateUrl: 'radio-button-help.html',
transclude: true,
replace: true
};
}
})();
(function()
{
'use strict';
angular
.module('lumx.ripple')
.directive('lxRipple', lxRipple);
lxRipple.$inject = ['$timeout'];
function lxRipple($timeout)
{
return {
restrict: 'A',
link: link,
};
function link(scope, element, attrs)
{
var timer;
element
.css(
{
position: 'relative',
overflow: 'hidden'
})
.on('mousedown', function(e)
{
var ripple;
if (element.find('.ripple').length === 0)
{
ripple = angular.element('<span/>',
{
class: 'ripple'
});
if (attrs.lxRipple)
{
ripple.addClass('bgc-' + attrs.lxRipple);
}
element.prepend(ripple);
}
else
{
ripple = element.find('.ripple');
}
ripple.removeClass('ripple--is-animated');
if (!ripple.height() && !ripple.width())
{
var diameter = Math.max(element.outerWidth(), element.outerHeight());
ripple.css(
{
height: diameter,
width: diameter
});
}
var x = e.pageX - element.offset().left - ripple.width() / 2;
var y = e.pageY - element.offset().top - ripple.height() / 2;
ripple.css(
{
top: y + 'px',
left: x + 'px'
}).addClass('ripple--is-animated');
timer = $timeout(function()
{
ripple.removeClass('ripple--is-animated');
}, 651);
});
scope.$on('$destroy', function()
{
$timeout.cancel(timer);
element.off();
});
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.search-filter')
.filter('lxSearchHighlight', lxSearchHighlight)
.directive('lxSearchFilter', lxSearchFilter);
lxSearchHighlight.$inject = ['$sce'];
function lxSearchHighlight($sce)
{
function escapeRegexp(queryToEscape)
{
return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}
return function (matchItem, query, icon)
{
var string = '';
if (icon)
{
string += '<i class="mdi mdi-' + icon + '"></i>';
}
string += query && matchItem ? matchItem.replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem;
return $sce.trustAsHtml(string);
};
}
function lxSearchFilter()
{
return {
restrict: 'E',
templateUrl: 'search-filter.html',
scope:
{
autocomplete: '&?lxAutocomplete',
closed: '=?lxClosed',
color: '@?lxColor',
icon: '@?lxIcon',
onSelect: '=?lxOnSelect',
searchOnFocus: '=?lxSearchOnFocus',
theme: '@?lxTheme',
width: '@?lxWidth'
},
link: link,
controller: LxSearchFilterController,
controllerAs: 'lxSearchFilter',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrl, transclude)
{
var input;
attrs.$observe('lxWidth', function(newWidth)
{
if (angular.isDefined(scope.lxSearchFilter.closed) && scope.lxSearchFilter.closed)
{
element.find('.search-filter__container').css('width', newWidth);
}
});
transclude(function()
{
input = element.find('input');
ctrl.setInput(input);
ctrl.setModel(input.data('$ngModelController'));
input.on('focus', ctrl.focusInput);
input.on('blur', ctrl.blurInput);
input.on('keydown', ctrl.keyEvent);
});
scope.$on('$destroy', function()
{
input.off();
});
}
}
LxSearchFilterController.$inject = ['$element', '$scope', 'LxDropdownService', 'LxNotificationService', 'LxUtils'];
function LxSearchFilterController($element, $scope, LxDropdownService, LxNotificationService, LxUtils)
{
var lxSearchFilter = this;
var debouncedAutocomplete;
var input;
var itemSelected = false;
lxSearchFilter.blurInput = blurInput;
lxSearchFilter.clearInput = clearInput;
lxSearchFilter.focusInput = focusInput;
lxSearchFilter.getClass = getClass;
lxSearchFilter.keyEvent = keyEvent;
lxSearchFilter.openInput = openInput;
lxSearchFilter.selectItem = selectItem;
lxSearchFilter.setInput = setInput;
lxSearchFilter.setModel = setModel;
lxSearchFilter.activeChoiceIndex = -1;
lxSearchFilter.color = angular.isDefined(lxSearchFilter.color) ? lxSearchFilter.color : 'black';
lxSearchFilter.dropdownId = LxUtils.generateUUID();
lxSearchFilter.theme = angular.isDefined(lxSearchFilter.theme) ? lxSearchFilter.theme : 'light';
////////////
function blurInput()
{
if (angular.isDefined(lxSearchFilter.closed) && lxSearchFilter.closed && !input.val())
{
$element.velocity(
{
width: 40
},
{
duration: 400,
easing: 'easeOutQuint',
queue: false
});
}
if (!input.val())
{
lxSearchFilter.modelController.$setViewValue(undefined);
}
}
function clearInput()
{
lxSearchFilter.modelController.$setViewValue(undefined);
lxSearchFilter.modelController.$render();
// Temporarily disabling search on focus since we never want to trigger it when clearing the input.
var searchOnFocus = lxSearchFilter.searchOnFocus;
lxSearchFilter.searchOnFocus = false;
input.focus();
lxSearchFilter.searchOnFocus = searchOnFocus;
}
function focusInput()
{
if (!lxSearchFilter.searchOnFocus)
{
return;
}
updateAutocomplete(lxSearchFilter.modelController.$viewValue, true);
}
function getClass()
{
var searchFilterClass = [];
if (angular.isUndefined(lxSearchFilter.closed) || !lxSearchFilter.closed)
{
searchFilterClass.push('search-filter--opened-mode');
}
if (angular.isDefined(lxSearchFilter.closed) && lxSearchFilter.closed)
{
searchFilterClass.push('search-filter--closed-mode');
}
if (input.val())
{
searchFilterClass.push('search-filter--has-clear-button');
}
if (angular.isDefined(lxSearchFilter.color))
{
searchFilterClass.push('search-filter--' + lxSearchFilter.color);
}
if (angular.isDefined(lxSearchFilter.theme))
{
searchFilterClass.push('search-filter--theme-' + lxSearchFilter.theme);
}
if (angular.isFunction(lxSearchFilter.autocomplete))
{
searchFilterClass.push('search-filter--autocomplete');
}
if (LxDropdownService.isOpen(lxSearchFilter.dropdownId))
{
searchFilterClass.push('search-filter--is-open');
}
return searchFilterClass;
}
function keyEvent(_event)
{
if (!angular.isFunction(lxSearchFilter.autocomplete))
{
return;
}
if (!LxDropdownService.isOpen(lxSearchFilter.dropdownId))
{
lxSearchFilter.activeChoiceIndex = -1;
}
switch (_event.keyCode) {
case 13:
keySelect();
if (lxSearchFilter.activeChoiceIndex > -1)
{
_event.preventDefault();
}
break;
case 38:
keyUp();
_event.preventDefault();
break;
case 40:
keyDown();
_event.preventDefault();
break;
}
$scope.$apply();
}
function keyDown()
{
if (lxSearchFilter.autocompleteList.length)
{
lxSearchFilter.activeChoiceIndex += 1;
if (lxSearchFilter.activeChoiceIndex >= lxSearchFilter.autocompleteList.length)
{
lxSearchFilter.activeChoiceIndex = 0;
}
}
}
function keySelect()
{
if (!lxSearchFilter.autocompleteList || lxSearchFilter.activeChoiceIndex === -1)
{
return;
}
selectItem(lxSearchFilter.autocompleteList[lxSearchFilter.activeChoiceIndex]);
}
function keyUp()
{
if (lxSearchFilter.autocompleteList.length)
{
lxSearchFilter.activeChoiceIndex -= 1;
if (lxSearchFilter.activeChoiceIndex < 0)
{
lxSearchFilter.activeChoiceIndex = lxSearchFilter.autocompleteList.length - 1;
}
}
}
function onAutocompleteSuccess(autocompleteList)
{
lxSearchFilter.autocompleteList = autocompleteList;
if (lxSearchFilter.autocompleteList.length)
{
LxDropdownService.open(lxSearchFilter.dropdownId, $element);
}
else
{
LxDropdownService.close(lxSearchFilter.dropdownId);
}
lxSearchFilter.isLoading = false;
}
function onAutocompleteError(error)
{
LxNotificationService.error(error);
lxSearchFilter.isLoading = false;
}
function openInput()
{
if (angular.isDefined(lxSearchFilter.closed) && lxSearchFilter.closed)
{
$element.velocity(
{
width: angular.isDefined(lxSearchFilter.width) ? parseInt(lxSearchFilter.width) : 240
},
{
duration: 400,
easing: 'easeOutQuint',
queue: false,
complete: function()
{
input.focus();
}
});
}
else
{
input.focus();
}
}
function selectItem(_item)
{
itemSelected = true;
LxDropdownService.close(lxSearchFilter.dropdownId);
lxSearchFilter.modelController.$setViewValue(_item);
lxSearchFilter.modelController.$render();
if (angular.isFunction(lxSearchFilter.onSelect))
{
lxSearchFilter.onSelect(_item);
}
}
function setInput(_input)
{
input = _input;
}
function setModel(_modelController)
{
lxSearchFilter.modelController = _modelController;
if (angular.isFunction(lxSearchFilter.autocomplete) && angular.isFunction(lxSearchFilter.autocomplete()))
{
debouncedAutocomplete = LxUtils.debounce(function()
{
lxSearchFilter.isLoading = true;
(lxSearchFilter.autocomplete()).apply(this, arguments);
}, 500);
lxSearchFilter.modelController.$parsers.push(updateAutocomplete);
}
}
function updateAutocomplete(_newValue, _immediate)
{
if ((_newValue || (angular.isUndefined(_newValue) && lxSearchFilter.searchOnFocus)) && !itemSelected)
{
if (_immediate)
{
lxSearchFilter.isLoading = true;
(lxSearchFilter.autocomplete())(_newValue, onAutocompleteSuccess, onAutocompleteError);
}
else
{
debouncedAutocomplete(_newValue, onAutocompleteSuccess, onAutocompleteError);
}
}
else
{
debouncedAutocomplete.clear();
LxDropdownService.close(lxSearchFilter.dropdownId);
}
itemSelected = false;
return _newValue;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.select')
.filter('filterChoices', filterChoices)
.directive('lxSelect', lxSelect)
.directive('lxSelectSelected', lxSelectSelected)
.directive('lxSelectChoices', lxSelectChoices);
filterChoices.$inject = ['$filter'];
function filterChoices($filter)
{
return function(choices, externalFilter, textFilter)
{
if (externalFilter)
{
return choices;
}
var toFilter = [];
if (!angular.isArray(choices))
{
if (angular.isObject(choices))
{
for (var idx in choices)
{
if (angular.isArray(choices[idx]))
{
toFilter = toFilter.concat(choices[idx]);
}
}
}
}
else
{
toFilter = choices;
}
return $filter('filter')(toFilter, textFilter);
};
}
function lxSelect()
{
return {
restrict: 'E',
templateUrl: 'select.html',
scope:
{
allowClear: '=?lxAllowClear',
allowNewValue: '=?lxAllowNewValue',
autocomplete: '=?lxAutocomplete',
newValueTransform: '=?lxNewValueTransform',
choices: '=?lxChoices',
choicesCustomStyle: '=?lxChoicesCustomStyle',
customStyle: '=?lxCustomStyle',
displayFilter: '=?lxDisplayFilter',
error: '=?lxError',
filter: '&?lxFilter',
fixedLabel: '=?lxFixedLabel',
helper: '=?lxHelper',
helperMessage: '@?lxHelperMessage',
label: '@?lxLabel',
loading: '=?lxLoading',
modelToSelection: '&?lxModelToSelection',
multiple: '=?lxMultiple',
ngChange: '&?',
ngDisabled: '=?',
ngModel: '=',
selectionToModel: '&?lxSelectionToModel',
theme: '@?lxTheme',
valid: '=?lxValid',
viewMode: '@?lxViewMode'
},
link: link,
controller: LxSelectController,
controllerAs: 'lxSelect',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs)
{
var backwardOneWay = ['customStyle'];
var backwardTwoWay = ['allowClear', 'choices', 'error', 'loading', 'multiple', 'valid'];
angular.forEach(backwardOneWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
attrs.$observe(attribute, function(newValue)
{
scope.lxSelect[attribute] = newValue;
});
}
});
angular.forEach(backwardTwoWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
scope.$watch(function()
{
return scope.$parent.$eval(attrs[attribute]);
}, function(newValue)
{
if (attribute === 'multiple' && angular.isUndefined(newValue))
{
scope.lxSelect[attribute] = true;
}
else
{
scope.lxSelect[attribute] = newValue;
}
});
}
});
attrs.$observe('placeholder', function(newValue)
{
scope.lxSelect.label = newValue;
});
attrs.$observe('change', function(newValue)
{
scope.lxSelect.ngChange = function(data)
{
return scope.$parent.$eval(newValue, data);
};
});
attrs.$observe('filter', function(newValue)
{
scope.lxSelect.filter = function(data)
{
return scope.$parent.$eval(newValue, data);
};
scope.lxSelect.displayFilter = true;
});
attrs.$observe('modelToSelection', function(newValue)
{
scope.lxSelect.modelToSelection = function(data)
{
return scope.$parent.$eval(newValue, data);
};
});
attrs.$observe('selectionToModel', function(newValue)
{
scope.lxSelect.selectionToModel = function(data)
{
return scope.$parent.$eval(newValue, data);
};
});
}
}
LxSelectController.$inject = ['$interpolate', '$element', '$filter', '$sce', 'LxDropdownService', 'LxUtils'];
function LxSelectController($interpolate, $element, $filter, $sce, LxDropdownService, LxUtils)
{
var lxSelect = this;
var choiceTemplate;
var selectedTemplate;
lxSelect.displayChoice = displayChoice;
lxSelect.displaySelected = displaySelected;
lxSelect.displaySubheader = displaySubheader;
lxSelect.getFilteredChoices = getFilteredChoices;
lxSelect.getSelectedModel = getSelectedModel;
lxSelect.isSelected = isSelected;
lxSelect.keyEvent = keyEvent;
lxSelect.registerChoiceTemplate = registerChoiceTemplate;
lxSelect.registerSelectedTemplate = registerSelectedTemplate;
lxSelect.select = select;
lxSelect.toggleChoice = toggleChoice;
lxSelect.unselect = unselect;
lxSelect.updateFilter = updateFilter;
lxSelect.helperDisplayable = helperDisplayable;
lxSelect.activeChoiceIndex = -1;
lxSelect.activeSelectedIndex = -1;
lxSelect.uuid = LxUtils.generateUUID();
lxSelect.filterModel = undefined;
lxSelect.ngModel = angular.isUndefined(lxSelect.ngModel) && lxSelect.multiple ? [] : lxSelect.ngModel;
lxSelect.unconvertedModel = lxSelect.multiple ? [] : undefined;
lxSelect.viewMode = angular.isUndefined(lxSelect.viewMode) ? 'field' : 'chips';
////////////
function arrayObjectIndexOf(arr, obj)
{
for (var i = 0; i < arr.length; i++)
{
if (angular.equals(arr[i], obj))
{
return i;
}
}
return -1;
}
function displayChoice(_choice)
{
var choiceScope = {
$choice: _choice
};
return $sce.trustAsHtml($interpolate(choiceTemplate)(choiceScope));
}
function displaySelected(_selected)
{
var selectedScope = {};
if (!angular.isArray(lxSelect.choices))
{
var found = false;
for (var header in lxSelect.choices)
{
if (found)
{
break;
}
if (lxSelect.choices.hasOwnProperty(header))
{
for (var idx = 0, len = lxSelect.choices[header].length; idx < len; idx++)
{
if (angular.equals(_selected, lxSelect.choices[header][idx]))
{
selectedScope.$selectedSubheader = header;
found = true;
break;
}
}
}
}
}
if (angular.isDefined(_selected))
{
selectedScope.$selected = _selected;
}
else
{
selectedScope.$selected = getSelectedModel();
}
return $sce.trustAsHtml($interpolate(selectedTemplate)(selectedScope));
}
function displaySubheader(_subheader)
{
return $sce.trustAsHtml(_subheader);
}
function getFilteredChoices()
{
return $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel);
}
function getSelectedModel()
{
if (angular.isDefined(lxSelect.modelToSelection) || angular.isDefined(lxSelect.selectionToModel))
{
return lxSelect.unconvertedModel;
}
else
{
return lxSelect.ngModel;
}
}
function isSelected(_choice)
{
if (lxSelect.multiple && angular.isDefined(getSelectedModel()))
{
return arrayObjectIndexOf(getSelectedModel(), _choice) !== -1;
}
else if (angular.isDefined(getSelectedModel()))
{
return angular.equals(getSelectedModel(), _choice);
}
}
function keyEvent(_event)
{
if (_event.keyCode !== 8)
{
lxSelect.activeSelectedIndex = -1;
}
if (!LxDropdownService.isOpen('dropdown-' + lxSelect.uuid))
{
lxSelect.activeChoiceIndex = -1;
}
switch (_event.keyCode) {
case 8:
keyRemove();
break;
case 13:
keySelect();
_event.preventDefault();
break;
case 38:
keyUp();
_event.preventDefault();
break;
case 40:
keyDown();
_event.preventDefault();
break;
}
}
function keyDown()
{
var filteredChoices = $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel);
if (filteredChoices.length)
{
lxSelect.activeChoiceIndex += 1;
if (lxSelect.activeChoiceIndex >= filteredChoices.length)
{
lxSelect.activeChoiceIndex = 0;
}
}
if (lxSelect.autocomplete)
{
LxDropdownService.open('dropdown-' + lxSelect.uuid, '#lx-select-selected-wrapper-' + lxSelect.uuid);
}
}
function keyRemove()
{
if (lxSelect.filterModel || !lxSelect.getSelectedModel().length)
{
return;
}
if (lxSelect.activeSelectedIndex === -1)
{
lxSelect.activeSelectedIndex = lxSelect.getSelectedModel().length - 1;
}
else
{
unselect(lxSelect.getSelectedModel()[lxSelect.activeSelectedIndex]);
}
}
function keySelect()
{
var filteredChoices = $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel);
if (filteredChoices.length && filteredChoices[lxSelect.activeChoiceIndex])
{
toggleChoice(filteredChoices[lxSelect.activeChoiceIndex]);
}
else if (lxSelect.filterModel && lxSelect.allowNewValue)
{
if (angular.isArray(getSelectedModel()))
{
var value = angular.isFunction(lxSelect.newValueTransform) ? lxSelect.newValueTransform(lxSelect.filterModel) : lxSelect.filterModel;
var identical = getSelectedModel().some(function (item) {
return angular.equals(item, value);
});
if (!identical)
{
getSelectedModel().push(value);
}
}
lxSelect.filterModel = undefined;
LxDropdownService.close('dropdown-' + lxSelect.uuid);
}
}
function keyUp()
{
var filteredChoices = $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel);
if (filteredChoices.length)
{
lxSelect.activeChoiceIndex -= 1;
if (lxSelect.activeChoiceIndex < 0)
{
lxSelect.activeChoiceIndex = filteredChoices.length - 1;
}
}
if (lxSelect.autocomplete)
{
LxDropdownService.open('dropdown-' + lxSelect.uuid, '#lx-select-selected-wrapper-' + lxSelect.uuid);
}
}
function registerChoiceTemplate(_choiceTemplate)
{
choiceTemplate = _choiceTemplate;
}
function registerSelectedTemplate(_selectedTemplate)
{
selectedTemplate = _selectedTemplate;
}
function select(_choice)
{
if (lxSelect.multiple && angular.isUndefined(lxSelect.ngModel))
{
lxSelect.ngModel = [];
}
if (angular.isDefined(lxSelect.selectionToModel))
{
lxSelect.selectionToModel(
{
data: _choice,
callback: function(resp)
{
if (lxSelect.multiple)
{
lxSelect.ngModel.push(resp);
}
else
{
lxSelect.ngModel = resp;
}
if (lxSelect.autocomplete)
{
$element.find('.lx-select-selected__filter').focus();
}
}
});
}
else
{
if (lxSelect.multiple)
{
lxSelect.ngModel.push(_choice);
}
else
{
lxSelect.ngModel = _choice;
}
if (lxSelect.autocomplete)
{
$element.find('.lx-select-selected__filter').focus();
}
}
}
function toggleChoice(_choice, _event)
{
if (lxSelect.multiple && !lxSelect.autocomplete)
{
_event.stopPropagation();
}
if (lxSelect.multiple && isSelected(_choice))
{
unselect(_choice);
}
else
{
select(_choice);
}
if (lxSelect.autocomplete)
{
lxSelect.activeChoiceIndex = -1;
lxSelect.filterModel = undefined;
LxDropdownService.close('dropdown-' + lxSelect.uuid);
}
}
function unselect(_choice)
{
if (angular.isDefined(lxSelect.selectionToModel))
{
lxSelect.selectionToModel(
{
data: _choice,
callback: function(resp)
{
removeElement(lxSelect.ngModel, resp);
if (lxSelect.autocomplete)
{
$element.find('.lx-select-selected__filter').focus();
lxSelect.activeSelectedIndex = -1;
}
}
});
removeElement(lxSelect.unconvertedModel, _choice);
}
else
{
removeElement(lxSelect.ngModel, _choice);
if (lxSelect.autocomplete)
{
$element.find('.lx-select-selected__filter').focus();
lxSelect.activeSelectedIndex = -1;
}
}
}
function updateFilter()
{
if (angular.isDefined(lxSelect.filter))
{
lxSelect.filter(
{
newValue: lxSelect.filterModel
});
}
if (lxSelect.autocomplete)
{
lxSelect.activeChoiceIndex = -1;
if (lxSelect.filterModel)
{
LxDropdownService.open('dropdown-' + lxSelect.uuid, '#lx-select-selected-wrapper-' + lxSelect.uuid);
}
else
{
LxDropdownService.close('dropdown-' + lxSelect.uuid);
}
}
}
function helperDisplayable() {
// If helper message is not defined, message is not displayed...
if (angular.isUndefined(lxSelect.helperMessage))
{
return false;
}
// If helper is defined return it's state.
if (angular.isDefined(lxSelect.helper))
{
return lxSelect.helper;
}
// Else check if there's choices.
var choices = lxSelect.getFilteredChoices();
if (angular.isArray(choices))
{
return !choices.length;
}
else if (angular.isObject(choices))
{
return !Object.keys(choices).length;
}
return true;
}
function removeElement(model, element)
{
var index = -1;
for (var i = 0, len = model.length; i < len; i++)
{
if (angular.equals(element, model[i]))
{
index = i;
break;
}
}
if (index > -1)
{
model.splice(index, 1);
}
}
}
function lxSelectSelected()
{
return {
restrict: 'E',
require: ['lxSelectSelected', '^lxSelect'],
templateUrl: 'select-selected.html',
link: link,
controller: LxSelectSelectedController,
controllerAs: 'lxSelectSelected',
bindToController: true,
transclude: true
};
function link(scope, element, attrs, ctrls, transclude)
{
ctrls[0].setParentController(ctrls[1]);
transclude(scope, function(clone)
{
var template = '';
for (var i = 0; i < clone.length; i++)
{
template += clone[i].data || clone[i].outerHTML || '';
}
ctrls[1].registerSelectedTemplate(template);
});
}
}
function LxSelectSelectedController()
{
var lxSelectSelected = this;
lxSelectSelected.clearModel = clearModel;
lxSelectSelected.setParentController = setParentController;
lxSelectSelected.removeSelected = removeSelected;
////////////
function clearModel(_event)
{
_event.stopPropagation();
lxSelectSelected.parentCtrl.ngModel = undefined;
lxSelectSelected.parentCtrl.unconvertedModel = undefined;
}
function setParentController(_parentCtrl)
{
lxSelectSelected.parentCtrl = _parentCtrl;
}
function removeSelected(_selected, _event)
{
_event.stopPropagation();
lxSelectSelected.parentCtrl.unselect(_selected);
}
}
function lxSelectChoices()
{
return {
restrict: 'E',
require: ['lxSelectChoices', '^lxSelect'],
templateUrl: 'select-choices.html',
link: link,
controller: LxSelectChoicesController,
controllerAs: 'lxSelectChoices',
bindToController: true,
transclude: true
};
function link(scope, element, attrs, ctrls, transclude)
{
ctrls[0].setParentController(ctrls[1]);
transclude(scope, function(clone)
{
var template = '';
for (var i = 0; i < clone.length; i++)
{
template += clone[i].data || clone[i].outerHTML || '';
}
ctrls[1].registerChoiceTemplate(template);
});
}
}
LxSelectChoicesController.$inject = ['$scope', '$timeout'];
function LxSelectChoicesController($scope, $timeout)
{
var lxSelectChoices = this;
var timer;
lxSelectChoices.isArray = isArray;
lxSelectChoices.setParentController = setParentController;
$scope.$on('$destroy', function()
{
$timeout.cancel(timer);
});
////////////
function isArray()
{
return angular.isArray(lxSelectChoices.parentCtrl.choices);
}
function setParentController(_parentCtrl)
{
lxSelectChoices.parentCtrl = _parentCtrl;
$scope.$watch(function()
{
return lxSelectChoices.parentCtrl.ngModel;
}, function(newModel, oldModel)
{
timer = $timeout(function()
{
if (newModel !== oldModel && angular.isDefined(lxSelectChoices.parentCtrl.ngChange))
{
lxSelectChoices.parentCtrl.ngChange(
{
newValue: newModel,
oldValue: oldModel
});
}
if (angular.isDefined(lxSelectChoices.parentCtrl.modelToSelection) || angular.isDefined(lxSelectChoices.parentCtrl.selectionToModel))
{
toSelection();
}
});
}, true);
}
function toSelection()
{
if (lxSelectChoices.parentCtrl.multiple)
{
lxSelectChoices.parentCtrl.unconvertedModel = [];
angular.forEach(lxSelectChoices.parentCtrl.ngModel, function(item)
{
lxSelectChoices.parentCtrl.modelToSelection(
{
data: item,
callback: function(resp)
{
lxSelectChoices.parentCtrl.unconvertedModel.push(resp);
}
});
});
}
else
{
lxSelectChoices.parentCtrl.modelToSelection(
{
data: lxSelectChoices.parentCtrl.ngModel,
callback: function(resp)
{
lxSelectChoices.parentCtrl.unconvertedModel = resp;
}
});
}
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.stepper')
.directive('lxStepper', lxStepper)
.directive('lxStep', lxStep)
.directive('lxStepNav', lxStepNav);
/* Stepper */
function lxStepper()
{
return {
restrict: 'E',
templateUrl: 'stepper.html',
scope: {
cancel: '&?lxCancel',
complete: '&lxComplete',
isLinear: '=?lxIsLinear',
labels: '=?lxLabels',
layout: '@?lxLayout'
},
controller: LxStepperController,
controllerAs: 'lxStepper',
bindToController: true,
transclude: true
};
}
function LxStepperController()
{
var lxStepper = this;
var _classes = [];
var _defaultValues = {
isLinear: true,
labels: {
'back': 'Back',
'cancel': 'Cancel',
'continue': 'Continue',
'optional': 'Optional'
},
layout: 'horizontal'
};
lxStepper.addStep = addStep;
lxStepper.getClasses = getClasses;
lxStepper.goToStep = goToStep;
lxStepper.isComplete = isComplete;
lxStepper.updateStep = updateStep;
lxStepper.activeIndex = 0;
lxStepper.isLinear = angular.isDefined(lxStepper.isLinear) ? lxStepper.isLinear : _defaultValues.isLinear;
lxStepper.labels = angular.isDefined(lxStepper.labels) ? lxStepper.labels : _defaultValues.labels;
lxStepper.layout = angular.isDefined(lxStepper.layout) ? lxStepper.layout : _defaultValues.layout;
lxStepper.steps = [];
////////////
function addStep(step)
{
lxStepper.steps.push(step);
}
function getClasses()
{
_classes.length = 0;
_classes.push('lx-stepper--layout-' + lxStepper.layout);
if (lxStepper.isLinear)
{
_classes.push('lx-stepper--is-linear');
}
if (lxStepper.steps[lxStepper.activeIndex].feedback)
{
_classes.push('lx-stepper--step-has-feedback');
}
if (lxStepper.steps[lxStepper.activeIndex].isLoading)
{
_classes.push('lx-stepper--step-is-loading');
}
return _classes;
}
function goToStep(index, bypass)
{
// Check if the the wanted step previous steps are optionals. If so, check if the step before the last optional step is valid to allow going to the wanted step from the nav (only if linear stepper).
var stepBeforeLastOptionalStep;
if (!bypass && lxStepper.isLinear)
{
for (var i = index - 1; i >= 0; i--)
{
if (angular.isDefined(lxStepper.steps[i]) && !lxStepper.steps[i].isOptional)
{
stepBeforeLastOptionalStep = lxStepper.steps[i];
break;
}
}
if (angular.isDefined(stepBeforeLastOptionalStep) && stepBeforeLastOptionalStep.isValid === true)
{
bypass = true;
}
}
// Check if the wanted step previous step is not valid to disallow going to the wanted step from the nav (only if linear stepper).
if (!bypass && lxStepper.isLinear && angular.isDefined(lxStepper.steps[index - 1]) && (angular.isUndefined(lxStepper.steps[index - 1].isValid) || lxStepper.steps[index - 1].isValid === false))
{
return;
}
if (index < lxStepper.steps.length)
{
lxStepper.activeIndex = parseInt(index);
}
}
function isComplete()
{
var countMandatory = 0;
var countValid = 0;
for (var i = 0, len = lxStepper.steps.length; i < len; i++)
{
if (!lxStepper.steps[i].isOptional)
{
countMandatory++;
if (lxStepper.steps[i].isValid === true) {
countValid++;
}
}
}
if (countValid === countMandatory)
{
lxStepper.complete();
return true;
}
}
function updateStep(step)
{
for (var i = 0, len = lxStepper.steps.length; i < len; i++)
{
if (lxStepper.steps[i].uuid === step.uuid)
{
lxStepper.steps[i].index = step.index;
lxStepper.steps[i].label = step.label;
return;
}
}
}
}
/* Step */
function lxStep()
{
return {
restrict: 'E',
require: ['lxStep', '^lxStepper'],
templateUrl: 'step.html',
scope: {
feedback: '@?lxFeedback',
isEditable: '=?lxIsEditable',
isOptional: '=?lxIsOptional',
label: '@lxLabel',
submit: '&?lxSubmit',
validate: '&?lxValidate'
},
link: link,
controller: LxStepController,
controllerAs: 'lxStep',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].init(ctrls[1], element.index());
attrs.$observe('lxFeedback', function(feedback)
{
ctrls[0].setFeedback(feedback);
});
attrs.$observe('lxLabel', function(label)
{
ctrls[0].setLabel(label);
});
attrs.$observe('lxIsEditable', function(isEditable)
{
ctrls[0].setIsEditable(isEditable);
});
attrs.$observe('lxIsOptional', function(isOptional)
{
ctrls[0].setIsOptional(isOptional);
});
}
}
LxStepController.$inject = ['$q', 'LxNotificationService', 'LxUtils'];
function LxStepController($q, LxNotificationService, LxUtils)
{
var lxStep = this;
var _classes = [];
var _nextStepIndex;
lxStep.getClasses = getClasses;
lxStep.init = init;
lxStep.previousStep = previousStep;
lxStep.setFeedback = setFeedback;
lxStep.setLabel = setLabel;
lxStep.setIsEditable = setIsEditable;
lxStep.setIsOptional = setIsOptional;
lxStep.submitStep = submitStep;
lxStep.step = {
errorMessage: undefined,
feedback: undefined,
index: undefined,
isEditable: false,
isLoading: false,
isOptional: false,
isValid: undefined,
label: undefined,
uuid: LxUtils.generateUUID()
};
////////////
function getClasses()
{
_classes.length = 0;
if (lxStep.step.index === lxStep.parent.activeIndex)
{
_classes.push('lx-step--is-active');
}
return _classes;
}
function init(parent, index)
{
lxStep.parent = parent;
lxStep.step.index = index;
lxStep.parent.addStep(lxStep.step);
}
function previousStep()
{
if (lxStep.step.index > 0)
{
lxStep.parent.goToStep(lxStep.step.index - 1);
}
}
function setFeedback(feedback)
{
lxStep.step.feedback = feedback;
updateParentStep();
}
function setLabel(label)
{
lxStep.step.label = label;
updateParentStep();
}
function setIsEditable(isEditable)
{
lxStep.step.isEditable = isEditable;
updateParentStep();
}
function setIsOptional(isOptional)
{
lxStep.step.isOptional = isOptional;
updateParentStep();
}
function submitStep()
{
if (lxStep.step.isValid === true && !lxStep.step.isEditable)
{
lxStep.parent.goToStep(_nextStepIndex, true);
return;
}
var validateFunction = lxStep.validate;
var validity = true;
if (angular.isFunction(validateFunction))
{
validity = validateFunction();
}
if (validity === true)
{
lxStep.step.isLoading = true;
updateParentStep();
var submitFunction = lxStep.submit;
if (!angular.isFunction(submitFunction))
{
submitFunction = function()
{
return $q(function(resolve)
{
resolve();
});
};
}
var promise = submitFunction();
promise.then(function(nextStepIndex)
{
lxStep.step.isValid = true;
updateParentStep();
var isComplete = lxStep.parent.isComplete();
if (!isComplete)
{
_nextStepIndex = angular.isDefined(nextStepIndex) && nextStepIndex > lxStep.parent.activeIndex && (!lxStep.parent.isLinear || (lxStep.parent.isLinear && lxStep.parent.steps[nextStepIndex - 1].isOptional)) ? nextStepIndex : lxStep.step.index + 1;
lxStep.parent.goToStep(_nextStepIndex, true);
}
}).catch(function(error)
{
LxNotificationService.error(error);
}).finally(function()
{
lxStep.step.isLoading = false;
updateParentStep();
});
}
else
{
lxStep.step.isValid = false;
lxStep.step.errorMessage = validity;
updateParentStep();
}
}
function updateParentStep()
{
lxStep.parent.updateStep(lxStep.step);
}
}
/* Step nav */
function lxStepNav()
{
return {
restrict: 'E',
require: ['lxStepNav', '^lxStepper'],
templateUrl: 'step-nav.html',
scope: {
activeIndex: '@lxActiveIndex',
step: '=lxStep'
},
link: link,
controller: LxStepNavController,
controllerAs: 'lxStepNav',
bindToController: true,
replace: true,
transclude: false
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].init(ctrls[1]);
}
}
function LxStepNavController()
{
var lxStepNav = this;
var _classes = [];
lxStepNav.getClasses = getClasses;
lxStepNav.init = init;
////////////
function getClasses()
{
_classes.length = 0;
if (parseInt(lxStepNav.step.index) === parseInt(lxStepNav.activeIndex))
{
_classes.push('lx-step-nav--is-active');
}
if (lxStepNav.step.isValid === true)
{
_classes.push('lx-step-nav--is-valid');
}
else if (lxStepNav.step.isValid === false)
{
_classes.push('lx-step-nav--has-error');
}
if (lxStepNav.step.isEditable)
{
_classes.push('lx-step-nav--is-editable');
}
if (lxStepNav.step.isOptional)
{
_classes.push('lx-step-nav--is-optional');
}
return _classes;
}
function init(parent, index)
{
lxStepNav.parent = parent;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.switch')
.directive('lxSwitch', lxSwitch)
.directive('lxSwitchLabel', lxSwitchLabel)
.directive('lxSwitchHelp', lxSwitchHelp);
function lxSwitch()
{
return {
restrict: 'E',
templateUrl: 'switch.html',
scope:
{
ngModel: '=',
name: '@?',
ngTrueValue: '@?',
ngFalseValue: '@?',
ngChange: '&?',
ngDisabled: '=?',
lxColor: '@?',
lxPosition: '@?'
},
controller: LxSwitchController,
controllerAs: 'lxSwitch',
bindToController: true,
transclude: true,
replace: true
};
}
LxSwitchController.$inject = ['$scope', '$timeout', 'LxUtils'];
function LxSwitchController($scope, $timeout, LxUtils)
{
var lxSwitch = this;
var switchId;
var switchHasChildren;
var timer;
lxSwitch.getSwitchId = getSwitchId;
lxSwitch.getSwitchHasChildren = getSwitchHasChildren;
lxSwitch.setSwitchId = setSwitchId;
lxSwitch.setSwitchHasChildren = setSwitchHasChildren;
lxSwitch.triggerNgChange = triggerNgChange;
$scope.$on('$destroy', function()
{
$timeout.cancel(timer);
});
init();
////////////
function getSwitchId()
{
return switchId;
}
function getSwitchHasChildren()
{
return switchHasChildren;
}
function init()
{
setSwitchId(LxUtils.generateUUID());
setSwitchHasChildren(false);
lxSwitch.ngTrueValue = angular.isUndefined(lxSwitch.ngTrueValue) ? true : lxSwitch.ngTrueValue;
lxSwitch.ngFalseValue = angular.isUndefined(lxSwitch.ngFalseValue) ? false : lxSwitch.ngFalseValue;
lxSwitch.lxColor = angular.isUndefined(lxSwitch.lxColor) ? 'accent' : lxSwitch.lxColor;
lxSwitch.lxPosition = angular.isUndefined(lxSwitch.lxPosition) ? 'left' : lxSwitch.lxPosition;
}
function setSwitchId(_switchId)
{
switchId = _switchId;
}
function setSwitchHasChildren(_switchHasChildren)
{
switchHasChildren = _switchHasChildren;
}
function triggerNgChange()
{
timer = $timeout(lxSwitch.ngChange);
}
}
function lxSwitchLabel()
{
return {
restrict: 'AE',
require: ['^lxSwitch', '^lxSwitchLabel'],
templateUrl: 'switch-label.html',
link: link,
controller: LxSwitchLabelController,
controllerAs: 'lxSwitchLabel',
bindToController: true,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].setSwitchHasChildren(true);
ctrls[1].setSwitchId(ctrls[0].getSwitchId());
}
}
function LxSwitchLabelController()
{
var lxSwitchLabel = this;
var switchId;
lxSwitchLabel.getSwitchId = getSwitchId;
lxSwitchLabel.setSwitchId = setSwitchId;
////////////
function getSwitchId()
{
return switchId;
}
function setSwitchId(_switchId)
{
switchId = _switchId;
}
}
function lxSwitchHelp()
{
return {
restrict: 'AE',
require: '^lxSwitch',
templateUrl: 'switch-help.html',
transclude: true,
replace: true
};
}
})();
(function()
{
'use strict';
angular
.module('lumx.tabs')
.directive('lxTabs', lxTabs)
.directive('lxTab', lxTab)
.directive('lxTabsPanes', lxTabsPanes)
.directive('lxTabPane', lxTabPane);
function lxTabs()
{
return {
restrict: 'E',
templateUrl: 'tabs.html',
scope:
{
layout: '@?lxLayout',
theme: '@?lxTheme',
color: '@?lxColor',
indicator: '@?lxIndicator',
activeTab: '=?lxActiveTab',
panesId: '@?lxPanesId',
links: '=?lxLinks'
},
controller: LxTabsController,
controllerAs: 'lxTabs',
bindToController: true,
replace: true,
transclude: true
};
}
LxTabsController.$inject = ['LxUtils', '$element', '$scope', '$timeout'];
function LxTabsController(LxUtils, $element, $scope, $timeout)
{
var lxTabs = this;
var tabsLength;
var timer1;
var timer2;
var timer3;
var timer4;
lxTabs.removeTab = removeTab;
lxTabs.setActiveTab = setActiveTab;
lxTabs.setViewMode = setViewMode;
lxTabs.tabIsActive = tabIsActive;
lxTabs.updateTabs = updateTabs;
lxTabs.activeTab = angular.isDefined(lxTabs.activeTab) ? lxTabs.activeTab : 0;
lxTabs.color = angular.isDefined(lxTabs.color) ? lxTabs.color : 'primary';
lxTabs.indicator = angular.isDefined(lxTabs.indicator) ? lxTabs.indicator : 'accent';
lxTabs.layout = angular.isDefined(lxTabs.layout) ? lxTabs.layout : 'full';
lxTabs.tabs = [];
lxTabs.theme = angular.isDefined(lxTabs.theme) ? lxTabs.theme : 'light';
lxTabs.viewMode = angular.isDefined(lxTabs.links) ? 'separate' : 'gather';
$scope.$watch(function()
{
return lxTabs.activeTab;
}, function(_newActiveTab, _oldActiveTab)
{
timer1 = $timeout(function()
{
setIndicatorPosition(_oldActiveTab);
if (lxTabs.viewMode === 'separate')
{
angular.element('#' + lxTabs.panesId).find('.tabs__pane').hide();
angular.element('#' + lxTabs.panesId).find('.tabs__pane').eq(lxTabs.activeTab).show();
}
});
});
$scope.$watch(function()
{
return lxTabs.links;
}, function(_newLinks)
{
lxTabs.viewMode = angular.isDefined(_newLinks) ? 'separate' : 'gather';
angular.forEach(_newLinks, function(link, index)
{
var tab = {
uuid: (angular.isUndefined(link.uuid) || link.uuid.length === 0) ? LxUtils.generateUUID() : link.uuid,
index: index,
label: link.label,
icon: link.icon,
disabled: link.disabled
};
updateTabs(tab);
});
});
timer2 = $timeout(function()
{
tabsLength = lxTabs.tabs.length;
});
$scope.$on('$destroy', function()
{
$timeout.cancel(timer1);
$timeout.cancel(timer2);
$timeout.cancel(timer3);
$timeout.cancel(timer4);
});
////////////
function removeTab(_tab)
{
lxTabs.tabs.splice(_tab.index, 1);
angular.forEach(lxTabs.tabs, function(tab, index)
{
tab.index = index;
});
if (lxTabs.activeTab === 0)
{
timer3 = $timeout(function()
{
setIndicatorPosition();
});
}
else
{
setActiveTab(lxTabs.tabs[0]);
}
}
function setActiveTab(_tab)
{
if (!_tab.disabled)
{
lxTabs.activeTab = _tab.index;
}
}
function setIndicatorPosition(_previousActiveTab)
{
var direction = lxTabs.activeTab > _previousActiveTab ? 'right' : 'left';
var indicator = $element.find('.tabs__indicator');
var activeTab = $element.find('.tabs__link').eq(lxTabs.activeTab);
var indicatorLeft = activeTab.position().left;
var indicatorRight = $element.outerWidth() - (indicatorLeft + activeTab.outerWidth());
if (angular.isUndefined(_previousActiveTab))
{
indicator.css(
{
left: indicatorLeft,
right: indicatorRight
});
}
else
{
var animationProperties = {
duration: 200,
easing: 'easeOutQuint'
};
if (direction === 'left')
{
indicator.velocity(
{
left: indicatorLeft
}, animationProperties);
indicator.velocity(
{
right: indicatorRight
}, animationProperties);
}
else
{
indicator.velocity(
{
right: indicatorRight
}, animationProperties);
indicator.velocity(
{
left: indicatorLeft
}, animationProperties);
}
}
}
function setViewMode(_viewMode)
{
lxTabs.viewMode = _viewMode;
}
function tabIsActive(_index)
{
return lxTabs.activeTab === _index;
}
function updateTabs(_tab)
{
var newTab = true;
angular.forEach(lxTabs.tabs, function(tab)
{
if (tab.index === _tab.index)
{
newTab = false;
tab.uuid = _tab.uuid;
tab.icon = _tab.icon;
tab.label = _tab.label;
}
});
if (newTab)
{
lxTabs.tabs.push(_tab);
if (angular.isDefined(tabsLength))
{
timer4 = $timeout(function()
{
setIndicatorPosition();
});
}
}
}
}
function lxTab()
{
return {
restrict: 'E',
require: ['lxTab', '^lxTabs'],
templateUrl: 'tab.html',
scope:
{
ngDisabled: '=?'
},
link: link,
controller: LxTabController,
controllerAs: 'lxTab',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].init(ctrls[1], element.index());
attrs.$observe('lxLabel', function(_newLabel)
{
ctrls[0].setLabel(_newLabel);
});
attrs.$observe('lxIcon', function(_newIcon)
{
ctrls[0].setIcon(_newIcon);
});
}
}
LxTabController.$inject = ['$scope', 'LxUtils'];
function LxTabController($scope, LxUtils)
{
var lxTab = this;
var parentCtrl;
var tab = {
uuid: LxUtils.generateUUID(),
index: undefined,
label: undefined,
icon: undefined,
disabled: false
};
lxTab.init = init;
lxTab.setIcon = setIcon;
lxTab.setLabel = setLabel;
lxTab.tabIsActive = tabIsActive;
$scope.$watch(function()
{
return lxTab.ngDisabled;
}, function(_isDisabled)
{
if (_isDisabled)
{
tab.disabled = true;
}
else
{
tab.disabled = false;
}
parentCtrl.updateTabs(tab);
});
$scope.$on('$destroy', function()
{
parentCtrl.removeTab(tab);
});
////////////
function init(_parentCtrl, _index)
{
parentCtrl = _parentCtrl;
tab.index = _index;
parentCtrl.updateTabs(tab);
}
function setIcon(_icon)
{
tab.icon = _icon;
parentCtrl.updateTabs(tab);
}
function setLabel(_label)
{
tab.label = _label;
parentCtrl.updateTabs(tab);
}
function tabIsActive()
{
return parentCtrl.tabIsActive(tab.index);
}
}
function lxTabsPanes()
{
return {
restrict: 'E',
templateUrl: 'tabs-panes.html',
scope: true,
replace: true,
transclude: true
};
}
function lxTabPane()
{
return {
restrict: 'E',
templateUrl: 'tab-pane.html',
scope: true,
replace: true,
transclude: true
};
}
})();
(function()
{
'use strict';
angular
.module('lumx.text-field')
.directive('lxTextField', lxTextField);
lxTextField.$inject = ['$timeout'];
function lxTextField($timeout)
{
return {
restrict: 'E',
templateUrl: 'text-field.html',
scope:
{
allowClear: '=?lxAllowClear',
error: '=?lxError',
fixedLabel: '=?lxFixedLabel',
focus: '=?lxFocus',
icon: '@?lxIcon',
label: '@lxLabel',
ngDisabled: '=?',
theme: '@?lxTheme',
valid: '=?lxValid'
},
link: link,
controller: LxTextFieldController,
controllerAs: 'lxTextField',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrl, transclude)
{
var backwardOneWay = ['icon', 'label', 'theme'];
var backwardTwoWay = ['error', 'fixedLabel', 'valid'];
var input;
var timer;
angular.forEach(backwardOneWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
attrs.$observe(attribute, function(newValue)
{
scope.lxTextField[attribute] = newValue;
});
}
});
angular.forEach(backwardTwoWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
scope.$watch(function()
{
return scope.$parent.$eval(attrs[attribute]);
}, function(newValue)
{
scope.lxTextField[attribute] = newValue;
});
}
});
transclude(function()
{
input = element.find('textarea');
if (input[0])
{
input.on('cut paste drop keydown', function()
{
timer = $timeout(ctrl.updateTextareaHeight);
});
}
else
{
input = element.find('input');
}
input.addClass('text-field__input');
ctrl.setInput(input);
ctrl.setModel(input.data('$ngModelController'));
input.on('focus', function()
{
var phase = scope.$root.$$phase;
if (phase === '$apply' || phase === '$digest')
{
ctrl.focusInput();
}
else
{
scope.$apply(ctrl.focusInput);
}
});
input.on('blur', ctrl.blurInput);
});
scope.$on('$destroy', function()
{
$timeout.cancel(timer);
input.off();
});
}
}
LxTextFieldController.$inject = ['$scope', '$timeout'];
function LxTextFieldController($scope, $timeout)
{
var lxTextField = this;
var input;
var modelController;
var timer1;
var timer2;
lxTextField.blurInput = blurInput;
lxTextField.clearInput = clearInput;
lxTextField.focusInput = focusInput;
lxTextField.hasValue = hasValue;
lxTextField.setInput = setInput;
lxTextField.setModel = setModel;
lxTextField.updateTextareaHeight = updateTextareaHeight;
$scope.$watch(function()
{
return modelController.$viewValue;
}, function(newValue, oldValue)
{
if (angular.isDefined(newValue) && newValue)
{
lxTextField.isActive = true;
}
else
{
lxTextField.isActive = false;
}
});
$scope.$watch(function()
{
return lxTextField.focus;
}, function(newValue, oldValue)
{
if (angular.isDefined(newValue) && newValue)
{
$timeout(function()
{
input.focus();
// Reset the value so we can re-focus the field later on if we want to.
lxTextField.focus = false;
});
}
});
$scope.$on('$destroy', function()
{
$timeout.cancel(timer1);
$timeout.cancel(timer2);
});
////////////
function blurInput()
{
if (!hasValue())
{
$scope.$apply(function()
{
lxTextField.isActive = false;
});
}
$scope.$apply(function()
{
lxTextField.isFocus = false;
});
}
function clearInput(_event)
{
_event.stopPropagation();
modelController.$setViewValue(undefined);
modelController.$render();
}
function focusInput()
{
lxTextField.isActive = true;
lxTextField.isFocus = true;
}
function hasValue()
{
return angular.isDefined(input.val()) && input.val().length > 0;
}
function init()
{
lxTextField.isActive = hasValue();
lxTextField.focus = angular.isDefined(lxTextField.focus) ? lxTextField.focus : false;
lxTextField.isFocus = lxTextField.focus;
}
function setInput(_input)
{
input = _input;
timer1 = $timeout(init);
if (input.selector === 'textarea')
{
timer2 = $timeout(updateTextareaHeight);
}
}
function setModel(_modelControler)
{
modelController = _modelControler;
}
function updateTextareaHeight()
{
var tmpTextArea = angular.element('<textarea class="text-field__input" style="width: ' + input.width() + 'px;">' + input.val() + '</textarea>');
tmpTextArea.appendTo('body');
input.css(
{
height: tmpTextArea[0].scrollHeight + 'px'
});
tmpTextArea.remove();
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.tooltip')
.directive('lxTooltip', lxTooltip);
function lxTooltip()
{
return {
restrict: 'A',
scope:
{
tooltip: '@lxTooltip',
position: '@?lxTooltipPosition'
},
link: link,
controller: LxTooltipController,
controllerAs: 'lxTooltip',
bindToController: true
};
function link(scope, element, attrs, ctrl)
{
if (angular.isDefined(attrs.lxTooltip))
{
attrs.$observe('lxTooltip', function(newValue)
{
ctrl.updateTooltipText(newValue);
});
}
if (angular.isDefined(attrs.lxTooltipPosition))
{
attrs.$observe('lxTooltipPosition', function(newValue)
{
scope.lxTooltip.position = newValue;
});
}
element.on('mouseenter', ctrl.showTooltip);
element.on('mouseleave', ctrl.hideTooltip);
scope.$on('$destroy', function()
{
element.off();
});
}
}
LxTooltipController.$inject = ['$element', '$scope', '$timeout', 'LxDepthService'];
function LxTooltipController($element, $scope, $timeout, LxDepthService)
{
var lxTooltip = this;
var timer1;
var timer2;
var tooltip;
var tooltipBackground;
var tooltipLabel;
lxTooltip.hideTooltip = hideTooltip;
lxTooltip.showTooltip = showTooltip;
lxTooltip.updateTooltipText = updateTooltipText;
lxTooltip.position = angular.isDefined(lxTooltip.position) ? lxTooltip.position : 'top';
$scope.$on('$destroy', function()
{
if (angular.isDefined(tooltip))
{
tooltip.remove();
tooltip = undefined;
}
$timeout.cancel(timer1);
$timeout.cancel(timer2);
});
////////////
function hideTooltip()
{
if (angular.isDefined(tooltip))
{
tooltip.removeClass('tooltip--is-active');
timer1 = $timeout(function()
{
if (angular.isDefined(tooltip))
{
tooltip.remove();
tooltip = undefined;
}
}, 200);
}
}
function setTooltipPosition()
{
var width = $element.outerWidth(),
height = $element.outerHeight(),
top = $element.offset().top,
left = $element.offset().left;
tooltip
.append(tooltipBackground)
.append(tooltipLabel)
.appendTo('body');
if (lxTooltip.position === 'top')
{
tooltip.css(
{
left: left - (tooltip.outerWidth() / 2) + (width / 2),
top: top - tooltip.outerHeight()
});
}
else if (lxTooltip.position === 'bottom')
{
tooltip.css(
{
left: left - (tooltip.outerWidth() / 2) + (width / 2),
top: top + height
});
}
else if (lxTooltip.position === 'left')
{
tooltip.css(
{
left: left - tooltip.outerWidth(),
top: top + (height / 2) - (tooltip.outerHeight() / 2)
});
}
else if (lxTooltip.position === 'right')
{
tooltip.css(
{
left: left + width,
top: top + (height / 2) - (tooltip.outerHeight() / 2)
});
}
}
function showTooltip()
{
if (angular.isUndefined(tooltip))
{
LxDepthService.register();
tooltip = angular.element('<div/>',
{
class: 'tooltip tooltip--' + lxTooltip.position
});
tooltipBackground = angular.element('<div/>',
{
class: 'tooltip__background'
});
tooltipLabel = angular.element('<span/>',
{
class: 'tooltip__label',
text: lxTooltip.tooltip
});
setTooltipPosition();
tooltip
.append(tooltipBackground)
.append(tooltipLabel)
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
timer2 = $timeout(function()
{
tooltip.addClass('tooltip--is-active');
});
}
}
function updateTooltipText(_newValue)
{
if (angular.isDefined(tooltipLabel))
{
tooltipLabel.text(_newValue);
}
}
}
})();
angular.module("lumx.dropdown").run(['$templateCache', function(a) { a.put('dropdown.html', '<div class="dropdown"\n' +
' ng-class="{ \'dropdown--has-toggle\': lxDropdown.hasToggle,\n' +
' \'dropdown--is-open\': lxDropdown.isOpen }"\n' +
' ng-transclude></div>\n' +
'');
a.put('dropdown-toggle.html', '<div class="dropdown-toggle" ng-transclude></div>\n' +
'');
a.put('dropdown-menu.html', '<div class="dropdown-menu">\n' +
' <div class="dropdown-menu__content" ng-transclude ng-if="lxDropdownMenu.parentCtrl.isOpen"></div>\n' +
'</div>\n' +
'');
}]);
angular.module("lumx.file-input").run(['$templateCache', function(a) { a.put('file-input.html', '<div class="input-file">\n' +
' <span class="input-file__label">{{ lxFileInput.label }}</span>\n' +
' <span class="input-file__filename">{{ lxFileInput.fileName }}</span>\n' +
' <input type="file" class="input-file__input">\n' +
'</div>\n' +
'');
}]);
angular.module("lumx.text-field").run(['$templateCache', function(a) { a.put('text-field.html', '<div class="text-field"\n' +
' ng-class="{ \'text-field--error\': lxTextField.error,\n' +
' \'text-field--fixed-label\': lxTextField.fixedLabel,\n' +
' \'text-field--has-icon\': lxTextField.icon,\n' +
' \'text-field--has-value\': lxTextField.hasValue(),\n' +
' \'text-field--is-active\': lxTextField.isActive,\n' +
' \'text-field--is-disabled\': lxTextField.ngDisabled,\n' +
' \'text-field--is-focus\': lxTextField.isFocus,\n' +
' \'text-field--theme-light\': !lxTextField.theme || lxTextField.theme === \'light\',\n' +
' \'text-field--theme-dark\': lxTextField.theme === \'dark\',\n' +
' \'text-field--valid\': lxTextField.valid }">\n' +
' <div class="text-field__icon" ng-if="lxTextField.icon">\n' +
' <i class="mdi mdi-{{ lxTextField.icon }}"></i>\n' +
' </div>\n' +
'\n' +
' <label class="text-field__label">\n' +
' {{ lxTextField.label }}\n' +
' </label>\n' +
'\n' +
' <div ng-transclude></div>\n' +
'\n' +
' <span class="text-field__clear" ng-click="lxTextField.clearInput($event)" ng-if="lxTextField.allowClear">\n' +
' <i class="mdi mdi-close-circle"></i>\n' +
' </span>\n' +
'</div>\n' +
'');
}]);
angular.module("lumx.search-filter").run(['$templateCache', function(a) { a.put('search-filter.html', '<div class="search-filter" ng-class="lxSearchFilter.getClass()">\n' +
' <div class="search-filter__container">\n' +
' <div class="search-filter__button">\n' +
' <lx-button type="submit" lx-size="l" lx-color="{{ lxSearchFilter.color }}" lx-type="icon" ng-click="lxSearchFilter.openInput()">\n' +
' <i class="mdi mdi-magnify"></i>\n' +
' </lx-button>\n' +
' </div>\n' +
'\n' +
' <div class="search-filter__input" ng-transclude></div>\n' +
'\n' +
' <div class="search-filter__clear">\n' +
' <lx-button type="button" lx-size="l" lx-color="{{ lxSearchFilter.color }}" lx-type="icon" ng-click="lxSearchFilter.clearInput()">\n' +
' <i class="mdi mdi-close"></i>\n' +
' </lx-button>\n' +
' </div>\n' +
' </div>\n' +
'\n' +
' <div class="search-filter__loader" ng-if="lxSearchFilter.isLoading">\n' +
' <lx-progress lx-type="linear"></lx-progress>\n' +
' </div>\n' +
'\n' +
' <lx-dropdown id="{{ lxSearchFilter.dropdownId }}" lx-effect="none" lx-width="100%" ng-if="lxSearchFilter.autocomplete">\n' +
' <lx-dropdown-menu class="search-filter__autocomplete-list">\n' +
' <ul>\n' +
' <li ng-repeat="item in lxSearchFilter.autocompleteList track by $index">\n' +
' <a class="search-filter__autocomplete-item"\n' +
' ng-class="{ \'search-filter__autocomplete-item--is-active\': lxSearchFilter.activeChoiceIndex === $index }"\n' +
' ng-click="lxSearchFilter.selectItem(item)"\n' +
' ng-bind-html="item | lxSearchHighlight:lxSearchFilter.modelController.$viewValue:lxSearchFilter.icon"></a>\n' +
' </li>\n' +
' </ul>\n' +
' </lx-dropdown-menu>\n' +
' </lx-dropdown>\n' +
'</div>');
}]);
angular.module("lumx.select").run(['$templateCache', function(a) { a.put('select.html', '<div class="lx-select"\n' +
' ng-class="{ \'lx-select--error\': lxSelect.error,\n' +
' \'lx-select--fixed-label\': lxSelect.fixedLabel && lxSelect.viewMode === \'field\',\n' +
' \'lx-select--is-active\': (!lxSelect.multiple && lxSelect.getSelectedModel()) || (lxSelect.multiple && lxSelect.getSelectedModel().length),\n' +
' \'lx-select--is-disabled\': lxSelect.ngDisabled,\n' +
' \'lx-select--is-multiple\': lxSelect.multiple,\n' +
' \'lx-select--is-unique\': !lxSelect.multiple,\n' +
' \'lx-select--theme-light\': !lxSelect.theme || lxSelect.theme === \'light\',\n' +
' \'lx-select--theme-dark\': lxSelect.theme === \'dark\',\n' +
' \'lx-select--valid\': lxSelect.valid,\n' +
' \'lx-select--custom-style\': lxSelect.customStyle,\n' +
' \'lx-select--default-style\': !lxSelect.customStyle,\n' +
' \'lx-select--view-mode-field\': !lxSelect.multiple || (lxSelect.multiple && lxSelect.viewMode === \'field\'),\n' +
' \'lx-select--view-mode-chips\': lxSelect.multiple && lxSelect.viewMode === \'chips\',\n' +
' \'lx-select--autocomplete\': lxSelect.autocomplete }">\n' +
' <span class="lx-select-label" ng-if="!lxSelect.autocomplete">\n' +
' {{ ::lxSelect.label }}\n' +
' </span>\n' +
'\n' +
' <lx-dropdown id="dropdown-{{ lxSelect.uuid }}" lx-width="100%" lx-effect="{{ lxSelect.autocomplete ? \'none\' : \'expand\' }}">\n' +
' <ng-transclude></ng-transclude>\n' +
' </lx-dropdown>\n' +
'</div>\n' +
'');
a.put('select-selected.html', '<div>\n' +
' <lx-dropdown-toggle ng-if="::!lxSelectSelected.parentCtrl.autocomplete">\n' +
' <ng-include src="\'select-selected-content.html\'"></ng-include>\n' +
' </lx-dropdown-toggle>\n' +
'\n' +
' <ng-include src="\'select-selected-content.html\'" ng-if="::lxSelectSelected.parentCtrl.autocomplete"></ng-include>\n' +
'</div>\n' +
'');
a.put('select-selected-content.html', '<div class="lx-select-selected-wrapper" id="lx-select-selected-wrapper-{{ lxSelectSelected.parentCtrl.uuid }}">\n' +
' <div class="lx-select-selected" ng-if="!lxSelectSelected.parentCtrl.multiple && lxSelectSelected.parentCtrl.getSelectedModel()">\n' +
' <span class="lx-select-selected__value"\n' +
' ng-bind-html="lxSelectSelected.parentCtrl.displaySelected()"></span>\n' +
'\n' +
' <a class="lx-select-selected__clear"\n' +
' ng-click="lxSelectSelected.clearModel($event)"\n' +
' ng-if="::lxSelectSelected.parentCtrl.allowClear">\n' +
' <i class="mdi mdi-close-circle"></i>\n' +
' </a>\n' +
' </div>\n' +
'\n' +
' <div class="lx-select-selected" ng-if="lxSelectSelected.parentCtrl.multiple">\n' +
' <span class="lx-select-selected__tag"\n' +
' ng-class="{ \'lx-select-selected__tag--is-active\': lxSelectSelected.parentCtrl.activeSelectedIndex === $index }"\n' +
' ng-click="lxSelectSelected.removeSelected(selected, $event)"\n' +
' ng-repeat="selected in lxSelectSelected.parentCtrl.getSelectedModel()"\n' +
' ng-bind-html="lxSelectSelected.parentCtrl.displaySelected(selected)"></span>\n' +
'\n' +
' <input type="text"\n' +
' placeholder="{{ ::lxSelectSelected.parentCtrl.label }}"\n' +
' class="lx-select-selected__filter"\n' +
' ng-model="lxSelectSelected.parentCtrl.filterModel"\n' +
' ng-change="lxSelectSelected.parentCtrl.updateFilter()"\n' +
' ng-keydown="lxSelectSelected.parentCtrl.keyEvent($event)"\n' +
' ng-if="::lxSelectSelected.parentCtrl.autocomplete && !lxSelectSelected.parentCtrl.ngDisabled">\n' +
' </div>\n' +
'</div>');
a.put('select-choices.html', '<lx-dropdown-menu class="lx-select-choices"\n' +
' ng-class="{ \'lx-select-choices--custom-style\': lxSelectChoices.parentCtrl.choicesCustomStyle,\n' +
' \'lx-select-choices--default-style\': !lxSelectChoices.parentCtrl.choicesCustomStyle,\n' +
' \'lx-select-choices--is-multiple\': lxSelectChoices.parentCtrl.multiple,\n' +
' \'lx-select-choices--is-unique\': !lxSelectChoices.parentCtrl.multiple, }">\n' +
' <ul>\n' +
' <li class="lx-select-choices__filter" ng-if="::lxSelectChoices.parentCtrl.displayFilter && !lxSelectChoices.parentCtrl.autocomplete">\n' +
' <lx-search-filter lx-dropdown-filter>\n' +
' <input type="text" ng-model="lxSelectChoices.parentCtrl.filterModel" ng-change="lxSelectChoices.parentCtrl.updateFilter()">\n' +
' </lx-search-filter>\n' +
' </li>\n' +
' \n' +
' <div ng-if="::lxSelectChoices.isArray()">\n' +
' <li class="lx-select-choices__choice"\n' +
' ng-class="{ \'lx-select-choices__choice--is-selected\': lxSelectChoices.parentCtrl.isSelected(choice),\n' +
' \'lx-select-choices__choice--is-focus\': lxSelectChoices.parentCtrl.activeChoiceIndex === $index }"\n' +
' ng-repeat="choice in lxSelectChoices.parentCtrl.choices | filterChoices:lxSelectChoices.parentCtrl.filter:lxSelectChoices.parentCtrl.filterModel"\n' +
' ng-bind-html="::lxSelectChoices.parentCtrl.displayChoice(choice)"\n' +
' ng-click="lxSelectChoices.parentCtrl.toggleChoice(choice, $event)"></li>\n' +
' </div>\n' +
'\n' +
' <div ng-if="::!lxSelectChoices.isArray()">\n' +
' <li class="lx-select-choices__subheader"\n' +
' ng-repeat-start="(subheader, children) in lxSelectChoices.parentCtrl.choices"\n' +
' ng-bind-html="::lxSelectChoices.parentCtrl.displaySubheader(subheader)"></li>\n' +
'\n' +
' <li class="lx-select-choices__choice"\n' +
' ng-class="{ \'lx-select-choices__choice--is-selected\': lxSelectChoices.parentCtrl.isSelected(choice),\n' +
' \'lx-select-choices__choice--is-focus\': lxSelectChoices.parentCtrl.activeChoiceIndex === $index }"\n' +
' ng-repeat-end\n' +
' ng-repeat="choice in children | filterChoices:lxSelectChoices.parentCtrl.filter:lxSelectChoices.parentCtrl.filterModel"\n' +
' ng-bind-html="::lxSelectChoices.parentCtrl.displayChoice(choice)"\n' +
' ng-click="lxSelectChoices.parentCtrl.toggleChoice(choice, $event)"></li>\n' +
' </div>\n' +
'\n' +
' <li class="lx-select-choices__subheader" ng-if="lxSelectChoices.parentCtrl.helperDisplayable()">\n' +
' {{ lxSelectChoices.parentCtrl.helperMessage }}\n' +
' </li>\n' +
'\n' +
' <li class="lx-select-choices__loader" ng-if="lxSelectChoices.parentCtrl.loading">\n' +
' <lx-progress lx-type="circular" lx-color="primary" lx-diameter="20"></lx-progress>\n' +
' </li>\n' +
' </ul>\n' +
'</lx-dropdown-menu>\n' +
'');
}]);
angular.module("lumx.tabs").run(['$templateCache', function(a) { a.put('tabs.html', '<div class="tabs tabs--layout-{{ lxTabs.layout }} tabs--theme-{{ lxTabs.theme }} tabs--color-{{ lxTabs.color }} tabs--indicator-{{ lxTabs.indicator }}">\n' +
' <div class="tabs__links">\n' +
' <a class="tabs__link"\n' +
' ng-class="{ \'tabs__link--is-active\': lxTabs.tabIsActive(tab.index),\n' +
' \'tabs__link--is-disabled\': tab.disabled }"\n' +
' ng-repeat="tab in lxTabs.tabs"\n' +
' ng-click="lxTabs.setActiveTab(tab)"\n' +
' lx-ripple>\n' +
' <i class="mdi mdi-{{ tab.icon }}" ng-if="tab.icon"></i>\n' +
' <span ng-if="tab.label">{{ tab.label }}</span>\n' +
' </a>\n' +
' </div>\n' +
' \n' +
' <div class="tabs__panes" ng-if="lxTabs.viewMode === \'gather\'" ng-transclude></div>\n' +
' <div class="tabs__indicator"></div>\n' +
'</div>\n' +
'');
a.put('tabs-panes.html', '<div class="tabs">\n' +
' <div class="tabs__panes" ng-transclude></div>\n' +
'</div>');
a.put('tab.html', '<div class="tabs__pane" ng-class="{ \'tabs__pane--is-disabled\': lxTab.ngDisabled }">\n' +
' <div ng-if="lxTab.tabIsActive()" ng-transclude></div>\n' +
'</div>\n' +
'');
a.put('tab-pane.html', '<div class="tabs__pane" ng-transclude></div>\n' +
'');
}]);
angular.module("lumx.date-picker").run(['$templateCache', function(a) { a.put('date-picker.html', '<div class="lx-date">\n' +
' <!-- Date picker input -->\n' +
' <div class="lx-date-input" ng-click="lxDatePicker.openDatePicker()" ng-if="lxDatePicker.hasInput">\n' +
' <ng-transclude></ng-transclude>\n' +
' </div>\n' +
' \n' +
' <!-- Date picker -->\n' +
' <div class="lx-date-picker lx-date-picker--{{ lxDatePicker.color }}">\n' +
' <div ng-if="lxDatePicker.isOpen">\n' +
' <!-- Date picker: header -->\n' +
' <div class="lx-date-picker__header">\n' +
' <a class="lx-date-picker__current-year"\n' +
' ng-class="{ \'lx-date-picker__current-year--is-active\': lxDatePicker.yearSelection }"\n' +
' ng-click="lxDatePicker.displayYearSelection()">\n' +
' {{ lxDatePicker.moment(lxDatePicker.ngModel).format(\'YYYY\') }}\n' +
' </a>\n' +
'\n' +
' <a class="lx-date-picker__current-date"\n' +
' ng-class="{ \'lx-date-picker__current-date--is-active\': !lxDatePicker.yearSelection }"\n' +
' ng-click="lxDatePicker.hideYearSelection()">\n' +
' {{ lxDatePicker.getDateFormatted() }}\n' +
' </a>\n' +
' </div>\n' +
' \n' +
' <!-- Date picker: content -->\n' +
' <div class="lx-date-picker__content">\n' +
' <!-- Calendar -->\n' +
' <div class="lx-date-picker__calendar" ng-if="!lxDatePicker.yearSelection">\n' +
' <div class="lx-date-picker__nav">\n' +
' <lx-button lx-size="l" lx-color="black" lx-type="icon" ng-click="lxDatePicker.previousMonth()">\n' +
' <i class="mdi mdi-chevron-left"></i>\n' +
' </lx-button>\n' +
'\n' +
' <span>{{ lxDatePicker.ngModelMoment.format(\'MMMM YYYY\') }}</span>\n' +
' \n' +
' <lx-button lx-size="l" lx-color="black" lx-type="icon" ng-click="lxDatePicker.nextMonth()">\n' +
' <i class="mdi mdi-chevron-right"></i>\n' +
' </lx-button>\n' +
' </div>\n' +
'\n' +
' <div class="lx-date-picker__days-of-week">\n' +
' <span ng-repeat="day in lxDatePicker.daysOfWeek">{{ day }}</span>\n' +
' </div>\n' +
'\n' +
' <div class="lx-date-picker__days">\n' +
' <span class="lx-date-picker__day lx-date-picker__day--is-empty"\n' +
' ng-repeat="x in lxDatePicker.emptyFirstDays"> </span>\n' +
'\n' +
' <div class="lx-date-picker__day"\n' +
' ng-class="{ \'lx-date-picker__day--is-selected\': day.selected,\n' +
' \'lx-date-picker__day--is-today\': day.today && !day.selected,\n' +
' \'lx-date-picker__day--is-disabled\': day.disabled }"\n' +
' ng-repeat="day in lxDatePicker.days">\n' +
' <a ng-click="lxDatePicker.select(day)">{{ day ? day.format(\'D\') : \'\' }}</a>\n' +
' </div>\n' +
'\n' +
' <span class="lx-date-picker__day lx-date-picker__day--is-empty"\n' +
' ng-repeat="x in lxDatePicker.emptyLastDays"> </span>\n' +
' </div>\n' +
' </div>\n' +
'\n' +
' <!-- Year selection -->\n' +
' <div class="lx-date-picker__year-selector" ng-if="lxDatePicker.yearSelection">\n' +
' <a class="lx-date-picker__year"\n' +
' ng-class="{ \'lx-date-picker__year--is-active\': year == lxDatePicker.moment(lxDatePicker.ngModel).format(\'YYYY\') }"\n' +
' ng-repeat="year in lxDatePicker.years"\n' +
' ng-click="lxDatePicker.selectYear(year)"\n' +
' ng-if="lxDatePicker.yearSelection">\n' +
' {{ year }}\n' +
' </a>\n' +
' </div>\n' +
' </div>\n' +
'\n' +
' <!-- Actions -->\n' +
' <div class="lx-date-picker__actions">\n' +
' <lx-button lx-color="{{ lxDatePicker.color }}" lx-type="flat" ng-click="lxDatePicker.closeDatePicker()">\n' +
' Ok\n' +
' </lx-button>\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
'</div>');
}]);
angular.module("lumx.progress").run(['$templateCache', function(a) { a.put('progress.html', '<div class="progress-container progress-container--{{ lxProgress.lxType }} progress-container--{{ lxProgress.lxColor }}"\n' +
' ng-class="{ \'progress-container--determinate\': lxProgress.lxValue,\n' +
' \'progress-container--indeterminate\': !lxProgress.lxValue }">\n' +
' <div class="progress-circular"\n' +
' ng-if="lxProgress.lxType === \'circular\'"\n' +
' ng-style="lxProgress.getProgressDiameter()">\n' +
' <svg class="progress-circular__svg">\n' +
' <circle class="progress-circular__path" cx="50" cy="50" r="20" fill="none" stroke-width="4" stroke-miterlimit="10" ng-style="lxProgress.getCircularProgressValue()">\n' +
' </svg>\n' +
' </div>\n' +
'\n' +
' <div class="progress-linear" ng-if="lxProgress.lxType === \'linear\'">\n' +
' <div class="progress-linear__background"></div>\n' +
' <div class="progress-linear__bar progress-linear__bar--first" ng-style="lxProgress.getLinearProgressValue()"></div>\n' +
' <div class="progress-linear__bar progress-linear__bar--second"></div>\n' +
' </div>\n' +
'</div>\n' +
'');
}]);
angular.module("lumx.button").run(['$templateCache', function(a) { a.put('link.html', '<a ng-transclude lx-ripple></a>\n' +
'');
a.put('button.html', '<button ng-transclude lx-ripple></button>\n' +
'');
}]);
angular.module("lumx.checkbox").run(['$templateCache', function(a) { a.put('checkbox.html', '<div class="checkbox checkbox--{{ lxCheckbox.lxColor }}"\n' +
' ng-class="{ \'checkbox--theme-light\': !lxCheckbox.theme || lxCheckbox.theme === \'light\',\n' +
' \'checkbox--theme-dark\': lxCheckbox.theme === \'dark\' }" >\n' +
' <input id="{{ lxCheckbox.getCheckboxId() }}"\n' +
' type="checkbox"\n' +
' class="checkbox__input"\n' +
' name="{{ lxCheckbox.name }}"\n' +
' ng-model="lxCheckbox.ngModel"\n' +
' ng-true-value="{{ lxCheckbox.ngTrueValue }}"\n' +
' ng-false-value="{{ lxCheckbox.ngFalseValue }}"\n' +
' ng-change="lxCheckbox.triggerNgChange()"\n' +
' ng-disabled="lxCheckbox.ngDisabled">\n' +
'\n' +
' <label for="{{ lxCheckbox.getCheckboxId() }}" class="checkbox__label" ng-transclude ng-if="!lxCheckbox.getCheckboxHasChildren()"></label>\n' +
' <ng-transclude-replace ng-if="lxCheckbox.getCheckboxHasChildren()"></ng-transclude-replace>\n' +
'</div>\n' +
'');
a.put('checkbox-label.html', '<label for="{{ lxCheckboxLabel.getCheckboxId() }}" class="checkbox__label" ng-transclude></label>\n' +
'');
a.put('checkbox-help.html', '<span class="checkbox__help" ng-transclude></span>\n' +
'');
}]);
angular.module("lumx.radio-button").run(['$templateCache', function(a) { a.put('radio-group.html', '<div class="radio-group" ng-transclude></div>\n' +
'');
a.put('radio-button.html', '<div class="radio-button radio-button--{{ lxRadioButton.lxColor }}">\n' +
' <input id="{{ lxRadioButton.getRadioButtonId() }}"\n' +
' type="radio"\n' +
' class="radio-button__input"\n' +
' name="{{ lxRadioButton.name }}"\n' +
' ng-model="lxRadioButton.ngModel"\n' +
' ng-value="lxRadioButton.ngValue"\n' +
' ng-change="lxRadioButton.triggerNgChange()"\n' +
' ng-disabled="lxRadioButton.ngDisabled">\n' +
'\n' +
' <label for="{{ lxRadioButton.getRadioButtonId() }}" class="radio-button__label" ng-transclude ng-if="!lxRadioButton.getRadioButtonHasChildren()"></label>\n' +
' <ng-transclude-replace ng-if="lxRadioButton.getRadioButtonHasChildren()"></ng-transclude-replace>\n' +
'</div>\n' +
'');
a.put('radio-button-label.html', '<label for="{{ lxRadioButtonLabel.getRadioButtonId() }}" class="radio-button__label" ng-transclude></label>\n' +
'');
a.put('radio-button-help.html', '<span class="radio-button__help" ng-transclude></span>\n' +
'');
}]);
angular.module("lumx.stepper").run(['$templateCache', function(a) { a.put('stepper.html', '<div class="lx-stepper" ng-class="lxStepper.getClasses()">\n' +
' <div class="lx-stepper__header" ng-if="lxStepper.layout === \'horizontal\'">\n' +
' <div class="lx-stepper__nav">\n' +
' <lx-step-nav lx-active-index="{{ lxStepper.activeIndex }}" lx-step="step" ng-repeat="step in lxStepper.steps"></lx-step-nav>\n' +
' </div>\n' +
'\n' +
' <div class="lx-stepper__feedback" ng-if="lxStepper.steps[lxStepper.activeIndex].feedback">\n' +
' <span>{{ lxStepper.steps[lxStepper.activeIndex].feedback }}</span>\n' +
' </div>\n' +
' </div>\n' +
'\n' +
' <div class="lx-stepper__steps" ng-transclude></div>\n' +
'</div>');
a.put('step.html', '<div class="lx-step" ng-class="lxStep.getClasses()">\n' +
' <div class="lx-step__nav" ng-if="lxStep.parent.layout === \'vertical\'">\n' +
' <lx-step-nav lx-active-index="{{ lxStep.parent.activeIndex }}" lx-step="lxStep.step"></lx-step-nav>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step__wrapper" ng-if="lxStep.parent.activeIndex === lxStep.step.index">\n' +
' <div class="lx-step__content">\n' +
' <ng-transclude></ng-transclude>\n' +
'\n' +
' <div class="lx-step__progress" ng-if="lxStep.step.isLoading">\n' +
' <lx-progress lx-type="circular"></lx-progress>\n' +
' </div>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step__actions" ng-if="lxStep.parent.activeIndex === lxStep.step.index">\n' +
' <div class="lx-step__action lx-step__action--continue">\n' +
' <lx-button ng-click="lxStep.submitStep()" ng-disabled="lxStep.isLoading">{{ lxStep.parent.labels.continue }}</lx-button>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step__action lx-step__action--cancel" ng-if="lxStep.parent.cancel">\n' +
' <lx-button lx-color="black" lx-type="flat" ng-click="lxStep.parent.cancel()" ng-disabled="lxStep.isLoading">{{ lxStep.parent.labels.cancel }}</lx-button>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step__action lx-step__action--back" ng-if="lxStep.parent.isLinear">\n' +
' <lx-button lx-color="black" lx-type="flat" ng-click="lxStep.previousStep()" ng-disabled="lxStep.isLoading || lxStep.step.index === 0">{{ lxStep.parent.labels.back }}</lx-button>\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
'</div>');
a.put('step-nav.html', '<div class="lx-step-nav" ng-click="lxStepNav.parent.goToStep(lxStepNav.step.index)" ng-class="lxStepNav.getClasses()" lx-ripple>\n' +
' <div class="lx-step-nav__indicator lx-step-nav__indicator--index" ng-if="lxStepNav.step.isValid === undefined">\n' +
' <span>{{ lxStepNav.step.index + 1 }}</span>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step-nav__indicator lx-step-nav__indicator--icon" ng-if="lxStepNav.step.isValid === true">\n' +
' <lx-icon lx-id="check" ng-if="!lxStepNav.step.isEditable"></lx-icon>\n' +
' <lx-icon lx-id="pencil" ng-if="lxStepNav.step.isEditable"></lx-icon>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step-nav__indicator lx-step-nav__indicator--error" ng-if="lxStepNav.step.isValid === false">\n' +
' <lx-icon lx-id="alert"></lx-icon>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step-nav__wrapper">\n' +
' <div class="lx-step-nav__label">\n' +
' <span>{{ lxStepNav.step.label }}</span>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step-nav__state">\n' +
' <span ng-if="(lxStepNav.step.isValid === undefined || lxStepNav.step.isValid === true) && lxStepNav.step.isOptional">{{ lxStepNav.parent.labels.optional }}</span>\n' +
' <span ng-if="lxStepNav.step.isValid === false">{{ lxStepNav.step.errorMessage }}</span>\n' +
' </div>\n' +
' </div>\n' +
'</div>');
}]);
angular.module("lumx.switch").run(['$templateCache', function(a) { a.put('switch.html', '<div class="switch switch--{{ lxSwitch.lxColor }} switch--{{ lxSwitch.lxPosition }}">\n' +
' <input id="{{ lxSwitch.getSwitchId() }}"\n' +
' type="checkbox"\n' +
' class="switch__input"\n' +
' name="{{ lxSwitch.name }}"\n' +
' ng-model="lxSwitch.ngModel"\n' +
' ng-true-value="{{ lxSwitch.ngTrueValue }}"\n' +
' ng-false-value="{{ lxSwitch.ngFalseValue }}"\n' +
' ng-change="lxSwitch.triggerNgChange()"\n' +
' ng-disabled="lxSwitch.ngDisabled">\n' +
'\n' +
' <label for="{{ lxSwitch.getSwitchId() }}" class="switch__label" ng-transclude ng-if="!lxSwitch.getSwitchHasChildren()"></label>\n' +
' <ng-transclude-replace ng-if="lxSwitch.getSwitchHasChildren()"></ng-transclude-replace>\n' +
'</div>\n' +
'');
a.put('switch-label.html', '<label for="{{ lxSwitchLabel.getSwitchId() }}" class="switch__label" ng-transclude></label>\n' +
'');
a.put('switch-help.html', '<span class="switch__help" ng-transclude></span>\n' +
'');
}]);
angular.module("lumx.fab").run(['$templateCache', function(a) { a.put('fab.html', '<div class="fab">\n' +
' <ng-transclude-replace></ng-transclude-replace>\n' +
'</div>\n' +
'');
a.put('fab-trigger.html', '<div class="fab__primary" ng-transclude></div>\n' +
'');
a.put('fab-actions.html', '<div class="fab__actions fab__actions--{{ parentCtrl.lxDirection }}" ng-transclude></div>\n' +
'');
}]);
angular.module("lumx.icon").run(['$templateCache', function(a) { a.put('icon.html', '<i class="icon mdi" ng-class="lxIcon.getClass()"></i>');
}]);
angular.module("lumx.data-table").run(['$templateCache', function(a) { a.put('data-table.html', '<div class="data-table-container">\n' +
' <table class="data-table"\n' +
' ng-class="{ \'data-table--no-border\': !lxDataTable.border,\n' +
' \'data-table--thumbnail\': lxDataTable.thumbnail }">\n' +
' <thead>\n' +
' <tr ng-class="{ \'data-table__selectable-row\': lxDataTable.selectable,\n' +
' \'data-table__selectable-row--is-selected\': lxDataTable.selectable && lxDataTable.allRowsSelected }">\n' +
' <th ng-if="lxDataTable.thumbnail"></th>\n' +
' <th ng-click="lxDataTable.toggleAllSelected()"\n' +
' ng-if="lxDataTable.selectable"></th>\n' +
' <th ng-class=" { \'data-table__sortable-cell\': th.sortable,\n' +
' \'data-table__sortable-cell--asc\': th.sortable && th.sort === \'asc\',\n' +
' \'data-table__sortable-cell--desc\': th.sortable && th.sort === \'desc\' }"\n' +
' ng-click="lxDataTable.sort(th)"\n' +
' ng-repeat="th in lxDataTable.thead track by $index"\n' +
' ng-if="!lxDataTable.thumbnail || (lxDataTable.thumbnail && $index != 0)">\n' +
' <lx-icon lx-id="{{ th.icon }}" ng-if="th.icon"></lx-icon>\n' +
' <span>{{ th.label }}</span>\n' +
' </th>\n' +
' </tr>\n' +
' </thead>\n' +
'\n' +
' <tbody>\n' +
' <tr ng-class="{ \'data-table__selectable-row\': lxDataTable.selectable,\n' +
' \'data-table__selectable-row--is-disabled\': lxDataTable.selectable && tr.lxDataTableDisabled,\n' +
' \'data-table__selectable-row--is-selected\': lxDataTable.selectable && tr.lxDataTableSelected }"\n' +
' ng-repeat="tr in lxDataTable.tbody"\n' +
' ng-click="lxDataTable.toggle(tr)">\n' +
' <td ng-if="lxDataTable.thumbnail">\n' +
' <div ng-if="lxDataTable.thead[0].format" ng-bind-html="lxDataTable.$sce.trustAsHtml(lxDataTable.thead[0].format(tr))"></div>\n' +
' </td>\n' +
' <td ng-if="lxDataTable.selectable"></td>\n' +
' <td ng-repeat="th in lxDataTable.thead track by $index"\n' +
' ng-if="!lxDataTable.thumbnail || (lxDataTable.thumbnail && $index != 0)">\n' +
' <span ng-if="!th.format">{{ tr[th.name] }}</span>\n' +
' <div ng-if="th.format" ng-bind-html="lxDataTable.$sce.trustAsHtml(th.format(tr))"></div>\n' +
' </td>\n' +
' </tr>\n' +
' </tbody>\n' +
' </table>\n' +
'</div>');
}]); | tholu/cdnjs | ajax/libs/lumx/1.5.14/lumx.js | JavaScript | mit | 203,404 |
<?php
defined('C5_EXECUTE') or die("Access Denied.");
if (ENABLE_AREA_LAYOUTS == false) {
die(t('Area layouts have been disabled.'));
}
global $c;
$form = Loader::helper('form');
//Loader::model('layout');
if( intval($_REQUEST['lpID']) ){
$layoutPreset = LayoutPreset::getByID($_REQUEST['lpID']);
if(is_object($layoutPreset)){
$layout = $layoutPreset->getLayoutObject();
}
}elseif(intval($_REQUEST['layoutID'])){
$layout = Layout::getById( intval($_REQUEST['layoutID']) );
}else $layout = new Layout( array('type'=>'table','rows'=>1,'columns'=>3 ) );
if(!$layout ){
echo t('Error: Layout not found');
}else{
$layoutPresets=LayoutPreset::getList();
if(intval($layout->lpID))
$layoutPreset = LayoutPreset::getById($layout->lpID);
?>
<?php if (!$_REQUEST['refresh']) { ?>
<div id="ccm-layout-edit-wrapper">
<?php } ?>
<style type="text/css">
#ccmLayoutConfigOptions { margin-top:12px; }
#ccmLayoutConfigOptions table td { padding-bottom:4px; vertical-align:top; padding-bottom:12px; padding-right:12px; }
#ccmLayoutConfigOptions table td.padBottom { }
</style>
<form method="post" class="ccm-ui" id="ccmAreaLayoutForm" action="<?php echo $action?>" style="width:96%; margin:auto;">
<input id="ccmAreaLayoutForm_layoutID" name="layoutID" type="hidden" value="<?php echo intval( $layout->layoutID ) ?>" />
<input id="ccmAreaLayoutForm_arHandle" name="arHandle" type="hidden" value="<?php echo htmlentities( $a->getAreaHandle(), ENT_COMPAT, APP_CHARSET) ?>" />
<?php if (count($layoutPresets) > 0) { ?>
<h2><?php echo t('Saved Presets')?></h2>
<input type="hidden" id="ccm-layout-refresh-action" value="<?php echo $refreshAction?>" />
<select id="ccmLayoutPresentIdSelector" name="lpID">
<option value="0"><?php echo t('** Custom (No Preset)') ?></option>
<?php foreach($layoutPresets as $availablePreset){ ?>
<option value="<?php echo $availablePreset->getLayoutPresetID() ?>" <?php echo ($availablePreset->getLayoutPresetID()==intval($layout->lpID))?'selected':''?>><?php echo $availablePreset->getLayoutPresetName() ?></option>
<?php } ?>
</select>
<a href="javascript:void(0)" id="ccm-layout-delete-preset" style="display: none" onclick="ccmLayoutEdit.deletePreset()"><img src="<?php echo ASSETS_URL_IMAGES?>/icons/delete_small.png" style="vertical-align: middle" width="16" height="16" border="0" /></a>
<br/><br/>
<?php } ?>
<div id="ccmLayoutConfigOptions">
<table>
<tr>
<td><?php echo t('Columns')?>:</td>
<td class="val">
<input name="layout_columns" type="text" value="<?php echo intval($layout->columns) ?>" size=2 />
</td>
</tr>
<tr>
<td class="padBottom"><?php echo t('Rows')?>:</td>
<td class="val padBottom">
<input name="layout_rows" type="text" value="<?php echo intval($layout->rows) ?>" size=2 />
</td>
</tr>
<tr>
<td class="padBottom"><?php echo t('Spacing')?>:</td>
<td class="val padBottom">
<input name="spacing" type="text" value="<?php echo intval($layout->spacing) ?>" size=2 /> <?php echo t('px')?>
</td>
</tr>
<tr>
<td class="padBottom"><label for="locked"><?php echo t('Lock Widths') ?>:</label></td>
<td class="val padBottom">
<input id="locked" name="locked" type="checkbox" value="1" <?php echo ( intval($layout->locked) ) ? 'checked="checked"' : '' ?> />
</td>
</tr>
</table>
</div>
<?php
//To Do: only provide this option if there's 1) blocks in the main area, or 2) existing layouts
if( !intval($layout->layoutID) ){ ?>
<?php /*
<div style="margin:16px 0px">
<?php echo t('Add layout to: ') ?>
<input name="add_to_position" type="radio" value="top" /> <?php echo t('top') ?>
<input name="add_to_position" type="radio" value="bottom" checked="checked" /> <?php echo t('bottom') ?>
</div>
*/ ?>
<input type="hidden" name="add_to_position" value="bottom" />
<?php } ?>
<?php if ( is_object($layoutPreset) ) { ?>
<div id="layoutPresetActions" style="display: none">
<label class="radio"><?php echo $form->radio('layoutPresetAction', 'update_existing_preset', true)?> <?php echo t('Update "%s" preset everywhere it is used?', $layoutPreset->getLayoutPresetName())?></label>
<label class="radio"><?php echo $form->radio('layoutPresetAction', 'save_as_custom')?> <?php echo t('Use this layout here, and leave "%s" unchanged?', $layoutPreset->getLayoutPresetName())?></label>
<label class="radio"><?php echo $form->radio('layoutPresetAction', 'create_new_preset')?> <?php echo t('Save this style as a new preset?')?><br/><span style="margin-left: 20px"><?php echo $form->text('layoutPresetNameAlt', array('style' => 'width: 127px', 'disabled' => true))?></span></label>
</div>
<?php } ?>
<div id="layoutPresetActionNew" style="margin-bottom:16px;">
<label for="layoutPresetAction" class="checkbox inline">
<?php echo $form->checkbox('layoutPresetAction', 'create_new_preset')?>
<?php echo t('Save this style as a new preset.')?>
</label>
<span style="margin-left: 10px"><?php echo $form->text('layoutPresetName', array('style' => 'width: 127px', 'disabled' => true))?></span>
</div>
<?php if(!$_REQUEST['refresh']) { ?>
<div class="ccm-buttons dialog-buttons">
<a href="#" class="btn ccm-button-left cancel" onclick="jQuery.fn.dialog.closeTop(); return false"><?php echo t('Cancel')?></a>
<a href="javascript:void(0)" onclick="$('#ccmAreaLayoutForm').submit()" class="ccm-button-right accept btn primary"><?php echo intval($layout->layoutID)?t('Save Changes'):t('Add')?></a>
</div>
<?php } ?>
</form>
<script type="text/javascript">
$(function() { ccmLayoutEdit.init(); });
</script>
<?php if (!$_REQUEST['refresh']) { ?>
</div>
<?php } ?>
<?php } ?> | HB-Biomedical-Technologies/hbbt-web-skeleton | www/concrete/elements/block_area_layout.php | PHP | mit | 5,830 |
/*!
* Datepicker for Bootstrap v1.5.0-dev (https://github.com/eternicode/bootstrap-datepicker)
*
* Copyright 2012 Stefan Petre
* Improvements by Andrew Rowls
* Licensed under the Apache License v2.0 (http://www.apache.org/licenses/LICENSE-2.0)
*/
.datepicker {
padding: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
direction: ltr;
}
.datepicker-inline {
width: 220px;
}
.datepicker.datepicker-rtl {
direction: rtl;
}
.datepicker.datepicker-rtl table tr td span {
float: right;
}
.datepicker-dropdown {
top: 0;
left: 0;
}
.datepicker-dropdown:before {
content: '';
display: inline-block;
border-left: 7px solid transparent;
border-right: 7px solid transparent;
border-bottom: 7px solid #ccc;
border-top: 0;
border-bottom-color: rgba(0, 0, 0, 0.2);
position: absolute;
}
.datepicker-dropdown:after {
content: '';
display: inline-block;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-bottom: 6px solid #ffffff;
border-top: 0;
position: absolute;
}
.datepicker-dropdown.datepicker-orient-left:before {
left: 6px;
}
.datepicker-dropdown.datepicker-orient-left:after {
left: 7px;
}
.datepicker-dropdown.datepicker-orient-right:before {
right: 6px;
}
.datepicker-dropdown.datepicker-orient-right:after {
right: 7px;
}
.datepicker-dropdown.datepicker-orient-bottom:before {
top: -7px;
}
.datepicker-dropdown.datepicker-orient-bottom:after {
top: -6px;
}
.datepicker-dropdown.datepicker-orient-top:before {
bottom: -7px;
border-bottom: 0;
border-top: 7px solid #999;
}
.datepicker-dropdown.datepicker-orient-top:after {
bottom: -6px;
border-bottom: 0;
border-top: 6px solid #ffffff;
}
.datepicker > div {
display: none;
}
.datepicker.days .datepicker-days,
.datepicker.months .datepicker-months,
.datepicker.years .datepicker-years {
display: block;
}
.datepicker table {
margin: 0;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.datepicker td,
.datepicker th {
text-align: center;
width: 20px;
height: 20px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
border: none;
}
.table-striped .datepicker table tr td,
.table-striped .datepicker table tr th {
background-color: transparent;
}
.datepicker table tr td.day:hover,
.datepicker table tr td.day.focused {
background: #eeeeee;
cursor: pointer;
}
.datepicker table tr td.old,
.datepicker table tr td.new {
color: #999999;
}
.datepicker table tr td.disabled,
.datepicker table tr td.disabled:hover {
background: none;
color: #999999;
cursor: default;
}
.datepicker table tr td.highlighted {
background: #d9edf7;
border-radius: 0;
}
.datepicker table tr td.today,
.datepicker table tr td.today:hover,
.datepicker table tr td.today.disabled,
.datepicker table tr td.today.disabled:hover {
background-color: #fde19a;
background-image: -moz-linear-gradient(top, #fdd49a, #fdf59a);
background-image: -ms-linear-gradient(top, #fdd49a, #fdf59a);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fdd49a), to(#fdf59a));
background-image: -webkit-linear-gradient(top, #fdd49a, #fdf59a);
background-image: -o-linear-gradient(top, #fdd49a, #fdf59a);
background-image: linear-gradient(top, #fdd49a, #fdf59a);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fdd49a', endColorstr='#fdf59a', GradientType=0);
border-color: #fdf59a #fdf59a #fbed50;
border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
color: #000;
}
.datepicker table tr td.today:hover,
.datepicker table tr td.today:hover:hover,
.datepicker table tr td.today.disabled:hover,
.datepicker table tr td.today.disabled:hover:hover,
.datepicker table tr td.today:active,
.datepicker table tr td.today:hover:active,
.datepicker table tr td.today.disabled:active,
.datepicker table tr td.today.disabled:hover:active,
.datepicker table tr td.today.active,
.datepicker table tr td.today:hover.active,
.datepicker table tr td.today.disabled.active,
.datepicker table tr td.today.disabled:hover.active,
.datepicker table tr td.today.disabled,
.datepicker table tr td.today:hover.disabled,
.datepicker table tr td.today.disabled.disabled,
.datepicker table tr td.today.disabled:hover.disabled,
.datepicker table tr td.today[disabled],
.datepicker table tr td.today:hover[disabled],
.datepicker table tr td.today.disabled[disabled],
.datepicker table tr td.today.disabled:hover[disabled] {
background-color: #fdf59a;
}
.datepicker table tr td.today:active,
.datepicker table tr td.today:hover:active,
.datepicker table tr td.today.disabled:active,
.datepicker table tr td.today.disabled:hover:active,
.datepicker table tr td.today.active,
.datepicker table tr td.today:hover.active,
.datepicker table tr td.today.disabled.active,
.datepicker table tr td.today.disabled:hover.active {
background-color: #fbf069 \9;
}
.datepicker table tr td.today:hover:hover {
color: #000;
}
.datepicker table tr td.today.active:hover {
color: #fff;
}
.datepicker table tr td.range,
.datepicker table tr td.range:hover,
.datepicker table tr td.range.disabled,
.datepicker table tr td.range.disabled:hover {
background: #eeeeee;
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
}
.datepicker table tr td.range.today,
.datepicker table tr td.range.today:hover,
.datepicker table tr td.range.today.disabled,
.datepicker table tr td.range.today.disabled:hover {
background-color: #f3d17a;
background-image: -moz-linear-gradient(top, #f3c17a, #f3e97a);
background-image: -ms-linear-gradient(top, #f3c17a, #f3e97a);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f3c17a), to(#f3e97a));
background-image: -webkit-linear-gradient(top, #f3c17a, #f3e97a);
background-image: -o-linear-gradient(top, #f3c17a, #f3e97a);
background-image: linear-gradient(top, #f3c17a, #f3e97a);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f3c17a', endColorstr='#f3e97a', GradientType=0);
border-color: #f3e97a #f3e97a #edde34;
border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
}
.datepicker table tr td.range.today:hover,
.datepicker table tr td.range.today:hover:hover,
.datepicker table tr td.range.today.disabled:hover,
.datepicker table tr td.range.today.disabled:hover:hover,
.datepicker table tr td.range.today:active,
.datepicker table tr td.range.today:hover:active,
.datepicker table tr td.range.today.disabled:active,
.datepicker table tr td.range.today.disabled:hover:active,
.datepicker table tr td.range.today.active,
.datepicker table tr td.range.today:hover.active,
.datepicker table tr td.range.today.disabled.active,
.datepicker table tr td.range.today.disabled:hover.active,
.datepicker table tr td.range.today.disabled,
.datepicker table tr td.range.today:hover.disabled,
.datepicker table tr td.range.today.disabled.disabled,
.datepicker table tr td.range.today.disabled:hover.disabled,
.datepicker table tr td.range.today[disabled],
.datepicker table tr td.range.today:hover[disabled],
.datepicker table tr td.range.today.disabled[disabled],
.datepicker table tr td.range.today.disabled:hover[disabled] {
background-color: #f3e97a;
}
.datepicker table tr td.range.today:active,
.datepicker table tr td.range.today:hover:active,
.datepicker table tr td.range.today.disabled:active,
.datepicker table tr td.range.today.disabled:hover:active,
.datepicker table tr td.range.today.active,
.datepicker table tr td.range.today:hover.active,
.datepicker table tr td.range.today.disabled.active,
.datepicker table tr td.range.today.disabled:hover.active {
background-color: #efe24b \9;
}
.datepicker table tr td.selected,
.datepicker table tr td.selected:hover,
.datepicker table tr td.selected.disabled,
.datepicker table tr td.selected.disabled:hover {
background-color: #9e9e9e;
background-image: -moz-linear-gradient(top, #b3b3b3, #808080);
background-image: -ms-linear-gradient(top, #b3b3b3, #808080);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#b3b3b3), to(#808080));
background-image: -webkit-linear-gradient(top, #b3b3b3, #808080);
background-image: -o-linear-gradient(top, #b3b3b3, #808080);
background-image: linear-gradient(top, #b3b3b3, #808080);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#b3b3b3', endColorstr='#808080', GradientType=0);
border-color: #808080 #808080 #595959;
border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
color: #fff;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
}
.datepicker table tr td.selected:hover,
.datepicker table tr td.selected:hover:hover,
.datepicker table tr td.selected.disabled:hover,
.datepicker table tr td.selected.disabled:hover:hover,
.datepicker table tr td.selected:active,
.datepicker table tr td.selected:hover:active,
.datepicker table tr td.selected.disabled:active,
.datepicker table tr td.selected.disabled:hover:active,
.datepicker table tr td.selected.active,
.datepicker table tr td.selected:hover.active,
.datepicker table tr td.selected.disabled.active,
.datepicker table tr td.selected.disabled:hover.active,
.datepicker table tr td.selected.disabled,
.datepicker table tr td.selected:hover.disabled,
.datepicker table tr td.selected.disabled.disabled,
.datepicker table tr td.selected.disabled:hover.disabled,
.datepicker table tr td.selected[disabled],
.datepicker table tr td.selected:hover[disabled],
.datepicker table tr td.selected.disabled[disabled],
.datepicker table tr td.selected.disabled:hover[disabled] {
background-color: #808080;
}
.datepicker table tr td.selected:active,
.datepicker table tr td.selected:hover:active,
.datepicker table tr td.selected.disabled:active,
.datepicker table tr td.selected.disabled:hover:active,
.datepicker table tr td.selected.active,
.datepicker table tr td.selected:hover.active,
.datepicker table tr td.selected.disabled.active,
.datepicker table tr td.selected.disabled:hover.active {
background-color: #666666 \9;
}
.datepicker table tr td.active,
.datepicker table tr td.active:hover,
.datepicker table tr td.active.disabled,
.datepicker table tr td.active.disabled:hover {
background-color: #006dcc;
background-image: -moz-linear-gradient(top, #0088cc, #0044cc);
background-image: -ms-linear-gradient(top, #0088cc, #0044cc);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc));
background-image: -webkit-linear-gradient(top, #0088cc, #0044cc);
background-image: -o-linear-gradient(top, #0088cc, #0044cc);
background-image: linear-gradient(top, #0088cc, #0044cc);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0088cc', endColorstr='#0044cc', GradientType=0);
border-color: #0044cc #0044cc #002a80;
border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
color: #fff;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
}
.datepicker table tr td.active:hover,
.datepicker table tr td.active:hover:hover,
.datepicker table tr td.active.disabled:hover,
.datepicker table tr td.active.disabled:hover:hover,
.datepicker table tr td.active:active,
.datepicker table tr td.active:hover:active,
.datepicker table tr td.active.disabled:active,
.datepicker table tr td.active.disabled:hover:active,
.datepicker table tr td.active.active,
.datepicker table tr td.active:hover.active,
.datepicker table tr td.active.disabled.active,
.datepicker table tr td.active.disabled:hover.active,
.datepicker table tr td.active.disabled,
.datepicker table tr td.active:hover.disabled,
.datepicker table tr td.active.disabled.disabled,
.datepicker table tr td.active.disabled:hover.disabled,
.datepicker table tr td.active[disabled],
.datepicker table tr td.active:hover[disabled],
.datepicker table tr td.active.disabled[disabled],
.datepicker table tr td.active.disabled:hover[disabled] {
background-color: #0044cc;
}
.datepicker table tr td.active:active,
.datepicker table tr td.active:hover:active,
.datepicker table tr td.active.disabled:active,
.datepicker table tr td.active.disabled:hover:active,
.datepicker table tr td.active.active,
.datepicker table tr td.active:hover.active,
.datepicker table tr td.active.disabled.active,
.datepicker table tr td.active.disabled:hover.active {
background-color: #003399 \9;
}
.datepicker table tr td span {
display: block;
width: 23%;
height: 54px;
line-height: 54px;
float: left;
margin: 1%;
cursor: pointer;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.datepicker table tr td span:hover {
background: #eeeeee;
}
.datepicker table tr td span.disabled,
.datepicker table tr td span.disabled:hover {
background: none;
color: #999999;
cursor: default;
}
.datepicker table tr td span.active,
.datepicker table tr td span.active:hover,
.datepicker table tr td span.active.disabled,
.datepicker table tr td span.active.disabled:hover {
background-color: #006dcc;
background-image: -moz-linear-gradient(top, #0088cc, #0044cc);
background-image: -ms-linear-gradient(top, #0088cc, #0044cc);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc));
background-image: -webkit-linear-gradient(top, #0088cc, #0044cc);
background-image: -o-linear-gradient(top, #0088cc, #0044cc);
background-image: linear-gradient(top, #0088cc, #0044cc);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0088cc', endColorstr='#0044cc', GradientType=0);
border-color: #0044cc #0044cc #002a80;
border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
color: #fff;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
}
.datepicker table tr td span.active:hover,
.datepicker table tr td span.active:hover:hover,
.datepicker table tr td span.active.disabled:hover,
.datepicker table tr td span.active.disabled:hover:hover,
.datepicker table tr td span.active:active,
.datepicker table tr td span.active:hover:active,
.datepicker table tr td span.active.disabled:active,
.datepicker table tr td span.active.disabled:hover:active,
.datepicker table tr td span.active.active,
.datepicker table tr td span.active:hover.active,
.datepicker table tr td span.active.disabled.active,
.datepicker table tr td span.active.disabled:hover.active,
.datepicker table tr td span.active.disabled,
.datepicker table tr td span.active:hover.disabled,
.datepicker table tr td span.active.disabled.disabled,
.datepicker table tr td span.active.disabled:hover.disabled,
.datepicker table tr td span.active[disabled],
.datepicker table tr td span.active:hover[disabled],
.datepicker table tr td span.active.disabled[disabled],
.datepicker table tr td span.active.disabled:hover[disabled] {
background-color: #0044cc;
}
.datepicker table tr td span.active:active,
.datepicker table tr td span.active:hover:active,
.datepicker table tr td span.active.disabled:active,
.datepicker table tr td span.active.disabled:hover:active,
.datepicker table tr td span.active.active,
.datepicker table tr td span.active:hover.active,
.datepicker table tr td span.active.disabled.active,
.datepicker table tr td span.active.disabled:hover.active {
background-color: #003399 \9;
}
.datepicker table tr td span.old,
.datepicker table tr td span.new {
color: #999999;
}
.datepicker .datepicker-switch {
width: 145px;
}
.datepicker .datepicker-switch,
.datepicker .prev,
.datepicker .next,
.datepicker tfoot tr th {
cursor: pointer;
}
.datepicker .datepicker-switch:hover,
.datepicker .prev:hover,
.datepicker .next:hover,
.datepicker tfoot tr th:hover {
background: #eeeeee;
}
.datepicker .cw {
font-size: 10px;
width: 12px;
padding: 0 2px 0 5px;
vertical-align: middle;
}
.input-append.date .add-on,
.input-prepend.date .add-on {
cursor: pointer;
}
.input-append.date .add-on i,
.input-prepend.date .add-on i {
margin-top: 3px;
}
.input-daterange input {
text-align: center;
}
.input-daterange input:first-child {
-webkit-border-radius: 3px 0 0 3px;
-moz-border-radius: 3px 0 0 3px;
border-radius: 3px 0 0 3px;
}
.input-daterange input:last-child {
-webkit-border-radius: 0 3px 3px 0;
-moz-border-radius: 0 3px 3px 0;
border-radius: 0 3px 3px 0;
}
.input-daterange .add-on {
display: inline-block;
width: auto;
min-width: 16px;
height: 18px;
padding: 4px 5px;
font-weight: normal;
line-height: 18px;
text-align: center;
text-shadow: 0 1px 0 #ffffff;
vertical-align: middle;
background-color: #eeeeee;
border: 1px solid #ccc;
margin-left: -5px;
margin-right: -5px;
}
| dedraks/cadpaz | web/css/ceacecb_part_1_bootstrap-datepicker_1.css | CSS | mit | 17,157 |
// File: chapter14/appUnderTest/app/scripts/app.js
angular.module('fifaApp', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/team_list.html',
controller: 'TeamListCtrl as teamListCtrl'
})
.when('/login', {
templateUrl: 'views/login.html',
})
.when('/team/:code', {
templateUrl: 'views/team_details.html',
controller:'TeamDetailsCtrl as teamDetailsCtrl',
resolve: {
auth: ['$q', '$location', 'UserService',
function($q, $location, UserService) {
return UserService.session().then(
function(success) {},
function(err) {
$location.path('/login');
return $q.reject(err);
});
}]
}
});
$routeProvider.otherwise({
redirectTo: '/'
});
});
| dikshay/angularjs-up-and-running | chapter14/appUnderTest/app/scripts/app.js | JavaScript | mit | 881 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2015 Natale Patriciello <natale.patriciello@gmail.com>
* 2016 Stefano Avallone <stavallo@unina.it>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "traffic-control-layer.h"
#include "ns3/log.h"
#include "ns3/object-vector.h"
#include "ns3/packet.h"
#include "ns3/queue-disc.h"
namespace ns3 {
NS_LOG_COMPONENT_DEFINE ("TrafficControlLayer");
NS_OBJECT_ENSURE_REGISTERED (TrafficControlLayer);
TypeId
TrafficControlLayer::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::TrafficControlLayer")
.SetParent<Object> ()
.SetGroupName ("TrafficControl")
.AddConstructor<TrafficControlLayer> ()
.AddAttribute ("RootQueueDiscList", "The list of root queue discs associated to this Traffic Control layer.",
ObjectVectorValue (),
MakeObjectVectorAccessor (&TrafficControlLayer::m_rootQueueDiscs),
MakeObjectVectorChecker<QueueDisc> ())
;
return tid;
}
TypeId
TrafficControlLayer::GetInstanceTypeId (void) const
{
return GetTypeId ();
}
TrafficControlLayer::TrafficControlLayer ()
: Object ()
{
NS_LOG_FUNCTION_NOARGS ();
}
void
TrafficControlLayer::DoDispose (void)
{
NS_LOG_FUNCTION (this);
m_node = 0;
m_rootQueueDiscs.clear ();
m_handlers.clear ();
m_netDeviceQueueToQueueDiscMap.clear ();
Object::DoDispose ();
}
void
TrafficControlLayer::DoInitialize (void)
{
NS_LOG_FUNCTION (this);
for (uint32_t j = 0; j < m_rootQueueDiscs.size (); j++)
{
if (m_rootQueueDiscs[j])
{
Ptr<NetDevice> device = m_node->GetDevice (j);
// NetDevices supporting flow control can set the number of device transmission
// queues through the NetDevice queue interface during initialization. Thus,
// ensure that the device has completed initialization
device->Initialize ();
std::map<Ptr<NetDevice>, NetDeviceInfo>::iterator qdMap = m_netDeviceQueueToQueueDiscMap.find (device);
NS_ASSERT (qdMap != m_netDeviceQueueToQueueDiscMap.end ());
Ptr<NetDeviceQueueInterface> devQueueIface = qdMap->second.first;
NS_ASSERT (devQueueIface);
devQueueIface->SetQueueDiscInstalled (true);
// set the wake callbacks on netdevice queues
if (m_rootQueueDiscs[j]->GetWakeMode () == QueueDisc::WAKE_ROOT)
{
for (uint32_t i = 0; i < devQueueIface->GetTxQueuesN (); i++)
{
devQueueIface->GetTxQueue (i)->SetWakeCallback (MakeCallback (&QueueDisc::Run, m_rootQueueDiscs[j]));
qdMap->second.second.push_back (m_rootQueueDiscs[j]);
}
}
else if (m_rootQueueDiscs[j]->GetWakeMode () == QueueDisc::WAKE_CHILD)
{
NS_ASSERT_MSG (m_rootQueueDiscs[j]->GetNQueueDiscClasses () == devQueueIface->GetTxQueuesN (),
"The number of child queue discs does not match the number of netdevice queues");
for (uint32_t i = 0; i < devQueueIface->GetTxQueuesN (); i++)
{
devQueueIface->GetTxQueue (i)->SetWakeCallback (MakeCallback (&QueueDisc::Run,
m_rootQueueDiscs[j]->GetQueueDiscClass (i)->GetQueueDisc ()));
qdMap->second.second.push_back (m_rootQueueDiscs[j]->GetQueueDiscClass (i)->GetQueueDisc ());
}
}
// initialize the queue disc
m_rootQueueDiscs[j]->Initialize ();
}
}
Object::DoInitialize ();
}
void
TrafficControlLayer::SetupDevice (Ptr<NetDevice> device)
{
NS_LOG_FUNCTION (this << device);
// ensure this setup is done just once (in case of dual stack nodes)
if (device->GetObject<NetDeviceQueueInterface> ())
{
NS_LOG_DEBUG ("The setup for this device has been already done.");
return;
}
// create a NetDeviceQueueInterface object and aggregate it to the device
Ptr<NetDeviceQueueInterface> devQueueIface = CreateObject<NetDeviceQueueInterface> ();
device->AggregateObject (devQueueIface);
// store a pointer to the created queue interface
NS_ASSERT_MSG (m_netDeviceQueueToQueueDiscMap.find (device) == m_netDeviceQueueToQueueDiscMap.end (),
"This is a bug: SetupDevice should be called only once per device");
m_netDeviceQueueToQueueDiscMap[device] = NetDeviceInfo (devQueueIface, QueueDiscVector ());
}
void
TrafficControlLayer::RegisterProtocolHandler (Node::ProtocolHandler handler,
uint16_t protocolType, Ptr<NetDevice> device)
{
NS_LOG_FUNCTION (this << protocolType << device);
struct ProtocolHandlerEntry entry;
entry.handler = handler;
entry.protocol = protocolType;
entry.device = device;
entry.promiscuous = false;
m_handlers.push_back (entry);
NS_LOG_DEBUG ("Handler for NetDevice: " << device << " registered for protocol " <<
protocolType << ".");
}
void
TrafficControlLayer::SetRootQueueDiscOnDevice (Ptr<NetDevice> device, Ptr<QueueDisc> qDisc)
{
NS_LOG_FUNCTION (this << device);
uint32_t index = GetDeviceIndex (device);
NS_ASSERT_MSG (index < m_node->GetNDevices (), "The provided device does not belong to"
<< " the node which this TrafficControlLayer object is aggregated to" );
if (index >= m_rootQueueDiscs.size ())
{
m_rootQueueDiscs.resize (index+1);
}
NS_ASSERT_MSG (m_rootQueueDiscs[index] == 0, "Cannot install a root queue disc on a "
<< "device already having one. Delete the existing queue disc first.");
m_rootQueueDiscs[index] = qDisc;
}
Ptr<QueueDisc>
TrafficControlLayer::GetRootQueueDiscOnDevice (Ptr<NetDevice> device)
{
NS_LOG_FUNCTION (this << device);
uint32_t index = GetDeviceIndex (device);
NS_ASSERT_MSG (index < m_node->GetNDevices (), "The provided device does not belong to"
<< " the node which this TrafficControlLayer object is aggregated to" );
if (index >= m_rootQueueDiscs.size ())
{
m_rootQueueDiscs.resize (index+1);
}
return m_rootQueueDiscs[index];
}
void
TrafficControlLayer::DeleteRootQueueDiscOnDevice (Ptr<NetDevice> device)
{
NS_LOG_FUNCTION (this << device);
uint32_t index = GetDeviceIndex (device);
NS_ASSERT_MSG (index < m_node->GetNDevices (), "The provided device does not belong to"
<< " the node which this TrafficControlLayer object is aggregated to" );
NS_ASSERT_MSG (index < m_rootQueueDiscs.size () && m_rootQueueDiscs[index] != 0, "No root queue disc"
<< " installed on device " << device);
// remove the root queue disc
m_rootQueueDiscs[index] = 0;
}
void
TrafficControlLayer::SetNode (Ptr<Node> node)
{
NS_LOG_FUNCTION (this << node);
m_node = node;
}
void
TrafficControlLayer::NotifyNewAggregate ()
{
NS_LOG_FUNCTION (this);
if (m_node == 0)
{
Ptr<Node> node = this->GetObject<Node> ();
//verify that it's a valid node and that
//the node was not set before
if (node != 0)
{
this->SetNode (node);
}
}
Object::NotifyNewAggregate ();
}
uint32_t
TrafficControlLayer::GetDeviceIndex (Ptr<NetDevice> device)
{
NS_LOG_FUNCTION (this << device);
uint32_t i;
for (i = 0; i < m_node->GetNDevices () && device != m_node->GetDevice (i); i++);
return i;
}
void
TrafficControlLayer::Receive (Ptr<NetDevice> device, Ptr<const Packet> p,
uint16_t protocol, const Address &from, const Address &to,
NetDevice::PacketType packetType)
{
NS_LOG_FUNCTION (this << device << p << protocol << from << to << packetType);
bool found = false;
for (ProtocolHandlerList::iterator i = m_handlers.begin ();
i != m_handlers.end (); i++)
{
if (i->device == 0
|| (i->device != 0 && i->device == device))
{
if (i->protocol == 0
|| i->protocol == protocol)
{
NS_LOG_DEBUG ("Found handler for packet " << p << ", protocol " <<
protocol << " and NetDevice " << device <<
". Send packet up");
i->handler (device, p, protocol, from, to, packetType);
found = true;
}
}
}
if (! found)
{
NS_FATAL_ERROR ("Handler for protocol " << p << " and device " << device <<
" not found. It isn't forwarded up; it dies here.");
}
}
void
TrafficControlLayer::Send (Ptr<NetDevice> device, Ptr<QueueDiscItem> item)
{
NS_LOG_FUNCTION (this << device << item);
NS_LOG_DEBUG ("Send packet to device " << device << " protocol number " <<
item->GetProtocol ());
std::map<Ptr<NetDevice>, NetDeviceInfo>::iterator qdMap = m_netDeviceQueueToQueueDiscMap.find (device);
NS_ASSERT (qdMap != m_netDeviceQueueToQueueDiscMap.end ());
Ptr<NetDeviceQueueInterface> devQueueIface = qdMap->second.first;
NS_ASSERT (devQueueIface);
// determine the transmission queue of the device where the packet will be enqueued
uint8_t txq = devQueueIface->GetSelectedQueue (item);
NS_ASSERT (txq < devQueueIface->GetTxQueuesN ());
if (qdMap->second.second.empty ())
{
// The device has no attached queue disc, thus add the header to the packet and
// send it directly to the device if the selected queue is not stopped
if (!devQueueIface->GetTxQueue (txq)->IsStopped ())
{
item->AddHeader ();
device->Send (item->GetPacket (), item->GetAddress (), item->GetProtocol ());
}
}
else
{
// Enqueue the packet in the queue disc associated with the netdevice queue
// selected for the packet and try to dequeue packets from such queue disc
item->SetTxQueueIndex (txq);
Ptr<QueueDisc> qDisc = qdMap->second.second[txq];
NS_ASSERT (qDisc);
qDisc->Enqueue (item);
qDisc->Run ();
}
}
} // namespace ns3
| Vivek-anand-jain/Implementation-of-BLUE-in-ns-3 | src/traffic-control/model/traffic-control-layer.cc | C++ | gpl-2.0 | 10,705 |
/*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRINITY_GUARDAI_H
#define TRINITY_GUARDAI_H
#include "ScriptedCreature.h"
class Creature;
class TC_GAME_API GuardAI : public ScriptedAI
{
public:
explicit GuardAI(Creature* creature);
static int32 Permissible(Creature const* creature);
void UpdateAI(uint32 diff) override;
bool CanSeeAlways(WorldObject const* obj) override;
void EnterEvadeMode(EvadeReason /*why*/) override;
void JustDied(Unit* killer) override;
};
#endif
| pete318/TrinityCore | src/server/game/AI/CoreAI/GuardAI.h | C | gpl-2.0 | 1,236 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2007 INRIA
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
*/
#ifndef PACKET_SOCKET_ADDRESS_H
#define PACKET_SOCKET_ADDRESS_H
#include "ns3/ptr.h"
#include "address.h"
#include "mac48-address.h"
#include "mac64-address.h"
#include "net-device.h"
namespace ns3 {
class NetDevice;
/**
* \ingroup address
*
* \brief an address for a packet socket
*/
class PacketSocketAddress
{
public:
PacketSocketAddress ();
void SetProtocol (uint16_t protocol);
void SetAllDevices (void);
void SetSingleDevice (uint32_t device);
void SetPhysicalAddress (const Address address);
uint16_t GetProtocol (void) const;
uint32_t GetSingleDevice (void) const;
bool IsSingleDevice (void) const;
Address GetPhysicalAddress (void) const;
/**
* \returns a new Address instance
*
* Convert an instance of this class to a polymorphic Address instance.
*/
operator Address () const;
/**
* \param address a polymorphic address
*
* Convert a polymorphic address to an Mac48Address instance.
* The conversion performs a type check.
*/
static PacketSocketAddress ConvertFrom (const Address &address);
/**
* \param address address to test
* \returns true if the address matches, false otherwise.
*/
static bool IsMatchingType (const Address &address);
private:
static uint8_t GetType (void);
Address ConvertTo (void) const;
uint16_t m_protocol;
bool m_isSingleDevice;
uint32_t m_device;
Address m_address;
};
} // namespace ns3
#endif /* PACKET_SOCKET_ADDRESS_H */
| annegabrielle/secure_adhoc_network_ns-3 | src/node/packet-socket-address.h | C | gpl-2.0 | 2,277 |
/*
* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/**===========================================================================
\file wlan_hdd_softap_tx_rx.c
\brief Linux HDD Tx/RX APIs
==========================================================================*/
/*---------------------------------------------------------------------------
Include files
-------------------------------------------------------------------------*/
#include <linux/semaphore.h>
#include <wlan_hdd_tx_rx.h>
#include <wlan_hdd_softap_tx_rx.h>
#include <wlan_hdd_dp_utils.h>
#include <wlan_qct_tl.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/etherdevice.h>
//#include <vos_list.h>
#include <vos_types.h>
#include <aniGlobal.h>
#include <halTypes.h>
#include <net/ieee80211_radiotap.h>
#include <linux/ratelimit.h>
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0))
#include <soc/qcom/subsystem_restart.h>
#else
#include <mach/subsystem_restart.h>
#endif
/*---------------------------------------------------------------------------
Preprocessor definitions and constants
-------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------
Type declarations
-------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------
Function definitions and documenation
-------------------------------------------------------------------------*/
#if 0
static void hdd_softap_dump_sk_buff(struct sk_buff * skb)
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,"%s: head = %p", __func__, skb->head);
//VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,"%s: data = %p", __func__, skb->data);
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,"%s: tail = %p", __func__, skb->tail);
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,"%s: end = %p", __func__, skb->end);
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,"%s: len = %d", __func__, skb->len);
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,"%s: data_len = %d", __func__, skb->data_len);
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,"%s: mac_len = %d", __func__, skb->mac_len);
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,"0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x",
skb->data[0], skb->data[1], skb->data[2], skb->data[3], skb->data[4],
skb->data[5], skb->data[6], skb->data[7]);
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,"0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x",
skb->data[8], skb->data[9], skb->data[10], skb->data[11], skb->data[12],
skb->data[13], skb->data[14], skb->data[15]);
}
#endif
extern void hdd_set_wlan_suspend_mode(bool suspend);
#define HDD_SAP_TX_TIMEOUT_RATELIMIT_INTERVAL 20*HZ
#define HDD_SAP_TX_TIMEOUT_RATELIMIT_BURST 1
#define HDD_SAP_TX_STALL_SSR_THRESHOLD 5
static DEFINE_RATELIMIT_STATE(hdd_softap_tx_timeout_rs, \
HDD_SAP_TX_TIMEOUT_RATELIMIT_INTERVAL, \
HDD_SAP_TX_TIMEOUT_RATELIMIT_BURST);
/**============================================================================
@brief hdd_softap_traffic_monitor_timeout_handler() -
SAP/P2P GO traffin monitor timeout handler function
If no traffic during programmed time, trigger suspand mode
@param pUsrData : [in] pointer to hdd context
@return : NONE
===========================================================================*/
void hdd_softap_traffic_monitor_timeout_handler( void *pUsrData )
{
hdd_context_t *pHddCtx = (hdd_context_t *)pUsrData;
v_TIME_t currentTS;
if (NULL == pHddCtx)
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Invalid user data, context", __func__);
return;
}
currentTS = vos_timer_get_system_time();
if (pHddCtx->cfg_ini->trafficIdleTimeout <
(currentTS - pHddCtx->traffic_monitor.lastFrameTs))
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s: No Data Activity calling Wlan Suspend", __func__ );
hdd_set_wlan_suspend_mode(1);
atomic_set(&pHddCtx->traffic_monitor.isActiveMode, 0);
}
else
{
vos_timer_start(&pHddCtx->traffic_monitor.trafficTimer,
pHddCtx->cfg_ini->trafficIdleTimeout);
}
return;
}
VOS_STATUS hdd_start_trafficMonitor( hdd_adapter_t *pAdapter )
{
hdd_context_t *pHddCtx = WLAN_HDD_GET_CTX(pAdapter);
VOS_STATUS status = VOS_STATUS_SUCCESS;
status = wlan_hdd_validate_context(pHddCtx);
if (0 != status)
{
VOS_TRACE( VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
"%s: HDD context is not valid", __func__);
return status;
}
if ((pHddCtx->cfg_ini->enableTrafficMonitor) &&
(!pHddCtx->traffic_monitor.isInitialized))
{
atomic_set(&pHddCtx->traffic_monitor.isActiveMode, 1);
vos_timer_init(&pHddCtx->traffic_monitor.trafficTimer,
VOS_TIMER_TYPE_SW,
hdd_softap_traffic_monitor_timeout_handler,
pHddCtx);
vos_lock_init(&pHddCtx->traffic_monitor.trafficLock);
pHddCtx->traffic_monitor.isInitialized = 1;
pHddCtx->traffic_monitor.lastFrameTs = 0;
/* Start traffic monitor timer here
* If no AP assoc, immediatly go into suspend */
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s Start Traffic Monitor Timer", __func__);
vos_timer_start(&pHddCtx->traffic_monitor.trafficTimer,
pHddCtx->cfg_ini->trafficIdleTimeout);
}
else
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s Traffic Monitor is not Enable in ini file", __func__);
}
return status;
}
VOS_STATUS hdd_stop_trafficMonitor( hdd_adapter_t *pAdapter )
{
hdd_context_t *pHddCtx = WLAN_HDD_GET_CTX(pAdapter);
VOS_STATUS status = VOS_STATUS_SUCCESS;
status = wlan_hdd_validate_context(pHddCtx);
if (-ENODEV == status)
{
VOS_TRACE( VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
"%s: HDD context is not valid", __func__);
return status;
}
if (pHddCtx->traffic_monitor.isInitialized)
{
if (VOS_TIMER_STATE_STOPPED !=
vos_timer_getCurrentState(&pHddCtx->traffic_monitor.trafficTimer))
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s Stop Traffic Monitor Timer", __func__);
vos_timer_stop(&pHddCtx->traffic_monitor.trafficTimer);
}
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s Destroy Traffic Monitor Timer", __func__);
vos_timer_destroy(&pHddCtx->traffic_monitor.trafficTimer);
vos_lock_destroy(&pHddCtx->traffic_monitor.trafficLock);
pHddCtx->traffic_monitor.isInitialized = 0;
}
return VOS_STATUS_SUCCESS;
}
/**============================================================================
@brief hdd_softap_flush_tx_queues() - Utility function to flush the TX queues
@param pAdapter : [in] pointer to adapter context
@return : VOS_STATUS_E_FAILURE if any errors encountered
: VOS_STATUS_SUCCESS otherwise
===========================================================================*/
static VOS_STATUS hdd_softap_flush_tx_queues( hdd_adapter_t *pAdapter )
{
VOS_STATUS status = VOS_STATUS_SUCCESS;
v_SINT_t i = -1;
v_U8_t STAId = 0;
hdd_list_node_t *anchor = NULL;
skb_list_node_t *pktNode = NULL;
struct sk_buff *skb = NULL;
spin_lock_bh( &pAdapter->staInfo_lock );
for (STAId = 0; STAId < WLAN_MAX_STA_COUNT; STAId++)
{
if (FALSE == pAdapter->aStaInfo[STAId].isUsed)
{
continue;
}
for (i = 0; i < NUM_TX_QUEUES; i ++)
{
spin_lock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[i].lock);
while (true)
{
status = hdd_list_remove_front ( &pAdapter->aStaInfo[STAId].wmm_tx_queue[i], &anchor);
if (VOS_STATUS_E_EMPTY != status)
{
//If success then we got a valid packet from some AC
pktNode = list_entry(anchor, skb_list_node_t, anchor);
skb = pktNode->skb;
++pAdapter->stats.tx_dropped;
++pAdapter->hdd_stats.hddTxRxStats.txFlushed;
++pAdapter->hdd_stats.hddTxRxStats.txFlushedAC[i];
kfree_skb(skb);
continue;
}
//current list is empty
break;
}
pAdapter->aStaInfo[STAId].txSuspended[i] = VOS_FALSE;
spin_unlock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[i].lock);
}
pAdapter->aStaInfo[STAId].vosLowResource = VOS_FALSE;
}
spin_unlock_bh( &pAdapter->staInfo_lock );
return status;
}
/**============================================================================
@brief hdd_softap_hard_start_xmit() - Function registered with the Linux OS for
transmitting packets. There are 2 versions of this function. One that uses
locked queue and other that uses lockless queues. Both have been retained to
do some performance testing
@param skb : [in] pointer to OS packet (sk_buff)
@param dev : [in] pointer to Libra network device
@return : NET_XMIT_DROP if packets are dropped
: NET_XMIT_SUCCESS if packet is enqueued succesfully
===========================================================================*/
int hdd_softap_hard_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
VOS_STATUS status;
WLANTL_ACEnumType ac = WLANTL_AC_BE;
sme_QosWmmUpType up = SME_QOS_WMM_UP_BE;
skb_list_node_t *pktNode = NULL;
v_SIZE_t pktListSize = 0;
v_BOOL_t txSuspended = VOS_FALSE;
hdd_adapter_t *pAdapter = (hdd_adapter_t *)netdev_priv(dev);
hdd_ap_ctx_t *pHddApCtx = WLAN_HDD_GET_AP_CTX_PTR(pAdapter);
vos_list_node_t *anchor = NULL;
v_U8_t STAId = WLAN_MAX_STA_COUNT;
//Extract the destination address from ethernet frame
v_MACADDR_t *pDestMacAddress = (v_MACADDR_t*)skb->data;
int os_status = NETDEV_TX_OK;
pDestMacAddress = (v_MACADDR_t*)skb->data;
++pAdapter->hdd_stats.hddTxRxStats.txXmitCalled;
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s: enter", __func__);
spin_lock_bh( &pAdapter->staInfo_lock );
if (vos_is_macaddr_broadcast( pDestMacAddress ) || vos_is_macaddr_group(pDestMacAddress))
{
//The BC/MC station ID is assigned during BSS starting phase. SAP will return the station
//ID used for BC/MC traffic. The station id is registered to TL as well.
STAId = pHddApCtx->uBCStaId;
/* Setting priority for broadcast packets which doesn't go to select_queue function */
skb->priority = SME_QOS_WMM_UP_BE;
skb->queue_mapping = HDD_LINUX_AC_BE;
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO_LOW,
"%s: BC/MC packet", __func__);
}
else
{
STAId = *(v_U8_t *)(((v_U8_t *)(skb->data)) - 1);
if (STAId == HDD_WLAN_INVALID_STA_ID)
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_WARN,
"%s: Failed to find right station", __func__);
++pAdapter->stats.tx_dropped;
++pAdapter->hdd_stats.hddTxRxStats.txXmitDropped;
kfree_skb(skb);
goto xmit_done;
}
else if (FALSE == pAdapter->aStaInfo[STAId].isUsed )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_WARN,
"%s: STA %d is unregistered", __func__, STAId);
++pAdapter->stats.tx_dropped;
++pAdapter->hdd_stats.hddTxRxStats.txXmitDropped;
kfree_skb(skb);
goto xmit_done;
}
if ( (WLANTL_STA_CONNECTED != pAdapter->aStaInfo[STAId].tlSTAState) &&
(WLANTL_STA_AUTHENTICATED != pAdapter->aStaInfo[STAId].tlSTAState) )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_WARN,
"%s: Station not connected yet", __func__);
++pAdapter->stats.tx_dropped;
++pAdapter->hdd_stats.hddTxRxStats.txXmitDropped;
kfree_skb(skb);
goto xmit_done;
}
else if(WLANTL_STA_CONNECTED == pAdapter->aStaInfo[STAId].tlSTAState)
{
if(ntohs(skb->protocol) != HDD_ETHERTYPE_802_1_X)
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_WARN,
"%s: NON-EAPOL packet in non-Authenticated state", __func__);
++pAdapter->stats.tx_dropped;
++pAdapter->hdd_stats.hddTxRxStats.txXmitDropped;
kfree_skb(skb);
goto xmit_done;
}
}
}
//Get TL AC corresponding to Qdisc queue index/AC.
ac = hdd_QdiscAcToTlAC[skb->queue_mapping];
//user priority from IP header, which is already extracted and set from
//select_queue call back function
up = skb->priority;
++pAdapter->hdd_stats.hddTxRxStats.txXmitClassifiedAC[ac];
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s: Classified as ac %d up %d", __func__, ac, up);
// If the memory differentiation mode is enabled, the memory limit of each queue will be
// checked. Over-limit packets will be dropped.
spin_lock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac].lock);
hdd_list_size(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac], &pktListSize);
if(pktListSize >= pAdapter->aTxQueueLimit[ac])
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_WARN,
"%s: station %d ac %d queue over limit %d", __func__, STAId, ac, pktListSize);
pAdapter->aStaInfo[STAId].txSuspended[ac] = VOS_TRUE;
netif_stop_subqueue(dev, skb_get_queue_mapping(skb));
txSuspended = VOS_TRUE;
}
/* If 3/4th of the max queue size is used then enable the flag.
* This flag indicates to place the DHCP packets in VOICE AC queue.*/
if (WLANTL_AC_BE == ac)
{
if (pAdapter->aStaInfo[STAId].wmm_tx_queue[ac].count >= HDD_TX_QUEUE_LOW_WATER_MARK)
{
VOS_TRACE( VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_WARN,
"%s: TX queue for Best Effort AC is 3/4th full", __func__);
pAdapter->aStaInfo[STAId].vosLowResource = VOS_TRUE;
}
else
{
pAdapter->aStaInfo[STAId].vosLowResource = VOS_FALSE;
}
}
spin_unlock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac].lock);
if (VOS_TRUE == txSuspended)
{
VOS_TRACE( VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_WARN,
"%s: TX queue full for AC=%d Disable OS TX queue",
__func__, ac );
os_status = NETDEV_TX_BUSY;
goto xmit_done;
}
//Use the skb->cb field to hold the list node information
pktNode = (skb_list_node_t *)&skb->cb;
//Stick the OS packet inside this node.
pktNode->skb = skb;
//Stick the User Priority inside this node
pktNode->userPriority = up;
INIT_LIST_HEAD(&pktNode->anchor);
spin_lock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac].lock);
status = hdd_list_insert_back_size(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac], &pktNode->anchor, &pktListSize );
spin_unlock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac].lock);
if ( !VOS_IS_STATUS_SUCCESS( status ) )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_WARN,
"%s:Insert Tx queue failed. Pkt dropped", __func__);
++pAdapter->hdd_stats.hddTxRxStats.txXmitDropped;
++pAdapter->hdd_stats.hddTxRxStats.txXmitDroppedAC[ac];
++pAdapter->stats.tx_dropped;
kfree_skb(skb);
goto xmit_done;
}
++pAdapter->hdd_stats.hddTxRxStats.txXmitQueued;
++pAdapter->hdd_stats.hddTxRxStats.txXmitQueuedAC[ac];
++pAdapter->hdd_stats.hddTxRxStats.pkt_tx_count;
if (1 == pktListSize)
{
//Let TL know we have a packet to send for this AC
status = WLANTL_STAPktPending( (WLAN_HDD_GET_CTX(pAdapter))->pvosContext, STAId, ac );
if ( !VOS_IS_STATUS_SUCCESS( status ) )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_WARN,
"%s: Failed to signal TL for AC=%d STAId =%d",
__func__, ac, STAId );
//Remove the packet from queue. It must be at the back of the queue, as TX thread cannot preempt us in the middle
//as we are in a soft irq context. Also it must be the same packet that we just allocated.
spin_lock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac].lock);
status = hdd_list_remove_back( &pAdapter->aStaInfo[STAId].wmm_tx_queue[ac], &anchor);
spin_unlock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac].lock);
++pAdapter->stats.tx_dropped;
++pAdapter->hdd_stats.hddTxRxStats.txXmitDropped;
++pAdapter->hdd_stats.hddTxRxStats.txXmitDroppedAC[ac];
kfree_skb(skb);
goto xmit_done;
}
}
dev->trans_start = jiffies;
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO_LOW,
"%s: exit", __func__);
xmit_done:
spin_unlock_bh( &pAdapter->staInfo_lock );
return os_status;
}
/**============================================================================
@brief hdd_softap_sta_2_sta_xmit This function for Transmitting the frames when the traffic is between two stations.
@param skb : [in] pointer to packet (sk_buff)
@param dev : [in] pointer to Libra network device
@param STAId : [in] Station Id of Destination Station
@param up : [in] User Priority
@return : NET_XMIT_DROP if packets are dropped
: NET_XMIT_SUCCESS if packet is enqueued succesfully
===========================================================================*/
VOS_STATUS hdd_softap_sta_2_sta_xmit(struct sk_buff *skb,
struct net_device *dev,
v_U8_t STAId,
v_U8_t up)
{
VOS_STATUS status = VOS_STATUS_SUCCESS;
skb_list_node_t *pktNode = NULL;
v_SIZE_t pktListSize = 0;
hdd_adapter_t *pAdapter = (hdd_adapter_t *)netdev_priv(dev);
v_U8_t ac;
vos_list_node_t *anchor = NULL;
++pAdapter->hdd_stats.hddTxRxStats.txXmitCalled;
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s: enter", __func__);
spin_lock_bh( &pAdapter->staInfo_lock );
if ( FALSE == pAdapter->aStaInfo[STAId].isUsed )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_WARN,
"%s: STA %d is unregistered", __func__, STAId );
kfree_skb(skb);
status = VOS_STATUS_E_FAILURE;
goto xmit_end;
}
/* If the QoS is not enabled on the receiving station, then send it with BE priority */
if ( !pAdapter->aStaInfo[STAId].isQosEnabled )
up = SME_QOS_WMM_UP_BE;
ac = hddWmmUpToAcMap[up];
++pAdapter->hdd_stats.hddTxRxStats.txXmitClassifiedAC[ac];
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s: Classified as ac %d up %d", __func__, ac, up);
skb->queue_mapping = hddLinuxUpToAcMap[up];
//Use the skb->cb field to hold the list node information
pktNode = (skb_list_node_t *)&skb->cb;
//Stick the OS packet inside this node.
pktNode->skb = skb;
//Stick the User Priority inside this node
pktNode->userPriority = up;
INIT_LIST_HEAD(&pktNode->anchor);
spin_lock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac].lock);
hdd_list_size(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac], &pktListSize);
if(pAdapter->aStaInfo[STAId].txSuspended[ac] ||
pktListSize >= pAdapter->aTxQueueLimit[ac])
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_WARN,
"%s: station %d ac %d queue over limit %d", __func__, STAId, ac, pktListSize);
/* TODO:Rx Flowchart should be trigerred here to SUPEND SSC on RX side.
* SUSPEND should be done based on Threshold. RESUME would be
* triggered in fetch cbk after recovery.
*/
kfree_skb(skb);
spin_unlock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac].lock);
status = VOS_STATUS_E_FAILURE;
goto xmit_end;
}
status = hdd_list_insert_back_size(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac], &pktNode->anchor, &pktListSize );
spin_unlock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac].lock);
if ( !VOS_IS_STATUS_SUCCESS( status ) )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_WARN,
"%s:Insert Tx queue failed. Pkt dropped", __func__);
++pAdapter->hdd_stats.hddTxRxStats.txXmitDropped;
++pAdapter->hdd_stats.hddTxRxStats.txXmitDroppedAC[ac];
++pAdapter->stats.tx_dropped;
kfree_skb(skb);
status = VOS_STATUS_E_FAILURE;
goto xmit_end;
}
++pAdapter->hdd_stats.hddTxRxStats.txXmitQueued;
++pAdapter->hdd_stats.hddTxRxStats.txXmitQueuedAC[ac];
if (1 == pktListSize)
{
//Let TL know we have a packet to send for this AC
//VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,"%s:Indicating Packet to TL", __func__);
status = WLANTL_STAPktPending( (WLAN_HDD_GET_CTX(pAdapter))->pvosContext, STAId, ac );
if ( !VOS_IS_STATUS_SUCCESS( status ) )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_WARN,
"%s: Failed to signal TL for AC=%d STAId =%d",
__func__, ac, STAId );
//Remove the packet from queue. It must be at the back of the queue, as TX thread cannot preempt us in the middle
//as we are in a soft irq context. Also it must be the same packet that we just allocated.
spin_lock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac].lock);
status = hdd_list_remove_back( &pAdapter->aStaInfo[STAId].wmm_tx_queue[ac], &anchor);
spin_unlock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac].lock);
++pAdapter->stats.tx_dropped;
++pAdapter->hdd_stats.hddTxRxStats.txXmitDropped;
++pAdapter->hdd_stats.hddTxRxStats.txXmitDroppedAC[ac];
kfree_skb(skb);
status = VOS_STATUS_E_FAILURE;
goto xmit_end;
}
}
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO_LOW, "%s: exit", __func__);
xmit_end:
spin_unlock_bh( &pAdapter->staInfo_lock );
return status;
}
/**============================================================================
@brief hdd_softap_tx_timeout() - Function called by OS if there is any
timeout during transmission. Since HDD simply enqueues packet
and returns control to OS right away, this would never be invoked
@param dev : [in] pointer to Libra network device
@return : None
===========================================================================*/
void hdd_softap_tx_timeout(struct net_device *dev)
{
hdd_adapter_t *pAdapter = WLAN_HDD_GET_PRIV_PTR(dev);
struct netdev_queue *txq;
int i = 0;
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Transmission timeout occurred", __func__);
if ( NULL == pAdapter )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
FL("pAdapter is NULL"));
VOS_ASSERT(0);
return;
}
++pAdapter->hdd_stats.hddTxRxStats.txTimeoutCount;
for (i = 0; i < 8; i++)
{
txq = netdev_get_tx_queue(dev, i);
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"Queue%d status: %d", i, netif_tx_queue_stopped(txq));
}
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"carrier state: %d", netif_carrier_ok(dev));
++pAdapter->hdd_stats.hddTxRxStats.continuousTxTimeoutCount;
if (pAdapter->hdd_stats.hddTxRxStats.continuousTxTimeoutCount >
HDD_SAP_TX_STALL_SSR_THRESHOLD)
{
// Driver could not recover, issue SSR
VOS_TRACE(VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Cannot recover from Data stall Issue SSR",
__func__);
WLANTL_FatalError();
return;
}
/* If Tx stalled for a long time then *hdd_tx_timeout* is called
* every 5sec. The TL debug spits out a lot of information on the
* serial console, if it is called every time *hdd_tx_timeout* is
* called then we may get a watchdog bite on the Application
* processor, so ratelimit the TL debug logs.
*/
if (__ratelimit(&hdd_softap_tx_timeout_rs))
{
hdd_wmm_tx_snapshot(pAdapter);
WLANTL_TLDebugMessage(VOS_TRUE);
}
}
/**============================================================================
@brief hdd_softap_stats() - Function registered with the Linux OS for
device TX/RX statistic
@param dev : [in] pointer to Libra network device
@return : pointer to net_device_stats structure
===========================================================================*/
struct net_device_stats* hdd_softap_stats(struct net_device *dev)
{
hdd_adapter_t* priv = netdev_priv(dev);
return &priv->stats;
}
/**============================================================================
@brief hdd_softap_init_tx_rx() - Init function to initialize Tx/RX
modules in HDD
@param pAdapter : [in] pointer to adapter context
@return : VOS_STATUS_E_FAILURE if any errors encountered
: VOS_STATUS_SUCCESS otherwise
===========================================================================*/
VOS_STATUS hdd_softap_init_tx_rx( hdd_adapter_t *pAdapter )
{
VOS_STATUS status = VOS_STATUS_SUCCESS;
v_SINT_t i = -1;
v_SIZE_t size = 0;
v_U8_t STAId = 0;
v_U8_t pACWeights[] = {
HDD_SOFTAP_BK_WEIGHT_DEFAULT,
HDD_SOFTAP_BE_WEIGHT_DEFAULT,
HDD_SOFTAP_VI_WEIGHT_DEFAULT,
HDD_SOFTAP_VO_WEIGHT_DEFAULT
};
pAdapter->isVosOutOfResource = VOS_FALSE;
pAdapter->isVosLowResource = VOS_FALSE;
vos_mem_zero(&pAdapter->stats, sizeof(struct net_device_stats));
while (++i != NUM_TX_QUEUES)
hdd_list_init( &pAdapter->wmm_tx_queue[i], HDD_TX_QUEUE_MAX_LEN);
/* Initial HDD buffer control / flow control fields*/
vos_pkt_get_available_buffer_pool (VOS_PKT_TYPE_TX_802_3_DATA, &size);
pAdapter->aTxQueueLimit[WLANTL_AC_BK] = HDD_SOFTAP_TX_BK_QUEUE_MAX_LEN;
pAdapter->aTxQueueLimit[WLANTL_AC_BE] = HDD_SOFTAP_TX_BE_QUEUE_MAX_LEN;
pAdapter->aTxQueueLimit[WLANTL_AC_VI] = HDD_SOFTAP_TX_VI_QUEUE_MAX_LEN;
pAdapter->aTxQueueLimit[WLANTL_AC_VO] = HDD_SOFTAP_TX_VO_QUEUE_MAX_LEN;
spin_lock_init( &pAdapter->staInfo_lock );
for (STAId = 0; STAId < WLAN_MAX_STA_COUNT; STAId++)
{
vos_mem_zero(&pAdapter->aStaInfo[STAId], sizeof(hdd_station_info_t));
for (i = 0; i < NUM_TX_QUEUES; i ++)
{
hdd_list_init(&pAdapter->aStaInfo[STAId].wmm_tx_queue[i], HDD_TX_QUEUE_MAX_LEN);
}
}
/* Update the AC weights suitable for SoftAP mode of operation */
WLANTL_SetACWeights((WLAN_HDD_GET_CTX(pAdapter))->pvosContext, pACWeights);
if (VOS_STATUS_SUCCESS != hdd_start_trafficMonitor(pAdapter))
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: failed to start Traffic Monito timer ", __func__ );
return VOS_STATUS_E_INVAL;
}
return status;
}
/**============================================================================
@brief hdd_softap_deinit_tx_rx() - Deinit function to clean up Tx/RX
modules in HDD
@param pAdapter : [in] pointer to adapter context
@return : VOS_STATUS_E_FAILURE if any errors encountered
: VOS_STATUS_SUCCESS otherwise
===========================================================================*/
VOS_STATUS hdd_softap_deinit_tx_rx( hdd_adapter_t *pAdapter )
{
VOS_STATUS status = VOS_STATUS_SUCCESS;
if (VOS_STATUS_SUCCESS != hdd_stop_trafficMonitor(pAdapter))
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Fail to Stop Traffic Monito timer", __func__ );
return VOS_STATUS_E_INVAL;
}
status = hdd_softap_flush_tx_queues(pAdapter);
return status;
}
/**============================================================================
@brief hdd_softap_flush_tx_queues_sta() - Utility function to flush the TX queues of a station
@param pAdapter : [in] pointer to adapter context
@param STAId : [in] Station ID to deinit
@return : VOS_STATUS_E_FAILURE if any errors encountered
: VOS_STATUS_SUCCESS otherwise
===========================================================================*/
static VOS_STATUS hdd_softap_flush_tx_queues_sta( hdd_adapter_t *pAdapter, v_U8_t STAId )
{
v_U8_t i = -1;
hdd_list_node_t *anchor = NULL;
skb_list_node_t *pktNode = NULL;
struct sk_buff *skb = NULL;
if (FALSE == pAdapter->aStaInfo[STAId].isUsed)
{
return VOS_STATUS_SUCCESS;
}
for (i = 0; i < NUM_TX_QUEUES; i ++)
{
spin_lock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[i].lock);
while (true)
{
if (VOS_STATUS_E_EMPTY !=
hdd_list_remove_front(&pAdapter->aStaInfo[STAId].wmm_tx_queue[i],
&anchor))
{
//If success then we got a valid packet from some AC
pktNode = list_entry(anchor, skb_list_node_t, anchor);
skb = pktNode->skb;
++pAdapter->stats.tx_dropped;
++pAdapter->hdd_stats.hddTxRxStats.txFlushed;
++pAdapter->hdd_stats.hddTxRxStats.txFlushedAC[i];
kfree_skb(skb);
continue;
}
//current list is empty
break;
}
spin_unlock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[i].lock);
}
return VOS_STATUS_SUCCESS;
}
/**============================================================================
@brief hdd_softap_init_tx_rx_sta() - Init function to initialize a station in Tx/RX
modules in HDD
@param pAdapter : [in] pointer to adapter context
@param STAId : [in] Station ID to deinit
@param pmacAddrSTA : [in] pointer to the MAC address of the station
@return : VOS_STATUS_E_FAILURE if any errors encountered
: VOS_STATUS_SUCCESS otherwise
===========================================================================*/
VOS_STATUS hdd_softap_init_tx_rx_sta( hdd_adapter_t *pAdapter, v_U8_t STAId, v_MACADDR_t *pmacAddrSTA)
{
v_U8_t i = 0;
spin_lock_bh( &pAdapter->staInfo_lock );
if (pAdapter->aStaInfo[STAId].isUsed)
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Reinit station %d", __func__, STAId );
spin_unlock_bh( &pAdapter->staInfo_lock );
return VOS_STATUS_E_FAILURE;
}
vos_mem_zero(&pAdapter->aStaInfo[STAId], sizeof(hdd_station_info_t));
for (i = 0; i < NUM_TX_QUEUES; i ++)
{
hdd_list_init(&pAdapter->aStaInfo[STAId].wmm_tx_queue[i], HDD_TX_QUEUE_MAX_LEN);
}
pAdapter->aStaInfo[STAId].isUsed = TRUE;
pAdapter->aStaInfo[STAId].isDeauthInProgress = FALSE;
vos_copy_macaddr( &pAdapter->aStaInfo[STAId].macAddrSTA, pmacAddrSTA);
spin_unlock_bh( &pAdapter->staInfo_lock );
return VOS_STATUS_SUCCESS;
}
/**============================================================================
@brief hdd_softap_deinit_tx_rx_sta() - Deinit function to clean up a statioin in Tx/RX
modules in HDD
@param pAdapter : [in] pointer to adapter context
@param STAId : [in] Station ID to deinit
@return : VOS_STATUS_E_FAILURE if any errors encountered
: VOS_STATUS_SUCCESS otherwise
===========================================================================*/
VOS_STATUS hdd_softap_deinit_tx_rx_sta ( hdd_adapter_t *pAdapter, v_U8_t STAId )
{
VOS_STATUS status = VOS_STATUS_SUCCESS;
v_U8_t ac;
/**Track whether OS TX queue has been disabled.*/
v_BOOL_t txSuspended[NUM_TX_QUEUES];
v_U8_t tlAC;
hdd_hostapd_state_t *pHostapdState;
v_U8_t i;
pHostapdState = WLAN_HDD_GET_HOSTAP_STATE_PTR(pAdapter);
spin_lock_bh( &pAdapter->staInfo_lock );
if (FALSE == pAdapter->aStaInfo[STAId].isUsed)
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Deinit station not inited %d", __func__, STAId );
spin_unlock_bh( &pAdapter->staInfo_lock );
return VOS_STATUS_E_FAILURE;
}
status = hdd_softap_flush_tx_queues_sta(pAdapter, STAId);
pAdapter->aStaInfo[STAId].isUsed = FALSE;
pAdapter->aStaInfo[STAId].isDeauthInProgress = FALSE;
/* if this STA had any of its WMM TX queues suspended, then the
associated queue on the network interface was disabled. check
to see if that is the case, in which case we need to re-enable
the interface queue. but we only do this if the BSS is running
since, if the BSS is stopped, all of the interfaces have been
stopped and should not be re-enabled */
if (BSS_START == pHostapdState->bssState)
{
for (ac = HDD_LINUX_AC_VO; ac <= HDD_LINUX_AC_BK; ac++)
{
tlAC = hdd_QdiscAcToTlAC[ac];
txSuspended[ac] = pAdapter->aStaInfo[STAId].txSuspended[tlAC];
}
}
vos_mem_zero(&pAdapter->aStaInfo[STAId], sizeof(hdd_station_info_t));
/* re-init spin lock, since netdev can still open adapter until
* driver gets unloaded
*/
for (i = 0; i < NUM_TX_QUEUES; i ++)
{
hdd_list_init(&pAdapter->aStaInfo[STAId].wmm_tx_queue[i],
HDD_TX_QUEUE_MAX_LEN);
}
if (BSS_START == pHostapdState->bssState)
{
for (ac = HDD_LINUX_AC_VO; ac <= HDD_LINUX_AC_BK; ac++)
{
if (txSuspended[ac])
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s: TX queue re-enabled", __func__);
netif_wake_subqueue(pAdapter->dev, ac);
}
}
}
spin_unlock_bh( &pAdapter->staInfo_lock );
return status;
}
/**============================================================================
@brief hdd_softap_disconnect_tx_rx() - Disconnect function to clean up Tx/RX
modules in HDD
@param pAdapter : [in] pointer to adapter context
@return : VOS_STATUS_E_FAILURE if any errors encountered
: VOS_STATUS_SUCCESS otherwise
===========================================================================*/
VOS_STATUS hdd_softap_disconnect_tx_rx( hdd_adapter_t *pAdapter )
{
return hdd_softap_flush_tx_queues(pAdapter);
}
/**============================================================================
@brief hdd_softap_tx_complete_cbk() - Callback function invoked by TL
to indicate that a packet has been transmitted across the bus
succesfully. OS packet resources can be released after this cbk.
@param vosContext : [in] pointer to VOS context
@param pVosPacket : [in] pointer to VOS packet (containing skb)
@param vosStatusIn : [in] status of the transmission
@return : VOS_STATUS_E_FAILURE if any errors encountered
: VOS_STATUS_SUCCESS otherwise
===========================================================================*/
VOS_STATUS hdd_softap_tx_complete_cbk( v_VOID_t *vosContext,
vos_pkt_t *pVosPacket,
VOS_STATUS vosStatusIn )
{
VOS_STATUS status = VOS_STATUS_SUCCESS;
hdd_adapter_t *pAdapter = NULL;
void* pOsPkt = NULL;
if( ( NULL == vosContext ) || ( NULL == pVosPacket ) )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Null params being passed", __func__);
return VOS_STATUS_E_FAILURE;
}
//Return the skb to the OS
status = vos_pkt_get_os_packet( pVosPacket, &pOsPkt, VOS_TRUE );
if(!VOS_IS_STATUS_SUCCESS( status ))
{
//This is bad but still try to free the VOSS resources if we can
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Failure extracting skb from vos pkt", __func__);
vos_pkt_return_packet( pVosPacket );
return VOS_STATUS_E_FAILURE;
}
//Get the Adapter context.
pAdapter = (hdd_adapter_t *)netdev_priv(((struct sk_buff *)pOsPkt)->dev);
if(pAdapter == NULL)
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: HDD adapter context is Null", __func__);
}
else
{
++pAdapter->hdd_stats.hddTxRxStats.txCompleted;
}
kfree_skb((struct sk_buff *)pOsPkt);
//Return the VOS packet resources.
status = vos_pkt_return_packet( pVosPacket );
if(!VOS_IS_STATUS_SUCCESS( status ))
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Could not return VOS packet to the pool", __func__);
}
return status;
}
/**============================================================================
@brief hdd_softap_tx_fetch_packet_cbk() - Callback function invoked by TL to
fetch a packet for transmission.
@param vosContext : [in] pointer to VOS context
@param staId : [in] Station for which TL is requesting a pkt
@param ac : [in] access category requested by TL
@param pVosPacket : [out] pointer to VOS packet packet pointer
@param pPktMetaInfo : [out] pointer to meta info for the pkt
@return : VOS_STATUS_E_EMPTY if no packets to transmit
: VOS_STATUS_E_FAILURE if any errors encountered
: VOS_STATUS_SUCCESS otherwise
===========================================================================*/
VOS_STATUS hdd_softap_tx_fetch_packet_cbk( v_VOID_t *vosContext,
v_U8_t *pStaId,
WLANTL_ACEnumType ac,
vos_pkt_t **ppVosPacket,
WLANTL_MetaInfoType *pPktMetaInfo )
{
VOS_STATUS status = VOS_STATUS_E_FAILURE;
hdd_adapter_t *pAdapter = NULL;
hdd_list_node_t *anchor = NULL;
skb_list_node_t *pktNode = NULL;
struct sk_buff *skb = NULL;
vos_pkt_t *pVosPacket = NULL;
v_MACADDR_t* pDestMacAddress = NULL;
v_TIME_t timestamp;
v_SIZE_t size = 0;
v_U8_t STAId = WLAN_MAX_STA_COUNT;
hdd_context_t *pHddCtx = NULL;
v_U8_t proto_type = 0;
//Sanity check on inputs
if ( ( NULL == vosContext ) ||
( NULL == pStaId ) ||
( NULL == ppVosPacket ) ||
( NULL == pPktMetaInfo ) )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Null Params being passed", __func__);
return VOS_STATUS_E_FAILURE;
}
//Get the HDD context.
pHddCtx = (hdd_context_t *)vos_get_context( VOS_MODULE_ID_HDD, vosContext );
if ( NULL == pHddCtx )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: HDD adapter context is Null", __func__);
return VOS_STATUS_E_FAILURE;
}
STAId = *pStaId;
if (STAId >= WLAN_MAX_STA_COUNT)
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Invalid STAId %d passed by TL", __func__, STAId);
return VOS_STATUS_E_FAILURE;
}
pAdapter = pHddCtx->sta_to_adapter[STAId];
if ((NULL == pAdapter) || (WLAN_HDD_ADAPTER_MAGIC != pAdapter->magic))
{
VOS_ASSERT(0);
return VOS_STATUS_E_FAILURE;
}
if (FALSE == pAdapter->aStaInfo[STAId].isUsed )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Unregistered STAId %d passed by TL", __func__, STAId);
return VOS_STATUS_E_FAILURE;
}
/* Monitor traffic */
if ( pHddCtx->cfg_ini->enableTrafficMonitor )
{
pHddCtx->traffic_monitor.lastFrameTs = vos_timer_get_system_time();
if ( !atomic_read(&pHddCtx->traffic_monitor.isActiveMode) )
{
vos_lock_acquire(&pHddCtx->traffic_monitor.trafficLock);
/* It was IDLE mode,
* this is new state, then switch mode from suspend to resume */
if ( !atomic_read(&pHddCtx->traffic_monitor.isActiveMode) )
{
hdd_set_wlan_suspend_mode(0);
vos_timer_start(&pHddCtx->traffic_monitor.trafficTimer,
pHddCtx->cfg_ini->trafficIdleTimeout);
atomic_set(&pHddCtx->traffic_monitor.isActiveMode, 1);
}
vos_lock_release(&pHddCtx->traffic_monitor.trafficLock);
}
}
++pAdapter->hdd_stats.hddTxRxStats.txFetched;
*ppVosPacket = NULL;
//Make sure the AC being asked for is sane
if( ac > WLANTL_MAX_AC || ac < 0)
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Invalid AC %d passed by TL", __func__, ac);
return VOS_STATUS_E_FAILURE;
}
++pAdapter->hdd_stats.hddTxRxStats.txFetchedAC[ac];
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s: AC %d passed by TL", __func__, ac);
//Get the vos packet. I don't want to dequeue and enqueue again if we are out of VOS resources
//This simplifies the locking and unlocking of Tx queue
status = vos_pkt_wrap_data_packet( &pVosPacket,
VOS_PKT_TYPE_TX_802_3_DATA,
NULL, //OS Pkt is not being passed
hdd_softap_tx_low_resource_cbk,
pAdapter );
if (status == VOS_STATUS_E_ALREADY || status == VOS_STATUS_E_RESOURCES)
{
//Remember VOS is in a low resource situation
pAdapter->isVosOutOfResource = VOS_TRUE;
++pAdapter->hdd_stats.hddTxRxStats.txFetchLowResources;
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_WARN,
"%s: VOSS in Low Resource scenario", __func__);
//TL needs to handle this case. VOS_STATUS_E_EMPTY is returned when the queue is empty.
return VOS_STATUS_E_FAILURE;
}
/* Only fetch this station and this AC. Return VOS_STATUS_E_EMPTY if nothing there. Do not get next AC
as the other branch does.
*/
spin_lock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac].lock);
hdd_list_size(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac], &size);
if (0 == size)
{
spin_unlock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac].lock);
vos_pkt_return_packet(pVosPacket);
return VOS_STATUS_E_EMPTY;
}
status = hdd_list_remove_front( &pAdapter->aStaInfo[STAId].wmm_tx_queue[ac], &anchor );
spin_unlock_bh(&pAdapter->aStaInfo[STAId].wmm_tx_queue[ac].lock);
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s: AC %d has packets pending", __func__, ac);
if(VOS_STATUS_SUCCESS == status)
{
//If success then we got a valid packet from some AC
pktNode = list_entry(anchor, skb_list_node_t, anchor);
skb = pktNode->skb;
}
else
{
++pAdapter->hdd_stats.hddTxRxStats.txFetchDequeueError;
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Error in de-queuing skb from Tx queue status = %d",
__func__, status );
vos_pkt_return_packet(pVosPacket);
return VOS_STATUS_E_FAILURE;
}
//Attach skb to VOS packet.
status = vos_pkt_set_os_packet( pVosPacket, skb );
if (status != VOS_STATUS_SUCCESS)
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Error attaching skb", __func__);
vos_pkt_return_packet(pVosPacket);
++pAdapter->stats.tx_dropped;
++pAdapter->hdd_stats.hddTxRxStats.txFetchDequeueError;
kfree_skb(skb);
return VOS_STATUS_E_FAILURE;
}
//Just being paranoid. To be removed later
if(pVosPacket == NULL)
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: VOS packet returned by VOSS is NULL", __func__);
++pAdapter->stats.tx_dropped;
++pAdapter->hdd_stats.hddTxRxStats.txFetchDequeueError;
kfree_skb(skb);
return VOS_STATUS_E_FAILURE;
}
//Return VOS packet to TL;
*ppVosPacket = pVosPacket;
//Fill out the meta information needed by TL
//FIXME This timestamp is really the time stamp of wrap_data_packet
vos_pkt_get_timestamp( pVosPacket, ×tamp );
pPktMetaInfo->usTimeStamp = (v_U16_t)timestamp;
if ( 1 < size )
{
pPktMetaInfo->bMorePackets = 1; //HDD has more packets to send
}
else
{
pPktMetaInfo->bMorePackets = 0;
}
pPktMetaInfo->ucIsEapol = 0;
if(pAdapter->aStaInfo[STAId].tlSTAState != WLANTL_STA_AUTHENTICATED)
{
if (TRUE == hdd_IsEAPOLPacket( pVosPacket ))
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO_HIGH,
"%s: VOS packet is EAPOL packet", __func__);
pPktMetaInfo->ucIsEapol = 1;
}
}
if (pHddCtx->cfg_ini->gEnableDebugLog)
{
proto_type = vos_pkt_get_proto_type(skb,
pHddCtx->cfg_ini->gEnableDebugLog);
if (VOS_PKT_PROTO_TYPE_EAPOL & proto_type)
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
"SAP TX EAPOL");
}
else if (VOS_PKT_PROTO_TYPE_DHCP & proto_type)
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
"SAP TX DHCP");
}
}
//xg: @@@@: temporarily disble these. will revisit later
{
pPktMetaInfo->ucUP = pktNode->userPriority;
pPktMetaInfo->ucTID = pPktMetaInfo->ucUP;
}
pPktMetaInfo->ucType = 0; //FIXME Don't know what this is
//Extract the destination address from ethernet frame
pDestMacAddress = (v_MACADDR_t*)skb->data;
// we need 802.3 to 802.11 frame translation
// (note that Bcast/Mcast will be translated in SW, unicast in HW)
pPktMetaInfo->ucDisableFrmXtl = 0;
pPktMetaInfo->ucBcast = vos_is_macaddr_broadcast( pDestMacAddress ) ? 1 : 0;
pPktMetaInfo->ucMcast = vos_is_macaddr_group( pDestMacAddress ) ? 1 : 0;
if ( (pAdapter->aStaInfo[STAId].txSuspended[ac]) &&
(size <= ((pAdapter->aTxQueueLimit[ac]*3)/4) ))
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s: TX queue re-enabled", __func__);
pAdapter->aStaInfo[STAId].txSuspended[ac] = VOS_FALSE;
netif_wake_subqueue(pAdapter->dev, skb_get_queue_mapping(skb));
}
// We're giving the packet to TL so consider it transmitted from
// a statistics perspective. We account for it here instead of
// when the packet is returned for two reasons. First, TL will
// manipulate the skb to the point where the len field is not
// accurate, leading to inaccurate byte counts if we account for
// it later. Second, TL does not provide any feedback as to
// whether or not the packet was successfully sent over the air,
// so the packet counts will be the same regardless of where we
// account for them
pAdapter->stats.tx_bytes += skb->len;
++pAdapter->stats.tx_packets;
++pAdapter->hdd_stats.hddTxRxStats.txFetchDequeued;
++pAdapter->hdd_stats.hddTxRxStats.txFetchDequeuedAC[ac];
pAdapter->hdd_stats.hddTxRxStats.continuousTxTimeoutCount = 0;
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s: Valid VOS PKT returned to TL", __func__);
return status;
}
/**============================================================================
@brief hdd_softap_tx_low_resource_cbk() - Callback function invoked in the
case where VOS packets are not available at the time of the call to get
packets. This callback function is invoked by VOS when packets are
available.
@param pVosPacket : [in] pointer to VOS packet
@param userData : [in] opaque user data that was passed initially
@return : VOS_STATUS_E_FAILURE if any errors encountered,
: VOS_STATUS_SUCCESS otherwise
=============================================================================*/
VOS_STATUS hdd_softap_tx_low_resource_cbk( vos_pkt_t *pVosPacket,
v_VOID_t *userData )
{
VOS_STATUS status;
v_SINT_t i = 0;
v_SIZE_t size = 0;
hdd_adapter_t* pAdapter = (hdd_adapter_t *)userData;
v_U8_t STAId = WLAN_MAX_STA_COUNT;
if(pAdapter == NULL)
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: HDD adapter context is Null", __func__);
return VOS_STATUS_E_FAILURE;
}
//Return the packet to VOS. We just needed to know that VOS is out of low resource
//situation. Here we will only signal TL that there is a pending data for a STA.
//VOS packet will be requested (if needed) when TL comes back to fetch data.
vos_pkt_return_packet( pVosPacket );
pAdapter->isVosOutOfResource = VOS_FALSE;
// Indicate to TL that there is pending data if a queue is non empty.
// This Code wasnt included in earlier version which resulted in
// Traffic stalling
for (STAId = 0; STAId < WLAN_MAX_STA_COUNT; STAId++)
{
if ((pAdapter->aStaInfo[STAId].tlSTAState == WLANTL_STA_AUTHENTICATED) ||
(pAdapter->aStaInfo[STAId].tlSTAState == WLANTL_STA_CONNECTED))
{
for( i=NUM_TX_QUEUES-1; i>=0; --i )
{
size = 0;
hdd_list_size(&pAdapter->aStaInfo[STAId].wmm_tx_queue[i], &size);
if ( size > 0 )
{
status = WLANTL_STAPktPending( (WLAN_HDD_GET_CTX(pAdapter))->pvosContext,
STAId,
(WLANTL_ACEnumType)i );
if( !VOS_IS_STATUS_SUCCESS( status ) )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Failure in indicating pkt to TL for ac=%d", __func__,i);
}
}
}
}
}
return VOS_STATUS_SUCCESS;
}
/**============================================================================
@brief hdd_softap_rx_packet_cbk() - Receive callback registered with TL.
TL will call this to notify the HDD when one or more packets were
received for a registered STA.
@param vosContext : [in] pointer to VOS context
@param pVosPacketChain : [in] pointer to VOS packet chain
@param staId : [in] Station Id (Adress 1 Index)
@param pRxMetaInfo : [in] pointer to meta info for the received pkt(s).
@return : VOS_STATUS_E_FAILURE if any errors encountered,
: VOS_STATUS_SUCCESS otherwise
===========================================================================*/
VOS_STATUS hdd_softap_rx_packet_cbk( v_VOID_t *vosContext,
vos_pkt_t *pVosPacketChain,
v_U8_t staId,
WLANTL_RxMetaInfoType* pRxMetaInfo )
{
hdd_adapter_t *pAdapter = NULL;
VOS_STATUS status = VOS_STATUS_E_FAILURE;
int rxstat;
struct sk_buff *skb = NULL;
vos_pkt_t* pVosPacket;
vos_pkt_t* pNextVosPacket;
hdd_context_t *pHddCtx = NULL;
v_U8_t proto_type;
//Sanity check on inputs
if ( ( NULL == vosContext ) ||
( NULL == pVosPacketChain ) ||
( NULL == pRxMetaInfo ) )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Null params being passed", __func__);
return VOS_STATUS_E_FAILURE;
}
pHddCtx = (hdd_context_t *)vos_get_context( VOS_MODULE_ID_HDD, vosContext );
if ( NULL == pHddCtx )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: HDD adapter context is Null", __func__);
return VOS_STATUS_E_FAILURE;
}
pAdapter = pHddCtx->sta_to_adapter[staId];
if( NULL == pAdapter )
{
VOS_ASSERT(0);
return VOS_STATUS_E_FAILURE;
}
/* Monitor traffic */
if ( pHddCtx->cfg_ini->enableTrafficMonitor )
{
pHddCtx->traffic_monitor.lastFrameTs = vos_timer_get_system_time();
if ( !atomic_read(&pHddCtx->traffic_monitor.isActiveMode) )
{
vos_lock_acquire(&pHddCtx->traffic_monitor.trafficLock);
/* It was IDLE mode,
* this is new state, then switch mode from suspend to resume */
if ( !atomic_read(&pHddCtx->traffic_monitor.isActiveMode) )
{
hdd_set_wlan_suspend_mode(0);
vos_timer_start(&pHddCtx->traffic_monitor.trafficTimer,
pHddCtx->cfg_ini->trafficIdleTimeout);
atomic_set(&pHddCtx->traffic_monitor.isActiveMode, 1);
}
vos_lock_release(&pHddCtx->traffic_monitor.trafficLock);
}
}
++pAdapter->hdd_stats.hddTxRxStats.rxChains;
// walk the chain until all are processed
pVosPacket = pVosPacketChain;
do
{
// get the pointer to the next packet in the chain
// (but don't unlink the packet since we free the entire chain later)
status = vos_pkt_walk_packet_chain( pVosPacket, &pNextVosPacket, VOS_FALSE);
// both "success" and "empty" are acceptable results
if (!((status == VOS_STATUS_SUCCESS) || (status == VOS_STATUS_E_EMPTY)))
{
++pAdapter->hdd_stats.hddTxRxStats.rxDropped;
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Failure walking packet chain", __func__);
return VOS_STATUS_E_FAILURE;
}
// Extract the OS packet (skb).
// Tell VOS to detach the OS packet from the VOS packet
status = vos_pkt_get_os_packet( pVosPacket, (v_VOID_t **)&skb, VOS_TRUE );
if(!VOS_IS_STATUS_SUCCESS( status ))
{
++pAdapter->hdd_stats.hddTxRxStats.rxDropped;
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Failure extracting skb from vos pkt", __func__);
return VOS_STATUS_E_FAILURE;
}
//hdd_softap_dump_sk_buff(skb);
skb->dev = pAdapter->dev;
if(skb->dev == NULL) {
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_FATAL,
"ERROR!!Invalid netdevice");
return VOS_STATUS_E_FAILURE;
}
++pAdapter->hdd_stats.hddTxRxStats.rxPackets;
++pAdapter->stats.rx_packets;
pAdapter->stats.rx_bytes += skb->len;
if (pHddCtx->cfg_ini->gEnableDebugLog)
{
proto_type = vos_pkt_get_proto_type(skb,
pHddCtx->cfg_ini->gEnableDebugLog);
if (VOS_PKT_PROTO_TYPE_EAPOL & proto_type)
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
"SAP RX EAPOL");
}
else if (VOS_PKT_PROTO_TYPE_DHCP & proto_type)
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
"SAP RX DHCP");
}
}
if (WLAN_RX_BCMC_STA_ID == pRxMetaInfo->ucDesSTAId)
{
//MC/BC packets. Duplicate a copy of packet
struct sk_buff *pSkbCopy;
hdd_ap_ctx_t *pHddApCtx;
pHddApCtx = WLAN_HDD_GET_AP_CTX_PTR(pAdapter);
if (!(pHddApCtx->apDisableIntraBssFwd))
{
pSkbCopy = skb_copy(skb, GFP_ATOMIC);
if (pSkbCopy)
{
hdd_softap_sta_2_sta_xmit(pSkbCopy, pSkbCopy->dev,
pHddApCtx->uBCStaId, (pRxMetaInfo->ucUP));
}
}
else
{
VOS_TRACE(VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: skb allocation fails", __func__);
}
} //(WLAN_RX_BCMC_STA_ID == staId)
if ((WLAN_RX_BCMC_STA_ID == pRxMetaInfo->ucDesSTAId) ||
(WLAN_RX_SAP_SELF_STA_ID == pRxMetaInfo->ucDesSTAId))
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO_LOW,
"%s: send one packet to kernel", __func__);
skb->protocol = eth_type_trans(skb, skb->dev);
skb->ip_summed = CHECKSUM_NONE;
#ifdef WLAN_OPEN_SOURCE
#ifdef WLAN_FEATURE_HOLD_RX_WAKELOCK
wake_lock_timeout(&pHddCtx->rx_wake_lock, msecs_to_jiffies(HDD_WAKE_LOCK_DURATION));
#endif
#endif
rxstat = netif_rx_ni(skb);
if (NET_RX_SUCCESS == rxstat)
{
++pAdapter->hdd_stats.hddTxRxStats.rxDelivered;
++pAdapter->hdd_stats.hddTxRxStats.pkt_rx_count;
}
else
{
++pAdapter->hdd_stats.hddTxRxStats.rxRefused;
}
}
else if ((WLAN_HDD_GET_AP_CTX_PTR(pAdapter))->apDisableIntraBssFwd)
{
kfree_skb(skb);
}
else
{
//loopback traffic
status = hdd_softap_sta_2_sta_xmit(skb, skb->dev,
pRxMetaInfo->ucDesSTAId, (pRxMetaInfo->ucUP));
}
// now process the next packet in the chain
pVosPacket = pNextVosPacket;
} while (pVosPacket);
//Return the entire VOS packet chain to the resource pool
status = vos_pkt_return_packet( pVosPacketChain );
if(!VOS_IS_STATUS_SUCCESS( status ))
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Failure returning vos pkt", __func__);
}
pAdapter->dev->last_rx = jiffies;
return status;
}
VOS_STATUS hdd_softap_DeregisterSTA( hdd_adapter_t *pAdapter, tANI_U8 staId )
{
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
hdd_context_t *pHddCtx;
if (NULL == pAdapter)
{
VOS_TRACE(VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: pAdapter is NULL", __func__);
return VOS_STATUS_E_INVAL;
}
if (WLAN_HDD_ADAPTER_MAGIC != pAdapter->magic)
{
VOS_TRACE(VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Invalid pAdapter magic", __func__);
return VOS_STATUS_E_INVAL;
}
pHddCtx = (hdd_context_t*)(pAdapter->pHddCtx);
//Clear station in TL and then update HDD data structures. This helps
//to block RX frames from other station to this station.
vosStatus = WLANTL_ClearSTAClient( pHddCtx->pvosContext, staId );
if ( !VOS_IS_STATUS_SUCCESS( vosStatus ) )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"WLANTL_ClearSTAClient() failed to for staID %d. "
"Status= %d [0x%08lX]",
staId, vosStatus, vosStatus );
}
vosStatus = hdd_softap_deinit_tx_rx_sta ( pAdapter, staId );
if( VOS_STATUS_E_FAILURE == vosStatus )
{
VOS_TRACE ( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"hdd_softap_deinit_tx_rx_sta() failed for staID %d. "
"Status = %d [0x%08lX]",
staId, vosStatus, vosStatus );
return( vosStatus );
}
pHddCtx->sta_to_adapter[staId] = NULL;
return( vosStatus );
}
VOS_STATUS hdd_softap_RegisterSTA( hdd_adapter_t *pAdapter,
v_BOOL_t fAuthRequired,
v_BOOL_t fPrivacyBit,
v_U8_t staId,
v_U8_t ucastSig,
v_U8_t bcastSig,
v_MACADDR_t *pPeerMacAddress,
v_BOOL_t fWmmEnabled )
{
VOS_STATUS vosStatus = VOS_STATUS_E_FAILURE;
WLAN_STADescType staDesc = {0};
hdd_context_t *pHddCtx = pAdapter->pHddCtx;
hdd_adapter_t *pmonAdapter = NULL;
//eCsrEncryptionType connectedCipherAlgo;
//v_BOOL_t fConnected;
/*
* Clean up old entry if it is not cleaned up properly
*/
if ( pAdapter->aStaInfo[staId].isUsed )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"clean up old entry for STA %d", staId);
hdd_softap_DeregisterSTA( pAdapter, staId );
}
// Get the Station ID from the one saved during the assocation.
staDesc.ucSTAId = staId;
/*Save the pAdapter Pointer for this staId*/
pHddCtx->sta_to_adapter[staId] = pAdapter;
staDesc.wSTAType = WLAN_STA_SOFTAP;
vos_mem_copy( staDesc.vSTAMACAddress.bytes, pPeerMacAddress->bytes,sizeof(pPeerMacAddress->bytes) );
vos_mem_copy( staDesc.vBSSIDforIBSS.bytes, &pAdapter->macAddressCurrent,6 );
vos_copy_macaddr( &staDesc.vSelfMACAddress, &pAdapter->macAddressCurrent );
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"register station");
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"station mac " MAC_ADDRESS_STR,
MAC_ADDR_ARRAY(staDesc.vSTAMACAddress.bytes));
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"BSSIDforIBSS " MAC_ADDRESS_STR,
MAC_ADDR_ARRAY(staDesc.vBSSIDforIBSS.bytes));
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"SOFTAP SELFMAC " MAC_ADDRESS_STR,
MAC_ADDR_ARRAY(staDesc.vSelfMACAddress.bytes));
vosStatus = hdd_softap_init_tx_rx_sta(pAdapter, staId, &staDesc.vSTAMACAddress);
staDesc.ucQosEnabled = fWmmEnabled;
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"HDD SOFTAP register TL QoS_enabled=%d",
staDesc.ucQosEnabled );
staDesc.ucProtectedFrame = (v_U8_t)fPrivacyBit ;
// For PRIMA UMA frame translation is not enable yet.
staDesc.ucSwFrameTXXlation = 1;
staDesc.ucSwFrameRXXlation = 1;
staDesc.ucAddRmvLLC = 1;
// Initialize signatures and state
staDesc.ucUcastSig = ucastSig;
staDesc.ucBcastSig = bcastSig;
staDesc.ucInitState = fAuthRequired ?
WLANTL_STA_CONNECTED : WLANTL_STA_AUTHENTICATED;
staDesc.ucIsReplayCheckValid = VOS_FALSE;
// Register the Station with TL...
vosStatus = WLANTL_RegisterSTAClient( (WLAN_HDD_GET_CTX(pAdapter))->pvosContext,
hdd_softap_rx_packet_cbk,
hdd_softap_tx_complete_cbk,
hdd_softap_tx_fetch_packet_cbk, &staDesc, 0 );
if ( !VOS_IS_STATUS_SUCCESS( vosStatus ) )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"SOFTAP WLANTL_RegisterSTAClient() failed to register. Status= %d [0x%08X]",
vosStatus, vosStatus );
return vosStatus;
}
//Timer value should be in milliseconds
if ( pHddCtx->cfg_ini->dynSplitscan &&
( VOS_TIMER_STATE_RUNNING !=
vos_timer_getCurrentState(&pHddCtx->tx_rx_trafficTmr)))
{
vos_timer_start(&pHddCtx->tx_rx_trafficTmr,
pHddCtx->cfg_ini->trafficMntrTmrForSplitScan);
}
// if ( WPA ), tell TL to go to 'connected' and after keys come to the driver,
// then go to 'authenticated'. For all other authentication types (those that do
// not require upper layer authentication) we can put TL directly into 'authenticated'
// state.
//VOS_ASSERT( fConnected );
pAdapter->aStaInfo[staId].ucSTAId = staId;
pAdapter->aStaInfo[staId].isQosEnabled = fWmmEnabled;
if ( !fAuthRequired )
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"open/shared auth StaId= %d. Changing TL state to AUTHENTICATED at Join time",
pAdapter->aStaInfo[staId].ucSTAId );
// Connections that do not need Upper layer auth, transition TL directly
// to 'Authenticated' state.
vosStatus = WLANTL_ChangeSTAState( (WLAN_HDD_GET_CTX(pAdapter))->pvosContext, staDesc.ucSTAId,
WLANTL_STA_AUTHENTICATED );
pAdapter->aStaInfo[staId].tlSTAState = WLANTL_STA_AUTHENTICATED;
pAdapter->sessionCtx.ap.uIsAuthenticated = VOS_TRUE;
}
else
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"ULA auth StaId= %d. Changing TL state to CONNECTED at Join time", pAdapter->aStaInfo[staId].ucSTAId );
vosStatus = WLANTL_ChangeSTAState( (WLAN_HDD_GET_CTX(pAdapter))->pvosContext, staDesc.ucSTAId,
WLANTL_STA_CONNECTED );
pAdapter->aStaInfo[staId].tlSTAState = WLANTL_STA_CONNECTED;
pAdapter->sessionCtx.ap.uIsAuthenticated = VOS_FALSE;
}
pmonAdapter= hdd_get_mon_adapter( pAdapter->pHddCtx);
if(pmonAdapter)
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO_HIGH,
"Turn on Monitor the carrier");
netif_carrier_on(pmonAdapter->dev);
//Enable Tx queue
netif_tx_start_all_queues(pmonAdapter->dev);
}
netif_carrier_on(pAdapter->dev);
//Enable Tx queue
netif_tx_start_all_queues(pAdapter->dev);
return( vosStatus );
}
VOS_STATUS hdd_softap_Register_BC_STA( hdd_adapter_t *pAdapter, v_BOOL_t fPrivacyBit)
{
VOS_STATUS vosStatus = VOS_STATUS_E_FAILURE;
hdd_context_t *pHddCtx = WLAN_HDD_GET_CTX(pAdapter);
v_MACADDR_t broadcastMacAddr = VOS_MAC_ADDR_BROADCAST_INITIALIZER;
pHddCtx->sta_to_adapter[WLAN_RX_BCMC_STA_ID] = pAdapter;
pHddCtx->sta_to_adapter[WLAN_RX_SAP_SELF_STA_ID] = pAdapter;
vosStatus = hdd_softap_RegisterSTA( pAdapter, VOS_FALSE, fPrivacyBit, (WLAN_HDD_GET_AP_CTX_PTR(pAdapter))->uBCStaId, 0, 1, &broadcastMacAddr,0);
return vosStatus;
}
VOS_STATUS hdd_softap_Deregister_BC_STA( hdd_adapter_t *pAdapter)
{
return hdd_softap_DeregisterSTA( pAdapter, (WLAN_HDD_GET_AP_CTX_PTR(pAdapter))->uBCStaId);
}
VOS_STATUS hdd_softap_stop_bss( hdd_adapter_t *pAdapter)
{
hdd_context_t *pHddCtx;
VOS_STATUS vosStatus = VOS_STATUS_E_FAILURE;
v_U8_t staId = 0;
pHddCtx = WLAN_HDD_GET_CTX(pAdapter);
/*bss deregister is not allowed during wlan driver loading or unloading*/
if (WLAN_HDD_IS_LOAD_UNLOAD_IN_PROGRESS(pHddCtx))
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
"%s:Loading_unloading in Progress. Ignore!!!",__func__);
return VOS_STATUS_E_PERM;
}
vosStatus = hdd_softap_Deregister_BC_STA( pAdapter);
if (!VOS_IS_STATUS_SUCCESS(vosStatus))
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Failed to deregister BC sta Id %d", __func__, (WLAN_HDD_GET_AP_CTX_PTR(pAdapter))->uBCStaId);
}
for (staId = 0; staId < WLAN_MAX_STA_COUNT; staId++)
{
if (pAdapter->aStaInfo[staId].isUsed)// This excludes BC sta as it is already deregistered
{
vosStatus = hdd_softap_DeregisterSTA( pAdapter, staId);
if (!VOS_IS_STATUS_SUCCESS(vosStatus))
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Failed to deregister sta Id %d", __func__, staId);
}
}
}
return vosStatus;
}
VOS_STATUS hdd_softap_change_STA_state( hdd_adapter_t *pAdapter, v_MACADDR_t *pDestMacAddress, WLANTL_STAStateType state)
{
v_U8_t ucSTAId = WLAN_MAX_STA_COUNT;
VOS_STATUS vosStatus = eHAL_STATUS_SUCCESS;
v_CONTEXT_t pVosContext = (WLAN_HDD_GET_CTX(pAdapter))->pvosContext;
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s: enter", __func__);
if (VOS_STATUS_SUCCESS != hdd_softap_GetStaId(pAdapter, pDestMacAddress, &ucSTAId))
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Failed to find right station", __func__);
return VOS_STATUS_E_FAILURE;
}
if (FALSE == vos_is_macaddr_equal(&pAdapter->aStaInfo[ucSTAId].macAddrSTA, pDestMacAddress))
{
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_ERROR,
"%s: Station MAC address does not matching", __func__);
return VOS_STATUS_E_FAILURE;
}
vosStatus = WLANTL_ChangeSTAState( pVosContext, ucSTAId, state );
VOS_TRACE( VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s: change station to state %d succeed", __func__, state);
if (VOS_STATUS_SUCCESS == vosStatus)
{
pAdapter->aStaInfo[ucSTAId].tlSTAState = WLANTL_STA_AUTHENTICATED;
}
VOS_TRACE(VOS_MODULE_ID_HDD_SAP_DATA, VOS_TRACE_LEVEL_INFO,
"%s exit",__func__);
return vosStatus;
}
VOS_STATUS hdd_softap_GetStaId(hdd_adapter_t *pAdapter, v_MACADDR_t *pMacAddress, v_U8_t *staId)
{
v_U8_t i;
for (i = 0; i < WLAN_MAX_STA_COUNT; i++)
{
if (vos_mem_compare(&pAdapter->aStaInfo[i].macAddrSTA, pMacAddress, sizeof(v_MACADDR_t)) &&
pAdapter->aStaInfo[i].isUsed)
{
*staId = i;
return VOS_STATUS_SUCCESS;
}
}
return VOS_STATUS_E_FAILURE;
}
VOS_STATUS hdd_softap_GetConnectedStaId(hdd_adapter_t *pAdapter, v_U8_t *staId)
{
v_U8_t i;
for (i = 0; i < WLAN_MAX_STA_COUNT; i++)
{
if (pAdapter->aStaInfo[i].isUsed &&
(!vos_is_macaddr_broadcast(&pAdapter->aStaInfo[i].macAddrSTA)))
{
*staId = i;
return VOS_STATUS_SUCCESS;
}
}
return VOS_STATUS_E_FAILURE;
}
| monishk10/moshi_cancro | drivers/staging/prima/CORE/HDD/src/wlan_hdd_softap_tx_rx.c | C | gpl-2.0 | 71,439 |
/*******************************************************************************
Intel 10 Gigabit PCI Express Linux driver
Copyright(c) 1999 - 2013 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope 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 St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
Linux NICS <linux.nics@intel.com>
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include "ixgbe.h"
#include "ixgbe_type.h"
#include "ixgbe_dcb.h"
#include "ixgbe_dcb_82598.h"
/**
* ixgbe_dcb_config_rx_arbiter_82598 - Config Rx data arbiter
* @hw: pointer to hardware structure
* @refill: refill credits index by traffic class
* @max: max credits index by traffic class
* @prio_type: priority type indexed by traffic class
*
* Configure Rx Data Arbiter and credits for each traffic class.
*/
s32 ixgbe_dcb_config_rx_arbiter_82598(struct ixgbe_hw *hw,
u16 *refill,
u16 *max,
u8 *prio_type)
{
u32 reg = 0;
u32 credit_refill = 0;
u32 credit_max = 0;
u8 i = 0;
reg = IXGBE_READ_REG(hw, IXGBE_RUPPBMR) | IXGBE_RUPPBMR_MQA;
IXGBE_WRITE_REG(hw, IXGBE_RUPPBMR, reg);
reg = IXGBE_READ_REG(hw, IXGBE_RMCS);
/* Enable Arbiter */
reg &= ~IXGBE_RMCS_ARBDIS;
/* Enable Receive Recycle within the BWG */
reg |= IXGBE_RMCS_RRM;
/* Enable Deficit Fixed Priority arbitration*/
reg |= IXGBE_RMCS_DFP;
IXGBE_WRITE_REG(hw, IXGBE_RMCS, reg);
/* Configure traffic class credits and priority */
for (i = 0; i < MAX_TRAFFIC_CLASS; i++) {
credit_refill = refill[i];
credit_max = max[i];
reg = credit_refill | (credit_max << IXGBE_RT2CR_MCL_SHIFT);
if (prio_type[i] == prio_link)
reg |= IXGBE_RT2CR_LSP;
IXGBE_WRITE_REG(hw, IXGBE_RT2CR(i), reg);
}
reg = IXGBE_READ_REG(hw, IXGBE_RDRXCTL);
reg |= IXGBE_RDRXCTL_RDMTS_1_2;
reg |= IXGBE_RDRXCTL_MPBEN;
reg |= IXGBE_RDRXCTL_MCEN;
IXGBE_WRITE_REG(hw, IXGBE_RDRXCTL, reg);
reg = IXGBE_READ_REG(hw, IXGBE_RXCTRL);
/* Make sure there is enough descriptors before arbitration */
reg &= ~IXGBE_RXCTRL_DMBYPS;
IXGBE_WRITE_REG(hw, IXGBE_RXCTRL, reg);
return 0;
}
/**
* ixgbe_dcb_config_tx_desc_arbiter_82598 - Config Tx Desc. arbiter
* @hw: pointer to hardware structure
* @refill: refill credits index by traffic class
* @max: max credits index by traffic class
* @bwg_id: bandwidth grouping indexed by traffic class
* @prio_type: priority type indexed by traffic class
*
* Configure Tx Descriptor Arbiter and credits for each traffic class.
*/
s32 ixgbe_dcb_config_tx_desc_arbiter_82598(struct ixgbe_hw *hw,
u16 *refill,
u16 *max,
u8 *bwg_id,
u8 *prio_type)
{
u32 reg, max_credits;
u8 i;
reg = IXGBE_READ_REG(hw, IXGBE_DPMCS);
/* Enable arbiter */
reg &= ~IXGBE_DPMCS_ARBDIS;
reg |= IXGBE_DPMCS_TSOEF;
/* Configure Max TSO packet size 34KB including payload and headers */
reg |= (0x4 << IXGBE_DPMCS_MTSOS_SHIFT);
IXGBE_WRITE_REG(hw, IXGBE_DPMCS, reg);
/* Configure traffic class credits and priority */
for (i = 0; i < MAX_TRAFFIC_CLASS; i++) {
max_credits = max[i];
reg = max_credits << IXGBE_TDTQ2TCCR_MCL_SHIFT;
reg |= refill[i];
reg |= (u32)(bwg_id[i]) << IXGBE_TDTQ2TCCR_BWG_SHIFT;
if (prio_type[i] == prio_group)
reg |= IXGBE_TDTQ2TCCR_GSP;
if (prio_type[i] == prio_link)
reg |= IXGBE_TDTQ2TCCR_LSP;
IXGBE_WRITE_REG(hw, IXGBE_TDTQ2TCCR(i), reg);
}
return 0;
}
/**
* ixgbe_dcb_config_tx_data_arbiter_82598 - Config Tx data arbiter
* @hw: pointer to hardware structure
* @refill: refill credits index by traffic class
* @max: max credits index by traffic class
* @bwg_id: bandwidth grouping indexed by traffic class
* @prio_type: priority type indexed by traffic class
*
* Configure Tx Data Arbiter and credits for each traffic class.
*/
s32 ixgbe_dcb_config_tx_data_arbiter_82598(struct ixgbe_hw *hw,
u16 *refill,
u16 *max,
u8 *bwg_id,
u8 *prio_type)
{
u32 reg;
u8 i;
reg = IXGBE_READ_REG(hw, IXGBE_PDPMCS);
/* Enable Data Plane Arbiter */
reg &= ~IXGBE_PDPMCS_ARBDIS;
/* Enable DFP and Transmit Recycle Mode */
reg |= (IXGBE_PDPMCS_TPPAC | IXGBE_PDPMCS_TRM);
IXGBE_WRITE_REG(hw, IXGBE_PDPMCS, reg);
/* Configure traffic class credits and priority */
for (i = 0; i < MAX_TRAFFIC_CLASS; i++) {
reg = refill[i];
reg |= (u32)(max[i]) << IXGBE_TDPT2TCCR_MCL_SHIFT;
reg |= (u32)(bwg_id[i]) << IXGBE_TDPT2TCCR_BWG_SHIFT;
if (prio_type[i] == prio_group)
reg |= IXGBE_TDPT2TCCR_GSP;
if (prio_type[i] == prio_link)
reg |= IXGBE_TDPT2TCCR_LSP;
IXGBE_WRITE_REG(hw, IXGBE_TDPT2TCCR(i), reg);
}
/* Enable Tx packet buffer division */
reg = IXGBE_READ_REG(hw, IXGBE_DTXCTL);
reg |= IXGBE_DTXCTL_ENDBUBD;
IXGBE_WRITE_REG(hw, IXGBE_DTXCTL, reg);
return 0;
}
/**
* ixgbe_dcb_config_pfc_82598 - Config priority flow control
* @hw: pointer to hardware structure
* @pfc_en: enabled pfc bitmask
*
* Configure Priority Flow Control for each traffic class.
*/
s32 ixgbe_dcb_config_pfc_82598(struct ixgbe_hw *hw, u8 pfc_en)
{
u32 fcrtl, reg;
u8 i;
/* Enable Transmit Priority Flow Control */
reg = IXGBE_READ_REG(hw, IXGBE_RMCS);
reg &= ~IXGBE_RMCS_TFCE_802_3X;
reg |= IXGBE_RMCS_TFCE_PRIORITY;
IXGBE_WRITE_REG(hw, IXGBE_RMCS, reg);
/* Enable Receive Priority Flow Control */
reg = IXGBE_READ_REG(hw, IXGBE_FCTRL);
reg &= ~(IXGBE_FCTRL_RPFCE | IXGBE_FCTRL_RFCE);
if (pfc_en)
reg |= IXGBE_FCTRL_RPFCE;
IXGBE_WRITE_REG(hw, IXGBE_FCTRL, reg);
/* Configure PFC Tx thresholds per TC */
for (i = 0; i < MAX_TRAFFIC_CLASS; i++) {
if (!(pfc_en & BIT(i))) {
IXGBE_WRITE_REG(hw, IXGBE_FCRTL(i), 0);
IXGBE_WRITE_REG(hw, IXGBE_FCRTH(i), 0);
continue;
}
fcrtl = (hw->fc.low_water[i] << 10) | IXGBE_FCRTL_XONE;
reg = (hw->fc.high_water[i] << 10) | IXGBE_FCRTH_FCEN;
IXGBE_WRITE_REG(hw, IXGBE_FCRTL(i), fcrtl);
IXGBE_WRITE_REG(hw, IXGBE_FCRTH(i), reg);
}
/* Configure pause time */
reg = hw->fc.pause_time * 0x00010001;
for (i = 0; i < (MAX_TRAFFIC_CLASS / 2); i++)
IXGBE_WRITE_REG(hw, IXGBE_FCTTV(i), reg);
/* Configure flow control refresh threshold value */
IXGBE_WRITE_REG(hw, IXGBE_FCRTV, hw->fc.pause_time / 2);
return 0;
}
/**
* ixgbe_dcb_config_tc_stats_82598 - Configure traffic class statistics
* @hw: pointer to hardware structure
*
* Configure queue statistics registers, all queues belonging to same traffic
* class uses a single set of queue statistics counters.
*/
static s32 ixgbe_dcb_config_tc_stats_82598(struct ixgbe_hw *hw)
{
u32 reg = 0;
u8 i = 0;
u8 j = 0;
/* Receive Queues stats setting - 8 queues per statistics reg */
for (i = 0, j = 0; i < 15 && j < 8; i = i + 2, j++) {
reg = IXGBE_READ_REG(hw, IXGBE_RQSMR(i));
reg |= ((0x1010101) * j);
IXGBE_WRITE_REG(hw, IXGBE_RQSMR(i), reg);
reg = IXGBE_READ_REG(hw, IXGBE_RQSMR(i + 1));
reg |= ((0x1010101) * j);
IXGBE_WRITE_REG(hw, IXGBE_RQSMR(i + 1), reg);
}
/* Transmit Queues stats setting - 4 queues per statistics reg */
for (i = 0; i < 8; i++) {
reg = IXGBE_READ_REG(hw, IXGBE_TQSMR(i));
reg |= ((0x1010101) * i);
IXGBE_WRITE_REG(hw, IXGBE_TQSMR(i), reg);
}
return 0;
}
/**
* ixgbe_dcb_hw_config_82598 - Config and enable DCB
* @hw: pointer to hardware structure
* @pfc_en: enabled pfc bitmask
* @refill: refill credits index by traffic class
* @max: max credits index by traffic class
* @bwg_id: bandwidth grouping indexed by traffic class
* @prio_type: priority type indexed by traffic class
*
* Configure dcb settings and enable dcb mode.
*/
s32 ixgbe_dcb_hw_config_82598(struct ixgbe_hw *hw, u8 pfc_en, u16 *refill,
u16 *max, u8 *bwg_id, u8 *prio_type)
{
ixgbe_dcb_config_rx_arbiter_82598(hw, refill, max, prio_type);
ixgbe_dcb_config_tx_desc_arbiter_82598(hw, refill, max,
bwg_id, prio_type);
ixgbe_dcb_config_tx_data_arbiter_82598(hw, refill, max,
bwg_id, prio_type);
ixgbe_dcb_config_pfc_82598(hw, pfc_en);
ixgbe_dcb_config_tc_stats_82598(hw);
return 0;
}
| HarveyHunt/linux | drivers/net/ethernet/intel/ixgbe/ixgbe_dcb_82598.c | C | gpl-2.0 | 8,776 |
! { dg-do compile }
! Test the fix for PR32157, in which overloading 'LEN', as
! in 'test' below would cause a compile error.
!
! Contributed by Michael Richmond <michael.a.richmond@nasa.gov>
!
subroutine len(c)
implicit none
character :: c
c = "X"
end subroutine len
subroutine test()
implicit none
character :: str
external len
call len(str)
if(str /= "X") STOP 1
end subroutine test
PROGRAM VAL
implicit none
external test
intrinsic len
call test()
if(len(" ") /= 1) STOP 2
END
| Gurgel100/gcc | gcc/testsuite/gfortran.dg/overload_2.f90 | FORTRAN | gpl-2.0 | 504 |
package autotest.afe;
import java.util.ArrayList;
import java.util.List;
public class CheckBoxPanel {
public static interface Display {
public ICheckBox generateCheckBox(int index);
}
private List<ICheckBox> checkBoxes = new ArrayList<ICheckBox>();
private Display display;
public void bindDisplay(Display display) {
this.display = display;
}
public ICheckBox generateCheckBox() {
return display.generateCheckBox(checkBoxes.size());
}
public void add(ICheckBox checkBox) {
checkBoxes.add(checkBox);
}
public List<ICheckBox> getChecked() {
List<ICheckBox> result = new ArrayList<ICheckBox>();
for(ICheckBox checkBox : checkBoxes) {
if (checkBox.getValue()) {
result.add(checkBox);
}
}
return result;
}
public void setEnabled(boolean enabled) {
for(ICheckBox thisBox : checkBoxes) {
thisBox.setEnabled(enabled);
}
}
public void reset() {
for (ICheckBox thisBox : checkBoxes) {
thisBox.setValue(false);
}
}
}
| spcui/autotest | frontend/client/src/autotest/afe/CheckBoxPanel.java | Java | gpl-2.0 | 1,139 |
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 2007 - 2008, Digium, Inc.
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
* \brief Asterisk datastore objects
*/
#ifndef _ASTERISK_DATASTORE_H
#define _ASTERISK_DATASTORE_H
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
#include "asterisk/linkedlists.h"
/*! \brief Structure for a data store type */
struct ast_datastore_info {
const char *type; /*!< Type of data store */
void *(*duplicate)(void *data); /*!< Duplicate item data (used for inheritance) */
void (*destroy)(void *data); /*!< Destroy function */
/*!
* \brief Fix up channel references
*
* \arg data The datastore data
* \arg old_chan The old channel owning the datastore
* \arg new_chan The new channel owning the datastore
*
* This is exactly like the fixup callback of the channel technology interface.
* It allows a datastore to fix any pointers it saved to the owning channel
* in case that the owning channel has changed. Generally, this would happen
* when the datastore is set to be inherited, and a masquerade occurs.
*
* \return nothing.
*/
void (*chan_fixup)(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan);
};
/*! \brief Structure for a data store object */
struct ast_datastore {
const char *uid; /*!< Unique data store identifier */
void *data; /*!< Contained data */
const struct ast_datastore_info *info; /*!< Data store type information */
unsigned int inheritance; /*!< Number of levels this item will continue to be inherited */
AST_LIST_ENTRY(ast_datastore) entry; /*!< Used for easy linking */
};
/*!
* \brief Create a data store object
* \param[in] info information describing the data store object
* \param[in] uid unique identifer
* \version 1.6.1 moved here and renamed from ast_channel_datastore_alloc
*/
struct ast_datastore * attribute_malloc __ast_datastore_alloc(const struct ast_datastore_info *info, const char *uid,
const char *file, int line, const char *function);
#define ast_datastore_alloc(info, uid) __ast_datastore_alloc(info, uid, __FILE__, __LINE__, __PRETTY_FUNCTION__)
/*!
* \brief Free a data store object
* \param[in] datastore datastore to free
* \version 1.6.1 moved here and renamed from ast_channel_datastore_free
*/
int ast_datastore_free(struct ast_datastore *datastore);
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
#endif /* _ASTERISK_DATASTORE_H */
| FireWRT/OpenWrt-Firefly-Libraries | staging_dir/target-mipsel_1004kc+dsp_uClibc-0.9.33.2/usr/include/asterisk-11/include/asterisk/datastore.h | C | gpl-2.0 | 2,873 |
package autotest.tko;
import autotest.common.Utils;
public abstract class LabelField extends ParameterizedField {
@Override
public String getSqlCondition(String value) {
String condition = " IS NOT NULL";
if (value.equals(Utils.JSON_NULL)) {
condition = " IS NULL";
}
return getFilteringName() + condition;
}
@Override
public String getFilteringName() {
return getQuotedSqlName() + ".id";
}
}
| nacc/autotest | frontend/client/src/autotest/tko/LabelField.java | Java | gpl-2.0 | 472 |
/* Basic C++ demangling support for GDB.
Copyright (C) 1991-2013 Free Software Foundation, Inc.
Written by Fred Fish at Cygnus Support.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* This file contains support code for C++ demangling that is common
to a styles of demangling, and GDB specific. */
#include "defs.h"
#include "command.h"
#include "gdbcmd.h"
#include "demangle.h"
#include "gdb-demangle.h"
#include "gdb_string.h"
/* Select the default C++ demangling style to use. The default is "auto",
which allows gdb to attempt to pick an appropriate demangling style for
the executable it has loaded. It can be set to a specific style ("gnu",
"lucid", "arm", "hp", etc.) in which case gdb will never attempt to do auto
selection of the style unless you do an explicit "set demangle auto".
To select one of these as the default, set DEFAULT_DEMANGLING_STYLE in
the appropriate target configuration file. */
#ifndef DEFAULT_DEMANGLING_STYLE
#define DEFAULT_DEMANGLING_STYLE AUTO_DEMANGLING_STYLE_STRING
#endif
/* See documentation in gdb-demangle.h. */
int demangle = 1;
static void
show_demangle (struct ui_file *file, int from_tty,
struct cmd_list_element *c, const char *value)
{
fprintf_filtered (file,
_("Demangling of encoded C++/ObjC names "
"when displaying symbols is %s.\n"),
value);
}
/* See documentation in gdb-demangle.h. */
int asm_demangle = 0;
static void
show_asm_demangle (struct ui_file *file, int from_tty,
struct cmd_list_element *c, const char *value)
{
fprintf_filtered (file,
_("Demangling of C++/ObjC names in "
"disassembly listings is %s.\n"),
value);
}
/* String name for the current demangling style. Set by the
"set demangle-style" command, printed as part of the output by the
"show demangle-style" command. */
static const char *current_demangling_style_string;
/* The array of names of the known demanglyng styles. Generated by
_initialize_demangler from libiberty_demanglers[] array. */
static const char **demangling_style_names;
static void
show_demangling_style_names(struct ui_file *file, int from_tty,
struct cmd_list_element *c, const char *value)
{
fprintf_filtered (file, _("The current C++ demangling style is \"%s\".\n"),
value);
}
/* Set current demangling style. Called by the "set demangle-style"
command after it has updated the current_demangling_style_string to
match what the user has entered.
If the user has entered a string that matches a known demangling style
name in the demanglers[] array then just leave the string alone and update
the current_demangling_style enum value to match.
If the user has entered a string that doesn't match, including an empty
string, then print a list of the currently known styles and restore
the current_demangling_style_string to match the current_demangling_style
enum value.
Note: Assumes that current_demangling_style_string always points to
a malloc'd string, even if it is a null-string. */
static void
set_demangling_command (char *ignore, int from_tty, struct cmd_list_element *c)
{
const struct demangler_engine *dem;
int i;
/* First just try to match whatever style name the user supplied with
one of the known ones. Don't bother special casing for an empty
name, we just treat it as any other style name that doesn't match.
If we match, update the current demangling style enum. */
for (dem = libiberty_demanglers, i = 0;
dem->demangling_style != unknown_demangling;
dem++)
{
if (strcmp (current_demangling_style_string,
dem->demangling_style_name) == 0)
{
current_demangling_style = dem->demangling_style;
current_demangling_style_string = demangling_style_names[i];
break;
}
i++;
}
/* We should have found a match, given we only add known styles to
the enumeration list. */
gdb_assert (dem->demangling_style != unknown_demangling);
}
/* G++ uses a special character to indicate certain internal names. Which
character it is depends on the platform:
- Usually '$' on systems where the assembler will accept that
- Usually '.' otherwise (this includes most sysv4-like systems and most
ELF targets)
- Occasionally '_' if neither of the above is usable
We check '$' first because it is the safest, and '.' often has another
meaning. We don't currently try to handle '_' because the precise forms
of the names are different on those targets. */
static char cplus_markers[] = {'$', '.', '\0'};
/* See documentation in gdb-demangle.h. */
int
is_cplus_marker (int c)
{
return c && strchr (cplus_markers, c) != NULL;
}
extern initialize_file_ftype _initialize_demangler; /* -Wmissing-prototypes */
void
_initialize_demangler (void)
{
int i, ndems;
/* Fill the demangling_style_names[] array, and set the default
demangling style chosen at compilation time. */
for (ndems = 0;
libiberty_demanglers[ndems].demangling_style != unknown_demangling;
ndems++)
;
demangling_style_names = xcalloc (ndems + 1, sizeof (char *));
for (i = 0;
libiberty_demanglers[i].demangling_style != unknown_demangling;
i++)
{
demangling_style_names[i]
= xstrdup (libiberty_demanglers[i].demangling_style_name);
if (current_demangling_style_string == NULL
&& strcmp (DEFAULT_DEMANGLING_STYLE, demangling_style_names[i]) == 0)
current_demangling_style_string = demangling_style_names[i];
}
add_setshow_boolean_cmd ("demangle", class_support, &demangle, _("\
Set demangling of encoded C++/ObjC names when displaying symbols."), _("\
Show demangling of encoded C++/ObjC names when displaying symbols."), NULL,
NULL,
show_demangle,
&setprintlist, &showprintlist);
add_setshow_boolean_cmd ("asm-demangle", class_support, &asm_demangle, _("\
Set demangling of C++/ObjC names in disassembly listings."), _("\
Show demangling of C++/ObjC names in disassembly listings."), NULL,
NULL,
show_asm_demangle,
&setprintlist, &showprintlist);
add_setshow_enum_cmd ("demangle-style", class_support,
demangling_style_names,
¤t_demangling_style_string, _("\
Set the current C++ demangling style."), _("\
Show the current C++ demangling style."), _("\
Use `set demangle-style' without arguments for a list of demangling styles."),
set_demangling_command,
show_demangling_style_names,
&setlist, &showlist);
}
| dje42/gdb | gdb/demangle.c | C | gpl-2.0 | 7,136 |
DELETE FROM scripted_areatrigger WHERE entry=1966;
INSERT INTO scripted_areatrigger VALUES (1966,'at_murkdeep');
| mangosArchives/serverOneRel18 | src/scripts/sql/updates/0.6/r2541_mangos.sql | SQL | gpl-2.0 | 113 |
tinymce.PluginManager.add("insertdatetime", function (e) {
function t(t, n) {
function i(e, t) {
if (e = "" + e, e.length < t)for (var n = 0; n < t - e.length; n++)e = "0" + e;
return e
}
return n = n || new Date, t = t.replace("%D", "%m/%d/%Y"), t = t.replace("%r", "%I:%M:%S %p"), t = t.replace("%Y", "" + n.getFullYear()), t = t.replace("%y", "" + n.getYear()), t = t.replace("%m", i(n.getMonth() + 1, 2)), t = t.replace("%d", i(n.getDate(), 2)), t = t.replace("%H", "" + i(n.getHours(), 2)), t = t.replace("%M", "" + i(n.getMinutes(), 2)), t = t.replace("%S", "" + i(n.getSeconds(), 2)), t = t.replace("%I", "" + ((n.getHours() + 11) % 12 + 1)), t = t.replace("%p", "" + (n.getHours() < 12 ? "AM" : "PM")), t = t.replace("%B", "" + e.translate(s[n.getMonth()])), t = t.replace("%b", "" + e.translate(o[n.getMonth()])), t = t.replace("%A", "" + e.translate(r[n.getDay()])), t = t.replace("%a", "" + e.translate(a[n.getDay()])), t = t.replace("%%", "%")
}
function n(n) {
var i = t(n);
if (e.settings.insertdatetime_element) {
var a;
a = /%[HMSIp]/.test(n) ? t("%Y-%m-%dT%H:%M") : t("%Y-%m-%d"), i = '<time datetime="' + a + '">' + i + "</time>";
var r = e.dom.getParent(e.selection.getStart(), "time");
if (r)return e.dom.setOuterHTML(r, i), void 0
}
e.insertContent(i)
}
var i, a = "Sun Mon Tue Wed Thu Fri Sat Sun".split(" "), r = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" "), o = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "), s = "January February March April May June July August September October November December".split(" "), l = [];
e.addCommand("mceInsertDate", function () {
n(e.getParam("insertdatetime_dateformat", e.translate("%Y-%m-%d")))
}), e.addCommand("mceInsertTime", function () {
n(e.getParam("insertdatetime_timeformat", e.translate("%H:%M:%S")))
}), e.addButton("inserttime", {
type: "splitbutton", title: "Insert time", onclick: function () {
n(i || "%H:%M:%S")
}, menu: l
}), tinymce.each(e.settings.insertdatetime_formats || ["%H:%M:%S", "%Y-%m-%d", "%I:%M:%S %p", "%D"], function (e) {
l.push({
text: t(e), onclick: function () {
i = e, n(e)
}
})
}), e.addMenuItem("insertdatetime", {icon: "date", text: "Insert date/time", menu: l, context: "insert"})
}); | DaveB95/CS3012Website | vendors/tinymce/plugins/insertdatetime/plugin.min.js | JavaScript | gpl-2.0 | 2,505 |
/* bnx2x_cmn.h: Broadcom Everest network driver.
*
* Copyright (c) 2007-2013 Broadcom Corporation
*
* 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.
*
* Maintained by: Eilon Greenstein <eilong@broadcom.com>
* Written by: Eliezer Tamir
* Based on code from Michael Chan's bnx2 driver
* UDP CSUM errata workaround by Arik Gendelman
* Slowpath and fastpath rework by Vladislav Zolotarov
* Statistics and Link management by Yitchak Gertner
*
*/
#ifndef BNX2X_CMN_H
#define BNX2X_CMN_H
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include "bnx2x.h"
#include "bnx2x_sriov.h"
/* This is used as a replacement for an MCP if it's not present */
extern int load_count[2][3]; /* per-path: 0-common, 1-port0, 2-port1 */
extern int num_queues;
extern int int_mode;
/************************ Macros ********************************/
#define BNX2X_PCI_FREE(x, y, size) \
do { \
if (x) { \
dma_free_coherent(&bp->pdev->dev, size, (void *)x, y); \
x = NULL; \
y = 0; \
} \
} while (0)
#define BNX2X_FREE(x) \
do { \
if (x) { \
kfree((void *)x); \
x = NULL; \
} \
} while (0)
#define BNX2X_PCI_ALLOC(x, y, size) \
do { \
x = dma_alloc_coherent(&bp->pdev->dev, size, y, \
GFP_KERNEL | __GFP_ZERO); \
if (x == NULL) \
goto alloc_mem_err; \
DP(NETIF_MSG_HW, "BNX2X_PCI_ALLOC: Physical %Lx Virtual %p\n", \
(unsigned long long)(*y), x); \
} while (0)
#define BNX2X_PCI_FALLOC(x, y, size) \
do { \
x = dma_alloc_coherent(&bp->pdev->dev, size, y, GFP_KERNEL); \
if (x == NULL) \
goto alloc_mem_err; \
memset((void *)x, 0xFFFFFFFF, size); \
DP(NETIF_MSG_HW, "BNX2X_PCI_FALLOC: Physical %Lx Virtual %p\n",\
(unsigned long long)(*y), x); \
} while (0)
#define BNX2X_ALLOC(x, size) \
do { \
x = kzalloc(size, GFP_KERNEL); \
if (x == NULL) \
goto alloc_mem_err; \
} while (0)
/*********************** Interfaces ****************************
* Functions that need to be implemented by each driver version
*/
/* Init */
/**
* bnx2x_send_unload_req - request unload mode from the MCP.
*
* @bp: driver handle
* @unload_mode: requested function's unload mode
*
* Return unload mode returned by the MCP: COMMON, PORT or FUNC.
*/
u32 bnx2x_send_unload_req(struct bnx2x *bp, int unload_mode);
/**
* bnx2x_send_unload_done - send UNLOAD_DONE command to the MCP.
*
* @bp: driver handle
* @keep_link: true iff link should be kept up
*/
void bnx2x_send_unload_done(struct bnx2x *bp, bool keep_link);
/**
* bnx2x_config_rss_pf - configure RSS parameters in a PF.
*
* @bp: driver handle
* @rss_obj: RSS object to use
* @ind_table: indirection table to configure
* @config_hash: re-configure RSS hash keys configuration
*/
int bnx2x_config_rss_pf(struct bnx2x *bp, struct bnx2x_rss_config_obj *rss_obj,
bool config_hash);
/**
* bnx2x__init_func_obj - init function object
*
* @bp: driver handle
*
* Initializes the Function Object with the appropriate
* parameters which include a function slow path driver
* interface.
*/
void bnx2x__init_func_obj(struct bnx2x *bp);
/**
* bnx2x_setup_queue - setup eth queue.
*
* @bp: driver handle
* @fp: pointer to the fastpath structure
* @leading: boolean
*
*/
int bnx2x_setup_queue(struct bnx2x *bp, struct bnx2x_fastpath *fp,
bool leading);
/**
* bnx2x_setup_leading - bring up a leading eth queue.
*
* @bp: driver handle
*/
int bnx2x_setup_leading(struct bnx2x *bp);
/**
* bnx2x_fw_command - send the MCP a request
*
* @bp: driver handle
* @command: request
* @param: request's parameter
*
* block until there is a reply
*/
u32 bnx2x_fw_command(struct bnx2x *bp, u32 command, u32 param);
/**
* bnx2x_initial_phy_init - initialize link parameters structure variables.
*
* @bp: driver handle
* @load_mode: current mode
*/
int bnx2x_initial_phy_init(struct bnx2x *bp, int load_mode);
/**
* bnx2x_link_set - configure hw according to link parameters structure.
*
* @bp: driver handle
*/
void bnx2x_link_set(struct bnx2x *bp);
/**
* bnx2x_force_link_reset - Forces link reset, and put the PHY
* in reset as well.
*
* @bp: driver handle
*/
void bnx2x_force_link_reset(struct bnx2x *bp);
/**
* bnx2x_link_test - query link status.
*
* @bp: driver handle
* @is_serdes: bool
*
* Returns 0 if link is UP.
*/
u8 bnx2x_link_test(struct bnx2x *bp, u8 is_serdes);
/**
* bnx2x_drv_pulse - write driver pulse to shmem
*
* @bp: driver handle
*
* writes the value in bp->fw_drv_pulse_wr_seq to drv_pulse mbox
* in the shmem.
*/
void bnx2x_drv_pulse(struct bnx2x *bp);
/**
* bnx2x_igu_ack_sb - update IGU with current SB value
*
* @bp: driver handle
* @igu_sb_id: SB id
* @segment: SB segment
* @index: SB index
* @op: SB operation
* @update: is HW update required
*/
void bnx2x_igu_ack_sb(struct bnx2x *bp, u8 igu_sb_id, u8 segment,
u16 index, u8 op, u8 update);
/* Disable transactions from chip to host */
void bnx2x_pf_disable(struct bnx2x *bp);
int bnx2x_pretend_func(struct bnx2x *bp, u16 pretend_func_val);
/**
* bnx2x__link_status_update - handles link status change.
*
* @bp: driver handle
*/
void bnx2x__link_status_update(struct bnx2x *bp);
/**
* bnx2x_link_report - report link status to upper layer.
*
* @bp: driver handle
*/
void bnx2x_link_report(struct bnx2x *bp);
/* None-atomic version of bnx2x_link_report() */
void __bnx2x_link_report(struct bnx2x *bp);
/**
* bnx2x_get_mf_speed - calculate MF speed.
*
* @bp: driver handle
*
* Takes into account current linespeed and MF configuration.
*/
u16 bnx2x_get_mf_speed(struct bnx2x *bp);
/**
* bnx2x_msix_sp_int - MSI-X slowpath interrupt handler
*
* @irq: irq number
* @dev_instance: private instance
*/
irqreturn_t bnx2x_msix_sp_int(int irq, void *dev_instance);
/**
* bnx2x_interrupt - non MSI-X interrupt handler
*
* @irq: irq number
* @dev_instance: private instance
*/
irqreturn_t bnx2x_interrupt(int irq, void *dev_instance);
/**
* bnx2x_cnic_notify - send command to cnic driver
*
* @bp: driver handle
* @cmd: command
*/
int bnx2x_cnic_notify(struct bnx2x *bp, int cmd);
/**
* bnx2x_setup_cnic_irq_info - provides cnic with IRQ information
*
* @bp: driver handle
*/
void bnx2x_setup_cnic_irq_info(struct bnx2x *bp);
/**
* bnx2x_setup_cnic_info - provides cnic with updated info
*
* @bp: driver handle
*/
void bnx2x_setup_cnic_info(struct bnx2x *bp);
/**
* bnx2x_int_enable - enable HW interrupts.
*
* @bp: driver handle
*/
void bnx2x_int_enable(struct bnx2x *bp);
/**
* bnx2x_int_disable_sync - disable interrupts.
*
* @bp: driver handle
* @disable_hw: true, disable HW interrupts.
*
* This function ensures that there are no
* ISRs or SP DPCs (sp_task) are running after it returns.
*/
void bnx2x_int_disable_sync(struct bnx2x *bp, int disable_hw);
/**
* bnx2x_nic_init_cnic - init driver internals for cnic.
*
* @bp: driver handle
* @load_code: COMMON, PORT or FUNCTION
*
* Initializes:
* - rings
* - status blocks
* - etc.
*/
void bnx2x_nic_init_cnic(struct bnx2x *bp);
/**
* bnx2x_preirq_nic_init - init driver internals.
*
* @bp: driver handle
*
* Initializes:
* - fastpath object
* - fastpath rings
* etc.
*/
void bnx2x_pre_irq_nic_init(struct bnx2x *bp);
/**
* bnx2x_postirq_nic_init - init driver internals.
*
* @bp: driver handle
* @load_code: COMMON, PORT or FUNCTION
*
* Initializes:
* - status blocks
* - slowpath rings
* - etc.
*/
void bnx2x_post_irq_nic_init(struct bnx2x *bp, u32 load_code);
/**
* bnx2x_alloc_mem_cnic - allocate driver's memory for cnic.
*
* @bp: driver handle
*/
int bnx2x_alloc_mem_cnic(struct bnx2x *bp);
/**
* bnx2x_alloc_mem - allocate driver's memory.
*
* @bp: driver handle
*/
int bnx2x_alloc_mem(struct bnx2x *bp);
/**
* bnx2x_free_mem_cnic - release driver's memory for cnic.
*
* @bp: driver handle
*/
void bnx2x_free_mem_cnic(struct bnx2x *bp);
/**
* bnx2x_free_mem - release driver's memory.
*
* @bp: driver handle
*/
void bnx2x_free_mem(struct bnx2x *bp);
/**
* bnx2x_set_num_queues - set number of queues according to mode.
*
* @bp: driver handle
*/
void bnx2x_set_num_queues(struct bnx2x *bp);
/**
* bnx2x_chip_cleanup - cleanup chip internals.
*
* @bp: driver handle
* @unload_mode: COMMON, PORT, FUNCTION
* @keep_link: true iff link should be kept up.
*
* - Cleanup MAC configuration.
* - Closes clients.
* - etc.
*/
void bnx2x_chip_cleanup(struct bnx2x *bp, int unload_mode, bool keep_link);
/**
* bnx2x_acquire_hw_lock - acquire HW lock.
*
* @bp: driver handle
* @resource: resource bit which was locked
*/
int bnx2x_acquire_hw_lock(struct bnx2x *bp, u32 resource);
/**
* bnx2x_release_hw_lock - release HW lock.
*
* @bp: driver handle
* @resource: resource bit which was locked
*/
int bnx2x_release_hw_lock(struct bnx2x *bp, u32 resource);
/**
* bnx2x_release_leader_lock - release recovery leader lock
*
* @bp: driver handle
*/
int bnx2x_release_leader_lock(struct bnx2x *bp);
/**
* bnx2x_set_eth_mac - configure eth MAC address in the HW
*
* @bp: driver handle
* @set: set or clear
*
* Configures according to the value in netdev->dev_addr.
*/
int bnx2x_set_eth_mac(struct bnx2x *bp, bool set);
/**
* bnx2x_set_rx_mode - set MAC filtering configurations.
*
* @dev: netdevice
*
* called with netif_tx_lock from dev_mcast.c
* If bp->state is OPEN, should be called with
* netif_addr_lock_bh()
*/
void bnx2x_set_rx_mode(struct net_device *dev);
/**
* bnx2x_set_storm_rx_mode - configure MAC filtering rules in a FW.
*
* @bp: driver handle
*
* If bp->state is OPEN, should be called with
* netif_addr_lock_bh().
*/
int bnx2x_set_storm_rx_mode(struct bnx2x *bp);
/**
* bnx2x_set_q_rx_mode - configures rx_mode for a single queue.
*
* @bp: driver handle
* @cl_id: client id
* @rx_mode_flags: rx mode configuration
* @rx_accept_flags: rx accept configuration
* @tx_accept_flags: tx accept configuration (tx switch)
* @ramrod_flags: ramrod configuration
*/
int bnx2x_set_q_rx_mode(struct bnx2x *bp, u8 cl_id,
unsigned long rx_mode_flags,
unsigned long rx_accept_flags,
unsigned long tx_accept_flags,
unsigned long ramrod_flags);
/* Parity errors related */
void bnx2x_set_pf_load(struct bnx2x *bp);
bool bnx2x_clear_pf_load(struct bnx2x *bp);
bool bnx2x_chk_parity_attn(struct bnx2x *bp, bool *global, bool print);
bool bnx2x_reset_is_done(struct bnx2x *bp, int engine);
void bnx2x_set_reset_in_progress(struct bnx2x *bp);
void bnx2x_set_reset_global(struct bnx2x *bp);
void bnx2x_disable_close_the_gate(struct bnx2x *bp);
int bnx2x_init_hw_func_cnic(struct bnx2x *bp);
/**
* bnx2x_sp_event - handle ramrods completion.
*
* @fp: fastpath handle for the event
* @rr_cqe: eth_rx_cqe
*/
void bnx2x_sp_event(struct bnx2x_fastpath *fp, union eth_rx_cqe *rr_cqe);
/**
* bnx2x_ilt_set_info - prepare ILT configurations.
*
* @bp: driver handle
*/
void bnx2x_ilt_set_info(struct bnx2x *bp);
/**
* bnx2x_ilt_set_cnic_info - prepare ILT configurations for SRC
* and TM.
*
* @bp: driver handle
*/
void bnx2x_ilt_set_info_cnic(struct bnx2x *bp);
/**
* bnx2x_dcbx_init - initialize dcbx protocol.
*
* @bp: driver handle
*/
void bnx2x_dcbx_init(struct bnx2x *bp, bool update_shmem);
/**
* bnx2x_set_power_state - set power state to the requested value.
*
* @bp: driver handle
* @state: required state D0 or D3hot
*
* Currently only D0 and D3hot are supported.
*/
int bnx2x_set_power_state(struct bnx2x *bp, pci_power_t state);
/**
* bnx2x_update_max_mf_config - update MAX part of MF configuration in HW.
*
* @bp: driver handle
* @value: new value
*/
void bnx2x_update_max_mf_config(struct bnx2x *bp, u32 value);
/* Error handling */
void bnx2x_fw_dump_lvl(struct bnx2x *bp, const char *lvl);
/* dev_close main block */
int bnx2x_nic_unload(struct bnx2x *bp, int unload_mode, bool keep_link);
/* dev_open main block */
int bnx2x_nic_load(struct bnx2x *bp, int load_mode);
/* hard_xmit callback */
netdev_tx_t bnx2x_start_xmit(struct sk_buff *skb, struct net_device *dev);
int bnx2x_get_vf_config(struct net_device *dev, int vf,
struct ifla_vf_info *ivi);
int bnx2x_set_vf_mac(struct net_device *dev, int queue, u8 *mac);
int bnx2x_set_vf_vlan(struct net_device *netdev, int vf, u16 vlan, u8 qos);
/* select_queue callback */
u16 bnx2x_select_queue(struct net_device *dev, struct sk_buff *skb);
static inline void bnx2x_update_rx_prod(struct bnx2x *bp,
struct bnx2x_fastpath *fp,
u16 bd_prod, u16 rx_comp_prod,
u16 rx_sge_prod)
{
struct ustorm_eth_rx_producers rx_prods = {0};
u32 i;
/* Update producers */
rx_prods.bd_prod = bd_prod;
rx_prods.cqe_prod = rx_comp_prod;
rx_prods.sge_prod = rx_sge_prod;
/* Make sure that the BD and SGE data is updated before updating the
* producers since FW might read the BD/SGE right after the producer
* is updated.
* This is only applicable for weak-ordered memory model archs such
* as IA-64. The following barrier is also mandatory since FW will
* assumes BDs must have buffers.
*/
wmb();
for (i = 0; i < sizeof(rx_prods)/4; i++)
REG_WR(bp, fp->ustorm_rx_prods_offset + i*4,
((u32 *)&rx_prods)[i]);
mmiowb(); /* keep prod updates ordered */
DP(NETIF_MSG_RX_STATUS,
"queue[%d]: wrote bd_prod %u cqe_prod %u sge_prod %u\n",
fp->index, bd_prod, rx_comp_prod, rx_sge_prod);
}
/* reload helper */
int bnx2x_reload_if_running(struct net_device *dev);
int bnx2x_change_mac_addr(struct net_device *dev, void *p);
/* NAPI poll Rx part */
int bnx2x_rx_int(struct bnx2x_fastpath *fp, int budget);
/* NAPI poll Tx part */
int bnx2x_tx_int(struct bnx2x *bp, struct bnx2x_fp_txdata *txdata);
/* suspend/resume callbacks */
int bnx2x_suspend(struct pci_dev *pdev, pm_message_t state);
int bnx2x_resume(struct pci_dev *pdev);
/* Release IRQ vectors */
void bnx2x_free_irq(struct bnx2x *bp);
void bnx2x_free_fp_mem_cnic(struct bnx2x *bp);
void bnx2x_free_fp_mem(struct bnx2x *bp);
int bnx2x_alloc_fp_mem_cnic(struct bnx2x *bp);
int bnx2x_alloc_fp_mem(struct bnx2x *bp);
void bnx2x_init_rx_rings(struct bnx2x *bp);
void bnx2x_init_rx_rings_cnic(struct bnx2x *bp);
void bnx2x_free_skbs_cnic(struct bnx2x *bp);
void bnx2x_free_skbs(struct bnx2x *bp);
void bnx2x_netif_stop(struct bnx2x *bp, int disable_hw);
void bnx2x_netif_start(struct bnx2x *bp);
int bnx2x_load_cnic(struct bnx2x *bp);
/**
* bnx2x_enable_msix - set msix configuration.
*
* @bp: driver handle
*
* fills msix_table, requests vectors, updates num_queues
* according to number of available vectors.
*/
int bnx2x_enable_msix(struct bnx2x *bp);
/**
* bnx2x_enable_msi - request msi mode from OS, updated internals accordingly
*
* @bp: driver handle
*/
int bnx2x_enable_msi(struct bnx2x *bp);
/**
* bnx2x_poll - NAPI callback
*
* @napi: napi structure
* @budget:
*
*/
int bnx2x_poll(struct napi_struct *napi, int budget);
/**
* bnx2x_alloc_mem_bp - allocate memories outsize main driver structure
*
* @bp: driver handle
*/
int bnx2x_alloc_mem_bp(struct bnx2x *bp);
/**
* bnx2x_free_mem_bp - release memories outsize main driver structure
*
* @bp: driver handle
*/
void bnx2x_free_mem_bp(struct bnx2x *bp);
/**
* bnx2x_change_mtu - change mtu netdev callback
*
* @dev: net device
* @new_mtu: requested mtu
*
*/
int bnx2x_change_mtu(struct net_device *dev, int new_mtu);
#ifdef NETDEV_FCOE_WWNN
/**
* bnx2x_fcoe_get_wwn - return the requested WWN value for this port
*
* @dev: net_device
* @wwn: output buffer
* @type: WWN type: NETDEV_FCOE_WWNN (node) or NETDEV_FCOE_WWPN (port)
*
*/
int bnx2x_fcoe_get_wwn(struct net_device *dev, u64 *wwn, int type);
#endif
/**
* bnx2x_tx_timeout - tx timeout netdev callback
*
* @dev: net device
*/
void bnx2x_tx_timeout(struct net_device *dev);
/**
* vlan rx register netdev callback
*
* @dev: net device
* @vlgrp: VLAN group
*/
void bnx2x_vlan_rx_register(struct net_device *dev,
struct vlan_group *vlgrp);
/*********************** Inlines **********************************/
/*********************** Fast path ********************************/
static inline void bnx2x_update_fpsb_idx(struct bnx2x_fastpath *fp)
{
barrier(); /* status block is written to by the chip */
fp->fp_hc_idx = fp->sb_running_index[SM_RX_ID];
}
static inline void bnx2x_igu_ack_sb_gen(struct bnx2x *bp, u8 igu_sb_id,
u8 segment, u16 index, u8 op,
u8 update, u32 igu_addr)
{
struct igu_regular cmd_data = {0};
cmd_data.sb_id_and_flags =
((index << IGU_REGULAR_SB_INDEX_SHIFT) |
(segment << IGU_REGULAR_SEGMENT_ACCESS_SHIFT) |
(update << IGU_REGULAR_BUPDATE_SHIFT) |
(op << IGU_REGULAR_ENABLE_INT_SHIFT));
DP(NETIF_MSG_INTR, "write 0x%08x to IGU addr 0x%x\n",
cmd_data.sb_id_and_flags, igu_addr);
REG_WR(bp, igu_addr, cmd_data.sb_id_and_flags);
/* Make sure that ACK is written */
mmiowb();
barrier();
}
static inline void bnx2x_hc_ack_sb(struct bnx2x *bp, u8 sb_id,
u8 storm, u16 index, u8 op, u8 update)
{
u32 hc_addr = (HC_REG_COMMAND_REG + BP_PORT(bp)*32 +
COMMAND_REG_INT_ACK);
struct igu_ack_register igu_ack;
igu_ack.status_block_index = index;
igu_ack.sb_id_and_flags =
((sb_id << IGU_ACK_REGISTER_STATUS_BLOCK_ID_SHIFT) |
(storm << IGU_ACK_REGISTER_STORM_ID_SHIFT) |
(update << IGU_ACK_REGISTER_UPDATE_INDEX_SHIFT) |
(op << IGU_ACK_REGISTER_INTERRUPT_MODE_SHIFT));
REG_WR(bp, hc_addr, (*(u32 *)&igu_ack));
/* Make sure that ACK is written */
mmiowb();
barrier();
}
static inline void bnx2x_ack_sb(struct bnx2x *bp, u8 igu_sb_id, u8 storm,
u16 index, u8 op, u8 update)
{
if (bp->common.int_block == INT_BLOCK_HC)
bnx2x_hc_ack_sb(bp, igu_sb_id, storm, index, op, update);
else {
u8 segment;
if (CHIP_INT_MODE_IS_BC(bp))
segment = storm;
else if (igu_sb_id != bp->igu_dsb_id)
segment = IGU_SEG_ACCESS_DEF;
else if (storm == ATTENTION_ID)
segment = IGU_SEG_ACCESS_ATTN;
else
segment = IGU_SEG_ACCESS_DEF;
bnx2x_igu_ack_sb(bp, igu_sb_id, segment, index, op, update);
}
}
static inline u16 bnx2x_hc_ack_int(struct bnx2x *bp)
{
u32 hc_addr = (HC_REG_COMMAND_REG + BP_PORT(bp)*32 +
COMMAND_REG_SIMD_MASK);
u32 result = REG_RD(bp, hc_addr);
barrier();
return result;
}
static inline u16 bnx2x_igu_ack_int(struct bnx2x *bp)
{
u32 igu_addr = (BAR_IGU_INTMEM + IGU_REG_SISR_MDPC_WMASK_LSB_UPPER*8);
u32 result = REG_RD(bp, igu_addr);
DP(NETIF_MSG_INTR, "read 0x%08x from IGU addr 0x%x\n",
result, igu_addr);
barrier();
return result;
}
static inline u16 bnx2x_ack_int(struct bnx2x *bp)
{
barrier();
if (bp->common.int_block == INT_BLOCK_HC)
return bnx2x_hc_ack_int(bp);
else
return bnx2x_igu_ack_int(bp);
}
static inline int bnx2x_has_tx_work_unload(struct bnx2x_fp_txdata *txdata)
{
/* Tell compiler that consumer and producer can change */
barrier();
return txdata->tx_pkt_prod != txdata->tx_pkt_cons;
}
static inline u16 bnx2x_tx_avail(struct bnx2x *bp,
struct bnx2x_fp_txdata *txdata)
{
s16 used;
u16 prod;
u16 cons;
prod = txdata->tx_bd_prod;
cons = txdata->tx_bd_cons;
used = SUB_S16(prod, cons);
#ifdef BNX2X_STOP_ON_ERROR
WARN_ON(used < 0);
WARN_ON(used > txdata->tx_ring_size);
WARN_ON((txdata->tx_ring_size - used) > MAX_TX_AVAIL);
#endif
return (s16)(txdata->tx_ring_size) - used;
}
static inline int bnx2x_tx_queue_has_work(struct bnx2x_fp_txdata *txdata)
{
u16 hw_cons;
/* Tell compiler that status block fields can change */
barrier();
hw_cons = le16_to_cpu(*txdata->tx_cons_sb);
return hw_cons != txdata->tx_pkt_cons;
}
static inline bool bnx2x_has_tx_work(struct bnx2x_fastpath *fp)
{
u8 cos;
for_each_cos_in_tx_queue(fp, cos)
if (bnx2x_tx_queue_has_work(fp->txdata_ptr[cos]))
return true;
return false;
}
#define BNX2X_IS_CQE_COMPLETED(cqe_fp) (cqe_fp->marker == 0x0)
#define BNX2X_SEED_CQE(cqe_fp) (cqe_fp->marker = 0xFFFFFFFF)
static inline int bnx2x_has_rx_work(struct bnx2x_fastpath *fp)
{
u16 cons;
union eth_rx_cqe *cqe;
struct eth_fast_path_rx_cqe *cqe_fp;
cons = RCQ_BD(fp->rx_comp_cons);
cqe = &fp->rx_comp_ring[cons];
cqe_fp = &cqe->fast_path_cqe;
return BNX2X_IS_CQE_COMPLETED(cqe_fp);
}
/**
* bnx2x_tx_disable - disables tx from stack point of view
*
* @bp: driver handle
*/
static inline void bnx2x_tx_disable(struct bnx2x *bp)
{
netif_tx_disable(bp->dev);
netif_carrier_off(bp->dev);
}
static inline void bnx2x_free_rx_sge(struct bnx2x *bp,
struct bnx2x_fastpath *fp, u16 index)
{
struct sw_rx_page *sw_buf = &fp->rx_page_ring[index];
struct page *page = sw_buf->page;
struct eth_rx_sge *sge = &fp->rx_sge_ring[index];
/* Skip "next page" elements */
if (!page)
return;
dma_unmap_page(&bp->pdev->dev, dma_unmap_addr(sw_buf, mapping),
SGE_PAGES, DMA_FROM_DEVICE);
__free_pages(page, PAGES_PER_SGE_SHIFT);
sw_buf->page = NULL;
sge->addr_hi = 0;
sge->addr_lo = 0;
}
static inline void bnx2x_add_all_napi_cnic(struct bnx2x *bp)
{
int i;
/* Add NAPI objects */
for_each_rx_queue_cnic(bp, i)
netif_napi_add(bp->dev, &bnx2x_fp(bp, i, napi),
bnx2x_poll, NAPI_POLL_WEIGHT);
}
static inline void bnx2x_add_all_napi(struct bnx2x *bp)
{
int i;
/* Add NAPI objects */
for_each_eth_queue(bp, i)
netif_napi_add(bp->dev, &bnx2x_fp(bp, i, napi),
bnx2x_poll, NAPI_POLL_WEIGHT);
}
static inline void bnx2x_del_all_napi_cnic(struct bnx2x *bp)
{
int i;
for_each_rx_queue_cnic(bp, i)
netif_napi_del(&bnx2x_fp(bp, i, napi));
}
static inline void bnx2x_del_all_napi(struct bnx2x *bp)
{
int i;
for_each_eth_queue(bp, i)
netif_napi_del(&bnx2x_fp(bp, i, napi));
}
int bnx2x_set_int_mode(struct bnx2x *bp);
static inline void bnx2x_disable_msi(struct bnx2x *bp)
{
if (bp->flags & USING_MSIX_FLAG) {
pci_disable_msix(bp->pdev);
bp->flags &= ~(USING_MSIX_FLAG | USING_SINGLE_MSIX_FLAG);
} else if (bp->flags & USING_MSI_FLAG) {
pci_disable_msi(bp->pdev);
bp->flags &= ~USING_MSI_FLAG;
}
}
static inline int bnx2x_calc_num_queues(struct bnx2x *bp)
{
return num_queues ?
min_t(int, num_queues, BNX2X_MAX_QUEUES(bp)) :
min_t(int, netif_get_num_default_rss_queues(),
BNX2X_MAX_QUEUES(bp));
}
static inline void bnx2x_clear_sge_mask_next_elems(struct bnx2x_fastpath *fp)
{
int i, j;
for (i = 1; i <= NUM_RX_SGE_PAGES; i++) {
int idx = RX_SGE_CNT * i - 1;
for (j = 0; j < 2; j++) {
BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
idx--;
}
}
}
static inline void bnx2x_init_sge_ring_bit_mask(struct bnx2x_fastpath *fp)
{
/* Set the mask to all 1-s: it's faster to compare to 0 than to 0xf-s */
memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
/* Clear the two last indices in the page to 1:
these are the indices that correspond to the "next" element,
hence will never be indicated and should be removed from
the calculations. */
bnx2x_clear_sge_mask_next_elems(fp);
}
/* note that we are not allocating a new buffer,
* we are just moving one from cons to prod
* we are not creating a new mapping,
* so there is no need to check for dma_mapping_error().
*/
static inline void bnx2x_reuse_rx_data(struct bnx2x_fastpath *fp,
u16 cons, u16 prod)
{
struct sw_rx_bd *cons_rx_buf = &fp->rx_buf_ring[cons];
struct sw_rx_bd *prod_rx_buf = &fp->rx_buf_ring[prod];
struct eth_rx_bd *cons_bd = &fp->rx_desc_ring[cons];
struct eth_rx_bd *prod_bd = &fp->rx_desc_ring[prod];
dma_unmap_addr_set(prod_rx_buf, mapping,
dma_unmap_addr(cons_rx_buf, mapping));
prod_rx_buf->data = cons_rx_buf->data;
*prod_bd = *cons_bd;
}
/************************* Init ******************************************/
/* returns func by VN for current port */
static inline int func_by_vn(struct bnx2x *bp, int vn)
{
return 2 * vn + BP_PORT(bp);
}
static inline int bnx2x_config_rss_eth(struct bnx2x *bp, bool config_hash)
{
return bnx2x_config_rss_pf(bp, &bp->rss_conf_obj, config_hash);
}
/**
* bnx2x_func_start - init function
*
* @bp: driver handle
*
* Must be called before sending CLIENT_SETUP for the first client.
*/
static inline int bnx2x_func_start(struct bnx2x *bp)
{
struct bnx2x_func_state_params func_params = {NULL};
struct bnx2x_func_start_params *start_params =
&func_params.params.start;
/* Prepare parameters for function state transitions */
__set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
func_params.f_obj = &bp->func_obj;
func_params.cmd = BNX2X_F_CMD_START;
/* Function parameters */
start_params->mf_mode = bp->mf_mode;
start_params->sd_vlan_tag = bp->mf_ov;
start_params->network_cos_mode = OVERRIDE_COS;
start_params->gre_tunnel_mode = IPGRE_TUNNEL;
start_params->gre_tunnel_rss = GRE_INNER_HEADERS_RSS;
return bnx2x_func_state_change(bp, &func_params);
}
/**
* bnx2x_set_fw_mac_addr - fill in a MAC address in FW format
*
* @fw_hi: pointer to upper part
* @fw_mid: pointer to middle part
* @fw_lo: pointer to lower part
* @mac: pointer to MAC address
*/
static inline void bnx2x_set_fw_mac_addr(__le16 *fw_hi, __le16 *fw_mid,
__le16 *fw_lo, u8 *mac)
{
((u8 *)fw_hi)[0] = mac[1];
((u8 *)fw_hi)[1] = mac[0];
((u8 *)fw_mid)[0] = mac[3];
((u8 *)fw_mid)[1] = mac[2];
((u8 *)fw_lo)[0] = mac[5];
((u8 *)fw_lo)[1] = mac[4];
}
static inline void bnx2x_free_rx_sge_range(struct bnx2x *bp,
struct bnx2x_fastpath *fp, int last)
{
int i;
if (fp->disable_tpa)
return;
for (i = 0; i < last; i++)
bnx2x_free_rx_sge(bp, fp, i);
}
static inline void bnx2x_set_next_page_rx_bd(struct bnx2x_fastpath *fp)
{
int i;
for (i = 1; i <= NUM_RX_RINGS; i++) {
struct eth_rx_bd *rx_bd;
rx_bd = &fp->rx_desc_ring[RX_DESC_CNT * i - 2];
rx_bd->addr_hi =
cpu_to_le32(U64_HI(fp->rx_desc_mapping +
BCM_PAGE_SIZE*(i % NUM_RX_RINGS)));
rx_bd->addr_lo =
cpu_to_le32(U64_LO(fp->rx_desc_mapping +
BCM_PAGE_SIZE*(i % NUM_RX_RINGS)));
}
}
/* Statistics ID are global per chip/path, while Client IDs for E1x are per
* port.
*/
static inline u8 bnx2x_stats_id(struct bnx2x_fastpath *fp)
{
struct bnx2x *bp = fp->bp;
if (!CHIP_IS_E1x(bp)) {
/* there are special statistics counters for FCoE 136..140 */
if (IS_FCOE_FP(fp))
return bp->cnic_base_cl_id + (bp->pf_num >> 1);
return fp->cl_id;
}
return fp->cl_id + BP_PORT(bp) * FP_SB_MAX_E1x;
}
static inline void bnx2x_init_vlan_mac_fp_objs(struct bnx2x_fastpath *fp,
bnx2x_obj_type obj_type)
{
struct bnx2x *bp = fp->bp;
/* Configure classification DBs */
bnx2x_init_mac_obj(bp, &bnx2x_sp_obj(bp, fp).mac_obj, fp->cl_id,
fp->cid, BP_FUNC(bp), bnx2x_sp(bp, mac_rdata),
bnx2x_sp_mapping(bp, mac_rdata),
BNX2X_FILTER_MAC_PENDING,
&bp->sp_state, obj_type,
&bp->macs_pool);
}
/**
* bnx2x_get_path_func_num - get number of active functions
*
* @bp: driver handle
*
* Calculates the number of active (not hidden) functions on the
* current path.
*/
static inline u8 bnx2x_get_path_func_num(struct bnx2x *bp)
{
u8 func_num = 0, i;
/* 57710 has only one function per-port */
if (CHIP_IS_E1(bp))
return 1;
/* Calculate a number of functions enabled on the current
* PATH/PORT.
*/
if (CHIP_REV_IS_SLOW(bp)) {
if (IS_MF(bp))
func_num = 4;
else
func_num = 2;
} else {
for (i = 0; i < E1H_FUNC_MAX / 2; i++) {
u32 func_config =
MF_CFG_RD(bp,
func_mf_config[BP_PORT(bp) + 2 * i].
config);
func_num +=
((func_config & FUNC_MF_CFG_FUNC_HIDE) ? 0 : 1);
}
}
WARN_ON(!func_num);
return func_num;
}
static inline void bnx2x_init_bp_objs(struct bnx2x *bp)
{
/* RX_MODE controlling object */
bnx2x_init_rx_mode_obj(bp, &bp->rx_mode_obj);
/* multicast configuration controlling object */
bnx2x_init_mcast_obj(bp, &bp->mcast_obj, bp->fp->cl_id, bp->fp->cid,
BP_FUNC(bp), BP_FUNC(bp),
bnx2x_sp(bp, mcast_rdata),
bnx2x_sp_mapping(bp, mcast_rdata),
BNX2X_FILTER_MCAST_PENDING, &bp->sp_state,
BNX2X_OBJ_TYPE_RX);
/* Setup CAM credit pools */
bnx2x_init_mac_credit_pool(bp, &bp->macs_pool, BP_FUNC(bp),
bnx2x_get_path_func_num(bp));
bnx2x_init_vlan_credit_pool(bp, &bp->vlans_pool, BP_ABS_FUNC(bp)>>1,
bnx2x_get_path_func_num(bp));
/* RSS configuration object */
bnx2x_init_rss_config_obj(bp, &bp->rss_conf_obj, bp->fp->cl_id,
bp->fp->cid, BP_FUNC(bp), BP_FUNC(bp),
bnx2x_sp(bp, rss_rdata),
bnx2x_sp_mapping(bp, rss_rdata),
BNX2X_FILTER_RSS_CONF_PENDING, &bp->sp_state,
BNX2X_OBJ_TYPE_RX);
}
static inline u8 bnx2x_fp_qzone_id(struct bnx2x_fastpath *fp)
{
if (CHIP_IS_E1x(fp->bp))
return fp->cl_id + BP_PORT(fp->bp) * ETH_MAX_RX_CLIENTS_E1H;
else
return fp->cl_id;
}
u32 bnx2x_rx_ustorm_prods_offset(struct bnx2x_fastpath *fp);
static inline void bnx2x_init_txdata(struct bnx2x *bp,
struct bnx2x_fp_txdata *txdata, u32 cid,
int txq_index, __le16 *tx_cons_sb,
struct bnx2x_fastpath *fp)
{
txdata->cid = cid;
txdata->txq_index = txq_index;
txdata->tx_cons_sb = tx_cons_sb;
txdata->parent_fp = fp;
txdata->tx_ring_size = IS_FCOE_FP(fp) ? MAX_TX_AVAIL : bp->tx_ring_size;
DP(NETIF_MSG_IFUP, "created tx data cid %d, txq %d\n",
txdata->cid, txdata->txq_index);
}
static inline u8 bnx2x_cnic_eth_cl_id(struct bnx2x *bp, u8 cl_idx)
{
return bp->cnic_base_cl_id + cl_idx +
(bp->pf_num >> 1) * BNX2X_MAX_CNIC_ETH_CL_ID_IDX;
}
static inline u8 bnx2x_cnic_fw_sb_id(struct bnx2x *bp)
{
/* the 'first' id is allocated for the cnic */
return bp->base_fw_ndsb;
}
static inline u8 bnx2x_cnic_igu_sb_id(struct bnx2x *bp)
{
return bp->igu_base_sb;
}
static inline void bnx2x_init_fcoe_fp(struct bnx2x *bp)
{
struct bnx2x_fastpath *fp = bnx2x_fcoe_fp(bp);
unsigned long q_type = 0;
bnx2x_fcoe(bp, rx_queue) = BNX2X_NUM_ETH_QUEUES(bp);
bnx2x_fcoe(bp, cl_id) = bnx2x_cnic_eth_cl_id(bp,
BNX2X_FCOE_ETH_CL_ID_IDX);
bnx2x_fcoe(bp, cid) = BNX2X_FCOE_ETH_CID(bp);
bnx2x_fcoe(bp, fw_sb_id) = DEF_SB_ID;
bnx2x_fcoe(bp, igu_sb_id) = bp->igu_dsb_id;
bnx2x_fcoe(bp, rx_cons_sb) = BNX2X_FCOE_L2_RX_INDEX;
bnx2x_init_txdata(bp, bnx2x_fcoe(bp, txdata_ptr[0]),
fp->cid, FCOE_TXQ_IDX(bp), BNX2X_FCOE_L2_TX_INDEX,
fp);
DP(NETIF_MSG_IFUP, "created fcoe tx data (fp index %d)\n", fp->index);
/* qZone id equals to FW (per path) client id */
bnx2x_fcoe(bp, cl_qzone_id) = bnx2x_fp_qzone_id(fp);
/* init shortcut */
bnx2x_fcoe(bp, ustorm_rx_prods_offset) =
bnx2x_rx_ustorm_prods_offset(fp);
/* Configure Queue State object */
__set_bit(BNX2X_Q_TYPE_HAS_RX, &q_type);
__set_bit(BNX2X_Q_TYPE_HAS_TX, &q_type);
/* No multi-CoS for FCoE L2 client */
BUG_ON(fp->max_cos != 1);
bnx2x_init_queue_obj(bp, &bnx2x_sp_obj(bp, fp).q_obj, fp->cl_id,
&fp->cid, 1, BP_FUNC(bp), bnx2x_sp(bp, q_rdata),
bnx2x_sp_mapping(bp, q_rdata), q_type);
DP(NETIF_MSG_IFUP,
"queue[%d]: bnx2x_init_sb(%p,%p) cl_id %d fw_sb %d igu_sb %d\n",
fp->index, bp, fp->status_blk.e2_sb, fp->cl_id, fp->fw_sb_id,
fp->igu_sb_id);
}
static inline int bnx2x_clean_tx_queue(struct bnx2x *bp,
struct bnx2x_fp_txdata *txdata)
{
int cnt = 1000;
while (bnx2x_has_tx_work_unload(txdata)) {
if (!cnt) {
BNX2X_ERR("timeout waiting for queue[%d]: txdata->tx_pkt_prod(%d) != txdata->tx_pkt_cons(%d)\n",
txdata->txq_index, txdata->tx_pkt_prod,
txdata->tx_pkt_cons);
#ifdef BNX2X_STOP_ON_ERROR
bnx2x_panic();
return -EBUSY;
#else
break;
#endif
}
cnt--;
usleep_range(1000, 2000);
}
return 0;
}
int bnx2x_get_link_cfg_idx(struct bnx2x *bp);
static inline void __storm_memset_struct(struct bnx2x *bp,
u32 addr, size_t size, u32 *data)
{
int i;
for (i = 0; i < size/4; i++)
REG_WR(bp, addr + (i * 4), data[i]);
}
/**
* bnx2x_wait_sp_comp - wait for the outstanding SP commands.
*
* @bp: driver handle
* @mask: bits that need to be cleared
*/
static inline bool bnx2x_wait_sp_comp(struct bnx2x *bp, unsigned long mask)
{
int tout = 5000; /* Wait for 5 secs tops */
while (tout--) {
smp_mb();
netif_addr_lock_bh(bp->dev);
if (!(bp->sp_state & mask)) {
netif_addr_unlock_bh(bp->dev);
return true;
}
netif_addr_unlock_bh(bp->dev);
usleep_range(1000, 2000);
}
smp_mb();
netif_addr_lock_bh(bp->dev);
if (bp->sp_state & mask) {
BNX2X_ERR("Filtering completion timed out. sp_state 0x%lx, mask 0x%lx\n",
bp->sp_state, mask);
netif_addr_unlock_bh(bp->dev);
return false;
}
netif_addr_unlock_bh(bp->dev);
return true;
}
/**
* bnx2x_set_ctx_validation - set CDU context validation values
*
* @bp: driver handle
* @cxt: context of the connection on the host memory
* @cid: SW CID of the connection to be configured
*/
void bnx2x_set_ctx_validation(struct bnx2x *bp, struct eth_context *cxt,
u32 cid);
void bnx2x_update_coalesce_sb_index(struct bnx2x *bp, u8 fw_sb_id,
u8 sb_index, u8 disable, u16 usec);
void bnx2x_acquire_phy_lock(struct bnx2x *bp);
void bnx2x_release_phy_lock(struct bnx2x *bp);
/**
* bnx2x_extract_max_cfg - extract MAX BW part from MF configuration.
*
* @bp: driver handle
* @mf_cfg: MF configuration
*
*/
static inline u16 bnx2x_extract_max_cfg(struct bnx2x *bp, u32 mf_cfg)
{
u16 max_cfg = (mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
FUNC_MF_CFG_MAX_BW_SHIFT;
if (!max_cfg) {
DP(NETIF_MSG_IFUP | BNX2X_MSG_ETHTOOL,
"Max BW configured to 0 - using 100 instead\n");
max_cfg = 100;
}
return max_cfg;
}
/* checks if HW supports GRO for given MTU */
static inline bool bnx2x_mtu_allows_gro(int mtu)
{
/* gro frags per page */
int fpp = SGE_PAGE_SIZE / (mtu - ETH_MAX_TPA_HEADER_SIZE);
/*
* 1. Number of frags should not grow above MAX_SKB_FRAGS
* 2. Frag must fit the page
*/
return mtu <= SGE_PAGE_SIZE && (U_ETH_SGL_SIZE * fpp) <= MAX_SKB_FRAGS;
}
/**
* bnx2x_get_iscsi_info - update iSCSI params according to licensing info.
*
* @bp: driver handle
*
*/
void bnx2x_get_iscsi_info(struct bnx2x *bp);
/**
* bnx2x_link_sync_notify - send notification to other functions.
*
* @bp: driver handle
*
*/
static inline void bnx2x_link_sync_notify(struct bnx2x *bp)
{
int func;
int vn;
/* Set the attention towards other drivers on the same port */
for (vn = VN_0; vn < BP_MAX_VN_NUM(bp); vn++) {
if (vn == BP_VN(bp))
continue;
func = func_by_vn(bp, vn);
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_0 +
(LINK_SYNC_ATTENTION_BIT_FUNC_0 + func)*4, 1);
}
}
/**
* bnx2x_update_drv_flags - update flags in shmem
*
* @bp: driver handle
* @flags: flags to update
* @set: set or clear
*
*/
static inline void bnx2x_update_drv_flags(struct bnx2x *bp, u32 flags, u32 set)
{
if (SHMEM2_HAS(bp, drv_flags)) {
u32 drv_flags;
bnx2x_acquire_hw_lock(bp, HW_LOCK_RESOURCE_DRV_FLAGS);
drv_flags = SHMEM2_RD(bp, drv_flags);
if (set)
SET_FLAGS(drv_flags, flags);
else
RESET_FLAGS(drv_flags, flags);
SHMEM2_WR(bp, drv_flags, drv_flags);
DP(NETIF_MSG_IFUP, "drv_flags 0x%08x\n", drv_flags);
bnx2x_release_hw_lock(bp, HW_LOCK_RESOURCE_DRV_FLAGS);
}
}
static inline bool bnx2x_is_valid_ether_addr(struct bnx2x *bp, u8 *addr)
{
if (is_valid_ether_addr(addr) ||
(is_zero_ether_addr(addr) &&
(IS_MF_STORAGE_SD(bp) || IS_MF_FCOE_AFEX(bp))))
return true;
return false;
}
/**
* bnx2x_fill_fw_str - Fill buffer with FW version string
*
* @bp: driver handle
* @buf: character buffer to fill with the fw name
* @buf_len: length of the above buffer
*
*/
void bnx2x_fill_fw_str(struct bnx2x *bp, char *buf, size_t buf_len);
int bnx2x_drain_tx_queues(struct bnx2x *bp);
void bnx2x_squeeze_objects(struct bnx2x *bp);
#endif /* BNX2X_CMN_H */
| MetSystem/fastsocket | kernel/drivers/net/bnx2x/bnx2x_cmn.h | C | gpl-2.0 | 35,738 |
<?php
if (!$os)
{
if (strstr($sysDescr, "KYOCERA ")) { $os = "kyocera"; }
}
?> | mehulsbhatt/librenms | includes/discovery/os/kyocera.inc.php | PHP | gpl-3.0 | 82 |
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, absolute_import, print_function)
store_version = 1 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.opensearch_store import OpenSearchOPDSStore
from calibre.gui2.store.search_result import SearchResult
class ArchiveOrgStore(BasicStoreConfig, OpenSearchOPDSStore):
open_search_url = 'http://bookserver.archive.org/catalog/opensearch.xml'
web_url = 'http://www.archive.org/details/texts'
# http://bookserver.archive.org/catalog/
def search(self, query, max_results=10, timeout=60):
for s in OpenSearchOPDSStore.search(self, query, max_results, timeout):
s.detail_item = 'http://www.archive.org/details/' + s.detail_item.split(':')[-1]
s.price = '$0.00'
s.drm = SearchResult.DRM_UNLOCKED
yield s
def get_details(self, search_result, timeout):
'''
The opensearch feed only returns a subset of formats that are available.
We want to get a list of all formats that the user can get.
'''
from calibre import browser
from contextlib import closing
from lxml import html
br = browser()
with closing(br.open(search_result.detail_item, timeout=timeout)) as nf:
idata = html.fromstring(nf.read())
formats = ', '.join(idata.xpath('//p[@id="dl" and @class="content"]//a/text()'))
search_result.formats = formats.upper()
return True
| drxaero/calibre | src/calibre/gui2/store/stores/archive_org_plugin.py | Python | gpl-3.0 | 1,689 |
/*!
* JavaScript for the debug toolbar profiler, enabled through $wgDebugToolbar
* and StartProfiler.php.
*
* @author Erik Bernhardson
* @since 1.23
*/
( function ( mw, $ ) {
'use strict';
/**
* @singleton
* @class mw.Debug.profile
*/
var profile = mw.Debug.profile = {
/**
* Object containing data for the debug toolbar
*
* @property ProfileData
*/
data: null,
/**
* @property DOMElement
*/
container: null,
/**
* Initializes the profiling pane.
*/
init: function ( data, width, mergeThresholdPx, dropThresholdPx ) {
data = data || mw.config.get( 'debugInfo' ).profile;
profile.width = width || $(window).width() - 20;
// merge events from same pixel(some events are very granular)
mergeThresholdPx = mergeThresholdPx || 2;
// only drop events if requested
dropThresholdPx = dropThresholdPx || 0;
if ( !Array.prototype.map || !Array.prototype.reduce || !Array.prototype.filter ) {
profile.container = profile.buildRequiresES5();
} else if ( data.length === 0 ) {
profile.container = profile.buildNoData();
} else {
// generate a flyout
profile.data = new ProfileData( data, profile.width, mergeThresholdPx, dropThresholdPx );
// draw it
profile.container = profile.buildSvg( profile.container );
profile.attachFlyout();
}
return profile.container;
},
buildRequiresES5: function () {
return $( '<div>' )
.text( 'An ES5 compatible javascript engine is required for the profile visualization.' )
.get( 0 );
},
buildNoData: function () {
return $( '<div>' ).addClass( 'mw-debug-profile-no-data' )
.text( 'No events recorded, ensure profiling is enabled in StartProfiler.php.' )
.get( 0 );
},
/**
* Creates DOM nodes appropriately namespaced for SVG.
*
* @param string tag to create
* @return DOMElement
*/
createSvgElement: document.createElementNS
? document.createElementNS.bind( document, 'http://www.w3.org/2000/svg' )
// throw a error for browsers which does not support document.createElementNS (IE<8)
: function () { throw new Error( 'document.createElementNS not supported' ); },
/**
* @param DOMElement|undefined
*/
buildSvg: function ( node ) {
var container, group, i, g,
timespan = profile.data.timespan,
gapPerEvent = 38,
space = 10.5,
currentHeight = space,
totalHeight = 0;
profile.ratio = ( profile.width - space * 2 ) / ( timespan.end - timespan.start );
totalHeight += gapPerEvent * profile.data.groups.length;
if ( node ) {
$( node ).empty();
} else {
node = profile.createSvgElement( 'svg' );
node.setAttribute( 'version', '1.2' );
node.setAttribute( 'baseProfile', 'tiny' );
}
node.style.height = totalHeight;
node.style.width = profile.width;
// use a container that can be transformed
container = profile.createSvgElement( 'g' );
node.appendChild( container );
for ( i = 0; i < profile.data.groups.length; i++ ) {
group = profile.data.groups[i];
g = profile.buildTimeline( group );
g.setAttribute( 'transform', 'translate( 0 ' + currentHeight + ' )' );
container.appendChild( g );
currentHeight += gapPerEvent;
}
return node;
},
/**
* @param Object group of periods to transform into graphics
*/
buildTimeline: function ( group ) {
var text, tspan, line, i,
sum = group.timespan.sum,
ms = ' ~ ' + ( sum < 1 ? sum.toFixed( 2 ) : sum.toFixed( 0 ) ) + ' ms',
timeline = profile.createSvgElement( 'g' );
timeline.setAttribute( 'class', 'mw-debug-profile-timeline' );
// draw label
text = profile.createSvgElement( 'text' );
text.setAttribute( 'x', profile.xCoord( group.timespan.start ) );
text.setAttribute( 'y', 0 );
text.textContent = group.name;
timeline.appendChild( text );
// draw metadata
tspan = profile.createSvgElement( 'tspan' );
tspan.textContent = ms;
text.appendChild( tspan );
// draw timeline periods
for ( i = 0; i < group.periods.length; i++ ) {
timeline.appendChild( profile.buildPeriod( group.periods[i] ) );
}
// full-width line under each timeline
line = profile.createSvgElement( 'line' );
line.setAttribute( 'class', 'mw-debug-profile-underline' );
line.setAttribute( 'x1', 0 );
line.setAttribute( 'y1', 28 );
line.setAttribute( 'x2', profile.width );
line.setAttribute( 'y2', 28 );
timeline.appendChild( line );
return timeline;
},
/**
* @param Object period to transform into graphics
*/
buildPeriod: function ( period ) {
var node,
head = profile.xCoord( period.start ),
tail = profile.xCoord( period.end ),
g = profile.createSvgElement( 'g' );
g.setAttribute( 'class', 'mw-debug-profile-period' );
$( g ).data( 'period', period );
if ( head + 16 > tail ) {
node = profile.createSvgElement( 'rect' );
node.setAttribute( 'x', head );
node.setAttribute( 'y', 8 );
node.setAttribute( 'width', 2 );
node.setAttribute( 'height', 9 );
g.appendChild( node );
node = profile.createSvgElement( 'rect' );
node.setAttribute( 'x', head );
node.setAttribute( 'y', 8 );
node.setAttribute( 'width', ( period.end - period.start ) * profile.ratio || 2 );
node.setAttribute( 'height', 6 );
g.appendChild( node );
} else {
node = profile.createSvgElement( 'polygon' );
node.setAttribute( 'points', pointList( [
[ head, 8 ],
[ head, 19 ],
[ head + 8, 8 ],
[ head, 8]
] ) );
g.appendChild( node );
node = profile.createSvgElement( 'polygon' );
node.setAttribute( 'points', pointList( [
[ tail, 8 ],
[ tail, 19 ],
[ tail - 8, 8 ],
[ tail, 8 ]
] ) );
g.appendChild( node );
node = profile.createSvgElement( 'line' );
node.setAttribute( 'x1', head );
node.setAttribute( 'y1', 9 );
node.setAttribute( 'x2', tail );
node.setAttribute( 'y2', 9 );
g.appendChild( node );
}
return g;
},
/**
* @param Object
*/
buildFlyout: function ( period ) {
var contained, sum, ms, mem, i,
node = $( '<div>' );
for ( i = 0; i < period.contained.length; i++ ) {
contained = period.contained[i];
sum = contained.end - contained.start;
ms = '' + ( sum < 1 ? sum.toFixed( 2 ) : sum.toFixed( 0 ) ) + ' ms';
mem = formatBytes( contained.memory );
$( '<div>' ).text( contained.source.name )
.append( $( '<span>' ).text( ' ~ ' + ms + ' / ' + mem ).addClass( 'mw-debug-profile-meta' ) )
.appendTo( node );
}
return node;
},
/**
* Attach a hover flyout to all .mw-debug-profile-period groups.
*/
attachFlyout: function () {
// for some reason addClass and removeClass from jQuery
// arn't working on svg elements in chrome <= 33.0 (possibly more)
var $container = $( profile.container ),
addClass = function ( node, value ) {
var current = node.getAttribute( 'class' ),
list = current ? current.split( ' ' ) : false,
idx = list ? list.indexOf( value ) : -1;
if ( idx === -1 ) {
node.setAttribute( 'class', current ? ( current + ' ' + value ) : value );
}
},
removeClass = function ( node, value ) {
var current = node.getAttribute( 'class' ),
list = current ? current.split( ' ' ) : false,
idx = list ? list.indexOf( value ) : -1;
if ( idx !== -1 ) {
list.splice( idx, 1 );
node.setAttribute( 'class', list.join( ' ' ) );
}
},
// hide all tipsy flyouts
hide = function () {
$container.find( '.mw-debug-profile-period.tipsy-visible' )
.each( function () {
removeClass( this, 'tipsy-visible' );
$( this ).tipsy( 'hide' );
} );
};
$container.find( '.mw-debug-profile-period' ).tipsy( {
fade: true,
gravity: function () {
return $.fn.tipsy.autoNS.call( this )
+ $.fn.tipsy.autoWE.call( this );
},
className: 'mw-debug-profile-tipsy',
center: false,
html: true,
trigger: 'manual',
title: function () {
return profile.buildFlyout( $( this ).data( 'period' ) ).html();
}
} ).on( 'mouseenter', function () {
hide();
addClass( this, 'tipsy-visible' );
$( this ).tipsy( 'show' );
} );
$container.on( 'mouseleave', function ( event ) {
var $from = $( event.relatedTarget ),
$to = $( event.target );
// only close the tipsy if we are not
if ( $from.closest( '.tipsy' ).length === 0 &&
$to.closest( '.tipsy' ).length === 0 &&
$to.get( 0 ).namespaceURI !== 'http://www.w4.org/2000/svg'
) {
hide();
}
} ).on( 'click', function () {
// convenience method for closing
hide();
} );
},
/**
* @return number the x co-ordinate for the specified timestamp
*/
xCoord: function ( msTimestamp ) {
return ( msTimestamp - profile.data.timespan.start ) * profile.ratio;
}
};
function ProfileData( data, width, mergeThresholdPx, dropThresholdPx ) {
// validate input data
this.data = data.map( function ( event ) {
event.periods = event.periods.filter( function ( period ) {
return period.start && period.end
&& period.start < period.end
// period start must be a reasonable ms timestamp
&& period.start > 1000000;
} );
return event;
} ).filter( function ( event ) {
return event.name && event.periods.length > 0;
} );
// start and end time of the data
this.timespan = this.data.reduce( function ( result, event ) {
return event.periods.reduce( periodMinMax, result );
}, periodMinMax.initial() );
// transform input data
this.groups = this.collate( width, mergeThresholdPx, dropThresholdPx );
return this;
}
/**
* There are too many unique events to display a line for each,
* so this does a basic grouping.
*/
ProfileData.groupOf = function ( label ) {
var pos, prefix = 'Profile section ended by close(): ';
if ( label.indexOf( prefix ) === 0 ) {
label = label.substring( prefix.length );
}
pos = [ '::', ':', '-' ].reduce( function ( result, separator ) {
var pos = label.indexOf( separator );
if ( pos === -1 ) {
return result;
} else if ( result === -1 ) {
return pos;
} else {
return Math.min( result, pos );
}
}, -1 );
if ( pos === -1 ) {
return label;
} else {
return label.substring( 0, pos );
}
};
/**
* @return Array list of objects with `name` and `events` keys
*/
ProfileData.groupEvents = function ( events ) {
var group, i,
groups = {};
// Group events together
for ( i = events.length - 1; i >= 0; i-- ) {
group = ProfileData.groupOf( events[i].name );
if ( groups[group] ) {
groups[group].push( events[i] );
} else {
groups[group] = [events[i]];
}
}
// Return an array of groups
return Object.keys( groups ).map( function ( group ) {
return {
name: group,
events: groups[group]
};
} );
};
ProfileData.periodSorter = function ( a, b ) {
if ( a.start === b.start ) {
return a.end - b.end;
}
return a.start - b.start;
};
ProfileData.genMergePeriodReducer = function ( mergeThresholdMs ) {
return function ( result, period ) {
if ( result.length === 0 ) {
// period is first result
return [{
start: period.start,
end: period.end,
contained: [period]
}];
}
var last = result[result.length - 1];
if ( period.end < last.end ) {
// end is contained within previous
result[result.length - 1].contained.push( period );
} else if ( period.start - mergeThresholdMs < last.end ) {
// neighbors within merging distance
result[result.length - 1].end = period.end;
result[result.length - 1].contained.push( period );
} else {
// period is next result
result.push({
start: period.start,
end: period.end,
contained: [period]
});
}
return result;
};
};
/**
* Collect all periods from the grouped events and apply merge and
* drop transformations
*/
ProfileData.extractPeriods = function ( events, mergeThresholdMs, dropThresholdMs ) {
// collect the periods from all events
return events.reduce( function ( result, event ) {
if ( !event.periods.length ) {
return result;
}
result.push.apply( result, event.periods.map( function ( period ) {
// maintain link from period to event
period.source = event;
return period;
} ) );
return result;
}, [] )
// sort combined periods
.sort( ProfileData.periodSorter )
// Apply merge threshold. Original periods
// are maintained in the `contained` property
.reduce( ProfileData.genMergePeriodReducer( mergeThresholdMs ), [] )
// Apply drop threshold
.filter( function ( period ) {
return period.end - period.start > dropThresholdMs;
} );
};
/**
* runs a callback on all periods in the group. Only valid after
* groups.periods[0..n].contained are populated. This runs against
* un-transformed data and is better suited to summing or other
* stat collection
*/
ProfileData.reducePeriods = function ( group, callback, result ) {
return group.periods.reduce( function ( result, period ) {
return period.contained.reduce( callback, result );
}, result );
};
/**
* Transforms this.data grouping by labels, merging neighboring
* events in the groups, and drops events and groups below the
* display threshold. Groups are returned sorted by starting time.
*/
ProfileData.prototype.collate = function ( width, mergeThresholdPx, dropThresholdPx ) {
// ms to pixel ratio
var ratio = ( this.timespan.end - this.timespan.start ) / width,
// transform thresholds to ms
mergeThresholdMs = mergeThresholdPx * ratio,
dropThresholdMs = dropThresholdPx * ratio;
return ProfileData.groupEvents( this.data )
// generate data about the grouped events
.map( function ( group ) {
// Cleaned periods from all events
group.periods = ProfileData.extractPeriods( group.events, mergeThresholdMs, dropThresholdMs );
// min and max timestamp per group
group.timespan = ProfileData.reducePeriods( group, periodMinMax, periodMinMax.initial() );
// ms from first call to end of last call
group.timespan.length = group.timespan.end - group.timespan.start;
// collect the un-transformed periods
group.timespan.sum = ProfileData.reducePeriods( group, function ( result, period ) {
result.push( period );
return result;
}, [] )
// sort by start time
.sort( ProfileData.periodSorter )
// merge overlapping
.reduce( ProfileData.genMergePeriodReducer( 0 ), [] )
// sum
.reduce( function ( result, period ) {
return result + period.end - period.start;
}, 0 );
return group;
}, this )
// remove groups that have had all their periods filtered
.filter( function ( group ) {
return group.periods.length > 0;
} )
// sort events by first start
.sort( function ( a, b ) {
return ProfileData.periodSorter( a.timespan, b.timespan );
} );
};
// reducer to find edges of period array
function periodMinMax( result, period ) {
if ( period.start < result.start ) {
result.start = period.start;
}
if ( period.end > result.end ) {
result.end = period.end;
}
return result;
}
periodMinMax.initial = function () {
return { start: Number.POSITIVE_INFINITY, end: Number.NEGATIVE_INFINITY };
};
function formatBytes( bytes ) {
var i, sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if ( bytes === 0 ) {
return '0 Bytes';
}
i = parseInt( Math.floor( Math.log( bytes ) / Math.log( 1024 ) ), 10 );
return Math.round( bytes / Math.pow( 1024, i ), 2 ) + ' ' + sizes[i];
}
// turns a 2d array into a point list for svg
// polygon points attribute
// ex: [[1,2],[3,4],[4,2]] = '1,2 3,4 4,2'
function pointList( pairs ) {
return pairs.map( function ( pair ) {
return pair.join( ',' );
} ).join( ' ' );
}
}( mediaWiki, jQuery ) );
| kylethayer/bioladder | wiki/resources/src/mediawiki/mediawiki.debug.profile.js | JavaScript | gpl-3.0 | 15,945 |
//
// NotificationStrategy.h
//
// $Id: //poco/1.3/Foundation/include/Poco/NotificationStrategy.h#2 $
//
// Library: Foundation
// Package: Events
// Module: NotificationStrategy
//
// Definition of the NotificationStrategy interface.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_NotificationStrategy_INCLUDED
#define Foundation_NotificationStrategy_INCLUDED
#include "Poco/Foundation.h"
namespace Poco {
template <class TArgs, class TDelegate>
class NotificationStrategy
/// The interface that all notification strategies must implement.
{
public:
NotificationStrategy()
{
}
virtual ~NotificationStrategy()
{
}
virtual void notify(const void* sender, TArgs& arguments) = 0;
/// Sends a notification to all registered delegates,
virtual void add(const TDelegate& pDelegate) = 0;
/// Adds a delegate to the strategy, if the delegate is not yet present
virtual void remove(const TDelegate& pDelegate) = 0;
/// Removes a delegate from the strategy if found.
virtual void clear() = 0;
/// Removes all delegates from the strategy.
virtual bool empty() const = 0;
/// Returns false if the strategy contains at least one delegate.
};
} // namespace Poco
#endif
| vcazan/openFloor | openCVBlobTracking/libs/poco/include/Poco/NotificationStrategy.h | C | gpl-3.0 | 2,615 |
/*
* ContextMenu Plugin
*
*
*/
(function($) {
$.extend(mejs.MepDefaults,
contextMenuItems = [
// demo of a fullscreen option
{
render: function(player) {
// check for fullscreen plugin
if (typeof player.enterFullScreen == 'undefined')
return null;
if (player.isFullScreen) {
return "Turn off Fullscreen";
} else {
return "Go Fullscreen";
}
},
click: function(player) {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
,
// demo of a mute/unmute button
{
render: function(player) {
if (player.media.muted) {
return "Unmute";
} else {
return "Mute";
}
},
click: function(player) {
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
},
// separator
{
isSeparator: true
}
,
// demo of simple download video
{
render: function(player) {
return "Download Video";
},
click: function(player) {
window.location.href = player.media.currentSrc;
}
}
]
);
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function(player, controls, layers, media) {
// create context menu
player.contextMenu = $('<div class="mejs-contextmenu"></div>')
.appendTo($('body'))
.hide();
// create events for showing context menu
player.container.bind('contextmenu', function(e) {
if (player.isContextMenuEnabled) {
e.preventDefault();
player.renderContextMenu(e.clientX-1, e.clientY-1);
return false;
}
});
player.container.bind('click', function() {
player.contextMenu.hide();
});
player.contextMenu.bind('mouseleave', function() {
//console.log('context hover out');
player.startContextMenuTimer();
});
},
isContextMenuEnabled: true,
enableContextMenu: function() {
this.isContextMenuEnabled = true;
},
disableContextMenu: function() {
this.isContextMenuEnabled = false;
},
contextMenuTimeout: null,
startContextMenuTimer: function() {
//console.log('startContextMenuTimer');
var t = this;
t.killContextMenuTimer();
t.contextMenuTimer = setTimeout(function() {
t.hideContextMenu();
t.killContextMenuTimer();
}, 750);
},
killContextMenuTimer: function() {
var timer = this.contextMenuTimer;
//console.log('killContextMenuTimer', timer);
if (timer != null) {
clearTimeout(timer);
delete timer;
timer = null;
}
},
hideContextMenu: function() {
this.contextMenu.hide();
},
renderContextMenu: function(x,y) {
// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
var t = this,
html = '',
items = t.options.contextMenuItems;
for (var i=0, il=items.length; i<il; i++) {
if (items[i].isSeparator) {
html += '<div class="mejs-contextmenu-separator"></div>';
} else {
var rendered = items[i].render(t);
// render can return null if the item doesn't need to be used at the moment
if (rendered != null) {
html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
}
}
}
// position and show the context menu
t.contextMenu
.empty()
.append($(html))
.css({top:y, left:x})
.show();
// bind events
t.contextMenu.find('.mejs-contextmenu-item').each(function() {
// which one is this?
var $dom = $(this),
itemIndex = parseInt( $dom.data('itemindex'), 10 ),
item = t.options.contextMenuItems[itemIndex];
// bind extra functionality?
if (typeof item.show != 'undefined')
item.show( $dom , t);
// bind click action
$dom.click(function() {
// perform click action
if (typeof item.click != 'undefined')
item.click(t);
// close
t.contextMenu.hide();
});
});
// stop the controls from hiding
setTimeout(function() {
t.killControlsTimer('rev3');
}, 100);
}
});
})(mejs.$); | europeana/broken_dont_bother_exhibitions | webtree/themes/main/javascripts/mediaelement-2.7/src/js/mep-feature-contextmenu.js | JavaScript | gpl-3.0 | 4,424 |
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
2011,2012,2013 Giovanni Di Sirio.
This file is part of ChibiOS/RT.
ChibiOS/RT is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS/RT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file GCC/ARMCMx/STM32L1xx/vectors.c
* @brief Interrupt vectors for the STM32 family.
*
* @defgroup ARMCMx_STM32L1xx_VECTORS STM32L1xx Interrupt Vectors
* @ingroup ARMCMx_SPECIFIC
* @details Interrupt vectors for the STM32L1xx family.
* @{
*/
#include "ch.h"
/**
* @brief Type of an IRQ vector.
*/
typedef void (*irq_vector_t)(void);
/**
* @brief Type of a structure representing the whole vectors table.
*/
typedef struct {
uint32_t *init_stack;
irq_vector_t reset_vector;
irq_vector_t nmi_vector;
irq_vector_t hardfault_vector;
irq_vector_t memmanage_vector;
irq_vector_t busfault_vector;
irq_vector_t usagefault_vector;
irq_vector_t vector1c;
irq_vector_t vector20;
irq_vector_t vector24;
irq_vector_t vector28;
irq_vector_t svcall_vector;
irq_vector_t debugmonitor_vector;
irq_vector_t vector34;
irq_vector_t pendsv_vector;
irq_vector_t systick_vector;
irq_vector_t vectors[45];
} vectors_t;
#if !defined(__DOXYGEN__)
extern uint32_t __main_stack_end__;
extern void ResetHandler(void);
extern void NMIVector(void);
extern void HardFaultVector(void);
extern void MemManageVector(void);
extern void BusFaultVector(void);
extern void UsageFaultVector(void);
extern void Vector1C(void);
extern void Vector20(void);
extern void Vector24(void);
extern void Vector28(void);
extern void SVCallVector(void);
extern void DebugMonitorVector(void);
extern void Vector34(void);
extern void PendSVVector(void);
extern void SysTickVector(void);
extern void Vector40(void);
extern void Vector44(void);
extern void Vector48(void);
extern void Vector4C(void);
extern void Vector50(void);
extern void Vector54(void);
extern void Vector58(void);
extern void Vector5C(void);
extern void Vector60(void);
extern void Vector64(void);
extern void Vector68(void);
extern void Vector6C(void);
extern void Vector70(void);
extern void Vector74(void);
extern void Vector78(void);
extern void Vector7C(void);
extern void Vector80(void);
extern void Vector84(void);
extern void Vector88(void);
extern void Vector8C(void);
extern void Vector90(void);
extern void Vector94(void);
extern void Vector98(void);
extern void Vector9C(void);
extern void VectorA0(void);
extern void VectorA4(void);
extern void VectorA8(void);
extern void VectorAC(void);
extern void VectorB0(void);
extern void VectorB4(void);
extern void VectorB8(void);
extern void VectorBC(void);
extern void VectorC0(void);
extern void VectorC4(void);
extern void VectorC8(void);
extern void VectorCC(void);
extern void VectorD0(void);
extern void VectorD4(void);
extern void VectorD8(void);
extern void VectorDC(void);
extern void VectorE0(void);
extern void VectorE4(void);
extern void VectorE8(void);
extern void VectorEC(void);
extern void VectorF0(void);
#endif /* !defined(__DOXYGEN__) */
/**
* @brief STM32L1xx vectors table.
*/
#if !defined(__DOXYGEN__)
__attribute__ ((section("vectors")))
#endif
vectors_t _vectors = {
&__main_stack_end__,ResetHandler, NMIVector, HardFaultVector,
MemManageVector, BusFaultVector, UsageFaultVector, Vector1C,
Vector20, Vector24, Vector28, SVCallVector,
DebugMonitorVector, Vector34, PendSVVector, SysTickVector,
{
Vector40, Vector44, Vector48, Vector4C,
Vector50, Vector54, Vector58, Vector5C,
Vector60, Vector64, Vector68, Vector6C,
Vector70, Vector74, Vector78, Vector7C,
Vector80, Vector84, Vector88, Vector8C,
Vector90, Vector94, Vector98, Vector9C,
VectorA0, VectorA4, VectorA8, VectorAC,
VectorB0, VectorB4, VectorB8, VectorBC,
VectorC0, VectorC4, VectorC8, VectorCC,
VectorD0, VectorD4, VectorD8, VectorDC,
VectorE0, VectorE4, VectorE8, VectorEC,
VectorF0
}
};
/**
* @brief Unhandled exceptions handler.
* @details Any undefined exception vector points to this function by default.
* This function simply stops the system into an infinite loop.
*
* @notapi
*/
#if !defined(__DOXYGEN__)
__attribute__ ((naked))
#endif
void _unhandled_exception(void) {
while (TRUE)
;
}
void NMIVector(void) __attribute__((weak, alias("_unhandled_exception")));
void HardFaultVector(void) __attribute__((weak, alias("_unhandled_exception")));
void MemManageVector(void) __attribute__((weak, alias("_unhandled_exception")));
void BusFaultVector(void) __attribute__((weak, alias("_unhandled_exception")));
void UsageFaultVector(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector1C(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector20(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector24(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector28(void) __attribute__((weak, alias("_unhandled_exception")));
void SVCallVector(void) __attribute__((weak, alias("_unhandled_exception")));
void DebugMonitorVector(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector34(void) __attribute__((weak, alias("_unhandled_exception")));
void PendSVVector(void) __attribute__((weak, alias("_unhandled_exception")));
void SysTickVector(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector40(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector44(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector48(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector4C(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector50(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector54(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector58(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector5C(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector60(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector64(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector68(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector6C(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector70(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector74(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector78(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector7C(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector80(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector84(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector88(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector8C(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector90(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector94(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector98(void) __attribute__((weak, alias("_unhandled_exception")));
void Vector9C(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorA0(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorA4(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorA8(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorAC(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorB0(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorB4(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorB8(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorBC(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorC0(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorC4(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorC8(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorCC(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorD0(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorD4(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorD8(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorDC(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorE0(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorE4(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorE8(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorEC(void) __attribute__((weak, alias("_unhandled_exception")));
void VectorF0(void) __attribute__((weak, alias("_unhandled_exception")));
/** @} */
| kvzhao/Embedded-ROS | os/ports/GCC/ARMCMx/STM32L1xx/vectors.c | C | gpl-3.0 | 9,889 |
<?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
/**
* Doctrine_Ticket_1365_TestCase
*
* @package Doctrine
* @author David Stendardi <david.stendardi@adenclassifieds.com>
* @category Query
* @link www.doctrine-project.org
* @since 0.10.4
* @version $Revision$
*/
class Doctrine_Ticket_1365_TestCase extends Doctrine_UnitTestCase
{
public function testInit()
{
$this->dbh = new Doctrine_Adapter_Mock('mysql');
$this->conn = Doctrine_Manager::getInstance()->openConnection($this->dbh);
$this->conn->setCharset('utf8');
$this->conn->setAttribute(Doctrine_Core::ATTR_USE_NATIVE_ENUM, true);
}
public function prepareData()
{
}
public function prepareTables()
{
$this->tables = array();
$this->tables[] = 'T1365_Person';
$this->tables[] = 'T1365_Skill';
$this->tables[] = 'T1365_PersonHasSkill';
parent :: prepareTables();
}
public function testTicket()
{
$q = Doctrine_Query::create()
->select('s.*, phs.*')
->from('T1365_Skill s')
->leftJoin('s.T1365_PersonHasSkill phs')
->where('phs.value0 > phs.value1');
$this->assertEqual(
$q->getSqlQuery(),
'SELECT l.id AS l__id, l.name AS l__name, ' .
'l2.id AS l2__id, l2.fk_person_id AS l2__fk_person_id, l2.fk_skill_id AS l2__fk_skill_id, l2.value0 AS l2__value0, l2.value1 AS l2__value1 ' .
'FROM la__skill l LEFT JOIN la__person_has_skill l2 ON l.id = l2.fk_skill_id ' .
'WHERE (l2.value0 > l2.value1)'
);
}
}
class T1365_Person extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('la__person');
$this->hasColumn('name', 'string', 255);
}
public function setUp()
{
$this->hasMany('T1365_PersonHasSkill', array('local' => 'id', 'foreign' => 'fk_person_id'));
}
}
class T1365_Skill extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('la__skill');
$this->hasColumn('name', 'string', 255);
}
public function setUp()
{
$this->hasMany('T1365_PersonHasSkill', array('local' => 'id', 'foreign' => 'fk_skill_id'));
}
}
class T1365_PersonHasSkill extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('la__person_has_skill');
$this->hasColumn('fk_person_id', 'integer', 8, array(
'type' => 'integer', 'length' => '8'
));
$this->hasColumn('fk_skill_id', 'integer', 8, array(
'type' => 'integer', 'length' => '8'
));
$this->hasColumn('value0', 'enum', 3, array(
'type' => 'enum', 'values' => array(
0 => '0', 1 => '1', 2 => '2', 3 => '3'
), 'default' => 0, 'notnull' => true, 'length' => '3'
));
$this->hasColumn('value1', 'enum', 3, array(
'type' => 'enum', 'values' => array(
0 => '0', 1 => '1', 2 => '2', 3 => '3'
), 'default' => 0, 'notnull' => true, 'length' => '3'
));
}
public function setUp()
{
$this->hasOne('T1365_Person', array('local' => 'fk_person_id', 'foreign' => 'id'));
$this->hasOne('T1365_Skill', array('local' => 'fk_skill_id', 'foreign' => 'id'));
}
} | aripringle/doctrine1 | tests/Ticket/1365TestCase.php | PHP | lgpl-2.1 | 4,392 |
package servicefabric
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// VersionClient is the azure Service Fabric Resource Provider API Client
type VersionClient struct {
BaseClient
}
// NewVersionClient creates an instance of the VersionClient client.
func NewVersionClient() VersionClient {
return NewVersionClientWithBaseURI(DefaultBaseURI)
}
// NewVersionClientWithBaseURI creates an instance of the VersionClient client.
func NewVersionClientWithBaseURI(baseURI string) VersionClient {
return VersionClient{NewWithBaseURI(baseURI)}
}
// Delete unprovisions an application type version resource.
//
// subscriptionID is the customer subscription identifier resourceGroupName is the name of the resource group.
// clusterName is the name of the cluster resource applicationTypeName is the name of the application type name
// resource version is the application type version.
func (client VersionClient) Delete(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string, version string) (result VersionDeleteFuture, err error) {
req, err := client.DeletePreparer(ctx, subscriptionID, resourceGroupName, clusterName, applicationTypeName, version)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "Delete", nil, "Failure preparing request")
return
}
result, err = client.DeleteSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "Delete", result.Response(), "Failure sending request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client VersionClient) DeletePreparer(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string, version string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationTypeName": autorest.Encode("path", applicationTypeName),
"clusterName": autorest.Encode("path", clusterName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", subscriptionID),
"version": autorest.Encode("path", version),
}
const APIVersion = "2017-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}/versions/{version}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client VersionClient) DeleteSender(req *http.Request) (future VersionDeleteFuture, err error) {
sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
future.Future = azure.NewFuture(req)
future.req = req
_, err = future.Done(sender)
if err != nil {
return
}
err = autorest.Respond(future.Response(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
return
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client VersionClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get returns an application type version resource.
//
// subscriptionID is the customer subscription identifier resourceGroupName is the name of the resource group.
// clusterName is the name of the cluster resource applicationTypeName is the name of the application type name
// resource version is the application type version.
func (client VersionClient) Get(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string, version string) (result VersionResource, err error) {
req, err := client.GetPreparer(ctx, subscriptionID, resourceGroupName, clusterName, applicationTypeName, version)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client VersionClient) GetPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string, version string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationTypeName": autorest.Encode("path", applicationTypeName),
"clusterName": autorest.Encode("path", clusterName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", subscriptionID),
"version": autorest.Encode("path", version),
}
const APIVersion = "2017-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}/versions/{version}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client VersionClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client VersionClient) GetResponder(resp *http.Response) (result VersionResource, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List returns all versions for the specified application type.
//
// subscriptionID is the customer subscription identifier resourceGroupName is the name of the resource group.
// clusterName is the name of the cluster resource applicationTypeName is the name of the application type name
// resource
func (client VersionClient) List(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string) (result VersionResourceList, err error) {
req, err := client.ListPreparer(ctx, subscriptionID, resourceGroupName, clusterName, applicationTypeName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "List", resp, "Failure sending request")
return
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client VersionClient) ListPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationTypeName": autorest.Encode("path", applicationTypeName),
"clusterName": autorest.Encode("path", clusterName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", subscriptionID),
}
const APIVersion = "2017-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}/versions", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client VersionClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client VersionClient) ListResponder(resp *http.Response) (result VersionResourceList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Put provisions an application type version resource.
//
// subscriptionID is the customer subscription identifier resourceGroupName is the name of the resource group.
// clusterName is the name of the cluster resource applicationTypeName is the name of the application type name
// resource version is the application type version. parameters is the application type version resource.
func (client VersionClient) Put(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string, version string, parameters VersionResource) (result VersionPutFuture, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.VersionProperties", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.VersionProperties.AppPackageURL", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil {
return result, validation.NewError("servicefabric.VersionClient", "Put", err.Error())
}
req, err := client.PutPreparer(ctx, subscriptionID, resourceGroupName, clusterName, applicationTypeName, version, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "Put", nil, "Failure preparing request")
return
}
result, err = client.PutSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "Put", result.Response(), "Failure sending request")
return
}
return
}
// PutPreparer prepares the Put request.
func (client VersionClient) PutPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string, version string, parameters VersionResource) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationTypeName": autorest.Encode("path", applicationTypeName),
"clusterName": autorest.Encode("path", clusterName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", subscriptionID),
"version": autorest.Encode("path", version),
}
const APIVersion = "2017-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}/versions/{version}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// PutSender sends the Put request. The method will close the
// http.Response Body if it receives an error.
func (client VersionClient) PutSender(req *http.Request) (future VersionPutFuture, err error) {
sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
future.Future = azure.NewFuture(req)
future.req = req
_, err = future.Done(sender)
if err != nil {
return
}
err = autorest.Respond(future.Response(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted))
return
}
// PutResponder handles the response to the Put request. The method always
// closes the http.Response Body.
func (client VersionClient) PutResponder(resp *http.Response) (result VersionResource, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| wjiangjay/origin | vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2017-07-01-preview/servicefabric/versiongroup.go | GO | apache-2.0 | 14,585 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.codeInsight.functionTypeComments;
import com.jetbrains.python.codeInsight.functionTypeComments.psi.PyFunctionTypeAnnotation;
import com.jetbrains.python.codeInsight.functionTypeComments.psi.PyParameterTypeList;
import com.jetbrains.python.psi.PyElementType;
/**
* @author Mikhail Golubev
*/
public interface PyFunctionTypeAnnotationElementTypes {
PyElementType FUNCTION_SIGNATURE = new PyElementType("FUNCTION_SIGNATURE", PyFunctionTypeAnnotation.class);
PyElementType PARAMETER_TYPE_LIST = new PyElementType("PARAMETER_TYPE_LIST", PyParameterTypeList.class);
}
| asedunov/intellij-community | python/src/com/jetbrains/python/codeInsight/functionTypeComments/PyFunctionTypeAnnotationElementTypes.java | Java | apache-2.0 | 1,200 |
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn matcher(x: Option<isize>) {
match x {
ref Some(i) => {} //~ ERROR expected identifier, found enum pattern
None => {}
}
}
fn main() {}
| avdi/rust | src/test/parse-fail/pat-ref-enum.rs | Rust | apache-2.0 | 625 |
# Taxonomy picker for sharepoint add-in #
### Summary ###
This sample shows an implementation of a SharePoint Taxonomy Picker control that can be used on provider hosted SharePoint apps.
### Applies to ###
- Office 365 Multi Tenant (MT)
- Office 365 Dedicated (D)
- SharePoint 2013 on-premises
### Prerequisites ###
- It's important that the provider hosted add-in that's running the taxonomy picker is using the same IE security zone as the SharePoint site it's installed on. If you get "Sorry we had trouble accessing your site" errors then please check this.
- You have to set the Options 'This service application is the default storage location for Keywords.' and 'This service application is the default storage location for column specific term sets.' on one of the Managed Metadata Service Application(s) Proxy Properties. If you get "Loading TermSet failed. Please refresh your browser and try again." errors then please check this.
### Solution ###
Solution | Author(s)
---------|----------
Contoso.Components.TaxonomyPicker | Patrik Björklund (**Cognit Consulting AB**), Richard diZerega, Anand Malli (**Microsoft**)
### Version history ###
Version | Date | Comments
---------| -----| --------
3.0 | April 30th 2015 | Merge taxonomy picker sample capabilities in this version
2.0 | March 26th 2014 | Updates
1.0 | October 30th 2013 | Initial release
### Disclaimer ###
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**
----------
# How to use the taxonomy picker in your provider hosted SharePoint add-in #
Using the Taxonomy Picker in your provider hosted add-in does not require many steps?
## Ensure you trigger the creation of an add-in web ##
When you build a provider hosted add-in it does not necessarily have an add-in web associated with it whereas a SharePoint hosted add-in always has an add-in web.
Since the Taxonomy Picker control uses the CSOM object model from JavaScript it’s required to have an add-in web.
To ensure you have an add-in web you can just add an empty module to your SharePoint add-in as shown below:

## Add-In permissions ##
The Taxonomy Picker communicates with SharePoint’s Managed Metadata Service, which requires special permissions in the add-in model. Working with Closed TermSets will require Read permission on the Taxonomy permission scope. To enable the creation of new terms in Open TermSets, the add-in will require Write permission on the Taxonomy permission scope. These permissions can be set in the AppManifest.xml as seen below:

## Required files ##
The Taxonomy Picker is implemented as a jQuery extension, which means it requires a reference to jQuery on and pages it will be used. In addition to jQuery, the Taxonomy Picker control requires the reference of a taxonomypicker.js and taxonomypicker.css files included in the sample solution.

## Loading required scripts and establishing clientcontext ##
The Taxonomy Picker uses SharePoint’s JavaScript Client Object Model (JSOM) for communication back to SharePoint and the Managed Metadata Service. The JavaScript below shows how to load the appropriate JSOM scripts, initialize SharePoint ClientContext, and wiring up a RequestExecutor to make cross-domain calls. Notice the reference to sp.taxonomy.js, which is a JSOM script specific to working with taxonomies:
```javascript
//Wait for the page to load
$(document).ready(function () {
//Get the URI decoded SharePoint site url from the SPHostUrl parameter.
var spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
var appWebUrl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
var spLanguage = decodeURIComponent(getQueryStringParameter('SPLanguage'));
//Build absolute path to the layouts root with the spHostUrl
var layoutsRoot = spHostUrl + '/_layouts/15/';
//load all appropriate scripts for the page to function
$.getScript(layoutsRoot + 'SP.Runtime.js',
function () {
$.getScript(layoutsRoot + 'SP.js',
function () {
//Load the SP.UI.Controls.js file to render the Add-In Chrome
$.getScript(layoutsRoot + 'SP.UI.Controls.js', renderSPChrome);
//load scripts for cross-domain calls
$.getScript(layoutsRoot + 'SP.RequestExecutor.js', function () {
context = new SP.ClientContext(appWebUrl);
var factory = new SP.ProxyWebRequestExecutorFactory(appWebUrl);
context.set_webRequestExecutorFactory(factory);
});
//load scripts for calling taxonomy APIs
$.getScript(layoutsRoot + 'init.js',
function () {
$.getScript(layoutsRoot + 'sp.taxonomy.js',
function () {
//READY TO INITALIZE TAXONOMY PICKERS
});
});
});
});
});
```
## Adding the taxonomy picker to html ##
Any hidden input element can be converted to a Taxonomy Picker. This includes regular hidden input elements and server-side controls that render hidden inputs elements (ex: asp:HiddenField):
### Client-side example ###
```html
<input type="hidden" id="taxPickerGeography" />
```
### Server-side example ###
```c#
<asp:HiddenField runat="server" ID="taxPickerGeography" />
```
### Transforming the html into a taxonomy picker control ###
The Taxonomy Picker is implemented as a jQuery extension, which makes it extremely easy to wire-up on the hidden input element:
```javascript
$('#taxPickerGeography').taxpicker({
isMulti: false,
allowFillIn: false,
termSetId: '1c4da890-60c8-4b91-ad3a-cf79ebe1281a'
}, context);
```
### Parameters ###
The first parameter of the Taxonomy Picker sets the options for the control. The properties that can be set include:
| Parameter | Description |
| ----------|-------------|
| isMulti | Boolean indicating if taxonomy picker support multiple value |
| isReadOnly | Boolean indicating if the taxonomy picker is rendered in read only mode |
| allowFillIn | Boolean indicating if the control allows fill=ins (Open TermSets only) |
| termSetId | the GUID of the TermSet to bind against (available from Term Mgmt) |
| useHashtags | Boolean indicating if the default hashtags TermSet should be used |
| useKeyword | Boolean indicating if the default keywords TermSet should be used |
| maxSuggestions | integer for the max number of suggestions to list (defaults is 10) |
| lcid | the locale ID for creating terms (default is 1033) |
| language | the language code for the control (defaults to en=us) context. |
The second parameter is an initialized SP.ClientContext object
## Sample implementations ##
```javascript
//Single-select open termset field
$('#taxPickerOpenSingle').taxpicker({
isMulti: false,
allowFillIn: true,
termSetId: 'ac8b3d2f-37e9-4f75-8f67-6fb8f8bfb39b' }
, context);
```
```javascript
//Multi-select closed termset field
$('#taxPickerClosedMulti').taxpicker({
isMulti: true,
allowFillIn: false,
termSetId: '1c4da890-60c8-4b91-ad3a-cf79ebe1281a' }
, context);
```
```javascript
//Use default Hashtags termset and limit the suggestions to 5
$('#taxPickerHashtags').taxpicker({
isMulti: true,
allowFillIn: true,
useHashtags: true,
maxSuggestions: 5 }
, context);
```
```javascript
//Use default keywords termset with a locale id of 1031 and German
$('#taxPickerKeywords').taxpicker({
isMulti: true,
allowFillIn: true,
useKeywords: true,
lcid: 1031,
language: 'de-de' }
, context);
```
## Setting values ##
The sample project includes a TaxonomyPickerExtensions.cs file, containing extension methods to help set values of a Taxonomy Picker server-side. This includes extension methods for converting TaxonomyFieldValue and TaxonomyFieldValueCollection objects into JSON that the Taxonomy Picker script can read from the hidden fields. Here is an example of using these methods to set the value of two Taxonomy Picker fields using C#:
```c#
//The following code shows how to set a taxonomy field server-side
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
var list = clientContext.Web.Lists.GetByTitle("MyList");
var listItem = list.GetItemById(1);
clientContext.Load(listItem);
clientContext.ExecuteQuery();
taxPickerGeographySingle.Value =
((TaxonomyFieldValue)listItem["SomeTaxFieldSingle"]).Serialize();
taxPickerGeographyMulti.Value =
((TaxonomyFieldValueCollection)listItem["SomeTaxFieldMulti"]).Serialize();
}
```
## Reading values ##
The Taxonomy Picker will store the selected terms in the hidden field using JSON string format. These values can be accessed by other client-side scripts or server-side following a post. The JSON will include the Term Name, Id, and PathOfTerm (ex: World;North America;United States). JSON.parse can be used client-side to convert the hidden input’s value to a typed object and any number of server-side libraries can be used (ex: JSON.net)
## Language support ##
The strings displayed by the control will be loaded dynamically based on the passed language. This requires you to pass the language via taking over the SPLanguage url parameter (see sample) or by hardcoding it. If no language is passed the control assumes the language is English (en-us).
$('#taxPickerKeywords').taxpicker({ isMulti: true, allowFillIn: true, useKeywords: true, lcid: 1031, language: 'de-de' }, context);
If you would like to add additional languages you need to create the appropriate JavaScript language resource files:

Such a resource file is simple collection of global constants:

# Appendix A: Using the taxonomypicker on hierarchical termsets #
The taxonomy picker can be used when a cascaded taxonomy picker control is required in your SharePoint Provider Hosted Add-In and you have Term Set structure similar to mentioned below:

And you wanted to represent them like this with cascading filter functionality:

Below you'll find the app.js file, containing initialization methods to set up the cascading taxonomy picker control.
Please ensure that you are already having a Term Set containing terms for at least 2 level.
Find out the GUID of the Term Set to bind (using Site Settings --> Term Store Management) & update below line with actual Term Set GUID.
```JavaScript
$('#taxPickerContinent').taxpicker({ isMulti: false, allowFillIn: false, useKeywords: false, termSetId: "<<TERMSET GUID>>", levelToShowTerms: 1 }, context, initializeCountryTaxPicker);
$('#taxPickerCountry').taxpicker({ isMulti: false, allowFillIn: false, useKeywords: false, termSetId: "<<TERMSET GUID>>", filterTermId: this._selectedTerms[0].Id, levelToShowTerms: 2, useTermSetasRootNode: false }, context, initializeRegionTaxPicker);
$('#taxPickerRegion').taxpicker({ isMulti: false, allowFillIn: false, useKeywords: false, termSetId: "<<TERMSET GUID>>", filterTermId: this._selectedTerms[0].Id, levelToShowTerms: 3, useTermSetasRootNode: false }, context);
```
To implement this you'll need to instantiate multiple taxonomy picker controls in app.js:
```JavaScript
// variable used for cross site CSOM calls
var context;
// variable to hold index of intialized taxPicker controls
var taxPickerIndex = {};
//Wait for the page to load
$(document).ready(function () {
//Get the URI decoded SharePoint site url from the SPHostUrl parameter.
var spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
var appWebUrl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
var spLanguage = decodeURIComponent(getQueryStringParameter('SPLanguage'));
//Build absolute path to the layouts root with the spHostUrl
var layoutsRoot = spHostUrl + '/_layouts/15/';
//load all appropriate scripts for the page to function
$.getScript(layoutsRoot + 'SP.Runtime.js',
function () {
$.getScript(layoutsRoot + 'SP.js',
function () {
//Load the SP.UI.Controls.js file to render the Add-In Chrome
$.getScript(layoutsRoot + 'SP.UI.Controls.js', renderSPChrome);
//load scripts for cross site calls (needed to use the people picker control in an IFrame)
$.getScript(layoutsRoot + 'SP.RequestExecutor.js', function () {
context = new SP.ClientContext(appWebUrl);
var factory = new SP.ProxyWebRequestExecutorFactory(appWebUrl);
context.set_webRequestExecutorFactory(factory);
});
//load scripts for calling taxonomy APIs
$.getScript(layoutsRoot + 'init.js',
function () {
$.getScript(layoutsRoot + 'sp.taxonomy.js',
function () {
//bind the taxonomy picker to the default keywords termset
$('#taxPickerKeywords').taxpicker({ isMulti: true, allowFillIn: true, useKeywords: true }, context);
$('#taxPickerContinent').taxpicker({ isMulti: false, allowFillIn: false, useKeywords: false, termSetId: "9df7c69b-267c-4b8b-ab3c-ac5c15cbbfae", levelToShowTerms: 1 }, context, initializeCountryTaxPicker);
taxPickerIndex["#taxPickerContinent"] = 0;
});
});
});
});
});
function initializeCountryTaxPicker() {
if (this._selectedTerms.length > 0) {
$('#taxPickerCountry').taxpicker({ isMulti: false, allowFillIn: false, useKeywords: false, termSetId: "9df7c69b-267c-4b8b-ab3c-ac5c15cbbfae", filterTermId: this._selectedTerms[0].Id, levelToShowTerms: 2, useTermSetasRootNode: false }, context, initializeRegionTaxPicker);
taxPickerIndex["#taxPickerCountry"] = 4;
}
}
function initializeRegionTaxPicker() {
if (this._selectedTerms.length > 0) {
$('#taxPickerRegion').taxpicker({ isMulti: false, allowFillIn: false, useKeywords: false, termSetId: "9df7c69b-267c-4b8b-ab3c-ac5c15cbbfae", filterTermId: this._selectedTerms[0].Id, levelToShowTerms: 3, useTermSetasRootNode: false }, context);
taxPickerIndex["#taxPickerRegion"] = 5;
}
}
function getValue(propertyName) {
if (taxPickerIndex != null) {
return taxPickerIndex[propertyName];
}
};
//function to get a parameter value by a specific key
function getQueryStringParameter(urlParameterKey) {
var params = document.URL.split('?')[1].split('&');
var strParams = '';
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split('=');
if (singleParam[0] == urlParameterKey)
return singleParam[1];
}
}
function chromeLoaded() {
$('body').show();
}
//function callback to render chrome after SP.UI.Controls.js loads
function renderSPChrome() {
var icon = decodeURIComponent(getQueryStringParameter('SPHostLogoUrl'));
//Set the chrome options for launching Help, Account, and Contact pages
var options = {
'appTitle': document.title,
'appIconUrl': icon,
'onCssLoaded': 'chromeLoaded()'
};
//Load the Chrome Control in the divSPChrome element of the page
var chromeNavigation = new SP.UI.Controls.Navigation('divSPChrome', options);
chromeNavigation.setVisible(true);
}
```
And properly define them in the aspx page:
```ASPX
<body style="display: none;">
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="True" />
<div id="divSPChrome"></div>
<div style="left: 50%; width: 600px; margin-left: -300px; position: absolute;">
<table>
<tr>
<td class="ms-formlabel" valign="top"><h3 class="ms-standardheader">Keywords:</h3></td>
<td class="ms-formbody" valign="top">
<div class="ms-core-form-line" style="margin-bottom: 0px;">
<input type="hidden" id="taxPickerKeywords" />
</div>
</td>
</tr>
<tr>
<td class="ms-formlabel" valign="top"><h3 class="ms-standardheader">Continent:</h3></td>
<td class="ms-formbody" valign="top">
<div class="ms-core-form-line" style="margin-bottom: 0px;">
<asp:HiddenField runat="server" ID="taxPickerContinent" />
</div>
</td>
</tr>
<tr>
<td class="ms-formlabel" valign="top"><h3 class="ms-standardheader">Country:</h3></td>
<td class="ms-formbody" valign="top">
<div class="ms-core-form-line" style="margin-bottom: 0px;">
<asp:HiddenField runat="server" ID="taxPickerCountry" />
</div>
</td>
</tr>
<tr>
<td class="ms-formlabel" valign="top"><h3 class="ms-standardheader">Region:</h3></td>
<td class="ms-formbody" valign="top">
<div class="ms-core-form-line" style="margin-bottom: 0px;">
<asp:HiddenField runat="server" ID="taxPickerRegion" />
</div>
</td>
</tr>
</table>
</div>
</form>
</body>
```
| sandhyagaddipati/PnPSamples | Components/Core.TaxonomyPicker/README.md | Markdown | apache-2.0 | 18,512 |
/**
* Implementation of Multi-User Chat (XEP-0045).
*/
package org.jivesoftware.openfire.muc.spi; | zuoyebushiwo/openfire-my-study | src/java/org/jivesoftware/openfire/muc/spi/package-info.java | Java | apache-2.0 | 99 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.gen;
import com.facebook.presto.byteCode.ByteCodeBlock;
import com.facebook.presto.byteCode.ByteCodeNode;
import com.facebook.presto.byteCode.ClassDefinition;
import com.facebook.presto.byteCode.MethodDefinition;
import com.facebook.presto.byteCode.Parameter;
import com.facebook.presto.byteCode.ParameterizedType;
import com.facebook.presto.byteCode.Scope;
import com.facebook.presto.byteCode.Variable;
import com.facebook.presto.byteCode.control.ForLoop;
import com.facebook.presto.byteCode.control.IfStatement;
import com.facebook.presto.byteCode.instruction.LabelNode;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.operator.PageProcessor;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.PageBuilder;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.relational.CallExpression;
import com.facebook.presto.sql.relational.ConstantExpression;
import com.facebook.presto.sql.relational.Expressions;
import com.facebook.presto.sql.relational.InputReferenceExpression;
import com.facebook.presto.sql.relational.RowExpression;
import com.facebook.presto.sql.relational.RowExpressionVisitor;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Primitives;
import io.airlift.slice.Slice;
import java.util.List;
import java.util.TreeSet;
import static com.facebook.presto.byteCode.Access.PUBLIC;
import static com.facebook.presto.byteCode.Access.a;
import static com.facebook.presto.byteCode.OpCode.NOP;
import static com.facebook.presto.byteCode.Parameter.arg;
import static com.facebook.presto.byteCode.ParameterizedType.type;
import static com.facebook.presto.sql.gen.ByteCodeUtils.generateWrite;
import static com.facebook.presto.sql.gen.ByteCodeUtils.loadConstant;
import static java.lang.String.format;
import static java.util.Collections.nCopies;
public class PageProcessorCompiler
implements BodyCompiler<PageProcessor>
{
private final Metadata metadata;
public PageProcessorCompiler(Metadata metadata)
{
this.metadata = metadata;
}
@Override
public void generateMethods(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, RowExpression filter, List<RowExpression> projections)
{
generateProcessMethod(classDefinition, filter, projections);
generateFilterMethod(classDefinition, callSiteBinder, filter);
for (int i = 0; i < projections.size(); i++) {
generateProjectMethod(classDefinition, callSiteBinder, "project_" + i, projections.get(i));
}
}
private void generateProcessMethod(ClassDefinition classDefinition, RowExpression filter, List<RowExpression> projections)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
Parameter start = arg("start", int.class);
Parameter end = arg("end", int.class);
Parameter pageBuilder = arg("pageBuilder", PageBuilder.class);
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "process", type(int.class), session, page, start, end, pageBuilder);
Scope scope = method.getScope();
Variable thisVariable = method.getThis();
Variable position = scope.declareVariable(int.class, "position");
method.getBody()
.comment("int position = start;")
.getVariable(start)
.putVariable(position);
List<Integer> allInputChannels = getInputChannels(Iterables.concat(projections, ImmutableList.of(filter)));
for (int channel : allInputChannels) {
Variable blockVariable = scope.declareVariable(Block.class, "block_" + channel);
method.getBody()
.comment("Block %s = page.getBlock(%s);", blockVariable.getName(), channel)
.getVariable(page)
.push(channel)
.invokeVirtual(Page.class, "getBlock", Block.class, int.class)
.putVariable(blockVariable);
}
//
// for loop loop body
//
LabelNode done = new LabelNode("done");
ByteCodeBlock loopBody = new ByteCodeBlock();
ForLoop loop = new ForLoop()
.initialize(NOP)
.condition(new ByteCodeBlock()
.comment("position < end")
.getVariable(position)
.getVariable(end)
.invokeStatic(CompilerOperations.class, "lessThan", boolean.class, int.class, int.class)
)
.update(new ByteCodeBlock()
.comment("position++")
.incrementVariable(position, (byte) 1))
.body(loopBody);
loopBody.comment("if (pageBuilder.isFull()) break;")
.getVariable(pageBuilder)
.invokeVirtual(PageBuilder.class, "isFull", boolean.class)
.ifTrueGoto(done);
// if (filter(cursor))
IfStatement filterBlock = new IfStatement();
filterBlock.condition()
.append(thisVariable)
.getVariable(session)
.append(pushBlockVariables(scope, getInputChannels(filter)))
.getVariable(position)
.invokeVirtual(classDefinition.getType(),
"filter",
type(boolean.class),
ImmutableList.<ParameterizedType>builder()
.add(type(ConnectorSession.class))
.addAll(nCopies(getInputChannels(filter).size(), type(Block.class)))
.add(type(int.class))
.build());
filterBlock.ifTrue()
.append(pageBuilder)
.invokeVirtual(PageBuilder.class, "declarePosition", void.class);
for (int projectionIndex = 0; projectionIndex < projections.size(); projectionIndex++) {
List<Integer> inputChannels = getInputChannels(projections.get(projectionIndex));
filterBlock.ifTrue()
.append(thisVariable)
.append(session)
.append(pushBlockVariables(scope, inputChannels))
.getVariable(position);
filterBlock.ifTrue()
.comment("pageBuilder.getBlockBuilder(%d)", projectionIndex)
.append(pageBuilder)
.push(projectionIndex)
.invokeVirtual(PageBuilder.class, "getBlockBuilder", BlockBuilder.class, int.class);
filterBlock.ifTrue()
.comment("project_%d(session, block_%s, position, blockBuilder)", projectionIndex, inputChannels)
.invokeVirtual(classDefinition.getType(),
"project_" + projectionIndex,
type(void.class),
ImmutableList.<ParameterizedType>builder()
.add(type(ConnectorSession.class))
.addAll(nCopies(inputChannels.size(), type(Block.class)))
.add(type(int.class))
.add(type(BlockBuilder.class))
.build());
}
loopBody.append(filterBlock);
method.getBody()
.append(loop)
.visitLabel(done)
.comment("return position;")
.getVariable(position)
.retInt();
}
private void generateFilterMethod(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, RowExpression filter)
{
Parameter session = arg("session", ConnectorSession.class);
List<Parameter> blocks = toBlockParameters(getInputChannels(filter));
Parameter position = arg("position", int.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"filter",
type(boolean.class),
ImmutableList.<Parameter>builder()
.add(session)
.addAll(blocks)
.add(position)
.build());
method.comment("Filter: %s", filter.toString());
Scope scope = method.getScope();
Variable wasNullVariable = scope.declareVariable(type(boolean.class), "wasNull");
ByteCodeExpressionVisitor visitor = new ByteCodeExpressionVisitor(
callSiteBinder,
fieldReferenceCompiler(callSiteBinder, position, wasNullVariable),
metadata.getFunctionRegistry());
ByteCodeNode body = filter.accept(visitor, scope);
LabelNode end = new LabelNode("end");
method
.getBody()
.comment("boolean wasNull = false;")
.putVariable(wasNullVariable, false)
.append(body)
.getVariable(wasNullVariable)
.ifFalseGoto(end)
.pop(boolean.class)
.push(false)
.visitLabel(end)
.retBoolean();
}
private void generateProjectMethod(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, String methodName, RowExpression projection)
{
Parameter session = arg("session", ConnectorSession.class);
List<Parameter> inputs = toBlockParameters(getInputChannels(projection));
Parameter position = arg("position", int.class);
Parameter output = arg("output", BlockBuilder.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
methodName,
type(void.class),
ImmutableList.<Parameter>builder()
.add(session)
.addAll(inputs)
.add(position)
.add(output)
.build());
method.comment("Projection: %s", projection.toString());
Scope scope = method.getScope();
Variable wasNullVariable = scope.declareVariable(type(boolean.class), "wasNull");
ByteCodeBlock body = method.getBody()
.comment("boolean wasNull = false;")
.putVariable(wasNullVariable, false);
ByteCodeExpressionVisitor visitor = new ByteCodeExpressionVisitor(callSiteBinder, fieldReferenceCompiler(callSiteBinder, position, wasNullVariable), metadata.getFunctionRegistry());
body.getVariable(output)
.comment("evaluate projection: " + projection.toString())
.append(projection.accept(visitor, scope))
.append(generateWrite(callSiteBinder, scope, wasNullVariable, projection.getType()))
.ret();
}
private static List<Integer> getInputChannels(Iterable<RowExpression> expressions)
{
TreeSet<Integer> channels = new TreeSet<>();
for (RowExpression expression : Expressions.subExpressions(expressions)) {
if (expression instanceof InputReferenceExpression) {
channels.add(((InputReferenceExpression) expression).getField());
}
}
return ImmutableList.copyOf(channels);
}
private static List<Integer> getInputChannels(RowExpression expression)
{
return getInputChannels(ImmutableList.of(expression));
}
private static List<Parameter> toBlockParameters(List<Integer> inputChannels)
{
ImmutableList.Builder<Parameter> parameters = ImmutableList.builder();
for (int channel : inputChannels) {
parameters.add(arg("block_" + channel, Block.class));
}
return parameters.build();
}
private static ByteCodeNode pushBlockVariables(Scope scope, List<Integer> inputs)
{
ByteCodeBlock block = new ByteCodeBlock();
for (int channel : inputs) {
block.append(scope.getVariable("block_" + channel));
}
return block;
}
private RowExpressionVisitor<Scope, ByteCodeNode> fieldReferenceCompiler(final CallSiteBinder callSiteBinder, final Variable positionVariable, final Variable wasNullVariable)
{
return new RowExpressionVisitor<Scope, ByteCodeNode>()
{
@Override
public ByteCodeNode visitInputReference(InputReferenceExpression node, Scope scope)
{
int field = node.getField();
Type type = node.getType();
Variable block = scope.getVariable("block_" + field);
Class<?> javaType = type.getJavaType();
if (!javaType.isPrimitive() && javaType != Slice.class) {
javaType = Object.class;
}
IfStatement ifStatement = new IfStatement();
ifStatement.condition()
.setDescription(format("block_%d.get%s()", field, type))
.append(block)
.getVariable(positionVariable)
.invokeInterface(Block.class, "isNull", boolean.class, int.class);
ifStatement.ifTrue()
.putVariable(wasNullVariable, true)
.pushJavaDefault(javaType);
String methodName = "get" + Primitives.wrap(javaType).getSimpleName();
ifStatement.ifFalse()
.append(loadConstant(callSiteBinder.bind(type, Type.class)))
.append(block)
.getVariable(positionVariable)
.invokeInterface(Type.class, methodName, javaType, Block.class, int.class);
return ifStatement;
}
@Override
public ByteCodeNode visitCall(CallExpression call, Scope scope)
{
throw new UnsupportedOperationException("not yet implemented");
}
@Override
public ByteCodeNode visitConstant(ConstantExpression literal, Scope scope)
{
throw new UnsupportedOperationException("not yet implemented");
}
};
}
}
| deciament/presto | presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java | Java | apache-2.0 | 15,098 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.inspections.quickfix;
import com.intellij.codeInsight.intention.LowPriorityAction;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ex.InspectionProfileModifiableModelKt;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.QualifiedName;
import com.jetbrains.python.inspections.unresolvedReference.PyUnresolvedReferencesInspection;
import org.jetbrains.annotations.NotNull;
/**
* @author yole
*/
public class AddIgnoredIdentifierQuickFix implements LocalQuickFix, LowPriorityAction {
public static final String END_WILDCARD = ".*";
@NotNull private final QualifiedName myIdentifier;
private final boolean myIgnoreAllAttributes;
public AddIgnoredIdentifierQuickFix(@NotNull QualifiedName identifier, boolean ignoreAllAttributes) {
myIdentifier = identifier;
myIgnoreAllAttributes = ignoreAllAttributes;
}
@NotNull
@Override
public String getName() {
if (myIgnoreAllAttributes) {
return "Mark all unresolved attributes of '" + myIdentifier + "' as ignored";
}
else {
return "Ignore unresolved reference '" + myIdentifier + "'";
}
}
@NotNull
@Override
public String getFamilyName() {
return "Ignore unresolved reference";
}
@Override
public boolean startInWriteAction() {
return false;
}
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
final PsiElement context = descriptor.getPsiElement();
InspectionProfileModifiableModelKt.modifyAndCommitProjectProfile(project, model -> {
PyUnresolvedReferencesInspection inspection =
(PyUnresolvedReferencesInspection)model.getUnwrappedTool(PyUnresolvedReferencesInspection.class.getSimpleName(), context);
String name = myIdentifier.toString();
if (myIgnoreAllAttributes) {
name += END_WILDCARD;
}
assert inspection != null;
if (!inspection.ignoredIdentifiers.contains(name)) {
inspection.ignoredIdentifiers.add(name);
}
});
}
}
| jk1/intellij-community | python/src/com/jetbrains/python/inspections/quickfix/AddIgnoredIdentifierQuickFix.java | Java | apache-2.0 | 2,763 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.internal.io
import java.text.NumberFormat
import java.util.{Date, Locale}
import scala.reflect.ClassTag
import org.apache.hadoop.conf.{Configurable, Configuration}
import org.apache.hadoop.fs.FileSystem
import org.apache.hadoop.mapred._
import org.apache.hadoop.mapreduce.{JobContext => NewJobContext,
OutputFormat => NewOutputFormat, RecordWriter => NewRecordWriter,
TaskAttemptContext => NewTaskAttemptContext, TaskAttemptID => NewTaskAttemptID, TaskType}
import org.apache.hadoop.mapreduce.task.{TaskAttemptContextImpl => NewTaskAttemptContextImpl}
import org.apache.spark.{SerializableWritable, SparkConf, SparkException, TaskContext}
import org.apache.spark.deploy.SparkHadoopUtil
import org.apache.spark.internal.Logging
import org.apache.spark.internal.io.FileCommitProtocol.TaskCommitMessage
import org.apache.spark.rdd.{HadoopRDD, RDD}
import org.apache.spark.util.{SerializableConfiguration, SerializableJobConf, Utils}
/**
* A helper object that saves an RDD using a Hadoop OutputFormat.
*/
private[spark]
object SparkHadoopWriter extends Logging {
import SparkHadoopWriterUtils._
/**
* Basic work flow of this command is:
* 1. Driver side setup, prepare the data source and hadoop configuration for the write job to
* be issued.
* 2. Issues a write job consists of one or more executor side tasks, each of which writes all
* rows within an RDD partition.
* 3. If no exception is thrown in a task, commits that task, otherwise aborts that task; If any
* exception is thrown during task commitment, also aborts that task.
* 4. If all tasks are committed, commit the job, otherwise aborts the job; If any exception is
* thrown during job commitment, also aborts the job.
*/
def write[K, V: ClassTag](
rdd: RDD[(K, V)],
config: HadoopWriteConfigUtil[K, V]): Unit = {
// Extract context and configuration from RDD.
val sparkContext = rdd.context
val stageId = rdd.id
// Set up a job.
val jobTrackerId = createJobTrackerID(new Date())
val jobContext = config.createJobContext(jobTrackerId, stageId)
config.initOutputFormat(jobContext)
// Assert the output format/key/value class is set in JobConf.
config.assertConf(jobContext, rdd.conf)
val committer = config.createCommitter(stageId)
committer.setupJob(jobContext)
// Try to write all RDD partitions as a Hadoop OutputFormat.
try {
val ret = sparkContext.runJob(rdd, (context: TaskContext, iter: Iterator[(K, V)]) => {
executeTask(
context = context,
config = config,
jobTrackerId = jobTrackerId,
sparkStageId = context.stageId,
sparkPartitionId = context.partitionId,
sparkAttemptNumber = context.attemptNumber,
committer = committer,
iterator = iter)
})
committer.commitJob(jobContext, ret)
logInfo(s"Job ${jobContext.getJobID} committed.")
} catch {
case cause: Throwable =>
logError(s"Aborting job ${jobContext.getJobID}.", cause)
committer.abortJob(jobContext)
throw new SparkException("Job aborted.", cause)
}
}
/** Write a RDD partition out in a single Spark task. */
private def executeTask[K, V: ClassTag](
context: TaskContext,
config: HadoopWriteConfigUtil[K, V],
jobTrackerId: String,
sparkStageId: Int,
sparkPartitionId: Int,
sparkAttemptNumber: Int,
committer: FileCommitProtocol,
iterator: Iterator[(K, V)]): TaskCommitMessage = {
// Set up a task.
val taskContext = config.createTaskAttemptContext(
jobTrackerId, sparkStageId, sparkPartitionId, sparkAttemptNumber)
committer.setupTask(taskContext)
val (outputMetrics, callback) = initHadoopOutputMetrics(context)
// Initiate the writer.
config.initWriter(taskContext, sparkPartitionId)
var recordsWritten = 0L
// Write all rows in RDD partition.
try {
val ret = Utils.tryWithSafeFinallyAndFailureCallbacks {
while (iterator.hasNext) {
val pair = iterator.next()
config.write(pair)
// Update bytes written metric every few records
maybeUpdateOutputMetrics(outputMetrics, callback, recordsWritten)
recordsWritten += 1
}
config.closeWriter(taskContext)
committer.commitTask(taskContext)
}(catchBlock = {
// If there is an error, release resource and then abort the task.
try {
config.closeWriter(taskContext)
} finally {
committer.abortTask(taskContext)
logError(s"Task ${taskContext.getTaskAttemptID} aborted.")
}
})
outputMetrics.setBytesWritten(callback())
outputMetrics.setRecordsWritten(recordsWritten)
ret
} catch {
case t: Throwable =>
throw new SparkException("Task failed while writing rows", t)
}
}
}
/**
* A helper class that reads JobConf from older mapred API, creates output Format/Committer/Writer.
*/
private[spark]
class HadoopMapRedWriteConfigUtil[K, V: ClassTag](conf: SerializableJobConf)
extends HadoopWriteConfigUtil[K, V] with Logging {
private var outputFormat: Class[_ <: OutputFormat[K, V]] = null
private var writer: RecordWriter[K, V] = null
private def getConf: JobConf = conf.value
// --------------------------------------------------------------------------
// Create JobContext/TaskAttemptContext
// --------------------------------------------------------------------------
override def createJobContext(jobTrackerId: String, jobId: Int): NewJobContext = {
val jobAttemptId = new SerializableWritable(new JobID(jobTrackerId, jobId))
new JobContextImpl(getConf, jobAttemptId.value)
}
override def createTaskAttemptContext(
jobTrackerId: String,
jobId: Int,
splitId: Int,
taskAttemptId: Int): NewTaskAttemptContext = {
// Update JobConf.
HadoopRDD.addLocalConfiguration(jobTrackerId, jobId, splitId, taskAttemptId, conf.value)
// Create taskContext.
val attemptId = new TaskAttemptID(jobTrackerId, jobId, TaskType.MAP, splitId, taskAttemptId)
new TaskAttemptContextImpl(getConf, attemptId)
}
// --------------------------------------------------------------------------
// Create committer
// --------------------------------------------------------------------------
override def createCommitter(jobId: Int): HadoopMapReduceCommitProtocol = {
// Update JobConf.
HadoopRDD.addLocalConfiguration("", 0, 0, 0, getConf)
// Create commit protocol.
FileCommitProtocol.instantiate(
className = classOf[HadoopMapRedCommitProtocol].getName,
jobId = jobId.toString,
outputPath = getConf.get("mapred.output.dir")
).asInstanceOf[HadoopMapReduceCommitProtocol]
}
// --------------------------------------------------------------------------
// Create writer
// --------------------------------------------------------------------------
override def initWriter(taskContext: NewTaskAttemptContext, splitId: Int): Unit = {
val numfmt = NumberFormat.getInstance(Locale.US)
numfmt.setMinimumIntegerDigits(5)
numfmt.setGroupingUsed(false)
val outputName = "part-" + numfmt.format(splitId)
val path = FileOutputFormat.getOutputPath(getConf)
val fs: FileSystem = {
if (path != null) {
path.getFileSystem(getConf)
} else {
FileSystem.get(getConf)
}
}
writer = getConf.getOutputFormat
.getRecordWriter(fs, getConf, outputName, Reporter.NULL)
.asInstanceOf[RecordWriter[K, V]]
require(writer != null, "Unable to obtain RecordWriter")
}
override def write(pair: (K, V)): Unit = {
require(writer != null, "Must call createWriter before write.")
writer.write(pair._1, pair._2)
}
override def closeWriter(taskContext: NewTaskAttemptContext): Unit = {
if (writer != null) {
writer.close(Reporter.NULL)
}
}
// --------------------------------------------------------------------------
// Create OutputFormat
// --------------------------------------------------------------------------
override def initOutputFormat(jobContext: NewJobContext): Unit = {
if (outputFormat == null) {
outputFormat = getConf.getOutputFormat.getClass
.asInstanceOf[Class[_ <: OutputFormat[K, V]]]
}
}
private def getOutputFormat(): OutputFormat[K, V] = {
require(outputFormat != null, "Must call initOutputFormat first.")
outputFormat.newInstance()
}
// --------------------------------------------------------------------------
// Verify hadoop config
// --------------------------------------------------------------------------
override def assertConf(jobContext: NewJobContext, conf: SparkConf): Unit = {
val outputFormatInstance = getOutputFormat()
val keyClass = getConf.getOutputKeyClass
val valueClass = getConf.getOutputValueClass
if (outputFormatInstance == null) {
throw new SparkException("Output format class not set")
}
if (keyClass == null) {
throw new SparkException("Output key class not set")
}
if (valueClass == null) {
throw new SparkException("Output value class not set")
}
SparkHadoopUtil.get.addCredentials(getConf)
logDebug("Saving as hadoop file of type (" + keyClass.getSimpleName + ", " +
valueClass.getSimpleName + ")")
if (SparkHadoopWriterUtils.isOutputSpecValidationEnabled(conf)) {
// FileOutputFormat ignores the filesystem parameter
val ignoredFs = FileSystem.get(getConf)
getOutputFormat().checkOutputSpecs(ignoredFs, getConf)
}
}
}
/**
* A helper class that reads Configuration from newer mapreduce API, creates output
* Format/Committer/Writer.
*/
private[spark]
class HadoopMapReduceWriteConfigUtil[K, V: ClassTag](conf: SerializableConfiguration)
extends HadoopWriteConfigUtil[K, V] with Logging {
private var outputFormat: Class[_ <: NewOutputFormat[K, V]] = null
private var writer: NewRecordWriter[K, V] = null
private def getConf: Configuration = conf.value
// --------------------------------------------------------------------------
// Create JobContext/TaskAttemptContext
// --------------------------------------------------------------------------
override def createJobContext(jobTrackerId: String, jobId: Int): NewJobContext = {
val jobAttemptId = new NewTaskAttemptID(jobTrackerId, jobId, TaskType.MAP, 0, 0)
new NewTaskAttemptContextImpl(getConf, jobAttemptId)
}
override def createTaskAttemptContext(
jobTrackerId: String,
jobId: Int,
splitId: Int,
taskAttemptId: Int): NewTaskAttemptContext = {
val attemptId = new NewTaskAttemptID(
jobTrackerId, jobId, TaskType.REDUCE, splitId, taskAttemptId)
new NewTaskAttemptContextImpl(getConf, attemptId)
}
// --------------------------------------------------------------------------
// Create committer
// --------------------------------------------------------------------------
override def createCommitter(jobId: Int): HadoopMapReduceCommitProtocol = {
FileCommitProtocol.instantiate(
className = classOf[HadoopMapReduceCommitProtocol].getName,
jobId = jobId.toString,
outputPath = getConf.get("mapreduce.output.fileoutputformat.outputdir")
).asInstanceOf[HadoopMapReduceCommitProtocol]
}
// --------------------------------------------------------------------------
// Create writer
// --------------------------------------------------------------------------
override def initWriter(taskContext: NewTaskAttemptContext, splitId: Int): Unit = {
val taskFormat = getOutputFormat()
// If OutputFormat is Configurable, we should set conf to it.
taskFormat match {
case c: Configurable => c.setConf(getConf)
case _ => ()
}
writer = taskFormat.getRecordWriter(taskContext)
.asInstanceOf[NewRecordWriter[K, V]]
require(writer != null, "Unable to obtain RecordWriter")
}
override def write(pair: (K, V)): Unit = {
require(writer != null, "Must call createWriter before write.")
writer.write(pair._1, pair._2)
}
override def closeWriter(taskContext: NewTaskAttemptContext): Unit = {
if (writer != null) {
writer.close(taskContext)
writer = null
} else {
logWarning("Writer has been closed.")
}
}
// --------------------------------------------------------------------------
// Create OutputFormat
// --------------------------------------------------------------------------
override def initOutputFormat(jobContext: NewJobContext): Unit = {
if (outputFormat == null) {
outputFormat = jobContext.getOutputFormatClass
.asInstanceOf[Class[_ <: NewOutputFormat[K, V]]]
}
}
private def getOutputFormat(): NewOutputFormat[K, V] = {
require(outputFormat != null, "Must call initOutputFormat first.")
outputFormat.newInstance()
}
// --------------------------------------------------------------------------
// Verify hadoop config
// --------------------------------------------------------------------------
override def assertConf(jobContext: NewJobContext, conf: SparkConf): Unit = {
if (SparkHadoopWriterUtils.isOutputSpecValidationEnabled(conf)) {
getOutputFormat().checkOutputSpecs(jobContext)
}
}
}
| akopich/spark | core/src/main/scala/org/apache/spark/internal/io/SparkHadoopWriter.scala | Scala | apache-2.0 | 14,219 |
module Vmdb
module Initializer
def self.init
_log.info "- Program Name: #{$PROGRAM_NAME}, PID: #{Process.pid}, ENV['MIQ_GUID']: #{ENV['MIQ_GUID']}, ENV['EVMSERVER']: #{ENV['EVMSERVER']}"
# When these classes are deserialized in ActiveRecord (e.g. EmsEvent, MiqQueue), they need to be preloaded
require 'VMwareWebService/VimTypes'
# UiWorker called in Development Mode
# * command line(rails server)
# * debugger
if defined?(Rails::Server)
# preload_for_worker_role depends on seeding, principally MiqDatabase
EvmDatabase.seed_primordial
MiqUiWorker.preload_for_worker_role
MiqServer.my_server.starting_server_record
MiqServer.my_server.update_attributes(:status => "started")
end
# Rails console needs session store configured
if defined?(Rails::Console)
MiqUiWorker.preload_for_console
end
end
end
end
| NaNi-Z/manageiq | lib/vmdb/initializer.rb | Ruby | apache-2.0 | 937 |
from fabric.api import *
import fabric.contrib.project as project
import os
import shutil
import sys
import SocketServer
from pelican.server import ComplexHTTPRequestHandler
# Local path configuration (can be absolute or relative to fabfile)
env.deploy_path = 'output'
DEPLOY_PATH = env.deploy_path
# Remote server configuration
production = 'root@localhost:22'
dest_path = '/var/www'
# Rackspace Cloud Files configuration settings
env.cloudfiles_username = 'my_rackspace_username'
env.cloudfiles_api_key = 'my_rackspace_api_key'
env.cloudfiles_container = 'my_cloudfiles_container'
# Github Pages configuration
env.github_pages_branch = "master"
# Port for `serve`
PORT = 8000
def clean():
"""Remove generated files"""
if os.path.isdir(DEPLOY_PATH):
shutil.rmtree(DEPLOY_PATH)
os.makedirs(DEPLOY_PATH)
def build():
"""Build local version of site"""
local('pelican -s pelicanconf.py')
def rebuild():
"""`build` with the delete switch"""
local('pelican -d -s pelicanconf.py')
def regenerate():
"""Automatically regenerate site upon file modification"""
local('pelican -r -s pelicanconf.py')
def serve():
"""Serve site at http://localhost:8000/"""
os.chdir(env.deploy_path)
class AddressReuseTCPServer(SocketServer.TCPServer):
allow_reuse_address = True
server = AddressReuseTCPServer(('', PORT), ComplexHTTPRequestHandler)
sys.stderr.write('Serving on port {0} ...\n'.format(PORT))
server.serve_forever()
def reserve():
"""`build`, then `serve`"""
build()
serve()
def preview():
"""Build production version of site"""
local('pelican -s publishconf.py')
def cf_upload():
"""Publish to Rackspace Cloud Files"""
rebuild()
with lcd(DEPLOY_PATH):
local('swift -v -A https://auth.api.rackspacecloud.com/v1.0 '
'-U {cloudfiles_username} '
'-K {cloudfiles_api_key} '
'upload -c {cloudfiles_container} .'.format(**env))
@hosts(production)
def publish():
"""Publish to production via rsync"""
local('pelican -s publishconf.py')
project.rsync_project(
remote_dir=dest_path,
exclude=".DS_Store",
local_dir=DEPLOY_PATH.rstrip('/') + '/',
delete=True,
extra_opts='-c',
)
def gh_pages():
"""Publish to GitHub Pages"""
rebuild()
local("ghp-import -b {github_pages_branch} {deploy_path} -p".format(**env))
| oscarvarto/oscarvarto.github.io | fabfile.py | Python | apache-2.0 | 2,437 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.jvm.actions;
public interface CreateConstructorRequest extends CreateExecutableRequest {
}
| smmribeiro/intellij-community | java/java-analysis-api/src/com/intellij/lang/jvm/actions/CreateConstructorRequest.java | Java | apache-2.0 | 259 |
package com.baidu.disconf.web.service.user.vo;
public class VisitorVo {
private Long id;
private String name;
private String role;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "VisitorVo [id=" + id + ", name=" + name + ", role=" + role + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((role == null) ? 0 : role.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
VisitorVo other = (VisitorVo) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (role == null) {
if (other.role != null) {
return false;
}
} else if (!role.equals(other.role)) {
return false;
}
return true;
}
}
| markyao/disconf | disconf-web/src/main/java/com/baidu/disconf/web/service/user/vo/VisitorVo.java | Java | apache-2.0 | 1,901 |
import os.path
import sys
import re
import warnings
import cx_Oracle
from django.db import connection, models
from django.db.backends.util import truncate_name
from django.core.management.color import no_style
from django.db.models.fields import NOT_PROVIDED
from django.db.utils import DatabaseError
# In revision r16016 function get_sequence_name has been transformed into
# method of DatabaseOperations class. To make code backward-compatible we
# need to handle both situations.
try:
from django.db.backends.oracle.base import get_sequence_name\
as original_get_sequence_name
except ImportError:
original_get_sequence_name = None
from south.db import generic
warnings.warn("! WARNING: South's Oracle support is still alpha. "
"Be wary of possible bugs.")
class DatabaseOperations(generic.DatabaseOperations):
"""
Oracle implementation of database operations.
"""
backend_name = 'oracle'
alter_string_set_type = 'ALTER TABLE %(table_name)s MODIFY %(column)s %(type)s %(nullity)s;'
alter_string_set_default = 'ALTER TABLE %(table_name)s MODIFY %(column)s DEFAULT %(default)s;'
add_column_string = 'ALTER TABLE %s ADD %s;'
delete_column_string = 'ALTER TABLE %s DROP COLUMN %s;'
add_constraint_string = 'ALTER TABLE %(table_name)s ADD CONSTRAINT %(constraint)s %(clause)s'
allows_combined_alters = False
has_booleans = False
constraints_dict = {
'P': 'PRIMARY KEY',
'U': 'UNIQUE',
'C': 'CHECK',
'R': 'FOREIGN KEY'
}
def get_sequence_name(self, table_name):
if original_get_sequence_name is None:
return self._get_connection().ops._get_sequence_name(table_name)
else:
return original_get_sequence_name(table_name)
#TODO: This will cause very obscure bugs if anyone uses a column name or string value
# that looks like a column definition (with 'CHECK', 'DEFAULT' and/or 'NULL' in it)
# e.g. "CHECK MATE" varchar(10) DEFAULT 'NULL'
def adj_column_sql(self, col):
# Syntax fixes -- Oracle is picky about clause order
col = re.sub('(?P<constr>CHECK \(.*\))(?P<any>.*)(?P<default>DEFAULT \d+)',
lambda mo: '%s %s%s'%(mo.group('default'), mo.group('constr'), mo.group('any')), col) #syntax fix for boolean/integer field only
col = re.sub('(?P<not_null>(NOT )?NULL) (?P<misc>(.* )?)(?P<default>DEFAULT.+)',
lambda mo: '%s %s %s'%(mo.group('default'),mo.group('not_null'),mo.group('misc') or ''), col) #fix order of NULL/NOT NULL and DEFAULT
return col
def check_meta(self, table_name):
return table_name in [ m._meta.db_table for m in models.get_models() ] #caching provided by Django
def normalize_name(self, name):
"""
Get the properly shortened and uppercased identifier as returned by quote_name(), but without the actual quotes.
"""
nn = self.quote_name(name)
if nn[0] == '"' and nn[-1] == '"':
nn = nn[1:-1]
return nn
@generic.invalidate_table_constraints
def create_table(self, table_name, fields):
qn = self.quote_name(table_name)
columns = []
autoinc_sql = ''
for field_name, field in fields:
col = self.column_sql(table_name, field_name, field)
if not col:
continue
col = self.adj_column_sql(col)
columns.append(col)
if isinstance(field, models.AutoField):
autoinc_sql = connection.ops.autoinc_sql(table_name, field_name)
sql = 'CREATE TABLE %s (%s);' % (qn, ', '.join([col for col in columns]))
self.execute(sql)
if autoinc_sql:
self.execute(autoinc_sql[0])
self.execute(autoinc_sql[1])
@generic.invalidate_table_constraints
def delete_table(self, table_name, cascade=True):
qn = self.quote_name(table_name)
# Note: PURGE is not valid syntax for Oracle 9i (it was added in 10)
if cascade:
self.execute('DROP TABLE %s CASCADE CONSTRAINTS;' % qn)
else:
self.execute('DROP TABLE %s;' % qn)
# If the table has an AutoField a sequence was created.
sequence_sql = """
DECLARE
i INTEGER;
BEGIN
SELECT COUNT(*) INTO i FROM USER_CATALOG
WHERE TABLE_NAME = '%(sq_name)s' AND TABLE_TYPE = 'SEQUENCE';
IF i = 1 THEN
EXECUTE IMMEDIATE 'DROP SEQUENCE "%(sq_name)s"';
END IF;
END;
/""" % {'sq_name': self.get_sequence_name(table_name)}
self.execute(sequence_sql)
@generic.invalidate_table_constraints
def alter_column(self, table_name, name, field, explicit_name=True):
if self.dry_run:
if self.debug:
print ' - no dry run output for alter_column() due to dynamic DDL, sorry'
return
qn = self.quote_name(table_name)
# hook for the field to do any resolution prior to it's attributes being queried
if hasattr(field, 'south_init'):
field.south_init()
field = self._field_sanity(field)
# Add _id or whatever if we need to
field.set_attributes_from_name(name)
if not explicit_name:
name = field.column
qn_col = self.quote_name(name)
# First, change the type
# This will actually also add any CHECK constraints needed,
# since e.g. 'type' for a BooleanField is 'NUMBER(1) CHECK (%(qn_column)s IN (0,1))'
params = {
'table_name':qn,
'column': qn_col,
'type': self._db_type_for_alter_column(field),
'nullity': 'NOT NULL',
'default': 'NULL'
}
if field.null:
params['nullity'] = 'NULL'
if not field.null and field.has_default():
params['default'] = self._default_value_workaround(field.get_default())
sql_templates = [
(self.alter_string_set_type, params),
(self.alter_string_set_default, params.copy()),
]
# drop CHECK constraints. Make sure this is executed before the ALTER TABLE statements
# generated above, since those statements recreate the constraints we delete here.
check_constraints = self._constraints_affecting_columns(table_name, [name], "CHECK")
for constraint in check_constraints:
self.execute(self.delete_check_sql % {
'table': self.quote_name(table_name),
'constraint': self.quote_name(constraint),
})
for sql_template, params in sql_templates:
try:
self.execute(sql_template % params)
except DatabaseError, exc:
description = str(exc)
# Oracle complains if a column is already NULL/NOT NULL
if 'ORA-01442' in description or 'ORA-01451' in description:
# so we just drop NULL/NOT NULL part from target sql and retry
params['nullity'] = ''
sql = sql_template % params
self.execute(sql)
# Oracle also has issues if we try to change a regular column
# to a LOB or vice versa (also REF, object, VARRAY or nested
# table, but these don't come up much in Django apps)
elif 'ORA-22858' in description or 'ORA-22859' in description:
self._alter_column_lob_workaround(table_name, name, field)
else:
raise
def _alter_column_lob_workaround(self, table_name, name, field):
"""
Oracle refuses to change a column type from/to LOB to/from a regular
column. In Django, this shows up when the field is changed from/to
a TextField.
What we need to do instead is:
- Rename the original column
- Add the desired field as new
- Update the table to transfer values from old to new
- Drop old column
"""
renamed = self._generate_temp_name(name)
self.rename_column(table_name, name, renamed)
self.add_column(table_name, name, field, keep_default=False)
self.execute("UPDATE %s set %s=%s" % (
self.quote_name(table_name),
self.quote_name(name),
self.quote_name(renamed),
))
self.delete_column(table_name, renamed)
def _generate_temp_name(self, for_name):
suffix = hex(hash(for_name)).upper()[1:]
return self.normalize_name(for_name + "_" + suffix)
@generic.copy_column_constraints #TODO: Appears to be nulled by the delete decorator below...
@generic.delete_column_constraints
def rename_column(self, table_name, old, new):
if old == new:
# Short-circuit out
return []
self.execute('ALTER TABLE %s RENAME COLUMN %s TO %s;' % (
self.quote_name(table_name),
self.quote_name(old),
self.quote_name(new),
))
@generic.invalidate_table_constraints
def add_column(self, table_name, name, field, keep_default=True):
sql = self.column_sql(table_name, name, field)
sql = self.adj_column_sql(sql)
if sql:
params = (
self.quote_name(table_name),
sql
)
sql = self.add_column_string % params
self.execute(sql)
# Now, drop the default if we need to
if not keep_default and field.default is not None:
field.default = NOT_PROVIDED
self.alter_column(table_name, name, field, explicit_name=False)
def delete_column(self, table_name, name):
return super(DatabaseOperations, self).delete_column(self.quote_name(table_name), name)
def lookup_constraint(self, db_name, table_name, column_name=None):
if column_name:
# Column names in the constraint cache come from the database,
# make sure we use the properly shortened/uppercased version
# for lookup.
column_name = self.normalize_name(column_name)
return super(DatabaseOperations, self).lookup_constraint(db_name, table_name, column_name)
def _constraints_affecting_columns(self, table_name, columns, type="UNIQUE"):
if columns:
columns = [self.normalize_name(c) for c in columns]
return super(DatabaseOperations, self)._constraints_affecting_columns(table_name, columns, type)
def _field_sanity(self, field):
"""
This particular override stops us sending DEFAULTs for BooleanField.
"""
if isinstance(field, models.BooleanField) and field.has_default():
field.default = int(field.to_python(field.get_default()))
return field
def _default_value_workaround(self, value):
from datetime import date,time,datetime
if isinstance(value, (date,time,datetime)):
return "'%s'" % value
else:
return super(DatabaseOperations, self)._default_value_workaround(value)
def _fill_constraint_cache(self, db_name, table_name):
self._constraint_cache.setdefault(db_name, {})
self._constraint_cache[db_name][table_name] = {}
rows = self.execute("""
SELECT user_cons_columns.constraint_name,
user_cons_columns.column_name,
user_constraints.constraint_type
FROM user_constraints
JOIN user_cons_columns ON
user_constraints.table_name = user_cons_columns.table_name AND
user_constraints.constraint_name = user_cons_columns.constraint_name
WHERE user_constraints.table_name = '%s'
""" % self.normalize_name(table_name))
for constraint, column, kind in rows:
self._constraint_cache[db_name][table_name].setdefault(column, set())
self._constraint_cache[db_name][table_name][column].add((self.constraints_dict[kind], constraint))
return
| edisonlz/fruit | web_project/base/site-packages/south/db/oracle.py | Python | apache-2.0 | 12,431 |
package org.opencv.samples.puzzle15;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.core.Point;
import org.opencv.imgproc.Imgproc;
import android.util.Log;
/**
* This class is a controller for puzzle game.
* It converts the image from Camera into the shuffled image
*/
public class Puzzle15Processor {
private static final int GRID_SIZE = 4;
private static final int GRID_AREA = GRID_SIZE * GRID_SIZE;
private static final int GRID_EMPTY_INDEX = GRID_AREA - 1;
private static final String TAG = "Puzzle15Processor";
private static final Scalar GRID_EMPTY_COLOR = new Scalar(0x33, 0x33, 0x33, 0xFF);
private int[] mIndexes;
private int[] mTextWidths;
private int[] mTextHeights;
private Mat mRgba15;
private Mat[] mCells15;
private boolean mShowTileNumbers = true;
public Puzzle15Processor() {
mTextWidths = new int[GRID_AREA];
mTextHeights = new int[GRID_AREA];
mIndexes = new int [GRID_AREA];
for (int i = 0; i < GRID_AREA; i++)
mIndexes[i] = i;
}
/* this method is intended to make processor prepared for a new game */
public synchronized void prepareNewGame() {
do {
shuffle(mIndexes);
} while (!isPuzzleSolvable());
}
/* This method is to make the processor know the size of the frames that
* will be delivered via puzzleFrame.
* If the frames will be different size - then the result is unpredictable
*/
public synchronized void prepareGameSize(int width, int height) {
mRgba15 = new Mat(height, width, CvType.CV_8UC4);
mCells15 = new Mat[GRID_AREA];
for (int i = 0; i < GRID_SIZE; i++) {
for (int j = 0; j < GRID_SIZE; j++) {
int k = i * GRID_SIZE + j;
mCells15[k] = mRgba15.submat(i * height / GRID_SIZE, (i + 1) * height / GRID_SIZE, j * width / GRID_SIZE, (j + 1) * width / GRID_SIZE);
}
}
for (int i = 0; i < GRID_AREA; i++) {
Size s = Imgproc.getTextSize(Integer.toString(i + 1), 3/* CV_FONT_HERSHEY_COMPLEX */, 1, 2, null);
mTextHeights[i] = (int) s.height;
mTextWidths[i] = (int) s.width;
}
}
/* this method to be called from the outside. it processes the frame and shuffles
* the tiles as specified by mIndexes array
*/
public synchronized Mat puzzleFrame(Mat inputPicture) {
Mat[] cells = new Mat[GRID_AREA];
int rows = inputPicture.rows();
int cols = inputPicture.cols();
rows = rows - rows%4;
cols = cols - cols%4;
for (int i = 0; i < GRID_SIZE; i++) {
for (int j = 0; j < GRID_SIZE; j++) {
int k = i * GRID_SIZE + j;
cells[k] = inputPicture.submat(i * inputPicture.rows() / GRID_SIZE, (i + 1) * inputPicture.rows() / GRID_SIZE, j * inputPicture.cols()/ GRID_SIZE, (j + 1) * inputPicture.cols() / GRID_SIZE);
}
}
rows = rows - rows%4;
cols = cols - cols%4;
// copy shuffled tiles
for (int i = 0; i < GRID_AREA; i++) {
int idx = mIndexes[i];
if (idx == GRID_EMPTY_INDEX)
mCells15[i].setTo(GRID_EMPTY_COLOR);
else {
cells[idx].copyTo(mCells15[i]);
if (mShowTileNumbers) {
Imgproc.putText(mCells15[i], Integer.toString(1 + idx), new Point((cols / GRID_SIZE - mTextWidths[idx]) / 2,
(rows / GRID_SIZE + mTextHeights[idx]) / 2), 3/* CV_FONT_HERSHEY_COMPLEX */, 1, new Scalar(255, 0, 0, 255), 2);
}
}
}
for (int i = 0; i < GRID_AREA; i++)
cells[i].release();
drawGrid(cols, rows, mRgba15);
return mRgba15;
}
public void toggleTileNumbers() {
mShowTileNumbers = !mShowTileNumbers;
}
public void deliverTouchEvent(int x, int y) {
int rows = mRgba15.rows();
int cols = mRgba15.cols();
int row = (int) Math.floor(y * GRID_SIZE / rows);
int col = (int) Math.floor(x * GRID_SIZE / cols);
if (row < 0 || row >= GRID_SIZE || col < 0 || col >= GRID_SIZE) {
Log.e(TAG, "It is not expected to get touch event outside of picture");
return ;
}
int idx = row * GRID_SIZE + col;
int idxtoswap = -1;
// left
if (idxtoswap < 0 && col > 0)
if (mIndexes[idx - 1] == GRID_EMPTY_INDEX)
idxtoswap = idx - 1;
// right
if (idxtoswap < 0 && col < GRID_SIZE - 1)
if (mIndexes[idx + 1] == GRID_EMPTY_INDEX)
idxtoswap = idx + 1;
// top
if (idxtoswap < 0 && row > 0)
if (mIndexes[idx - GRID_SIZE] == GRID_EMPTY_INDEX)
idxtoswap = idx - GRID_SIZE;
// bottom
if (idxtoswap < 0 && row < GRID_SIZE - 1)
if (mIndexes[idx + GRID_SIZE] == GRID_EMPTY_INDEX)
idxtoswap = idx + GRID_SIZE;
// swap
if (idxtoswap >= 0) {
synchronized (this) {
int touched = mIndexes[idx];
mIndexes[idx] = mIndexes[idxtoswap];
mIndexes[idxtoswap] = touched;
}
}
}
private void drawGrid(int cols, int rows, Mat drawMat) {
for (int i = 1; i < GRID_SIZE; i++) {
Imgproc.line(drawMat, new Point(0, i * rows / GRID_SIZE), new Point(cols, i * rows / GRID_SIZE), new Scalar(0, 255, 0, 255), 3);
Imgproc.line(drawMat, new Point(i * cols / GRID_SIZE, 0), new Point(i * cols / GRID_SIZE, rows), new Scalar(0, 255, 0, 255), 3);
}
}
private static void shuffle(int[] array) {
for (int i = array.length; i > 1; i--) {
int temp = array[i - 1];
int randIx = (int) (Math.random() * i);
array[i - 1] = array[randIx];
array[randIx] = temp;
}
}
private boolean isPuzzleSolvable() {
int sum = 0;
for (int i = 0; i < GRID_AREA; i++) {
if (mIndexes[i] == GRID_EMPTY_INDEX)
sum += (i / GRID_SIZE) + 1;
else {
int smaller = 0;
for (int j = i + 1; j < GRID_AREA; j++) {
if (mIndexes[j] < mIndexes[i])
smaller++;
}
sum += smaller;
}
}
return sum % 2 == 0;
}
}
| apavlenko/opencv | samples/android/15-puzzle/src/org/opencv/samples/puzzle15/Puzzle15Processor.java | Java | bsd-3-clause | 6,624 |
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// ViEPerformanceMonitor is used to check the current CPU usage and triggers a
// callback when getting over a specified threshold.
#ifndef WEBRTC_VIDEO_ENGINE_VIE_PERFORMANCE_MONITOR_H_
#define WEBRTC_VIDEO_ENGINE_VIE_PERFORMANCE_MONITOR_H_
#include "system_wrappers/interface/scoped_ptr.h"
#include "typedefs.h" // NOLINT
#include "video_engine/vie_defines.h"
namespace webrtc {
class CpuWrapper;
class CriticalSectionWrapper;
class EventWrapper;
class ThreadWrapper;
class ViEBaseObserver;
class ViEPerformanceMonitor {
public:
explicit ViEPerformanceMonitor(int engine_id);
~ViEPerformanceMonitor();
int Init(ViEBaseObserver* vie_base_observer);
void Terminate();
bool ViEBaseObserverRegistered();
protected:
static bool ViEMonitorThreadFunction(void* obj);
bool ViEMonitorProcess();
private:
const int engine_id_;
// TODO(mfldoman) Make this one scoped_ptr.
CriticalSectionWrapper* pointer_cs_;
ThreadWrapper* monitor_thread_;
EventWrapper& monitor_event_;
CpuWrapper* cpu_;
ViEBaseObserver* vie_base_observer_;
};
} // namespace webrtc
#endif // WEBRTC_VIDEO_ENGINE_VIE_PERFORMANCE_MONITOR_H_
| Linphone-sync/webrtc | video_engine/vie_performance_monitor.h | C | bsd-3-clause | 1,557 |
// Copyright 2013 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.
#include "apps/app_lifetime_monitor_factory.h"
#include "apps/app_lifetime_monitor.h"
#include "apps/app_window_registry.h"
#include "chrome/browser/profiles/profile.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "extensions/browser/extensions_browser_client.h"
namespace apps {
// static
AppLifetimeMonitor* AppLifetimeMonitorFactory::GetForProfile(Profile* profile) {
return static_cast<AppLifetimeMonitor*>(
GetInstance()->GetServiceForBrowserContext(profile, false));
}
AppLifetimeMonitorFactory* AppLifetimeMonitorFactory::GetInstance() {
return Singleton<AppLifetimeMonitorFactory>::get();
}
AppLifetimeMonitorFactory::AppLifetimeMonitorFactory()
: BrowserContextKeyedServiceFactory(
"AppLifetimeMonitor",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(AppWindowRegistry::Factory::GetInstance());
}
AppLifetimeMonitorFactory::~AppLifetimeMonitorFactory() {}
KeyedService* AppLifetimeMonitorFactory::BuildServiceInstanceFor(
content::BrowserContext* profile) const {
return new AppLifetimeMonitor(static_cast<Profile*>(profile));
}
bool AppLifetimeMonitorFactory::ServiceIsCreatedWithBrowserContext() const {
return true;
}
content::BrowserContext* AppLifetimeMonitorFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return extensions::ExtensionsBrowserClient::Get()->
GetOriginalContext(context);
}
} // namespace apps
| 7kbird/chrome | apps/app_lifetime_monitor_factory.cc | C++ | bsd-3-clause | 1,638 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.