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 (C) 2007-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. */ #include "config.h" #include "V8HTMLFrameSetElement.h" #include "Document.h" #include "Frame.h" #include "HTMLCollection.h" #include "HTMLFrameElement.h" #include "HTMLFrameSetElement.h" #include "HTMLNames.h" #include "Node.h" #include "V8Binding.h" #include "V8DOMWindow.h" #include "V8Proxy.h" namespace WebCore { v8::Handle<v8::Value> V8HTMLFrameSetElement::namedPropertyGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.HTMLFrameSetElement.NamedPropertyGetter"); HTMLFrameSetElement* imp = V8HTMLFrameSetElement::toNative(info.Holder()); Node* frameNode = imp->children()->namedItem(v8StringToAtomicWebCoreString(name)); if (frameNode && frameNode->hasTagName(HTMLNames::frameTag)) { Document* doc = static_cast<HTMLFrameElement*>(frameNode)->contentDocument(); if (!doc) return v8::Undefined(); if (Frame* frame = doc->frame()) return toV8(frame->domWindow()); } return notHandledByInterceptor(); } } // namespace WebCore
mogoweb/webkit_for_android5.1
webkit/Source/WebCore/bindings/v8/custom/V8HTMLFrameSetElementCustom.cpp
C++
apache-2.0
2,606
package liquibase.database; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import liquibase.change.core.CreateTableChange; import liquibase.executor.ExecutorService; import liquibase.sdk.executor.MockExecutor; import liquibase.sql.visitor.AppendSqlVisitor; import liquibase.sql.visitor.SqlVisitor; import liquibase.statement.SqlStatement; import liquibase.statement.core.CreateTableStatement; import liquibase.statement.core.DropTableStatement; import liquibase.structure.core.Table; import org.junit.Test; /** * Base test class for database-specific tests */ public abstract class AbstractJdbcDatabaseTest { protected AbstractJdbcDatabase database; protected AbstractJdbcDatabaseTest(AbstractJdbcDatabase database) throws Exception { this.database = database; } public AbstractJdbcDatabase getDatabase() { return database; } protected abstract String getProductNameString(); public abstract void supportsInitiallyDeferrableColumns(); public abstract void getCurrentDateTimeFunction(); // @Test // public void onlyAdjustAutoCommitOnMismatch() throws Exception { // // Train expectations for setConnection(). If getAutoCommit() returns the same value the Database wants, based // // on getAutoCommitMode(), it should _not_ call setAutoCommit(boolean) on the connection // DatabaseConnection connection = createStrictMock(DatabaseConnection.class); // expect(connection.getConnectionUserName()).andReturn("user").anyTimes(); // expect(connection.getURL()).andReturn("URL"); // expect(connection.getAutoCommit()).andReturn(getDatabase().getAutoCommitMode()); // replay(connection); // getDatabase().setConnection(connection); // verify(connection); // // // Reset the mock and train expectations for close(). Since the auto-commit mode was not adjusted while setting // // the connection, it should not be adjusted on close() either // reset(connection); // connection.close(); // replay(connection); // // getDatabase().close(); // verify(connection); // } @Test public void defaultsWorkWithoutAConnection() { database.getDatabaseProductName(); database.getDefaultCatalogName(); database.getDefaultSchemaName(); database.getDefaultPort(); } @Test public void isCorrectDatabaseImplementation() throws Exception { assertTrue(getDatabase().isCorrectDatabaseImplementation(getMockConnection())); } protected DatabaseConnection getMockConnection() throws Exception { DatabaseConnection conn = createMock(DatabaseConnection.class); // DatabaseMetaData metaData = createMock(DatabaseMetaData.class); conn.setAutoCommit(false); expectLastCall().anyTimes(); // expect(((JdbcConnection) conn).getUnderlyingConnection().getMetaData()).andReturn(metaData).anyTimes(); expect(conn.getDatabaseProductName()).andReturn(getProductNameString()).anyTimes(); replay(conn); // replay(metaData); return conn; } @Test public void escapeTableName_noSchema() { Database database = getDatabase(); assertEquals("tableName", database.escapeTableName(null, null, "tableName")); } @Test public void escapeTableName_withSchema() { Database database = getDatabase(); if (database.supportsCatalogInObjectName(Table.class)) { assertEquals("catalogName.schemaName.tableName", database.escapeTableName("catalogName", "schemaName", "tableName")); } else { assertEquals("schemaName.tableName", database.escapeTableName("catalogName", "schemaName", "tableName")); } } @Test public void executeRollbackStatements_WithStatementsOverload_ShouldNotIncludeAppendTextFromApplyToRollbackFalseVisitor() throws Exception { Database database = getDatabase(); final MockExecutor mockExecutor = new MockExecutor(); ExecutorService.getInstance().setExecutor(database, mockExecutor); final List<SqlVisitor> sqlVisitors = new ArrayList<SqlVisitor>(); final SqlStatement dropTableStatement = new DropTableStatement(null, null, "test_table", false); final AppendSqlVisitor appendSqlVisitor = new AppendSqlVisitor(); appendSqlVisitor.setApplyToRollback(false); appendSqlVisitor.setValue(" SHOULD NOT BE APPENDED"); sqlVisitors.add(appendSqlVisitor); database.executeRollbackStatements(new SqlStatement[] {dropTableStatement}, sqlVisitors); assertEquals("DROP TABLE test_table;", mockExecutor.getRanSql().trim()); } @Test public void executeRollbackStatements_WithStatementsOverload_ShouldIncludeAppendTextFromApplyToRollbackTrueVisitor() throws Exception { Database database = getDatabase(); final MockExecutor mockExecutor = new MockExecutor(); ExecutorService.getInstance().setExecutor(database, mockExecutor); final List<SqlVisitor> sqlVisitors = new ArrayList<SqlVisitor>(); final SqlStatement dropTableStatement = new DropTableStatement(null, null, "test_table", false); final AppendSqlVisitor appendSqlVisitor = new AppendSqlVisitor(); appendSqlVisitor.setApplyToRollback(true); appendSqlVisitor.setValue(" SHOULD BE APPENDED"); sqlVisitors.add(appendSqlVisitor); database.executeRollbackStatements(new SqlStatement[] {dropTableStatement}, sqlVisitors); assertEquals("DROP TABLE test_table SHOULD BE APPENDED;", mockExecutor.getRanSql().trim()); } @Test public void executeRollbackStatements_WithChangeOverload_ShouldNotIncludeAppendTextFromApplyToRollbackFalseVisitor() throws Exception { Database database = getDatabase(); final MockExecutor mockExecutor = new MockExecutor(); ExecutorService.getInstance().setExecutor(database, mockExecutor); final List<SqlVisitor> sqlVisitors = new ArrayList<SqlVisitor>(); final CreateTableChange change = new CreateTableChange(); change.setTableName("test_table"); final AppendSqlVisitor appendSqlVisitor = new AppendSqlVisitor(); appendSqlVisitor.setApplyToRollback(false); appendSqlVisitor.setValue(" SHOULD NOT BE APPENDED"); sqlVisitors.add(appendSqlVisitor); database.executeRollbackStatements(change, sqlVisitors); assertEquals("DROP TABLE test_table;", mockExecutor.getRanSql().trim()); } @Test public void executeRollbackStatements_WithChangeOverload_ShouldIncludeAppendTextFromApplyToRollbackTrueVisitor() throws Exception { Database database = getDatabase(); final MockExecutor mockExecutor = new MockExecutor(); ExecutorService.getInstance().setExecutor(database, mockExecutor); final List<SqlVisitor> sqlVisitors = new ArrayList<SqlVisitor>(); final CreateTableChange change = new CreateTableChange(); change.setTableName("test_table"); final AppendSqlVisitor appendSqlVisitor = new AppendSqlVisitor(); appendSqlVisitor.setApplyToRollback(true); appendSqlVisitor.setValue(" SHOULD BE APPENDED"); sqlVisitors.add(appendSqlVisitor); database.executeRollbackStatements(change, sqlVisitors); assertEquals("DROP TABLE test_table SHOULD BE APPENDED;", mockExecutor.getRanSql().trim()); } // @Test // public void getColumnType_javaTypes() throws SQLException { // Database database = getDatabase(); // DatabaseConnection connection = database.getConnection(); // if (connection != null) { // ((JdbcConnection) connection).getUnderlyingConnection().rollback(); // assertEquals(database.getDateType().getDataTypeName().toUpperCase(), database.getDataType("java.sql.Types.DATE", false).toUpperCase()); // assertEquals(database.getBooleanType().getDataTypeName().toUpperCase(), database.getDataType("java.sql.Types.BOOLEAN", false).toUpperCase()); // assertEquals("VARCHAR(255)", database.getDataType("java.sql.Types.VARCHAR(255)", false).toUpperCase().replaceAll("VARCHAR2", "VARCHAR")); // } // } }
foxel/liquibase
liquibase-core/src/test/java/liquibase/database/AbstractJdbcDatabaseTest.java
Java
apache-2.0
8,833
#ifndef CERT_TRANS_UTIL_READ_PRIVATE_KEY_H_ #define CERT_TRANS_UTIL_READ_PRIVATE_KEY_H_ #include <openssl/evp.h> #include <string> #include "util/statusor.h" namespace cert_trans { util::StatusOr<EVP_PKEY*> ReadPrivateKey(const std::string& file); util::StatusOr<EVP_PKEY*> ReadPublicKey(const std::string& file); } // namespace cert_trans #endif // CERT_TRANS_UTIL_READ_PRIVATE_KEY_H_
rhamilto/origin
vendor/github.com/google/certificate-transparency/cpp/util/read_key.h
C
apache-2.0
397
package run import ( "archive/tar" "bytes" "fmt" "io" "strings" "github.com/docker/engine-api/types" "github.com/docker/engine-api/types/container" "github.com/docker/go-connections/nat" "github.com/golang/glog" "github.com/openshift/origin/pkg/oc/bootstrap/docker/dockerhelper" "github.com/openshift/origin/pkg/oc/bootstrap/docker/errors" ) type RunHelper struct { client dockerhelper.Interface dockerHelper *dockerhelper.Helper } func NewRunHelper(dockerHelper *dockerhelper.Helper) *RunHelper { return &RunHelper{ client: dockerHelper.Client(), dockerHelper: dockerHelper, } } func (h *RunHelper) New() *Runner { return &Runner{ client: h.client, dockerHelper: h.dockerHelper, config: &container.Config{}, hostConfig: &container.HostConfig{}, } } // Runner is a helper to run new containers on Docker type Runner struct { name string client dockerhelper.Interface dockerHelper *dockerhelper.Helper config *container.Config hostConfig *container.HostConfig removeContainer bool copies map[string][]byte } // Name sets the name of the container to create func (h *Runner) Name(name string) *Runner { h.name = name return h } // Image sets the image to run func (h *Runner) Image(image string) *Runner { h.config.Image = image return h } func (h *Runner) PortForward(local, remote int) *Runner { if h.hostConfig.PortBindings == nil { h.hostConfig.PortBindings = nat.PortMap{} } containerPort := nat.Port(fmt.Sprintf("%d/tcp", remote)) binding := nat.PortBinding{ HostPort: fmt.Sprintf("%d", local), } h.hostConfig.PortBindings[containerPort] = []nat.PortBinding{binding} if h.config.ExposedPorts == nil { h.config.ExposedPorts = map[nat.Port]struct{}{} } h.config.ExposedPorts[containerPort] = struct{}{} return h } // Entrypoint sets the entrypoint to use when running func (h *Runner) Entrypoint(cmd ...string) *Runner { h.config.Entrypoint = cmd return h } // Command sets the command to run func (h *Runner) Command(cmd ...string) *Runner { h.config.Cmd = cmd return h } func (h *Runner) Copy(contents map[string][]byte) *Runner { h.copies = contents return h } // HostPid tells Docker to run using the host's pid namespace func (h *Runner) HostPid() *Runner { h.hostConfig.PidMode = "host" return h } // HostNetwork tells Docker to run using the host's Network namespace func (h *Runner) HostNetwork() *Runner { h.hostConfig.NetworkMode = "host" return h } // Bind tells Docker to bind host dirs to container dirs func (h *Runner) Bind(binds ...string) *Runner { h.hostConfig.Binds = append(h.hostConfig.Binds, binds...) return h } // Env tells Docker to add environment variables to the container getting started func (h *Runner) Env(env ...string) *Runner { h.config.Env = append(h.config.Env, env...) return h } // Privileged tells Docker to run the container as privileged func (h *Runner) Privileged() *Runner { h.hostConfig.Privileged = true return h } // DiscardContainer if true will cause the container to be removed when done executing. // Will be ignored in the case of Start func (h *Runner) DiscardContainer() *Runner { h.removeContainer = true return h } // User sets the username or UID to use when running the container. // Will be ignored if empty string func (h *Runner) User(user string) *Runner { if strings.TrimSpace(user) != "" { h.config.User = user } return h } func (h *Runner) DNS(address ...string) *Runner { h.hostConfig.DNS = address return h } // Start starts the container as a daemon and returns func (h *Runner) Start() (string, error) { id, err := h.Create() if err != nil { return "", err } if err := h.copy(id); err != nil { return id, err } return id, h.startContainer(id) } // Output starts the container, waits for it to finish and returns its output func (h *Runner) Output() (string, string, int, error) { return h.runWithOutput() } // Run executes the container and waits until it completes func (h *Runner) Run() (int, error) { _, _, rc, err := h.runWithOutput() return rc, err } func (h *Runner) Create() (string, error) { if h.hostConfig.Privileged { userNsMode, err := h.dockerHelper.UserNamespaceEnabled() if err != nil { return "", err } if userNsMode { h.hostConfig.UsernsMode = "host" } } glog.V(4).Infof("Creating container named %q\nconfig:\n%s\nhost config:\n%s\n", h.name, printConfig(h.config), printHostConfig(h.hostConfig)) response, err := h.client.ContainerCreate(h.config, h.hostConfig, nil, h.name) if err != nil { return "", errors.NewError("cannot create container using image %s", h.config.Image).WithCause(err) } glog.V(5).Infof("Container created with id %q", response.ID) if len(response.Warnings) > 0 { glog.V(5).Infof("Warnings from container creation: %v", response.Warnings) } return response.ID, nil } func (h *Runner) copy(id string) error { if len(h.copies) == 0 { return nil } archive := streamingArchive(h.copies) defer archive.Close() err := h.client.CopyToContainer(id, "/", archive, types.CopyToContainerOptions{}) return err } // streamingArchive returns a ReadCloser containing a tar archive with contents serialized as files. func streamingArchive(contents map[string][]byte) io.ReadCloser { r, w := io.Pipe() go func() { archive := tar.NewWriter(w) for k, v := range contents { if err := archive.WriteHeader(&tar.Header{ Name: k, Mode: 0644, Size: int64(len(v)), Typeflag: tar.TypeReg, }); err != nil { w.CloseWithError(err) return } if _, err := archive.Write(v); err != nil { w.CloseWithError(err) return } } archive.Close() w.Close() }() return r } func (h *Runner) startContainer(id string) error { err := h.client.ContainerStart(id) if err != nil { return errors.NewError("cannot start container %s", id).WithCause(err) } return nil } func (h *Runner) runWithOutput() (string, string, int, error) { id, err := h.Create() if err != nil { return "", "", 0, err } if h.removeContainer { defer func() { glog.V(5).Infof("Deleting container %q", id) if err = h.client.ContainerRemove(id, types.ContainerRemoveOptions{}); err != nil { glog.V(2).Infof("Error deleting container %q: %v", id, err) } }() } glog.V(5).Infof("Starting container %q", id) err = h.startContainer(id) if err != nil { glog.V(2).Infof("Error occurred starting container %q: %v", id, err) return "", "", 0, err } glog.V(5).Infof("Waiting for container %q", id) rc, err := h.client.ContainerWait(id) if err != nil { glog.V(2).Infof("Error occurred waiting for container %q: %v", id, err) return "", "", 0, err } glog.V(5).Infof("Done waiting for container %q, rc=%d", id, rc) // changed to only reading logs after execution instead of streaming // stdout/stderr to avoid race condition in (at least) docker 1.10-1.14-dev: // https://github.com/docker/docker/issues/29285 glog.V(5).Infof("Reading logs from container %q", id) stdOut := &bytes.Buffer{} stdErr := &bytes.Buffer{} err = h.client.ContainerLogs(id, types.ContainerLogsOptions{ShowStdout: true, ShowStderr: true}, stdOut, stdErr) if err != nil { glog.V(2).Infof("Error occurred while reading logs: %v", err) return "", "", 0, err } glog.V(5).Infof("Done reading logs from container %q", id) glog.V(5).Infof("Stdout:\n%s", stdOut.String()) glog.V(5).Infof("Stderr:\n%s", stdErr.String()) if rc != 0 || err != nil { return stdOut.String(), stdErr.String(), rc, newRunError(rc, err, stdOut.String(), stdErr.String(), h.config) } glog.V(4).Infof("Container run successful\n") return stdOut.String(), stdErr.String(), rc, nil } // printConfig prints out the relevant parts of a container's Docker config func printConfig(c *container.Config) string { out := &bytes.Buffer{} fmt.Fprintf(out, " image: %s\n", c.Image) if len(c.Entrypoint) > 0 { fmt.Fprintf(out, " entry point:\n") for _, e := range c.Entrypoint { fmt.Fprintf(out, " %s\n", e) } } if len(c.Cmd) > 0 { fmt.Fprintf(out, " command:\n") for _, c := range c.Cmd { fmt.Fprintf(out, " %s\n", c) } } if len(c.Env) > 0 { fmt.Fprintf(out, " environment:\n") for _, e := range c.Env { fmt.Fprintf(out, " %s\n", e) } } return out.String() } func printHostConfig(c *container.HostConfig) string { out := &bytes.Buffer{} fmt.Fprintf(out, " pid mode: %s\n", c.PidMode) fmt.Fprintf(out, " user mode: %s\n", c.UsernsMode) fmt.Fprintf(out, " network mode: %s\n", c.NetworkMode) if len(c.DNS) > 0 { fmt.Fprintf(out, " DNS:\n") for _, h := range c.DNS { fmt.Fprintf(out, " %s\n", h) } } if len(c.Binds) > 0 { fmt.Fprintf(out, " volume binds:\n") for _, b := range c.Binds { fmt.Fprintf(out, " %s\n", b) } } return out.String() }
ashetty1/kedge
vendor/github.com/openshift/origin/pkg/oc/bootstrap/docker/run/run.go
GO
apache-2.0
8,854
<?php /** * @version $Id: formatter.php 2325 2012-08-13 17:46:48Z btowles $ * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only * * Rockettheme Gantry Template uses the Joomla Framework (http://www.joomla.org), a GNU/GPLv2 content management system * */ // no direct access defined('GANTRY_VERSION') or die('Restricted access'); gantry_import('facets.menu.gantrymenuformatter'); /* * Created on Jan 16, 2009 * * To change the template for this generated file go to * Window - Preferences - PHPeclipse - PHP - Code Templates */ class GantryMenuFormatterTouch extends GantryMenuFormatter { function format(&$node, &$menu_params) { // Format the current node if ($node->type == 'menuitem' or $node->type == 'separator') { if ($node->hasChildren()) { $node->addLinkClass("daddy"); } else { $node->addLinkClass("orphan"); } $node->addLinkClass("item"); } if ($node->level == 1) { $node->addListItemClass("root"); } } }
devxive/nawala-rdk
src/lib_gantry/facets/menu/themes/touch/formatter.php
PHP
apache-2.0
1,098
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; import org.elasticsearch.xpack.ql.expression.Expression; import org.elasticsearch.xpack.ql.expression.function.scalar.BinaryScalarFunction; import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; import org.elasticsearch.xpack.ql.tree.NodeInfo; import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.ql.type.DataType; import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.NonIsoDateTimeProcessor.NonIsoDateTimeExtractor; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.temporal.ChronoField; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.ToIntFunction; import static org.elasticsearch.xpack.ql.expression.TypeResolutions.ParamOrdinal.SECOND; import static org.elasticsearch.xpack.sql.expression.SqlTypeResolutions.isDate; public class DatePart extends BinaryDateTimeDatePartFunction { public enum Part implements DateTimeField { YEAR(DateTimeExtractor.YEAR::extract, "years", "yyyy", "yy"), QUARTER(QuarterProcessor::quarter, "quarters", "qq", "q"), MONTH(DateTimeExtractor.MONTH_OF_YEAR::extract, "months", "mm", "m"), DAYOFYEAR(DateTimeExtractor.DAY_OF_YEAR::extract, "dy", "y"), DAY(DateTimeExtractor.DAY_OF_MONTH::extract, "days", "dd", "d"), WEEK(NonIsoDateTimeExtractor.WEEK_OF_YEAR::extract, "weeks", "wk", "ww"), WEEKDAY(NonIsoDateTimeExtractor.DAY_OF_WEEK::extract, "weekdays", "dw"), HOUR(DateTimeExtractor.HOUR_OF_DAY::extract, "hours", "hh"), MINUTE(DateTimeExtractor.MINUTE_OF_HOUR::extract, "minutes", "mi", "n"), SECOND(DateTimeExtractor.SECOND_OF_MINUTE::extract, "seconds", "ss", "s"), MILLISECOND(dt -> dt.get(ChronoField.MILLI_OF_SECOND), "milliseconds", "ms"), MICROSECOND(dt -> dt.get(ChronoField.MICRO_OF_SECOND), "microseconds", "mcs"), NANOSECOND(ZonedDateTime::getNano, "nanoseconds", "ns"), TZOFFSET(dt -> dt.getOffset().getTotalSeconds() / 60, "tz"); private static final Map<String, Part> NAME_TO_PART; private static final List<String> VALID_VALUES; static { NAME_TO_PART = DateTimeField.initializeResolutionMap(values()); VALID_VALUES = DateTimeField.initializeValidValues(values()); } private ToIntFunction<ZonedDateTime> extractFunction; private Set<String> aliases; Part(ToIntFunction<ZonedDateTime> extractFunction, String... aliases) { this.extractFunction = extractFunction; this.aliases = Set.of(aliases); } @Override public Iterable<String> aliases() { return aliases; } public static List<String> findSimilar(String match) { return DateTimeField.findSimilar(NAME_TO_PART.keySet(), match); } public static Part resolve(String dateTimePart) { return DateTimeField.resolveMatch(NAME_TO_PART, dateTimePart); } public Integer extract(ZonedDateTime dateTime) { return extractFunction.applyAsInt(dateTime); } } public DatePart(Source source, Expression dateTimePart, Expression timestamp, ZoneId zoneId) { super(source, dateTimePart, timestamp, zoneId); } @Override public DataType dataType() { return DataTypes.INTEGER; } @Override protected TypeResolution resolveType() { TypeResolution resolution = super.resolveType(); if (resolution.unresolved()) { return resolution; } resolution = isDate(right(), sourceText(), SECOND); if (resolution.unresolved()) { return resolution; } return TypeResolution.TYPE_RESOLVED; } @Override protected BinaryScalarFunction replaceChildren(Expression newDateTimePart, Expression newTimestamp) { return new DatePart(source(), newDateTimePart, newTimestamp, zoneId()); } @Override protected NodeInfo<? extends Expression> info() { return NodeInfo.create(this, DatePart::new, left(), right(), zoneId()); } @Override protected String scriptMethodName() { return "datePart"; } @Override public Object fold() { return DatePartProcessor.process(left().fold(), right().fold(), zoneId()); } @Override protected Pipe createPipe(Pipe dateTimePart, Pipe timestamp, ZoneId zoneId) { return new DatePartPipe(source(), this, dateTimePart, timestamp, zoneId); } @Override protected boolean resolveDateTimeField(String dateTimeField) { return Part.resolve(dateTimeField) != null; } @Override protected List<String> findSimilarDateTimeFields(String dateTimeField) { return Part.findSimilar(dateTimeField); } @Override protected List<String> validDateTimeFieldValues() { return Part.VALID_VALUES; } }
ern/elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePart.java
Java
apache-2.0
5,417
// Copyright 2011 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 ast import ( "go/token" "sort" "strconv" ) // SortImports sorts runs of consecutive import lines in import blocks in f. // It also removes duplicate imports when it is possible to do so without data loss. func SortImports(fset *token.FileSet, f *File) { for _, d := range f.Decls { d, ok := d.(*GenDecl) if !ok || d.Tok != token.IMPORT { // Not an import declaration, so we're done. // Imports are always first. break } if !d.Lparen.IsValid() { // Not a block: sorted by default. continue } // Identify and sort runs of specs on successive lines. i := 0 specs := d.Specs[:0] for j, s := range d.Specs { if j > i && fset.Position(s.Pos()).Line > 1+fset.Position(d.Specs[j-1].End()).Line { // j begins a new run. End this one. specs = append(specs, sortSpecs(fset, f, d.Specs[i:j])...) i = j } } specs = append(specs, sortSpecs(fset, f, d.Specs[i:])...) d.Specs = specs // Deduping can leave a blank line before the rparen; clean that up. if len(d.Specs) > 0 { lastSpec := d.Specs[len(d.Specs)-1] lastLine := fset.Position(lastSpec.Pos()).Line rParenLine := fset.Position(d.Rparen).Line for rParenLine > lastLine+1 { rParenLine-- fset.File(d.Rparen).MergeLine(rParenLine) } } } } func importPath(s Spec) string { t, err := strconv.Unquote(s.(*ImportSpec).Path.Value) if err == nil { return t } return "" } func importName(s Spec) string { n := s.(*ImportSpec).Name if n == nil { return "" } return n.Name } func importComment(s Spec) string { c := s.(*ImportSpec).Comment if c == nil { return "" } return c.Text() } // collapse indicates whether prev may be removed, leaving only next. func collapse(prev, next Spec) bool { if importPath(next) != importPath(prev) || importName(next) != importName(prev) { return false } return prev.(*ImportSpec).Comment == nil } type posSpan struct { Start token.Pos End token.Pos } func sortSpecs(fset *token.FileSet, f *File, specs []Spec) []Spec { // Can't short-circuit here even if specs are already sorted, // since they might yet need deduplication. // A lone import, however, may be safely ignored. if len(specs) <= 1 { return specs } // Record positions for specs. pos := make([]posSpan, len(specs)) for i, s := range specs { pos[i] = posSpan{s.Pos(), s.End()} } // Identify comments in this range. // Any comment from pos[0].Start to the final line counts. lastLine := fset.Position(pos[len(pos)-1].End).Line cstart := len(f.Comments) cend := len(f.Comments) for i, g := range f.Comments { if g.Pos() < pos[0].Start { continue } if i < cstart { cstart = i } if fset.Position(g.End()).Line > lastLine { cend = i break } } comments := f.Comments[cstart:cend] // Assign each comment to the import spec preceding it. importComment := map[*ImportSpec][]*CommentGroup{} specIndex := 0 for _, g := range comments { for specIndex+1 < len(specs) && pos[specIndex+1].Start <= g.Pos() { specIndex++ } s := specs[specIndex].(*ImportSpec) importComment[s] = append(importComment[s], g) } // Sort the import specs by import path. // Remove duplicates, when possible without data loss. // Reassign the import paths to have the same position sequence. // Reassign each comment to abut the end of its spec. // Sort the comments by new position. sort.Sort(byImportSpec(specs)) // Dedup. Thanks to our sorting, we can just consider // adjacent pairs of imports. deduped := specs[:0] for i, s := range specs { if i == len(specs)-1 || !collapse(s, specs[i+1]) { deduped = append(deduped, s) } else { p := s.Pos() fset.File(p).MergeLine(fset.Position(p).Line) } } specs = deduped // Fix up comment positions for i, s := range specs { s := s.(*ImportSpec) if s.Name != nil { s.Name.NamePos = pos[i].Start } s.Path.ValuePos = pos[i].Start s.EndPos = pos[i].End for _, g := range importComment[s] { for _, c := range g.List { c.Slash = pos[i].End } } } sort.Sort(byCommentPos(comments)) return specs } type byImportSpec []Spec // slice of *ImportSpec func (x byImportSpec) Len() int { return len(x) } func (x byImportSpec) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x byImportSpec) Less(i, j int) bool { ipath := importPath(x[i]) jpath := importPath(x[j]) if ipath != jpath { return ipath < jpath } iname := importName(x[i]) jname := importName(x[j]) if iname != jname { return iname < jname } return importComment(x[i]) < importComment(x[j]) } type byCommentPos []*CommentGroup func (x byCommentPos) Len() int { return len(x) } func (x byCommentPos) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x byCommentPos) Less(i, j int) bool { return x[i].Pos() < x[j].Pos() }
cyberroadie/go
src/go/ast/import.go
GO
bsd-3-clause
4,958
module Sass::Script::Tree # The parse tree node for a literal scalar value. This wraps an instance of # {Sass::Script::Value::Base}. # # List literals should use {ListLiteral} instead. class Literal < Node # The wrapped value. # # @return [Sass::Script::Value::Base] attr_reader :value # Creates a new literal value. # # @param value [Sass::Script::Value::Base] # @see #value def initialize(value) @value = value end # @see Node#children def children; []; end # @see Node#to_sass def to_sass(opts = {}); value.to_sass(opts); end # @see Node#deep_copy def deep_copy; dup; end # @see Node#options= def options=(options) value.options = options end def inspect value.inspect end def force_division! value.original = nil if value.is_a?(Sass::Script::Value::Number) end protected def _perform(environment) value.source_range = source_range value end end end
jmatbastos/rbenv
versions/2.2.3/lib/ruby/gems/2.2.0/gems/sass-3.4.19/lib/sass/script/tree/literal.rb
Ruby
mit
1,014
/* * Copyright 2008 Freescale Semiconductor, Inc. * * 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. */ #include <linux/stddef.h> #include <linux/kernel.h> #include <linux/interrupt.h> #include <linux/of_platform.h> #include <asm/system.h> #include <asm/mpic.h> #include <asm/i8259.h> #ifdef CONFIG_PPC_I8259 static void mpc86xx_8259_cascade(unsigned int irq, struct irq_desc *desc) { unsigned int cascade_irq = i8259_irq(); if (cascade_irq != NO_IRQ) generic_handle_irq(cascade_irq); desc->chip->eoi(irq); } #endif /* CONFIG_PPC_I8259 */ void __init mpc86xx_init_irq(void) { struct mpic *mpic; struct device_node *np; struct resource res; #ifdef CONFIG_PPC_I8259 struct device_node *cascade_node = NULL; int cascade_irq; #endif /* Determine PIC address. */ np = of_find_node_by_type(NULL, "open-pic"); if (np == NULL) return; of_address_to_resource(np, 0, &res); mpic = mpic_alloc(np, res.start, MPIC_PRIMARY | MPIC_WANTS_RESET | MPIC_BIG_ENDIAN | MPIC_BROKEN_FRR_NIRQS | MPIC_SINGLE_DEST_CPU, 0, 256, " MPIC "); of_node_put(np); BUG_ON(mpic == NULL); mpic_init(mpic); #ifdef CONFIG_PPC_I8259 /* Initialize i8259 controller */ for_each_node_by_type(np, "interrupt-controller") if (of_device_is_compatible(np, "chrp,iic")) { cascade_node = np; break; } if (cascade_node == NULL) { printk(KERN_DEBUG "Could not find i8259 PIC\n"); return; } cascade_irq = irq_of_parse_and_map(cascade_node, 0); if (cascade_irq == NO_IRQ) { printk(KERN_ERR "Failed to map cascade interrupt\n"); return; } i8259_init(cascade_node, 0); of_node_put(cascade_node); set_irq_chained_handler(cascade_irq, mpc86xx_8259_cascade); #endif }
felixhaedicke/nst-kernel
src/arch/powerpc/platforms/86xx/pic.c
C
gpl-2.0
1,899
/* * 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.pig.piggybank.evaluation.string; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.apache.pig.EvalFunc; import org.apache.pig.FuncSpec; import org.apache.pig.PigWarning; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; /** * <dl> * <dt><b>Syntax:</b></dt> * <dd><code>int RegexMatch(String expression, String regex)</code>.</dd> * <dt><b>Output:</b></dt> * <dd><code>return 1 if expression contains regex, 0 otherwise</code>.</dd> * </dl> */ public class RegexMatch extends EvalFunc<Integer> { String mExpression = null; Pattern mPattern = null; @Override public Schema outputSchema(Schema input) { try { return new Schema(new Schema.FieldSchema(getSchemaName(this.getClass().getName().toLowerCase(), input), DataType.INTEGER)); } catch (Exception e) { return null; } } public Integer exec(Tuple input) throws IOException { if (input.size()!=2) { String msg = "RegexMatch : Only 2 parameters are allowed."; throw new IOException(msg); } if (input.get(0)==null) return null; try { if (!input.get(1).equals(mExpression)) { mExpression = (String)input.get(1); try { mPattern = Pattern.compile(mExpression); } catch (Exception e) { String msg = "RegexMatch : Mal-Formed Regular Expression "+input.get(1); throw new IOException(msg); } } } catch (NullPointerException e) { String msg = "RegexMatch : Regular Expression is null "; throw new IOException(msg); } if (mPattern.matcher((String)input.get(0)).matches()) return 1; return 0; } @Override public List<FuncSpec> getArgToFuncMapping() throws FrontendException { List<FuncSpec> funcList = new ArrayList<FuncSpec>(); Schema s = new Schema(); s.add(new Schema.FieldSchema(null, DataType.CHARARRAY)); s.add(new Schema.FieldSchema(null, DataType.CHARARRAY)); funcList.add(new FuncSpec(this.getClass().getName(), s)); return funcList; } }
kaituo/sedge
trunk/contrib/piggybank/java/src/main/java/org/apache/pig/piggybank/evaluation/string/RegexMatch.java
Java
mit
3,296
/** * Transforms object or iterable to map. Iterable needs to be in the format acceptable by the `Map` constructor. * * map = toMap( { 'foo': 1, 'bar': 2 } ); * map = toMap( [ [ 'foo', 1 ], [ 'bar', 2 ] ] ); * map = toMap( anotherMap ); * */ export default function toMap<T>(data: Record<string, T> | Array<[string, T]> | Map<string, T>): Map<string, T>;
markogresak/DefinitelyTyped
types/ckeditor__ckeditor5-utils/v27/src/tomap.d.ts
TypeScript
mit
365
/* ,adPPYba, 88 88 8b,dPPYba, ,adPPYba, 8b,dPPYba, a8" "" 88 88 88P' "8a a8" "8a 88P' `"8a 8b 88 88 88 d8 8b d8 88 88 "8a, ,aa "8a, ,a88 88b, ,a8" "8a, ,a8" 88 88 `"Ybbd8"' `"YbbdP'Y8 88`YbbdP"' `"YbbdP"' 88 88 88 88 -o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o- Objetivo de esta hoja de estilos -------------------------------------------------------------- Normaliza el estilo de todos los elementos HTML para que por defecto se vean bien e igual en todos los navegadores. Se aplica a -------------------------------------------------------------- frontend, backend y extranet Copiado de -------------------------------------------------------------- https://github.com/necolas/normalize.css */ /* =========================================================================== HTML5 display definitions ======================================================================== */ article, aside, details, figcaption, figure, footer, header, hgroup, nav, section { display: block; } audio, canvas, video { display: inline-block; *display: inline; *zoom: 1; } audio:not([controls]) { display: none; } [hidden] { display: none; } /* =========================================================================== Base ======================================================================== */ /* * 1. Correct text resizing oddly in IE6/7 when body font-size is set using em units * 2. Force vertical scrollbar in non-IE * 3. Prevent iOS text size adjust on device orientation change, without disabling user zoom: h5bp.com/g */ html { font-size: 100%; overflow-y: scroll; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } body { margin: 0; font-size: 13px; line-height: 1.231; } body, button, input, select, textarea { font-family: sans-serif; color: #222; } /* * Remove text-shadow in selection highlight: h5bp.com/i * These selection declarations have to be separate * Also: hot pink! (or customize the background color to match your design) */ ::-moz-selection { background: #fe57a1; color: #fff; text-shadow: none; } ::selection { background: #fe57a1; color: #fff; text-shadow: none; } /* =========================================================================== Links ======================================================================== */ a { color: #00e; } a:visited { color: #551a8b; } a:hover { color: #06e; } a:focus { outline: thin dotted; } /* Improve readability when focused and hovered in all browsers: h5bp.com/h */ a:hover, a:active { outline: 0; } /* =========================================================================== Typography ======================================================================== */ abbr[title] { border-bottom: 1px dotted; } b, strong { font-weight: bold; } blockquote { margin: 1em 40px; } dfn { font-style: italic; } hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; } ins { background: #ff9; color: #000; text-decoration: none; } mark { background: #ff0; color: #000; font-style: italic; font-weight: bold; } /* Redeclare monospace font family: h5bp.com/j */ pre, code, kbd, samp { font-family: monospace, monospace; _font-family: 'courier new', monospace; font-size: 1em; } /* Improve readability of pre-formatted text in all browsers */ pre { white-space: pre; white-space: pre-wrap; word-wrap: break-word; } q { quotes: none; } q:before, q:after { content: ""; content: none; } small { font-size: 85%; } /* Position subscript and superscript content without affecting line-height: h5bp.com/k */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } /* =========================================================================== Lists ======================================================================== */ ul, ol { margin: 1em 0; padding: 0 0 0 40px; } dd { margin: 0 0 0 40px; } nav ul, nav ol { list-style: none; list-style-image: none; margin: 0; padding: 0; } /* =========================================================================== Embedded content ======================================================================== */ /* * 1. Improve image quality when scaled in IE7: h5bp.com/d * 2. Remove the gap between images and borders on image containers: h5bp.com/e */ img { border: 0; -ms-interpolation-mode: bicubic; vertical-align: middle; } /* * Correct overflow not hidden in IE9 */ svg:not(:root) { overflow: hidden; } /* =========================================================================== Figures ======================================================================== */ figure { margin: 0; } /* =========================================================================== Forms ======================================================================== */ form { margin: 0; } fieldset { border: 0; margin: 0; padding: 0; } /* Indicate that 'label' will shift focus to the associated form element */ label { cursor: pointer; } /* * 1. Correct color not inheriting in IE6/7/8/9 * 2. Correct alignment displayed oddly in IE6/7 */ legend { border: 0; *margin-left: -7px; padding: 0; } /* * 1. Correct font-size not inheriting in all browsers * 2. Remove margins in FF3/4 S5 Chrome * 3. Define consistent vertical alignment display in all browsers */ button, input, select, textarea { font-size: 100%; margin: 0; vertical-align: baseline; *vertical-align: middle; } /* * 1. Define line-height as normal to match FF3/4 (set using !important in the UA stylesheet) * 2. Correct inner spacing displayed oddly in IE6/7 */ button, input { line-height: normal; *overflow: visible; } /* * Reintroduce inner spacing in 'table' to avoid overlap and whitespace issues in IE6/7 */ table button, table input { *overflow: auto; } /* * 1. Display hand cursor for clickable form elements * 2. Allow styling of clickable form elements in iOS */ button, input[type="button"], input[type="reset"], input[type="submit"] { cursor: pointer; -webkit-appearance: button; } /* * Consistent box sizing and appearance */ input[type="checkbox"], input[type="radio"] { box-sizing: border-box; } input[type="search"] { -webkit-appearance: textfield; -moz-box-sizing: content-box; -webkit-box-sizing: content-box; box-sizing: content-box; } input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; } /* * Remove inner padding and border in FF3/4: h5bp.com/l */ button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; } /* * 1. Remove default vertical scrollbar in IE6/7/8/9 * 2. Allow only vertical resizing */ textarea { overflow: auto; vertical-align: top; resize: vertical; } /* Colors for form validity */ input:valid, textarea:valid { } input:invalid, textarea:invalid { background-color: #f0dddd; } /* =========================================================================== Tables ======================================================================== */ table { border-collapse: collapse; border-spacing: 0; } td { vertical-align: top; }
raymercb/devsulabs
web/css/normalizar.css
CSS
mit
7,421
(function ($, Drupal, window) { "use strict"; /** * Attach the tableResponsive function to Drupal.behaviors. */ Drupal.behaviors.tableResponsive = { attach: function (context, settings) { var $tables = $(context).find('table.responsive-enabled').once('tableresponsive'); if ($tables.length) { for (var i = 0, il = $tables.length; i < il; i++) { TableResponsive.tables.push(new TableResponsive($tables[i])); } } } }; /** * The TableResponsive object optimizes table presentation for all screen sizes. * * A responsive table hides columns at small screen sizes, leaving the most * important columns visible to the end user. Users should not be prevented from * accessing all columns, however. This class adds a toggle to a table with * hidden columns that exposes the columns. Exposing the columns will likely * break layouts, but it provides the user with a means to access data, which * is a guiding principle of responsive design. */ function TableResponsive (table) { this.table = table; this.$table = $(table); this.showText = Drupal.t('Show all columns'); this.hideText = Drupal.t('Hide unimportant columns'); // Store a reference to the header elements of the table so that the DOM is // traversed only once to find them. this.$headers = this.$table.find('th'); // Add a link before the table for users to show or hide weight columns. this.$link = $('<a href="#" class="tableresponsive-toggle"></a>') .attr({ 'title': Drupal.t('Show table cells that were hidden to make the table fit within a small screen.') }) .on('click', $.proxy(this, 'eventhandlerToggleColumns')); this.$table.before($('<div class="tableresponsive-toggle-columns"></div>').append(this.$link)); // Attach a resize handler to the window. $(window) .on('resize.tableresponsive', $.proxy(this, 'eventhandlerEvaluateColumnVisibility')) .trigger('resize.tableresponsive'); } /** * Extend the TableResponsive function with a list of managed tables. */ $.extend(TableResponsive, { tables: [] }); /** * Associates an action link with the table that will show hidden columns. * * Columns are assumed to be hidden if their header has the class priority-low * or priority-medium. */ $.extend(TableResponsive.prototype, { eventhandlerEvaluateColumnVisibility: function (e) { var pegged = parseInt(this.$link.data('pegged'), 10); var hiddenLength = this.$headers.filter('.priority-medium:hidden, .priority-low:hidden').length; // If the table has hidden columns, associate an action link with the table // to show the columns. if (hiddenLength > 0) { this.$link.show().text(this.showText); } // When the toggle is pegged, its presence is maintained because the user // has interacted with it. This is necessary to keep the link visible if the // user adjusts screen size and changes the visibilty of columns. if (!pegged && hiddenLength === 0) { this.$link.hide().text(this.hideText); } }, // Toggle the visibility of columns classed with either 'priority-low' or // 'priority-medium'. eventhandlerToggleColumns: function (e) { e.preventDefault(); var self = this; var $hiddenHeaders = this.$headers.filter('.priority-medium:hidden, .priority-low:hidden'); this.$revealedCells = this.$revealedCells || $(); // Reveal hidden columns. if ($hiddenHeaders.length > 0) { $hiddenHeaders.each(function (index, element) { var $header = $(this); var position = $header.prevAll('th').length; self.$table.find('tbody tr').each(function () { var $cells = $(this).find('td:eq(' + position + ')'); $cells.show(); // Keep track of the revealed cells, so they can be hidden later. self.$revealedCells = $().add(self.$revealedCells).add($cells); }); $header.show(); // Keep track of the revealed headers, so they can be hidden later. self.$revealedCells = $().add(self.$revealedCells).add($header); }); this.$link.text(this.hideText).data('pegged', 1); } // Hide revealed columns. else { this.$revealedCells.hide(); // Strip the 'display:none' declaration from the style attributes of // the table cells that .hide() added. this.$revealedCells.each(function (index, element) { var $cell = $(this); var properties = $cell.attr('style').split(';'); var newProps = []; // The hide method adds display none to the element. The element should // be returned to the same state it was in before the columns were // revealed, so it is necessary to remove the display none // value from the style attribute. var match = /^display\s*\:\s*none$/; for (var i = 0; i < properties.length; i++) { var prop = properties[i]; prop.trim(); // Find the display:none property and remove it. var isDisplayNone = match.exec(prop); if (isDisplayNone) { continue; } newProps.push(prop); } // Return the rest of the style attribute values to the element. $cell.attr('style', newProps.join(';')); }); this.$link.text(this.showText).data('pegged', 0); // Refresh the toggle link. $(window).trigger('resize.tableresponsive'); } } }); // Make the TableResponsive object available in the Drupal namespace. Drupal.TableResponsive = TableResponsive; })(jQuery, Drupal, window);
teenatt1992/pmidemo
sites/all/modules/responsive_tables/js/tableresponsive.js
JavaScript
gpl-2.0
5,554
<?php /** * Abstract send email * * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://cakephp.org CakePHP(tm) Project * @package Cake.Network.Email * @since CakePHP(tm) v 2.0.0 * @license https://opensource.org/licenses/mit-license.php MIT License */ /** * Abstract transport for sending email * * @package Cake.Network.Email */ abstract class AbstractTransport { /** * Configurations * * @var array */ protected $_config = array(); /** * Send mail * * @param CakeEmail $email CakeEmail instance. * @return array */ abstract public function send(CakeEmail $email); /** * Set the config * * @param array $config Configuration options. * @return array Returns configs */ public function config($config = null) { if (is_array($config)) { $this->_config = $config + $this->_config; } return $this->_config; } /** * Help to convert headers in string * * @param array $headers Headers in format key => value * @param string $eol End of line string. * @return string */ protected function _headersToString($headers, $eol = "\r\n") { $out = ''; foreach ($headers as $key => $value) { if ($value === false || $value === null || $value === '') { continue; } $out .= $key . ': ' . $value . $eol; } if (!empty($out)) { $out = substr($out, 0, -1 * strlen($eol)); } return $out; } }
xplico/CapAnalysis
www/lib/Cake/Network/Email/AbstractTransport.php
PHP
gpl-2.0
1,766
/* Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. The MySQL Connector/J is licensed under the terms of the GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPLv2 as it is applied to this software, see the FOSS License Exception <http://www.mysql.com/about/legal/licensing/foss-exception.html>. 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; version 2 of the License. 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.mysql.jdbc.exceptions.jdbc4; import java.sql.SQLSyntaxErrorException; public class MySQLSyntaxErrorException extends SQLSyntaxErrorException { static final long serialVersionUID = 6919059513432113764L; public MySQLSyntaxErrorException() { super(); } public MySQLSyntaxErrorException(String reason, String SQLState, int vendorCode) { super(reason, SQLState, vendorCode); } public MySQLSyntaxErrorException(String reason, String SQLState) { super(reason, SQLState); } public MySQLSyntaxErrorException(String reason) { super(reason); } }
swankjesse/mysql-connector-j
src/com/mysql/jdbc/exceptions/jdbc4/MySQLSyntaxErrorException.java
Java
gpl-2.0
1,719
<?php if ( ( is_single() || is_page() ) && 'et_full_width_page' === get_post_meta( get_the_ID(), '_et_pb_page_layout', true ) ) return; if ( is_active_sidebar( 'sidebar-1' ) ) : ?> <div id="sidebar"> <?php dynamic_sidebar( 'sidebar-1' ); ?> </div> <!-- end #sidebar --> <?php endif; ?>
gwpdev/udofb
wp-content/themes/udof2015/sidebar.php
PHP
gpl-2.0
291
// 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 "content/shell/browser/shell_content_browser_client.h" #include "base/base_switches.h" #include "base/command_line.h" #include "base/files/file.h" #include "base/files/file_util.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/resource_dispatcher_host.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "content/public/common/web_preferences.h" #include "content/shell/browser/ipc_echo_message_filter.h" #include "content/shell/browser/shell.h" #include "content/shell/browser/shell_browser_context.h" #include "content/shell/browser/shell_browser_main_parts.h" #include "content/shell/browser/shell_devtools_delegate.h" #include "content/shell/browser/shell_message_filter.h" #include "content/shell/browser/shell_net_log.h" #include "content/shell/browser/shell_notification_manager.h" #include "content/shell/browser/shell_quota_permission_context.h" #include "content/shell/browser/shell_resource_dispatcher_host_delegate.h" #include "content/shell/browser/shell_web_contents_view_delegate_creator.h" #include "content/shell/browser/webkit_test_controller.h" #include "content/shell/common/shell_messages.h" #include "content/shell/common/shell_switches.h" #include "content/shell/common/webkit_test_helpers.h" #include "content/shell/geolocation/shell_access_token_store.h" #include "net/url_request/url_request_context_getter.h" #include "url/gurl.h" #if defined(OS_ANDROID) #include "base/android/path_utils.h" #include "components/crash/browser/crash_dump_manager_android.h" #include "content/shell/android/shell_descriptors.h" #endif #if defined(OS_POSIX) && !defined(OS_MACOSX) #include "base/debug/leak_annotations.h" #include "components/crash/app/breakpad_linux.h" #include "components/crash/browser/crash_handler_host_linux.h" #include "content/public/common/content_descriptors.h" #endif #if defined(OS_WIN) #include "content/common/sandbox_win.h" #include "sandbox/win/src/sandbox.h" #endif namespace content { namespace { ShellContentBrowserClient* g_browser_client; bool g_swap_processes_for_redirect = false; #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID) breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost( const std::string& process_type) { base::FilePath dumps_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kCrashDumpsDir); { ANNOTATE_SCOPED_MEMORY_LEAK; breakpad::CrashHandlerHostLinux* crash_handler = new breakpad::CrashHandlerHostLinux( process_type, dumps_path, false); crash_handler->StartUploaderThread(); return crash_handler; } } int GetCrashSignalFD(const CommandLine& command_line) { if (!breakpad::IsCrashReporterEnabled()) return -1; std::string process_type = command_line.GetSwitchValueASCII(switches::kProcessType); if (process_type == switches::kRendererProcess) { static breakpad::CrashHandlerHostLinux* crash_handler = NULL; if (!crash_handler) crash_handler = CreateCrashHandlerHost(process_type); return crash_handler->GetDeathSignalSocket(); } if (process_type == switches::kPluginProcess) { static breakpad::CrashHandlerHostLinux* crash_handler = NULL; if (!crash_handler) crash_handler = CreateCrashHandlerHost(process_type); return crash_handler->GetDeathSignalSocket(); } if (process_type == switches::kPpapiPluginProcess) { static breakpad::CrashHandlerHostLinux* crash_handler = NULL; if (!crash_handler) crash_handler = CreateCrashHandlerHost(process_type); return crash_handler->GetDeathSignalSocket(); } if (process_type == switches::kGpuProcess) { static breakpad::CrashHandlerHostLinux* crash_handler = NULL; if (!crash_handler) crash_handler = CreateCrashHandlerHost(process_type); return crash_handler->GetDeathSignalSocket(); } return -1; } #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID) void RequestDesktopNotificationPermissionOnIO( const GURL& source_origin, RenderFrameHost* render_frame_host, const base::Callback<void(blink::WebNotificationPermission)>& callback) { ShellNotificationManager* manager = ShellContentBrowserClient::Get()->GetShellNotificationManager(); if (manager) manager->RequestPermission(source_origin, callback); else callback.Run(blink::WebNotificationPermissionAllowed); } } // namespace ShellContentBrowserClient* ShellContentBrowserClient::Get() { return g_browser_client; } void ShellContentBrowserClient::SetSwapProcessesForRedirect(bool swap) { g_swap_processes_for_redirect = swap; } ShellContentBrowserClient::ShellContentBrowserClient() : shell_browser_main_parts_(NULL) { DCHECK(!g_browser_client); g_browser_client = this; if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) return; webkit_source_dir_ = GetWebKitRootDirFilePath(); } ShellContentBrowserClient::~ShellContentBrowserClient() { g_browser_client = NULL; } ShellNotificationManager* ShellContentBrowserClient::GetShellNotificationManager() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) return NULL; if (!shell_notification_manager_) shell_notification_manager_.reset(new ShellNotificationManager()); return shell_notification_manager_.get(); } BrowserMainParts* ShellContentBrowserClient::CreateBrowserMainParts( const MainFunctionParams& parameters) { shell_browser_main_parts_ = new ShellBrowserMainParts(parameters); return shell_browser_main_parts_; } void ShellContentBrowserClient::RenderProcessWillLaunch( RenderProcessHost* host) { if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kExposeIpcEcho)) host->AddFilter(new IPCEchoMessageFilter()); if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) return; host->AddFilter(new ShellMessageFilter( host->GetID(), BrowserContext::GetDefaultStoragePartition(browser_context()) ->GetDatabaseTracker(), BrowserContext::GetDefaultStoragePartition(browser_context()) ->GetQuotaManager(), BrowserContext::GetDefaultStoragePartition(browser_context()) ->GetURLRequestContext())); host->Send(new ShellViewMsg_SetWebKitSourceDir(webkit_source_dir_)); } net::URLRequestContextGetter* ShellContentBrowserClient::CreateRequestContext( BrowserContext* content_browser_context, ProtocolHandlerMap* protocol_handlers, URLRequestInterceptorScopedVector request_interceptors) { ShellBrowserContext* shell_browser_context = ShellBrowserContextForBrowserContext(content_browser_context); return shell_browser_context->CreateRequestContext( protocol_handlers, request_interceptors.Pass()); } net::URLRequestContextGetter* ShellContentBrowserClient::CreateRequestContextForStoragePartition( BrowserContext* content_browser_context, const base::FilePath& partition_path, bool in_memory, ProtocolHandlerMap* protocol_handlers, URLRequestInterceptorScopedVector request_interceptors) { ShellBrowserContext* shell_browser_context = ShellBrowserContextForBrowserContext(content_browser_context); return shell_browser_context->CreateRequestContextForStoragePartition( partition_path, in_memory, protocol_handlers, request_interceptors.Pass()); } bool ShellContentBrowserClient::IsHandledURL(const GURL& url) { if (!url.is_valid()) return false; DCHECK_EQ(url.scheme(), base::StringToLowerASCII(url.scheme())); // Keep in sync with ProtocolHandlers added by // ShellURLRequestContextGetter::GetURLRequestContext(). static const char* const kProtocolList[] = { url::kBlobScheme, url::kFileSystemScheme, kChromeUIScheme, kChromeDevToolsScheme, url::kDataScheme, url::kFileScheme, }; for (size_t i = 0; i < arraysize(kProtocolList); ++i) { if (url.scheme() == kProtocolList[i]) return true; } return false; } void ShellContentBrowserClient::AppendExtraCommandLineSwitches( CommandLine* command_line, int child_process_id) { if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) command_line->AppendSwitch(switches::kDumpRenderTree); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableFontAntialiasing)) command_line->AppendSwitch(switches::kEnableFontAntialiasing); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kExposeInternalsForTesting)) command_line->AppendSwitch(switches::kExposeInternalsForTesting); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kExposeIpcEcho)) command_line->AppendSwitch(switches::kExposeIpcEcho); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kStableReleaseMode)) command_line->AppendSwitch(switches::kStableReleaseMode); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableCrashReporter)) { command_line->AppendSwitch(switches::kEnableCrashReporter); } if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kCrashDumpsDir)) { command_line->AppendSwitchPath( switches::kCrashDumpsDir, CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kCrashDumpsDir)); } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableLeakDetection)) { command_line->AppendSwitchASCII( switches::kEnableLeakDetection, CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kEnableLeakDetection)); } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kRegisterFontFiles)) { command_line->AppendSwitchASCII( switches::kRegisterFontFiles, CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kRegisterFontFiles)); } } void ShellContentBrowserClient::OverrideWebkitPrefs( RenderViewHost* render_view_host, const GURL& url, WebPreferences* prefs) { if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) return; WebKitTestController::Get()->OverrideWebkitPrefs(prefs); } void ShellContentBrowserClient::ResourceDispatcherHostCreated() { resource_dispatcher_host_delegate_.reset( new ShellResourceDispatcherHostDelegate()); ResourceDispatcherHost::Get()->SetDelegate( resource_dispatcher_host_delegate_.get()); } std::string ShellContentBrowserClient::GetDefaultDownloadName() { return "download"; } WebContentsViewDelegate* ShellContentBrowserClient::GetWebContentsViewDelegate( WebContents* web_contents) { #if !defined(USE_AURA) return CreateShellWebContentsViewDelegate(web_contents); #else return NULL; #endif } QuotaPermissionContext* ShellContentBrowserClient::CreateQuotaPermissionContext() { return new ShellQuotaPermissionContext(); } void ShellContentBrowserClient::RequestDesktopNotificationPermission( const GURL& source_origin, RenderFrameHost* render_frame_host, const base::Callback<void(blink::WebNotificationPermission)>& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&RequestDesktopNotificationPermissionOnIO, source_origin, render_frame_host, callback)); } blink::WebNotificationPermission ShellContentBrowserClient::CheckDesktopNotificationPermission( const GURL& source_url, ResourceContext* context, int render_process_id) { ShellNotificationManager* manager = GetShellNotificationManager(); if (manager) return manager->CheckPermission(source_url); return blink::WebNotificationPermissionAllowed; } SpeechRecognitionManagerDelegate* ShellContentBrowserClient::GetSpeechRecognitionManagerDelegate() { return new ShellSpeechRecognitionManagerDelegate(); } net::NetLog* ShellContentBrowserClient::GetNetLog() { return shell_browser_main_parts_->net_log(); } bool ShellContentBrowserClient::ShouldSwapProcessesForRedirect( ResourceContext* resource_context, const GURL& current_url, const GURL& new_url) { return g_swap_processes_for_redirect; } DevToolsManagerDelegate* ShellContentBrowserClient::GetDevToolsManagerDelegate() { return new ShellDevToolsManagerDelegate(browser_context()); } #if defined(OS_POSIX) && !defined(OS_MACOSX) void ShellContentBrowserClient::GetAdditionalMappedFilesForChildProcess( const CommandLine& command_line, int child_process_id, std::vector<FileDescriptorInfo>* mappings) { #if defined(OS_ANDROID) int flags = base::File::FLAG_OPEN | base::File::FLAG_READ; base::FilePath pak_file; bool r = PathService::Get(base::DIR_ANDROID_APP_DATA, &pak_file); CHECK(r); pak_file = pak_file.Append(FILE_PATH_LITERAL("paks")); pak_file = pak_file.Append(FILE_PATH_LITERAL("content_shell.pak")); base::File f(pak_file, flags); if (!f.IsValid()) { NOTREACHED() << "Failed to open file when creating renderer process: " << "content_shell.pak"; } mappings->push_back( FileDescriptorInfo(kShellPakDescriptor, base::FileDescriptor(f.Pass()))); if (breakpad::IsCrashReporterEnabled()) { f = breakpad::CrashDumpManager::GetInstance()->CreateMinidumpFile( child_process_id); if (!f.IsValid()) { LOG(ERROR) << "Failed to create file for minidump, crash reporting will " << "be disabled for this process."; } else { mappings->push_back( FileDescriptorInfo(kAndroidMinidumpDescriptor, base::FileDescriptor(f.Pass()))); } } #else // !defined(OS_ANDROID) int crash_signal_fd = GetCrashSignalFD(command_line); if (crash_signal_fd >= 0) { mappings->push_back(FileDescriptorInfo( kCrashDumpSignal, base::FileDescriptor(crash_signal_fd, false))); } #endif // defined(OS_ANDROID) } #endif // defined(OS_POSIX) && !defined(OS_MACOSX) #if defined(OS_WIN) void ShellContentBrowserClient::PreSpawnRenderer(sandbox::TargetPolicy* policy, bool* success) { // Add sideloaded font files for testing. See also DIR_WINDOWS_FONTS // addition in |StartSandboxedProcess|. std::vector<std::string> font_files = GetSideloadFontFiles(); for (std::vector<std::string>::const_iterator i(font_files.begin()); i != font_files.end(); ++i) { policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, sandbox::TargetPolicy::FILES_ALLOW_READONLY, base::UTF8ToWide(*i).c_str()); } } #endif // OS_WIN ShellBrowserContext* ShellContentBrowserClient::browser_context() { return shell_browser_main_parts_->browser_context(); } ShellBrowserContext* ShellContentBrowserClient::off_the_record_browser_context() { return shell_browser_main_parts_->off_the_record_browser_context(); } AccessTokenStore* ShellContentBrowserClient::CreateAccessTokenStore() { return new ShellAccessTokenStore(browser_context()); } ShellBrowserContext* ShellContentBrowserClient::ShellBrowserContextForBrowserContext( BrowserContext* content_browser_context) { if (content_browser_context == browser_context()) return browser_context(); DCHECK_EQ(content_browser_context, off_the_record_browser_context()); return off_the_record_browser_context(); } } // namespace content
s20121035/rk3288_android5.1_repo
external/chromium_org/content/shell/browser/shell_content_browser_client.cc
C++
gpl-3.0
15,870
/////////////////////////////////////////////////////////////////////////////// // Copyright 2015 John Maddock. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/multiprecision/mpfr.hpp> #include <boost/type_traits/is_nothrow_move_constructible.hpp> #include <boost/type_traits/is_nothrow_move_assignable.hpp> #include <boost/type_traits/has_nothrow_constructor.hpp> #include <boost/type_traits/has_nothrow_assign.hpp> #include <boost/type_traits/has_nothrow_copy.hpp> #include <boost/static_assert.hpp> #ifndef BOOST_NO_CXX11_NOEXCEPT #if !defined(BOOST_NO_CXX11_NOEXCEPT) && !defined(BOOST_NO_SFINAE_EXPR) || defined(BOOST_IS_NOTHROW_MOVE_CONSTRUCT) // // Move construct: // BOOST_STATIC_ASSERT(boost::is_nothrow_move_constructible<boost::multiprecision::mpfr_float>::value); BOOST_STATIC_ASSERT(boost::is_nothrow_move_constructible<boost::multiprecision::mpfr_float_100>::value); #endif #if !defined(BOOST_NO_CXX11_NOEXCEPT) && !defined(BOOST_NO_SFINAE_EXPR) || defined(BOOST_IS_NOTHROW_MOVE_ASSIGN) // // Move assign: // BOOST_STATIC_ASSERT(boost::is_nothrow_move_assignable<boost::multiprecision::mpfr_float>::value); BOOST_STATIC_ASSERT(boost::is_nothrow_move_assignable<boost::multiprecision::mpfr_float_100>::value); #endif #endif // noexcept
gwq5210/litlib
thirdparty/sources/boost_1_60_0/libs/multiprecision/test/test_nothrow_mpfr.cpp
C++
gpl-3.0
1,382
/* This file is part of netcdf-4, a netCDF-like interface for HDF5, or a HDF5 backend for netCDF, depending on your point of view. This file handles the nc4 attribute functions. Remember that with atts, type conversion can take place when writing them, and when reading them. Copyright 2003-2005, University Corporation for Atmospheric Research. See COPYRIGHT file for copying and redistribution conditions. $Id: nc4attr.c,v 1.78 2010/05/25 17:54:23 dmh Exp $ */ #include "nc4internal.h" #include "nc.h" #include "nc4dispatch.h" #include "ncdispatch.h" #ifdef USE_PNETCDF #include <pnetcdf.h> #endif int nc4typelen(nc_type type); /* Get or put attribute metadata from our linked list of file info. Always locate the attribute by name, never by attnum. The mem_type is ignored if data=NULL. */ int nc4_get_att(int ncid, NC_FILE_INFO_T *nc, int varid, const char *name, nc_type *xtype, nc_type mem_type, size_t *lenp, int *attnum, int is_long, void *data) { NC_GRP_INFO_T *grp; NC_HDF5_FILE_INFO_T *h5; NC_ATT_INFO_T *att; int my_attnum = -1; int need_to_convert = 0; int range_error = NC_NOERR; void *bufr = NULL; size_t type_size; char norm_name[NC_MAX_NAME + 1]; int i; int retval = NC_NOERR; if (attnum) my_attnum = *attnum; assert(nc && nc->nc4_info); LOG((3, "nc4_get_att: ncid 0x%x varid %d name %s attnum %d mem_type %d", ncid, varid, name, my_attnum, mem_type)); /* Find info for this file and group, and set pointer to each. */ h5 = nc->nc4_info; if (!(grp = nc4_rec_find_grp(h5->root_grp, (ncid & GRP_ID_MASK)))) return NC_EBADGRPID; /* Normalize name. */ if ((retval = nc4_normalize_name(name, norm_name))) return retval; /* Find the attribute, if it exists. If we don't find it, we are major failures. */ if ((retval = nc4_find_grp_att(grp, varid, norm_name, my_attnum, &att))) return retval; /* If mem_type is NC_NAT, it means we want to use the attribute's * file type as the mem type as well. */ if (mem_type == NC_NAT) mem_type = att->xtype; /* If the attribute is NC_CHAR, and the mem_type isn't, or vice * versa, that's a freakish attempt to convert text to * numbers. Some pervert out there is trying to pull a fast one! * Send him an NC_ECHAR error...*/ if (data && att->len && ((att->xtype == NC_CHAR && mem_type != NC_CHAR) || (att->xtype != NC_CHAR && mem_type == NC_CHAR))) return NC_ECHAR; /* take that, you freak! */ /* Copy the info. */ if (lenp) *lenp = att->len; if (xtype) *xtype = att->xtype; if (attnum) *attnum = att->attnum; /* Zero len attributes are easy to read! */ if (!att->len) return NC_NOERR; /* Later on, we will need to know the size of this type. */ if ((retval = nc4_get_typelen_mem(h5, mem_type, is_long, &type_size))) return retval; /* We may have to convert data. Treat NC_CHAR the same as * NC_UBYTE. If the mem_type is NAT, don't try any conversion - use * the attribute's type. */ if (data && att->len && mem_type != att->xtype && mem_type != NC_NAT && !(mem_type == NC_CHAR && (att->xtype == NC_UBYTE || att->xtype == NC_BYTE))) { need_to_convert++; if (!(bufr = malloc((size_t)(att->len * type_size)))) return NC_ENOMEM; if ((retval = nc4_convert_type(att->data, bufr, att->xtype, mem_type, (size_t)att->len, &range_error, NULL, (h5->cmode & NC_CLASSIC_MODEL), 0, is_long))) BAIL(retval); /* For strict netcdf-3 rules, ignore erange errors between UBYTE * and BYTE types. */ if ((h5->cmode & NC_CLASSIC_MODEL) && (att->xtype == NC_UBYTE || att->xtype == NC_BYTE) && (mem_type == NC_UBYTE || mem_type == NC_BYTE) && range_error) range_error = 0; } else { bufr = att->data; } /* If the caller wants data, copy it for him. If he hasn't allocated enough memory for it, he will burn in segmantation fault hell, writhing with the agony of undiscovered memory bugs! */ if (data) { if (att->vldata) { size_t base_typelen = type_size; hvl_t *vldest = data; NC_TYPE_INFO_T *type; if ((retval = nc4_find_type(h5, att->xtype, &type))) return retval; for (i = 0; i < att->len; i++) { vldest[i].len = att->vldata[i].len; if (!(vldest[i].p = malloc(vldest[i].len * base_typelen))) BAIL(NC_ENOMEM); memcpy(vldest[i].p, att->vldata[i].p, vldest[i].len * base_typelen); } } else if (att->stdata) { for (i = 0; i < att->len; i++) { if (!(((char **)data)[i] = malloc(strlen(att->stdata[i]) + 1))) BAIL(NC_ENOMEM); strcpy(((char **)data)[i], att->stdata[i]); } } else { /* For long types, we need to handle this special... */ if (is_long && att->xtype == NC_INT) { long *lp = data; int *ip = bufr; for (i = 0; i < att->len; i++) *lp++ = *ip++; } else memcpy(data, bufr, (size_t)(att->len * type_size)); } } exit: if (need_to_convert) free(bufr); if (retval) return retval; if (range_error) return NC_ERANGE; return NC_NOERR; } /* Put attribute metadata into our global metadata. */ int nc4_put_att(int ncid, NC_FILE_INFO_T *nc, int varid, const char *name, nc_type file_type, nc_type mem_type, size_t len, int is_long, const void *data) { NC_GRP_INFO_T *grp; NC_HDF5_FILE_INFO_T *h5; NC_VAR_INFO_T *var = NULL; NC_ATT_INFO_T *att, **attlist = NULL, *varatt; NC_TYPE_INFO_T *type = NULL; char norm_name[NC_MAX_NAME + 1]; int new_att = 0; int retval = NC_NOERR, range_error = 0; size_t type_size; int i; int res; if (!name) return NC_EBADNAME; assert(nc && nc->nc4_info); LOG((1, "nc4_put_att: ncid 0x%x varid %d name %s " "file_type %d mem_type %d len %d", ncid, varid, name, file_type, mem_type, len)); /* If len is not zero, then there must be some data. */ if (len && !data) return NC_EINVAL; /* Find info for this file and group, and set pointer to each. */ h5 = nc->nc4_info; if (!(grp = nc4_rec_find_grp(h5->root_grp, (ncid & GRP_ID_MASK)))) return NC_EBADGRPID; /* If the file is read-only, return an error. */ if (h5->no_write) return NC_EPERM; /* Check and normalize the name. */ if ((retval = nc4_check_name(name, norm_name))) return retval; /* Find att, if it exists. */ if (varid == NC_GLOBAL) attlist = &grp->att; else { for (var = grp->var; var; var = var->next) if (var->varid == varid) { attlist = &var->att; break; } if (!var) return NC_ENOTVAR; } for (att = *attlist; att; att = att->next) if (!strcmp(att->name, norm_name)) break; if (!att) { /* If this is a new att, require define mode. */ if (!(h5->flags & NC_INDEF)) { if (h5->cmode & NC_CLASSIC_MODEL) return NC_EINDEFINE; if ((retval = NC4_redef(ncid))) BAIL(retval); } new_att++; } else { /* For an existing att, if we're not in define mode, the len must not be greater than the existing len for classic model. */ if (!(h5->flags & NC_INDEF) && len * nc4typelen(file_type) > (size_t)att->len * nc4typelen(att->xtype)) { if (h5->cmode & NC_CLASSIC_MODEL) return NC_EINDEFINE; if ((retval = nc_enddef(ncid))) BAIL(retval); } } /* We must have two valid types to continue. */ if (file_type == NC_NAT || mem_type == NC_NAT) return NC_EBADTYPE; /* Get information about this type. */ if ((retval = nc4_find_type(h5, file_type, &type))) return retval; if ((retval = nc4_get_typelen_mem(h5, file_type, is_long, &type_size))) return retval; /* No character conversions are allowed. */ if (file_type != mem_type && (file_type == NC_CHAR || mem_type == NC_CHAR || file_type == NC_STRING || mem_type == NC_STRING)) return NC_ECHAR; /* For classic mode file, only allow atts with classic types to be * created. */ if (h5->cmode & NC_CLASSIC_MODEL && file_type > NC_DOUBLE) return NC_ESTRICTNC3; /* Add to the end of the attribute list, if this att doesn't already exist. */ if (new_att) { LOG((3, "adding attribute %s to the list...", norm_name)); if ((res = nc4_att_list_add(attlist))) BAIL (res); /* Find this att's entry in the list (the last one). */ for (att=*attlist; att->next; att=att->next) ; } /* Now fill in the metadata. */ att->dirty++; if (att->name) free(att->name); if (!(att->name = malloc((strlen(norm_name) + 1) * sizeof(char)))) return NC_ENOMEM; strcpy(att->name, norm_name); att->xtype = file_type; att->len = len; if (att->prev) att->attnum = att->prev->attnum + 1; else att->attnum = 0; if (type) att->class = type->class; /* If this is the _FillValue attribute, then we will also have to * copy the value to the fll_vlue pointer of the NC_VAR_INFO_T * struct for this var. (But ignore a global _FillValue * attribute). */ if (!strcmp(att->name, _FillValue) && varid != NC_GLOBAL) { NC_TYPE_INFO_T *type_info; int size; /* Fill value must be same type. */ if (att->xtype != var->xtype) return NC_EINVAL; /* If we already wrote to the dataset, then return an error. */ if (var->written_to) return NC_ELATEFILL; /* If fill value hasn't been set, allocate space. Of course, * vlens have to be differnt... */ if ((retval = nc4_get_typelen_mem(grp->file->nc4_info, var->xtype, 0, &type_size))) return retval; if ((retval = nc4_find_type(grp->file->nc4_info, var->xtype, &type_info))) BAIL(retval); /* Already set a fill value? Now I'll have to free the old * one. Make up your damn mind, would you? */ if (var->fill_value) { if (type_info && type_info->class == NC_VLEN) if ((retval = nc_free_vlen(var->fill_value))) return retval; free(var->fill_value); } /* Allocate space for the fill value. */ if (type_info && type_info->class == NC_VLEN) size = sizeof(hvl_t); else if (var->xtype == NC_STRING) size = sizeof(char *); else size = type_size; /* size = strlen(*(char **)data) + 1; */ if (!(var->fill_value = malloc(size))) return NC_ENOMEM; /* Copy the fill_value. */ LOG((4, "Copying fill value into metadata for variable %s", var->name)); if (type_info && type_info->class == NC_VLEN) { nc_vlen_t *in_vlen = (nc_vlen_t *)data, *fv_vlen = (nc_vlen_t *)(var->fill_value); fv_vlen->len = in_vlen->len; if (!(fv_vlen->p = malloc(size * in_vlen->len))) return NC_ENOMEM; memcpy(fv_vlen->p, in_vlen->p, in_vlen->len * size); } else if (var->xtype == NC_STRING) { if (!(*(char **)var->fill_value = malloc(strlen(*(char **)data) + 1))) return NC_ENOMEM; strcpy(*(char **)(var->fill_value), *(char **)data); } else memcpy(var->fill_value, data, type_size); /* Mark the var and all its atts as dirty, so they get * rewritten. */ var->dirty++; for (varatt = var->att; varatt; varatt = varatt->next) varatt->dirty++; } /* Copy the attribute data, if there is any. VLENs and string * arrays have to be handled specially. */ if (type && type->class == NC_VLEN && data && att->len) { const hvl_t *vldata1; vldata1 = data; if (!(att->vldata = malloc(att->len * sizeof(hvl_t)))) BAIL(NC_ENOMEM); for (i = 0; i < att->len; i++) { att->vldata[i].len = vldata1[i].len; if (!(att->vldata[i].p = malloc(type_size * att->vldata[i].len))) BAIL(NC_ENOMEM); memcpy(att->vldata[i].p, vldata1[i].p, type_size * att->vldata[i].len); } } else if (file_type == NC_STRING && data && att->len) { LOG((4, "copying array of NC_STRING")); if (!(att->stdata = malloc(sizeof(char *) * att->len))) BAIL(NC_ENOMEM); for (i = 0; i < att->len; i++) { LOG((5, "copying string %d of size %d", i, strlen(((char **)data)[i]) + 1)); if (!(att->stdata[i] = malloc(strlen(((char **)data)[i]) + 1))) BAIL(NC_ENOMEM); strcpy(att->stdata[i], ((char **)data)[i]); } } else { /* Data types are like religions, in that one can convert. */ if (att->len) { if (!new_att) free (att->data); if (!(att->data = malloc(att->len * type_size))) BAIL(NC_ENOMEM); if (type) { /* Just copy the data... */ if (type->class == NC_OPAQUE || type->class == NC_COMPOUND || type->class == NC_ENUM) memcpy(att->data, data, len * type_size); else LOG((0, "nc4_put_att: unknown type.")); } else { if ((retval = nc4_convert_type(data, att->data, mem_type, file_type, len, &range_error, NULL, (h5->cmode & NC_CLASSIC_MODEL), is_long, 0))) BAIL(retval); } } } att->dirty = 1; att->created = 0; exit: /* If there was an error return it, otherwise return any potential range error value. If none, return NC_NOERR as usual.*/ if (retval) return retval; if (range_error) return NC_ERANGE; return NC_NOERR; } /* Learn about an att. All the nc4 nc_inq_ functions just call * add_meta_get to get the metadata on an attribute. */ int NC4_inq_att(int ncid, int varid, const char *name, nc_type *xtypep, size_t *lenp) { NC_FILE_INFO_T *nc; LOG((2, "nc_inq_att: ncid 0x%x varid %d name %s", ncid, varid, name)); /* Find metadata. */ if (!(nc = nc4_find_nc_file(ncid))) return NC_EBADID; #ifdef USE_PNETCDF /* Take care of files created/opened with parallel-netcdf library. */ if (nc->pnetcdf_file) { MPI_Offset mpi_len; int ret; if ((ret = ncmpi_inq_att(nc->int_ncid, varid, name, xtypep, &mpi_len))) return ret; if (lenp) *lenp = mpi_len; } #endif /* USE_PNETCDF */ /* Handle netcdf-3 files. */ assert(nc->nc4_info); /* Handle netcdf-4 files. */ return nc4_get_att(ncid, nc, varid, name, xtypep, NC_UBYTE, lenp, NULL, 0, NULL); } /* Learn an attnum, given a name. */ int NC4_inq_attid(int ncid, int varid, const char *name, int *attnump) { NC_FILE_INFO_T *nc; LOG((2, "nc_inq_attid: ncid 0x%x varid %d name %s", ncid, varid, name)); /* Find metadata. */ if (!(nc = nc4_find_nc_file(ncid))) return NC_EBADID; #ifdef USE_PNETCDF /* Take care of files created/opened with parallel-netcdf library. */ if (nc->pnetcdf_file) return ncmpi_inq_attid(nc->int_ncid, varid, name, attnump); #endif /* USE_PNETCDF */ /* Handle netcdf-3 files. */ assert(nc->nc4_info); /* Handle netcdf-4 files. */ return nc4_get_att(ncid, nc, varid, name, NULL, NC_UBYTE, NULL, attnump, 0, NULL); } /* Given an attnum, find the att's name. */ int NC4_inq_attname(int ncid, int varid, int attnum, char *name) { NC_FILE_INFO_T *nc; NC_ATT_INFO_T *att; int retval = NC_NOERR; LOG((2, "nc_inq_attname: ncid 0x%x varid %d attnum %d", ncid, varid, attnum)); /* Find metadata. */ if (!(nc = nc4_find_nc_file(ncid))) return NC_EBADID; #ifdef USE_PNETCDF /* Take care of files created/opened with parallel-netcdf library. */ if (nc->pnetcdf_file) return ncmpi_inq_attname(nc->int_ncid, varid, attnum, name); #endif /* USE_PNETCDF */ /* Handle netcdf-3 files. */ assert(nc->nc4_info); /* Handle netcdf-4 files. */ if ((retval = nc4_find_nc_att(ncid, varid, NULL, attnum, &att))) return retval; /* Get the name. */ if (name) strcpy(name, att->name); return NC_NOERR; } /* I think all atts should be named the exact same thing, to avoid confusion! */ int NC4_rename_att(int ncid, int varid, const char *name, const char *newname) { NC_FILE_INFO_T *nc; NC_GRP_INFO_T *grp; NC_HDF5_FILE_INFO_T *h5; NC_VAR_INFO_T *var; NC_ATT_INFO_T *att, *list; char norm_newname[NC_MAX_NAME + 1], norm_name[NC_MAX_NAME + 1]; hid_t datasetid = 0; int retval = NC_NOERR; if (!name || !newname) return NC_EINVAL; LOG((2, "nc_rename_att: ncid 0x%x varid %d name %s newname %s", ncid, varid, name, newname)); /* If the new name is too long, that's an error. */ if (strlen(newname) > NC_MAX_NAME) return NC_EMAXNAME; /* Find metadata for this file. */ if ((retval = nc4_find_nc_grp_h5(ncid, &nc, &grp, &h5))) return retval; #ifdef USE_PNETCDF /* Take care of files created/opened with parallel-netcdf library. */ if (nc->pnetcdf_file) return ncmpi_rename_att(nc->int_ncid, varid, name, newname); #endif /* USE_PNETCDF */ /* Handle netcdf-3 files. */ assert(h5); /* If the file is read-only, return an error. */ if (h5->no_write) return NC_EPERM; /* Check and normalize the name. */ if ((retval = nc4_check_name(newname, norm_newname))) return retval; /* Is norm_newname in use? */ if (varid == NC_GLOBAL) { list = grp->att; } else { for (var = grp->var; var; var = var->next) if (var->varid == varid) { list = var->att; break; } if (!var) return NC_ENOTVAR; } for (att = list; att; att = att->next) if (!strncmp(att->name, norm_newname, NC_MAX_NAME)) return NC_ENAMEINUSE; /* Normalize name and find the attribute. */ if ((retval = nc4_normalize_name(name, norm_name))) return retval; for (att = list; att; att = att->next) if (!strncmp(att->name, norm_name, NC_MAX_NAME)) break; if (!att) return NC_ENOTATT; /* If we're not in define mode, new name must be of equal or less size, if complying with strict NC3 rules. */ if (!(h5->flags & NC_INDEF) && strlen(norm_newname) > strlen(att->name) && (h5->cmode & NC_CLASSIC_MODEL)) return NC_ENOTINDEFINE; /* Delete the original attribute, if it exists in the HDF5 file. */ if (att->created) { if (varid == NC_GLOBAL) { if (H5Adelete(grp->hdf_grpid, att->name) < 0) return NC_EHDFERR; } else { if ((retval = nc4_open_var_grp2(grp, varid, &datasetid))) return retval; if (H5Adelete(datasetid, att->name) < 0) return NC_EHDFERR; } att->created = 0; } /* Copy the new name into our metadata. */ free(att->name); if (!(att->name = malloc((strlen(norm_newname) + 1) * sizeof(char)))) return NC_ENOMEM; strcpy(att->name, norm_newname); att->dirty = 1; return retval; } /* Delete an att. Rub it out. Push the button on it. Liquidate it. Bump it off. Take it for a one-way ride. Terminate it. Drop the bomb on it. You get the idea. Ed Hartnett, 10/1/3 */ int NC4_del_att(int ncid, int varid, const char *name) { NC_FILE_INFO_T *nc; NC_GRP_INFO_T *grp; NC_HDF5_FILE_INFO_T *h5; NC_ATT_INFO_T *att, *natt; NC_VAR_INFO_T *var; NC_ATT_INFO_T **attlist = NULL; hid_t locid = 0, datasetid = 0; int retval = NC_NOERR; if (!name) return NC_EINVAL; LOG((2, "nc_del_att: ncid 0x%x varid %d name %s", ncid, varid, name)); /* Find metadata for this file. */ if ((retval = nc4_find_nc_grp_h5(ncid, &nc, &grp, &h5))) return retval; #ifdef USE_PNETCDF /* Take care of files created/opened with parallel-netcdf library. */ if (nc->pnetcdf_file) return ncmpi_del_att(nc->int_ncid, varid, name); #endif /* USE_PNETCDF */ /* Handle netcdf-3 files. */ assert(h5); assert(h5 && grp); /* If the file is read-only, return an error. */ if (h5->no_write) return NC_EPERM; /* If it's not in define mode, forget it. */ if (!(h5->flags & NC_INDEF)) { if (h5->cmode & NC_CLASSIC_MODEL) return NC_ENOTINDEFINE; if ((retval = NC4_redef(ncid))) BAIL(retval); } /* Get either the global or a variable attribute list. Also figure out the HDF5 location it's attached to. */ if (varid == NC_GLOBAL) { attlist = &grp->att; locid = grp->hdf_grpid; } else { for(var = grp->var; var; var = var->next) { if (var->varid == varid) { attlist = &var->att; break; } } if (!var) return NC_ENOTVAR; if (var->created) { locid = var->hdf_datasetid; } } /* Now find the attribute by name or number. */ for (att = *attlist; att; att = att->next) if (!strcmp(att->name, name)) break; /* If att is NULL, we couldn't find the attribute. */ if (!att) BAIL_QUIET(NC_ENOTATT); /* Delete it from the HDF5 file, if it's been created. */ if (att->created) if(H5Adelete(locid, att->name) < 0) BAIL(NC_EATTMETA); /* Renumber all following attributes. */ for (natt = att->next; natt; natt = natt->next) natt->attnum--; /* Delete this attribute from this list. */ if ((retval = nc4_att_list_del(attlist, att))) BAIL(retval); exit: if (datasetid > 0) H5Dclose(datasetid); return retval; } /* Write an attribute with type conversion. */ int nc4_put_att_tc(int ncid, int varid, const char *name, nc_type file_type, nc_type mem_type, int mem_type_is_long, size_t len, const void *op) { NC_FILE_INFO_T *nc; if (!name || strlen(name) > NC_MAX_NAME) return NC_EBADNAME; LOG((3, "nc4_put_att_tc: ncid 0x%x varid %d name %s file_type %d " "mem_type %d len %d", ncid, varid, name, file_type, mem_type, len)); /* The length needs to be positive (cast needed for braindead systems with signed size_t). */ if((unsigned long) len > X_INT_MAX) return NC_EINVAL; /* Find metadata. */ if (!(nc = nc4_find_nc_file(ncid))) return NC_EBADID; #ifdef USE_PNETCDF /* Take care of files created/opened with parallel-netcdf library. */ if (nc->pnetcdf_file) { if (mem_type == NC_UBYTE) mem_type = NC_BYTE; switch(mem_type) { case NC_BYTE: return ncmpi_put_att_schar(nc->int_ncid, varid, name, file_type, len, op); case NC_CHAR: return ncmpi_put_att_text(nc->int_ncid, varid, name, len, op); case NC_SHORT: return ncmpi_put_att_short(nc->int_ncid, varid, name, file_type, len, op); case NC_INT: if (mem_type_is_long) return ncmpi_put_att_long(nc->int_ncid, varid, name, file_type, len, op); else return ncmpi_put_att_int(nc->int_ncid, varid, name, file_type, len, op); case NC_FLOAT: return ncmpi_put_att_float(nc->int_ncid, varid, name, file_type, len, op); case NC_DOUBLE: return ncmpi_put_att_double(nc->int_ncid, varid, name, file_type, len, op); case NC_NAT: default: return NC_EBADTYPE; } } #endif /* USE_PNETCDF */ /* Handle netcdf-3 files. */ assert(nc->nc4_info); /* Otherwise, handle things the netcdf-4 way. */ return nc4_put_att(ncid, nc, varid, name, file_type, mem_type, len, mem_type_is_long, op); } /* Read an attribute of any type, with type conversion. This may be * called by any of the nc_get_att_* functions. */ int nc4_get_att_tc(int ncid, int varid, const char *name, nc_type mem_type, int mem_type_is_long, void *ip) { NC_FILE_INFO_T *nc; LOG((3, "nc4_get_att_tc: ncid 0x%x varid %d name %s mem_type %d", ncid, varid, name, mem_type)); /* Find metadata. */ if (!(nc = nc4_find_nc_file(ncid))) return NC_EBADID; #ifdef USE_PNETCDF /* Take care of files created/opened with parallel-netcdf library. */ if (nc->pnetcdf_file) { if (mem_type == NC_UBYTE) mem_type = NC_BYTE; switch(mem_type) { case NC_BYTE: return ncmpi_get_att_schar(nc->int_ncid, varid, name, ip); case NC_CHAR: return ncmpi_get_att_text(nc->int_ncid, varid, name, ip); case NC_SHORT: return ncmpi_get_att_short(nc->int_ncid, varid, name, ip); case NC_INT: if (mem_type_is_long) return ncmpi_get_att_long(nc->int_ncid, varid, name, ip); else return ncmpi_get_att_int(nc->int_ncid, varid, name, ip); case NC_FLOAT: return ncmpi_get_att_float(nc->int_ncid, varid, name, ip); case NC_DOUBLE: return ncmpi_get_att_double(nc->int_ncid, varid, name, ip); case NC_NAT: default: return NC_EBADTYPE; } } #endif /* USE_PNETCDF */ /* Handle netcdf-3 files. */ assert(nc->nc4_info); return nc4_get_att(ncid, nc, varid, name, NULL, mem_type, NULL, NULL, mem_type_is_long, ip); } int NC4_put_att(int ncid, int varid, const char *name, nc_type xtype, size_t nelems, const void *value, nc_type memtype) { return nc4_put_att_tc(ncid, varid, name, xtype, memtype, 0, nelems, value); } int NC4_get_att(int ncid, int varid, const char *name, void *value, nc_type memtype) { return nc4_get_att_tc(ncid, varid, name, memtype, 0, value); }
MengbinZhu/pfldp
ropp-7.0/netcdf-4.1.3/libsrc4/nc4attr.c
C
gpl-3.0
25,049
<?php /* @version v5.20.16 12-Jan-2020 @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved. @copyright (c) 2014 Damien Regad, Mark Newnham and the ADOdb community Released under both BSD license and Lesser GPL library license. Whenever there is any discrepancy between the two licenses, the BSD license will take precedence. Latest version is available at http://adodb.org/ SQLite info: http://www.hwaci.com/sw/sqlite/ Install Instructions: ==================== 1. Place this in adodb/drivers 2. Rename the file, remove the .txt prefix. */ // security - hide paths if (!defined('ADODB_DIR')) die(); class ADODB_sqlite3 extends ADOConnection { var $databaseType = "sqlite3"; var $replaceQuote = "''"; // string to use to replace quotes var $concat_operator='||'; var $_errorNo = 0; var $hasLimit = true; var $hasInsertID = true; /// supports autoincrement ID? var $hasAffectedRows = true; /// supports affected rows for update/delete? var $metaTablesSQL = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"; var $sysDate = "adodb_date('Y-m-d')"; var $sysTimeStamp = "adodb_date('Y-m-d H:i:s')"; var $fmtTimeStamp = "'Y-m-d H:i:s'"; function __construct() { } function ServerInfo() { $version = SQLite3::version(); $arr['version'] = $version['versionString']; $arr['description'] = 'SQLite 3'; return $arr; } function BeginTrans() { if ($this->transOff) { return true; } $ret = $this->Execute("BEGIN TRANSACTION"); $this->transCnt += 1; return true; } function CommitTrans($ok=true) { if ($this->transOff) { return true; } if (!$ok) { return $this->RollbackTrans(); } $ret = $this->Execute("COMMIT"); if ($this->transCnt > 0) { $this->transCnt -= 1; } return !empty($ret); } function RollbackTrans() { if ($this->transOff) { return true; } $ret = $this->Execute("ROLLBACK"); if ($this->transCnt > 0) { $this->transCnt -= 1; } return !empty($ret); } // mark newnham function MetaColumns($table, $normalize=true) { global $ADODB_FETCH_MODE; $false = false; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; if ($this->fetchMode !== false) { $savem = $this->SetFetchMode(false); } $rs = $this->Execute("PRAGMA table_info('$table')"); if (isset($savem)) { $this->SetFetchMode($savem); } if (!$rs) { $ADODB_FETCH_MODE = $save; return $false; } $arr = array(); while ($r = $rs->FetchRow()) { $type = explode('(',$r['type']); $size = ''; if (sizeof($type)==2) { $size = trim($type[1],')'); } $fn = strtoupper($r['name']); $fld = new ADOFieldObject; $fld->name = $r['name']; $fld->type = $type[0]; $fld->max_length = $size; $fld->not_null = $r['notnull']; $fld->default_value = $r['dflt_value']; $fld->scale = 0; if (isset($r['pk']) && $r['pk']) { $fld->primary_key=1; } if ($save == ADODB_FETCH_NUM) { $arr[] = $fld; } else { $arr[strtoupper($fld->name)] = $fld; } } $rs->Close(); $ADODB_FETCH_MODE = $save; return $arr; } function _init($parentDriver) { $parentDriver->hasTransactions = false; $parentDriver->hasInsertID = true; } function _insertid() { return $this->_connectionID->lastInsertRowID(); } function _affectedrows() { return $this->_connectionID->changes(); } function ErrorMsg() { if ($this->_logsql) { return $this->_errorMsg; } return ($this->_errorNo) ? $this->ErrorNo() : ''; //**tochange? } function ErrorNo() { return $this->_connectionID->lastErrorCode(); //**tochange?? } function SQLDate($fmt, $col=false) { $fmt = $this->qstr($fmt); return ($col) ? "adodb_date2($fmt,$col)" : "adodb_date($fmt)"; } function _createFunctions() { $this->_connectionID->createFunction('adodb_date', 'adodb_date', 1); $this->_connectionID->createFunction('adodb_date2', 'adodb_date2', 2); } // returns true or false function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) { if (empty($argHostname) && $argDatabasename) { $argHostname = $argDatabasename; } $this->_connectionID = new SQLite3($argHostname); $this->_createFunctions(); return true; } // returns true or false function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) { // There's no permanent connect in SQLite3 return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename); } // returns query ID if successful, otherwise false function _query($sql,$inputarr=false) { $rez = $this->_connectionID->query($sql); if ($rez === false) { $this->_errorNo = $this->_connectionID->lastErrorCode(); } // If no data was returned, we don't need to create a real recordset elseif ($rez->numColumns() == 0) { $rez->finalize(); $rez = true; } return $rez; } function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) { $nrows = (int) $nrows; $offset = (int) $offset; $offsetStr = ($offset >= 0) ? " OFFSET $offset" : ''; $limitStr = ($nrows >= 0) ? " LIMIT $nrows" : ($offset >= 0 ? ' LIMIT 999999999' : ''); if ($secs2cache) { $rs = $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr); } else { $rs = $this->Execute($sql."$limitStr$offsetStr",$inputarr); } return $rs; } /* This algorithm is not very efficient, but works even if table locking is not available. Will return false if unable to generate an ID after $MAXLOOPS attempts. */ var $_genSeqSQL = "create table %s (id integer)"; function GenID($seq='adodbseq',$start=1) { // if you have to modify the parameter below, your database is overloaded, // or you need to implement generation of id's yourself! $MAXLOOPS = 100; //$this->debug=1; while (--$MAXLOOPS>=0) { @($num = $this->GetOne("select id from $seq")); if ($num === false) { $this->Execute(sprintf($this->_genSeqSQL ,$seq)); $start -= 1; $num = '0'; $ok = $this->Execute("insert into $seq values($start)"); if (!$ok) { return false; } } $this->Execute("update $seq set id=id+1 where id=$num"); if ($this->affected_rows() > 0) { $num += 1; $this->genID = $num; return $num; } } if ($fn = $this->raiseErrorFn) { $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num); } return false; } function CreateSequence($seqname='adodbseq',$start=1) { if (empty($this->_genSeqSQL)) { return false; } $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname)); if (!$ok) { return false; } $start -= 1; return $this->Execute("insert into $seqname values($start)"); } var $_dropSeqSQL = 'drop table %s'; function DropSequence($seqname = 'adodbseq') { if (empty($this->_dropSeqSQL)) { return false; } return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); } // returns true or false function _close() { return $this->_connectionID->close(); } function MetaIndexes($table, $primary = FALSE, $owner = false) { $false = false; // save old fetch mode global $ADODB_FETCH_MODE; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; if ($this->fetchMode !== FALSE) { $savem = $this->SetFetchMode(FALSE); } $SQL=sprintf("SELECT name,sql FROM sqlite_master WHERE type='index' AND tbl_name='%s'", strtolower($table)); $rs = $this->Execute($SQL); if (!is_object($rs)) { if (isset($savem)) { $this->SetFetchMode($savem); } $ADODB_FETCH_MODE = $save; return $false; } $indexes = array (); while ($row = $rs->FetchRow()) { if ($primary && preg_match("/primary/i",$row[1]) == 0) { continue; } if (!isset($indexes[$row[0]])) { $indexes[$row[0]] = array( 'unique' => preg_match("/unique/i",$row[1]), 'columns' => array() ); } /** * There must be a more elegant way of doing this, * the index elements appear in the SQL statement * in cols[1] between parentheses * e.g CREATE UNIQUE INDEX ware_0 ON warehouse (org,warehouse) */ $cols = explode("(",$row[1]); $cols = explode(")",$cols[1]); array_pop($cols); $indexes[$row[0]]['columns'] = $cols; } if (isset($savem)) { $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; } return $indexes; } } /*-------------------------------------------------------------------------------------- Class Name: Recordset --------------------------------------------------------------------------------------*/ class ADORecordset_sqlite3 extends ADORecordSet { var $databaseType = "sqlite3"; var $bind = false; function __construct($queryID,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; $mode = $ADODB_FETCH_MODE; } switch($mode) { case ADODB_FETCH_NUM: $this->fetchMode = SQLITE3_NUM; break; case ADODB_FETCH_ASSOC: $this->fetchMode = SQLITE3_ASSOC; break; default: $this->fetchMode = SQLITE3_BOTH; break; } $this->adodbFetchMode = $mode; $this->_queryID = $queryID; $this->_inited = true; $this->fields = array(); if ($queryID) { $this->_currentRow = 0; $this->EOF = !$this->_fetch(); @$this->_initrs(); } else { $this->_numOfRows = 0; $this->_numOfFields = 0; $this->EOF = true; } return $this->_queryID; } function FetchField($fieldOffset = -1) { $fld = new ADOFieldObject; $fld->name = $this->_queryID->columnName($fieldOffset); $fld->type = 'VARCHAR'; $fld->max_length = -1; return $fld; } function _initrs() { $this->_numOfFields = $this->_queryID->numColumns(); } function Fields($colname) { if ($this->fetchMode != SQLITE3_NUM) { return $this->fields[$colname]; } if (!$this->bind) { $this->bind = array(); for ($i=0; $i < $this->_numOfFields; $i++) { $o = $this->FetchField($i); $this->bind[strtoupper($o->name)] = $i; } } return $this->fields[$this->bind[strtoupper($colname)]]; } function _seek($row) { // sqlite3 does not implement seek if ($this->debug) { ADOConnection::outp("SQLite3 does not implement seek"); } return false; } function _fetch($ignore_fields=false) { $this->fields = $this->_queryID->fetchArray($this->fetchMode); return !empty($this->fields); } function _close() { } }
evltuma/moodle
lib/adodb/drivers/adodb-sqlite3.inc.php
PHP
gpl-3.0
10,353
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use Iterator; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * @implements Iterator<string, Column> */ class ColumnIterator implements Iterator { /** * Worksheet to iterate. * * @var Worksheet */ private $worksheet; /** * Current iterator position. * * @var int */ private $currentColumnIndex = 1; /** * Start position. * * @var int */ private $startColumnIndex = 1; /** * End position. * * @var int */ private $endColumnIndex = 1; /** * Create a new column iterator. * * @param Worksheet $worksheet The worksheet to iterate over * @param string $startColumn The column address at which to start iterating * @param string $endColumn Optionally, the column address at which to stop iterating */ public function __construct(Worksheet $worksheet, $startColumn = 'A', $endColumn = null) { // Set subject $this->worksheet = $worksheet; $this->resetEnd($endColumn); $this->resetStart($startColumn); } /** * Destructor. */ public function __destruct() { // @phpstan-ignore-next-line $this->worksheet = null; } /** * (Re)Set the start column and the current column pointer. * * @param string $startColumn The column address at which to start iterating * * @return $this */ public function resetStart(string $startColumn = 'A') { $startColumnIndex = Coordinate::columnIndexFromString($startColumn); if ($startColumnIndex > Coordinate::columnIndexFromString($this->worksheet->getHighestColumn())) { throw new Exception( "Start column ({$startColumn}) is beyond highest column ({$this->worksheet->getHighestColumn()})" ); } $this->startColumnIndex = $startColumnIndex; if ($this->endColumnIndex < $this->startColumnIndex) { $this->endColumnIndex = $this->startColumnIndex; } $this->seek($startColumn); return $this; } /** * (Re)Set the end column. * * @param string $endColumn The column address at which to stop iterating * * @return $this */ public function resetEnd($endColumn = null) { $endColumn = $endColumn ?: $this->worksheet->getHighestColumn(); $this->endColumnIndex = Coordinate::columnIndexFromString($endColumn); return $this; } /** * Set the column pointer to the selected column. * * @param string $column The column address to set the current pointer at * * @return $this */ public function seek(string $column = 'A') { $column = Coordinate::columnIndexFromString($column); if (($column < $this->startColumnIndex) || ($column > $this->endColumnIndex)) { throw new PhpSpreadsheetException( "Column $column is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})" ); } $this->currentColumnIndex = $column; return $this; } /** * Rewind the iterator to the starting column. */ public function rewind(): void { $this->currentColumnIndex = $this->startColumnIndex; } /** * Return the current column in this worksheet. */ public function current(): Column { return new Column($this->worksheet, Coordinate::stringFromColumnIndex($this->currentColumnIndex)); } /** * Return the current iterator key. */ public function key(): string { return Coordinate::stringFromColumnIndex($this->currentColumnIndex); } /** * Set the iterator to its next value. */ public function next(): void { ++$this->currentColumnIndex; } /** * Set the iterator to its previous value. */ public function prev(): void { --$this->currentColumnIndex; } /** * Indicate if more columns exist in the worksheet range of columns that we're iterating. */ public function valid(): bool { return $this->currentColumnIndex <= $this->endColumnIndex && $this->currentColumnIndex >= $this->startColumnIndex; } }
collectiveaccess/pawtucket2
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnIterator.php
PHP
gpl-3.0
4,460
import mock import pytest import yaml import inspect import collections from ansible.module_utils.six import string_types from ansible.modules.cloud.openstack import os_server class AnsibleFail(Exception): pass class AnsibleExit(Exception): pass def params_from_doc(func): '''This function extracts the docstring from the specified function, parses it as a YAML document, and returns parameters for the os_server module.''' doc = inspect.getdoc(func) cfg = yaml.load(doc) for task in cfg: for module, params in task.items(): for k, v in params.items(): if k in ['nics'] and isinstance(v, string_types): params[k] = [v] task[module] = collections.defaultdict(str, params) return cfg[0]['os_server'] class FakeCloud (object): ports = [ {'name': 'port1', 'id': '1234'}, {'name': 'port2', 'id': '4321'}, ] networks = [ {'name': 'network1', 'id': '5678'}, {'name': 'network2', 'id': '8765'}, ] images = [ {'name': 'cirros', 'id': '1'}, {'name': 'fedora', 'id': '2'}, ] flavors = [ {'name': 'm1.small', 'id': '1', 'flavor_ram': 1024}, {'name': 'm1.tiny', 'id': '2', 'flavor_ram': 512}, ] def _find(self, source, name): for item in source: if item['name'] == name or item['id'] == name: return item def get_image_id(self, name, exclude=None): image = self._find(self.images, name) if image: return image['id'] def get_flavor(self, name): return self._find(self.flavors, name) def get_flavor_by_ram(self, ram, include=None): for flavor in self.flavors: if flavor['ram'] >= ram and (include is None or include in flavor['name']): return flavor def get_port(self, name): return self._find(self.ports, name) def get_network(self, name): return self._find(self.networks, name) create_server = mock.MagicMock() class TestNetworkArgs(object): '''This class exercises the _network_args function of the os_server module. For each test, we parse the YAML document contained in the docstring to retrieve the module parameters for the test.''' def setup_method(self, method): self.cloud = FakeCloud() self.module = mock.MagicMock() self.module.params = params_from_doc(method) def test_nics_string_net_id(self): ''' - os_server: nics: net-id=1234 ''' args = os_server._network_args(self.module, self.cloud) assert(args[0]['net-id'] == '1234') def test_nics_string_net_id_list(self): ''' - os_server: nics: net-id=1234,net-id=4321 ''' args = os_server._network_args(self.module, self.cloud) assert(args[0]['net-id'] == '1234') assert(args[1]['net-id'] == '4321') def test_nics_string_port_id(self): ''' - os_server: nics: port-id=1234 ''' args = os_server._network_args(self.module, self.cloud) assert(args[0]['port-id'] == '1234') def test_nics_string_net_name(self): ''' - os_server: nics: net-name=network1 ''' args = os_server._network_args(self.module, self.cloud) assert(args[0]['net-id'] == '5678') def test_nics_string_port_name(self): ''' - os_server: nics: port-name=port1 ''' args = os_server._network_args(self.module, self.cloud) assert(args[0]['port-id'] == '1234') def test_nics_structured_net_id(self): ''' - os_server: nics: - net-id: '1234' ''' args = os_server._network_args(self.module, self.cloud) assert(args[0]['net-id'] == '1234') def test_nics_structured_mixed(self): ''' - os_server: nics: - net-id: '1234' - port-name: port1 - 'net-name=network1,port-id=4321' ''' args = os_server._network_args(self.module, self.cloud) assert(args[0]['net-id'] == '1234') assert(args[1]['port-id'] == '1234') assert(args[2]['net-id'] == '5678') assert(args[3]['port-id'] == '4321') class TestCreateServer(object): def setup_method(self, method): self.cloud = FakeCloud() self.module = mock.MagicMock() self.module.params = params_from_doc(method) self.module.fail_json.side_effect = AnsibleFail() self.module.exit_json.side_effect = AnsibleExit() self.meta = mock.MagicMock() self.meta.gett_hostvars_from_server.return_value = { 'id': '1234' } os_server.meta = self.meta def test_create_server(self): ''' - os_server: image: cirros flavor: m1.tiny nics: - net-name: network1 meta: - key: value ''' with pytest.raises(AnsibleExit): os_server._create_server(self.module, self.cloud) assert(self.cloud.create_server.call_count == 1) assert(self.cloud.create_server.call_args[1]['image'] == self.cloud.get_image_id('cirros')) assert(self.cloud.create_server.call_args[1]['flavor'] == self.cloud.get_flavor('m1.tiny')['id']) assert(self.cloud.create_server.call_args[1]['nics'][0]['net-id'] == self.cloud.get_network('network1')['id']) def test_create_server_bad_flavor(self): ''' - os_server: image: cirros flavor: missing_flavor nics: - net-name: network1 ''' with pytest.raises(AnsibleFail): os_server._create_server(self.module, self.cloud) assert('missing_flavor' in self.module.fail_json.call_args[1]['msg']) def test_create_server_bad_nic(self): ''' - os_server: image: cirros flavor: m1.tiny nics: - net-name: missing_network ''' with pytest.raises(AnsibleFail): os_server._create_server(self.module, self.cloud) assert('missing_network' in self.module.fail_json.call_args[1]['msg'])
britcey/ansible
test/units/modules/cloud/openstack/test_os_server.py
Python
gpl-3.0
6,519
/* { dg-options "-O2 -fdump-tree-fre3-details" } */ typedef enum { } UErrorCode; class UnicodeString { public: UnicodeString (); virtual ~UnicodeString (); }; class A { UnicodeString &m_fn1 (UnicodeString &, int &p2, UErrorCode &) const; }; UnicodeString::UnicodeString () {} UnicodeString & A::m_fn1 (UnicodeString &, int &p2, UErrorCode &) const { UnicodeString a[2]; } /* { dg-final { scan-tree-dump-not "\\n OBJ_TYPE_REF" "fre3" } } */
selmentdev/selment-toolchain
source/gcc-latest/gcc/testsuite/g++.dg/ipa/devirt-40.C
C++
gpl-3.0
452
// Copyright 2012 Software Freedom Conservancy. 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. goog.provide('remote.ui.SessionContainer'); goog.provide('remote.ui.SessionContainer.SessionTab_'); goog.require('goog.array'); goog.require('goog.dom.TagName'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.structs.Map'); goog.require('goog.style'); goog.require('goog.ui.Component'); goog.require('goog.ui.Tab'); goog.require('goog.ui.TabBar'); goog.require('remote.ui.ControlBlock'); goog.require('remote.ui.CreateSessionDialog'); goog.require('remote.ui.Event'); goog.require('remote.ui.FieldSet'); goog.require('remote.ui.SessionView'); /** * A fieldset for displaying information about the active sessions on the * server. * @param {!Array.<string>} browsers List of potential browsers for new * sessions. * @constructor * @extends {remote.ui.FieldSet} */ remote.ui.SessionContainer = function(browsers) { goog.base(this, 'Sessions'); /** * Tabbar widget for selecting individual sessions. * @private {!goog.ui.TabBar} */ this.tabBar_ = new goog.ui.TabBar(goog.ui.TabBar.Location.START, null); /** * Widget for viewing details on an individual session. * @private {!remote.ui.SessionView} */ this.view_ = new remote.ui.SessionView(); /** * Dialog for creating a new session. * @private {!remote.ui.CreateSessionDialog} */ this.createSessionDialog_ = new remote.ui.CreateSessionDialog(browsers); /** * Button that opens the {@link remote.ui.CreateSessionDialog}. * @private {!Element} */ this.createButton_ = this.getDomHelper().createDom( goog.dom.TagName.BUTTON, null, 'Create Session'); /** * Button that refreshes the list of sessions. * @private {!Element} */ this.refreshButton_ = this.getDomHelper().createDom( goog.dom.TagName.BUTTON, null, 'Refresh Sessions'); /** @private {!remote.ui.ControlBlock} */ this.controlBlock_ = new remote.ui.ControlBlock(); /** * Tracks any tabs for pending new sessions that are descendants of this * component. * @private {!Array.<!goog.ui.Tab>} */ this.pendingTabs_ = []; /** * Key for the interval that updates the content of the pending session tabs. * @private {number} */ this.updateKey_ = setInterval(goog.bind(this.updatePendingTabs_, this), 300); this.addChild(this.tabBar_); this.addChild(this.view_); this.addChild(this.controlBlock_); this.setEnabled(false); this.controlBlock_.addElement(this.createButton_); this.controlBlock_.addElement(this.refreshButton_); goog.events.listen(this.createButton_, goog.events.EventType.CLICK, goog.bind(this.createSessionDialog_.setVisible, this.createSessionDialog_, true)); goog.events.listen(this.refreshButton_, goog.events.EventType.CLICK, goog.bind(this.dispatchEvent, this, remote.ui.Event.Type.REFRESH)); goog.events.listen(this.tabBar_, goog.ui.Component.EventType.SELECT, this.onSessionSelect_, false, this); goog.events.listen(this.createSessionDialog_, goog.ui.Component.EventType.ACTION, this.onCreateSession_, false, this); }; goog.inherits(remote.ui.SessionContainer, remote.ui.FieldSet); /** @override */ remote.ui.SessionContainer.prototype.disposeInternal = function() { goog.events.removeAll(this.createButton_); goog.events.removeAll(this.refreshButton_); clearInterval(this.updateKey_); this.createSessionDialog_.dispose(); delete this.createSessionDialog_; delete this.tabBar_; delete this.view_; delete this.controlBlock_; delete this.pendingTabs_; delete this.updateKey_; goog.base(this, 'disposeInternal'); }; /** @override */ remote.ui.SessionContainer.prototype.createFieldSetDom = function() { this.tabBar_.createDom(); this.view_.createDom(); this.controlBlock_.createDom(); var dom = this.getDomHelper(); return dom.createDom(goog.dom.TagName.DIV, 'session-container', this.controlBlock_.getElement(), this.tabBar_.getElement(), this.view_.getElement()); }; /** * @param {boolean} enabled Whether this container should be enabled. */ remote.ui.SessionContainer.prototype.setEnabled = function(enabled) { if (enabled) { this.createButton_.removeAttribute('disabled'); this.refreshButton_.removeAttribute('disabled'); } else { this.createButton_.setAttribute('disabled', 'disabled'); this.refreshButton_.setAttribute('disabled', 'disabled'); } }; /** * @param {!Element} element The element to add. */ remote.ui.SessionContainer.prototype.addControlElement = function(element) { this.view_.addControlElement(element); }; /** * Returns the session associated with the currently selected tab. * @return {webdriver.Session} The selected session, or null if there is none. */ remote.ui.SessionContainer.prototype.getSelectedSession = function() { var tab = this.tabBar_.getSelectedTab(); return tab ? tab.session_ : null; }; /** * Interval callback that updates the displayed content for pending session * tabs. * @private */ remote.ui.SessionContainer.prototype.updatePendingTabs_ = function() { if (!this.pendingTabs_.length) { return; } // Each pending tab has a simple animated sequence of ".", "..", "...", etc. // Compute the next entry in the sequence once, so it can be used for every // tab to keep them in sync. var content = this.pendingTabs_[0].getContent(); content = content.length === 5 ? '.' : content + '.'; goog.array.forEach(this.pendingTabs_, function(tab) { tab.setContent(content); }); }; /** * Adjusts the height of the session view so it is always relative to our * tab bar. * @private */ remote.ui.SessionContainer.prototype.adjustSessionViewSize_ = function() { var size = goog.style.getSize(this.tabBar_.getElement()); this.view_.setHeight(size.height + 20); }; /** * Adds a tab to represent a "pending" session. Pending tabs will be replaced * in FIFO order as new sessions are registered by the server. * @private */ remote.ui.SessionContainer.prototype.addPendingTab_ = function() { var content = '.'; if (this.pendingTabs_.length) { content = this.pendingTabs_[0].getContent(); } var tab = new goog.ui.Tab(content, null, this.getDomHelper()); tab.setEnabled(false); this.pendingTabs_.push(tab); this.tabBar_.addChild(tab, true); this.adjustSessionViewSize_(); }; /** * Removes a "pending" session tab, if there is one to remove. */ remote.ui.SessionContainer.prototype.removePendingTab = function() { var tab = this.pendingTabs_.shift(); if (tab) { this.tabBar_.removeChild(tab, true); this.adjustSessionViewSize_(); } }; /** * Adds a new session to this container. The new session will be selected for * viewing. * @param {!webdriver.Session} session The new session. */ remote.ui.SessionContainer.prototype.addSession = function(session) { var tab = new remote.ui.SessionContainer.SessionTab_(session); // Replace the first non-session tab with the new session. var pending = this.pendingTabs_.shift(); var index = this.tabBar_.indexOfChild(pending); if (index < 0) { // Only happens if !pending === true. this.tabBar_.addChild(tab, true); } else { this.tabBar_.addChildAt(tab, index, true); this.tabBar_.removeChild(pending, true); } this.adjustSessionViewSize_(); this.tabBar_.setSelectedTab(tab); }; /** * Removes a session from this container. * @param {!webdriver.Session} session The session to remove. */ remote.ui.SessionContainer.prototype.removeSession = function(session) { var selectedTab = this.tabBar_.getSelectedTab(); var tabToRemove; var n = this.tabBar_.getChildCount(); for (var i = 0; i < n; ++i) { var tab = this.tabBar_.getChildAt(i); if (tab.session_.getId() == session.getId()) { tabToRemove = tab; break; } } if (tabToRemove) { this.tabBar_.removeChild(tabToRemove, true); tabToRemove.dispose(); if (selectedTab == tabToRemove && !!this.tabBar_.getChildCount()) { this.tabBar_.setSelectedTabIndex(0); } else { this.view_.update(null); } } }; /** * Updates the sessions displayed by this container. Any new sessions * will be added, while tabs not present in the input list will be removed. The * last tab selected before this function was called will be selected when it is * finished. If this tab was removed, the first displayed tab will be selected. * @param {!Array.<!webdriver.Session>} sessions List of sessions to refresh * our view with. */ remote.ui.SessionContainer.prototype.refreshSessions = function(sessions) { var newSessionsById = new goog.structs.Map(); goog.array.forEach(sessions, function(session) { newSessionsById.set(session.getId(), session); }); var tabBar = this.tabBar_; var selectedTab = tabBar.getSelectedTab(); var sessionTabs = []; var n = tabBar.getChildCount() - this.pendingTabs_.length; for (var i = 0; i < n; ++i) { sessionTabs.push(tabBar.getChildAt(i)); } // Remove any old sessions and refresh those whose IDs match. goog.array.forEach(sessionTabs, function(tab) { var id = tab.session_.getId(); var newSession = newSessionsById.get(id); if (newSession) { newSessionsById.remove(id); tab.session_ = newSession; } else { tabBar.removeChild(tab, true); if (selectedTab === tab) { selectedTab = null; } } }, this); // Remove all of our pending session tabs. As far as we know, we have an // up-to-date list of sessions. goog.array.forEach(this.pendingTabs_, function(tab) { tabBar.removeChild(tab, true); }); this.pendingTabs_ = []; // Add the new sessions. goog.array.forEach(newSessionsById.getValues(), this.addSession, this); // Update our selection. if (selectedTab) { this.view_.update(selectedTab.session_); tabBar.setSelectedTab(selectedTab); } else if (tabBar.getChildCount()) { tabBar.setSelectedTabIndex(0); } else { this.view_.update(null); } }; /** * Callback for when the user has selected to create a new session. * Dispatches a {@link remote.ui.Event.Type.CREATE} event with the desired * capabilities for the new session as data. * @private */ remote.ui.SessionContainer.prototype.onCreateSession_ = function() { this.addPendingTab_(); var event = new remote.ui.Event(remote.ui.Event.Type.CREATE, this, this.createSessionDialog_.getUserSelection()); this.dispatchEvent(event); }; /** * Event handler for when users select a session from our tabbar. * @private */ remote.ui.SessionContainer.prototype.onSessionSelect_ = function() { var tab = /** @type {!remote.ui.SessionContainer.SessionTab_} */ ( this.tabBar_.getSelectedTab()); this.view_.update(tab ? tab.session_ : null); }; /** * A single tab in a {@link remote.ui.SessionContainer}. Each tab represents an * active session on the WebDriver server. * @param {!webdriver.Session} session The session for this tab. * @constructor * @extends {goog.ui.Tab} * @private */ remote.ui.SessionContainer.SessionTab_ = function(session) { var browser = session.getCapability('browserName') || 'unknown browser'; browser = browser.toLowerCase().replace(/(^|\b)[a-z]/g, function(c) { return c.toUpperCase(); }); goog.base(this, browser); /** * The session for this tab. * @private {!webdriver.Session} */ this.session_ = session; }; goog.inherits(remote.ui.SessionContainer.SessionTab_, goog.ui.Tab); /** @override */ remote.ui.SessionContainer.SessionTab_.prototype.disposeInternal = function() { delete this.session_; goog.base(this, 'disposeInternal'); };
isaksky/selenium
javascript/remote/ui/sessioncontainer.js
JavaScript
apache-2.0
12,232
using System; using System.Collections.Generic; using System.Linq; using ICSharpCode.NRefactory.TypeSystem; namespace CoreLib.Plugin { /// <summary> /// Used to deterministically order members. It is assumed that all members belong to the same type. /// </summary> public class MemberOrderer : IComparer<IMember> { public static readonly MemberOrderer Instance = new MemberOrderer(); private MemberOrderer() { } private int CompareMethods(IMethod x, IMethod y) { int result = String.CompareOrdinal(x.Name, y.Name); if (result != 0) return result; if (x.Parameters.Count > y.Parameters.Count) return 1; else if (x.Parameters.Count < y.Parameters.Count) return -1; var xparms = String.Join(",", x.Parameters.Select(p => p.Type.FullName)); var yparms = String.Join(",", y.Parameters.Select(p => p.Type.FullName)); var presult = String.CompareOrdinal(xparms, yparms); if (presult != 0) return presult; var rresult = String.CompareOrdinal(x.ReturnType.FullName, y.ReturnType.FullName); if (rresult != 0) return rresult; if (x.TypeParameters.Count > y.TypeParameters.Count) return 1; else if (x.TypeParameters.Count < y.TypeParameters.Count) return -1; return 0; } public int Compare(IMember x, IMember y) { if (x is IMethod) { if (y is IMethod) { return CompareMethods((IMethod)x, (IMethod)y); } else return -1; } else if (y is IMethod) { return 1; } if (x is IProperty) { if (y is IProperty) { return String.CompareOrdinal(x.Name, y.Name); } else return -1; } else if (y is IProperty) { return 1; } if (x is IField) { if (y is IField) { return String.CompareOrdinal(x.Name, y.Name); } else return -1; } else if (y is IField) { return 1; } if (x is IEvent) { if (y is IEvent) { return String.CompareOrdinal(x.Name, y.Name); } else return -1; } else if (y is IEvent) { return 1; } throw new ArgumentException("Invalid member type" + x.GetType().FullName); } } }
x335/SaltarelleCompiler
Runtime/CoreLib.Plugin/MemberOrderer.cs
C#
apache-2.0
2,116
package test; import org.testng.annotations.Test; /** * This used to create a StackOverflowError. */ public class StaticTest { @Test public void test() { } @Test public static class InnerStaticClass extends StaticTest { } }
s2oBCN/testng
src/test/java/test/StaticTest.java
Java
apache-2.0
240
#pragma once #include "geometry/point2d.hpp" namespace graphics { template <typename T> class Path { private: vector<m2::Point<T> > m_pts; public: void reset(m2::Point<T> const & pt) { m_pts.clear(); m_pts.push_back(pt); } void lineRel(m2::Point<T> const & pt) { ASSERT(!m_pts.empty(), ()); m2::Point<T> const & p = m_pts.back(); m_pts.push_back(p + pt); } void eclipseArcRel(m2::Point<T> const & pt) { /// TODO : write implementation } m2::Point<T> const * points() const { ASSERT(!m_pts.empty(), ()); return &m_pts[0]; } unsigned size() const { return m_pts.size(); } }; }
sidorov-panda/omim
graphics/path.hpp
C++
apache-2.0
714
package com.marshalchen.common.uimodule.superlistview; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import android.widget.GridView; import android.widget.ListAdapter; import com.marshalchen.common.uimodule.R; /** * Created by kentin on 24/04/14. */ public class SuperGridview extends BaseSuperAbsListview { //------------------------------------------------------- // Custom Grid attributes //------------------------------------------------------- private int mColumns; private int mHorizontalSpacing; private int mVerticalSpacing; public SuperGridview(Context context) { super(context); } public SuperGridview(Context context, AttributeSet attrs) { super(context, attrs); } public SuperGridview(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public GridView getList(){ return (GridView) mList; } @Override protected void initAttrs(AttributeSet attrs) { super.initAttrs(attrs); TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.superlistview); try { mSuperListViewMainLayout = a.getResourceId(R.styleable.superlistview_superlv_mainLayoutID, R.layout.super_list_view_view_progress_gridview); } finally { a.recycle(); } TypedArray ag = getContext().obtainStyledAttributes(attrs, R.styleable.supergridview); try { mColumns = ag.getInt(R.styleable.supergridview_supergv__columns, 1); mVerticalSpacing = (int) ag.getDimension(R.styleable.supergridview_supergv__verticalSpacing, 1); mHorizontalSpacing = (int) ag.getDimension(R.styleable.supergridview_supergv__horizontalSpacing, 1); } finally { ag.recycle(); } } @Override protected void initAbsListView(View v) { View listView = v.findViewById(android.R.id.list); if (listView instanceof GridView) mList = (GridView) listView; else throw new IllegalArgumentException(listView.getClass().getName()); if (mList!=null) { getList().setNumColumns(mColumns); getList().setVerticalSpacing(mVerticalSpacing); getList().setHorizontalSpacing(mHorizontalSpacing); getList().setHorizontalSpacing((int) mDividerHeight); getList().setVerticalSpacing((int) mDividerHeight); mList.setClipToPadding(mClipToPadding); mList.setOnScrollListener(this); if (mSelector != 0) mList.setSelector(mSelector); if (mPadding != -1.0f) { mList.setPadding(mPadding, mPadding, mPadding, mPadding); } else { mList.setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom); } mList.setScrollBarStyle(mScrollbarStyle); } } @Override public void setAdapter(ListAdapter adapter) { getList().setAdapter(adapter); super.setAdapter(adapter); } @Override public void clear() { getList().setAdapter(null); } }
cymcsg/UltimateAndroid
deprecated/UltimateAndroidNormal/UltimateAndroidUi/src/com/marshalchen/common/uimodule/superlistview/SuperGridview.java
Java
apache-2.0
3,271
/* Essentials */ html, body { height: 100%; margin: 0; padding: 0; font-family: "Helvetica Neue", Helvetica, Arial, Verdana, sans-serif; background: white; font-size: 12px; } label, input, button, select, textarea { font-size: 12px; font-weight: normal; line-height: 20px; } select, textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"], .uneditable-input { font-size: 12px; height: 16px; line-height: 16px; } textarea { height: auto; } select { height: 26px; } a:link, a:visited { color: #77BACE; text-decoration: none; } a:hover { text-decoration: underline; } fieldset { -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; background: #F6F6F6; border: 1px solid #ccc; padding: 1% 0%; margin: 10px 0; } fieldset label { display: block; float: left; width: 200px; height: 25px; line-height: 25px; text-shadow: 0 1px 0 #fff; font-weight: bold; padding-left: 10px; margin: -5px 0 5px 0; text-transform: uppercase; font-size: 12px; } fieldset input[type=text] { -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; border: 1px solid #BBBBBB; height: 20px; color: #666666; -webkit-box-shadow: inset 0 2px 2px #ccc, 0 1px 0 #fff; -moz-box-shadow: inset 0 2px 2px #ccc, 0 1px 0 #fff; box-shadow: inset 0 2px 2px #ccc, 0 1px 0 #fff; padding-left: 10px; background-position: 10px 6px; margin: 0; display: block; float: left; width: 96%; margin: 0 10px; } fieldset input[type=text]:focus { outline: none; border: 1px solid #77BACE; -webkit-box-shadow: inset 0 2px 2px #ccc, 0 0 10px #ADDCE6; -moz-box-shadow: inset 0 2px 2px #ccc, 0 0 10px #ADDCE6; box-shadow: inset 0 2px 2px #ccc, 0 0 10px #ADDCE6; } fieldset select { width: 96%; margin: 0 10px; border: 1px solid #bbb; height: 20px; color: #666666; } fieldset textarea { -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; border: 1px solid #BBBBBB; color: #666666; -webkit-box-shadow: inset 0 2px 2px #ccc, 0 1px 0 #fff; -moz-box-shadow: inset 0 2px 2px #ccc, 0 1px 0 #fff; box-shadow: inset 0 2px 2px #ccc, 0 1px 0 #fff; padding-left: 10px; background-position: 10px 6px; margin: 0 0.5%; display: block; float: left; width: 96%; margin: 0 10px; } fieldset textarea:focus { outline: none; border: 1px solid #77BACE; -webkit-box-shadow: inset 0 2px 2px #ccc, 0 0 10px #ADDCE6; -moz-box-shadow: inset 0 2px 2px #ccc, 0 0 10px #ADDCE6; box-shadow: inset 0 2px 2px #ccc, 0 0 10px #ADDCE6; } .m-clear { clear: both; } .m-spacer { height: 20px; } /* header */ #m-header h3.title { padding-left:20px; line-height:20px; } #m-header h3.title a { text-decoration: none; color: black; } #m-header div.info { padding-top:10px; padding-right:20px; } #m-header div.info a { margin-left:15px; } #m-header .navbar-inner { border-radius:0px; } /* sidebar */ #m-sidebar .accordion-group { margin-left: 10px; border:1px solid #C2C2C3; } #m-sidebar .accordion-heading { border-radius: 3px 3px 0px 0px; background-color: #CCCCCC; box-shadow: 0 1px 0 0 rgba(255, 255, 255, 0.5) inset; background: linear-gradient(to bottom, #FAFAFA 0%, #EFEFEF 100%) repeat scroll 0 0 transparent; text-shadow: 0 1px 0 #FFFFFF; color: #333333; } #m-sidebar .accordion-heading .accordion-toggle { display: block; padding: 5px 15px; } #m-sidebar .title { color:black; font-size:14px; font-weight: bold; } /* footer */ #m-footer hr { margin-left: 10px; } /* main */ #m-main { float: right; padding-right: 10px; } /* widget */ .m-widget { margin-top: 0px; margin-bottom: 10px; border-radius: 3px; box-shadow: #E6E6E6 0px 1px 1px 0px; } .m-widget .header { height: 20px; padding: 5px 15px; border:1px solid #C2C2C3; padding-left: 10px; border-radius: 3px 3px 0px 0px; background-color: #CCCCCC; box-shadow: 0 1px 0 0 rgba(255, 255, 255, 0.5) inset; background: linear-gradient(to bottom, #FAFAFA 0%, #EFEFEF 100%) repeat scroll 0 0 transparent; text-shadow: 0 1px 0 #FFFFFF; color: #333333; } .m-widget .header .title { float: left; margin: 0px; font-size:14px; } .m-widget .header .ctrl { float: right; } .m-widget .header .ctrl .btn { margin: 0px; padding-left: 3px; padding-right: 3px; padding-top: 0px; padding-bottom: 0px; } .m-widget .content { border-left: 1px solid #C2C2C3; border-right: 1px solid #C2C2C3; border-bottom: 1px solid #C2C2C3; border-radius: 0px 0px 3px 3px; } .m-widget .content.content-inner { padding-left: 10px; padding-top:10px; font-size: 12px; } .m-widget .content .table { margin-bottom: 0px; } /* page */ .m-page-size { margin-bottom:0px; width:55px; display:inline; } /* Main Table */ .m-table { width: 100%; margin: -5px 0 0 0; line-height: 16px; } .m-table td { margin: 0; padding: 0; border-bottom: 1px dotted #ccc; } .m-table thead tr { height: 20px; background: url(../img/table_sorter_header.png) repeat-x; text-align: left; text-indent: 10px; cursor: pointer; } .m-table td { padding: 4px 10px; } .m-table input[type=image] { margin-right: 10px; } .m-table input[type=checkbox] { margin: 3px 3px 3px 4px; } .m-table th.sorting { background: no-repeat url(../img/sorting.png); background-position: right -52px; cursor: pointer; } .m-table th.sorting-asc { background-position: right -2px; } .m-table th.sorting-desc { background-position: right -29px; } /* etc */ .m-form-blank { margin: 0px; } .m-form-bottom { margin-bottom: 10px; } .m-table-check { text-indent: 0px; text-align: center; } .m-blank { margin-bottom: 10px; } .form-inline .chzn-container { vertical-align: middle; } /* Alerts */ div.m-alert-info { display: block; width: 95%; margin: 10px 3% 0 3%; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; background: #B5E5EF url(../img/icn_alert_info.png) no-repeat; background-position: 10px 10px; border: 1px solid #77BACE; color: #082B33; padding: 10px 0; text-indent: 40px; font-size: 14px; } div.m-alert-warning { display: block; width: 95%; margin: 10px 3% 0 3%; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; background: #F5F3BA url(../img/icn_alert_warning.png) no-repeat; background-position: 10px 10px; border: 1px solid #C7A20D; color: #796616; padding: 10px 0; text-indent: 40px; font-size: 14px; } div.m-alert-error { display: block; width: 95%; margin: 10px 3% 0 3%; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; background: #F3D9D9 url(../img/icn_alert_error.png) no-repeat; background-position: 10px 10px; border: 1px solid #D20009; color: #7B040F; padding: 10px 0; text-indent: 40px; font-size: 14px; } div.m-alert-success { display: block; width: 95%; margin: 10px 3% 0 3%; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; background: #E2F6C5 url(../img/icn_alert_success.png) no-repeat; background-position: 10px 10px; border: 1px solid #79C20D; color: #32510F; padding: 10px 0; text-indent: 40px; font-size: 14px; } /** * bootstrap modal */ .modal { top: 50%; } .modal-backdrop, .modal-backdrop.fade.in { opacity: 0.2; filter: alpha(opacity=20); } /** * uniform * 美化中文下的字体大小 */ div.uploader span.filename { font-size: 12px; } div.uploader span.action { font-size: 12px; } /** * boostrap里的配置会导致radio样式下包裹的radio样式margin-left:-20px; * 导致被uniform渲染后的radio会跑到显示的radio的左边,无法点击到 * 这里设置为0px,让用户可以简单点击到 */ .radio input[type="radio"], .checkbox input[type="checkbox"] { float: left; margin-left: 0px; } /** * uniform里用的是checker,要和bootstrap里保持一致 */ .radio.inline + .radio.inline, .checkbox.inline + .checkbox.inline, .checker.inline + .checker.inline { margin-left: 10px; } /** * uniform里checkbox的margin-right是5px,radio的margin-right是3px * 为了避免上下不对齐,统一改成5px */ div.radio { margin-right: 5px; } /** * 输入框背景显示标尺 */ input.measure-input { background: url("../img/ruler.gif") repeat-x scroll 0 9px transparent; border-color: #AAAAAA #CCCCCC #CCCCCC #AAAAAA; border-radius: 3px 3px 3px 3px; border-style: solid; border-width: 1px; color: #777777; font-family: "Helvetica Neue",Arial,Helvetica,sans-serif; font-size: 12px; font-weight: normal; outline: 0 none; padding-bottom: 3px; } .navbar-inverse .navbar-search .search-query { border-radius: 15px 15px 15px 15px; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; font-size: 13px; font-weight: 400; line-height: 1; margin-bottom: 0; height: 20px; background: none repeat scroll 0 0 rgba(35, 43, 48, 0.83); border-color: #111111; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1) inset, 0 1px 0 rgba(255, 255, 255, 0.15); color: gray; transition: none 0s ease 0s; } .navbar-inverse .navbar-search .search-query:focus { transition: width 0.3s ease 0s; width: 100px; background: white; } .navbar-inverse .navbar-search i { position: absolute; right: 10px; top: 5px; } /** * chozen中single select的search input高度过小的问题 */ .chzn-search input[type="text"] { height: 24px; }
callmeyan/lemon
webapp/s/mossle/css/layout3.css
CSS
apache-2.0
9,578
/* * 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.beam.sdk.coders; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThat; import java.util.Collections; import org.apache.beam.sdk.coders.Coder.Context; import org.apache.beam.sdk.coders.Coder.NonDeterministicException; import org.apache.beam.sdk.values.TypeDescriptor; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for constructs defined within {@link Coder}. */ @RunWith(JUnit4.class) public class CoderTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testContextEqualsAndHashCode() { assertEquals(Context.NESTED, new Context(false)); assertEquals(Context.OUTER, new Context(true)); assertNotEquals(Context.NESTED, Context.OUTER); assertEquals(Context.NESTED.hashCode(), new Context(false).hashCode()); assertEquals(Context.OUTER.hashCode(), new Context(true).hashCode()); // Even though this isn't strictly required by the hashCode contract, // we still want this to be true. assertNotEquals(Context.NESTED.hashCode(), Context.OUTER.hashCode()); } @Test public void testContextToString() { assertEquals("Context{NESTED}", Context.NESTED.toString()); assertEquals("Context{OUTER}", Context.OUTER.toString()); } @Test public void testNonDeterministicExcpetionRequiresReason() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Reasons must not be empty"); new NonDeterministicException(VoidCoder.of(), Collections.<String>emptyList()); } @Test public void testNonDeterministicException() { NonDeterministicException rootCause = new NonDeterministicException(VoidCoder.of(), "Root Cause"); NonDeterministicException exception = new NonDeterministicException(StringUtf8Coder.of(), "Problem", rootCause); assertEquals(rootCause, exception.getCause()); assertThat(exception.getReasons(), contains("Problem")); assertThat(exception.toString(), containsString("Problem")); assertThat(exception.toString(), containsString("is not deterministic")); } @Test public void testTypeIsPreserved() throws Exception { assertThat(VoidCoder.of().getEncodedTypeDescriptor(), equalTo(TypeDescriptor.of(Void.class))); } }
xsm110/Apache-Beam
sdks/java/core/src/test/java/org/apache/beam/sdk/coders/CoderTest.java
Java
apache-2.0
3,407
# Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org> # Gael Varoquaux <gael.varoquaux@normalesup.org> # License: BSD 3 clause import numpy as np import scipy as sp from scipy import ndimage from nose.tools import assert_equal, assert_true from numpy.testing import assert_raises from sklearn.feature_extraction.image import ( img_to_graph, grid_to_graph, extract_patches_2d, reconstruct_from_patches_2d, PatchExtractor, extract_patches) from sklearn.utils.graph import connected_components from sklearn.utils.testing import SkipTest from sklearn.utils.fixes import sp_version if sp_version < (0, 12): raise SkipTest("Skipping because SciPy version earlier than 0.12.0 and " "thus does not include the scipy.misc.face() image.") def test_img_to_graph(): x, y = np.mgrid[:4, :4] - 10 grad_x = img_to_graph(x) grad_y = img_to_graph(y) assert_equal(grad_x.nnz, grad_y.nnz) # Negative elements are the diagonal: the elements of the original # image. Positive elements are the values of the gradient, they # should all be equal on grad_x and grad_y np.testing.assert_array_equal(grad_x.data[grad_x.data > 0], grad_y.data[grad_y.data > 0]) def test_grid_to_graph(): # Checking that the function works with graphs containing no edges size = 2 roi_size = 1 # Generating two convex parts with one vertex # Thus, edges will be empty in _to_graph mask = np.zeros((size, size), dtype=np.bool) mask[0:roi_size, 0:roi_size] = True mask[-roi_size:, -roi_size:] = True mask = mask.reshape(size ** 2) A = grid_to_graph(n_x=size, n_y=size, mask=mask, return_as=np.ndarray) assert_true(connected_components(A)[0] == 2) # Checking that the function works whatever the type of mask is mask = np.ones((size, size), dtype=np.int16) A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask) assert_true(connected_components(A)[0] == 1) # Checking dtype of the graph mask = np.ones((size, size)) A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask, dtype=np.bool) assert_true(A.dtype == np.bool) A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask, dtype=np.int) assert_true(A.dtype == np.int) A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask, dtype=np.float64) assert_true(A.dtype == np.float64) def test_connect_regions(): try: face = sp.face(gray=True) except AttributeError: # Newer versions of scipy have face in misc from scipy import misc face = misc.face(gray=True) for thr in (50, 150): mask = face > thr graph = img_to_graph(face, mask) assert_equal(ndimage.label(mask)[1], connected_components(graph)[0]) def test_connect_regions_with_grid(): try: face = sp.face(gray=True) except AttributeError: # Newer versions of scipy have face in misc from scipy import misc face = misc.face(gray=True) mask = face > 50 graph = grid_to_graph(*face.shape, mask=mask) assert_equal(ndimage.label(mask)[1], connected_components(graph)[0]) mask = face > 150 graph = grid_to_graph(*face.shape, mask=mask, dtype=None) assert_equal(ndimage.label(mask)[1], connected_components(graph)[0]) def _downsampled_face(): try: face = sp.face(gray=True) except AttributeError: # Newer versions of scipy have face in misc from scipy import misc face = misc.face(gray=True) face = face.astype(np.float32) face = (face[::2, ::2] + face[1::2, ::2] + face[::2, 1::2] + face[1::2, 1::2]) face = (face[::2, ::2] + face[1::2, ::2] + face[::2, 1::2] + face[1::2, 1::2]) face = face.astype(np.float32) face /= 16.0 return face def _orange_face(face=None): face = _downsampled_face() if face is None else face face_color = np.zeros(face.shape + (3,)) face_color[:, :, 0] = 256 - face face_color[:, :, 1] = 256 - face / 2 face_color[:, :, 2] = 256 - face / 4 return face_color def _make_images(face=None): face = _downsampled_face() if face is None else face # make a collection of faces images = np.zeros((3,) + face.shape) images[0] = face images[1] = face + 1 images[2] = face + 2 return images downsampled_face = _downsampled_face() orange_face = _orange_face(downsampled_face) face_collection = _make_images(downsampled_face) def test_extract_patches_all(): face = downsampled_face i_h, i_w = face.shape p_h, p_w = 16, 16 expected_n_patches = (i_h - p_h + 1) * (i_w - p_w + 1) patches = extract_patches_2d(face, (p_h, p_w)) assert_equal(patches.shape, (expected_n_patches, p_h, p_w)) def test_extract_patches_all_color(): face = orange_face i_h, i_w = face.shape[:2] p_h, p_w = 16, 16 expected_n_patches = (i_h - p_h + 1) * (i_w - p_w + 1) patches = extract_patches_2d(face, (p_h, p_w)) assert_equal(patches.shape, (expected_n_patches, p_h, p_w, 3)) def test_extract_patches_all_rect(): face = downsampled_face face = face[:, 32:97] i_h, i_w = face.shape p_h, p_w = 16, 12 expected_n_patches = (i_h - p_h + 1) * (i_w - p_w + 1) patches = extract_patches_2d(face, (p_h, p_w)) assert_equal(patches.shape, (expected_n_patches, p_h, p_w)) def test_extract_patches_max_patches(): face = downsampled_face i_h, i_w = face.shape p_h, p_w = 16, 16 patches = extract_patches_2d(face, (p_h, p_w), max_patches=100) assert_equal(patches.shape, (100, p_h, p_w)) expected_n_patches = int(0.5 * (i_h - p_h + 1) * (i_w - p_w + 1)) patches = extract_patches_2d(face, (p_h, p_w), max_patches=0.5) assert_equal(patches.shape, (expected_n_patches, p_h, p_w)) assert_raises(ValueError, extract_patches_2d, face, (p_h, p_w), max_patches=2.0) assert_raises(ValueError, extract_patches_2d, face, (p_h, p_w), max_patches=-1.0) def test_reconstruct_patches_perfect(): face = downsampled_face p_h, p_w = 16, 16 patches = extract_patches_2d(face, (p_h, p_w)) face_reconstructed = reconstruct_from_patches_2d(patches, face.shape) np.testing.assert_array_almost_equal(face, face_reconstructed) def test_reconstruct_patches_perfect_color(): face = orange_face p_h, p_w = 16, 16 patches = extract_patches_2d(face, (p_h, p_w)) face_reconstructed = reconstruct_from_patches_2d(patches, face.shape) np.testing.assert_array_almost_equal(face, face_reconstructed) def test_patch_extractor_fit(): faces = face_collection extr = PatchExtractor(patch_size=(8, 8), max_patches=100, random_state=0) assert_true(extr == extr.fit(faces)) def test_patch_extractor_max_patches(): faces = face_collection i_h, i_w = faces.shape[1:3] p_h, p_w = 8, 8 max_patches = 100 expected_n_patches = len(faces) * max_patches extr = PatchExtractor(patch_size=(p_h, p_w), max_patches=max_patches, random_state=0) patches = extr.transform(faces) assert_true(patches.shape == (expected_n_patches, p_h, p_w)) max_patches = 0.5 expected_n_patches = len(faces) * int((i_h - p_h + 1) * (i_w - p_w + 1) * max_patches) extr = PatchExtractor(patch_size=(p_h, p_w), max_patches=max_patches, random_state=0) patches = extr.transform(faces) assert_true(patches.shape == (expected_n_patches, p_h, p_w)) def test_patch_extractor_max_patches_default(): faces = face_collection extr = PatchExtractor(max_patches=100, random_state=0) patches = extr.transform(faces) assert_equal(patches.shape, (len(faces) * 100, 19, 25)) def test_patch_extractor_all_patches(): faces = face_collection i_h, i_w = faces.shape[1:3] p_h, p_w = 8, 8 expected_n_patches = len(faces) * (i_h - p_h + 1) * (i_w - p_w + 1) extr = PatchExtractor(patch_size=(p_h, p_w), random_state=0) patches = extr.transform(faces) assert_true(patches.shape == (expected_n_patches, p_h, p_w)) def test_patch_extractor_color(): faces = _make_images(orange_face) i_h, i_w = faces.shape[1:3] p_h, p_w = 8, 8 expected_n_patches = len(faces) * (i_h - p_h + 1) * (i_w - p_w + 1) extr = PatchExtractor(patch_size=(p_h, p_w), random_state=0) patches = extr.transform(faces) assert_true(patches.shape == (expected_n_patches, p_h, p_w, 3)) def test_extract_patches_strided(): image_shapes_1D = [(10,), (10,), (11,), (10,)] patch_sizes_1D = [(1,), (2,), (3,), (8,)] patch_steps_1D = [(1,), (1,), (4,), (2,)] expected_views_1D = [(10,), (9,), (3,), (2,)] last_patch_1D = [(10,), (8,), (8,), (2,)] image_shapes_2D = [(10, 20), (10, 20), (10, 20), (11, 20)] patch_sizes_2D = [(2, 2), (10, 10), (10, 11), (6, 6)] patch_steps_2D = [(5, 5), (3, 10), (3, 4), (4, 2)] expected_views_2D = [(2, 4), (1, 2), (1, 3), (2, 8)] last_patch_2D = [(5, 15), (0, 10), (0, 8), (4, 14)] image_shapes_3D = [(5, 4, 3), (3, 3, 3), (7, 8, 9), (7, 8, 9)] patch_sizes_3D = [(2, 2, 3), (2, 2, 2), (1, 7, 3), (1, 3, 3)] patch_steps_3D = [(1, 2, 10), (1, 1, 1), (2, 1, 3), (3, 3, 4)] expected_views_3D = [(4, 2, 1), (2, 2, 2), (4, 2, 3), (3, 2, 2)] last_patch_3D = [(3, 2, 0), (1, 1, 1), (6, 1, 6), (6, 3, 4)] image_shapes = image_shapes_1D + image_shapes_2D + image_shapes_3D patch_sizes = patch_sizes_1D + patch_sizes_2D + patch_sizes_3D patch_steps = patch_steps_1D + patch_steps_2D + patch_steps_3D expected_views = expected_views_1D + expected_views_2D + expected_views_3D last_patches = last_patch_1D + last_patch_2D + last_patch_3D for (image_shape, patch_size, patch_step, expected_view, last_patch) in zip(image_shapes, patch_sizes, patch_steps, expected_views, last_patches): image = np.arange(np.prod(image_shape)).reshape(image_shape) patches = extract_patches(image, patch_shape=patch_size, extraction_step=patch_step) ndim = len(image_shape) assert_true(patches.shape[:ndim] == expected_view) last_patch_slices = [slice(i, i + j, None) for i, j in zip(last_patch, patch_size)] assert_true((patches[[slice(-1, None, None)] * ndim] == image[last_patch_slices].squeeze()).all()) def test_extract_patches_square(): # test same patch size for all dimensions face = downsampled_face i_h, i_w = face.shape p = 8 expected_n_patches = ((i_h - p + 1), (i_w - p + 1)) patches = extract_patches(face, patch_shape=p) assert_true(patches.shape == (expected_n_patches[0], expected_n_patches[1], p, p)) def test_width_patch(): # width and height of the patch should be less than the image x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert_raises(ValueError, extract_patches_2d, x, (4, 1)) assert_raises(ValueError, extract_patches_2d, x, (1, 4))
toastedcornflakes/scikit-learn
sklearn/feature_extraction/tests/test_image.py
Python
bsd-3-clause
11,187
// 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 CHROME_BROWSER_UI_GTK_FIRST_RUN_DIALOG_H_ #define CHROME_BROWSER_UI_GTK_FIRST_RUN_DIALOG_H_ typedef struct _GtkButton GtkButton; typedef struct _GtkWidget GtkWidget; #include "base/compiler_specific.h" #include "chrome/browser/first_run/first_run.h" #include "ui/base/gtk/gtk_signal.h" class FirstRunDialog { public: // Displays the first run UI for reporting opt-in, import data etc. // Returns true if the dialog was shown. static bool Show(Profile* profile); private: explicit FirstRunDialog(Profile* profile); virtual ~FirstRunDialog(); CHROMEGTK_CALLBACK_1(FirstRunDialog, void, OnResponseDialog, int); CHROMEG_CALLBACK_0(FirstRunDialog, void, OnLearnMoreLinkClicked, GtkButton*); void ShowReportingDialog(); // This method closes the first run window and quits the message loop so that // the Chrome startup can continue. This should be called when all the // first run tasks are done. void FirstRunDone(); Profile* profile_; // Dialog that holds the bug reporting and default browser checkboxes. GtkWidget* dialog_; // Crash reporting checkbox GtkWidget* report_crashes_; // Make browser default checkbox GtkWidget* make_default_; // Whether we should show the dialog asking the user whether to report // crashes and usage stats. bool show_reporting_dialog_; // User response (accept or cancel) is returned through this. int* response_; DISALLOW_COPY_AND_ASSIGN(FirstRunDialog); }; #endif // CHROME_BROWSER_UI_GTK_FIRST_RUN_DIALOG_H_
androidarmv6/android_external_chromium_org
chrome/browser/ui/gtk/first_run_dialog.h
C
bsd-3-clause
1,687
// 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. #include "chrome/browser/chromeos/ui/idle_logout_dialog_view.h" #include "ash/shell.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.h" #include "chrome/browser/ui/browser_list.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager_client.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "ui/aura/root_window.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/controls/label.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" namespace { // Global singleton instance of our dialog class. chromeos::IdleLogoutDialogView* g_instance = NULL; const int kIdleLogoutDialogMaxWidth = 300; const int kCountdownUpdateIntervalMs = 1000; } // namespace namespace chromeos { IdleLogoutSettingsProvider* IdleLogoutDialogView::provider_ = NULL; //////////////////////////////////////////////////////////////////////////////// // IdleLogoutSettingsProvider public methods IdleLogoutSettingsProvider::IdleLogoutSettingsProvider() { } IdleLogoutSettingsProvider::~IdleLogoutSettingsProvider() { } base::TimeDelta IdleLogoutSettingsProvider::GetCountdownUpdateInterval() { return base::TimeDelta::FromMilliseconds(kCountdownUpdateIntervalMs); } KioskModeSettings* IdleLogoutSettingsProvider::GetKioskModeSettings() { return KioskModeSettings::Get(); } void IdleLogoutSettingsProvider::LogoutCurrentUser(IdleLogoutDialogView*) { DBusThreadManager::Get()->GetSessionManagerClient()->StopSession(); } //////////////////////////////////////////////////////////////////////////////// // IdleLogoutDialogView public static methods // static void IdleLogoutDialogView::ShowDialog() { // We only show the dialog if it is not already showing. We don't want two // countdowns on the screen for any reason. If the dialog is closed by using // CloseDialog, we reset g_instance so the next Show will work correctly; in // case the dialog is closed by the system, DeleteDelegate is guaranteed to be // called, in which case we reset g_instance there if not already reset. if (!g_instance) { g_instance = new IdleLogoutDialogView(); g_instance->InitAndShow(); } } // static void IdleLogoutDialogView::CloseDialog() { if (g_instance) g_instance->GetWidget()->Close(); } //////////////////////////////////////////////////////////////////////////////// // Overridden from views::DialogDelegateView int IdleLogoutDialogView::GetDialogButtons() const { return ui::DIALOG_BUTTON_NONE; } ui::ModalType IdleLogoutDialogView::GetModalType() const { return ui::MODAL_TYPE_WINDOW; } string16 IdleLogoutDialogView::GetWindowTitle() const { return l10n_util::GetStringUTF16(IDS_IDLE_LOGOUT_TITLE); } bool IdleLogoutDialogView::Close() { if (timer_.IsRunning()) timer_.Stop(); // We just closed our dialog. The global // instance is invalid now, set it to null. g_instance = NULL; return true; } //////////////////////////////////////////////////////////////////////////////// // IdleLogoutDialog private methods IdleLogoutDialogView::IdleLogoutDialogView() : restart_label_(NULL), weak_ptr_factory_(this) { if (!IdleLogoutDialogView::provider_) IdleLogoutDialogView::provider_ = new IdleLogoutSettingsProvider(); } IdleLogoutDialogView::~IdleLogoutDialogView() { if (this == g_instance) g_instance = NULL; } void IdleLogoutDialogView::InitAndShow() { KioskModeSettings* settings = IdleLogoutDialogView::provider_->GetKioskModeSettings(); if (!settings->is_initialized()) { settings->Initialize(base::Bind(&IdleLogoutDialogView::InitAndShow, weak_ptr_factory_.GetWeakPtr())); return; } ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); restart_label_ = new views::Label(); restart_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); restart_label_->SetMultiLine(true); restart_label_->SetFont(rb.GetFont(ui::ResourceBundle::BaseFont)); views::GridLayout* layout = views::GridLayout::CreatePanel(this); SetLayoutManager(layout); views::ColumnSet* column_set = layout->AddColumnSet(0); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::CENTER, 1, views::GridLayout::FIXED, kIdleLogoutDialogMaxWidth, 0); layout->StartRow(0, 0); layout->AddPaddingRow(0, views::kRelatedControlHorizontalSpacing); layout->StartRow(0, 0); layout->AddView(restart_label_); layout->AddPaddingRow(0, views::kRelatedControlHorizontalSpacing); // We're initialized, show the dialog. Show(); } void IdleLogoutDialogView::Show() { KioskModeSettings* settings = IdleLogoutDialogView::provider_->GetKioskModeSettings(); // Setup the countdown label before showing. countdown_end_time_ = base::Time::Now() + settings->GetIdleLogoutWarningDuration(); UpdateCountdown(); views::DialogDelegate::CreateDialogWidget( this, ash::Shell::GetPrimaryRootWindow(), NULL); GetWidget()->SetAlwaysOnTop(true); GetWidget()->Show(); // Update countdown every 1 second. timer_.Start(FROM_HERE, IdleLogoutDialogView::provider_->GetCountdownUpdateInterval(), this, &IdleLogoutDialogView::UpdateCountdown); } void IdleLogoutDialogView::UpdateCountdown() { base::TimeDelta logout_warning_time = countdown_end_time_ - base::Time::Now(); int64 seconds_left = (logout_warning_time.InMillisecondsF() / base::Time::kMillisecondsPerSecond) + 0.5; if (seconds_left > 1) { restart_label_->SetText(l10n_util::GetStringFUTF16( IDS_IDLE_LOGOUT_WARNING_RESTART, base::Int64ToString16(seconds_left))); } else if (seconds_left > 0) { restart_label_->SetText(l10n_util::GetStringUTF16( IDS_IDLE_LOGOUT_WARNING_RESTART_1S)); } else { // Set the label - the logout probably won't be instant. restart_label_->SetText(l10n_util::GetStringUTF16( IDS_IDLE_LOGOUT_WARNING_RESTART_NOW)); // We're done; stop the timer and logout. timer_.Stop(); IdleLogoutDialogView::provider_->LogoutCurrentUser(this); } } // static IdleLogoutDialogView* IdleLogoutDialogView::current_instance() { return g_instance; } // static void IdleLogoutDialogView::set_settings_provider( IdleLogoutSettingsProvider* provider) { provider_ = provider; } } // namespace chromeos
ThinkingBridge/platform_external_chromium_org
chrome/browser/chromeos/ui/idle_logout_dialog_view.cc
C++
bsd-3-clause
6,885
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.common.io.stream; import org.elasticsearch.Version; import java.io.IOException; /** * Wraps a {@link StreamInput} and delegates to it. To be used to add functionality to an existing stream by subclassing. */ public abstract class FilterStreamInput extends StreamInput { private final StreamInput delegate; protected FilterStreamInput(StreamInput delegate) { this.delegate = delegate; } @Override public byte readByte() throws IOException { return delegate.readByte(); } @Override public void readBytes(byte[] b, int offset, int len) throws IOException { delegate.readBytes(b, offset, len); } @Override public void reset() throws IOException { delegate.reset(); } @Override public int read() throws IOException { return delegate.read(); } @Override public void close() throws IOException { delegate.close(); } @Override public int available() throws IOException { return delegate.available(); } @Override public Version getVersion() { return delegate.getVersion(); } @Override public void setVersion(Version version) { delegate.setVersion(version); } }
strahanjen/strahanjen.github.io
elasticsearch-master/core/src/main/java/org/elasticsearch/common/io/stream/FilterStreamInput.java
Java
bsd-3-clause
2,063
// Type definitions for Chance 1.0.16 // Project: http://chancejs.com // Definitions by: Chris Bowdon <https://github.com/cbowdon> // Brice BERNARD <https://github.com/brikou> // Carlos Sanchez <https://github.com/cafesanu> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Chance { type Seed = number | string; interface Seeded { seed: Seed; } interface ChanceStatic { (): Chance; (seed: Seed): Chance; (generator: () => any): Chance; new (): Chance; new (seed: Seed): Chance; new (generator: () => any): Chance; } interface Chance extends Seeded { // Basics bool(opts?: Options): boolean; character(opts?: Options): string; floating(opts?: Options): number; integer(opts?: Options): number; letter(opts?: Options): string; natural(opts?: Options): number; string(opts?: Options): string; // Text paragraph(opts?: Options): string; sentence(opts?: Options): string; syllable(opts?: Options): string; word(opts?: Options): string; // Person age(opts?: Options): number; gender(): string; birthday(): Date; birthday(opts?: Options): Date | string; cf(opts?: Options): string; cpf(): string; first(opts?: Options): string; last(opts?: Options): string; name(opts?: Options): string; name_prefix(opts?: Options): string; name_suffix(opts?: Options): string; prefix(opts?: Options): string; ssn(opts?: Options): string; suffix(opts?: Options): string; // Mobile animal(opts?: Options): string; // Mobile android_id(): string; apple_token(): string; bb_pin(): string; wp7_anid(): string; wp8_anid2(): string; // Web avatar(opts?: Options): string; color(opts?: Options): string; company(): string; domain(opts?: Options): string; email(opts?: Options): string; fbid(): string; google_analytics(): string; hashtag(): string; ip(): string; ipv6(): string; klout(): string; profession(opts?: Options): string; tld(): string; twitter(): string; url(opts?: Options): string; // Location address(opts?: Options): string; altitude(opts?: Options): number; areacode(): string; city(): string; coordinates(opts?: Options): string; country(opts?: Options): string; depth(opts?: Options): number; geohash(opts?: Options): string; latitude(opts?: Options): number; longitude(opts?: Options): number; phone(opts?: Options): string; postal(): string; province(opts?: Options): string; state(opts?: Options): string; street(opts?: Options): string; zip(opts?: Options): string; // Time ampm(): string; date(): Date; date(opts: DateOptions): Date | string; hammertime(): number; hour(opts?: Options): number; millisecond(): number; minute(): number; month(): string; month(opts: Options): Month; second(): number; timestamp(): number; timezone(): Timezone; weekday(opts: Options): 'Monday' | 'Tuesday' | 'Wednesday' | 'Thursday' | 'Friday' | 'Saturday' | 'Sunday'; year(opts?: Options): string; // Finance cc(opts?: Options): string; cc_type(): string; cc_type(opts: Options): string | CreditCardType; currency(): Currency; currency_pair(): [Currency, Currency]; dollar(opts?: Options): string; euro(opts?: Options): string; exp(): string; exp(opts: Options): string | CreditCardExpiration; exp_month(opts?: Options): string; exp_year(opts?: Options): string; // Helpers capitalize(str: string): string; mixin(desc: MixinDescriptor): any; pad(num: number, width: number, padChar?: string): string; /** * @deprecated Use pickone */ pick<T>(arr: T[]): T; pickone<T>(arr: T[]): T; /** * @deprecated Use pickset */ pick<T>(arr: T[], count: number): T[]; pickset<T>(arr: T[], count?: number): T[]; set: Setter; shuffle<T>(arr: T[]): T[]; // Miscellaneous coin(): string; d4(): number; d6(): number; d8(): number; d10(): number; d12(): number; d20(): number; d30(): number; d100(): number; guid(options?: { version: 4 | 5 }): string; hash(opts?: Options): string; n<T>(generator: () => T, count: number, opts?: Options): T[]; normal(opts?: Options): number; radio(opts?: Options): string; rpg(dice: string): number[]; rpg(dice: string, opts?: Options): number[] | number; tv(opts?: Options): string; unique<T>(generator: () => T, count: number, opts?: Options): T[]; weighted<T>(values: T[], weights: number[]): T; // "Hidden" cc_types(): CreditCardType[]; mersenne_twister(seed?: Seed): any; // API return type not defined in docs months(): Month[]; name_prefixes(): Name[]; provinces(): Name[]; states(): Name[]; street_suffix(): Name; street_suffixes(): Name[]; } // A more rigorous approach might be to produce // the correct options interfaces for each method interface Options { [id: string]: any; } interface DateOptions { string?: boolean; american?: boolean; year?: number; month?: number; day?: number; min?: Date; max?: Date; } interface Month { name: string; short_name: string; numeric: string; } interface CreditCardType { name: string; short_name: string; prefix: string; length: number; } interface Currency { code: string; name: string; } interface CreditCardExpiration { month: string; year: string; } interface MixinDescriptor { [id: string]: () => any; } interface Setter { (key: "firstNames", values: string[]): any; (key: "lastNames", values: string[]): any; (key: "provinces", values: string[]): any; (key: "us_states_and_dc", values: string[]): any; (key: "territories", values: string[]): any; (key: "armed_forces", values: string[]): any; (key: "street_suffixes", values: string[]): any; (key: "months", values: string[]): any; (key: "cc_types", values: string[]): any; (key: "currency_types", values: string[]): any; <T>(key: string, values: T[]): any; } interface Name { name: string; abbreviation: string; } interface Timezone { name: string; abbr: string; offset: number; isdst: boolean; text: string; utc: string[]; } } declare module "chance" { interface ExportedChance extends Chance.ChanceStatic { Chance: ExportedChance; } var Chance: ExportedChance; export = Chance; }
AgentME/DefinitelyTyped
types/chance/index.d.ts
TypeScript
mit
7,513
import { Keystone } from '@keystonejs/keystone'; import { KnexAdapter } from '@keystonejs/adapter-knex'; import { Text, Checkbox, Password } from '@keystonejs/fields'; const keystone = new Keystone({ adapter: new KnexAdapter(), }); keystone.createList('Test', { fields: { name: { type: Text }, email: { type: Text, isUnique: true }, isAdmin: { type: Checkbox }, password: { type: Password }, }, access: true, });
markogresak/DefinitelyTyped
types/keystonejs__fields/keystonejs__fields-tests.ts
TypeScript
mit
463
module Serverspec module Type class Cgroup < Base attr_accessor :subsystem def method_missing(meth) if @subsystem.nil? @subsystem = meth.to_s return self else param = "#{@subsystem}.#{meth.to_s}" ret = backend.run_command("cgget -n -r #{param} #{@name} | awk '{print $2}'") val = ret[:stdout].strip val = val.to_i if val.match(/^\d+$/) val end end end end end
gauravve/serverspec
lib/serverspec/type/cgroup.rb
Ruby
mit
484
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.Win32.SafeHandles { [SecurityCritical] public sealed partial class SafePipeHandle : SafeHandle { internal SafePipeHandle() : base(new IntPtr(DefaultInvalidHandle), true) { } public SafePipeHandle(IntPtr preexistingHandle, bool ownsHandle) : base(new IntPtr(DefaultInvalidHandle), ownsHandle) { SetHandle(preexistingHandle); } internal void SetHandle(int descriptor) { base.SetHandle((IntPtr)descriptor); } } }
iamjasonp/corefx
src/System.IO.Pipes/src/Microsoft/Win32/SafeHandles/SafePipeHandle.cs
C#
mit
849
# frozen_string_literal: true # copied from https://github.com/collectiveidea/delayed_job/blob/master/spec/delayed/backend/test.rb require "ostruct" # An in-memory backend suitable only for testing. Tries to behave as if it were an ORM. module Delayed module Backend module Test class Job attr_accessor :id attr_accessor :priority attr_accessor :attempts attr_accessor :handler attr_accessor :last_error attr_accessor :run_at attr_accessor :locked_at attr_accessor :locked_by attr_accessor :failed_at attr_accessor :queue include Delayed::Backend::Base cattr_accessor :id, default: 0 def initialize(hash = {}) self.attempts = 0 self.priority = 0 self.id = (self.class.id += 1) hash.each { |k, v| send(:"#{k}=", v) } end @jobs = [] def self.all @jobs end def self.count all.size end def self.delete_all all.clear end def self.create(attrs = {}) new(attrs).tap(&:save) end def self.create!(*args); create(*args); end def self.clear_locks!(worker_name) all.select { |j| j.locked_by == worker_name }.each { |j| j.locked_by = nil; j.locked_at = nil } end # Find a few candidate jobs to run (in case some immediately get locked by others). def self.find_available(worker_name, limit = 5, max_run_time = Worker.max_run_time) jobs = all.select do |j| j.run_at <= db_time_now && (j.locked_at.nil? || j.locked_at < db_time_now - max_run_time || j.locked_by == worker_name) && !j.failed? end jobs = jobs.select { |j| Worker.queues.include?(j.queue) } if Worker.queues.any? jobs = jobs.select { |j| j.priority >= Worker.min_priority } if Worker.min_priority jobs = jobs.select { |j| j.priority <= Worker.max_priority } if Worker.max_priority jobs.sort_by { |j| [j.priority, j.run_at] }[0..limit - 1] end # Lock this job for this worker. # Returns true if we have the lock, false otherwise. def lock_exclusively!(max_run_time, worker) now = self.class.db_time_now if locked_by != worker # We don't own this job so we will update the locked_by name and the locked_at self.locked_at = now self.locked_by = worker end true end def self.db_time_now Time.current end def update_attributes(attrs = {}) attrs.each { |k, v| send(:"#{k}=", v) } save end def destroy self.class.all.delete(self) end def save self.run_at ||= Time.current self.class.all << self unless self.class.all.include?(self) true end def save!; save; end def reload reset self end end end end end
Erol/rails
activejob/test/support/delayed_job/delayed/backend/test.rb
Ruby
mit
3,098
// Type definitions for redux-batched-actions 0.1 // Project: https://github.com/tshelburne/redux-batched-actions // Definitions by: Chad Burggraf <https://github.com/ChadBurggraf> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { Action, Reducer } from 'redux'; export as namespace ReduxBatchedActions; /** * Batching action creator that creates a higher-order * action from an array of actions. */ export function batchActions<A extends Action>(actions: A[]): Action; /** * Creates a higher-order reducer that enables batching * actions for the given reducer. */ export function enableBatching<S>(reducer: Reducer<S>): Reducer<S>;
chrismbarr/DefinitelyTyped
redux-batched-actions/index.d.ts
TypeScript
mit
669
/* * drivers/video/tegra/host/host1x/host1x_channel.h * * Tegra Graphics Host Channel * * Copyright (c) 2011, NVIDIA 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; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __NVHOST_HOST1X_CHANNEL_H #define __NVHOST_HOST1X_CHANNEL_H struct nvhost_job; struct nvhost_channel; struct nvhost_hwctx; /* Submit job to a host1x client */ int host1x_channel_submit(struct nvhost_job *job); /* Read 3d register via FIFO */ int host1x_channel_read_3d_reg( struct nvhost_channel *channel, struct nvhost_hwctx *hwctx, u32 offset, u32 *value); /* Reads words from FIFO */ int host1x_drain_read_fifo(void __iomem *chan_regs, u32 *ptr, unsigned int count, unsigned int *pending); int host1x_save_context(struct nvhost_module *mod, u32 syncpt_id); #endif
timduru/tf101-kernel-tegra
drivers/video/tegra_NEW/host/host1x/host1x_channel.h
C
gpl-2.0
1,451
// { dg-options "-std=gnu++0x" } // 2010-09-27 Paolo Carlini <paolo.carlini@oracle.com> // Copyright (C) 2010-2013 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, 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 General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <memory> #include <testsuite_hooks.h> #include <testsuite_tr1.h> struct MyAlloc { }; struct MyDerivedAlloc : public MyAlloc { }; struct UA { }; struct UB { typedef int allocator_type; }; struct UC { typedef MyAlloc allocator_type; }; struct UD { typedef MyDerivedAlloc allocator_type; }; void test01() { bool test __attribute__((unused)) = true; using std::uses_allocator; using namespace __gnu_test; // Positive tests. VERIFY( (test_relationship<uses_allocator, UC, MyAlloc>(true)) ); VERIFY( (test_relationship<uses_allocator, UC, MyDerivedAlloc>(true))); // Negative tests. VERIFY( (test_relationship<uses_allocator, UA, MyAlloc>(false)) ); VERIFY( (test_relationship<uses_allocator, UB, MyAlloc>(false)) ); VERIFY( (test_relationship<uses_allocator, UD, MyAlloc>(false)) ); } int main() { test01(); return 0; }
skristiansson/eco32-gcc
libstdc++-v3/testsuite/20_util/uses_allocator/value.cc
C++
gpl-2.0
1,735
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 2012 Red Hat */ #include <linux/module.h> #include <drm/drm_crtc_helper.h> #include <drm/drm_drv.h> #include <drm/drm_fb_helper.h> #include <drm/drm_file.h> #include <drm/drm_gem_shmem_helper.h> #include <drm/drm_managed.h> #include <drm/drm_ioctl.h> #include <drm/drm_probe_helper.h> #include <drm/drm_print.h> #include "udl_drv.h" static int udl_usb_suspend(struct usb_interface *interface, pm_message_t message) { struct drm_device *dev = usb_get_intfdata(interface); return drm_mode_config_helper_suspend(dev); } static int udl_usb_resume(struct usb_interface *interface) { struct drm_device *dev = usb_get_intfdata(interface); return drm_mode_config_helper_resume(dev); } DEFINE_DRM_GEM_FOPS(udl_driver_fops); static const struct drm_driver driver = { .driver_features = DRIVER_ATOMIC | DRIVER_GEM | DRIVER_MODESET, /* GEM hooks */ .fops = &udl_driver_fops, DRM_GEM_SHMEM_DRIVER_OPS, .name = DRIVER_NAME, .desc = DRIVER_DESC, .date = DRIVER_DATE, .major = DRIVER_MAJOR, .minor = DRIVER_MINOR, .patchlevel = DRIVER_PATCHLEVEL, }; static struct udl_device *udl_driver_create(struct usb_interface *interface) { struct udl_device *udl; int r; udl = devm_drm_dev_alloc(&interface->dev, &driver, struct udl_device, drm); if (IS_ERR(udl)) return udl; r = udl_init(udl); if (r) return ERR_PTR(r); usb_set_intfdata(interface, udl); return udl; } static int udl_usb_probe(struct usb_interface *interface, const struct usb_device_id *id) { int r; struct udl_device *udl; udl = udl_driver_create(interface); if (IS_ERR(udl)) return PTR_ERR(udl); r = drm_dev_register(&udl->drm, 0); if (r) return r; DRM_INFO("Initialized udl on minor %d\n", udl->drm.primary->index); drm_fbdev_generic_setup(&udl->drm, 0); return 0; } static void udl_usb_disconnect(struct usb_interface *interface) { struct drm_device *dev = usb_get_intfdata(interface); drm_kms_helper_poll_fini(dev); udl_drop_usb(dev); drm_dev_unplug(dev); } /* * There are many DisplayLink-based graphics products, all with unique PIDs. * So we match on DisplayLink's VID + Vendor-Defined Interface Class (0xff) * We also require a match on SubClass (0x00) and Protocol (0x00), * which is compatible with all known USB 2.0 era graphics chips and firmware, * but allows DisplayLink to increment those for any future incompatible chips */ static const struct usb_device_id id_table[] = { {.idVendor = 0x17e9, .bInterfaceClass = 0xff, .bInterfaceSubClass = 0x00, .bInterfaceProtocol = 0x00, .match_flags = USB_DEVICE_ID_MATCH_VENDOR | USB_DEVICE_ID_MATCH_INT_CLASS | USB_DEVICE_ID_MATCH_INT_SUBCLASS | USB_DEVICE_ID_MATCH_INT_PROTOCOL,}, {}, }; MODULE_DEVICE_TABLE(usb, id_table); static struct usb_driver udl_driver = { .name = "udl", .probe = udl_usb_probe, .disconnect = udl_usb_disconnect, .suspend = udl_usb_suspend, .resume = udl_usb_resume, .id_table = id_table, }; module_usb_driver(udl_driver); MODULE_LICENSE("GPL");
apopple/linux
drivers/gpu/drm/udl/udl_drv.c
C
gpl-2.0
3,045
/* POSIX compatible FILE stream write function. Copyright (C) 2008-2014 Free Software Foundation, Inc. Written by Bruno Haible <bruno@clisp.org>, 2008. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> /* Specification. */ #include <stdio.h> /* Replace these functions only if module 'nonblocking' or module 'sigpipe' is requested. */ #if GNULIB_NONBLOCKING || GNULIB_SIGPIPE /* On native Windows platforms, SIGPIPE does not exist. When write() is called on a pipe with no readers, WriteFile() fails with error GetLastError() = ERROR_NO_DATA, and write() in consequence fails with error EINVAL. This write() function is at the basis of the function which flushes the buffer of a FILE stream. */ # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__ # include <errno.h> # include <signal.h> # include <io.h> # define WIN32_LEAN_AND_MEAN /* avoid including junk */ # include <windows.h> # include "msvc-nothrow.h" # if GNULIB_NONBLOCKING # define CLEAR_ERRNO \ errno = 0; # define HANDLE_ENOSPC \ if (errno == ENOSPC && ferror (stream)) \ { \ int fd = fileno (stream); \ if (fd >= 0) \ { \ HANDLE h = (HANDLE) _get_osfhandle (fd); \ if (GetFileType (h) == FILE_TYPE_PIPE) \ { \ /* h is a pipe or socket. */ \ DWORD state; \ if (GetNamedPipeHandleState (h, &state, NULL, NULL, \ NULL, NULL, 0) \ && (state & PIPE_NOWAIT) != 0) \ /* h is a pipe in non-blocking mode. \ Change errno from ENOSPC to EAGAIN. */ \ errno = EAGAIN; \ } \ } \ } \ else # else # define CLEAR_ERRNO # define HANDLE_ENOSPC # endif # if GNULIB_SIGPIPE # define CLEAR_LastError \ SetLastError (0); # define HANDLE_ERROR_NO_DATA \ if (GetLastError () == ERROR_NO_DATA && ferror (stream)) \ { \ int fd = fileno (stream); \ if (fd >= 0 \ && GetFileType ((HANDLE) _get_osfhandle (fd)) \ == FILE_TYPE_PIPE) \ { \ /* Try to raise signal SIGPIPE. */ \ raise (SIGPIPE); \ /* If it is currently blocked or ignored, change errno from \ EINVAL to EPIPE. */ \ errno = EPIPE; \ } \ } \ else # else # define CLEAR_LastError # define HANDLE_ERROR_NO_DATA # endif # define CALL_WITH_SIGPIPE_EMULATION(RETTYPE, EXPRESSION, FAILED) \ if (ferror (stream)) \ return (EXPRESSION); \ else \ { \ RETTYPE ret; \ CLEAR_ERRNO \ CLEAR_LastError \ ret = (EXPRESSION); \ if (FAILED) \ { \ HANDLE_ENOSPC \ HANDLE_ERROR_NO_DATA \ ; \ } \ return ret; \ } # if !REPLACE_PRINTF_POSIX /* avoid collision with printf.c */ int printf (const char *format, ...) { int retval; va_list args; va_start (args, format); retval = vfprintf (stdout, format, args); va_end (args); return retval; } # endif # if !REPLACE_FPRINTF_POSIX /* avoid collision with fprintf.c */ int fprintf (FILE *stream, const char *format, ...) { int retval; va_list args; va_start (args, format); retval = vfprintf (stream, format, args); va_end (args); return retval; } # endif # if !REPLACE_VPRINTF_POSIX /* avoid collision with vprintf.c */ int vprintf (const char *format, va_list args) { return vfprintf (stdout, format, args); } # endif # if !REPLACE_VFPRINTF_POSIX /* avoid collision with vfprintf.c */ int vfprintf (FILE *stream, const char *format, va_list args) #undef vfprintf { CALL_WITH_SIGPIPE_EMULATION (int, vfprintf (stream, format, args), ret == EOF) } # endif int putchar (int c) { return fputc (c, stdout); } int fputc (int c, FILE *stream) #undef fputc { CALL_WITH_SIGPIPE_EMULATION (int, fputc (c, stream), ret == EOF) } int fputs (const char *string, FILE *stream) #undef fputs { CALL_WITH_SIGPIPE_EMULATION (int, fputs (string, stream), ret == EOF) } int puts (const char *string) #undef puts { FILE *stream = stdout; CALL_WITH_SIGPIPE_EMULATION (int, puts (string), ret == EOF) } size_t fwrite (const void *ptr, size_t s, size_t n, FILE *stream) #undef fwrite { CALL_WITH_SIGPIPE_EMULATION (size_t, fwrite (ptr, s, n, stream), ret < n) } # endif #endif
wkritzinger/asuswrt-merlin
release/src/router/wget/lib/stdio-write.c
C
gpl-2.0
7,422
Then %r{I should see an image with a path of "([^"]*)"} do |path| page.should have_css("img[src^='#{path}']") end Then %r{^the file at "([^"]*)" is the same as "([^"]*)"$} do |web_file, path| expected = IO.read(path) actual = if web_file.match %r{^https?://} Net::HTTP.get(URI.parse(web_file)) else visit(web_file) page.body end actual.should == expected end
samn/spectral-workbench
webserver/vendor/plugins/paperclip/features/step_definitions/html_steps.rb
Ruby
gpl-3.0
384
type='TrueType' name='Calligrapher-Regular' desc={'Ascent':899,'Descent':-234,'CapHeight':731,'Flags':32,'FontBBox':'[-50 -234 1328 899]','ItalicAngle':0,'StemV':70,'MissingWidth':800} up=-200 ut=20 cw={ '\x00':800,'\x01':800,'\x02':800,'\x03':800,'\x04':800,'\x05':800,'\x06':800,'\x07':800,'\x08':800,'\t':800,'\n':800,'\x0b':800,'\x0c':800,'\r':800,'\x0e':800,'\x0f':800,'\x10':800,'\x11':800,'\x12':800,'\x13':800,'\x14':800,'\x15':800, '\x16':800,'\x17':800,'\x18':800,'\x19':800,'\x1a':800,'\x1b':800,'\x1c':800,'\x1d':800,'\x1e':800,'\x1f':800,' ':282,'!':324,'"':405,'#':584,'$':632,'%':980,'&':776,'\'':259,'(':299,')':299,'*':377,'+':600, ',':259,'-':432,'.':254,'/':597,'0':529,'1':298,'2':451,'3':359,'4':525,'5':423,'6':464,'7':417,'8':457,'9':479,':':275,';':282,'<':600,'=':600,'>':600,'?':501,'@':800,'A':743, 'B':636,'C':598,'D':712,'E':608,'F':562,'G':680,'H':756,'I':308,'J':314,'K':676,'L':552,'M':1041,'N':817,'O':729,'P':569,'Q':698,'R':674,'S':618,'T':673,'U':805,'V':753,'W':1238, 'X':716,'Y':754,'Z':599,'[':315,'\\':463,']':315,'^':600,'_':547,'`':278,'a':581,'b':564,'c':440,'d':571,'e':450,'f':347,'g':628,'h':611,'i':283,'j':283,'k':560,'l':252,'m':976, 'n':595,'o':508,'p':549,'q':540,'r':395,'s':441,'t':307,'u':614,'v':556,'w':915,'x':559,'y':597,'z':452,'{':315,'|':222,'}':315,'~':600,'\x7f':800,'\x80':800,'\x81':800,'\x82':0,'\x83':0, '\x84':0,'\x85':780,'\x86':0,'\x87':0,'\x88':278,'\x89':0,'\x8a':0,'\x8b':0,'\x8c':1064,'\x8d':800,'\x8e':800,'\x8f':800,'\x90':800,'\x91':259,'\x92':259,'\x93':470,'\x94':470,'\x95':500,'\x96':300,'\x97':600,'\x98':278,'\x99':990, '\x9a':0,'\x9b':0,'\x9c':790,'\x9d':800,'\x9e':800,'\x9f':754,'\xa0':282,'\xa1':324,'\xa2':450,'\xa3':640,'\xa4':518,'\xa5':603,'\xa6':0,'\xa7':519,'\xa8':254,'\xa9':800,'\xaa':349,'\xab':0,'\xac':0,'\xad':432,'\xae':800,'\xaf':278, '\xb0':0,'\xb1':0,'\xb2':0,'\xb3':0,'\xb4':278,'\xb5':614,'\xb6':0,'\xb7':254,'\xb8':278,'\xb9':0,'\xba':305,'\xbb':0,'\xbc':0,'\xbd':0,'\xbe':0,'\xbf':501,'\xc0':743,'\xc1':743,'\xc2':743,'\xc3':743,'\xc4':743,'\xc5':743, '\xc6':1060,'\xc7':598,'\xc8':608,'\xc9':608,'\xca':608,'\xcb':608,'\xcc':308,'\xcd':308,'\xce':308,'\xcf':308,'\xd0':0,'\xd1':817,'\xd2':729,'\xd3':729,'\xd4':729,'\xd5':729,'\xd6':729,'\xd7':0,'\xd8':729,'\xd9':805,'\xda':805,'\xdb':805, '\xdc':805,'\xdd':0,'\xde':0,'\xdf':688,'\xe0':581,'\xe1':581,'\xe2':581,'\xe3':581,'\xe4':581,'\xe5':581,'\xe6':792,'\xe7':440,'\xe8':450,'\xe9':450,'\xea':450,'\xeb':450,'\xec':283,'\xed':283,'\xee':283,'\xef':283,'\xf0':800,'\xf1':595, '\xf2':508,'\xf3':508,'\xf4':508,'\xf5':508,'\xf6':508,'\xf7':0,'\xf8':508,'\xf9':614,'\xfa':614,'\xfb':614,'\xfc':614,'\xfd':0,'\xfe':0,'\xff':597} enc='cp1252' diff='' filename='calligra.z' originalsize=40120
sesuncedu/bitcurator
tools/py3fpdf/attic/font/calligra.py
Python
gpl-3.0
2,763
(function() { var BATCH_DRAW_STOP_TIME_DIFF = 500; var now =(function() { if (Kinetic.root.performance && Kinetic.root.performance.now) { return function() { return Kinetic.root.performance.now(); }; } else { return function() { return new Date().getTime(); }; } })(); var RAF = (function() { return Kinetic.root.requestAnimationFrame || Kinetic.root.webkitRequestAnimationFrame || Kinetic.root.mozRequestAnimationFrame || Kinetic.root.oRequestAnimationFrame || Kinetic.root.msRequestAnimationFrame || FRAF; })(); function FRAF(callback) { Kinetic.root.setTimeout(callback, 1000 / 60); } function requestAnimFrame() { return RAF.apply(Kinetic.root, arguments); } /** * Animation constructor. A stage is used to contain multiple layers and handle * @constructor * @memberof Kinetic * @param {Function} func function executed on each animation frame. The function is passed a frame object, which contains * timeDiff, lastTime, time, and frameRate properties. The timeDiff property is the number of milliseconds that have passed * since the last animation frame. The lastTime property is time in milliseconds that elapsed from the moment the animation started * to the last animation frame. The time property is the time in milliseconds that ellapsed from the moment the animation started * to the current animation frame. The frameRate property is the current frame rate in frames / second * @param {Kinetic.Layer|Array} [layers] layer(s) to be redrawn on each animation frame. Can be a layer, an array of layers, or null. * Not specifying a node will result in no redraw. * @example * // move a node to the right at 50 pixels / second<br> * var velocity = 50;<br><br> * * var anim = new Kinetic.Animation(function(frame) {<br> * var dist = velocity * (frame.timeDiff / 1000);<br> * node.move(dist, 0);<br> * }, layer);<br><br> * * anim.start(); */ Kinetic.Animation = function(func, layers) { var Anim = Kinetic.Animation; this.func = func; this.setLayers(layers); this.id = Anim.animIdCounter++; this.frame = { time: 0, timeDiff: 0, lastTime: now() }; }; /* * Animation methods */ Kinetic.Animation.prototype = { /** * set layers to be redrawn on each animation frame * @method * @memberof Kinetic.Animation.prototype * @param {Kinetic.Layer|Array} [layers] layer(s) to be redrawn.&nbsp; Can be a layer, an array of layers, or null. Not specifying a node will result in no redraw. */ setLayers: function(layers) { var lays = []; // if passing in no layers if (!layers) { lays = []; } // if passing in an array of Layers // NOTE: layers could be an array or Kinetic.Collection. for simplicity, I'm just inspecting // the length property to check for both cases else if (layers.length > 0) { lays = layers; } // if passing in a Layer else { lays = [layers]; } this.layers = lays; }, /** * get layers * @method * @memberof Kinetic.Animation.prototype */ getLayers: function() { return this.layers; }, /** * add layer. Returns true if the layer was added, and false if it was not * @method * @memberof Kinetic.Animation.prototype * @param {Kinetic.Layer} layer */ addLayer: function(layer) { var layers = this.layers, len, n; if (layers) { len = layers.length; // don't add the layer if it already exists for (n = 0; n < len; n++) { if (layers[n]._id === layer._id) { return false; } } } else { this.layers = []; } this.layers.push(layer); return true; }, /** * determine if animation is running or not. returns true or false * @method * @memberof Kinetic.Animation.prototype */ isRunning: function() { var a = Kinetic.Animation, animations = a.animations, len = animations.length, n; for(n = 0; n < len; n++) { if(animations[n].id === this.id) { return true; } } return false; }, /** * start animation * @method * @memberof Kinetic.Animation.prototype */ start: function() { var Anim = Kinetic.Animation; this.stop(); this.frame.timeDiff = 0; this.frame.lastTime = now(); Anim._addAnimation(this); }, /** * stop animation * @method * @memberof Kinetic.Animation.prototype */ stop: function() { Kinetic.Animation._removeAnimation(this); }, _updateFrameObject: function(time) { this.frame.timeDiff = time - this.frame.lastTime; this.frame.lastTime = time; this.frame.time += this.frame.timeDiff; this.frame.frameRate = 1000 / this.frame.timeDiff; } }; Kinetic.Animation.animations = []; Kinetic.Animation.animIdCounter = 0; Kinetic.Animation.animRunning = false; Kinetic.Animation._addAnimation = function(anim) { this.animations.push(anim); this._handleAnimation(); }; Kinetic.Animation._removeAnimation = function(anim) { var id = anim.id, animations = this.animations, len = animations.length, n; for(n = 0; n < len; n++) { if(animations[n].id === id) { this.animations.splice(n, 1); break; } } }; Kinetic.Animation._runFrames = function() { var layerHash = {}, animations = this.animations, anim, layers, func, n, i, layersLen, layer, key; /* * loop through all animations and execute animation * function. if the animation object has specified node, * we can add the node to the nodes hash to eliminate * drawing the same node multiple times. The node property * can be the stage itself or a layer */ /* * WARNING: don't cache animations.length because it could change while * the for loop is running, causing a JS error */ for(n = 0; n < animations.length; n++) { anim = animations[n]; layers = anim.layers; func = anim.func; anim._updateFrameObject(now()); layersLen = layers.length; for (i=0; i<layersLen; i++) { layer = layers[i]; if(layer._id !== undefined) { layerHash[layer._id] = layer; } } // if animation object has a function, execute it if(func) { func.call(anim, anim.frame); } } for(key in layerHash) { layerHash[key].draw(); } }; Kinetic.Animation._animationLoop = function() { var Anim = Kinetic.Animation; if(Anim.animations.length) { requestAnimFrame(Anim._animationLoop); Anim._runFrames(); } else { Anim.animRunning = false; } }; Kinetic.Animation._handleAnimation = function() { var that = this; if(!this.animRunning) { this.animRunning = true; that._animationLoop(); } }; var moveTo = Kinetic.Node.prototype.moveTo; Kinetic.Node.prototype.moveTo = function(container) { moveTo.call(this, container); }; /** * batch draw * @method * @memberof Kinetic.Layer.prototype */ Kinetic.Layer.prototype.batchDraw = function() { var that = this, Anim = Kinetic.Animation; if (!this.batchAnim) { this.batchAnim = new Anim(function() { if (that.lastBatchDrawTime && now() - that.lastBatchDrawTime > BATCH_DRAW_STOP_TIME_DIFF) { that.batchAnim.stop(); } }, this); } this.lastBatchDrawTime = now(); if (!this.batchAnim.isRunning()) { this.draw(); this.batchAnim.start(); } }; /** * batch draw * @method * @memberof Kinetic.Stage.prototype */ Kinetic.Stage.prototype.batchDraw = function() { this.getChildren().each(function(layer) { layer.batchDraw(); }); }; })((1,eval)('this'));
kimadactyl/NoiseEater
public/js/vendor/kineticjs/src/Animation.js
JavaScript
gpl-3.0
9,374
// test for iterating over function properties var d = ""; function f(a,b) {} f.c = "Foo"; for (i in f) d+=i; result = d == "c";
lancernet/Espruino
tests/test_iterate_function_object_props_for_in.js
JavaScript
mpl-2.0
134
<%! from django.utils.translation import ugettext as _ %> <%! from django.core.urlresolvers import reverse %> <%inherit file="../main.html" /> <%namespace name='static' file='/static_content.html'/> <%block name="bodyclass">register verification-process is-not-verified step-confirmation</%block> <%block name="pagetitle">${_("Re-Verification Submission Confirmation")}</%block> <%block name="js_extra"> <script src="${static.url('js/vendor/responsive-carousel/responsive-carousel.js')}"></script> <script src="${static.url('js/vendor/responsive-carousel/responsive-carousel.keybd.js')}"></script> </%block> <%block name="content"> <div class="container"> <section class="wrapper"> <div class="wrapper-progress"> <section class="progress"> <h3 class="sr title">${_("Your Progress")}</h3> <ol class="progress-steps"> <li class="progress-step is-completed" id="progress-step1"> <span class="wrapper-step-number"><span class="step-number">1</span></span> <span class="step-name">${_("Re-Take Photo")}</span> </li> <li class="progress-step is-completed" id="progress-step2"> <span class="wrapper-step-number"><span class="step-number">2</span></span> <span class="step-name">${_("Re-Take ID Photo")}</span> </li> <li class="progress-step is-completed" id="progress-step3"> <span class="wrapper-step-number"><span class="step-number">3</span></span> <span class="step-name">${_("Review")}</span> </li> <li class="progress-step is-current progress-step-icon" id="progress-step4"> <span class="wrapper-step-number"><span class="step-number"> <i class="icon fa fa-check-square-o"></i> </span></span> <span class="step-name"><span class="sr">${_("Current Step: ")}</span>${_("Confirmation")}</span> </li> </ol> <span class="progress-sts"> <span class="progress-sts-value"></span> </span> </section> </div> <div class="wrapper-content-main"> <article class="content-main"> <section class="content-confirmation"> <div class="wrapper-view"> <div class="view"> <h3 class="title">${_("Your Credentials Have Been Updated")}</h3> <div class="instruction"> <p>${_("We've captured your re-submitted information and will review it to verify your identity shortly. You should receive an update to your veriication status within 1-2 days. In the meantime, you still have access to all of your course content.")}</p> </div> <ol class="list-nav"> <li class="nav-item"> <a class="action action-primary" href="${reverse('dashboard')}">${_("Return to Your Dashboard")}</a> </li> </ol> </div> <!-- /view --> </div> <!-- /wrapper-view --> </section> </article> </div> <!-- /wrapper-content-main --> <%include file="_reverification_support.html" /> </section> </div> </%block>
olexiim/edx-platform
lms/templates/verify_student/reverification_confirmation.html
HTML
agpl-3.0
3,158
// @(#)root/roostats:$Id$ // Author: Kyle Cranmer /************************************************************************* * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOSTATS_BernsteinCorrection #define ROOSTATS_BernsteinCorrection #ifndef ROOT_Rtypes #include "Rtypes.h" #endif #include "TH1F.h" #include "RooWorkspace.h" namespace RooStats { class BernsteinCorrection { public: BernsteinCorrection(double tolerance = 0.05); virtual ~BernsteinCorrection() {} Int_t ImportCorrectedPdf(RooWorkspace*, const char*,const char*,const char*); void SetMaxCorrection(Double_t maxCorr){fMaxCorrection = maxCorr;} void SetMaxDegree(Int_t maxDegree){fMaxDegree = maxDegree;} void CreateQSamplingDist(RooWorkspace* wks, const char* nominalName, const char* varName, const char* dataName, TH1F*, TH1F*, Int_t degree, Int_t nToys=500); private: Int_t fMaxDegree; // maximum polynomial degree correction (default is 10) Double_t fMaxCorrection; // maximum correction factor at any point (default is 100) Double_t fTolerance; // probability to add an unnecessary term protected: ClassDef(BernsteinCorrection,2) // A utility to add polynomial corrrection terms to a model to improve the description of data. }; } #endif
perovic/root
roofit/roostats/inc/RooStats/BernsteinCorrection.h
C
lgpl-2.1
1,926
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.sql.qa.security; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.xpack.sql.qa.cli.EmbeddedCli.SecurityConfig; import org.elasticsearch.xpack.sql.qa.cli.SelectTestCase; public class CliSelectIT extends SelectTestCase { @Override protected Settings restClientSettings() { return RestSqlIT.securitySettings(); } @Override protected String getProtocol() { return RestSqlIT.SSL_ENABLED ? "https" : "http"; } @Override protected SecurityConfig securityConfig() { return CliSecurityIT.adminSecurityConfig(); } }
nknize/elasticsearch
x-pack/plugin/sql/qa/server/security/src/test/java/org/elasticsearch/xpack/sql/qa/security/CliSelectIT.java
Java
apache-2.0
871
// Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.auth.ldap; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; abstract class LdapType { static final LdapType RFC_2307 = new Rfc2307(); static LdapType guessType(final DirContext ctx) throws NamingException { final Attributes rootAtts = ctx.getAttributes(""); Attribute supported = rootAtts.get("supportedCapabilities"); if (supported != null && (supported.contains("1.2.840.113556.1.4.800") || supported.contains("1.2.840.113556.1.4.1851"))) { return new ActiveDirectory(); } return RFC_2307; } abstract String groupPattern(); abstract String groupMemberPattern(); abstract String groupName(); abstract String accountFullName(); abstract String accountEmailAddress(); abstract String accountSshUserName(); abstract String accountMemberField(); abstract String accountPattern(); private static class Rfc2307 extends LdapType { @Override String groupPattern() { return "(cn=${groupname})"; } @Override String groupMemberPattern() { return "(|(memberUid=${username})(gidNumber=${gidNumber}))"; } @Override String groupName() { return "cn"; } @Override String accountFullName() { return "displayName"; } @Override String accountEmailAddress() { return "mail"; } @Override String accountSshUserName() { return "uid"; } @Override String accountMemberField() { return null; // Not defined in RFC 2307 } @Override String accountPattern() { return "(uid=${username})"; } } private static class ActiveDirectory extends LdapType { @Override String groupPattern() { return "(&(objectClass=group)(cn=${groupname}))"; } @Override String groupName() { return "cn"; } @Override String groupMemberPattern() { return null; // Active Directory uses memberOf in the account } @Override String accountFullName() { return "${givenName} ${sn}"; } @Override String accountEmailAddress() { return "mail"; } @Override String accountSshUserName() { return "${sAMAccountName.toLowerCase}"; } @Override String accountMemberField() { return "memberOf"; } @Override String accountPattern() { return "(&(objectClass=user)(sAMAccountName=${username}))"; } } }
gracefullife/gerrit
gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapType.java
Java
apache-2.0
3,163
// Copyright 2014 The Crashpad 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. #ifndef CRASHPAD_COMPAT_NON_WIN_WINNT_H_ #define CRASHPAD_COMPAT_NON_WIN_WINNT_H_ #include <stdint.h> //! \file //! \anchor VER_SUITE_x //! \name VER_SUITE_* //! //! \brief Installable product values for MINIDUMP_SYSTEM_INFO::SuiteMask. //! \{ #define VER_SUITE_SMALLBUSINESS 0x0001 #define VER_SUITE_ENTERPRISE 0x0002 #define VER_SUITE_BACKOFFICE 0x0004 #define VER_SUITE_COMMUNICATIONS 0x0008 #define VER_SUITE_TERMINAL 0x0010 #define VER_SUITE_SMALLBUSINESS_RESTRICTED 0x0020 #define VER_SUITE_EMBEDDEDNT 0x0040 #define VER_SUITE_DATACENTER 0x0080 #define VER_SUITE_SINGLEUSERTS 0x0100 #define VER_SUITE_PERSONAL 0x0200 #define VER_SUITE_BLADE 0x0400 #define VER_SUITE_EMBEDDED_RESTRICTED 0x0800 #define VER_SUITE_SECURITY_APPLIANCE 0x1000 #define VER_SUITE_STORAGE_SERVER 0x2000 #define VER_SUITE_COMPUTE_SERVER 0x4000 #define VER_SUITE_WH_SERVER 0x8000 //! \} //! \brief The maximum number of exception parameters present in the //! MINIDUMP_EXCEPTION::ExceptionInformation array. #define EXCEPTION_MAXIMUM_PARAMETERS 15 //! \anchor PROCESSOR_ARCHITECTURE_x //! \name PROCESSOR_ARCHITECTURE_* //! //! \brief CPU type values for MINIDUMP_SYSTEM_INFO::ProcessorArchitecture. //! //! \sa crashpad::MinidumpCPUArchitecture //! \{ #define PROCESSOR_ARCHITECTURE_INTEL 0 #define PROCESSOR_ARCHITECTURE_MIPS 1 #define PROCESSOR_ARCHITECTURE_ALPHA 2 #define PROCESSOR_ARCHITECTURE_PPC 3 #define PROCESSOR_ARCHITECTURE_SHX 4 #define PROCESSOR_ARCHITECTURE_ARM 5 #define PROCESSOR_ARCHITECTURE_IA64 6 #define PROCESSOR_ARCHITECTURE_ALPHA64 7 #define PROCESSOR_ARCHITECTURE_MSIL 8 #define PROCESSOR_ARCHITECTURE_AMD64 9 #define PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 10 #define PROCESSOR_ARCHITECTURE_NEUTRAL 11 #define PROCESSOR_ARCHITECTURE_ARM64 12 #define PROCESSOR_ARCHITECTURE_ARM32_ON_WIN64 13 #define PROCESSOR_ARCHITECTURE_UNKNOWN 0xffff //! \} //! \anchor PF_x //! \name PF_* //! //! \brief CPU feature values for \ref CPU_INFORMATION::ProcessorFeatures //! "CPU_INFORMATION::OtherCpuInfo::ProcessorFeatures". //! //! \{ #define PF_FLOATING_POINT_PRECISION_ERRATA 0 #define PF_FLOATING_POINT_EMULATED 1 #define PF_COMPARE_EXCHANGE_DOUBLE 2 #define PF_MMX_INSTRUCTIONS_AVAILABLE 3 #define PF_PPC_MOVEMEM_64BIT_OK 4 #define PF_ALPHA_BYTE_INSTRUCTIONS 5 #define PF_XMMI_INSTRUCTIONS_AVAILABLE 6 #define PF_3DNOW_INSTRUCTIONS_AVAILABLE 7 #define PF_RDTSC_INSTRUCTION_AVAILABLE 8 #define PF_PAE_ENABLED 9 #define PF_XMMI64_INSTRUCTIONS_AVAILABLE 10 #define PF_SSE_DAZ_MODE_AVAILABLE 11 #define PF_NX_ENABLED 12 #define PF_SSE3_INSTRUCTIONS_AVAILABLE 13 #define PF_COMPARE_EXCHANGE128 14 #define PF_COMPARE64_EXCHANGE128 15 #define PF_CHANNELS_ENABLED 16 #define PF_XSAVE_ENABLED 17 #define PF_ARM_VFP_32_REGISTERS_AVAILABLE 18 #define PF_ARM_NEON_INSTRUCTIONS_AVAILABLE 19 #define PF_SECOND_LEVEL_ADDRESS_TRANSLATION 20 #define PF_VIRT_FIRMWARE_ENABLED 21 #define PF_RDWRFSGSBASE_AVAILABLE 22 #define PF_FASTFAIL_AVAILABLE 23 #define PF_ARM_DIVIDE_INSTRUCTION_AVAILABLE 24 #define PF_ARM_64BIT_LOADSTORE_ATOMIC 25 #define PF_ARM_EXTERNAL_CACHE_AVAILABLE 26 #define PF_ARM_FMAC_INSTRUCTIONS_AVAILABLE 27 #define PF_RDRAND_INSTRUCTION_AVAILABLE 28 #define PF_ARM_V8_INSTRUCTIONS_AVAILABLE 29 #define PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE 30 #define PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE 31 #define PF_RDTSCP_INSTRUCTION_AVAILABLE 32 //! \} //! \anchor PAGE_x //! \name PAGE_* //! //! \brief Memory protection constants for MINIDUMP_MEMORY_INFO::Protect and //! MINIDUMP_MEMORY_INFO::AllocationProtect. //! \{ #define PAGE_NOACCESS 0x1 #define PAGE_READONLY 0x2 #define PAGE_READWRITE 0x4 #define PAGE_WRITECOPY 0x8 #define PAGE_EXECUTE 0x10 #define PAGE_EXECUTE_READ 0x20 #define PAGE_EXECUTE_READWRITE 0x40 #define PAGE_EXECUTE_WRITECOPY 0x80 #define PAGE_GUARD 0x100 #define PAGE_NOCACHE 0x200 #define PAGE_WRITECOMBINE 0x400 //! \} //! \anchor MEM_x //! \name MEM_* //! //! \brief Memory state and type constants for MINIDUMP_MEMORY_INFO::State and //! MINIDUMP_MEMORY_INFO::Type. //! \{ #define MEM_COMMIT 0x1000 #define MEM_RESERVE 0x2000 #define MEM_DECOMMIT 0x4000 #define MEM_RELEASE 0x8000 #define MEM_FREE 0x10000 #define MEM_PRIVATE 0x20000 #define MEM_MAPPED 0x40000 #define MEM_RESET 0x80000 //! \} //! \brief The maximum number of distinct identifiable features that could //! possibly be carried in an XSAVE area. //! //! This corresponds to the number of bits in the XSAVE state-component bitmap, //! XSAVE_BV. See Intel Software Developer’s Manual, Volume 1: Basic //! Architecture (253665-060), 13.4.2 “XSAVE Header”. #define MAXIMUM_XSTATE_FEATURES (64) //! \brief The location of a single state component within an XSAVE area. struct XSTATE_FEATURE { //! \brief The location of a state component within a CPU-specific context //! structure. //! //! This is equivalent to the difference (`ptrdiff_t`) between the return //! value of `LocateXStateFeature()` and its \a Context argument. uint32_t Offset; //! \brief The size of a state component with a CPU-specific context //! structure. //! //! This is equivalent to the size returned by `LocateXStateFeature()` in \a //! Length. uint32_t Size; }; //! \anchor IMAGE_DEBUG_MISC_x //! \name IMAGE_DEBUG_MISC_* //! //! Data type values for IMAGE_DEBUG_MISC::DataType. //! \{ //! \brief A pointer to a `.dbg` file. //! //! IMAGE_DEBUG_MISC::Data will contain the path or file name of the `.dbg` file //! associated with the module. #define IMAGE_DEBUG_MISC_EXENAME 1 //! \} //! \brief Miscellaneous debugging record. //! //! This structure is referenced by MINIDUMP_MODULE::MiscRecord. It is obsolete, //! superseded by the CodeView record. struct IMAGE_DEBUG_MISC { //! \brief The type of data carried in the #Data field. //! //! This is a value of \ref IMAGE_DEBUG_MISC_x "IMAGE_DEBUG_MISC_*". uint32_t DataType; //! \brief The length of this structure in bytes, including the entire #Data //! field and its `NUL` terminator. //! //! \note The Windows documentation states that this field is rounded up to //! nearest nearest 4-byte multiple. uint32_t Length; //! \brief The encoding of the #Data field. //! //! If this field is `0`, #Data contains narrow or multibyte character data. //! If this field is `1`, #Data is UTF-16-encoded. //! //! On Windows, with this field set to `0`, #Data will be encoded in the code //! page of the system that linked the module. On other operating systems, //! UTF-8 may be used. uint8_t Unicode; uint8_t Reserved[3]; //! \brief The data carried within this structure. //! //! For string data, this field will be `NUL`-terminated. If #Unicode is `1`, //! this field is UTF-16-encoded, and will be terminated by a UTF-16 `NUL` //! code unit (two `NUL` bytes). uint8_t Data[1]; }; //! \anchor VER_NT_x //! \name VER_NT_* //! //! \brief Operating system type values for MINIDUMP_SYSTEM_INFO::ProductType. //! //! \sa crashpad::MinidumpOSType //! \{ #define VER_NT_WORKSTATION 1 #define VER_NT_DOMAIN_CONTROLLER 2 #define VER_NT_SERVER 3 //! \} //! \anchor VER_PLATFORM_x //! \name VER_PLATFORM_* //! //! \brief Operating system family values for MINIDUMP_SYSTEM_INFO::PlatformId. //! //! \sa crashpad::MinidumpOS //! \{ #define VER_PLATFORM_WIN32s 0 #define VER_PLATFORM_WIN32_WINDOWS 1 #define VER_PLATFORM_WIN32_NT 2 //! \} #endif // CRASHPAD_COMPAT_NON_WIN_WINNT_H_
scheib/chromium
third_party/crashpad/crashpad/compat/non_win/winnt.h
C
bsd-3-clause
8,032
# Fixtures were created for acts_as_adjency_list, but now we have nested set, so we need to rebuild it after import Taxon.rebuild! Taxon.all.each{|t| t.send(:set_permalink); t.save}
rafarubert/loja
vendor/spree/db/sample/taxons.rb
Ruby
bsd-3-clause
182
describe "Complex#rationalize" do it "raises RangeError if self has non-zero imaginary part" do lambda { Complex(1,5).rationalize }.should raise_error(RangeError) end it "raises RangeError if self has 0.0 imaginary part" do lambda { Complex(1,0.0).rationalize }.should raise_error(RangeError) end it "returns a Rational if self has zero imaginary part" do Complex(1,0).rationalize.should == Rational(1,1) Complex(2<<63+5).rationalize.should == Rational(2<<63+5,1) end ruby_bug "redmine #5178", "1.9.3.0" do it "sends #rationalize to the real part" do real = mock_numeric('real') real.should_receive(:rationalize).with(0.1).and_return(:result) Complex(real, 0).rationalize(0.1).should == :result end end it "ignores a single argument" do Complex(1,0).rationalize(0.1).should == Rational(1,1) end it "raises ArgumentError when passed more than one argument" do lambda { Complex(1,0).rationalize(0.1, 0.1) }.should raise_error(ArgumentError) lambda { Complex(1,0).rationalize(0.1, 0.1, 2) }.should raise_error(ArgumentError) end end
digitalextremist/rubinius
spec/ruby/core/complex/rationalize_spec.rb
Ruby
bsd-3-clause
1,113
#!/usr/bin/env bash # Copyright 2015, 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. # # This script is invoked by Jenkins and runs full performance test suite. set -ex # Enter the gRPC repo root cd $(dirname $0)/../.. # run 8core client vs 8core server tools/run_tests/run_performance_tests.py \ -l c++ csharp node ruby java python go node_express \ --netperf \ --category scalable \ --bq_result_table performance_test.performance_experiment \ --remote_worker_host grpc-performance-server-8core grpc-performance-client-8core grpc-performance-client2-8core \ --xml_report report_8core.xml \ || EXIT_CODE=1 # prevent pushing leftover build files to remote hosts in the next step. git clean -fdxq --exclude='report*.xml' # scalability with 32cores (and upload to a different BQ table) tools/run_tests/run_performance_tests.py \ -l c++ java csharp go \ --netperf \ --category scalable \ --bq_result_table performance_test.performance_experiment_32core \ --remote_worker_host grpc-performance-server-32core grpc-performance-client-32core grpc-performance-client2-32core \ --xml_report report_32core.xml \ || EXIT_CODE=1 # prevent pushing leftover build files to remote hosts in the next step. git clean -fdxq --exclude='report*.xml' # selected scenarios on Windows tools/run_tests/run_performance_tests.py \ -l csharp \ --category scalable \ --bq_result_table performance_test.performance_experiment_windows \ --remote_worker_host grpc-performance-windows1 grpc-performance-windows2 \ --xml_report report_windows.xml \ || EXIT_CODE=1 exit $EXIT_CODE
7anner/grpc
tools/jenkins/run_full_performance.sh
Shell
bsd-3-clause
3,096
YUI.add('datatable-body', function(Y) { /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. @module datatable @submodule datatable-body @since 3.5.0 **/ var Lang = Y.Lang, isArray = Lang.isArray, isNumber = Lang.isNumber, isString = Lang.isString, fromTemplate = Lang.sub, htmlEscape = Y.Escape.html, toArray = Y.Array, bind = Y.bind, YObject = Y.Object, ClassNameManager = Y.ClassNameManager, _getClassName = ClassNameManager.getClassName; /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. Translates the provided `modelList` into a rendered `<tbody>` based on the data in the constituent Models, altered or ammended by any special column configurations. The `columns` configuration, passed to the constructor, determines which columns will be rendered. The rendering process involves constructing an HTML template for a complete row of data, built by concatenating a customized copy of the instance's `CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is then populated with values from each Model in the `modelList`, aggregating a complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @class BodyView @namespace DataTable @extends View @since 3.5.0 **/ Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], { // -- Instance properties ------------------------------------------------- /** HTML template used to create table cells. @property CELL_TEMPLATE @type {HTML} @default '<td {headers} class="{className}">{content}</td>' @since 3.5.0 **/ CELL_TEMPLATE: '<td {headers} class="{className}">{content}</td>', /** CSS class applied to even rows. This is assigned at instantiation after setting up the `_cssPrefix` for the instance. For DataTable, this will be `yui3-datatable-even`. @property CLASS_EVEN @type {String} @default 'yui3-table-even' @since 3.5.0 **/ //CLASS_EVEN: null /** CSS class applied to odd rows. This is assigned at instantiation after setting up the `_cssPrefix` for the instance. When used by DataTable instances, this will be `yui3-datatable-odd`. @property CLASS_ODD @type {String} @default 'yui3-table-odd' @since 3.5.0 **/ //CLASS_ODD: null /** HTML template used to create table rows. @property ROW_TEMPLATE @type {HTML} @default '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>' @since 3.5.0 **/ ROW_TEMPLATE : '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>', /** The object that serves as the source of truth for column and row data. This property is assigned at instantiation from the `source` property of the configuration object passed to the constructor. @property source @type {Object} @default (initially unset) @since 3.5.0 **/ //TODO: should this be protected? //source: null, // -- Public methods ------------------------------------------------------ /** Returns the `<td>` Node from the given row and column index. Alternately, the `seed` can be a Node. If so, the nearest ancestor cell is returned. If the `seed` is a cell, it is returned. If there is no cell at the given coordinates, `null` is returned. Optionally, include an offset array or string to return a cell near the cell identified by the `seed`. The offset can be an array containing the number of rows to shift followed by the number of columns to shift, or one of "above", "below", "next", or "previous". <pre><code>// Previous cell in the previous row var cell = table.getCell(e.target, [-1, -1]); // Next cell var cell = table.getCell(e.target, 'next'); var cell = table.getCell(e.taregt, [0, 1];</pre></code> @method getCell @param {Number[]|Node} seed Array of row and column indexes, or a Node that is either the cell itself or a descendant of one. @param {Number[]|String} [shift] Offset by which to identify the returned cell Node @return {Node} @since 3.5.0 **/ getCell: function (seed, shift) { var tbody = this.get('container'), row, cell, index, rowIndexOffset; if (seed && tbody) { if (isArray(seed)) { row = tbody.get('children').item(seed[0]); cell = row && row.get('children').item(seed[1]); } else if (Y.instanceOf(seed, Y.Node)) { cell = seed.ancestor('.' + this.getClassName('cell'), true); } if (cell && shift) { rowIndexOffset = tbody.get('firstChild.rowIndex'); if (isString(shift)) { // TODO this should be a static object map switch (shift) { case 'above' : shift = [-1, 0]; break; case 'below' : shift = [1, 0]; break; case 'next' : shift = [0, 1]; break; case 'previous': shift = [0, -1]; break; } } if (isArray(shift)) { index = cell.get('parentNode.rowIndex') + shift[0] - rowIndexOffset; row = tbody.get('children').item(index); index = cell.get('cellIndex') + shift[1]; cell = row && row.get('children').item(index); } } } return cell || null; }, /** Builds a CSS class name from the provided tokens. If the instance is created with `cssPrefix` or `source` in the configuration, it will use this prefix (the `_cssPrefix` of the `source` object) as the base token. This allows class instances to generate markup with class names that correspond to the parent class that is consuming them. @method getClassName @param {String} token* Any number of tokens to include in the class name @return {String} The generated class name @since 3.5.0 **/ getClassName: function () { var args = toArray(arguments); args.unshift(this._cssPrefix); args.push(true); return _getClassName.apply(ClassNameManager, args); }, /** Returns the Model associated to the record `id`, `clientId`, or index (not row index). If a DOM element id or Node for a table row or child of a row is passed, that will work, too. If no Model can be found, `null` is returned. @method getRecord @param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or identifier for a row or child element @return {Model} @since 3.5.0 **/ getRecord: function (seed) { var modelList = this.get('modelList'), tbody = this.get('container'), row = null, record; if (tbody) { if (isString(seed)) { if (!record) { seed = tbody.one('#' + seed); } } if (Y.instanceOf(seed, Y.Node)) { row = seed.ancestor(function (node) { return node.get('parentNode').compareTo(tbody); }, true); record = row && modelList.getByClientId(row.getData('yui3-record')); } } return record || null; }, /** Returns the `<tr>` Node from the given row index, Model, or Model's `clientId`. If the rows haven't been rendered yet, or if the row can't be found by the input, `null` is returned. @method getRow @param {Number|String|Model} id Row index, Model instance, or clientId @return {Node} @since 3.5.0 **/ getRow: function (id) { var tbody = this.get('container') || null; if (id) { id = this._idMap[id.get ? id.get('clientId') : id] || id; } return tbody && Y.one(isNumber(id) ? tbody.get('children').item(id) : '#' + id); }, /** Creates the table's `<tbody>` content by assembling markup generated by populating the `ROW\_TEMPLATE`, and `CELL\_TEMPLATE` templates with content from the `columns` property and `modelList` attribute. The rendering process happens in three stages: 1. A row template is assembled from the `columns` property (see `_createRowTemplate`) 2. An HTML string is built up by concatening the application of the data in each Model in the `modelList` to the row template. For cells with `formatter`s, the function is called to generate cell content. Cells with `nodeFormatter`s are ignored. For all other cells, the data value from the Model attribute for the given column key is used. The accumulated row markup is then inserted into the container. 3. If any column is configured with a `nodeFormatter`, the `modelList` is iterated again to apply the `nodeFormatter`s. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @method render @return {BodyView} The instance @chainable @since 3.5.0 **/ render: function () { var tbody = this.get('container'), data = this.get('modelList'), columns = this.columns; // Needed for mutation this._createRowTemplate(columns); if (tbody && data) { tbody.setContent(this._createDataHTML(columns)); this._applyNodeFormatters(tbody, columns); } this.bindUI(); return this; }, // -- Protected and private methods --------------------------------------- /** Handles changes in the source's columns attribute. Redraws the table data. @method _afterColumnsChange @param {EventFacade} e The `columnsChange` event object @protected @since 3.5.0 **/ // TODO: Preserve existing DOM // This will involve parsing and comparing the old and new column configs // and reacting to four types of changes: // 1. formatter, nodeFormatter, emptyCellValue changes // 2. column deletions // 3. column additions // 4. column moves (preserve cells) _afterColumnsChange: function (e) { this.columns = this._parseColumns(e.newVal); this.render(); }, /** Handles modelList changes, including additions, deletions, and updates. Modifies the existing table DOM accordingly. @method _afterDataChange @param {EventFacade} e The `change` event from the ModelList @protected @since 3.5.0 **/ _afterDataChange: function (e) { // Baseline view will just rerender the tbody entirely this.render(); }, /** Reacts to a change in the instance's `modelList` attribute by breaking down the bubbling relationship with the previous `modelList` and setting up that relationship with the new one. @method _afterModelListChange @param {EventFacade} e The `modelListChange` event @protected @since 3.5.0 **/ _afterModelListChange: function (e) { var old = e.prevVal, now = e.newVal; if (old && old.removeTarget) { old.removeTarget(this); } if (now && now.addTarget(this)) { now.addTarget(this); } this._idMap = {}; }, /** Iterates the `modelList`, and calls any `nodeFormatter`s found in the `columns` param on the appropriate cell Nodes in the `tbody`. @method _applyNodeFormatters @param {Node} tbody The `<tbody>` Node whose columns to update @param {Object[]} columns The column configurations @protected @since 3.5.0 **/ _applyNodeFormatters: function (tbody, columns) { var source = this.source, data = this.get('modelList'), formatters = [], linerQuery = '.' + this.getClassName('liner'), rows, i, len; // Only iterate the ModelList again if there are nodeFormatters for (i = 0, len = columns.length; i < len; ++i) { if (columns[i].nodeFormatter) { formatters.push(i); } } if (data && formatters.length) { rows = tbody.get('childNodes'); data.each(function (record, index) { var formatterData = { data : record.toJSON(), record : record, rowIndex : index }, row = rows.item(index), i, len, col, key, cells, cell, keep; if (row) { cells = row.get('childNodes'); for (i = 0, len = formatters.length; i < len; ++i) { cell = cells.item(formatters[i]); if (cell) { col = formatterData.column = columns[formatters[i]]; key = col.key || col.id; formatterData.value = record.get(key); formatterData.td = cell; formatterData.cell = cell.one(linerQuery) || cell; keep = col.nodeFormatter.call(source,formatterData); if (keep === false) { // Remove from the Node cache to reduce // memory footprint. This also purges events, // which you shouldn't be scoping to a cell // anyway. You've been warned. Incidentally, // you should always return false. Just sayin. cell.destroy(true); } } } } }); } }, /** Binds event subscriptions from the UI and the source (if assigned). @method bindUI @protected @since 3.5.0 **/ bindUI: function () { var handles = this._eventHandles; if (this.source && !handles.columnsChange) { handles.columnsChange = this.source.after('columnsChange', bind('_afterColumnsChange', this)); } if (!handles.dataChange) { handles.dataChange = this.after( ['modelListChange', '*:change', '*:add', '*:remove', '*:reset'], bind('_afterDataChange', this)); } }, /** The base token for classes created with the `getClassName` method. @property _cssPrefix @type {String} @default 'yui3-table' @protected @since 3.5.0 **/ _cssPrefix: ClassNameManager.getClassName('table'), /** Iterates the `modelList` and applies each Model to the `_rowTemplate`, allowing any column `formatter` or `emptyCellValue` to override cell content for the appropriate column. The aggregated HTML string is returned. @method _createDataHTML @param {Object[]} columns The column configurations to customize the generated cell content or class names @return {HTML} The markup for all Models in the `modelList`, each applied to the `_rowTemplate` @protected @since 3.5.0 **/ _createDataHTML: function (columns) { var data = this.get('modelList'), html = ''; if (data) { data.each(function (model, index) { html += this._createRowHTML(model, index); }, this); } return html; }, /** Applies the data of a given Model, modified by any column formatters and supplemented by other template values to the instance's `_rowTemplate` (see `_createRowTemplate`). The generated string is then returned. The data from Model's attributes is fetched by `toJSON` and this data object is appended with other properties to supply values to {placeholders} in the template. For a template generated from a Model with 'foo' and 'bar' attributes, the data object would end up with the following properties before being used to populate the `_rowTemplate`: * `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute. * `foo` - The value to populate the 'foo' column cell content. This value will be the value stored in the Model's `foo` attribute, or the result of the column's `formatter` if assigned. If the value is '', `null`, or `undefined`, and the column's `emptyCellValue` is assigned, that value will be used. * `bar` - Same for the 'bar' column cell content. * `foo-className` - String of CSS classes to apply to the `<td>`. * `bar-className` - Same. * `rowClass` - String of CSS classes to apply to the `<tr>`. This will be the odd/even class per the specified index plus any additional classes assigned by column formatters (via `o.rowClass`). Because this object is available to formatters, any additional properties can be added to fill in custom {placeholders} in the `_rowTemplate`. @method _createRowHTML @param {Model} model The Model instance to apply to the row template @param {Number} index The index the row will be appearing @return {HTML} The markup for the provided Model, less any `nodeFormatter`s @protected @since 3.5.0 **/ _createRowHTML: function (model, index) { var data = model.toJSON(), clientId = model.get('clientId'), values = { rowId : this._getRowId(clientId), clientId: clientId, rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN }, source = this.source || this, columns = this.columns, i, len, col, token, value, formatterData; for (i = 0, len = columns.length; i < len; ++i) { col = columns[i]; value = data[col.key]; token = col._id; values[token + '-className'] = ''; if (col.formatter) { formatterData = { value : value, data : data, column : col, record : model, className: '', rowClass : '', rowIndex : index }; if (typeof col.formatter === 'string') { if (value !== undefined) { // TODO: look for known formatters by string name value = fromTemplate(col.formatter, formatterData); } } else { // Formatters can either return a value value = col.formatter.call(source, formatterData); // or update the value property of the data obj passed if (value === undefined) { value = formatterData.value; } values[token + '-className'] = formatterData.className; values.rowClass += ' ' + formatterData.rowClass; } } if (value === undefined || value === null || value === '') { value = col.emptyCellValue || ''; } values[token] = col.allowHTML ? value : htmlEscape(value); values.rowClass = values.rowClass.replace(/\s+/g, ' '); } return fromTemplate(this._rowTemplate, values); }, /** Creates a custom HTML template string for use in generating the markup for individual table rows with {placeholder}s to capture data from the Models in the `modelList` attribute or from column `formatter`s. Assigns the `_rowTemplate` property. @method _createRowTemplate @param {Object[]} columns Array of column configuration objects @protected @since 3.5.0 **/ _createRowTemplate: function (columns) { var html = '', cellTemplate = this.CELL_TEMPLATE, i, len, col, key, token, headers, tokenValues; for (i = 0, len = columns.length; i < len; ++i) { col = columns[i]; key = col.key; token = col._id; // Only include headers if there are more than one headers = (col._headers || []).length > 1 ? 'headers="' + col._headers.join(' ') + '"' : ''; tokenValues = { content : '{' + token + '}', headers : headers, className: this.getClassName('col', token) + ' ' + (col.className || '') + ' ' + this.getClassName('cell') + ' {' + token + '-className}' }; if (col.nodeFormatter) { // Defer all node decoration to the formatter tokenValues.content = ''; } html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues); } this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, { content: html }); }, /** Destroys the instance. @method destructor @protected @since 3.5.0 **/ destructor: function () { // will unbind the bubble relationship and clear the table if necessary this.set('modelList', null); (new Y.EventHandle(YObject.values(this._eventHandles))).detach(); }, /** Holds the event subscriptions needing to be detached when the instance is `destroy()`ed. @property _eventHandles @type {Object} @default undefined (initially unset) @protected @since 3.5.0 **/ //_eventHandles: null, /** Returns the row ID associated with a Model's clientId. @method _getRowId @param {String} clientId The Model clientId @return {String} @protected **/ _getRowId: function (clientId) { return this._idMap[clientId] || (this._idMap[clientId] = Y.guid()); }, /** Map of Model clientIds to row ids. @property _idMap @type {Object} @protected **/ //_idMap, /** Initializes the instance. Reads the following configuration properties in addition to the instance attributes: * `columns` - (REQUIRED) The initial column information * `cssPrefix` - The base string for classes generated by `getClassName` * `source` - The object to serve as source of truth for column info @method initializer @param {Object} config Configuration data @protected @since 3.5.0 **/ initializer: function (config) { var cssPrefix = config.cssPrefix || (config.source || {}).cssPrefix, modelList = this.get('modelList'); this.source = config.source; this.columns = this._parseColumns(config.columns); this._eventHandles = {}; this._idMap = {}; if (cssPrefix) { this._cssPrefix = cssPrefix; } this.CLASS_ODD = this.getClassName('odd'); this.CLASS_EVEN = this.getClassName('even'); this.after('modelListChange', bind('_afterModelListChange', this)); if (modelList && modelList.addTarget) { modelList.addTarget(this); } }, /** Flattens an array of potentially nested column configurations into a single depth array of data columns. Columns that have children are disregarded in favor of searching their child columns. The resulting array corresponds 1:1 with columns that will contain data in the `<tbody>`. @method _parseColumns @param {Object[]} data Array of unfiltered column configuration objects @param {Object[]} columns Working array of data columns. Used for recursion. @return {Object[]} Only those columns that will be rendered. @protected @since 3.5.0 **/ _parseColumns: function (data, columns) { var col, i, len; columns || (columns = []); if (isArray(data) && data.length) { for (i = 0, len = data.length; i < len; ++i) { col = data[i]; if (typeof col === 'string') { col = { key: col }; } if (col.key || col.formatter || col.nodeFormatter) { col.index = columns.length; columns.push(col); } else if (col.children) { this._parseColumns(col.children, columns); } } } return columns; } /** The HTML template used to create a full row of markup for a single Model in the `modelList` plus any customizations defined in the column configurations. @property _rowTemplate @type {HTML} @default (initially unset) @protected @since 3.5.0 **/ //_rowTemplate: null }, { ATTRS: { modelList: { setter: '_setModelList' } } }); }, '@VERSION@' ,{requires:['datatable-core', 'view', 'classnamemanager']});
bootcdn/cdnjs
ajax/libs/yui/3.5.0pr4/datatable-body/datatable-body.js
JavaScript
mit
32,017
<?php namespace Drupal\Tests\language\Unit\Menu; use Drupal\Tests\Core\Menu\LocalTaskIntegrationTestBase; /** * Tests existence of language local tasks. * * @group language */ class LanguageLocalTasksTest extends LocalTaskIntegrationTestBase { protected function setUp() { $this->directoryList = array( 'language' => 'core/modules/language', ); parent::setUp(); } /** * Tests language admin overview local tasks existence. * * @dataProvider getLanguageAdminOverviewRoutes */ public function testLanguageAdminLocalTasks($route, $expected) { $this->assertLocalTasks($route, $expected); } /** * Provides a list of routes to test. */ public function getLanguageAdminOverviewRoutes() { return array( array('entity.configurable_language.collection', array(array('entity.configurable_language.collection', 'language.negotiation'))), array('language.negotiation', array(array('entity.configurable_language.collection', 'language.negotiation'))), ); } /** * Tests language edit local tasks existence. */ public function testLanguageEditLocalTasks() { $this->assertLocalTasks('entity.configurable_language.edit_form', array( 0 => array('entity.configurable_language.edit_form'), )); } }
windtrader/drupalvm-d8
web/core/modules/language/tests/src/Unit/Menu/LanguageLocalTasksTest.php
PHP
gpl-2.0
1,291
/* * Copyright 2010 Tilera 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 * as published by the Free Software Foundation, version 2. * * 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, GOOD TITLE or * NON INFRINGEMENT. See the GNU General Public License for * more details. */ #include <asm/page.h> #include <asm/cacheflush.h> #include <arch/icache.h> void __flush_icache_range(unsigned long start, unsigned long end) { invalidate_icache((const void *)start, end - start, PAGE_SIZE); }
wkritzinger/asuswrt-merlin
release/src-rt-7.x.main/src/linux/linux-2.6.36/arch/tile/lib/cacheflush.c
C
gpl-2.0
770
/* * originally written by: Kirk Reiser <kirk@braille.uwo.ca> * this version considerably modified by David Borowski, david575@rogers.com * * Copyright (C) 1998-99 Kirk Reiser. * Copyright (C) 2003 David Borowski. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * specificly written as a driver for the speakup screenreview * s not a general device driver. */ #include "speakup.h" #include "spk_priv.h" #include "serialio.h" #include "speakup_dtlk.h" /* local header file for LiteTalk values */ #define DRV_VERSION "2.11" #define PROCSPEECH 0x0d static int synth_probe(struct spk_synth *synth); static struct var_t vars[] = { { CAPS_START, .u.s = {"\x01+35p" } }, { CAPS_STOP, .u.s = {"\x01-35p" } }, { RATE, .u.n = {"\x01%ds", 8, 0, 9, 0, 0, NULL } }, { PITCH, .u.n = {"\x01%dp", 50, 0, 99, 0, 0, NULL } }, { VOL, .u.n = {"\x01%dv", 5, 0, 9, 0, 0, NULL } }, { TONE, .u.n = {"\x01%dx", 1, 0, 2, 0, 0, NULL } }, { PUNCT, .u.n = {"\x01%db", 7, 0, 15, 0, 0, NULL } }, { VOICE, .u.n = {"\x01%do", 0, 0, 7, 0, 0, NULL } }, { FREQUENCY, .u.n = {"\x01%df", 5, 0, 9, 0, 0, NULL } }, { DIRECT, .u.n = {NULL, 0, 0, 1, 0, 0, NULL } }, V_LAST_VAR }; /* * These attributes will appear in /sys/accessibility/speakup/ltlk. */ static struct kobj_attribute caps_start_attribute = __ATTR(caps_start, S_IWUSR|S_IRUGO, spk_var_show, spk_var_store); static struct kobj_attribute caps_stop_attribute = __ATTR(caps_stop, S_IWUSR|S_IRUGO, spk_var_show, spk_var_store); static struct kobj_attribute freq_attribute = __ATTR(freq, S_IWUSR|S_IRUGO, spk_var_show, spk_var_store); static struct kobj_attribute pitch_attribute = __ATTR(pitch, S_IWUSR|S_IRUGO, spk_var_show, spk_var_store); static struct kobj_attribute punct_attribute = __ATTR(punct, S_IWUSR|S_IRUGO, spk_var_show, spk_var_store); static struct kobj_attribute rate_attribute = __ATTR(rate, S_IWUSR|S_IRUGO, spk_var_show, spk_var_store); static struct kobj_attribute tone_attribute = __ATTR(tone, S_IWUSR|S_IRUGO, spk_var_show, spk_var_store); static struct kobj_attribute voice_attribute = __ATTR(voice, S_IWUSR|S_IRUGO, spk_var_show, spk_var_store); static struct kobj_attribute vol_attribute = __ATTR(vol, S_IWUSR|S_IRUGO, spk_var_show, spk_var_store); static struct kobj_attribute delay_time_attribute = __ATTR(delay_time, S_IWUSR|S_IRUGO, spk_var_show, spk_var_store); static struct kobj_attribute direct_attribute = __ATTR(direct, S_IWUSR|S_IRUGO, spk_var_show, spk_var_store); static struct kobj_attribute full_time_attribute = __ATTR(full_time, S_IWUSR|S_IRUGO, spk_var_show, spk_var_store); static struct kobj_attribute jiffy_delta_attribute = __ATTR(jiffy_delta, S_IWUSR|S_IRUGO, spk_var_show, spk_var_store); static struct kobj_attribute trigger_time_attribute = __ATTR(trigger_time, S_IWUSR|S_IRUGO, spk_var_show, spk_var_store); /* * Create a group of attributes so that we can create and destroy them all * at once. */ static struct attribute *synth_attrs[] = { &caps_start_attribute.attr, &caps_stop_attribute.attr, &freq_attribute.attr, &pitch_attribute.attr, &punct_attribute.attr, &rate_attribute.attr, &tone_attribute.attr, &voice_attribute.attr, &vol_attribute.attr, &delay_time_attribute.attr, &direct_attribute.attr, &full_time_attribute.attr, &jiffy_delta_attribute.attr, &trigger_time_attribute.attr, NULL, /* need to NULL terminate the list of attributes */ }; static struct spk_synth synth_ltlk = { .name = "ltlk", .version = DRV_VERSION, .long_name = "LiteTalk", .init = "\01@\x01\x31y\n\0", .procspeech = PROCSPEECH, .clear = SYNTH_CLEAR, .delay = 500, .trigger = 50, .jiffies = 50, .full = 40000, .startup = SYNTH_START, .checkval = SYNTH_CHECK, .vars = vars, .probe = synth_probe, .release = spk_serial_release, .synth_immediate = spk_synth_immediate, .catch_up = spk_do_catch_up, .flush = spk_synth_flush, .is_alive = spk_synth_is_alive_restart, .synth_adjust = NULL, .read_buff_add = NULL, .get_index = spk_serial_in_nowait, .indexing = { .command = "\x01%di", .lowindex = 1, .highindex = 5, .currindex = 1, }, .attributes = { .attrs = synth_attrs, .name = "ltlk", }, }; /* interrogate the LiteTalk and print its settings */ static void synth_interrogate(struct spk_synth *synth) { unsigned char *t, i; unsigned char buf[50], rom_v[20]; spk_synth_immediate(synth, "\x18\x01?"); for (i = 0; i < 50; i++) { buf[i] = spk_serial_in(); if (i > 2 && buf[i] == 0x7f) break; } t = buf+2; for (i = 0; *t != '\r'; t++) { rom_v[i] = *t; if (++i >= 19) break; } rom_v[i] = 0; pr_info("%s: ROM version: %s\n", synth->long_name, rom_v); } static int synth_probe(struct spk_synth *synth) { int failed = 0; failed = spk_serial_synth_probe(synth); if (failed == 0) synth_interrogate(synth); synth->alive = !failed; return failed; } module_param_named(ser, synth_ltlk.ser, int, S_IRUGO); module_param_named(start, synth_ltlk.startup, short, S_IRUGO); MODULE_PARM_DESC(ser, "Set the serial port for the synthesizer (0-based)."); MODULE_PARM_DESC(start, "Start the synthesizer once it is loaded."); static int __init ltlk_init(void) { return synth_add(&synth_ltlk); } static void __exit ltlk_exit(void) { synth_remove(&synth_ltlk); } module_init(ltlk_init); module_exit(ltlk_exit); MODULE_AUTHOR("Kirk Reiser <kirk@braille.uwo.ca>"); MODULE_AUTHOR("David Borowski"); MODULE_DESCRIPTION("Speakup support for DoubleTalk LT/LiteTalk synthesizers"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_VERSION);
mericon/Xp_Kernel_LGH850
virt/drivers/staging/speakup/speakup_ltlk.c
C
gpl-2.0
6,157
<?php /* * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@prestashop.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <contact@prestashop.com> * @copyright 2007-2015 PrestaShop SA * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ /** * @since 1.5.0 * @property SupplyOrder $object */ class AdminSupplyOrdersControllerCore extends AdminController { /** * @var array List of warehouses */ protected $warehouses; public function __construct() { $this->bootstrap = true; $this->context = Context::getContext(); $this->table = 'supply_order'; $this->className = 'SupplyOrder'; $this->identifier = 'id_supply_order'; $this->lang = false; $this->is_template_list = false; $this->multishop_context = Shop::CONTEXT_ALL; $this->addRowAction('updatereceipt'); $this->addRowAction('changestate'); $this->addRowAction('edit'); $this->addRowAction('view'); $this->addRowAction('details'); $this->list_no_link = true; $this->fields_list = array( 'reference' => array( 'title' => $this->l('Reference'), 'havingFilter' => true ), 'supplier' => array( 'title' => $this->l('Supplier'), 'filter_key' => 's!name' ), 'warehouse' => array( 'title' => $this->l('Warehouse'), 'filter_key' => 'w!name' ), 'state' => array( 'title' => $this->l('Status'), 'filter_key' => 'stl!name', 'color' => 'color', ), 'date_add' => array( 'title' => $this->l('Creation'), 'align' => 'left', 'type' => 'date', 'havingFilter' => true, 'filter_key' => 'a!date_add' ), 'date_upd' => array( 'title' => $this->l('Last modification'), 'align' => 'left', 'type' => 'date', 'havingFilter' => true, 'filter_key' => 'a!date_upd' ), 'date_delivery_expected' => array( 'title' => $this->l('Delivery (expected)'), 'align' => 'left', 'type' => 'date', 'havingFilter' => true, 'filter_key' => 'a!date_delivery_expected' ), 'id_export' => array( 'title' => $this->l('Export'), 'callback' => 'printExportIcons', 'orderby' => false, 'search' => false ), ); // gets the list of warehouses available $this->warehouses = Warehouse::getWarehouses(true); // gets the final list of warehouses array_unshift($this->warehouses, array('id_warehouse' => -1, 'name' => $this->l('All Warehouses'))); parent::__construct(); } /** * AdminController::init() override * @see AdminController::init() */ public function init() { if (Tools::isSubmit('submitFilterorders')) { $this->list_id = 'orders'; } elseif (Tools::isSubmit('submitFiltertemplates')) { $this->list_id = 'templates'; } parent::init(); if (Tools::isSubmit('addsupply_order') || Tools::isSubmit('submitAddsupply_order') || (Tools::isSubmit('updatesupply_order') && Tools::isSubmit('id_supply_order'))) { // override table, lang, className and identifier for the current controller $this->table = 'supply_order'; $this->className = 'SupplyOrder'; $this->identifier = 'id_supply_order'; $this->lang = false; $this->action = 'new'; $this->display = 'add'; if (Tools::isSubmit('updatesupply_order')) { if ($this->tabAccess['edit'] === '1') { $this->display = 'edit'; } else { $this->errors[] = Tools::displayError('You do not have permission to edit this.'); } } } if (Tools::isSubmit('update_receipt') && Tools::isSubmit('id_supply_order')) { // change the display type in order to add specific actions to $this->display = 'update_receipt'; // display correct toolBar $this->initToolbar(); } } public function initPageHeaderToolbar() { if ($this->display == 'details') { $this->page_header_toolbar_btn['back'] = array( 'href' => Context::getContext()->link->getAdminLink('AdminSupplyOrders'), 'desc' => $this->l('Back to list', null, null, false), 'icon' => 'process-icon-back' ); } elseif (empty($this->display)) { $this->page_header_toolbar_btn['new_supply_order'] = array( 'href' => self::$currentIndex.'&addsupply_order&token='.$this->token, 'desc' => $this->l('Add new supply order', null, null, false), 'icon' => 'process-icon-new' ); $this->page_header_toolbar_btn['new_supply_order_template'] = array( 'href' => self::$currentIndex.'&addsupply_order&mod=template&token='.$this->token, 'desc' => $this->l('Add new supply order template', null, null, false), 'icon' => 'process-icon-new' ); } parent::initPageHeaderToolbar(); } /** * AdminController::renderForm() override * @see AdminController::renderForm() */ public function renderForm() { if (Tools::isSubmit('addsupply_order') || Tools::isSubmit('updatesupply_order') || Tools::isSubmit('submitAddsupply_order') || Tools::isSubmit('submitUpdatesupply_order')) { if (Tools::isSubmit('addsupply_order') || Tools::isSubmit('submitAddsupply_order')) { $this->toolbar_title = $this->l('Stock: Create a new supply order'); } $update = false; if (Tools::isSubmit('updatesupply_order') || Tools::isSubmit('submitUpdatesupply_order')) { $this->toolbar_title = $this->l('Stock: Manage supply orders'); $update = true; } if (Tools::isSubmit('mod') && Tools::getValue('mod') === 'template' || $this->object->is_template) { $this->toolbar_title .= ' ('.$this->l('template').')'; } $this->addJqueryUI('ui.datepicker'); //get warehouses list $warehouses = Warehouse::getWarehouses(true); // displays warning if there are no warehouses if (!$warehouses) { $this->displayWarning($this->l('You must have at least one warehouse. See Stock/Warehouses')); } //get currencies list $currencies = Currency::getCurrencies(false, true, true); //get suppliers list $suppliers = array_unique(Supplier::getSuppliers(), SORT_REGULAR); //get languages list $languages = Language::getLanguages(true); $this->fields_form = array( 'legend' => array( 'title' => $this->l('Order information'), 'icon' => 'icon-pencil' ), 'input' => array( array( 'type' => 'text', 'label' => $this->l('Reference'), 'name' => 'reference', 'required' => true, 'hint' => $this->l('The reference number for your order.'), ), array( 'type' => 'select', 'label' => $this->l('Supplier'), 'name' => 'id_supplier', 'required' => true, 'options' => array( 'query' => $suppliers, 'id' => 'id_supplier', 'name' => 'name' ), 'hint' => array( $this->l('Select the supplier you\'ll be purchasing from.'), $this->l('Warning: All products already added to the order will be removed.') ) ), array( 'type' => 'select', 'label' => $this->l('Warehouse'), 'name' => 'id_warehouse', 'required' => true, 'options' => array( 'query' => $warehouses, 'id' => 'id_warehouse', 'name' => 'name' ), 'hint' => $this->l('Which warehouse will the order be sent to?'), ), array( 'type' => 'select', 'label' => $this->l('Currency'), 'name' => 'id_currency', 'required' => true, 'options' => array( 'query' => $currencies, 'id' => 'id_currency', 'name' => 'name' ), 'hint' => array( $this->l('The currency of the order.'), $this->l('Warning: All products already added to the order will be removed.') ) ), array( 'type' => 'select', 'label' => $this->l('Order Language'), 'name' => 'id_lang', 'required' => true, 'options' => array( 'query' => $languages, 'id' => 'id_lang', 'name' => 'name' ), 'hint' => $this->l('The language of the order.') ), array( 'type' => 'text', 'label' => $this->l('Global discount percentage'), 'name' => 'discount_rate', 'required' => false, 'hint' => $this->l('This is the global discount percentage for the order.'), ), array( 'type' => 'text', 'label' => $this->l('Automatically load products'), 'name' => 'load_products', 'required' => false, 'hint' => array( $this->l('This will reset the order.'), $this->l('If a value specified, each of your current product (from the selected supplier and warehouse) with a quantity lower than or equal to this value will be loaded. This means that PrestaShop will pre-fill this order with the products that are low on quantity.'), ), ), ), 'submit' => (!$update ? array('title' => $this->l('Save order')) : array()), 'buttons' => (!$update ? array( 'save-and-stay' => array( 'title' => $this->l('Save order and stay'), 'name' => 'submitAddsupply_orderAndStay', 'type' => 'submit', 'class' => 'btn btn-default pull-right', 'icon' => 'process-icon-save' ) ) : array()) ); if (Tools::isSubmit('mod') && Tools::getValue('mod') === 'template' || $this->object->is_template) { $this->fields_form['input'][] = array( 'type' => 'hidden', 'name' => 'is_template' ); $this->fields_form['input'][] = array( 'type' => 'hidden', 'name' => 'date_delivery_expected', ); } else { $this->fields_form['input'][] = array( 'type' => 'date', 'label' => $this->l('Expected delivery date'), 'name' => 'date_delivery_expected', 'required' => true, 'desc' => $this->l('The expected delivery date for this order is...'), ); } //specific discount display if (isset($this->object->discount_rate)) { $this->object->discount_rate = Tools::ps_round($this->object->discount_rate, 4); } //specific date display if (isset($this->object->date_delivery_expected)) { $date = explode(' ', $this->object->date_delivery_expected); if ($date) { $this->object->date_delivery_expected = $date[0]; } } $this->displayInformation( $this->l('If you wish to order products, they have to be available for the specified supplier/warehouse.') .' '. $this->l('See Catalog/Products/[Your Product]/Suppliers & Warehouses.') .'<br />'. $this->l('Changing the currency or the supplier will reset the order.') .'<br />' .'<br />'. $this->l('Please note that you can only order from one supplier at a time.') ); return parent::renderForm(); } } /** * AdminController::getList() override * @see AdminController::getList() * * @param int $id_lang * @param string|null $order_by * @param string|null $order_way * @param int $start * @param int|null $limit * @param int|bool $id_lang_shop * * @throws PrestaShopException */ public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false) { if (Tools::isSubmit('csv_orders') || Tools::isSubmit('csv_orders_details') || Tools::isSubmit('csv_order_details')) { $limit = false; } // defines button specific for non-template supply orders if (!$this->is_template_list && $this->display != 'details') { // adds export csv buttons $this->toolbar_btn['export-csv-orders'] = array( 'short' => 'Export Orders', 'href' => $this->context->link->getAdminLink('AdminSupplyOrders').'&csv_orders&id_warehouse='.$this->getCurrentWarehouse(), 'desc' => $this->l('Export Orders (CSV)'), 'class' => 'process-icon-export' ); $this->toolbar_btn['export-csv-details'] = array( 'short' => 'Export Orders Details', 'href' => $this->context->link->getAdminLink('AdminSupplyOrders').'&csv_orders_details&id_warehouse='.$this->getCurrentWarehouse(), 'desc' => $this->l('Export Orders Details (CSV)'), 'class' => 'process-icon-export' ); unset($this->toolbar_btn['new']); if ($this->tabAccess['add'] === '1') { $this->toolbar_btn['new'] = array( 'href' => self::$currentIndex.'&add'.$this->table.'&token='.$this->token, 'desc' => $this->l('Add New') ); } } parent::getList($id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop); // adds colors depending on the receipt state if ($order_by == 'quantity_expected') { $nb_items = count($this->_list); for ($i = 0; $i < $nb_items; ++$i) { $item = &$this->_list[$i]; if ($item['quantity_received'] == $item['quantity_expected']) { $item['color'] = '#00bb35'; } elseif ($item['quantity_received'] > $item['quantity_expected']) { $item['color'] = '#fb0008'; } } } // actions filters on supply orders list if ($this->table == 'supply_order') { $nb_items = count($this->_list); for ($i = 0; $i < $nb_items; $i++) { // if the current state doesn't allow order edit, skip the edit action if ($this->_list[$i]['editable'] == 0) { $this->addRowActionSkipList('edit', $this->_list[$i]['id_supply_order']); } if ($this->_list[$i]['enclosed'] == 1 && $this->_list[$i]['receipt_state'] == 0) { $this->addRowActionSkipList('changestate', $this->_list[$i]['id_supply_order']); } if (1 != $this->_list[$i]['pending_receipt']) { $this->addRowActionSkipList('updatereceipt', $this->_list[$i]['id_supply_order']); } } } } /** * AdminController::renderList() override * @see AdminController::renderList() */ public function renderList() { $this->displayInformation($this->l('This interface allows you to manage supply orders.').'<br />'); $this->displayInformation($this->l('You can create pre-filled order templates, from which you can build actual orders much quicker.').'<br />'); if (count($this->warehouses) <= 1) { $this->displayWarning($this->l('You must choose at least one warehouse before creating supply orders. For more information, see Stock/Warehouses.')); } // assigns warehouses $this->tpl_list_vars['warehouses'] = $this->warehouses; $this->tpl_list_vars['current_warehouse'] = $this->getCurrentWarehouse(); $this->tpl_list_vars['filter_status'] = $this->getFilterStatus(); // overrides query $this->_select = ' s.name AS supplier, w.name AS warehouse, stl.name AS state, st.delivery_note, st.editable, st.enclosed, st.receipt_state, st.pending_receipt, st.color AS color, a.id_supply_order as id_export'; $this->_join = ' LEFT JOIN `'._DB_PREFIX_.'supply_order_state_lang` stl ON ( a.id_supply_order_state = stl.id_supply_order_state AND stl.id_lang = '.(int)$this->context->language->id.' ) LEFT JOIN `'._DB_PREFIX_.'supply_order_state` st ON a.id_supply_order_state = st.id_supply_order_state LEFT JOIN `'._DB_PREFIX_.'supplier` s ON a.id_supplier = s.id_supplier LEFT JOIN `'._DB_PREFIX_.'warehouse` w ON (w.id_warehouse = a.id_warehouse)'; $this->_where = ' AND a.is_template = 0'; if ($this->getCurrentWarehouse() != -1) { $this->_where .= ' AND a.id_warehouse = '.$this->getCurrentWarehouse(); self::$currentIndex .= '&id_warehouse='.(int)$this->getCurrentWarehouse(); } if ($this->getFilterStatus() != 0) { $this->_where .= ' AND st.enclosed != 1'; self::$currentIndex .= '&filter_status=on'; } $this->list_id = 'orders'; $this->_filterHaving = null; if (Tools::isSubmit('submitFilter'.$this->list_id) || $this->context->cookie->{'submitFilter'.$this->list_id} !== false || Tools::getValue($this->list_id.'Orderby') || Tools::getValue($this->list_id.'Orderway')) { $this->filter = true; parent::processFilter(); } $first_list = parent::renderList(); if (Tools::isSubmit('csv_orders') || Tools::isSubmit('csv_orders_details') || Tools::isSubmit('csv_order_details')) { if (count($this->_list) > 0) { $this->renderCSV(); die; } else { $this->displayWarning($this->l('There is nothing to export as a CSV file.')); } } // second list : templates $second_list = null; $this->is_template_list = true; unset($this->tpl_list_vars['warehouses']); unset($this->tpl_list_vars['current_warehouse']); unset($this->tpl_list_vars['filter_status']); // unsets actions $this->actions = array(); unset($this->toolbar_btn['export-csv-orders']); unset($this->toolbar_btn['export-csv-details']); // adds actions $this->addRowAction('view'); $this->addRowAction('edit'); $this->addRowAction('createsupplyorder'); $this->addRowAction('delete'); // unsets some fields unset($this->fields_list['state'], $this->fields_list['date_upd'], $this->fields_list['id_pdf'], $this->fields_list['date_delivery_expected'], $this->fields_list['id_export']); // $this->fields_list['date_add']['align'] = 'left'; // adds filter, to gets only templates unset($this->_where); $this->_where = ' AND a.is_template = 1'; if ($this->getCurrentWarehouse() != -1) { $this->_where .= ' AND a.id_warehouse = '.$this->getCurrentWarehouse(); } // re-defines toolbar & buttons $this->toolbar_title = $this->l('Stock: Supply order templates'); $this->initToolbar(); unset($this->toolbar_btn['new']); $this->toolbar_btn['new'] = array( 'href' => self::$currentIndex.'&add'.$this->table.'&mod=template&token='.$this->token, 'desc' => $this->l('Add new template'), 'imgclass' => 'new_1', 'class' => 'process-icon-new' ); $this->list_id = 'templates'; $this->_filterHaving = null; if (Tools::isSubmit('submitFilter'.$this->list_id) || $this->context->cookie->{'submitFilter'.$this->list_id} !== false || Tools::getValue($this->list_id.'Orderby') || Tools::getValue($this->list_id.'Orderway')) { $this->filter = true; parent::processFilter(); } // inits list $second_list = parent::renderList(); return $first_list.$second_list; } /** * Init the content of change state action */ public function initChangeStateContent() { $id_supply_order = (int)Tools::getValue('id_supply_order', 0); if ($id_supply_order <= 0) { $this->errors[] = Tools::displayError('The specified supply order is not valid'); return parent::initContent(); } $supply_order = new SupplyOrder($id_supply_order); $supply_order_state = new SupplyOrderState($supply_order->id_supply_order_state); if (!Validate::isLoadedObject($supply_order) || !Validate::isLoadedObject($supply_order_state)) { $this->errors[] = Tools::displayError('The specified supply order is not valid'); return parent::initContent(); } // change the display type in order to add specific actions to $this->display = 'update_order_state'; // overrides parent::initContent(); $this->initToolbar(); $this->initPageHeaderToolbar(); // given the current state, loads available states $states = SupplyOrderState::getSupplyOrderStates($supply_order->id_supply_order_state); // gets the state that are not allowed $allowed_states = array(); foreach ($states as &$state) { $allowed_states[] = $state['id_supply_order_state']; $state['allowed'] = 1; } $not_allowed_states = SupplyOrderState::getStates($allowed_states); // generates the final list of states $index = count($allowed_states); foreach ($not_allowed_states as &$not_allowed_state) { $not_allowed_state['allowed'] = 0; $states[$index] = $not_allowed_state; ++$index; } // loads languages $this->getlanguages(); // defines the fields of the form to display $this->fields_form[0]['form'] = array( 'legend' => array( 'title' => $this->l('Supply order status'), 'icon' => 'icon-pencil' ), 'input' => array(), 'submit' => array( 'title' => $this->l('Save') ) ); $this->displayInformation($this->l('Be careful when changing status. Some of those changes cannot be canceled. ')); // sets up the helper $helper = new HelperForm(); $helper->submit_action = 'submitChangestate'; $helper->currentIndex = self::$currentIndex; $helper->toolbar_btn = $this->toolbar_btn; $helper->toolbar_scroll = false; $helper->token = $this->token; $helper->id = null; // no display standard hidden field in the form $helper->languages = $this->_languages; $helper->default_form_language = $this->default_form_language; $helper->allow_employee_form_lang = $this->allow_employee_form_lang; $helper->title = sprintf($this->l('Stock: Change supply order status #%s'), $supply_order->reference); $helper->show_cancel_button = true; $helper->override_folder = 'supply_orders_change_state/'; // assigns our content $helper->tpl_vars['show_change_state_form'] = true; $helper->tpl_vars['supply_order_state'] = $supply_order_state; $helper->tpl_vars['supply_order'] = $supply_order; $helper->tpl_vars['supply_order_states'] = $states; // generates the form to display $content = $helper->generateForm($this->fields_form); $this->context->smarty->assign(array( 'content' => $content, 'url_post' => self::$currentIndex.'&token='.$this->token, 'show_page_header_toolbar' => $this->show_page_header_toolbar, 'page_header_toolbar_title' => $this->page_header_toolbar_title, 'page_header_toolbar_btn' => $this->page_header_toolbar_btn )); } /** * Init the content of change state action */ public function initUpdateSupplyOrderContent() { $this->addJqueryPlugin('autocomplete'); // load supply order $id_supply_order = (int)Tools::getValue('id_supply_order', null); if ($id_supply_order != null) { $supply_order = new SupplyOrder($id_supply_order); $currency = new Currency($supply_order->id_currency); if (Validate::isLoadedObject($supply_order)) { // load products of this order $products = $supply_order->getEntries(); $product_ids = array(); if (isset($this->order_products_errors) && is_array($this->order_products_errors)) { //for each product in error array, check if it is in products array, and remove it to conserve last user values foreach ($this->order_products_errors as $pe) { foreach ($products as $index_p => $p) { if (($p['id_product'] == $pe['id_product']) && ($p['id_product_attribute'] == $pe['id_product_attribute'])) { unset($products[$index_p]); } } } // then merge arrays $products = array_merge($this->order_products_errors, $products); } foreach ($products as &$item) { // calculate md5 checksum on each product for use in tpl $item['checksum'] = md5(_COOKIE_KEY_.$item['id_product'].'_'.$item['id_product_attribute']); $item['unit_price_te'] = Tools::ps_round($item['unit_price_te'], 2); // add id to ids list $product_ids[] = $item['id_product'].'_'.$item['id_product_attribute']; } $this->tpl_form_vars['products_list'] = $products; $this->tpl_form_vars['product_ids'] = implode($product_ids, '|'); $this->tpl_form_vars['product_ids_to_delete'] = ''; $this->tpl_form_vars['supplier_id'] = $supply_order->id_supplier; $this->tpl_form_vars['currency'] = $currency; } } $this->tpl_form_vars['content'] = $this->content; $this->tpl_form_vars['token'] = $this->token; $this->tpl_form_vars['show_product_management_form'] = true; // call parent initcontent to render standard form content parent::initContent(); } /** * Inits the content of 'update_receipt' action * Called in initContent() * @see AdminSuppliersOrders::initContent() */ public function initUpdateReceiptContent() { $id_supply_order = (int)Tools::getValue('id_supply_order', null); // if there is no order to fetch if (null == $id_supply_order) { return parent::initContent(); } $supply_order = new SupplyOrder($id_supply_order); // if it's not a valid order if (!Validate::isLoadedObject($supply_order)) { return parent::initContent(); } $this->initPageHeaderToolbar(); // re-defines fields_list $this->fields_list = array( 'supplier_reference' => array( 'title' => $this->l('Supplier reference'), 'orderby' => false, 'filter' => false, 'search' => false, ), 'reference' => array( 'title' => $this->l('Reference'), 'orderby' => false, 'filter' => false, 'search' => false, ), 'ean13' => array( 'title' => $this->l('EAN-13 or JAN barcode'), 'orderby' => false, 'filter' => false, 'search' => false, ), 'upc' => array( 'title' => $this->l('UPC barcode'), 'orderby' => false, 'filter' => false, 'search' => false, ), 'name' => array( 'title' => $this->l('Name'), 'orderby' => false, 'filter' => false, 'search' => false, ), 'quantity_received_today' => array( 'title' => $this->l('Quantity received today?'), 'type' => 'editable', 'orderby' => false, 'filter' => false, 'search' => false, 'hint' => $this->l('The quantity of supplies that you received today.'), ), 'quantity_received' => array( 'title' => $this->l('Quantity received'), 'orderby' => false, 'filter' => false, 'search' => false, 'badge_danger' => true, 'badge_success' => true, 'hint' => $this->l('The quantity of supplies that you received so far (today and the days before, if it applies).'), ), 'quantity_expected' => array( 'title' => $this->l('Quantity expected'), 'orderby' => false, 'filter' => false, 'search' => false, ), 'quantity_left' => array( 'title' => $this->l('Quantity left'), 'orderby' => false, 'filter' => false, 'search' => false, 'hint' => $this->l('The quantity of supplies left to receive for this order.'), ) ); // attributes override unset($this->_select, $this->_join, $this->_where, $this->_orderBy, $this->_orderWay, $this->_group, $this->_filterHaving, $this->_filter); $this->table = 'supply_order_detail'; $this->identifier = 'id_supply_order_detail'; $this->className = 'SupplyOrderDetail'; $this->list_simple_header = false; $this->list_no_link = true; $this->colorOnBackground = true; $this->row_hover = false; $this->bulk_actions = array('Update' => array('text' => $this->l('Update selected'), 'confirm' => $this->l('Update selected items?'))); $this->addRowAction('details'); // sets toolbar title with order reference $this->toolbar_title = sprintf($this->l('Receipt of products for supply order #%s'), $supply_order->reference); $this->lang = false; $lang_id = (int)$this->context->language->id; //employee lang // gets values corresponding to fields_list $this->_select = ' a.id_supply_order_detail as id, a.quantity_received as quantity_received, a.quantity_expected as quantity_expected, IF (a.quantity_expected < a.quantity_received, 0, a.quantity_expected - a.quantity_received) as quantity_left, IF (a.quantity_expected < a.quantity_received, 0, a.quantity_expected - a.quantity_received) as quantity_received_today, IF (a.quantity_expected = a.quantity_received, 1, 0) badge_success, IF (a.quantity_expected > a.quantity_received, 1, 0) badge_danger'; $this->_where = 'AND a.`id_supply_order` = '.(int)$id_supply_order; $this->_group = 'GROUP BY a.id_supply_order_detail'; // gets the list ordered by price desc, without limit $this->getList($lang_id, 'quantity_expected', 'DESC', 0, Tools::getValue('supply_order_pagination'), false); // defines action for POST $action = '&id_supply_order='.$id_supply_order.'&update_receipt=1'; // unsets some buttons unset($this->toolbar_btn['export-csv-orders']); unset($this->toolbar_btn['export-csv-details']); unset($this->toolbar_btn['new']); $this->toolbar_btn['back'] = array( 'desc' => $this->l('Back'), 'href' => $this->context->link->getAdminLink('AdminSupplyOrders') ); // renders list $helper = new HelperList(); $this->setHelperDisplay($helper); $helper->actions = array('details'); $helper->force_show_bulk_actions = true; $helper->override_folder = 'supply_orders_receipt_history/'; $helper->toolbar_btn = $this->toolbar_btn; $helper->list_id = 'supply_order_detail'; $helper->ajax_params = array( 'display_product_history' => 1, ); $helper->currentIndex = self::$currentIndex.$action; // display these global order informations $this->displayInformation($this->l('This interface allows you to update the quantities of this ongoing order.').'<br />'); $this->displayInformation($this->l('Be careful! Once you update, you cannot go back unless you add new negative stock movements.').'<br />'); $this->displayInformation($this->l('A green line means that you\'ve received exactly the quantity you expected. A red line means that you\'ve received more than expected.').'<br />'); // generates content $content = $helper->generateList($this->_list, $this->fields_list); // assigns var $this->context->smarty->assign(array( 'content' => $content, 'show_page_header_toolbar' => $this->show_page_header_toolbar, 'page_header_toolbar_title' => $this->page_header_toolbar_title, 'page_header_toolbar_btn' => $this->page_header_toolbar_btn )); } /** * AdminController::initContent() override * @see AdminController::initContent() */ public function initContent() { if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $this->warnings[md5('PS_ADVANCED_STOCK_MANAGEMENT')] = $this->l('You need to activate the Advanced Stock Management feature prior to using this feature.'); return false; } // Manage the add stock form if (Tools::isSubmit('changestate')) { $this->initChangeStateContent(); } elseif (Tools::isSubmit('update_receipt') && Tools::isSubmit('id_supply_order') && !Tools::isSubmit('detailssupply_order_detail')) { $this->initUpdateReceiptContent(); } elseif (Tools::isSubmit('viewsupply_order') && Tools::isSubmit('id_supply_order')) { $this->action = 'view'; $this->display = 'view'; parent::initContent(); } elseif (Tools::isSubmit('updatesupply_order')) { $this->initUpdateSupplyOrderContent(); } else { if (Tools::isSubmit('detailssupply_order_detail')) { $this->action = 'details'; $this->display = 'details'; } parent::initContent(); } } /** * Ths method manage associated products to the order when updating it */ public function manageOrderProducts() { // load supply order $id_supply_order = (int)Tools::getValue('id_supply_order', null); $products_already_in_order = array(); if ($id_supply_order != null) { $supply_order = new SupplyOrder($id_supply_order); if (Validate::isLoadedObject($supply_order)) { // tests if the supplier or currency have changed in the supply order $new_supplier_id = (int)Tools::getValue('id_supplier'); $new_currency_id = (int)Tools::getValue('id_currency'); if (($new_supplier_id != $supply_order->id_supplier) || ($new_currency_id != $supply_order->id_currency)) { // resets all products in this order $supply_order->resetProducts(); } else { $products_already_in_order = $supply_order->getEntries(); $currency = new Currency($supply_order->id_ref_currency); // gets all product ids to manage $product_ids_str = Tools::getValue('product_ids', null); $product_ids = explode('|', $product_ids_str); $product_ids_to_delete_str = Tools::getValue('product_ids_to_delete', null); $product_ids_to_delete = array_unique(explode('|', $product_ids_to_delete_str)); //delete products that are not managed anymore foreach ($products_already_in_order as $paio) { $product_ok = false; foreach ($product_ids_to_delete as $id) { $id_check = $paio['id_product'].'_'.$paio['id_product_attribute']; if ($id_check == $id) { $product_ok = true; } } if ($product_ok === true) { $entry = new SupplyOrderDetail($paio['id_supply_order_detail']); $entry->delete(); } } // manage each product foreach ($product_ids as $id) { $errors = array(); // check if a checksum is available for this product and test it $check = Tools::getValue('input_check_'.$id, ''); $check_valid = md5(_COOKIE_KEY_.$id); if ($check_valid != $check) { continue; } $pos = strpos($id, '_'); if ($pos === false) { continue; } // Load / Create supply order detail $entry = new SupplyOrderDetail(); $id_supply_order_detail = (int)Tools::getValue('input_id_'.$id, 0); if ($id_supply_order_detail > 0) { $existing_entry = new SupplyOrderDetail($id_supply_order_detail); if (Validate::isLoadedObject($supply_order)) { $entry = &$existing_entry; } } // get product informations $entry->id_product = substr($id, 0, $pos); $entry->id_product_attribute = substr($id, $pos + 1); $entry->unit_price_te = (float)str_replace(array(' ', ','), array('', '.'), Tools::getValue('input_unit_price_te_'.$id, 0)); $entry->quantity_expected = (int)str_replace(array(' ', ','), array('', '.'), Tools::getValue('input_quantity_expected_'.$id, 0)); $entry->discount_rate = (float)str_replace(array(' ', ','), array('', '.'), Tools::getValue('input_discount_rate_'.$id, 0)); $entry->tax_rate = (float)str_replace(array(' ', ','), array('', '.'), Tools::getValue('input_tax_rate_'.$id, 0)); $entry->reference = Tools::getValue('input_reference_'.$id, ''); $entry->supplier_reference = Tools::getValue('input_supplier_reference_'.$id, ''); $entry->ean13 = Tools::getValue('input_ean13_'.$id, ''); $entry->upc = Tools::getValue('input_upc_'.$id, ''); //get the product name in the order language $entry->name = Product::getProductName($entry->id_product, $entry->id_product_attribute, $supply_order->id_lang); if (empty($entry->name)) { $entry->name = ''; } if ($entry->supplier_reference == null) { $entry->supplier_reference = ''; } $entry->exchange_rate = $currency->conversion_rate; $entry->id_currency = $currency->id; $entry->id_supply_order = $supply_order->id; $errors = $entry->validateController(); //get the product name displayed in the backoffice according to the employee language $entry->name_displayed = Tools::getValue('input_name_displayed_'.$id, ''); // if there is a problem, handle error for the current product if (count($errors) > 0) { // add the product to error array => display again product line $this->order_products_errors[] = array( 'id_product' => $entry->id_product, 'id_product_attribute' => $entry->id_product_attribute, 'unit_price_te' => $entry->unit_price_te, 'quantity_expected' => $entry->quantity_expected, 'discount_rate' => $entry->discount_rate, 'tax_rate' => $entry->tax_rate, 'name' => $entry->name, 'name_displayed' => $entry->name_displayed, 'reference' => $entry->reference, 'supplier_reference' => $entry->supplier_reference, 'ean13' => $entry->ean13, 'upc' => $entry->upc, ); $error_str = '<ul>'; foreach ($errors as $e) { $error_str .= '<li>'.sprintf($this->l('Field: %s'), $e).'</li>'; } $error_str .= '</ul>'; $this->errors[] = sprintf(Tools::displayError('Please verify the product information for "%s":'), $entry->name).' ' .$error_str; } else { $entry->save(); } } } } } } /** * AdminController::postProcess() override * @see AdminController::postProcess() */ public function postProcess() { $this->is_editing_order = false; // Checks access if (Tools::isSubmit('submitAddsupply_order') && !($this->tabAccess['add'] === '1')) { $this->errors[] = Tools::displayError('You do not have permission to add a supply order.'); } if (Tools::isSubmit('submitBulkUpdatesupply_order_detail') && !($this->tabAccess['edit'] === '1')) { $this->errors[] = Tools::displayError('You do not have permission to edit an order.'); } // Trick to use both Supply Order as template and actual orders if (Tools::isSubmit('is_template')) { $_GET['mod'] = 'template'; } // checks if supply order reference is unique if (Tools::isSubmit('reference')) { // gets the reference $ref = pSQL(Tools::getValue('reference')); if (Tools::getValue('id_supply_order') != 0 && SupplyOrder::getReferenceById((int)Tools::getValue('id_supply_order')) != $ref) { if ((int)SupplyOrder::exists($ref) != 0) { $this->errors[] = Tools::displayError('The reference has to be unique.'); } } elseif (Tools::getValue('id_supply_order') == 0 && (int)SupplyOrder::exists($ref) != 0) { $this->errors[] = Tools::displayError('The reference has to be unique.'); } } if ($this->errors) { return; } // Global checks when add / update a supply order if (Tools::isSubmit('submitAddsupply_order') || Tools::isSubmit('submitAddsupply_orderAndStay')) { $this->action = 'save'; $this->is_editing_order = true; // get supplier ID $id_supplier = (int)Tools::getValue('id_supplier', 0); if ($id_supplier <= 0 || !Supplier::supplierExists($id_supplier)) { $this->errors[] = Tools::displayError('The selected supplier is not valid.'); } // get warehouse id $id_warehouse = (int)Tools::getValue('id_warehouse', 0); if ($id_warehouse <= 0 || !Warehouse::exists($id_warehouse)) { $this->errors[] = Tools::displayError('The selected warehouse is not valid.'); } // get currency id $id_currency = (int)Tools::getValue('id_currency', 0); if ($id_currency <= 0 || (!($result = Currency::getCurrency($id_currency)) || empty($result))) { $this->errors[] = Tools::displayError('The selected currency is not valid.'); } // get delivery date if (Tools::getValue('mod') != 'template' && strtotime(Tools::getValue('date_delivery_expected')) <= strtotime('-1 day')) { $this->errors[] = Tools::displayError('The specified date cannot be in the past.'); } // gets threshold $quantity_threshold = Tools::getValue('load_products'); if (is_numeric($quantity_threshold)) { $quantity_threshold = (int)$quantity_threshold; } else { $quantity_threshold = null; } if (!count($this->errors)) { // forces date for templates if (Tools::isSubmit('is_template') && !Tools::getValue('date_delivery_expected')) { $_POST['date_delivery_expected'] = date('Y-m-d h:i:s'); } // specify initial state $_POST['id_supply_order_state'] = 1; //defaut creation state // specify global reference currency $_POST['id_ref_currency'] = Currency::getDefaultCurrency()->id; // specify supplier name $_POST['supplier_name'] = Supplier::getNameById($id_supplier); //specific discount check $_POST['discount_rate'] = (float)str_replace(array(' ', ','), array('', '.'), Tools::getValue('discount_rate', 0)); } // manage each associated product $this->manageOrderProducts(); // if the threshold is defined and we are saving the order if (Tools::isSubmit('submitAddsupply_order') && Validate::isInt($quantity_threshold)) { $this->loadProducts((int)$quantity_threshold); } } // Manage state change if (Tools::isSubmit('submitChangestate') && Tools::isSubmit('id_supply_order') && Tools::isSubmit('id_supply_order_state')) { if ($this->tabAccess['edit'] != '1') { $this->errors[] = Tools::displayError('You do not have permission to change the order status.'); } // get state ID $id_state = (int)Tools::getValue('id_supply_order_state', 0); if ($id_state <= 0) { $this->errors[] = Tools::displayError('The selected supply order status is not valid.'); } // get supply order ID $id_supply_order = (int)Tools::getValue('id_supply_order', 0); if ($id_supply_order <= 0) { $this->errors[] = Tools::displayError('The supply order ID is not valid.'); } if (!count($this->errors)) { // try to load supply order $supply_order = new SupplyOrder($id_supply_order); if (Validate::isLoadedObject($supply_order)) { // get valid available possible states for this order $states = SupplyOrderState::getSupplyOrderStates($supply_order->id_supply_order_state); foreach ($states as $state) { // if state is valid, change it in the order if ($id_state == $state['id_supply_order_state']) { $new_state = new SupplyOrderState($id_state); $old_state = new SupplyOrderState($supply_order->id_supply_order_state); // special case of validate state - check if there are products in the order and the required state is not an enclosed state if ($supply_order->isEditable() && !$supply_order->hasEntries() && !$new_state->enclosed) { $this->errors[] = Tools::displayError('It is not possible to change the status of this order because you did not order any products.'); } if (!count($this->errors)) { $supply_order->id_supply_order_state = $state['id_supply_order_state']; if ($supply_order->save()) { if ($new_state->pending_receipt) { $supply_order_details = $supply_order->getEntries(); foreach ($supply_order_details as $supply_order_detail) { $is_present = Stock::productIsPresentInStock($supply_order_detail['id_product'], $supply_order_detail['id_product_attribute'], $supply_order->id_warehouse); if (!$is_present) { $stock = new Stock(); $stock_params = array( 'id_product_attribute' => $supply_order_detail['id_product_attribute'], 'id_product' => $supply_order_detail['id_product'], 'physical_quantity' => 0, 'price_te' => $supply_order_detail['price_te'], 'usable_quantity' => 0, 'id_warehouse' => $supply_order->id_warehouse ); // saves stock in warehouse $stock->hydrate($stock_params); $stock->add(); } } } // if pending_receipt, // or if the order is being canceled, // or if the order is received completely // synchronizes StockAvailable if (($new_state->pending_receipt && !$new_state->receipt_state) || (($old_state->receipt_state || $old_state->pending_receipt) && $new_state->enclosed && !$new_state->receipt_state) || ($new_state->receipt_state && $new_state->enclosed)) { $supply_order_details = $supply_order->getEntries(); $products_done = array(); foreach ($supply_order_details as $supply_order_detail) { if (!in_array($supply_order_detail['id_product'], $products_done)) { StockAvailable::synchronize($supply_order_detail['id_product']); $products_done[] = $supply_order_detail['id_product']; } } } $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token; $redirect = self::$currentIndex.'&token='.$token; $this->redirect_after = $redirect.'&conf=5'; } } } } } else { $this->errors[] = Tools::displayError('The selected supplier is not valid.'); } } } // updates receipt if (Tools::isSubmit('submitBulkUpdatesupply_order_detail') && Tools::isSubmit('id_supply_order')) { $this->postProcessUpdateReceipt(); } // use template to create a supply order if (Tools::isSubmit('create_supply_order') && Tools::isSubmit('id_supply_order')) { $this->postProcessCopyFromTemplate(); } if ((!count($this->errors) && $this->is_editing_order) || !$this->is_editing_order) { parent::postProcess(); } } /** * Exports CSV */ protected function renderCSV() { // exports orders if (Tools::isSubmit('csv_orders')) { $ids = array(); foreach ($this->_list as $entry) { $ids[] = $entry['id_supply_order']; } if (count($ids) <= 0) { return; } $id_lang = Context::getContext()->language->id; $orders = new PrestaShopCollection('SupplyOrder', $id_lang); $orders->where('is_template', '=', false); $orders->where('id_supply_order', 'in', $ids); $id_warehouse = $this->getCurrentWarehouse(); if ($id_warehouse != -1) { $orders->where('id_warehouse', '=', $id_warehouse); } $orders->getAll(); $csv = new CSV($orders, $this->l('supply_orders')); $csv->export(); } // exports details for all orders elseif (Tools::isSubmit('csv_orders_details')) { // header header('Content-type: text/csv'); header('Content-Type: application/force-download; charset=UTF-8'); header('Cache-Control: no-store, no-cache'); header('Content-disposition: attachment; filename="'.$this->l('supply_orders_details').'.csv"'); // echoes details $ids = array(); foreach ($this->_list as $entry) { $ids[] = $entry['id_supply_order']; } if (count($ids) <= 0) { return; } // for each supply order $keys = array('id_product', 'id_product_attribute', 'reference', 'supplier_reference', 'ean13', 'upc', 'name', 'unit_price_te', 'quantity_expected', 'quantity_received', 'price_te', 'discount_rate', 'discount_value_te', 'price_with_discount_te', 'tax_rate', 'tax_value', 'price_ti', 'tax_value_with_order_discount', 'price_with_order_discount_te', 'id_supply_order'); echo sprintf("%s\n", implode(';', array_map(array('CSVCore', 'wrap'), $keys))); // overrides keys (in order to add FORMAT calls) $keys = array('sod.id_product', 'sod.id_product_attribute', 'sod.reference', 'sod.supplier_reference', 'sod.ean13', 'sod.upc', 'sod.name', 'FORMAT(sod.unit_price_te, 2)', 'sod.quantity_expected', 'sod.quantity_received', 'FORMAT(sod.price_te, 2)', 'FORMAT(sod.discount_rate, 2)', 'FORMAT(sod.discount_value_te, 2)', 'FORMAT(sod.price_with_discount_te, 2)', 'FORMAT(sod.tax_rate, 2)', 'FORMAT(sod.tax_value, 2)', 'FORMAT(sod.price_ti, 2)', 'FORMAT(sod.tax_value_with_order_discount, 2)', 'FORMAT(sod.price_with_order_discount_te, 2)', 'sod.id_supply_order'); foreach ($ids as $id) { $query = new DbQuery(); $query->select(implode(', ', $keys)); $query->from('supply_order_detail', 'sod'); $query->leftJoin('supply_order', 'so', 'so.id_supply_order = sod.id_supply_order'); $id_warehouse = $this->getCurrentWarehouse(); if ($id_warehouse != -1) { $query->where('so.id_warehouse = '.(int)$id_warehouse); } $query->where('sod.id_supply_order = '.(int)$id); $query->orderBy('sod.id_supply_order_detail DESC'); $resource = Db::getInstance()->query($query); // gets details while ($row = Db::getInstance()->nextRow($resource)) { echo sprintf("%s\n", implode(';', array_map(array('CSVCore', 'wrap'), $row))); } } } // exports details for the given order elseif (Tools::isSubmit('csv_order_details') && Tools::getValue('id_supply_order')) { $supply_order = new SupplyOrder((int)Tools::getValue('id_supply_order')); if (Validate::isLoadedObject($supply_order)) { $details = $supply_order->getEntriesCollection(); $details->getAll(); $csv = new CSV($details, $this->l('supply_order').'_'.$supply_order->reference.'_details'); $csv->export(); } } } /** * Helper function for AdminSupplyOrdersController::postProcess() * * @see AdminSupplyOrdersController::postProcess() */ protected function postProcessUpdateReceipt() { // gets all box selected $rows = Tools::getValue('supply_order_detailBox'); if (!$rows) { $this->errors[] = Tools::displayError('You did not select any products to update.'); return; } // final array with id_supply_order_detail and value to update $to_update = array(); // gets quantity for each id_order_detail foreach ($rows as $row) { if (Tools::getValue('quantity_received_today_'.$row)) { $to_update[$row] = (int)Tools::getValue('quantity_received_today_'.$row); } } // checks if there is something to update if (!count($to_update)) { $this->errors[] = Tools::displayError('You did not select any products to update.'); return; } $supply_order = new SupplyOrder((int)Tools::getValue('id_supply_order')); foreach ($to_update as $id_supply_order_detail => $quantity) { $supply_order_detail = new SupplyOrderDetail($id_supply_order_detail); if (Validate::isLoadedObject($supply_order_detail) && Validate::isLoadedObject($supply_order)) { // checks if quantity is valid // It's possible to receive more quantity than expected in case of a shipping error from the supplier if (!Validate::isInt($quantity) || $quantity <= 0) { $this->errors[] = sprintf(Tools::displayError('Quantity (%d) for product #%d is not valid'), (int)$quantity, (int)$id_supply_order_detail); } else { // everything is valid : updates // creates the history $supplier_receipt_history = new SupplyOrderReceiptHistory(); $supplier_receipt_history->id_supply_order_detail = (int)$id_supply_order_detail; $supplier_receipt_history->id_employee = (int)$this->context->employee->id; $supplier_receipt_history->employee_firstname = pSQL($this->context->employee->firstname); $supplier_receipt_history->employee_lastname = pSQL($this->context->employee->lastname); $supplier_receipt_history->id_supply_order_state = (int)$supply_order->id_supply_order_state; $supplier_receipt_history->quantity = (int)$quantity; // updates quantity received $supply_order_detail->quantity_received += (int)$quantity; // if current state is "Pending receipt", then we sets it to "Order received in part" if (3 == $supply_order->id_supply_order_state) { $supply_order->id_supply_order_state = 4; } // Adds to stock $warehouse = new Warehouse($supply_order->id_warehouse); if (!Validate::isLoadedObject($warehouse)) { $this->errors[] = Tools::displayError('The warehouse could not be loaded.'); return; } $price = $supply_order_detail->unit_price_te; // converts the unit price to the warehouse currency if needed if ($supply_order->id_currency != $warehouse->id_currency) { // first, converts the price to the default currency $price_converted_to_default_currency = Tools::convertPrice($supply_order_detail->unit_price_te, $supply_order->id_currency, false); // then, converts the newly calculated pri-ce from the default currency to the needed currency $price = Tools::ps_round(Tools::convertPrice($price_converted_to_default_currency, $warehouse->id_currency, true), 6); } $manager = StockManagerFactory::getManager(); $res = $manager->addProduct($supply_order_detail->id_product, $supply_order_detail->id_product_attribute, $warehouse, (int)$quantity, Configuration::get('PS_STOCK_MVT_SUPPLY_ORDER'), $price, true, $supply_order->id); $location = Warehouse::getProductLocation($supply_order_detail->id_product, $supply_order_detail->id_product_attribute, $warehouse->id); $res = Warehouse::setProductlocation($supply_order_detail->id_product, $supply_order_detail->id_product_attribute, $warehouse->id, $location ? $location : ''); if ($res) { $supplier_receipt_history->add(); $supply_order_detail->save(); StockAvailable::synchronize($supply_order_detail->id_product); } else { $this->errors[] = Tools::displayError('Something went wrong when setting warehouse on product record'); } } } } $supply_order->id_supply_order_state = ($supply_order->id_supply_order_state == 4 && $supply_order->getAllPendingQuantity() > 0) ? 4 : 5; $supply_order->save(); if (!count($this->errors)) { // display confirm message $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token; $redirect = self::$currentIndex.'&token='.$token; $this->redirect_after = $redirect.'&conf=4'; } } /** * Display state action link * @param string $token the token to add to the link * @param int $id the identifier to add to the link * @return string */ public function displayUpdateReceiptLink($token = null, $id) { if (!array_key_exists('Receipt', self::$cache_lang)) { self::$cache_lang['Receipt'] = $this->l('Update ongoing receipt of products'); } $this->context->smarty->assign(array( 'href' => self::$currentIndex. '&'.$this->identifier.'='.$id. '&update_receipt&token='.($token != null ? $token : $this->token), 'action' => self::$cache_lang['Receipt'], )); return $this->context->smarty->fetch('helpers/list/list_action_supply_order_receipt.tpl'); } /** * Display receipt action link * @param string $token the token to add to the link * @param int $id the identifier to add to the link * @return string */ public function displayChangestateLink($token = null, $id) { if (!array_key_exists('State', self::$cache_lang)) { self::$cache_lang['State'] = $this->l('Change status'); } $this->context->smarty->assign(array( 'href' => self::$currentIndex. '&'.$this->identifier.'='.$id. '&changestate&token='.($token != null ? $token : $this->token), 'action' => self::$cache_lang['State'], )); return $this->context->smarty->fetch('helpers/list/list_action_supply_order_change_state.tpl'); } /** * Display state action link * @param string $token the token to add to the link * @param int $id the identifier to add to the link * @return string */ public function displayCreateSupplyOrderLink($token = null, $id) { if (!array_key_exists('CreateSupplyOrder', self::$cache_lang)) { self::$cache_lang['CreateSupplyOrder'] = $this->l('Use this template to create a supply order'); } if (!array_key_exists('CreateSupplyOrderConfirm', self::$cache_lang)) { self::$cache_lang['CreateSupplyOrderConfirm'] = $this->l('Are you sure you want to use this template?'); } $this->context->smarty->assign(array( 'href' => self::$currentIndex. '&'.$this->identifier.'='.$id. '&create_supply_order&token='.($token != null ? $token : $this->token), 'confirm' => self::$cache_lang['CreateSupplyOrderConfirm'], 'action' => self::$cache_lang['CreateSupplyOrder'], )); return $this->context->smarty->fetch('helpers/list/list_action_supply_order_create_from_template.tpl'); } public function renderDetails() { // tests if an id is submit if (Tools::isSubmit('id_supply_order') && !Tools::isSubmit('display_product_history')) { // overrides attributes $this->identifier = 'id_supply_order_history'; $this->table = 'supply_order_history'; $this->lang = false; $this->actions = array(); $this->toolbar_btn = array(); $this->list_simple_header = true; // gets current lang id $lang_id = (int)$this->context->language->id; // gets supply order id $id_supply_order = (int)Tools::getValue('id_supply_order'); // creates new fields_list $this->fields_list = array( 'history_date' => array( 'title' => $this->l('Last update'), 'align' => 'left', 'type' => 'datetime', 'havingFilter' => true ), 'history_employee' => array( 'title' => $this->l('Employee'), 'align' => 'left', 'havingFilter' => true ), 'history_state_name' => array( 'title' => $this->l('Status'), 'align' => 'left', 'color' => 'color', 'havingFilter' => true ), ); // loads history of the given order unset($this->_select, $this->_join, $this->_where, $this->_orderBy, $this->_orderWay, $this->_group, $this->_filterHaving, $this->_filter); $this->_select = ' a.`date_add` as history_date, CONCAT(a.`employee_lastname`, \' \', a.`employee_firstname`) as history_employee, sosl.`name` as history_state_name, sos.`color` as color'; $this->_join = ' LEFT JOIN `'._DB_PREFIX_.'supply_order_state` sos ON (a.`id_state` = sos.`id_supply_order_state`) LEFT JOIN `'._DB_PREFIX_.'supply_order_state_lang` sosl ON ( a.`id_state` = sosl.`id_supply_order_state` AND sosl.`id_lang` = '.(int)$lang_id.' )'; $this->_where = 'AND a.`id_supply_order` = '.(int)$id_supply_order; $this->_orderBy = 'a.date_add'; $this->_orderWay = 'DESC'; return parent::renderList(); } elseif (Tools::isSubmit('id_supply_order') && Tools::isSubmit('display_product_history')) { $this->identifier = 'id_supply_order_receipt_history'; $this->table = 'supply_order_receipt_history'; $this->actions = array(); $this->toolbar_btn = array(); $this->list_simple_header = true; $this->lang = false; $lang_id = (int)$this->context->language->id; $id_supply_order_detail = (int)Tools::getValue('id_supply_order'); unset($this->fields_list); $this->fields_list = array( 'date_add' => array( 'title' => $this->l('Last update'), 'align' => 'left', 'type' => 'datetime', 'havingFilter' => true ), 'employee' => array( 'title' => $this->l('Employee'), 'align' => 'left', 'havingFilter' => true ), 'quantity' => array( 'title' => $this->l('Quantity received'), 'align' => 'left', 'havingFilter' => true ), ); // loads history of the given order unset($this->_select, $this->_join, $this->_where, $this->_orderBy, $this->_orderWay, $this->_group, $this->_filterHaving, $this->_filter); $this->_select = 'CONCAT(a.`employee_lastname`, \' \', a.`employee_firstname`) as employee'; $this->_where = 'AND a.`id_supply_order_detail` = '.(int)$id_supply_order_detail; $this->_orderBy = 'a.date_add'; $this->_orderWay = 'DESC'; return parent::renderList(); } } /** * method call when ajax request is made for search product to add to the order * @TODO - Update this method to retreive the reference, ean13, upc corresponding to a product attribute */ public function ajaxProcessSearchProduct() { // Get the search pattern $pattern = pSQL(Tools::getValue('q', false)); if (!$pattern || $pattern == '' || strlen($pattern) < 1) { die(); } // get supplier id $id_supplier = (int)Tools::getValue('id_supplier', false); // gets the currency $id_currency = (int)Tools::getValue('id_currency', false); // get lang from context $id_lang = (int)Context::getContext()->language->id; $query = new DbQuery(); $query->select(' CONCAT(p.id_product, \'_\', IFNULL(pa.id_product_attribute, \'0\')) as id, ps.product_supplier_reference as supplier_reference, IFNULL(pa.reference, IFNULL(p.reference, \'\')) as reference, IFNULL(pa.ean13, IFNULL(p.ean13, \'\')) as ean13, IFNULL(pa.upc, IFNULL(p.upc, \'\')) as upc, md5(CONCAT(\''._COOKIE_KEY_.'\', p.id_product, \'_\', IFNULL(pa.id_product_attribute, \'0\'))) as checksum, IFNULL(CONCAT(pl.name, \' : \', GROUP_CONCAT(DISTINCT agl.name, \' - \', al.name order by agl.name SEPARATOR \', \')), pl.name) as name '); $query->from('product', 'p'); $query->innerJoin('product_lang', 'pl', 'pl.id_product = p.id_product AND pl.id_lang = '.$id_lang); $query->leftJoin('product_attribute', 'pa', 'pa.id_product = p.id_product'); $query->leftJoin('product_attribute_combination', 'pac', 'pac.id_product_attribute = pa.id_product_attribute'); $query->leftJoin('attribute', 'atr', 'atr.id_attribute = pac.id_attribute'); $query->leftJoin('attribute_lang', 'al', 'al.id_attribute = atr.id_attribute AND al.id_lang = '.$id_lang); $query->leftJoin('attribute_group_lang', 'agl', 'agl.id_attribute_group = atr.id_attribute_group AND agl.id_lang = '.$id_lang); $query->leftJoin('product_supplier', 'ps', 'ps.id_product = p.id_product AND ps.id_product_attribute = IFNULL(pa.id_product_attribute, 0)'); $query->where('(pl.name LIKE \'%'.$pattern.'%\' OR p.reference LIKE \'%'.$pattern.'%\' OR ps.product_supplier_reference LIKE \'%'.$pattern.'%\')'); $query->where('NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'product_download` pd WHERE (pd.id_product = p.id_product))'); $query->where('p.is_virtual = 0 AND p.cache_is_pack = 0'); if ($id_supplier) { $query->where('ps.id_supplier = '.$id_supplier.' OR p.id_supplier = '.$id_supplier); } $query->groupBy('p.id_product, pa.id_product_attribute'); $items = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query); foreach ($items as &$item) { $ids = explode('_', $item['id']); $prices = ProductSupplier::getProductSupplierPrice($ids[0], $ids[1], $id_supplier, true); if (count($prices)) { $item['unit_price_te'] = Tools::convertPriceFull($prices['product_supplier_price_te'], new Currency((int)$prices['id_currency']), new Currency($id_currency) ); } } if ($items) { die(Tools::jsonEncode($items)); } die(1); } /** * @see AdminController::renderView() */ public function renderView() { $this->show_toolbar = true; $this->toolbar_scroll = false; $this->table = 'supply_order_detail'; $this->identifier = 'id_supply_order_detail'; $this->className = 'SupplyOrderDetail'; $this->colorOnBackground = false; $this->lang = false; $this->list_simple_header = true; $this->list_no_link = true; // gets the id supplier to view $id_supply_order = (int)Tools::getValue('id_supply_order'); // gets global order information $supply_order = new SupplyOrder((int)$id_supply_order); if (Validate::isLoadedObject($supply_order)) { if (!$supply_order->is_template) { $this->displayInformation($this->l('This interface allows you to display detailed information about your order.').'<br />'); } else { $this->displayInformation($this->l('This interface allows you to display detailed information about your order template.').'<br />'); } $lang_id = (int)$supply_order->id_lang; // just in case.. unset($this->_select, $this->_join, $this->_where, $this->_orderBy, $this->_orderWay, $this->_group, $this->_filterHaving, $this->_filter); // gets all information on the products ordered $this->_where = 'AND a.`id_supply_order` = '.(int)$id_supply_order; // gets the list ordered by price desc, without limit $this->getList($lang_id, 'price_te', 'DESC', 0, false, false); // gets the currency used in this order $currency = new Currency($supply_order->id_currency); // gets the warehouse where products will be received $warehouse = new Warehouse($supply_order->id_warehouse); // sets toolbar title with order reference if (!$supply_order->is_template) { $this->toolbar_title = sprintf($this->l('Details on supply order #%s'), $supply_order->reference); } else { $this->toolbar_title = sprintf($this->l('Details on supply order template #%s'), $supply_order->reference); } // re-defines fields_list $this->fields_list = array( 'supplier_reference' => array( 'title' => $this->l('Supplier Reference'), 'align' => 'center', 'orderby' => false, 'filter' => false, 'search' => false, ), 'reference' => array( 'title' => $this->l('Reference'), 'align' => 'center', 'orderby' => false, 'filter' => false, 'search' => false, ), 'ean13' => array( 'title' => $this->l('EAN-13 or JAN barcode'), 'align' => 'center', 'orderby' => false, 'filter' => false, 'search' => false, ), 'upc' => array( 'title' => $this->l('UPC barcode'), 'align' => 'center', 'orderby' => false, 'filter' => false, 'search' => false, ), 'name' => array( 'title' => $this->l('Name'), 'orderby' => false, 'filter' => false, 'search' => false, ), 'unit_price_te' => array( 'title' => $this->l('Unit price (tax excl.)'), 'align' => 'right', 'orderby' => false, 'filter' => false, 'search' => false, 'type' => 'price', 'currency' => true, ), 'quantity_expected' => array( 'title' => $this->l('Quantity'), 'align' => 'right', 'orderby' => false, 'filter' => false, 'search' => false, ), 'price_te' => array( 'title' => $this->l('Price (tax excl.)'), 'align' => 'right', 'orderby' => false, 'filter' => false, 'search' => false, 'type' => 'price', 'currency' => true, ), 'discount_rate' => array( 'title' => $this->l('Discount percentage'), 'align' => 'right', 'orderby' => false, 'filter' => false, 'search' => false, 'suffix' => '%', ), 'discount_value_te' => array( 'title' => $this->l('Discount value (tax excl.)'), 'align' => 'right', 'orderby' => false, 'filter' => false, 'search' => false, 'type' => 'price', 'currency' => true, ), 'price_with_discount_te' => array( 'title' => $this->l('Price with product discount (tax excl.)'), 'align' => 'right', 'orderby' => false, 'filter' => false, 'search' => false, 'type' => 'price', 'currency' => true, ), 'tax_rate' => array( 'title' => $this->l('Tax rate'), 'align' => 'right', 'orderby' => false, 'filter' => false, 'search' => false, 'suffix' => '%', ), 'tax_value' => array( 'title' => $this->l('Tax value'), 'align' => 'right', 'orderby' => false, 'filter' => false, 'search' => false, 'type' => 'price', 'currency' => true, ), 'price_ti' => array( 'title' => $this->l('Price (tax incl.)'), 'align' => 'right', 'orderby' => false, 'filter' => false, 'search' => false, 'type' => 'price', 'currency' => true, ), ); //some staff before render list foreach ($this->_list as &$item) { $item['discount_rate'] = Tools::ps_round($item['discount_rate'], 4); $item['tax_rate'] = Tools::ps_round($item['tax_rate'], 4); $item['id_currency'] = $currency->id; } // unsets some buttons unset($this->toolbar_btn['export-csv-orders']); unset($this->toolbar_btn['export-csv-details']); unset($this->toolbar_btn['new']); // renders list $helper = new HelperList(); $this->setHelperDisplay($helper); $helper->actions = array(); $helper->show_toolbar = false; $helper->toolbar_btn = $this->toolbar_btn; $content = $helper->generateList($this->_list, $this->fields_list); // display these global order informations $this->tpl_view_vars = array( 'supply_order_detail_content' => $content, 'supply_order_warehouse' => (Validate::isLoadedObject($warehouse) ? $warehouse->name : ''), 'supply_order_reference' => $supply_order->reference, 'supply_order_supplier_name' => $supply_order->supplier_name, 'supply_order_creation_date' => Tools::displayDate($supply_order->date_add, null, false), 'supply_order_last_update' => Tools::displayDate($supply_order->date_upd, null, false), 'supply_order_expected' => Tools::displayDate($supply_order->date_delivery_expected, null, false), 'supply_order_discount_rate' => Tools::ps_round($supply_order->discount_rate, 2), 'supply_order_total_te' => Tools::displayPrice($supply_order->total_te, $currency), 'supply_order_discount_value_te' => Tools::displayPrice($supply_order->discount_value_te, $currency), 'supply_order_total_with_discount_te' => Tools::displayPrice($supply_order->total_with_discount_te, $currency), 'supply_order_total_tax' => Tools::displayPrice($supply_order->total_tax, $currency), 'supply_order_total_ti' => Tools::displayPrice($supply_order->total_ti, $currency), 'supply_order_currency' => $currency, 'is_template' => $supply_order->is_template, ); } return parent::renderView(); } /** * Callback used to display custom content for a given field * @param int $id_supply_order * @param string $tr * @return string $content */ public function printExportIcons($id_supply_order, $tr) { $supply_order = new SupplyOrder((int)$id_supply_order); if (!Validate::isLoadedObject($supply_order)) { return; } $supply_order_state = new SupplyOrderState($supply_order->id_supply_order_state); if (!Validate::isLoadedObject($supply_order_state)) { return; } $content = ''; if ($supply_order_state->editable == false) { $content .= '<a class="btn btn-default" href="'.$this->context->link->getAdminLink('AdminPdf') .'&submitAction=generateSupplyOrderFormPDF&id_supply_order='.(int)$supply_order->id.'" title="'.$this->l('Export as PDF') .'"><i class="icon-print"></i></a>'; } if ($supply_order_state->enclosed == true && $supply_order_state->receipt_state == true) { $content .= '&nbsp;<a href="'.$this->context->link->getAdminLink('AdminSupplyOrders').'&id_supply_order='.(int)$supply_order->id.' &csv_order_details" class="btn btn-default" title='.$this->l('Export as CSV').'"> <i class="icon-table"></i></a>'; } return $content; } /** * Assigns default actions in toolbar_btn smarty var, if they are not set. * uses override to specifically add, modify or remove items * @see AdminSupplier::initToolbar() */ public function initToolbar() { switch ($this->display) { case 'update_order_state': $this->toolbar_btn['save'] = array( 'href' => '#', 'desc' => $this->l('Save') ); case 'update_receipt': // Default cancel button - like old back link if (!isset($this->no_back) || $this->no_back == false) { $back = Tools::safeOutput(Tools::getValue('back', '')); if (empty($back)) { $back = self::$currentIndex.'&token='.$this->token; } $this->toolbar_btn['cancel'] = array( 'href' => $back, 'desc' => $this->l('Cancel') ); } break; case 'add': case 'edit': $this->toolbar_btn['save-and-stay'] = array( 'href' => '#', 'desc' => $this->l('Save and stay') ); default: parent::initToolbar(); } } /** * Overrides AdminController::afterAdd() * @see AdminController::afterAdd() * @param ObjectModel $object * @return bool */ protected function afterAdd($object) { if (is_numeric(Tools::getValue('load_products'))) { $this->loadProducts((int)Tools::getValue('load_products')); } $this->object = $object; return true; } /** * Loads products which quantity (hysical quantity) is equal or less than $threshold * @param int $threshold */ protected function loadProducts($threshold) { // if there is already an order if (Tools::getValue('id_supply_order')) { $supply_order = new SupplyOrder((int)Tools::getValue('id_supply_order')); } else { // else, we just created a new order $supply_order = $this->object; } // if order is not valid, return; if (!Validate::isLoadedObject($supply_order)) { return; } // resets products if needed if (Tools::getValue('id_supply_order')) { $supply_order->resetProducts(); } // gets products $query = new DbQuery(); $query->select(' ps.id_product, ps.id_product_attribute, ps.product_supplier_reference as supplier_reference, ps.product_supplier_price_te as unit_price_te, ps.id_currency, IFNULL(pa.reference, IFNULL(p.reference, \'\')) as reference, IFNULL(pa.ean13, IFNULL(p.ean13, \'\')) as ean13, IFNULL(pa.upc, IFNULL(p.upc, \'\')) as upc'); $query->from('product_supplier', 'ps'); $query->innerJoin('warehouse_product_location', 'wpl', ' wpl.id_product = ps.id_product AND wpl.id_product_attribute = ps.id_product_attribute AND wpl.id_warehouse = '.(int)$supply_order->id_warehouse.' '); $query->leftJoin('product', 'p', 'p.id_product = ps.id_product'); $query->leftJoin('product_attribute', 'pa', ' pa.id_product_attribute = ps.id_product_attribute AND p.id_product = ps.id_product '); $query->where('ps.id_supplier = '.(int)$supply_order->id_supplier); // gets items $items = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query); // loads order currency $order_currency = new Currency($supply_order->id_currency); if (!Validate::isLoadedObject($order_currency)) { return; } $manager = StockManagerFactory::getManager(); foreach ($items as $item) { $diff = (int)$threshold; if ($supply_order->is_template != 1) { $real_quantity = (int)$manager->getProductRealQuantities($item['id_product'], $item['id_product_attribute'], $supply_order->id_warehouse, true); $diff = (int)$threshold - (int)$real_quantity; } if ($diff >= 0) { // sets supply_order_detail $supply_order_detail = new SupplyOrderDetail(); $supply_order_detail->id_supply_order = $supply_order->id; $supply_order_detail->id_currency = $order_currency->id; $supply_order_detail->id_product = $item['id_product']; $supply_order_detail->id_product_attribute = $item['id_product_attribute']; $supply_order_detail->reference = $item['reference']; $supply_order_detail->supplier_reference = $item['supplier_reference']; $supply_order_detail->name = Product::getProductName($item['id_product'], $item['id_product_attribute'], $supply_order->id_lang); $supply_order_detail->ean13 = $item['ean13']; $supply_order_detail->upc = $item['upc']; $supply_order_detail->quantity_expected = ((int)$diff == 0) ? 1 : (int)$diff; $supply_order_detail->exchange_rate = $order_currency->conversion_rate; $product_currency = new Currency($item['id_currency']); if (Validate::isLoadedObject($product_currency)) { $supply_order_detail->unit_price_te = Tools::convertPriceFull($item['unit_price_te'], $product_currency, $order_currency); } else { $supply_order_detail->unit_price_te = 0; } $supply_order_detail->save(); unset($product_currency); } } // updates supply order $supply_order->update(); } /** * Overrides AdminController::beforeAdd() * @see AdminController::beforeAdd() * * @param SupplyOrder $object * * @return true */ public function beforeAdd($object) { if (Tools::isSubmit('is_template')) { $object->is_template = 1; } return true; } /** * Helper function for AdminSupplyOrdersController::postProcess() * @see AdminSupplyOrdersController::postProcess() */ protected function postProcessCopyFromTemplate() { // gets SupplyOrder and checks if it is valid $id_supply_order = (int)Tools::getValue('id_supply_order'); $supply_order = new SupplyOrder($id_supply_order); if (!Validate::isLoadedObject($supply_order)) { $this->errors[] = Tools::displayError('This template could not be copied.'); } // gets SupplyOrderDetail $entries = $supply_order->getEntriesCollection($supply_order->id_lang); // updates SupplyOrder so that it is not a template anymore $language = new Language($supply_order->id_lang); $ref = $supply_order->reference; $ref .= ' ('.date($language->date_format_full).')'; $supply_order->reference = $ref; $supply_order->is_template = 0; $supply_order->id = (int)0; $supply_order->save(); // copies SupplyOrderDetail foreach ($entries as $entry) { $entry->id_supply_order = $supply_order->id; $entry->id = (int)0; $entry->save(); } // redirect when done $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token; $redirect = self::$currentIndex.'&token='.$token; $this->redirect_after = $redirect.'&conf=19'; } /** * Gets the current warehouse used * * @return int id_warehouse */ protected function getCurrentWarehouse() { static $warehouse = 0; if ($warehouse == 0) { $warehouse = -1; // all warehouses if ((int)Tools::getValue('id_warehouse')) { $warehouse = (int)Tools::getValue('id_warehouse'); } } return $warehouse; } /** * Gets the current filter used * * @return int status */ protected function getFilterStatus() { static $status = 0; $status = 0; if (Tools::getValue('filter_status') === 'on') { $status = 1; } return $status; } public function initProcess() { if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $this->warnings[md5('PS_ADVANCED_STOCK_MANAGEMENT')] = $this->l('You need to activate advanced stock management prior to using this feature.'); return false; } parent::initProcess(); } }
insbadia-dawm8/gitteam
proyecto/controllers/admin/AdminSupplyOrdersController.php
PHP
mit
96,247
/** * Parse JavaScript SDK v1.10.1 * * The source tree of this library can be found at * https://github.com/ParsePlatform/Parse-SDK-JS */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Parse = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.track = track; var _CoreManager = _dereq_('./CoreManager'); var _CoreManager2 = _interopRequireDefault(_CoreManager); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Parse.Analytics provides an interface to Parse's logging and analytics * backend. * * @class Parse.Analytics * @static */ /** * Tracks the occurrence of a custom event with additional dimensions. * Parse will store a data point at the time of invocation with the given * event name. * * Dimensions will allow segmentation of the occurrences of this custom * event. Keys and values should be {@code String}s, and will throw * otherwise. * * To track a user signup along with additional metadata, consider the * following: * <pre> * var dimensions = { * gender: 'm', * source: 'web', * dayType: 'weekend' * }; * Parse.Analytics.track('signup', dimensions); * </pre> * * There is a default limit of 8 dimensions per event tracked. * * @method track * @param {String} name The name of the custom event to report to Parse as * having happened. * @param {Object} dimensions The dictionary of information by which to * segment this event. * @param {Object} options A Backbone-style callback object. * @return {Parse.Promise} A promise that is resolved when the round-trip * to the server completes. */ function track(name, dimensions, options) { name = name || ''; name = name.replace(/^\s*/, ''); name = name.replace(/\s*$/, ''); if (name.length === 0) { throw new TypeError('A name for the custom event must be provided'); } for (var key in dimensions) { if (typeof key !== 'string' || typeof dimensions[key] !== 'string') { throw new TypeError('track() dimensions expects keys and values of type "string".'); } } options = options || {}; return _CoreManager2.default.getAnalyticsController().track(name, dimensions)._thenRunCallbacks(options); } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var DefaultController = { track: function (name, dimensions) { var RESTController = _CoreManager2.default.getRESTController(); return RESTController.request('POST', 'events/' + name, { dimensions: dimensions }); } }; _CoreManager2.default.setAnalyticsController(DefaultController); },{"./CoreManager":3}],2:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.run = run; var _CoreManager = _dereq_('./CoreManager'); var _CoreManager2 = _interopRequireDefault(_CoreManager); var _decode = _dereq_('./decode'); var _decode2 = _interopRequireDefault(_decode); var _encode = _dereq_('./encode'); var _encode2 = _interopRequireDefault(_encode); var _ParseError = _dereq_('./ParseError'); var _ParseError2 = _interopRequireDefault(_ParseError); var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Contains functions for calling and declaring * <a href="/docs/cloud_code_guide#functions">cloud functions</a>. * <p><strong><em> * Some functions are only available from Cloud Code. * </em></strong></p> * * @class Parse.Cloud * @static */ /** * Makes a call to a cloud function. * @method run * @param {String} name The function name. * @param {Object} data The parameters to send to the cloud function. * @param {Object} options A Backbone-style options object * options.success, if set, should be a function to handle a successful * call to a cloud function. options.error should be a function that * handles an error running the cloud function. Both functions are * optional. Both functions take a single argument. * @return {Parse.Promise} A promise that will be resolved with the result * of the function. */ function run(name, data, options) { options = options || {}; if (typeof name !== 'string' || name.length === 0) { throw new TypeError('Cloud function name must be a string.'); } var requestOptions = {}; if (options.useMasterKey) { requestOptions.useMasterKey = options.useMasterKey; } if (options.sessionToken) { requestOptions.sessionToken = options.sessionToken; } return _CoreManager2.default.getCloudController().run(name, data, requestOptions)._thenRunCallbacks(options); } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var DefaultController = { run: function (name, data, options) { var RESTController = _CoreManager2.default.getRESTController(); var payload = (0, _encode2.default)(data, true); var requestOptions = {}; if (options.hasOwnProperty('useMasterKey')) { requestOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('sessionToken')) { requestOptions.sessionToken = options.sessionToken; } var request = RESTController.request('POST', 'functions/' + name, payload, requestOptions); return request.then(function (res) { var decoded = (0, _decode2.default)(res); if (decoded && decoded.hasOwnProperty('result')) { return _ParsePromise2.default.as(decoded.result); } return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.INVALID_JSON, 'The server returned an invalid response.')); })._thenRunCallbacks(options); } }; _CoreManager2.default.setCloudController(DefaultController); },{"./CoreManager":3,"./ParseError":13,"./ParsePromise":21,"./decode":36,"./encode":37}],3:[function(_dereq_,module,exports){ (function (process){ 'use strict'; /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var config = { // Defaults IS_NODE: typeof process !== 'undefined' && !!process.versions && !!process.versions.node && !process.versions.electron, REQUEST_ATTEMPT_LIMIT: 5, SERVER_URL: 'https://api.parse.com/1', LIVEQUERY_SERVER_URL: null, VERSION: 'js' + '1.10.1', APPLICATION_ID: null, JAVASCRIPT_KEY: null, MASTER_KEY: null, USE_MASTER_KEY: false, PERFORM_USER_REWRITE: true, FORCE_REVOCABLE_SESSION: false }; function requireMethods(name, methods, controller) { methods.forEach(function (func) { if (typeof controller[func] !== 'function') { throw new Error(name + ' must implement ' + func + '()'); } }); } module.exports = { get: function (key) { if (config.hasOwnProperty(key)) { return config[key]; } throw new Error('Configuration key not found: ' + key); }, set: function (key, value) { config[key] = value; }, /* Specialized Controller Setters/Getters */ setAnalyticsController: function (controller) { requireMethods('AnalyticsController', ['track'], controller); config['AnalyticsController'] = controller; }, getAnalyticsController: function () { return config['AnalyticsController']; }, setCloudController: function (controller) { requireMethods('CloudController', ['run'], controller); config['CloudController'] = controller; }, getCloudController: function () { return config['CloudController']; }, setConfigController: function (controller) { requireMethods('ConfigController', ['current', 'get'], controller); config['ConfigController'] = controller; }, getConfigController: function () { return config['ConfigController']; }, setFileController: function (controller) { requireMethods('FileController', ['saveFile', 'saveBase64'], controller); config['FileController'] = controller; }, getFileController: function () { return config['FileController']; }, setInstallationController: function (controller) { requireMethods('InstallationController', ['currentInstallationId'], controller); config['InstallationController'] = controller; }, getInstallationController: function () { return config['InstallationController']; }, setObjectController: function (controller) { requireMethods('ObjectController', ['save', 'fetch', 'destroy'], controller); config['ObjectController'] = controller; }, getObjectController: function () { return config['ObjectController']; }, setObjectStateController: function (controller) { requireMethods('ObjectStateController', ['getState', 'initializeState', 'removeState', 'getServerData', 'setServerData', 'getPendingOps', 'setPendingOp', 'pushPendingState', 'popPendingState', 'mergeFirstPendingState', 'getObjectCache', 'estimateAttribute', 'estimateAttributes', 'commitServerChanges', 'enqueueTask', 'clearAllState'], controller); config['ObjectStateController'] = controller; }, getObjectStateController: function () { return config['ObjectStateController']; }, setPushController: function (controller) { requireMethods('PushController', ['send'], controller); config['PushController'] = controller; }, getPushController: function () { return config['PushController']; }, setQueryController: function (controller) { requireMethods('QueryController', ['find'], controller); config['QueryController'] = controller; }, getQueryController: function () { return config['QueryController']; }, setRESTController: function (controller) { requireMethods('RESTController', ['request', 'ajax'], controller); config['RESTController'] = controller; }, getRESTController: function () { return config['RESTController']; }, setSessionController: function (controller) { requireMethods('SessionController', ['getSession'], controller); config['SessionController'] = controller; }, getSessionController: function () { return config['SessionController']; }, setStorageController: function (controller) { if (controller.async) { requireMethods('An async StorageController', ['getItemAsync', 'setItemAsync', 'removeItemAsync'], controller); } else { requireMethods('A synchronous StorageController', ['getItem', 'setItem', 'removeItem'], controller); } config['StorageController'] = controller; }, getStorageController: function () { return config['StorageController']; }, setUserController: function (controller) { requireMethods('UserController', ['setCurrentUser', 'currentUser', 'currentUserAsync', 'signUp', 'logIn', 'become', 'logOut', 'requestPasswordReset', 'upgradeToRevocableSession', 'linkWith'], controller); config['UserController'] = controller; }, getUserController: function () { return config['UserController']; }, setLiveQueryController: function (controller) { requireMethods('LiveQueryController', ['subscribe', 'unsubscribe', 'open', 'close'], controller); config['LiveQueryController'] = controller; }, getLiveQueryController: function () { return config['LiveQueryController']; }, setHooksController: function (controller) { requireMethods('HooksController', ['create', 'get', 'update', 'remove'], controller); config['HooksController'] = controller; }, getHooksController: function () { return config['HooksController']; } }; }).call(this,_dereq_('_process')) },{"_process":63}],4:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * This is a simple wrapper to unify EventEmitter implementations across platforms. */ module.exports = _dereq_('events').EventEmitter; var EventEmitter; },{"events":170}],5:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _parseDate = _dereq_('./parseDate'); var _parseDate2 = _interopRequireDefault(_parseDate); var _ParseUser = _dereq_('./ParseUser'); var _ParseUser2 = _interopRequireDefault(_ParseUser); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * -weak */ var PUBLIC_KEY = "*"; var initialized = false; var requestedPermissions; var initOptions; var provider = { authenticate: function (options) { var _this = this; if (typeof FB === 'undefined') { options.error(this, 'Facebook SDK not found.'); } FB.login(function (response) { if (response.authResponse) { if (options.success) { options.success(_this, { id: response.authResponse.userID, access_token: response.authResponse.accessToken, expiration_date: new Date(response.authResponse.expiresIn * 1000 + new Date().getTime()).toJSON() }); } } else { if (options.error) { options.error(_this, response); } } }, { scope: requestedPermissions }); }, restoreAuthentication: function (authData) { if (authData) { var expiration = (0, _parseDate2.default)(authData.expiration_date); var expiresIn = expiration ? (expiration.getTime() - new Date().getTime()) / 1000 : 0; var authResponse = { userID: authData.id, accessToken: authData.access_token, expiresIn: expiresIn }; var newOptions = {}; if (initOptions) { for (var key in initOptions) { newOptions[key] = initOptions[key]; } } newOptions.authResponse = authResponse; // Suppress checks for login status from the browser. newOptions.status = false; // If the user doesn't match the one known by the FB SDK, log out. // Most of the time, the users will match -- it's only in cases where // the FB SDK knows of a different user than the one being restored // from a Parse User that logged in with username/password. var existingResponse = FB.getAuthResponse(); if (existingResponse && existingResponse.userID !== authResponse.userID) { FB.logout(); } FB.init(newOptions); } return true; }, getAuthType: function () { return 'facebook'; }, deauthenticate: function () { this.restoreAuthentication(null); } }; /** * Provides a set of utilities for using Parse with Facebook. * @class Parse.FacebookUtils * @static */ var FacebookUtils = { /** * Initializes Parse Facebook integration. Call this function after you * have loaded the Facebook Javascript SDK with the same parameters * as you would pass to<code> * <a href= * "https://developers.facebook.com/docs/reference/javascript/FB.init/"> * FB.init()</a></code>. Parse.FacebookUtils will invoke FB.init() for you * with these arguments. * * @method init * @param {Object} options Facebook options argument as described here: * <a href= * "https://developers.facebook.com/docs/reference/javascript/FB.init/"> * FB.init()</a>. The status flag will be coerced to 'false' because it * interferes with Parse Facebook integration. Call FB.getLoginStatus() * explicitly if this behavior is required by your application. */ init: function (options) { if (typeof FB === 'undefined') { throw new Error('The Facebook JavaScript SDK must be loaded before calling init.'); } initOptions = {}; if (options) { for (var key in options) { initOptions[key] = options[key]; } } if (initOptions.status && typeof console !== 'undefined') { var warn = console.warn || console.log || function () {}; warn.call(console, 'The "status" flag passed into' + ' FB.init, when set to true, can interfere with Parse Facebook' + ' integration, so it has been suppressed. Please call' + ' FB.getLoginStatus() explicitly if you require this behavior.'); } initOptions.status = false; FB.init(initOptions); _ParseUser2.default._registerAuthenticationProvider(provider); initialized = true; }, /** * Gets whether the user has their account linked to Facebook. * * @method isLinked * @param {Parse.User} user User to check for a facebook link. * The user must be logged in on this device. * @return {Boolean} <code>true</code> if the user has their account * linked to Facebook. */ isLinked: function (user) { return user._isLinked('facebook'); }, /** * Logs in a user using Facebook. This method delegates to the Facebook * SDK to authenticate the user, and then automatically logs in (or * creates, in the case where it is a new user) a Parse.User. * * @method logIn * @param {String, Object} permissions The permissions required for Facebook * log in. This is a comma-separated string of permissions. * Alternatively, supply a Facebook authData object as described in our * REST API docs if you want to handle getting facebook auth tokens * yourself. * @param {Object} options Standard options object with success and error * callbacks. */ logIn: function (permissions, options) { if (!permissions || typeof permissions === 'string') { if (!initialized) { throw new Error('You must initialize FacebookUtils before calling logIn.'); } requestedPermissions = permissions; return _ParseUser2.default._logInWith('facebook', options); } else { var newOptions = {}; if (options) { for (var key in options) { newOptions[key] = options[key]; } } newOptions.authData = permissions; return _ParseUser2.default._logInWith('facebook', newOptions); } }, /** * Links Facebook to an existing PFUser. This method delegates to the * Facebook SDK to authenticate the user, and then automatically links * the account to the Parse.User. * * @method link * @param {Parse.User} user User to link to Facebook. This must be the * current user. * @param {String, Object} permissions The permissions required for Facebook * log in. This is a comma-separated string of permissions. * Alternatively, supply a Facebook authData object as described in our * REST API docs if you want to handle getting facebook auth tokens * yourself. * @param {Object} options Standard options object with success and error * callbacks. */ link: function (user, permissions, options) { if (!permissions || typeof permissions === 'string') { if (!initialized) { throw new Error('You must initialize FacebookUtils before calling link.'); } requestedPermissions = permissions; return user._linkWith('facebook', options); } else { var newOptions = {}; if (options) { for (var key in options) { newOptions[key] = options[key]; } } newOptions.authData = permissions; return user._linkWith('facebook', newOptions); } }, /** * Unlinks the Parse.User from a Facebook account. * * @method unlink * @param {Parse.User} user User to unlink from Facebook. This must be the * current user. * @param {Object} options Standard options object with success and error * callbacks. */ unlink: function (user, options) { if (!initialized) { throw new Error('You must initialize FacebookUtils before calling unlink.'); } return user._unlinkFrom('facebook', options); } }; exports.default = FacebookUtils; },{"./ParseUser":26,"./parseDate":41}],6:[function(_dereq_,module,exports){ 'use strict'; var _CoreManager = _dereq_('./CoreManager'); var _CoreManager2 = _interopRequireDefault(_CoreManager); var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); var _Storage = _dereq_('./Storage'); var _Storage2 = _interopRequireDefault(_Storage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var iidCache = null; /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function hexOctet() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); } function generateId() { return hexOctet() + hexOctet() + '-' + hexOctet() + '-' + hexOctet() + '-' + hexOctet() + '-' + hexOctet() + hexOctet() + hexOctet(); } var InstallationController = { currentInstallationId: function () { if (typeof iidCache === 'string') { return _ParsePromise2.default.as(iidCache); } var path = _Storage2.default.generatePath('installationId'); return _Storage2.default.getItemAsync(path).then(function (iid) { if (!iid) { iid = generateId(); return _Storage2.default.setItemAsync(path, iid).then(function () { iidCache = iid; return iid; }); } iidCache = iid; return iid; }); }, _clearCache: function () { iidCache = null; }, _setInstallationIdCache: function (iid) { iidCache = iid; } }; module.exports = InstallationController; },{"./CoreManager":3,"./ParsePromise":21,"./Storage":30}],7:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); var _getIterator2 = _dereq_('babel-runtime/core-js/get-iterator'); var _getIterator3 = _interopRequireDefault(_getIterator2); var _stringify = _dereq_('babel-runtime/core-js/json/stringify'); var _stringify2 = _interopRequireDefault(_stringify); var _map = _dereq_('babel-runtime/core-js/map'); var _map2 = _interopRequireDefault(_map); var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = _dereq_('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _EventEmitter2 = _dereq_('./EventEmitter'); var _EventEmitter3 = _interopRequireDefault(_EventEmitter2); var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); var _ParseObject = _dereq_('./ParseObject'); var _ParseObject2 = _interopRequireDefault(_ParseObject); var _LiveQuerySubscription = _dereq_('./LiveQuerySubscription'); var _LiveQuerySubscription2 = _interopRequireDefault(_LiveQuerySubscription); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // The LiveQuery client inner state /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var CLIENT_STATE = { INITIALIZED: 'initialized', CONNECTING: 'connecting', CONNECTED: 'connected', CLOSED: 'closed', RECONNECTING: 'reconnecting', DISCONNECTED: 'disconnected' }; // The event type the LiveQuery client should sent to server var OP_TYPES = { CONNECT: 'connect', SUBSCRIBE: 'subscribe', UNSUBSCRIBE: 'unsubscribe', ERROR: 'error' }; // The event we get back from LiveQuery server var OP_EVENTS = { CONNECTED: 'connected', SUBSCRIBED: 'subscribed', UNSUBSCRIBED: 'unsubscribed', ERROR: 'error', CREATE: 'create', UPDATE: 'update', ENTER: 'enter', LEAVE: 'leave', DELETE: 'delete' }; // The event the LiveQuery client should emit var CLIENT_EMMITER_TYPES = { CLOSE: 'close', ERROR: 'error', OPEN: 'open' }; // The event the LiveQuery subscription should emit var SUBSCRIPTION_EMMITER_TYPES = { OPEN: 'open', CLOSE: 'close', ERROR: 'error', CREATE: 'create', UPDATE: 'update', ENTER: 'enter', LEAVE: 'leave', DELETE: 'delete' }; var generateInterval = function (k) { return Math.random() * Math.min(30, Math.pow(2, k) - 1) * 1000; }; /** * Creates a new LiveQueryClient. * Extends events.EventEmitter * <a href="https://nodejs.org/api/events.html#events_class_eventemitter">cloud functions</a>. * * A wrapper of a standard WebSocket client. We add several useful methods to * help you connect/disconnect to LiveQueryServer, subscribe/unsubscribe a ParseQuery easily. * * javascriptKey and masterKey are used for verifying the LiveQueryClient when it tries * to connect to the LiveQuery server * * @class Parse.LiveQueryClient * @constructor * @param {Object} options * @param {string} options.applicationId - applicationId of your Parse app * @param {string} options.serverURL - <b>the URL of your LiveQuery server</b> * @param {string} options.javascriptKey (optional) * @param {string} options.masterKey (optional) Your Parse Master Key. (Node.js only!) * @param {string} options.sessionToken (optional) * * * We expose three events to help you monitor the status of the LiveQueryClient. * * <pre> * let Parse = require('parse/node'); * let LiveQueryClient = Parse.LiveQueryClient; * let client = new LiveQueryClient({ * applicationId: '', * serverURL: '', * javascriptKey: '', * masterKey: '' * }); * </pre> * * Open - When we establish the WebSocket connection to the LiveQuery server, you'll get this event. * <pre> * client.on('open', () => { * * });</pre> * * Close - When we lose the WebSocket connection to the LiveQuery server, you'll get this event. * <pre> * client.on('close', () => { * * });</pre> * * Error - When some network error or LiveQuery server error happens, you'll get this event. * <pre> * client.on('error', (error) => { * * });</pre> * * */ var LiveQueryClient = function (_EventEmitter) { (0, _inherits3.default)(LiveQueryClient, _EventEmitter); function LiveQueryClient(_ref) { var applicationId = _ref.applicationId, serverURL = _ref.serverURL, javascriptKey = _ref.javascriptKey, masterKey = _ref.masterKey, sessionToken = _ref.sessionToken; (0, _classCallCheck3.default)(this, LiveQueryClient); var _this = (0, _possibleConstructorReturn3.default)(this, (LiveQueryClient.__proto__ || (0, _getPrototypeOf2.default)(LiveQueryClient)).call(this)); if (!serverURL || serverURL.indexOf('ws') !== 0) { throw new Error('You need to set a proper Parse LiveQuery server url before using LiveQueryClient'); } _this.reconnectHandle = null; _this.attempts = 1; _this.id = 0; _this.requestId = 1; _this.serverURL = serverURL; _this.applicationId = applicationId; _this.javascriptKey = javascriptKey; _this.masterKey = masterKey; _this.sessionToken = sessionToken; _this.connectPromise = new _ParsePromise2.default(); _this.subscriptions = new _map2.default(); _this.state = CLIENT_STATE.INITIALIZED; return _this; } (0, _createClass3.default)(LiveQueryClient, [{ key: 'shouldOpen', value: function () { return this.state === CLIENT_STATE.INITIALIZED || this.state === CLIENT_STATE.DISCONNECTED; } /** * Subscribes to a ParseQuery * * If you provide the sessionToken, when the LiveQuery server gets ParseObject's * updates from parse server, it'll try to check whether the sessionToken fulfills * the ParseObject's ACL. The LiveQuery server will only send updates to clients whose * sessionToken is fit for the ParseObject's ACL. You can check the LiveQuery protocol * <a href="https://github.com/ParsePlatform/parse-server/wiki/Parse-LiveQuery-Protocol-Specification">here</a> for more details. The subscription you get is the same subscription you get * from our Standard API. * * @method subscribe * @param {Object} query - the ParseQuery you want to subscribe to * @param {string} sessionToken (optional) * @return {Object} subscription */ }, { key: 'subscribe', value: function (query, sessionToken) { var _this2 = this; if (!query) { return; } var where = query.toJSON().where; var className = query.className; var subscribeRequest = { op: OP_TYPES.SUBSCRIBE, requestId: this.requestId, query: { className: className, where: where } }; if (sessionToken) { subscribeRequest.sessionToken = sessionToken; } var subscription = new _LiveQuerySubscription2.default(this.requestId, query, sessionToken); this.subscriptions.set(this.requestId, subscription); this.requestId += 1; this.connectPromise.then(function () { _this2.socket.send((0, _stringify2.default)(subscribeRequest)); }); // adding listener so process does not crash // best practice is for developer to register their own listener subscription.on('error', function () {}); return subscription; } /** * After calling unsubscribe you'll stop receiving events from the subscription object. * * @method unsubscribe * @param {Object} subscription - subscription you would like to unsubscribe from. */ }, { key: 'unsubscribe', value: function (subscription) { var _this3 = this; if (!subscription) { return; } this.subscriptions.delete(subscription.id); var unsubscribeRequest = { op: OP_TYPES.UNSUBSCRIBE, requestId: subscription.id }; this.connectPromise.then(function () { _this3.socket.send((0, _stringify2.default)(unsubscribeRequest)); }); } /** * After open is called, the LiveQueryClient will try to send a connect request * to the LiveQuery server. * * @method open */ }, { key: 'open', value: function () { var _this4 = this; var WebSocketImplementation = this._getWebSocketImplementation(); if (!WebSocketImplementation) { this.emit(CLIENT_EMMITER_TYPES.ERROR, 'Can not find WebSocket implementation'); return; } if (this.state !== CLIENT_STATE.RECONNECTING) { this.state = CLIENT_STATE.CONNECTING; } // Get WebSocket implementation this.socket = new WebSocketImplementation(this.serverURL); // Bind WebSocket callbacks this.socket.onopen = function () { _this4._handleWebSocketOpen(); }; this.socket.onmessage = function (event) { _this4._handleWebSocketMessage(event); }; this.socket.onclose = function () { _this4._handleWebSocketClose(); }; this.socket.onerror = function (error) { _this4._handleWebSocketError(error); }; } }, { key: 'resubscribe', value: function () { var _this5 = this; this.subscriptions.forEach(function (subscription, requestId) { var query = subscription.query; var where = query.toJSON().where; var className = query.className; var sessionToken = subscription.sessionToken; var subscribeRequest = { op: OP_TYPES.SUBSCRIBE, requestId: requestId, query: { className: className, where: where } }; if (sessionToken) { subscribeRequest.sessionToken = sessionToken; } _this5.connectPromise.then(function () { _this5.socket.send((0, _stringify2.default)(subscribeRequest)); }); }); } /** * This method will close the WebSocket connection to this LiveQueryClient, * cancel the auto reconnect and unsubscribe all subscriptions based on it. * * @method close */ }, { key: 'close', value: function () { if (this.state === CLIENT_STATE.INITIALIZED || this.state === CLIENT_STATE.DISCONNECTED) { return; } this.state = CLIENT_STATE.DISCONNECTED; this.socket.close(); // Notify each subscription about the close var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = (0, _getIterator3.default)(this.subscriptions.values()), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var subscription = _step.value; subscription.emit(SUBSCRIPTION_EMMITER_TYPES.CLOSE); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } this._handleReset(); this.emit(CLIENT_EMMITER_TYPES.CLOSE); } }, { key: '_getWebSocketImplementation', value: function () { return typeof WebSocket === 'function' || (typeof WebSocket === 'undefined' ? 'undefined' : (0, _typeof3.default)(WebSocket)) === 'object' ? WebSocket : null; } // ensure we start with valid state if connect is called again after close }, { key: '_handleReset', value: function () { this.attempts = 1; this.id = 0; this.requestId = 1; this.connectPromise = new _ParsePromise2.default(); this.subscriptions = new _map2.default(); } }, { key: '_handleWebSocketOpen', value: function () { this.attempts = 1; var connectRequest = { op: OP_TYPES.CONNECT, applicationId: this.applicationId, javascriptKey: this.javascriptKey, masterKey: this.masterKey, sessionToken: this.sessionToken }; this.socket.send((0, _stringify2.default)(connectRequest)); } }, { key: '_handleWebSocketMessage', value: function (event) { var data = event.data; if (typeof data === 'string') { data = JSON.parse(data); } var subscription = null; if (data.requestId) { subscription = this.subscriptions.get(data.requestId); } switch (data.op) { case OP_EVENTS.CONNECTED: if (this.state === CLIENT_STATE.RECONNECTING) { this.resubscribe(); } this.emit(CLIENT_EMMITER_TYPES.OPEN); this.id = data.clientId; this.connectPromise.resolve(); this.state = CLIENT_STATE.CONNECTED; break; case OP_EVENTS.SUBSCRIBED: if (subscription) { subscription.emit(SUBSCRIPTION_EMMITER_TYPES.OPEN); } break; case OP_EVENTS.ERROR: if (data.requestId) { if (subscription) { subscription.emit(SUBSCRIPTION_EMMITER_TYPES.ERROR, data.error); } } else { this.emit(CLIENT_EMMITER_TYPES.ERROR, data.error); } break; case OP_EVENTS.UNSUBSCRIBED: // We have already deleted subscription in unsubscribe(), do nothing here break; default: // create, update, enter, leave, delete cases var className = data.object.className; // Delete the extrea __type and className fields during transfer to full JSON delete data.object.__type; delete data.object.className; var parseObject = new _ParseObject2.default(className); parseObject._finishFetch(data.object); if (!subscription) { break; } subscription.emit(data.op, parseObject); } } }, { key: '_handleWebSocketClose', value: function () { if (this.state === CLIENT_STATE.DISCONNECTED) { return; } this.state = CLIENT_STATE.CLOSED; this.emit(CLIENT_EMMITER_TYPES.CLOSE); // Notify each subscription about the close var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = (0, _getIterator3.default)(this.subscriptions.values()), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var subscription = _step2.value; subscription.emit(SUBSCRIPTION_EMMITER_TYPES.CLOSE); } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } this._handleReconnect(); } }, { key: '_handleWebSocketError', value: function (error) { this.emit(CLIENT_EMMITER_TYPES.ERROR, error); var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { for (var _iterator3 = (0, _getIterator3.default)(this.subscriptions.values()), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var subscription = _step3.value; subscription.emit(SUBSCRIPTION_EMMITER_TYPES.ERROR); } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3.return) { _iterator3.return(); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } this._handleReconnect(); } }, { key: '_handleReconnect', value: function () { var _this6 = this; // if closed or currently reconnecting we stop attempting to reconnect if (this.state === CLIENT_STATE.DISCONNECTED) { return; } this.state = CLIENT_STATE.RECONNECTING; var time = generateInterval(this.attempts); // handle case when both close/error occur at frequent rates we ensure we do not reconnect unnecessarily. // we're unable to distinguish different between close/error when we're unable to reconnect therefore // we try to reonnect in both cases // server side ws and browser WebSocket behave differently in when close/error get triggered if (this.reconnectHandle) { clearTimeout(this.reconnectHandle); } this.reconnectHandle = setTimeout(function () { _this6.attempts++; _this6.connectPromise = new _ParsePromise2.default(); _this6.open(); }.bind(this), time); } }]); return LiveQueryClient; }(_EventEmitter3.default); exports.default = LiveQueryClient; },{"./EventEmitter":4,"./LiveQuerySubscription":8,"./ParseObject":18,"./ParsePromise":21,"babel-runtime/core-js/get-iterator":44,"babel-runtime/core-js/json/stringify":45,"babel-runtime/core-js/map":46,"babel-runtime/core-js/object/get-prototype-of":51,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/inherits":60,"babel-runtime/helpers/possibleConstructorReturn":61,"babel-runtime/helpers/typeof":62}],8:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = _dereq_('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _EventEmitter2 = _dereq_('./EventEmitter'); var _EventEmitter3 = _interopRequireDefault(_EventEmitter2); var _CoreManager = _dereq_('./CoreManager'); var _CoreManager2 = _interopRequireDefault(_CoreManager); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Creates a new LiveQuery Subscription. * Extends events.EventEmitter * <a href="https://nodejs.org/api/events.html#events_class_eventemitter">cloud functions</a>. * * @constructor * @param {string} id - subscription id * @param {string} query - query to subscribe to * @param {string} sessionToken - optional session token * * <p>Open Event - When you call query.subscribe(), we send a subscribe request to * the LiveQuery server, when we get the confirmation from the LiveQuery server, * this event will be emitted. When the client loses WebSocket connection to the * LiveQuery server, we will try to auto reconnect the LiveQuery server. If we * reconnect the LiveQuery server and successfully resubscribe the ParseQuery, * you'll also get this event. * * <pre> * subscription.on('open', () => { * * });</pre></p> * * <p>Create Event - When a new ParseObject is created and it fulfills the ParseQuery you subscribe, * you'll get this event. The object is the ParseObject which is created. * * <pre> * subscription.on('create', (object) => { * * });</pre></p> * * <p>Update Event - When an existing ParseObject which fulfills the ParseQuery you subscribe * is updated (The ParseObject fulfills the ParseQuery before and after changes), * you'll get this event. The object is the ParseObject which is updated. * Its content is the latest value of the ParseObject. * * <pre> * subscription.on('update', (object) => { * * });</pre></p> * * <p>Enter Event - When an existing ParseObject's old value doesn't fulfill the ParseQuery * but its new value fulfills the ParseQuery, you'll get this event. The object is the * ParseObject which enters the ParseQuery. Its content is the latest value of the ParseObject. * * <pre> * subscription.on('enter', (object) => { * * });</pre></p> * * * <p>Update Event - When an existing ParseObject's old value fulfills the ParseQuery but its new value * doesn't fulfill the ParseQuery, you'll get this event. The object is the ParseObject * which leaves the ParseQuery. Its content is the latest value of the ParseObject. * * <pre> * subscription.on('leave', (object) => { * * });</pre></p> * * * <p>Delete Event - When an existing ParseObject which fulfills the ParseQuery is deleted, you'll * get this event. The object is the ParseObject which is deleted. * * <pre> * subscription.on('delete', (object) => { * * });</pre></p> * * * <p>Close Event - When the client loses the WebSocket connection to the LiveQuery * server and we stop receiving events, you'll get this event. * * <pre> * subscription.on('close', () => { * * });</pre></p> * * */ /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var Subscription = function (_EventEmitter) { (0, _inherits3.default)(Subscription, _EventEmitter); function Subscription(id, query, sessionToken) { (0, _classCallCheck3.default)(this, Subscription); var _this2 = (0, _possibleConstructorReturn3.default)(this, (Subscription.__proto__ || (0, _getPrototypeOf2.default)(Subscription)).call(this)); _this2.id = id; _this2.query = query; _this2.sessionToken = sessionToken; return _this2; } /** * @method unsubscribe */ (0, _createClass3.default)(Subscription, [{ key: 'unsubscribe', value: function () { var _this3 = this; var _this = this; _CoreManager2.default.getLiveQueryController().getDefaultLiveQueryClient().then(function (liveQueryClient) { liveQueryClient.unsubscribe(_this); _this.emit('close'); _this3.resolve(); }); } }]); return Subscription; }(_EventEmitter3.default); exports.default = Subscription; },{"./CoreManager":3,"./EventEmitter":4,"babel-runtime/core-js/object/get-prototype-of":51,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/inherits":60,"babel-runtime/helpers/possibleConstructorReturn":61}],9:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stringify = _dereq_('babel-runtime/core-js/json/stringify'); var _stringify2 = _interopRequireDefault(_stringify); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); exports.defaultState = defaultState; exports.setServerData = setServerData; exports.setPendingOp = setPendingOp; exports.pushPendingState = pushPendingState; exports.popPendingState = popPendingState; exports.mergeFirstPendingState = mergeFirstPendingState; exports.estimateAttribute = estimateAttribute; exports.estimateAttributes = estimateAttributes; exports.commitServerChanges = commitServerChanges; var _encode = _dereq_('./encode'); var _encode2 = _interopRequireDefault(_encode); var _ParseFile = _dereq_('./ParseFile'); var _ParseFile2 = _interopRequireDefault(_ParseFile); var _ParseObject = _dereq_('./ParseObject'); var _ParseObject2 = _interopRequireDefault(_ParseObject); var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); var _ParseRelation = _dereq_('./ParseRelation'); var _ParseRelation2 = _interopRequireDefault(_ParseRelation); var _TaskQueue = _dereq_('./TaskQueue'); var _TaskQueue2 = _interopRequireDefault(_TaskQueue); var _ParseOp = _dereq_('./ParseOp'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function defaultState() { return { serverData: {}, pendingOps: [{}], objectCache: {}, tasks: new _TaskQueue2.default(), existed: false }; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function setServerData(serverData, attributes) { for (var _attr in attributes) { if (typeof attributes[_attr] !== 'undefined') { serverData[_attr] = attributes[_attr]; } else { delete serverData[_attr]; } } } function setPendingOp(pendingOps, attr, op) { var last = pendingOps.length - 1; if (op) { pendingOps[last][attr] = op; } else { delete pendingOps[last][attr]; } } function pushPendingState(pendingOps) { pendingOps.push({}); } function popPendingState(pendingOps) { var first = pendingOps.shift(); if (!pendingOps.length) { pendingOps[0] = {}; } return first; } function mergeFirstPendingState(pendingOps) { var first = popPendingState(pendingOps); var next = pendingOps[0]; for (var _attr2 in first) { if (next[_attr2] && first[_attr2]) { var merged = next[_attr2].mergeWith(first[_attr2]); if (merged) { next[_attr2] = merged; } } else { next[_attr2] = first[_attr2]; } } } function estimateAttribute(serverData, pendingOps, className, id, attr) { var value = serverData[attr]; for (var i = 0; i < pendingOps.length; i++) { if (pendingOps[i][attr]) { if (pendingOps[i][attr] instanceof _ParseOp.RelationOp) { if (id) { value = pendingOps[i][attr].applyTo(value, { className: className, id: id }, attr); } } else { value = pendingOps[i][attr].applyTo(value); } } } return value; } function estimateAttributes(serverData, pendingOps, className, id) { var data = {}; var attr = void 0; for (attr in serverData) { data[attr] = serverData[attr]; } for (var i = 0; i < pendingOps.length; i++) { for (attr in pendingOps[i]) { if (pendingOps[i][attr] instanceof _ParseOp.RelationOp) { if (id) { data[attr] = pendingOps[i][attr].applyTo(data[attr], { className: className, id: id }, attr); } } else { data[attr] = pendingOps[i][attr].applyTo(data[attr]); } } } return data; } function commitServerChanges(serverData, objectCache, changes) { for (var _attr3 in changes) { var val = changes[_attr3]; serverData[_attr3] = val; if (val && (typeof val === 'undefined' ? 'undefined' : (0, _typeof3.default)(val)) === 'object' && !(val instanceof _ParseObject2.default) && !(val instanceof _ParseFile2.default) && !(val instanceof _ParseRelation2.default)) { var json = (0, _encode2.default)(val, false, true); objectCache[_attr3] = (0, _stringify2.default)(json); } } } },{"./ParseFile":14,"./ParseObject":18,"./ParseOp":19,"./ParsePromise":21,"./ParseRelation":23,"./TaskQueue":32,"./encode":37,"babel-runtime/core-js/json/stringify":45,"babel-runtime/helpers/typeof":62}],10:[function(_dereq_,module,exports){ 'use strict'; var _decode = _dereq_('./decode'); var _decode2 = _interopRequireDefault(_decode); var _encode = _dereq_('./encode'); var _encode2 = _interopRequireDefault(_encode); var _CoreManager = _dereq_('./CoreManager'); var _CoreManager2 = _interopRequireDefault(_CoreManager); var _InstallationController = _dereq_('./InstallationController'); var _InstallationController2 = _interopRequireDefault(_InstallationController); var _ParseOp = _dereq_('./ParseOp'); var ParseOp = _interopRequireWildcard(_ParseOp); var _RESTController = _dereq_('./RESTController'); var _RESTController2 = _interopRequireDefault(_RESTController); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Contains all Parse API classes and functions. * @class Parse * @static */ /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ var Parse = { /** * Call this method first to set up your authentication tokens for Parse. * You can get your keys from the Data Browser on parse.com. * @method initialize * @param {String} applicationId Your Parse Application ID. * @param {String} javaScriptKey (optional) Your Parse JavaScript Key (Not needed for parse-server) * @param {String} masterKey (optional) Your Parse Master Key. (Node.js only!) * @static */ initialize: function (applicationId, javaScriptKey) { if ('browser' === 'browser' && _CoreManager2.default.get('IS_NODE') && !undefined) { console.log('It looks like you\'re using the browser version of the SDK in a ' + 'node.js environment. You should require(\'parse/node\') instead.'); } Parse._initialize(applicationId, javaScriptKey); }, _initialize: function (applicationId, javaScriptKey, masterKey) { _CoreManager2.default.set('APPLICATION_ID', applicationId); _CoreManager2.default.set('JAVASCRIPT_KEY', javaScriptKey); _CoreManager2.default.set('MASTER_KEY', masterKey); _CoreManager2.default.set('USE_MASTER_KEY', false); } }; /** These legacy setters may eventually be deprecated **/ Object.defineProperty(Parse, 'applicationId', { get: function () { return _CoreManager2.default.get('APPLICATION_ID'); }, set: function (value) { _CoreManager2.default.set('APPLICATION_ID', value); } }); Object.defineProperty(Parse, 'javaScriptKey', { get: function () { return _CoreManager2.default.get('JAVASCRIPT_KEY'); }, set: function (value) { _CoreManager2.default.set('JAVASCRIPT_KEY', value); } }); Object.defineProperty(Parse, 'masterKey', { get: function () { return _CoreManager2.default.get('MASTER_KEY'); }, set: function (value) { _CoreManager2.default.set('MASTER_KEY', value); } }); Object.defineProperty(Parse, 'serverURL', { get: function () { return _CoreManager2.default.get('SERVER_URL'); }, set: function (value) { _CoreManager2.default.set('SERVER_URL', value); } }); Object.defineProperty(Parse, 'liveQueryServerURL', { get: function () { return _CoreManager2.default.get('LIVEQUERY_SERVER_URL'); }, set: function (value) { _CoreManager2.default.set('LIVEQUERY_SERVER_URL', value); } }); /** End setters **/ Parse.ACL = _dereq_('./ParseACL').default; Parse.Analytics = _dereq_('./Analytics'); Parse.Cloud = _dereq_('./Cloud'); Parse.CoreManager = _dereq_('./CoreManager'); Parse.Config = _dereq_('./ParseConfig').default; Parse.Error = _dereq_('./ParseError').default; Parse.FacebookUtils = _dereq_('./FacebookUtils').default; Parse.File = _dereq_('./ParseFile').default; Parse.GeoPoint = _dereq_('./ParseGeoPoint').default; Parse.Polygon = _dereq_('./ParsePolygon').default; Parse.Installation = _dereq_('./ParseInstallation').default; Parse.Object = _dereq_('./ParseObject').default; Parse.Op = { Set: ParseOp.SetOp, Unset: ParseOp.UnsetOp, Increment: ParseOp.IncrementOp, Add: ParseOp.AddOp, Remove: ParseOp.RemoveOp, AddUnique: ParseOp.AddUniqueOp, Relation: ParseOp.RelationOp }; Parse.Promise = _dereq_('./ParsePromise').default; Parse.Push = _dereq_('./Push'); Parse.Query = _dereq_('./ParseQuery').default; Parse.Relation = _dereq_('./ParseRelation').default; Parse.Role = _dereq_('./ParseRole').default; Parse.Session = _dereq_('./ParseSession').default; Parse.Storage = _dereq_('./Storage'); Parse.User = _dereq_('./ParseUser').default; Parse.LiveQuery = _dereq_('./ParseLiveQuery').default; Parse.LiveQueryClient = _dereq_('./LiveQueryClient').default; Parse._request = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _CoreManager2.default.getRESTController().request.apply(null, args); }; Parse._ajax = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return _CoreManager2.default.getRESTController().ajax.apply(null, args); }; // We attempt to match the signatures of the legacy versions of these methods Parse._decode = function (_, value) { return (0, _decode2.default)(value); }; Parse._encode = function (value, _, disallowObjects) { return (0, _encode2.default)(value, disallowObjects); }; Parse._getInstallationId = function () { return _CoreManager2.default.getInstallationController().currentInstallationId(); }; _CoreManager2.default.setInstallationController(_InstallationController2.default); _CoreManager2.default.setRESTController(_RESTController2.default); // For legacy requires, of the form `var Parse = require('parse').Parse` Parse.Parse = Parse; module.exports = Parse; },{"./Analytics":1,"./Cloud":2,"./CoreManager":3,"./FacebookUtils":5,"./InstallationController":6,"./LiveQueryClient":7,"./ParseACL":11,"./ParseConfig":12,"./ParseError":13,"./ParseFile":14,"./ParseGeoPoint":15,"./ParseInstallation":16,"./ParseLiveQuery":17,"./ParseObject":18,"./ParseOp":19,"./ParsePolygon":20,"./ParsePromise":21,"./ParseQuery":22,"./ParseRelation":23,"./ParseRole":24,"./ParseSession":25,"./ParseUser":26,"./Push":27,"./RESTController":28,"./Storage":30,"./decode":36,"./encode":37}],11:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _keys = _dereq_('babel-runtime/core-js/object/keys'); var _keys2 = _interopRequireDefault(_keys); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _ParseRole = _dereq_('./ParseRole'); var _ParseRole2 = _interopRequireDefault(_ParseRole); var _ParseUser = _dereq_('./ParseUser'); var _ParseUser2 = _interopRequireDefault(_ParseUser); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var PUBLIC_KEY = '*'; /** * Creates a new ACL. * If no argument is given, the ACL has no permissions for anyone. * If the argument is a Parse.User, the ACL will have read and write * permission for only that user. * If the argument is any other JSON object, that object will be interpretted * as a serialized ACL created with toJSON(). * @class Parse.ACL * @constructor * * <p>An ACL, or Access Control List can be added to any * <code>Parse.Object</code> to restrict access to only a subset of users * of your application.</p> */ var ParseACL = function () { function ParseACL(arg1) { (0, _classCallCheck3.default)(this, ParseACL); this.permissionsById = {}; if (arg1 && (typeof arg1 === 'undefined' ? 'undefined' : (0, _typeof3.default)(arg1)) === 'object') { if (arg1 instanceof _ParseUser2.default) { this.setReadAccess(arg1, true); this.setWriteAccess(arg1, true); } else { for (var userId in arg1) { var accessList = arg1[userId]; if (typeof userId !== 'string') { throw new TypeError('Tried to create an ACL with an invalid user id.'); } this.permissionsById[userId] = {}; for (var permission in accessList) { var allowed = accessList[permission]; if (permission !== 'read' && permission !== 'write') { throw new TypeError('Tried to create an ACL with an invalid permission type.'); } if (typeof allowed !== 'boolean') { throw new TypeError('Tried to create an ACL with an invalid permission value.'); } this.permissionsById[userId][permission] = allowed; } } } } else if (typeof arg1 === 'function') { throw new TypeError('ParseACL constructed with a function. Did you forget ()?'); } } /** * Returns a JSON-encoded version of the ACL. * @method toJSON * @return {Object} */ (0, _createClass3.default)(ParseACL, [{ key: 'toJSON', value: function () { var permissions = {}; for (var p in this.permissionsById) { permissions[p] = this.permissionsById[p]; } return permissions; } /** * Returns whether this ACL is equal to another object * @method equals * @param other The other object to compare to * @return {Boolean} */ }, { key: 'equals', value: function (other) { if (!(other instanceof ParseACL)) { return false; } var users = (0, _keys2.default)(this.permissionsById); var otherUsers = (0, _keys2.default)(other.permissionsById); if (users.length !== otherUsers.length) { return false; } for (var u in this.permissionsById) { if (!other.permissionsById[u]) { return false; } if (this.permissionsById[u].read !== other.permissionsById[u].read) { return false; } if (this.permissionsById[u].write !== other.permissionsById[u].write) { return false; } } return true; } }, { key: '_setAccess', value: function (accessType, userId, allowed) { if (userId instanceof _ParseUser2.default) { userId = userId.id; } else if (userId instanceof _ParseRole2.default) { var name = userId.getName(); if (!name) { throw new TypeError('Role must have a name'); } userId = 'role:' + name; } if (typeof userId !== 'string') { throw new TypeError('userId must be a string.'); } if (typeof allowed !== 'boolean') { throw new TypeError('allowed must be either true or false.'); } var permissions = this.permissionsById[userId]; if (!permissions) { if (!allowed) { // The user already doesn't have this permission, so no action is needed return; } else { permissions = {}; this.permissionsById[userId] = permissions; } } if (allowed) { this.permissionsById[userId][accessType] = true; } else { delete permissions[accessType]; if ((0, _keys2.default)(permissions).length === 0) { delete this.permissionsById[userId]; } } } }, { key: '_getAccess', value: function (accessType, userId) { if (userId instanceof _ParseUser2.default) { userId = userId.id; if (!userId) { throw new Error('Cannot get access for a ParseUser without an ID'); } } else if (userId instanceof _ParseRole2.default) { var name = userId.getName(); if (!name) { throw new TypeError('Role must have a name'); } userId = 'role:' + name; } var permissions = this.permissionsById[userId]; if (!permissions) { return false; } return !!permissions[accessType]; } /** * Sets whether the given user is allowed to read this object. * @method setReadAccess * @param userId An instance of Parse.User or its objectId. * @param {Boolean} allowed Whether that user should have read access. */ }, { key: 'setReadAccess', value: function (userId, allowed) { this._setAccess('read', userId, allowed); } /** * Get whether the given user id is *explicitly* allowed to read this object. * Even if this returns false, the user may still be able to access it if * getPublicReadAccess returns true or a role that the user belongs to has * write access. * @method getReadAccess * @param userId An instance of Parse.User or its objectId, or a Parse.Role. * @return {Boolean} */ }, { key: 'getReadAccess', value: function (userId) { return this._getAccess('read', userId); } /** * Sets whether the given user id is allowed to write this object. * @method setWriteAccess * @param userId An instance of Parse.User or its objectId, or a Parse.Role.. * @param {Boolean} allowed Whether that user should have write access. */ }, { key: 'setWriteAccess', value: function (userId, allowed) { this._setAccess('write', userId, allowed); } /** * Gets whether the given user id is *explicitly* allowed to write this object. * Even if this returns false, the user may still be able to write it if * getPublicWriteAccess returns true or a role that the user belongs to has * write access. * @method getWriteAccess * @param userId An instance of Parse.User or its objectId, or a Parse.Role. * @return {Boolean} */ }, { key: 'getWriteAccess', value: function (userId) { return this._getAccess('write', userId); } /** * Sets whether the public is allowed to read this object. * @method setPublicReadAccess * @param {Boolean} allowed */ }, { key: 'setPublicReadAccess', value: function (allowed) { this.setReadAccess(PUBLIC_KEY, allowed); } /** * Gets whether the public is allowed to read this object. * @method getPublicReadAccess * @return {Boolean} */ }, { key: 'getPublicReadAccess', value: function () { return this.getReadAccess(PUBLIC_KEY); } /** * Sets whether the public is allowed to write this object. * @method setPublicWriteAccess * @param {Boolean} allowed */ }, { key: 'setPublicWriteAccess', value: function (allowed) { this.setWriteAccess(PUBLIC_KEY, allowed); } /** * Gets whether the public is allowed to write this object. * @method getPublicWriteAccess * @return {Boolean} */ }, { key: 'getPublicWriteAccess', value: function () { return this.getWriteAccess(PUBLIC_KEY); } /** * Gets whether users belonging to the given role are allowed * to read this object. Even if this returns false, the role may * still be able to write it if a parent role has read access. * * @method getRoleReadAccess * @param role The name of the role, or a Parse.Role object. * @return {Boolean} true if the role has read access. false otherwise. * @throws {TypeError} If role is neither a Parse.Role nor a String. */ }, { key: 'getRoleReadAccess', value: function (role) { if (role instanceof _ParseRole2.default) { // Normalize to the String name role = role.getName(); } if (typeof role !== 'string') { throw new TypeError('role must be a ParseRole or a String'); } return this.getReadAccess('role:' + role); } /** * Gets whether users belonging to the given role are allowed * to write this object. Even if this returns false, the role may * still be able to write it if a parent role has write access. * * @method getRoleWriteAccess * @param role The name of the role, or a Parse.Role object. * @return {Boolean} true if the role has write access. false otherwise. * @throws {TypeError} If role is neither a Parse.Role nor a String. */ }, { key: 'getRoleWriteAccess', value: function (role) { if (role instanceof _ParseRole2.default) { // Normalize to the String name role = role.getName(); } if (typeof role !== 'string') { throw new TypeError('role must be a ParseRole or a String'); } return this.getWriteAccess('role:' + role); } /** * Sets whether users belonging to the given role are allowed * to read this object. * * @method setRoleReadAccess * @param role The name of the role, or a Parse.Role object. * @param {Boolean} allowed Whether the given role can read this object. * @throws {TypeError} If role is neither a Parse.Role nor a String. */ }, { key: 'setRoleReadAccess', value: function (role, allowed) { if (role instanceof _ParseRole2.default) { // Normalize to the String name role = role.getName(); } if (typeof role !== 'string') { throw new TypeError('role must be a ParseRole or a String'); } this.setReadAccess('role:' + role, allowed); } /** * Sets whether users belonging to the given role are allowed * to write this object. * * @method setRoleWriteAccess * @param role The name of the role, or a Parse.Role object. * @param {Boolean} allowed Whether the given role can write this object. * @throws {TypeError} If role is neither a Parse.Role nor a String. */ }, { key: 'setRoleWriteAccess', value: function (role, allowed) { if (role instanceof _ParseRole2.default) { // Normalize to the String name role = role.getName(); } if (typeof role !== 'string') { throw new TypeError('role must be a ParseRole or a String'); } this.setWriteAccess('role:' + role, allowed); } }]); return ParseACL; }(); exports.default = ParseACL; },{"./ParseRole":24,"./ParseUser":26,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/typeof":62}],12:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stringify = _dereq_('babel-runtime/core-js/json/stringify'); var _stringify2 = _interopRequireDefault(_stringify); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _CoreManager = _dereq_('./CoreManager'); var _CoreManager2 = _interopRequireDefault(_CoreManager); var _decode = _dereq_('./decode'); var _decode2 = _interopRequireDefault(_decode); var _encode = _dereq_('./encode'); var _encode2 = _interopRequireDefault(_encode); var _escape2 = _dereq_('./escape'); var _escape3 = _interopRequireDefault(_escape2); var _ParseError = _dereq_('./ParseError'); var _ParseError2 = _interopRequireDefault(_ParseError); var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); var _Storage = _dereq_('./Storage'); var _Storage2 = _interopRequireDefault(_Storage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Parse.Config is a local representation of configuration data that * can be set from the Parse dashboard. * * @class Parse.Config * @constructor */ var ParseConfig = function () { function ParseConfig() { (0, _classCallCheck3.default)(this, ParseConfig); this.attributes = {}; this._escapedAttributes = {}; } /** * Gets the value of an attribute. * @method get * @param {String} attr The name of an attribute. */ (0, _createClass3.default)(ParseConfig, [{ key: 'get', value: function (attr) { return this.attributes[attr]; } /** * Gets the HTML-escaped value of an attribute. * @method escape * @param {String} attr The name of an attribute. */ }, { key: 'escape', value: function (attr) { var html = this._escapedAttributes[attr]; if (html) { return html; } var val = this.attributes[attr]; var escaped = ''; if (val != null) { escaped = (0, _escape3.default)(val.toString()); } this._escapedAttributes[attr] = escaped; return escaped; } /** * Retrieves the most recently-fetched configuration object, either from * memory or from local storage if necessary. * * @method current * @static * @return {Config} The most recently-fetched Parse.Config if it * exists, else an empty Parse.Config. */ }], [{ key: 'current', value: function () { var controller = _CoreManager2.default.getConfigController(); return controller.current(); } /** * Gets a new configuration object from the server. * @method get * @static * @param {Object} options A Backbone-style options object. * Valid options are:<ul> * <li>success: Function to call when the get completes successfully. * <li>error: Function to call when the get fails. * </ul> * @return {Parse.Promise} A promise that is resolved with a newly-created * configuration object when the get completes. */ }, { key: 'get', value: function (options) { options = options || {}; var controller = _CoreManager2.default.getConfigController(); return controller.get()._thenRunCallbacks(options); } }]); return ParseConfig; }(); /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ exports.default = ParseConfig; var currentConfig = null; var CURRENT_CONFIG_KEY = 'currentConfig'; function decodePayload(data) { try { var json = JSON.parse(data); if (json && (typeof json === 'undefined' ? 'undefined' : (0, _typeof3.default)(json)) === 'object') { return (0, _decode2.default)(json); } } catch (e) { return null; } } var DefaultController = { current: function () { if (currentConfig) { return currentConfig; } var config = new ParseConfig(); var storagePath = _Storage2.default.generatePath(CURRENT_CONFIG_KEY); var configData; if (!_Storage2.default.async()) { configData = _Storage2.default.getItem(storagePath); if (configData) { var attributes = decodePayload(configData); if (attributes) { config.attributes = attributes; currentConfig = config; } } return config; } // Return a promise for async storage controllers return _Storage2.default.getItemAsync(storagePath).then(function (configData) { if (configData) { var attributes = decodePayload(configData); if (attributes) { config.attributes = attributes; currentConfig = config; } } return config; }); }, get: function () { var RESTController = _CoreManager2.default.getRESTController(); return RESTController.request('GET', 'config', {}, {}).then(function (response) { if (!response || !response.params) { var error = new _ParseError2.default(_ParseError2.default.INVALID_JSON, 'Config JSON response invalid.'); return _ParsePromise2.default.error(error); } var config = new ParseConfig(); config.attributes = {}; for (var attr in response.params) { config.attributes[attr] = (0, _decode2.default)(response.params[attr]); } currentConfig = config; return _Storage2.default.setItemAsync(_Storage2.default.generatePath(CURRENT_CONFIG_KEY), (0, _stringify2.default)(response.params)).then(function () { return config; }); }); } }; _CoreManager2.default.setConfigController(DefaultController); },{"./CoreManager":3,"./ParseError":13,"./ParsePromise":21,"./Storage":30,"./decode":36,"./encode":37,"./escape":39,"babel-runtime/core-js/json/stringify":45,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/typeof":62}],13:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ /** * Constructs a new Parse.Error object with the given code and message. * @class Parse.Error * @constructor * @param {Number} code An error code constant from <code>Parse.Error</code>. * @param {String} message A detailed description of the error. */ var ParseError = function () { function ParseError(code, message) { (0, _classCallCheck3.default)(this, ParseError); this.code = code; this.message = message; } (0, _createClass3.default)(ParseError, [{ key: 'toString', value: function () { return 'ParseError: ' + this.code + ' ' + this.message; } }]); return ParseError; }(); /** * Error code indicating some error other than those enumerated here. * @property OTHER_CAUSE * @static * @final */ exports.default = ParseError; ParseError.OTHER_CAUSE = -1; /** * Error code indicating that something has gone wrong with the server. * If you get this error code, it is Parse's fault. Contact us at * https://parse.com/help * @property INTERNAL_SERVER_ERROR * @static * @final */ ParseError.INTERNAL_SERVER_ERROR = 1; /** * Error code indicating the connection to the Parse servers failed. * @property CONNECTION_FAILED * @static * @final */ ParseError.CONNECTION_FAILED = 100; /** * Error code indicating the specified object doesn't exist. * @property OBJECT_NOT_FOUND * @static * @final */ ParseError.OBJECT_NOT_FOUND = 101; /** * Error code indicating you tried to query with a datatype that doesn't * support it, like exact matching an array or object. * @property INVALID_QUERY * @static * @final */ ParseError.INVALID_QUERY = 102; /** * Error code indicating a missing or invalid classname. Classnames are * case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the * only valid characters. * @property INVALID_CLASS_NAME * @static * @final */ ParseError.INVALID_CLASS_NAME = 103; /** * Error code indicating an unspecified object id. * @property MISSING_OBJECT_ID * @static * @final */ ParseError.MISSING_OBJECT_ID = 104; /** * Error code indicating an invalid key name. Keys are case-sensitive. They * must start with a letter, and a-zA-Z0-9_ are the only valid characters. * @property INVALID_KEY_NAME * @static * @final */ ParseError.INVALID_KEY_NAME = 105; /** * Error code indicating a malformed pointer. You should not see this unless * you have been mucking about changing internal Parse code. * @property INVALID_POINTER * @static * @final */ ParseError.INVALID_POINTER = 106; /** * Error code indicating that badly formed JSON was received upstream. This * either indicates you have done something unusual with modifying how * things encode to JSON, or the network is failing badly. * @property INVALID_JSON * @static * @final */ ParseError.INVALID_JSON = 107; /** * Error code indicating that the feature you tried to access is only * available internally for testing purposes. * @property COMMAND_UNAVAILABLE * @static * @final */ ParseError.COMMAND_UNAVAILABLE = 108; /** * You must call Parse.initialize before using the Parse library. * @property NOT_INITIALIZED * @static * @final */ ParseError.NOT_INITIALIZED = 109; /** * Error code indicating that a field was set to an inconsistent type. * @property INCORRECT_TYPE * @static * @final */ ParseError.INCORRECT_TYPE = 111; /** * Error code indicating an invalid channel name. A channel name is either * an empty string (the broadcast channel) or contains only a-zA-Z0-9_ * characters and starts with a letter. * @property INVALID_CHANNEL_NAME * @static * @final */ ParseError.INVALID_CHANNEL_NAME = 112; /** * Error code indicating that push is misconfigured. * @property PUSH_MISCONFIGURED * @static * @final */ ParseError.PUSH_MISCONFIGURED = 115; /** * Error code indicating that the object is too large. * @property OBJECT_TOO_LARGE * @static * @final */ ParseError.OBJECT_TOO_LARGE = 116; /** * Error code indicating that the operation isn't allowed for clients. * @property OPERATION_FORBIDDEN * @static * @final */ ParseError.OPERATION_FORBIDDEN = 119; /** * Error code indicating the result was not found in the cache. * @property CACHE_MISS * @static * @final */ ParseError.CACHE_MISS = 120; /** * Error code indicating that an invalid key was used in a nested * JSONObject. * @property INVALID_NESTED_KEY * @static * @final */ ParseError.INVALID_NESTED_KEY = 121; /** * Error code indicating that an invalid filename was used for ParseFile. * A valid file name contains only a-zA-Z0-9_. characters and is between 1 * and 128 characters. * @property INVALID_FILE_NAME * @static * @final */ ParseError.INVALID_FILE_NAME = 122; /** * Error code indicating an invalid ACL was provided. * @property INVALID_ACL * @static * @final */ ParseError.INVALID_ACL = 123; /** * Error code indicating that the request timed out on the server. Typically * this indicates that the request is too expensive to run. * @property TIMEOUT * @static * @final */ ParseError.TIMEOUT = 124; /** * Error code indicating that the email address was invalid. * @property INVALID_EMAIL_ADDRESS * @static * @final */ ParseError.INVALID_EMAIL_ADDRESS = 125; /** * Error code indicating a missing content type. * @property MISSING_CONTENT_TYPE * @static * @final */ ParseError.MISSING_CONTENT_TYPE = 126; /** * Error code indicating a missing content length. * @property MISSING_CONTENT_LENGTH * @static * @final */ ParseError.MISSING_CONTENT_LENGTH = 127; /** * Error code indicating an invalid content length. * @property INVALID_CONTENT_LENGTH * @static * @final */ ParseError.INVALID_CONTENT_LENGTH = 128; /** * Error code indicating a file that was too large. * @property FILE_TOO_LARGE * @static * @final */ ParseError.FILE_TOO_LARGE = 129; /** * Error code indicating an error saving a file. * @property FILE_SAVE_ERROR * @static * @final */ ParseError.FILE_SAVE_ERROR = 130; /** * Error code indicating that a unique field was given a value that is * already taken. * @property DUPLICATE_VALUE * @static * @final */ ParseError.DUPLICATE_VALUE = 137; /** * Error code indicating that a role's name is invalid. * @property INVALID_ROLE_NAME * @static * @final */ ParseError.INVALID_ROLE_NAME = 139; /** * Error code indicating that an application quota was exceeded. Upgrade to * resolve. * @property EXCEEDED_QUOTA * @static * @final */ ParseError.EXCEEDED_QUOTA = 140; /** * Error code indicating that a Cloud Code script failed. * @property SCRIPT_FAILED * @static * @final */ ParseError.SCRIPT_FAILED = 141; /** * Error code indicating that a Cloud Code validation failed. * @property VALIDATION_ERROR * @static * @final */ ParseError.VALIDATION_ERROR = 142; /** * Error code indicating that invalid image data was provided. * @property INVALID_IMAGE_DATA * @static * @final */ ParseError.INVALID_IMAGE_DATA = 143; /** * Error code indicating an unsaved file. * @property UNSAVED_FILE_ERROR * @static * @final */ ParseError.UNSAVED_FILE_ERROR = 151; /** * Error code indicating an invalid push time. * @property INVALID_PUSH_TIME_ERROR * @static * @final */ ParseError.INVALID_PUSH_TIME_ERROR = 152; /** * Error code indicating an error deleting a file. * @property FILE_DELETE_ERROR * @static * @final */ ParseError.FILE_DELETE_ERROR = 153; /** * Error code indicating that the application has exceeded its request * limit. * @property REQUEST_LIMIT_EXCEEDED * @static * @final */ ParseError.REQUEST_LIMIT_EXCEEDED = 155; /** * Error code indicating an invalid event name. * @property INVALID_EVENT_NAME * @static * @final */ ParseError.INVALID_EVENT_NAME = 160; /** * Error code indicating that the username is missing or empty. * @property USERNAME_MISSING * @static * @final */ ParseError.USERNAME_MISSING = 200; /** * Error code indicating that the password is missing or empty. * @property PASSWORD_MISSING * @static * @final */ ParseError.PASSWORD_MISSING = 201; /** * Error code indicating that the username has already been taken. * @property USERNAME_TAKEN * @static * @final */ ParseError.USERNAME_TAKEN = 202; /** * Error code indicating that the email has already been taken. * @property EMAIL_TAKEN * @static * @final */ ParseError.EMAIL_TAKEN = 203; /** * Error code indicating that the email is missing, but must be specified. * @property EMAIL_MISSING * @static * @final */ ParseError.EMAIL_MISSING = 204; /** * Error code indicating that a user with the specified email was not found. * @property EMAIL_NOT_FOUND * @static * @final */ ParseError.EMAIL_NOT_FOUND = 205; /** * Error code indicating that a user object without a valid session could * not be altered. * @property SESSION_MISSING * @static * @final */ ParseError.SESSION_MISSING = 206; /** * Error code indicating that a user can only be created through signup. * @property MUST_CREATE_USER_THROUGH_SIGNUP * @static * @final */ ParseError.MUST_CREATE_USER_THROUGH_SIGNUP = 207; /** * Error code indicating that an an account being linked is already linked * to another user. * @property ACCOUNT_ALREADY_LINKED * @static * @final */ ParseError.ACCOUNT_ALREADY_LINKED = 208; /** * Error code indicating that the current session token is invalid. * @property INVALID_SESSION_TOKEN * @static * @final */ ParseError.INVALID_SESSION_TOKEN = 209; /** * Error code indicating that a user cannot be linked to an account because * that account's id could not be found. * @property LINKED_ID_MISSING * @static * @final */ ParseError.LINKED_ID_MISSING = 250; /** * Error code indicating that a user with a linked (e.g. Facebook) account * has an invalid session. * @property INVALID_LINKED_SESSION * @static * @final */ ParseError.INVALID_LINKED_SESSION = 251; /** * Error code indicating that a service being linked (e.g. Facebook or * Twitter) is unsupported. * @property UNSUPPORTED_SERVICE * @static * @final */ ParseError.UNSUPPORTED_SERVICE = 252; /** * Error code indicating that there were multiple errors. Aggregate errors * have an "errors" property, which is an array of error objects with more * detail about each error that occurred. * @property AGGREGATE_ERROR * @static * @final */ ParseError.AGGREGATE_ERROR = 600; /** * Error code indicating the client was unable to read an input file. * @property FILE_READ_ERROR * @static * @final */ ParseError.FILE_READ_ERROR = 601; /** * Error code indicating a real error code is unavailable because * we had to use an XDomainRequest object to allow CORS requests in * Internet Explorer, which strips the body from HTTP responses that have * a non-2XX status code. * @property X_DOMAIN_REQUEST * @static * @final */ ParseError.X_DOMAIN_REQUEST = 602; },{"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58}],14:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _CoreManager = _dereq_('./CoreManager'); var _CoreManager2 = _interopRequireDefault(_CoreManager); var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var dataUriRegexp = /^data:([a-zA-Z]*\/[a-zA-Z+.-]*);(charset=[a-zA-Z0-9\-\/\s]*,)?base64,/; function b64Digit(number) { if (number < 26) { return String.fromCharCode(65 + number); } if (number < 52) { return String.fromCharCode(97 + (number - 26)); } if (number < 62) { return String.fromCharCode(48 + (number - 52)); } if (number === 62) { return '+'; } if (number === 63) { return '/'; } throw new TypeError('Tried to encode large digit ' + number + ' in base64.'); } /** * A Parse.File is a local representation of a file that is saved to the Parse * cloud. * @class Parse.File * @constructor * @param name {String} The file's name. This will be prefixed by a unique * value once the file has finished saving. The file name must begin with * an alphanumeric character, and consist of alphanumeric characters, * periods, spaces, underscores, or dashes. * @param data {Array} The data for the file, as either: * 1. an Array of byte value Numbers, or * 2. an Object like { base64: "..." } with a base64-encoded String. * 3. a File object selected with a file upload control. (3) only works * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+. * For example:<pre> * var fileUploadControl = $("#profilePhotoFileUpload")[0]; * if (fileUploadControl.files.length > 0) { * var file = fileUploadControl.files[0]; * var name = "photo.jpg"; * var parseFile = new Parse.File(name, file); * parseFile.save().then(function() { * // The file has been saved to Parse. * }, function(error) { * // The file either could not be read, or could not be saved to Parse. * }); * }</pre> * @param type {String} Optional Content-Type header to use for the file. If * this is omitted, the content type will be inferred from the name's * extension. */ var ParseFile = function () { function ParseFile(name, data, type) { (0, _classCallCheck3.default)(this, ParseFile); var specifiedType = type || ''; this._name = name; if (data !== undefined) { if (Array.isArray(data)) { this._source = { format: 'base64', base64: ParseFile.encodeBase64(data), type: specifiedType }; } else if (typeof File !== 'undefined' && data instanceof File) { this._source = { format: 'file', file: data, type: specifiedType }; } else if (data && typeof data.base64 === 'string') { var _base = data.base64; var commaIndex = _base.indexOf(','); if (commaIndex !== -1) { var matches = dataUriRegexp.exec(_base.slice(0, commaIndex + 1)); // if data URI with type and charset, there will be 4 matches. this._source = { format: 'base64', base64: _base.slice(commaIndex + 1), type: matches[1] }; } else { this._source = { format: 'base64', base64: _base, type: specifiedType }; } } else { throw new TypeError('Cannot create a Parse.File with that data.'); } } } /** * Gets the name of the file. Before save is called, this is the filename * given by the user. After save is called, that name gets prefixed with a * unique identifier. * @method name * @return {String} */ (0, _createClass3.default)(ParseFile, [{ key: 'name', value: function () { return this._name; } /** * Gets the url of the file. It is only available after you save the file or * after you get the file from a Parse.Object. * @method url * @param {Object} options An object to specify url options * @return {String} */ }, { key: 'url', value: function (options) { options = options || {}; if (!this._url) { return; } if (options.forceSecure) { return this._url.replace(/^http:\/\//i, 'https://'); } else { return this._url; } } /** * Saves the file to the Parse cloud. * @method save * @param {Object} options A Backbone-style options object. * @return {Parse.Promise} Promise that is resolved when the save finishes. */ }, { key: 'save', value: function (options) { var _this = this; options = options || {}; var controller = _CoreManager2.default.getFileController(); if (!this._previousSave) { if (this._source.format === 'file') { this._previousSave = controller.saveFile(this._name, this._source, options).then(function (res) { _this._name = res.name; _this._url = res.url; return _this; }); } else { this._previousSave = controller.saveBase64(this._name, this._source, options).then(function (res) { _this._name = res.name; _this._url = res.url; return _this; }); } } if (this._previousSave) { return this._previousSave._thenRunCallbacks(options); } } }, { key: 'toJSON', value: function () { return { __type: 'File', name: this._name, url: this._url }; } }, { key: 'equals', value: function (other) { if (this === other) { return true; } // Unsaved Files are never equal, since they will be saved to different URLs return other instanceof ParseFile && this.name() === other.name() && this.url() === other.url() && typeof this.url() !== 'undefined'; } }], [{ key: 'fromJSON', value: function (obj) { if (obj.__type !== 'File') { throw new TypeError('JSON object does not represent a ParseFile'); } var file = new ParseFile(obj.name); file._url = obj.url; return file; } }, { key: 'encodeBase64', value: function (bytes) { var chunks = []; chunks.length = Math.ceil(bytes.length / 3); for (var i = 0; i < chunks.length; i++) { var b1 = bytes[i * 3]; var b2 = bytes[i * 3 + 1] || 0; var b3 = bytes[i * 3 + 2] || 0; var has2 = i * 3 + 1 < bytes.length; var has3 = i * 3 + 2 < bytes.length; chunks[i] = [b64Digit(b1 >> 2 & 0x3F), b64Digit(b1 << 4 & 0x30 | b2 >> 4 & 0x0F), has2 ? b64Digit(b2 << 2 & 0x3C | b3 >> 6 & 0x03) : '=', has3 ? b64Digit(b3 & 0x3F) : '='].join(''); } return chunks.join(''); } }]); return ParseFile; }(); exports.default = ParseFile; var DefaultController = { saveFile: function (name, source) { if (source.format !== 'file') { throw new Error('saveFile can only be used with File-type sources.'); } // To directly upload a File, we use a REST-style AJAX request var headers = { 'X-Parse-Application-ID': _CoreManager2.default.get('APPLICATION_ID'), 'X-Parse-JavaScript-Key': _CoreManager2.default.get('JAVASCRIPT_KEY'), 'Content-Type': source.type || (source.file ? source.file.type : null) }; var url = _CoreManager2.default.get('SERVER_URL'); if (url[url.length - 1] !== '/') { url += '/'; } url += 'files/' + name; return _CoreManager2.default.getRESTController().ajax('POST', url, source.file, headers); }, saveBase64: function (name, source, options) { if (source.format !== 'base64') { throw new Error('saveBase64 can only be used with Base64-type sources.'); } var data = { base64: source.base64 }; if (source.type) { data._ContentType = source.type; } return _CoreManager2.default.getRESTController().request('POST', 'files/' + name, data, options); } }; _CoreManager2.default.setFileController(DefaultController); },{"./CoreManager":3,"./ParsePromise":21,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58}],15:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Creates a new GeoPoint with any of the following forms:<br> * <pre> * new GeoPoint(otherGeoPoint) * new GeoPoint(30, 30) * new GeoPoint([30, 30]) * new GeoPoint({latitude: 30, longitude: 30}) * new GeoPoint() // defaults to (0, 0) * </pre> * @class Parse.GeoPoint * @constructor * * <p>Represents a latitude / longitude point that may be associated * with a key in a ParseObject or used as a reference point for geo queries. * This allows proximity-based queries on the key.</p> * * <p>Only one key in a class may contain a GeoPoint.</p> * * <p>Example:<pre> * var point = new Parse.GeoPoint(30.0, -20.0); * var object = new Parse.Object("PlaceObject"); * object.set("location", point); * object.save();</pre></p> */ var ParseGeoPoint = function () { function ParseGeoPoint(arg1, arg2) { (0, _classCallCheck3.default)(this, ParseGeoPoint); if (Array.isArray(arg1)) { ParseGeoPoint._validate(arg1[0], arg1[1]); this._latitude = arg1[0]; this._longitude = arg1[1]; } else if ((typeof arg1 === 'undefined' ? 'undefined' : (0, _typeof3.default)(arg1)) === 'object') { ParseGeoPoint._validate(arg1.latitude, arg1.longitude); this._latitude = arg1.latitude; this._longitude = arg1.longitude; } else if (typeof arg1 === 'number' && typeof arg2 === 'number') { ParseGeoPoint._validate(arg1, arg2); this._latitude = arg1; this._longitude = arg2; } else { this._latitude = 0; this._longitude = 0; } } /** * North-south portion of the coordinate, in range [-90, 90]. * Throws an exception if set out of range in a modern browser. * @property latitude * @type Number */ (0, _createClass3.default)(ParseGeoPoint, [{ key: 'toJSON', /** * Returns a JSON representation of the GeoPoint, suitable for Parse. * @method toJSON * @return {Object} */ value: function () { ParseGeoPoint._validate(this._latitude, this._longitude); return { __type: 'GeoPoint', latitude: this._latitude, longitude: this._longitude }; } }, { key: 'equals', value: function (other) { return other instanceof ParseGeoPoint && this.latitude === other.latitude && this.longitude === other.longitude; } /** * Returns the distance from this GeoPoint to another in radians. * @method radiansTo * @param {Parse.GeoPoint} point the other Parse.GeoPoint. * @return {Number} */ }, { key: 'radiansTo', value: function (point) { var d2r = Math.PI / 180.0; var lat1rad = this.latitude * d2r; var long1rad = this.longitude * d2r; var lat2rad = point.latitude * d2r; var long2rad = point.longitude * d2r; var sinDeltaLatDiv2 = Math.sin((lat1rad - lat2rad) / 2); var sinDeltaLongDiv2 = Math.sin((long1rad - long2rad) / 2); // Square of half the straight line chord distance between both points. var a = sinDeltaLatDiv2 * sinDeltaLatDiv2 + Math.cos(lat1rad) * Math.cos(lat2rad) * sinDeltaLongDiv2 * sinDeltaLongDiv2; a = Math.min(1.0, a); return 2 * Math.asin(Math.sqrt(a)); } /** * Returns the distance from this GeoPoint to another in kilometers. * @method kilometersTo * @param {Parse.GeoPoint} point the other Parse.GeoPoint. * @return {Number} */ }, { key: 'kilometersTo', value: function (point) { return this.radiansTo(point) * 6371.0; } /** * Returns the distance from this GeoPoint to another in miles. * @method milesTo * @param {Parse.GeoPoint} point the other Parse.GeoPoint. * @return {Number} */ }, { key: 'milesTo', value: function (point) { return this.radiansTo(point) * 3958.8; } /** * Throws an exception if the given lat-long is out of bounds. */ }, { key: 'latitude', get: function () { return this._latitude; }, set: function (val) { ParseGeoPoint._validate(val, this.longitude); this._latitude = val; } /** * East-west portion of the coordinate, in range [-180, 180]. * Throws if set out of range in a modern browser. * @property longitude * @type Number */ }, { key: 'longitude', get: function () { return this._longitude; }, set: function (val) { ParseGeoPoint._validate(this.latitude, val); this._longitude = val; } }], [{ key: '_validate', value: function (latitude, longitude) { if (latitude !== latitude || longitude !== longitude) { throw new TypeError('GeoPoint latitude and longitude must be valid numbers'); } if (latitude < -90.0) { throw new TypeError('GeoPoint latitude out of bounds: ' + latitude + ' < -90.0.'); } if (latitude > 90.0) { throw new TypeError('GeoPoint latitude out of bounds: ' + latitude + ' > 90.0.'); } if (longitude < -180.0) { throw new TypeError('GeoPoint longitude out of bounds: ' + longitude + ' < -180.0.'); } if (longitude > 180.0) { throw new TypeError('GeoPoint longitude out of bounds: ' + longitude + ' > 180.0.'); } } /** * Creates a GeoPoint with the user's current location, if available. * Calls options.success with a new GeoPoint instance or calls options.error. * @method current * @param {Object} options An object with success and error callbacks. * @static */ }, { key: 'current', value: function (options) { var promise = new _ParsePromise2.default(); navigator.geolocation.getCurrentPosition(function (location) { promise.resolve(new ParseGeoPoint(location.coords.latitude, location.coords.longitude)); }, function (error) { promise.reject(error); }); return promise._thenRunCallbacks(options); } }]); return ParseGeoPoint; }(); /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ exports.default = ParseGeoPoint; },{"./ParsePromise":21,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/typeof":62}],16:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = _dereq_('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _ParseObject2 = _dereq_('./ParseObject'); var _ParseObject3 = _interopRequireDefault(_ParseObject2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Installation = function (_ParseObject) { (0, _inherits3.default)(Installation, _ParseObject); function Installation(attributes) { (0, _classCallCheck3.default)(this, Installation); var _this = (0, _possibleConstructorReturn3.default)(this, (Installation.__proto__ || (0, _getPrototypeOf2.default)(Installation)).call(this, '_Installation')); if (attributes && (typeof attributes === 'undefined' ? 'undefined' : (0, _typeof3.default)(attributes)) === 'object') { if (!_this.set(attributes || {})) { throw new Error('Can\'t create an invalid Session'); } } return _this; } return Installation; }(_ParseObject3.default); /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ exports.default = Installation; _ParseObject3.default.registerSubclass('_Installation', Installation); },{"./ParseObject":18,"babel-runtime/core-js/object/get-prototype-of":51,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/inherits":60,"babel-runtime/helpers/possibleConstructorReturn":61,"babel-runtime/helpers/typeof":62}],17:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _EventEmitter = _dereq_('./EventEmitter'); var _EventEmitter2 = _interopRequireDefault(_EventEmitter); var _LiveQueryClient = _dereq_('./LiveQueryClient'); var _LiveQueryClient2 = _interopRequireDefault(_LiveQueryClient); var _CoreManager = _dereq_('./CoreManager'); var _CoreManager2 = _interopRequireDefault(_CoreManager); var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function open() { var LiveQueryController = _CoreManager2.default.getLiveQueryController(); LiveQueryController.open(); } function close() { var LiveQueryController = _CoreManager2.default.getLiveQueryController(); LiveQueryController.close(); } /** * * We expose three events to help you monitor the status of the WebSocket connection: * * <p>Open - When we establish the WebSocket connection to the LiveQuery server, you'll get this event. * * <pre> * Parse.LiveQuery.on('open', () => { * * });</pre></p> * * <p>Close - When we lose the WebSocket connection to the LiveQuery server, you'll get this event. * * <pre> * Parse.LiveQuery.on('close', () => { * * });</pre></p> * * <p>Error - When some network error or LiveQuery server error happens, you'll get this event. * * <pre> * Parse.LiveQuery.on('error', (error) => { * * });</pre></p> * * @class Parse.LiveQuery * @static * */ var LiveQuery = new _EventEmitter2.default(); /** * After open is called, the LiveQuery will try to send a connect request * to the LiveQuery server. * * @method open */ LiveQuery.open = open; /** * When you're done using LiveQuery, you can call Parse.LiveQuery.close(). * This function will close the WebSocket connection to the LiveQuery server, * cancel the auto reconnect, and unsubscribe all subscriptions based on it. * If you call query.subscribe() after this, we'll create a new WebSocket * connection to the LiveQuery server. * * @method close */ LiveQuery.close = close; // Register a default onError callback to make sure we do not crash on error LiveQuery.on('error', function () {}); exports.default = LiveQuery; function getSessionToken() { var controller = _CoreManager2.default.getUserController(); return controller.currentUserAsync().then(function (currentUser) { return currentUser ? currentUser.getSessionToken() : undefined; }); } function getLiveQueryClient() { return _CoreManager2.default.getLiveQueryController().getDefaultLiveQueryClient(); } var defaultLiveQueryClient = void 0; var DefaultLiveQueryController = { setDefaultLiveQueryClient: function (liveQueryClient) { defaultLiveQueryClient = liveQueryClient; }, getDefaultLiveQueryClient: function () { if (defaultLiveQueryClient) { return _ParsePromise2.default.as(defaultLiveQueryClient); } return getSessionToken().then(function (sessionToken) { var liveQueryServerURL = _CoreManager2.default.get('LIVEQUERY_SERVER_URL'); if (liveQueryServerURL && liveQueryServerURL.indexOf('ws') !== 0) { throw new Error('You need to set a proper Parse LiveQuery server url before using LiveQueryClient'); } // If we can not find Parse.liveQueryServerURL, we try to extract it from Parse.serverURL if (!liveQueryServerURL) { var tempServerURL = _CoreManager2.default.get('SERVER_URL'); var protocol = 'ws://'; // If Parse is being served over SSL/HTTPS, ensure LiveQuery Server uses 'wss://' prefix if (tempServerURL.indexOf('https') === 0) { protocol = 'wss://'; } var host = tempServerURL.replace(/^https?:\/\//, ''); liveQueryServerURL = protocol + host; _CoreManager2.default.set('LIVEQUERY_SERVER_URL', liveQueryServerURL); } var applicationId = _CoreManager2.default.get('APPLICATION_ID'); var javascriptKey = _CoreManager2.default.get('JAVASCRIPT_KEY'); var masterKey = _CoreManager2.default.get('MASTER_KEY'); // Get currentUser sessionToken if possible defaultLiveQueryClient = new _LiveQueryClient2.default({ applicationId: applicationId, serverURL: liveQueryServerURL, javascriptKey: javascriptKey, masterKey: masterKey, sessionToken: sessionToken }); // Register a default onError callback to make sure we do not crash on error // Cannot create these events on a nested way because of EventEmiiter from React Native defaultLiveQueryClient.on('error', function (error) { LiveQuery.emit('error', error); }); defaultLiveQueryClient.on('open', function () { LiveQuery.emit('open'); }); defaultLiveQueryClient.on('close', function () { LiveQuery.emit('close'); }); return defaultLiveQueryClient; }); }, open: function () { var _this = this; getLiveQueryClient().then(function (liveQueryClient) { _this.resolve(liveQueryClient.open()); }); }, close: function () { var _this2 = this; getLiveQueryClient().then(function (liveQueryClient) { _this2.resolve(liveQueryClient.close()); }); }, subscribe: function (query) { var _this3 = this; var subscriptionWrap = new _EventEmitter2.default(); getLiveQueryClient().then(function (liveQueryClient) { if (liveQueryClient.shouldOpen()) { liveQueryClient.open(); } var promiseSessionToken = getSessionToken(); // new event emitter return promiseSessionToken.then(function (sessionToken) { var subscription = liveQueryClient.subscribe(query, sessionToken); // enter, leave create, etc subscriptionWrap.id = subscription.id; subscriptionWrap.query = subscription.query; subscriptionWrap.sessionToken = subscription.sessionToken; subscriptionWrap.unsubscribe = subscription.unsubscribe; // Cannot create these events on a nested way because of EventEmiiter from React Native subscription.on('open', function () { subscriptionWrap.emit('open'); }); subscription.on('create', function (object) { subscriptionWrap.emit('create', object); }); subscription.on('update', function (object) { subscriptionWrap.emit('update', object); }); subscription.on('enter', function (object) { subscriptionWrap.emit('enter', object); }); subscription.on('leave', function (object) { subscriptionWrap.emit('leave', object); }); subscription.on('delete', function (object) { subscriptionWrap.emit('delete', object); }); subscription.on('close', function (object) { subscriptionWrap.emit('close', object); }); subscription.on('error', function (object) { subscriptionWrap.emit('error', object); }); _this3.resolve(); }); }); return subscriptionWrap; }, unsubscribe: function (subscription) { var _this4 = this; getLiveQueryClient().then(function (liveQueryClient) { _this4.resolve(liveQueryClient.unsubscribe(subscription)); }); }, _clearCachedDefaultClient: function () { defaultLiveQueryClient = null; } }; _CoreManager2.default.setLiveQueryController(DefaultLiveQueryController); },{"./CoreManager":3,"./EventEmitter":4,"./LiveQueryClient":7,"./ParsePromise":21}],18:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _defineProperty = _dereq_('babel-runtime/core-js/object/define-property'); var _defineProperty2 = _interopRequireDefault(_defineProperty); var _create = _dereq_('babel-runtime/core-js/object/create'); var _create2 = _interopRequireDefault(_create); var _freeze = _dereq_('babel-runtime/core-js/object/freeze'); var _freeze2 = _interopRequireDefault(_freeze); var _stringify = _dereq_('babel-runtime/core-js/json/stringify'); var _stringify2 = _interopRequireDefault(_stringify); var _keys = _dereq_('babel-runtime/core-js/object/keys'); var _keys2 = _interopRequireDefault(_keys); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _CoreManager = _dereq_('./CoreManager'); var _CoreManager2 = _interopRequireDefault(_CoreManager); var _canBeSerialized = _dereq_('./canBeSerialized'); var _canBeSerialized2 = _interopRequireDefault(_canBeSerialized); var _decode = _dereq_('./decode'); var _decode2 = _interopRequireDefault(_decode); var _encode = _dereq_('./encode'); var _encode2 = _interopRequireDefault(_encode); var _equals = _dereq_('./equals'); var _equals2 = _interopRequireDefault(_equals); var _escape2 = _dereq_('./escape'); var _escape3 = _interopRequireDefault(_escape2); var _ParseACL = _dereq_('./ParseACL'); var _ParseACL2 = _interopRequireDefault(_ParseACL); var _parseDate = _dereq_('./parseDate'); var _parseDate2 = _interopRequireDefault(_parseDate); var _ParseError = _dereq_('./ParseError'); var _ParseError2 = _interopRequireDefault(_ParseError); var _ParseFile = _dereq_('./ParseFile'); var _ParseFile2 = _interopRequireDefault(_ParseFile); var _ParseOp = _dereq_('./ParseOp'); var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); var _ParseQuery = _dereq_('./ParseQuery'); var _ParseQuery2 = _interopRequireDefault(_ParseQuery); var _ParseRelation = _dereq_('./ParseRelation'); var _ParseRelation2 = _interopRequireDefault(_ParseRelation); var _SingleInstanceStateController = _dereq_('./SingleInstanceStateController'); var SingleInstanceStateController = _interopRequireWildcard(_SingleInstanceStateController); var _unique = _dereq_('./unique'); var _unique2 = _interopRequireDefault(_unique); var _UniqueInstanceStateController = _dereq_('./UniqueInstanceStateController'); var UniqueInstanceStateController = _interopRequireWildcard(_UniqueInstanceStateController); var _unsavedChildren = _dereq_('./unsavedChildren'); var _unsavedChildren2 = _interopRequireDefault(_unsavedChildren); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Mapping of class names to constructors, so we can populate objects from the // server with appropriate subclasses of ParseObject /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var classMap = {}; // Global counter for generating unique local Ids var localCount = 0; // Global counter for generating unique Ids for non-single-instance objects var objectCount = 0; // On web clients, objects are single-instance: any two objects with the same Id // will have the same attributes. However, this may be dangerous default // behavior in a server scenario var singleInstance = !_CoreManager2.default.get('IS_NODE'); if (singleInstance) { _CoreManager2.default.setObjectStateController(SingleInstanceStateController); } else { _CoreManager2.default.setObjectStateController(UniqueInstanceStateController); } function getServerUrlPath() { var serverUrl = _CoreManager2.default.get('SERVER_URL'); if (serverUrl[serverUrl.length - 1] !== '/') { serverUrl += '/'; } var url = serverUrl.replace(/https?:\/\//, ''); return url.substr(url.indexOf('/')); } /** * Creates a new model with defined attributes. * * <p>You won't normally call this method directly. It is recommended that * you use a subclass of <code>Parse.Object</code> instead, created by calling * <code>extend</code>.</p> * * <p>However, if you don't want to use a subclass, or aren't sure which * subclass is appropriate, you can use this form:<pre> * var object = new Parse.Object("ClassName"); * </pre> * That is basically equivalent to:<pre> * var MyClass = Parse.Object.extend("ClassName"); * var object = new MyClass(); * </pre></p> * * @class Parse.Object * @constructor * @param {String} className The class name for the object * @param {Object} attributes The initial set of data to store in the object. * @param {Object} options The options for this object instance. */ var ParseObject = function () { /** * The ID of this object, unique within its class. * @property id * @type String */ function ParseObject(className, attributes, options) { (0, _classCallCheck3.default)(this, ParseObject); // Enable legacy initializers if (typeof this.initialize === 'function') { this.initialize.apply(this, arguments); } var toSet = null; this._objCount = objectCount++; if (typeof className === 'string') { this.className = className; if (attributes && (typeof attributes === 'undefined' ? 'undefined' : (0, _typeof3.default)(attributes)) === 'object') { toSet = attributes; } } else if (className && (typeof className === 'undefined' ? 'undefined' : (0, _typeof3.default)(className)) === 'object') { this.className = className.className; toSet = {}; for (var attr in className) { if (attr !== 'className') { toSet[attr] = className[attr]; } } if (attributes && (typeof attributes === 'undefined' ? 'undefined' : (0, _typeof3.default)(attributes)) === 'object') { options = attributes; } } if (toSet && !this.set(toSet, options)) { throw new Error('Can\'t create an invalid Parse Object'); } } /** Prototype getters / setters **/ (0, _createClass3.default)(ParseObject, [{ key: '_getId', /** Private methods **/ /** * Returns a local or server Id used uniquely identify this object */ value: function () { if (typeof this.id === 'string') { return this.id; } if (typeof this._localId === 'string') { return this._localId; } var localId = 'local' + String(localCount++); this._localId = localId; return localId; } /** * Returns a unique identifier used to pull data from the State Controller. */ }, { key: '_getStateIdentifier', value: function () { if (singleInstance) { var _id = this.id; if (!_id) { _id = this._getId(); } return { id: _id, className: this.className }; } else { return this; } } }, { key: '_getServerData', value: function () { var stateController = _CoreManager2.default.getObjectStateController(); return stateController.getServerData(this._getStateIdentifier()); } }, { key: '_clearServerData', value: function () { var serverData = this._getServerData(); var unset = {}; for (var attr in serverData) { unset[attr] = undefined; } var stateController = _CoreManager2.default.getObjectStateController(); stateController.setServerData(this._getStateIdentifier(), unset); } }, { key: '_getPendingOps', value: function () { var stateController = _CoreManager2.default.getObjectStateController(); return stateController.getPendingOps(this._getStateIdentifier()); } }, { key: '_clearPendingOps', value: function () { var pending = this._getPendingOps(); var latest = pending[pending.length - 1]; var keys = (0, _keys2.default)(latest); keys.forEach(function (key) { delete latest[key]; }); } }, { key: '_getDirtyObjectAttributes', value: function () { var attributes = this.attributes; var stateController = _CoreManager2.default.getObjectStateController(); var objectCache = stateController.getObjectCache(this._getStateIdentifier()); var dirty = {}; for (var attr in attributes) { var val = attributes[attr]; if (val && (typeof val === 'undefined' ? 'undefined' : (0, _typeof3.default)(val)) === 'object' && !(val instanceof ParseObject) && !(val instanceof _ParseFile2.default) && !(val instanceof _ParseRelation2.default)) { // Due to the way browsers construct maps, the key order will not change // unless the object is changed try { var json = (0, _encode2.default)(val, false, true); var stringified = (0, _stringify2.default)(json); if (objectCache[attr] !== stringified) { dirty[attr] = val; } } catch (e) { // Error occurred, possibly by a nested unsaved pointer in a mutable container // No matter how it happened, it indicates a change in the attribute dirty[attr] = val; } } } return dirty; } }, { key: '_toFullJSON', value: function (seen) { var json = this.toJSON(seen); json.__type = 'Object'; json.className = this.className; return json; } }, { key: '_getSaveJSON', value: function () { var pending = this._getPendingOps(); var dirtyObjects = this._getDirtyObjectAttributes(); var json = {}; for (var attr in dirtyObjects) { json[attr] = new _ParseOp.SetOp(dirtyObjects[attr]).toJSON(); } for (attr in pending[0]) { json[attr] = pending[0][attr].toJSON(); } return json; } }, { key: '_getSaveParams', value: function () { var method = this.id ? 'PUT' : 'POST'; var body = this._getSaveJSON(); var path = 'classes/' + this.className; if (this.id) { path += '/' + this.id; } else if (this.className === '_User') { path = 'users'; } return { method: method, body: body, path: path }; } }, { key: '_finishFetch', value: function (serverData) { if (!this.id && serverData.objectId) { this.id = serverData.objectId; } var stateController = _CoreManager2.default.getObjectStateController(); stateController.initializeState(this._getStateIdentifier()); var decoded = {}; for (var attr in serverData) { if (attr === 'ACL') { decoded[attr] = new _ParseACL2.default(serverData[attr]); } else if (attr !== 'objectId') { decoded[attr] = (0, _decode2.default)(serverData[attr]); if (decoded[attr] instanceof _ParseRelation2.default) { decoded[attr]._ensureParentAndKey(this, attr); } } } if (decoded.createdAt && typeof decoded.createdAt === 'string') { decoded.createdAt = (0, _parseDate2.default)(decoded.createdAt); } if (decoded.updatedAt && typeof decoded.updatedAt === 'string') { decoded.updatedAt = (0, _parseDate2.default)(decoded.updatedAt); } if (!decoded.updatedAt && decoded.createdAt) { decoded.updatedAt = decoded.createdAt; } stateController.commitServerChanges(this._getStateIdentifier(), decoded); } }, { key: '_setExisted', value: function (existed) { var stateController = _CoreManager2.default.getObjectStateController(); var state = stateController.getState(this._getStateIdentifier()); if (state) { state.existed = existed; } } }, { key: '_migrateId', value: function (serverId) { if (this._localId && serverId) { if (singleInstance) { var stateController = _CoreManager2.default.getObjectStateController(); var oldState = stateController.removeState(this._getStateIdentifier()); this.id = serverId; delete this._localId; if (oldState) { stateController.initializeState(this._getStateIdentifier(), oldState); } } else { this.id = serverId; delete this._localId; } } } }, { key: '_handleSaveResponse', value: function (response, status) { var changes = {}; var stateController = _CoreManager2.default.getObjectStateController(); var pending = stateController.popPendingState(this._getStateIdentifier()); for (var attr in pending) { if (pending[attr] instanceof _ParseOp.RelationOp) { changes[attr] = pending[attr].applyTo(undefined, this, attr); } else if (!(attr in response)) { // Only SetOps and UnsetOps should not come back with results changes[attr] = pending[attr].applyTo(undefined); } } for (attr in response) { if ((attr === 'createdAt' || attr === 'updatedAt') && typeof response[attr] === 'string') { changes[attr] = (0, _parseDate2.default)(response[attr]); } else if (attr === 'ACL') { changes[attr] = new _ParseACL2.default(response[attr]); } else if (attr !== 'objectId') { changes[attr] = (0, _decode2.default)(response[attr]); if (changes[attr] instanceof _ParseOp.UnsetOp) { changes[attr] = undefined; } } } if (changes.createdAt && !changes.updatedAt) { changes.updatedAt = changes.createdAt; } this._migrateId(response.objectId); if (status !== 201) { this._setExisted(true); } stateController.commitServerChanges(this._getStateIdentifier(), changes); } }, { key: '_handleSaveError', value: function () { this._getPendingOps(); var stateController = _CoreManager2.default.getObjectStateController(); stateController.mergeFirstPendingState(this._getStateIdentifier()); } /** Public methods **/ }, { key: 'initialize', value: function () {} // NOOP /** * Returns a JSON version of the object suitable for saving to Parse. * @method toJSON * @return {Object} */ }, { key: 'toJSON', value: function (seen) { var seenEntry = this.id ? this.className + ':' + this.id : this; var seen = seen || [seenEntry]; var json = {}; var attrs = this.attributes; for (var attr in attrs) { if ((attr === 'createdAt' || attr === 'updatedAt') && attrs[attr].toJSON) { json[attr] = attrs[attr].toJSON(); } else { json[attr] = (0, _encode2.default)(attrs[attr], false, false, seen); } } var pending = this._getPendingOps(); for (var attr in pending[0]) { json[attr] = pending[0][attr].toJSON(); } if (this.id) { json.objectId = this.id; } return json; } /** * Determines whether this ParseObject is equal to another ParseObject * @method equals * @return {Boolean} */ }, { key: 'equals', value: function (other) { if (this === other) { return true; } return other instanceof ParseObject && this.className === other.className && this.id === other.id && typeof this.id !== 'undefined'; } /** * Returns true if this object has been modified since its last * save/refresh. If an attribute is specified, it returns true only if that * particular attribute has been modified since the last save/refresh. * @method dirty * @param {String} attr An attribute name (optional). * @return {Boolean} */ }, { key: 'dirty', value: function (attr) { if (!this.id) { return true; } var pendingOps = this._getPendingOps(); var dirtyObjects = this._getDirtyObjectAttributes(); if (attr) { if (dirtyObjects.hasOwnProperty(attr)) { return true; } for (var i = 0; i < pendingOps.length; i++) { if (pendingOps[i].hasOwnProperty(attr)) { return true; } } return false; } if ((0, _keys2.default)(pendingOps[0]).length !== 0) { return true; } if ((0, _keys2.default)(dirtyObjects).length !== 0) { return true; } return false; } /** * Returns an array of keys that have been modified since last save/refresh * @method dirtyKeys * @return {Array of string} */ }, { key: 'dirtyKeys', value: function () { var pendingOps = this._getPendingOps(); var keys = {}; for (var i = 0; i < pendingOps.length; i++) { for (var attr in pendingOps[i]) { keys[attr] = true; } } var dirtyObjects = this._getDirtyObjectAttributes(); for (var attr in dirtyObjects) { keys[attr] = true; } return (0, _keys2.default)(keys); } /** * Gets a Pointer referencing this Object. * @method toPointer * @return {Object} */ }, { key: 'toPointer', value: function () { if (!this.id) { throw new Error('Cannot create a pointer to an unsaved ParseObject'); } return { __type: 'Pointer', className: this.className, objectId: this.id }; } /** * Gets the value of an attribute. * @method get * @param {String} attr The string name of an attribute. */ }, { key: 'get', value: function (attr) { return this.attributes[attr]; } /** * Gets a relation on the given class for the attribute. * @method relation * @param String attr The attribute to get the relation for. */ }, { key: 'relation', value: function (attr) { var value = this.get(attr); if (value) { if (!(value instanceof _ParseRelation2.default)) { throw new Error('Called relation() on non-relation field ' + attr); } value._ensureParentAndKey(this, attr); return value; } return new _ParseRelation2.default(this, attr); } /** * Gets the HTML-escaped value of an attribute. * @method escape * @param {String} attr The string name of an attribute. */ }, { key: 'escape', value: function (attr) { var val = this.attributes[attr]; if (val == null) { return ''; } if (typeof val !== 'string') { if (typeof val.toString !== 'function') { return ''; } val = val.toString(); } return (0, _escape3.default)(val); } /** * Returns <code>true</code> if the attribute contains a value that is not * null or undefined. * @method has * @param {String} attr The string name of the attribute. * @return {Boolean} */ }, { key: 'has', value: function (attr) { var attributes = this.attributes; if (attributes.hasOwnProperty(attr)) { return attributes[attr] != null; } return false; } /** * Sets a hash of model attributes on the object. * * <p>You can call it with an object containing keys and values, or with one * key and value. For example:<pre> * gameTurn.set({ * player: player1, * diceRoll: 2 * }, { * error: function(gameTurnAgain, error) { * // The set failed validation. * } * }); * * game.set("currentPlayer", player2, { * error: function(gameTurnAgain, error) { * // The set failed validation. * } * }); * * game.set("finished", true);</pre></p> * * @method set * @param {String} key The key to set. * @param {} value The value to give it. * @param {Object} options A set of options for the set. * The only supported option is <code>error</code>. * @return {Boolean} true if the set succeeded. */ }, { key: 'set', value: function (key, value, options) { var changes = {}; var newOps = {}; if (key && (typeof key === 'undefined' ? 'undefined' : (0, _typeof3.default)(key)) === 'object') { changes = key; options = value; } else if (typeof key === 'string') { changes[key] = value; } else { return this; } options = options || {}; var readonly = []; if (typeof this.constructor.readOnlyAttributes === 'function') { readonly = readonly.concat(this.constructor.readOnlyAttributes()); } for (var k in changes) { if (k === 'createdAt' || k === 'updatedAt') { // This property is read-only, but for legacy reasons we silently // ignore it continue; } if (readonly.indexOf(k) > -1) { throw new Error('Cannot modify readonly attribute: ' + k); } if (options.unset) { newOps[k] = new _ParseOp.UnsetOp(); } else if (changes[k] instanceof _ParseOp.Op) { newOps[k] = changes[k]; } else if (changes[k] && (0, _typeof3.default)(changes[k]) === 'object' && typeof changes[k].__op === 'string') { newOps[k] = (0, _ParseOp.opFromJSON)(changes[k]); } else if (k === 'objectId' || k === 'id') { if (typeof changes[k] === 'string') { this.id = changes[k]; } } else if (k === 'ACL' && (0, _typeof3.default)(changes[k]) === 'object' && !(changes[k] instanceof _ParseACL2.default)) { newOps[k] = new _ParseOp.SetOp(new _ParseACL2.default(changes[k])); } else { newOps[k] = new _ParseOp.SetOp(changes[k]); } } // Calculate new values var currentAttributes = this.attributes; var newValues = {}; for (var attr in newOps) { if (newOps[attr] instanceof _ParseOp.RelationOp) { newValues[attr] = newOps[attr].applyTo(currentAttributes[attr], this, attr); } else if (!(newOps[attr] instanceof _ParseOp.UnsetOp)) { newValues[attr] = newOps[attr].applyTo(currentAttributes[attr]); } } // Validate changes if (!options.ignoreValidation) { var validation = this.validate(newValues); if (validation) { if (typeof options.error === 'function') { options.error(this, validation); } return false; } } // Consolidate Ops var pendingOps = this._getPendingOps(); var last = pendingOps.length - 1; var stateController = _CoreManager2.default.getObjectStateController(); for (var attr in newOps) { var nextOp = newOps[attr].mergeWith(pendingOps[last][attr]); stateController.setPendingOp(this._getStateIdentifier(), attr, nextOp); } return this; } /** * Remove an attribute from the model. This is a noop if the attribute doesn't * exist. * @method unset * @param {String} attr The string name of an attribute. */ }, { key: 'unset', value: function (attr, options) { options = options || {}; options.unset = true; return this.set(attr, null, options); } /** * Atomically increments the value of the given attribute the next time the * object is saved. If no amount is specified, 1 is used by default. * * @method increment * @param attr {String} The key. * @param amount {Number} The amount to increment by (optional). */ }, { key: 'increment', value: function (attr, amount) { if (typeof amount === 'undefined') { amount = 1; } if (typeof amount !== 'number') { throw new Error('Cannot increment by a non-numeric amount.'); } return this.set(attr, new _ParseOp.IncrementOp(amount)); } /** * Atomically add an object to the end of the array associated with a given * key. * @method add * @param attr {String} The key. * @param item {} The item to add. */ }, { key: 'add', value: function (attr, item) { return this.set(attr, new _ParseOp.AddOp([item])); } /** * Atomically add the objects to the end of the array associated with a given * key. * @method addAll * @param attr {String} The key. * @param items {[]} The items to add. */ }, { key: 'addAll', value: function (attr, items) { return this.set(attr, new _ParseOp.AddOp(items)); } /** * Atomically add an object to the array associated with a given key, only * if it is not already present in the array. The position of the insert is * not guaranteed. * * @method addUnique * @param attr {String} The key. * @param item {} The object to add. */ }, { key: 'addUnique', value: function (attr, item) { return this.set(attr, new _ParseOp.AddUniqueOp([item])); } /** * Atomically add the objects to the array associated with a given key, only * if it is not already present in the array. The position of the insert is * not guaranteed. * * @method addAllUnique * @param attr {String} The key. * @param items {[]} The objects to add. */ }, { key: 'addAllUnique', value: function (attr, items) { return this.set(attr, new _ParseOp.AddUniqueOp(items)); } /** * Atomically remove all instances of an object from the array associated * with a given key. * * @method remove * @param attr {String} The key. * @param item {} The object to remove. */ }, { key: 'remove', value: function (attr, item) { return this.set(attr, new _ParseOp.RemoveOp([item])); } /** * Atomically remove all instances of the objects from the array associated * with a given key. * * @method removeAll * @param attr {String} The key. * @param items {[]} The object to remove. */ }, { key: 'removeAll', value: function (attr, items) { return this.set(attr, new _ParseOp.RemoveOp(items)); } /** * Returns an instance of a subclass of Parse.Op describing what kind of * modification has been performed on this field since the last time it was * saved. For example, after calling object.increment("x"), calling * object.op("x") would return an instance of Parse.Op.Increment. * * @method op * @param attr {String} The key. * @returns {Parse.Op} The operation, or undefined if none. */ }, { key: 'op', value: function (attr) { var pending = this._getPendingOps(); for (var i = pending.length; i--;) { if (pending[i][attr]) { return pending[i][attr]; } } } /** * Creates a new model with identical attributes to this one, similar to Backbone.Model's clone() * @method clone * @return {Parse.Object} */ }, { key: 'clone', value: function () { var clone = new this.constructor(); if (!clone.className) { clone.className = this.className; } var attributes = this.attributes; if (typeof this.constructor.readOnlyAttributes === 'function') { var readonly = this.constructor.readOnlyAttributes() || []; // Attributes are frozen, so we have to rebuild an object, // rather than delete readonly keys var copy = {}; for (var a in attributes) { if (readonly.indexOf(a) < 0) { copy[a] = attributes[a]; } } attributes = copy; } if (clone.set) { clone.set(attributes); } return clone; } /** * Creates a new instance of this object. Not to be confused with clone() * @method newInstance * @return {Parse.Object} */ }, { key: 'newInstance', value: function () { var clone = new this.constructor(); if (!clone.className) { clone.className = this.className; } clone.id = this.id; if (singleInstance) { // Just return an object with the right id return clone; } var stateController = _CoreManager2.default.getObjectStateController(); if (stateController) { stateController.duplicateState(this._getStateIdentifier(), clone._getStateIdentifier()); } return clone; } /** * Returns true if this object has never been saved to Parse. * @method isNew * @return {Boolean} */ }, { key: 'isNew', value: function () { return !this.id; } /** * Returns true if this object was created by the Parse server when the * object might have already been there (e.g. in the case of a Facebook * login) * @method existed * @return {Boolean} */ }, { key: 'existed', value: function () { if (!this.id) { return false; } var stateController = _CoreManager2.default.getObjectStateController(); var state = stateController.getState(this._getStateIdentifier()); if (state) { return state.existed; } return false; } /** * Checks if the model is currently in a valid state. * @method isValid * @return {Boolean} */ }, { key: 'isValid', value: function () { return !this.validate(this.attributes); } /** * You should not call this function directly unless you subclass * <code>Parse.Object</code>, in which case you can override this method * to provide additional validation on <code>set</code> and * <code>save</code>. Your implementation should return * * @method validate * @param {Object} attrs The current data to validate. * @return {} False if the data is valid. An error object otherwise. * @see Parse.Object#set */ }, { key: 'validate', value: function (attrs) { if (attrs.hasOwnProperty('ACL') && !(attrs.ACL instanceof _ParseACL2.default)) { return new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'ACL must be a Parse ACL.'); } for (var key in attrs) { if (!/^[A-Za-z][0-9A-Za-z_]*$/.test(key)) { return new _ParseError2.default(_ParseError2.default.INVALID_KEY_NAME); } } return false; } /** * Returns the ACL for this object. * @method getACL * @returns {Parse.ACL} An instance of Parse.ACL. * @see Parse.Object#get */ }, { key: 'getACL', value: function () { var acl = this.get('ACL'); if (acl instanceof _ParseACL2.default) { return acl; } return null; } /** * Sets the ACL to be used for this object. * @method setACL * @param {Parse.ACL} acl An instance of Parse.ACL. * @param {Object} options Optional Backbone-like options object to be * passed in to set. * @return {Boolean} Whether the set passed validation. * @see Parse.Object#set */ }, { key: 'setACL', value: function (acl, options) { return this.set('ACL', acl, options); } /** * Clears any changes to this object made since the last call to save() * @method revert */ }, { key: 'revert', value: function () { this._clearPendingOps(); } /** * Clears all attributes on a model * @method clear */ }, { key: 'clear', value: function () { var attributes = this.attributes; var erasable = {}; var readonly = ['createdAt', 'updatedAt']; if (typeof this.constructor.readOnlyAttributes === 'function') { readonly = readonly.concat(this.constructor.readOnlyAttributes()); } for (var attr in attributes) { if (readonly.indexOf(attr) < 0) { erasable[attr] = true; } } return this.set(erasable, { unset: true }); } /** * Fetch the model from the server. If the server's representation of the * model differs from its current attributes, they will be overriden. * * @method fetch * @param {Object} options A Backbone-style callback object. * Valid options are:<ul> * <li>success: A Backbone-style success callback. * <li>error: An Backbone-style error callback. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to * be used for this request. * <li>sessionToken: A valid session token, used for making a request on * behalf of a specific user. * </ul> * @return {Parse.Promise} A promise that is fulfilled when the fetch * completes. */ }, { key: 'fetch', value: function (options) { options = options || {}; var fetchOptions = {}; if (options.hasOwnProperty('useMasterKey')) { fetchOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('sessionToken')) { fetchOptions.sessionToken = options.sessionToken; } var controller = _CoreManager2.default.getObjectController(); return controller.fetch(this, true, fetchOptions)._thenRunCallbacks(options); } /** * Set a hash of model attributes, and save the model to the server. * updatedAt will be updated when the request returns. * You can either call it as:<pre> * object.save();</pre> * or<pre> * object.save(null, options);</pre> * or<pre> * object.save(attrs, options);</pre> * or<pre> * object.save(key, value, options);</pre> * * For example, <pre> * gameTurn.save({ * player: "Jake Cutter", * diceRoll: 2 * }, { * success: function(gameTurnAgain) { * // The save was successful. * }, * error: function(gameTurnAgain, error) { * // The save failed. Error is an instance of Parse.Error. * } * });</pre> * or with promises:<pre> * gameTurn.save({ * player: "Jake Cutter", * diceRoll: 2 * }).then(function(gameTurnAgain) { * // The save was successful. * }, function(error) { * // The save failed. Error is an instance of Parse.Error. * });</pre> * * @method save * @param {Object} options A Backbone-style callback object. * Valid options are:<ul> * <li>success: A Backbone-style success callback. * <li>error: An Backbone-style error callback. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to * be used for this request. * <li>sessionToken: A valid session token, used for making a request on * behalf of a specific user. * </ul> * @return {Parse.Promise} A promise that is fulfilled when the save * completes. */ }, { key: 'save', value: function (arg1, arg2, arg3) { var _this = this; var attrs; var options; if ((typeof arg1 === 'undefined' ? 'undefined' : (0, _typeof3.default)(arg1)) === 'object' || typeof arg1 === 'undefined') { attrs = arg1; if ((typeof arg2 === 'undefined' ? 'undefined' : (0, _typeof3.default)(arg2)) === 'object') { options = arg2; } } else { attrs = {}; attrs[arg1] = arg2; options = arg3; } // Support save({ success: function() {}, error: function() {} }) if (!options && attrs) { options = {}; if (typeof attrs.success === 'function') { options.success = attrs.success; delete attrs.success; } if (typeof attrs.error === 'function') { options.error = attrs.error; delete attrs.error; } } if (attrs) { var validation = this.validate(attrs); if (validation) { if (options && typeof options.error === 'function') { options.error(this, validation); } return _ParsePromise2.default.error(validation); } this.set(attrs, options); } options = options || {}; var saveOptions = {}; if (options.hasOwnProperty('useMasterKey')) { saveOptions.useMasterKey = !!options.useMasterKey; } if (options.hasOwnProperty('sessionToken') && typeof options.sessionToken === 'string') { saveOptions.sessionToken = options.sessionToken; } var controller = _CoreManager2.default.getObjectController(); var unsaved = (0, _unsavedChildren2.default)(this); return controller.save(unsaved, saveOptions).then(function () { return controller.save(_this, saveOptions); })._thenRunCallbacks(options, this); } /** * Destroy this model on the server if it was already persisted. * If `wait: true` is passed, waits for the server to respond * before removal. * * @method destroy * @param {Object} options A Backbone-style callback object. * Valid options are:<ul> * <li>success: A Backbone-style success callback * <li>error: An Backbone-style error callback. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to * be used for this request. * <li>sessionToken: A valid session token, used for making a request on * behalf of a specific user. * </ul> * @return {Parse.Promise} A promise that is fulfilled when the destroy * completes. */ }, { key: 'destroy', value: function (options) { options = options || {}; var destroyOptions = {}; if (options.hasOwnProperty('useMasterKey')) { destroyOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('sessionToken')) { destroyOptions.sessionToken = options.sessionToken; } if (!this.id) { return _ParsePromise2.default.as()._thenRunCallbacks(options); } return _CoreManager2.default.getObjectController().destroy(this, destroyOptions)._thenRunCallbacks(options); } /** Static methods **/ }, { key: 'attributes', get: function () { var stateController = _CoreManager2.default.getObjectStateController(); return (0, _freeze2.default)(stateController.estimateAttributes(this._getStateIdentifier())); } /** * The first time this object was saved on the server. * @property createdAt * @type Date */ }, { key: 'createdAt', get: function () { return this._getServerData().createdAt; } /** * The last time this object was updated on the server. * @property updatedAt * @type Date */ }, { key: 'updatedAt', get: function () { return this._getServerData().updatedAt; } }], [{ key: '_clearAllState', value: function () { var stateController = _CoreManager2.default.getObjectStateController(); stateController.clearAllState(); } /** * Fetches the given list of Parse.Object. * If any error is encountered, stops and calls the error handler. * * <pre> * Parse.Object.fetchAll([object1, object2, ...], { * success: function(list) { * // All the objects were fetched. * }, * error: function(error) { * // An error occurred while fetching one of the objects. * }, * }); * </pre> * * @method fetchAll * @param {Array} list A list of <code>Parse.Object</code>. * @param {Object} options A Backbone-style callback object. * @static * Valid options are:<ul> * <li>success: A Backbone-style success callback. * <li>error: An Backbone-style error callback. * </ul> */ }, { key: 'fetchAll', value: function (list, options) { var options = options || {}; var queryOptions = {}; if (options.hasOwnProperty('useMasterKey')) { queryOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('sessionToken')) { queryOptions.sessionToken = options.sessionToken; } return _CoreManager2.default.getObjectController().fetch(list, true, queryOptions)._thenRunCallbacks(options); } /** * Fetches the given list of Parse.Object if needed. * If any error is encountered, stops and calls the error handler. * * <pre> * Parse.Object.fetchAllIfNeeded([object1, ...], { * success: function(list) { * // Objects were fetched and updated. * }, * error: function(error) { * // An error occurred while fetching one of the objects. * }, * }); * </pre> * * @method fetchAllIfNeeded * @param {Array} list A list of <code>Parse.Object</code>. * @param {Object} options A Backbone-style callback object. * @static * Valid options are:<ul> * <li>success: A Backbone-style success callback. * <li>error: An Backbone-style error callback. * </ul> */ }, { key: 'fetchAllIfNeeded', value: function (list, options) { var options = options || {}; var queryOptions = {}; if (options.hasOwnProperty('useMasterKey')) { queryOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('sessionToken')) { queryOptions.sessionToken = options.sessionToken; } return _CoreManager2.default.getObjectController().fetch(list, false, queryOptions)._thenRunCallbacks(options); } /** * Destroy the given list of models on the server if it was already persisted. * * <p>Unlike saveAll, if an error occurs while deleting an individual model, * this method will continue trying to delete the rest of the models if * possible, except in the case of a fatal error like a connection error. * * <p>In particular, the Parse.Error object returned in the case of error may * be one of two types: * * <ul> * <li>A Parse.Error.AGGREGATE_ERROR. This object's "errors" property is an * array of other Parse.Error objects. Each error object in this array * has an "object" property that references the object that could not be * deleted (for instance, because that object could not be found).</li> * <li>A non-aggregate Parse.Error. This indicates a serious error that * caused the delete operation to be aborted partway through (for * instance, a connection failure in the middle of the delete).</li> * </ul> * * <pre> * Parse.Object.destroyAll([object1, object2, ...], { * success: function() { * // All the objects were deleted. * }, * error: function(error) { * // An error occurred while deleting one or more of the objects. * // If this is an aggregate error, then we can inspect each error * // object individually to determine the reason why a particular * // object was not deleted. * if (error.code === Parse.Error.AGGREGATE_ERROR) { * for (var i = 0; i < error.errors.length; i++) { * console.log("Couldn't delete " + error.errors[i].object.id + * "due to " + error.errors[i].message); * } * } else { * console.log("Delete aborted because of " + error.message); * } * }, * }); * </pre> * * @method destroyAll * @param {Array} list A list of <code>Parse.Object</code>. * @param {Object} options A Backbone-style callback object. * @static * Valid options are:<ul> * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to * be used for this request. * <li>sessionToken: A valid session token, used for making a request on * behalf of a specific user. * </ul> * @return {Parse.Promise} A promise that is fulfilled when the destroyAll * completes. */ }, { key: 'destroyAll', value: function (list, options) { var options = options || {}; var destroyOptions = {}; if (options.hasOwnProperty('useMasterKey')) { destroyOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('sessionToken')) { destroyOptions.sessionToken = options.sessionToken; } return _CoreManager2.default.getObjectController().destroy(list, destroyOptions)._thenRunCallbacks(options); } /** * Saves the given list of Parse.Object. * If any error is encountered, stops and calls the error handler. * * <pre> * Parse.Object.saveAll([object1, object2, ...], { * success: function(list) { * // All the objects were saved. * }, * error: function(error) { * // An error occurred while saving one of the objects. * }, * }); * </pre> * * @method saveAll * @param {Array} list A list of <code>Parse.Object</code>. * @param {Object} options A Backbone-style callback object. * @static * Valid options are:<ul> * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to * be used for this request. * <li>sessionToken: A valid session token, used for making a request on * behalf of a specific user. * </ul> */ }, { key: 'saveAll', value: function (list, options) { var options = options || {}; var saveOptions = {}; if (options.hasOwnProperty('useMasterKey')) { saveOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('sessionToken')) { saveOptions.sessionToken = options.sessionToken; } return _CoreManager2.default.getObjectController().save(list, saveOptions)._thenRunCallbacks(options); } /** * Creates a reference to a subclass of Parse.Object with the given id. This * does not exist on Parse.Object, only on subclasses. * * <p>A shortcut for: <pre> * var Foo = Parse.Object.extend("Foo"); * var pointerToFoo = new Foo(); * pointerToFoo.id = "myObjectId"; * </pre> * * @method createWithoutData * @param {String} id The ID of the object to create a reference to. * @static * @return {Parse.Object} A Parse.Object reference. */ }, { key: 'createWithoutData', value: function (id) { var obj = new this(); obj.id = id; return obj; } /** * Creates a new instance of a Parse Object from a JSON representation. * @method fromJSON * @param {Object} json The JSON map of the Object's data * @param {boolean} override In single instance mode, all old server data * is overwritten if this is set to true * @static * @return {Parse.Object} A Parse.Object reference */ }, { key: 'fromJSON', value: function (json, override) { if (!json.className) { throw new Error('Cannot create an object without a className'); } var constructor = classMap[json.className]; var o = constructor ? new constructor() : new ParseObject(json.className); var otherAttributes = {}; for (var attr in json) { if (attr !== 'className' && attr !== '__type') { otherAttributes[attr] = json[attr]; } } if (override) { // id needs to be set before clearServerData can work if (otherAttributes.objectId) { o.id = otherAttributes.objectId; } var preserved = null; if (typeof o._preserveFieldsOnFetch === 'function') { preserved = o._preserveFieldsOnFetch(); } o._clearServerData(); if (preserved) { o._finishFetch(preserved); } } o._finishFetch(otherAttributes); if (json.objectId) { o._setExisted(true); } return o; } /** * Registers a subclass of Parse.Object with a specific class name. * When objects of that class are retrieved from a query, they will be * instantiated with this subclass. * This is only necessary when using ES6 subclassing. * @method registerSubclass * @param {String} className The class name of the subclass * @param {Class} constructor The subclass */ }, { key: 'registerSubclass', value: function (className, constructor) { if (typeof className !== 'string') { throw new TypeError('The first argument must be a valid class name.'); } if (typeof constructor === 'undefined') { throw new TypeError('You must supply a subclass constructor.'); } if (typeof constructor !== 'function') { throw new TypeError('You must register the subclass constructor. ' + 'Did you attempt to register an instance of the subclass?'); } classMap[className] = constructor; if (!constructor.className) { constructor.className = className; } } /** * Creates a new subclass of Parse.Object for the given Parse class name. * * <p>Every extension of a Parse class will inherit from the most recent * previous extension of that class. When a Parse.Object is automatically * created by parsing JSON, it will use the most recent extension of that * class.</p> * * <p>You should call either:<pre> * var MyClass = Parse.Object.extend("MyClass", { * <i>Instance methods</i>, * initialize: function(attrs, options) { * this.someInstanceProperty = [], * <i>Other instance properties</i> * } * }, { * <i>Class properties</i> * });</pre> * or, for Backbone compatibility:<pre> * var MyClass = Parse.Object.extend({ * className: "MyClass", * <i>Instance methods</i>, * initialize: function(attrs, options) { * this.someInstanceProperty = [], * <i>Other instance properties</i> * } * }, { * <i>Class properties</i> * });</pre></p> * * @method extend * @param {String} className The name of the Parse class backing this model. * @param {Object} protoProps Instance properties to add to instances of the * class returned from this method. * @param {Object} classProps Class properties to add the class returned from * this method. * @return {Class} A new subclass of Parse.Object. */ }, { key: 'extend', value: function (className, protoProps, classProps) { if (typeof className !== 'string') { if (className && typeof className.className === 'string') { return ParseObject.extend(className.className, className, protoProps); } else { throw new Error('Parse.Object.extend\'s first argument should be the className.'); } } var adjustedClassName = className; if (adjustedClassName === 'User' && _CoreManager2.default.get('PERFORM_USER_REWRITE')) { adjustedClassName = '_User'; } var parentProto = ParseObject.prototype; if (this.hasOwnProperty('__super__') && this.__super__) { parentProto = this.prototype; } else if (classMap[adjustedClassName]) { parentProto = classMap[adjustedClassName].prototype; } var ParseObjectSubclass = function (attributes, options) { this.className = adjustedClassName; this._objCount = objectCount++; // Enable legacy initializers if (typeof this.initialize === 'function') { this.initialize.apply(this, arguments); } if (attributes && (typeof attributes === 'undefined' ? 'undefined' : (0, _typeof3.default)(attributes)) === 'object') { if (!this.set(attributes || {}, options)) { throw new Error('Can\'t create an invalid Parse Object'); } } }; ParseObjectSubclass.className = adjustedClassName; ParseObjectSubclass.__super__ = parentProto; ParseObjectSubclass.prototype = (0, _create2.default)(parentProto, { constructor: { value: ParseObjectSubclass, enumerable: false, writable: true, configurable: true } }); if (protoProps) { for (var prop in protoProps) { if (prop !== 'className') { (0, _defineProperty2.default)(ParseObjectSubclass.prototype, prop, { value: protoProps[prop], enumerable: false, writable: true, configurable: true }); } } } if (classProps) { for (var prop in classProps) { if (prop !== 'className') { (0, _defineProperty2.default)(ParseObjectSubclass, prop, { value: classProps[prop], enumerable: false, writable: true, configurable: true }); } } } ParseObjectSubclass.extend = function (name, protoProps, classProps) { if (typeof name === 'string') { return ParseObject.extend.call(ParseObjectSubclass, name, protoProps, classProps); } return ParseObject.extend.call(ParseObjectSubclass, adjustedClassName, name, protoProps); }; ParseObjectSubclass.createWithoutData = ParseObject.createWithoutData; classMap[adjustedClassName] = ParseObjectSubclass; return ParseObjectSubclass; } /** * Enable single instance objects, where any local objects with the same Id * share the same attributes, and stay synchronized with each other. * This is disabled by default in server environments, since it can lead to * security issues. * @method enableSingleInstance */ }, { key: 'enableSingleInstance', value: function () { singleInstance = true; _CoreManager2.default.setObjectStateController(SingleInstanceStateController); } /** * Disable single instance objects, where any local objects with the same Id * share the same attributes, and stay synchronized with each other. * When disabled, you can have two instances of the same object in memory * without them sharing attributes. * @method disableSingleInstance */ }, { key: 'disableSingleInstance', value: function () { singleInstance = false; _CoreManager2.default.setObjectStateController(UniqueInstanceStateController); } }]); return ParseObject; }(); exports.default = ParseObject; var DefaultController = { fetch: function (target, forceFetch, options) { if (Array.isArray(target)) { if (target.length < 1) { return _ParsePromise2.default.as([]); } var objs = []; var ids = []; var className = null; var results = []; var error = null; target.forEach(function (el) { if (error) { return; } if (!className) { className = el.className; } if (className !== el.className) { error = new _ParseError2.default(_ParseError2.default.INVALID_CLASS_NAME, 'All objects should be of the same class'); } if (!el.id) { error = new _ParseError2.default(_ParseError2.default.MISSING_OBJECT_ID, 'All objects must have an ID'); } if (forceFetch || (0, _keys2.default)(el._getServerData()).length === 0) { ids.push(el.id); objs.push(el); } results.push(el); }); if (error) { return _ParsePromise2.default.error(error); } var query = new _ParseQuery2.default(className); query.containedIn('objectId', ids); query._limit = ids.length; return query.find(options).then(function (objects) { var idMap = {}; objects.forEach(function (o) { idMap[o.id] = o; }); for (var i = 0; i < objs.length; i++) { var obj = objs[i]; if (!obj || !obj.id || !idMap[obj.id]) { if (forceFetch) { return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.OBJECT_NOT_FOUND, 'All objects must exist on the server.')); } } } if (!singleInstance) { // If single instance objects are disabled, we need to replace the for (var i = 0; i < results.length; i++) { var obj = results[i]; if (obj && obj.id && idMap[obj.id]) { var id = obj.id; obj._finishFetch(idMap[id].toJSON()); results[i] = idMap[id]; } } } return _ParsePromise2.default.as(results); }); } else { var RESTController = _CoreManager2.default.getRESTController(); return RESTController.request('GET', 'classes/' + target.className + '/' + target._getId(), {}, options).then(function (response) { if (target instanceof ParseObject) { target._clearPendingOps(); target._clearServerData(); target._finishFetch(response); } return target; }); } }, destroy: function (target, options) { var RESTController = _CoreManager2.default.getRESTController(); if (Array.isArray(target)) { if (target.length < 1) { return _ParsePromise2.default.as([]); } var batches = [[]]; target.forEach(function (obj) { if (!obj.id) { return; } batches[batches.length - 1].push(obj); if (batches[batches.length - 1].length >= 20) { batches.push([]); } }); if (batches[batches.length - 1].length === 0) { // If the last batch is empty, remove it batches.pop(); } var deleteCompleted = _ParsePromise2.default.as(); var errors = []; batches.forEach(function (batch) { deleteCompleted = deleteCompleted.then(function () { return RESTController.request('POST', 'batch', { requests: batch.map(function (obj) { return { method: 'DELETE', path: getServerUrlPath() + 'classes/' + obj.className + '/' + obj._getId(), body: {} }; }) }, options).then(function (results) { for (var i = 0; i < results.length; i++) { if (results[i] && results[i].hasOwnProperty('error')) { var err = new _ParseError2.default(results[i].error.code, results[i].error.error); err.object = batch[i]; errors.push(err); } } }); }); }); return deleteCompleted.then(function () { if (errors.length) { var aggregate = new _ParseError2.default(_ParseError2.default.AGGREGATE_ERROR); aggregate.errors = errors; return _ParsePromise2.default.error(aggregate); } return _ParsePromise2.default.as(target); }); } else if (target instanceof ParseObject) { return RESTController.request('DELETE', 'classes/' + target.className + '/' + target._getId(), {}, options).then(function () { return _ParsePromise2.default.as(target); }); } return _ParsePromise2.default.as(target); }, save: function (target, options) { var RESTController = _CoreManager2.default.getRESTController(); var stateController = _CoreManager2.default.getObjectStateController(); if (Array.isArray(target)) { if (target.length < 1) { return _ParsePromise2.default.as([]); } var unsaved = target.concat(); for (var i = 0; i < target.length; i++) { if (target[i] instanceof ParseObject) { unsaved = unsaved.concat((0, _unsavedChildren2.default)(target[i], true)); } } unsaved = (0, _unique2.default)(unsaved); var filesSaved = _ParsePromise2.default.as(); var pending = []; unsaved.forEach(function (el) { if (el instanceof _ParseFile2.default) { filesSaved = filesSaved.then(function () { return el.save(); }); } else if (el instanceof ParseObject) { pending.push(el); } }); return filesSaved.then(function () { var objectError = null; return _ParsePromise2.default._continueWhile(function () { return pending.length > 0; }, function () { var batch = []; var nextPending = []; pending.forEach(function (el) { if (batch.length < 20 && (0, _canBeSerialized2.default)(el)) { batch.push(el); } else { nextPending.push(el); } }); pending = nextPending; if (batch.length < 1) { return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'Tried to save a batch with a cycle.')); } // Queue up tasks for each object in the batch. // When every task is ready, the API request will execute var batchReturned = new _ParsePromise2.default(); var batchReady = []; var batchTasks = []; batch.forEach(function (obj, index) { var ready = new _ParsePromise2.default(); batchReady.push(ready); stateController.pushPendingState(obj._getStateIdentifier()); batchTasks.push(stateController.enqueueTask(obj._getStateIdentifier(), function () { ready.resolve(); return batchReturned.then(function (responses, status) { if (responses[index].hasOwnProperty('success')) { obj._handleSaveResponse(responses[index].success, status); } else { if (!objectError && responses[index].hasOwnProperty('error')) { var serverError = responses[index].error; objectError = new _ParseError2.default(serverError.code, serverError.error); // Cancel the rest of the save pending = []; } obj._handleSaveError(); } }); })); }); _ParsePromise2.default.when(batchReady).then(function () { // Kick off the batch request return RESTController.request('POST', 'batch', { requests: batch.map(function (obj) { var params = obj._getSaveParams(); params.path = getServerUrlPath() + params.path; return params; }) }, options); }).then(function (response, status) { batchReturned.resolve(response, status); }); return _ParsePromise2.default.when(batchTasks); }).then(function () { if (objectError) { return _ParsePromise2.default.error(objectError); } return _ParsePromise2.default.as(target); }); }); } else if (target instanceof ParseObject) { // copying target lets Flow guarantee the pointer isn't modified elsewhere var targetCopy = target; var task = function () { var params = targetCopy._getSaveParams(); return RESTController.request(params.method, params.path, params.body, options).then(function (response, status) { targetCopy._handleSaveResponse(response, status); }, function (error) { targetCopy._handleSaveError(); return _ParsePromise2.default.error(error); }); }; stateController.pushPendingState(target._getStateIdentifier()); return stateController.enqueueTask(target._getStateIdentifier(), task).then(function () { return target; }, function (error) { return _ParsePromise2.default.error(error); }); } return _ParsePromise2.default.as(); } }; _CoreManager2.default.setObjectController(DefaultController); },{"./CoreManager":3,"./ParseACL":11,"./ParseError":13,"./ParseFile":14,"./ParseOp":19,"./ParsePromise":21,"./ParseQuery":22,"./ParseRelation":23,"./SingleInstanceStateController":29,"./UniqueInstanceStateController":33,"./canBeSerialized":35,"./decode":36,"./encode":37,"./equals":38,"./escape":39,"./parseDate":41,"./unique":42,"./unsavedChildren":43,"babel-runtime/core-js/json/stringify":45,"babel-runtime/core-js/object/create":47,"babel-runtime/core-js/object/define-property":48,"babel-runtime/core-js/object/freeze":49,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/typeof":62}],19:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.RelationOp = exports.RemoveOp = exports.AddUniqueOp = exports.AddOp = exports.IncrementOp = exports.UnsetOp = exports.SetOp = exports.Op = undefined; var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = _dereq_('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); exports.opFromJSON = opFromJSON; var _arrayContainsObject = _dereq_('./arrayContainsObject'); var _arrayContainsObject2 = _interopRequireDefault(_arrayContainsObject); var _decode = _dereq_('./decode'); var _decode2 = _interopRequireDefault(_decode); var _encode = _dereq_('./encode'); var _encode2 = _interopRequireDefault(_encode); var _ParseObject = _dereq_('./ParseObject'); var _ParseObject2 = _interopRequireDefault(_ParseObject); var _ParseRelation = _dereq_('./ParseRelation'); var _ParseRelation2 = _interopRequireDefault(_ParseRelation); var _unique = _dereq_('./unique'); var _unique2 = _interopRequireDefault(_unique); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function opFromJSON(json) { if (!json || !json.__op) { return null; } switch (json.__op) { case 'Delete': return new UnsetOp(); case 'Increment': return new IncrementOp(json.amount); case 'Add': return new AddOp((0, _decode2.default)(json.objects)); case 'AddUnique': return new AddUniqueOp((0, _decode2.default)(json.objects)); case 'Remove': return new RemoveOp((0, _decode2.default)(json.objects)); case 'AddRelation': var toAdd = (0, _decode2.default)(json.objects); if (!Array.isArray(toAdd)) { return new RelationOp([], []); } return new RelationOp(toAdd, []); case 'RemoveRelation': var toRemove = (0, _decode2.default)(json.objects); if (!Array.isArray(toRemove)) { return new RelationOp([], []); } return new RelationOp([], toRemove); case 'Batch': var toAdd = []; var toRemove = []; for (var i = 0; i < json.ops.length; i++) { if (json.ops[i].__op === 'AddRelation') { toAdd = toAdd.concat((0, _decode2.default)(json.ops[i].objects)); } else if (json.ops[i].__op === 'RemoveRelation') { toRemove = toRemove.concat((0, _decode2.default)(json.ops[i].objects)); } } return new RelationOp(toAdd, toRemove); } return null; } var Op = exports.Op = function () { function Op() { (0, _classCallCheck3.default)(this, Op); } (0, _createClass3.default)(Op, [{ key: 'applyTo', // Empty parent class value: function () {} }, { key: 'mergeWith', value: function () {} }, { key: 'toJSON', value: function () {} }]); return Op; }(); var SetOp = exports.SetOp = function (_Op) { (0, _inherits3.default)(SetOp, _Op); function SetOp(value) { (0, _classCallCheck3.default)(this, SetOp); var _this = (0, _possibleConstructorReturn3.default)(this, (SetOp.__proto__ || (0, _getPrototypeOf2.default)(SetOp)).call(this)); _this._value = value; return _this; } (0, _createClass3.default)(SetOp, [{ key: 'applyTo', value: function () { return this._value; } }, { key: 'mergeWith', value: function () { return new SetOp(this._value); } }, { key: 'toJSON', value: function () { return (0, _encode2.default)(this._value, false, true); } }]); return SetOp; }(Op); var UnsetOp = exports.UnsetOp = function (_Op2) { (0, _inherits3.default)(UnsetOp, _Op2); function UnsetOp() { (0, _classCallCheck3.default)(this, UnsetOp); return (0, _possibleConstructorReturn3.default)(this, (UnsetOp.__proto__ || (0, _getPrototypeOf2.default)(UnsetOp)).apply(this, arguments)); } (0, _createClass3.default)(UnsetOp, [{ key: 'applyTo', value: function () { return undefined; } }, { key: 'mergeWith', value: function () { return new UnsetOp(); } }, { key: 'toJSON', value: function () { return { __op: 'Delete' }; } }]); return UnsetOp; }(Op); var IncrementOp = exports.IncrementOp = function (_Op3) { (0, _inherits3.default)(IncrementOp, _Op3); function IncrementOp(amount) { (0, _classCallCheck3.default)(this, IncrementOp); var _this3 = (0, _possibleConstructorReturn3.default)(this, (IncrementOp.__proto__ || (0, _getPrototypeOf2.default)(IncrementOp)).call(this)); if (typeof amount !== 'number') { throw new TypeError('Increment Op must be initialized with a numeric amount.'); } _this3._amount = amount; return _this3; } (0, _createClass3.default)(IncrementOp, [{ key: 'applyTo', value: function (value) { if (typeof value === 'undefined') { return this._amount; } if (typeof value !== 'number') { throw new TypeError('Cannot increment a non-numeric value.'); } return this._amount + value; } }, { key: 'mergeWith', value: function (previous) { if (!previous) { return this; } if (previous instanceof SetOp) { return new SetOp(this.applyTo(previous._value)); } if (previous instanceof UnsetOp) { return new SetOp(this._amount); } if (previous instanceof IncrementOp) { return new IncrementOp(this.applyTo(previous._amount)); } throw new Error('Cannot merge Increment Op with the previous Op'); } }, { key: 'toJSON', value: function () { return { __op: 'Increment', amount: this._amount }; } }]); return IncrementOp; }(Op); var AddOp = exports.AddOp = function (_Op4) { (0, _inherits3.default)(AddOp, _Op4); function AddOp(value) { (0, _classCallCheck3.default)(this, AddOp); var _this4 = (0, _possibleConstructorReturn3.default)(this, (AddOp.__proto__ || (0, _getPrototypeOf2.default)(AddOp)).call(this)); _this4._value = Array.isArray(value) ? value : [value]; return _this4; } (0, _createClass3.default)(AddOp, [{ key: 'applyTo', value: function (value) { if (value == null) { return this._value; } if (Array.isArray(value)) { return value.concat(this._value); } throw new Error('Cannot add elements to a non-array value'); } }, { key: 'mergeWith', value: function (previous) { if (!previous) { return this; } if (previous instanceof SetOp) { return new SetOp(this.applyTo(previous._value)); } if (previous instanceof UnsetOp) { return new SetOp(this._value); } if (previous instanceof AddOp) { return new AddOp(this.applyTo(previous._value)); } throw new Error('Cannot merge Add Op with the previous Op'); } }, { key: 'toJSON', value: function () { return { __op: 'Add', objects: (0, _encode2.default)(this._value, false, true) }; } }]); return AddOp; }(Op); var AddUniqueOp = exports.AddUniqueOp = function (_Op5) { (0, _inherits3.default)(AddUniqueOp, _Op5); function AddUniqueOp(value) { (0, _classCallCheck3.default)(this, AddUniqueOp); var _this5 = (0, _possibleConstructorReturn3.default)(this, (AddUniqueOp.__proto__ || (0, _getPrototypeOf2.default)(AddUniqueOp)).call(this)); _this5._value = (0, _unique2.default)(Array.isArray(value) ? value : [value]); return _this5; } (0, _createClass3.default)(AddUniqueOp, [{ key: 'applyTo', value: function (value) { if (value == null) { return this._value || []; } if (Array.isArray(value)) { // copying value lets Flow guarantee the pointer isn't modified elsewhere var valueCopy = value; var toAdd = []; this._value.forEach(function (v) { if (v instanceof _ParseObject2.default) { if (!(0, _arrayContainsObject2.default)(valueCopy, v)) { toAdd.push(v); } } else { if (valueCopy.indexOf(v) < 0) { toAdd.push(v); } } }); return value.concat(toAdd); } throw new Error('Cannot add elements to a non-array value'); } }, { key: 'mergeWith', value: function (previous) { if (!previous) { return this; } if (previous instanceof SetOp) { return new SetOp(this.applyTo(previous._value)); } if (previous instanceof UnsetOp) { return new SetOp(this._value); } if (previous instanceof AddUniqueOp) { return new AddUniqueOp(this.applyTo(previous._value)); } throw new Error('Cannot merge AddUnique Op with the previous Op'); } }, { key: 'toJSON', value: function () { return { __op: 'AddUnique', objects: (0, _encode2.default)(this._value, false, true) }; } }]); return AddUniqueOp; }(Op); var RemoveOp = exports.RemoveOp = function (_Op6) { (0, _inherits3.default)(RemoveOp, _Op6); function RemoveOp(value) { (0, _classCallCheck3.default)(this, RemoveOp); var _this6 = (0, _possibleConstructorReturn3.default)(this, (RemoveOp.__proto__ || (0, _getPrototypeOf2.default)(RemoveOp)).call(this)); _this6._value = (0, _unique2.default)(Array.isArray(value) ? value : [value]); return _this6; } (0, _createClass3.default)(RemoveOp, [{ key: 'applyTo', value: function (value) { if (value == null) { return []; } if (Array.isArray(value)) { var i = value.indexOf(this._value); var removed = value.concat([]); for (var i = 0; i < this._value.length; i++) { var index = removed.indexOf(this._value[i]); while (index > -1) { removed.splice(index, 1); index = removed.indexOf(this._value[i]); } if (this._value[i] instanceof _ParseObject2.default && this._value[i].id) { for (var j = 0; j < removed.length; j++) { if (removed[j] instanceof _ParseObject2.default && this._value[i].id === removed[j].id) { removed.splice(j, 1); j--; } } } } return removed; } throw new Error('Cannot remove elements from a non-array value'); } }, { key: 'mergeWith', value: function (previous) { if (!previous) { return this; } if (previous instanceof SetOp) { return new SetOp(this.applyTo(previous._value)); } if (previous instanceof UnsetOp) { return new UnsetOp(); } if (previous instanceof RemoveOp) { var uniques = previous._value.concat([]); for (var i = 0; i < this._value.length; i++) { if (this._value[i] instanceof _ParseObject2.default) { if (!(0, _arrayContainsObject2.default)(uniques, this._value[i])) { uniques.push(this._value[i]); } } else { if (uniques.indexOf(this._value[i]) < 0) { uniques.push(this._value[i]); } } } return new RemoveOp(uniques); } throw new Error('Cannot merge Remove Op with the previous Op'); } }, { key: 'toJSON', value: function () { return { __op: 'Remove', objects: (0, _encode2.default)(this._value, false, true) }; } }]); return RemoveOp; }(Op); var RelationOp = exports.RelationOp = function (_Op7) { (0, _inherits3.default)(RelationOp, _Op7); function RelationOp(adds, removes) { (0, _classCallCheck3.default)(this, RelationOp); var _this7 = (0, _possibleConstructorReturn3.default)(this, (RelationOp.__proto__ || (0, _getPrototypeOf2.default)(RelationOp)).call(this)); _this7._targetClassName = null; if (Array.isArray(adds)) { _this7.relationsToAdd = (0, _unique2.default)(adds.map(_this7._extractId, _this7)); } if (Array.isArray(removes)) { _this7.relationsToRemove = (0, _unique2.default)(removes.map(_this7._extractId, _this7)); } return _this7; } (0, _createClass3.default)(RelationOp, [{ key: '_extractId', value: function (obj) { if (typeof obj === 'string') { return obj; } if (!obj.id) { throw new Error('You cannot add or remove an unsaved Parse Object from a relation'); } if (!this._targetClassName) { this._targetClassName = obj.className; } if (this._targetClassName !== obj.className) { throw new Error('Tried to create a Relation with 2 different object types: ' + this._targetClassName + ' and ' + obj.className + '.'); } return obj.id; } }, { key: 'applyTo', value: function (value, object, key) { if (!value) { if (!object || !key) { throw new Error('Cannot apply a RelationOp without either a previous value, or an object and a key'); } var parent = new _ParseObject2.default(object.className); if (object.id && object.id.indexOf('local') === 0) { parent._localId = object.id; } else if (object.id) { parent.id = object.id; } var relation = new _ParseRelation2.default(parent, key); relation.targetClassName = this._targetClassName; return relation; } if (value instanceof _ParseRelation2.default) { if (this._targetClassName) { if (value.targetClassName) { if (this._targetClassName !== value.targetClassName) { throw new Error('Related object must be a ' + value.targetClassName + ', but a ' + this._targetClassName + ' was passed in.'); } } else { value.targetClassName = this._targetClassName; } } return value; } else { throw new Error('Relation cannot be applied to a non-relation field'); } } }, { key: 'mergeWith', value: function (previous) { if (!previous) { return this; } else if (previous instanceof UnsetOp) { throw new Error('You cannot modify a relation after deleting it.'); } else if (previous instanceof RelationOp) { if (previous._targetClassName && previous._targetClassName !== this._targetClassName) { throw new Error('Related object must be of class ' + previous._targetClassName + ', but ' + (this._targetClassName || 'null') + ' was passed in.'); } var newAdd = previous.relationsToAdd.concat([]); this.relationsToRemove.forEach(function (r) { var index = newAdd.indexOf(r); if (index > -1) { newAdd.splice(index, 1); } }); this.relationsToAdd.forEach(function (r) { var index = newAdd.indexOf(r); if (index < 0) { newAdd.push(r); } }); var newRemove = previous.relationsToRemove.concat([]); this.relationsToAdd.forEach(function (r) { var index = newRemove.indexOf(r); if (index > -1) { newRemove.splice(index, 1); } }); this.relationsToRemove.forEach(function (r) { var index = newRemove.indexOf(r); if (index < 0) { newRemove.push(r); } }); var newRelation = new RelationOp(newAdd, newRemove); newRelation._targetClassName = this._targetClassName; return newRelation; } throw new Error('Cannot merge Relation Op with the previous Op'); } }, { key: 'toJSON', value: function () { var _this8 = this; var idToPointer = function (id) { return { __type: 'Pointer', className: _this8._targetClassName, objectId: id }; }; var adds = null; var removes = null; var pointers = null; if (this.relationsToAdd.length > 0) { pointers = this.relationsToAdd.map(idToPointer); adds = { __op: 'AddRelation', objects: pointers }; } if (this.relationsToRemove.length > 0) { pointers = this.relationsToRemove.map(idToPointer); removes = { __op: 'RemoveRelation', objects: pointers }; } if (adds && removes) { return { __op: 'Batch', ops: [adds, removes] }; } return adds || removes || {}; } }]); return RelationOp; }(Op); },{"./ParseObject":18,"./ParseRelation":23,"./arrayContainsObject":34,"./decode":36,"./encode":37,"./unique":42,"babel-runtime/core-js/object/get-prototype-of":51,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/inherits":60,"babel-runtime/helpers/possibleConstructorReturn":61}],20:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _ParseGeoPoint = _dereq_('./ParseGeoPoint'); var _ParseGeoPoint2 = _interopRequireDefault(_ParseGeoPoint); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Creates a new Polygon with any of the following forms:<br> * <pre> * new Polygon([[0,0],[0,1],[1,1],[1,0]]) * new Polygon([GeoPoint, GeoPoint, GeoPoint]) * </pre> * @class Parse.GeoPoint * @constructor * * <p>Represents a coordinates that may be associated * with a key in a ParseObject or used as a reference point for geo queries. * This allows proximity-based queries on the key.</p> * * <p>Example:<pre> * var polygon = new Parse.Polygon([[0,0],[0,1],[1,1],[1,0]]); * var object = new Parse.Object("PlaceObject"); * object.set("area", polygon); * object.save();</pre></p> */ var ParsePolygon = function () { function ParsePolygon(arg1) { (0, _classCallCheck3.default)(this, ParsePolygon); this._coordinates = ParsePolygon._validate(arg1); } /** * Coordinates value for this Polygon. * Throws an exception if not valid type. * @property coordinates * @type Array */ (0, _createClass3.default)(ParsePolygon, [{ key: 'toJSON', /** * Returns a JSON representation of the GeoPoint, suitable for Parse. * @method toJSON * @return {Object} */ value: function () { ParsePolygon._validate(this._coordinates); return { __type: 'Polygon', coordinates: this._coordinates }; } }, { key: 'equals', value: function (other) { if (!(other instanceof ParsePolygon) || this.coordinates.length !== other.coordinates.length) { return false; } var isEqual = true; for (var i = 1; i < this._coordinates.length; i += 1) { if (this._coordinates[i][0] != other.coordinates[i][0] || this._coordinates[i][1] != other.coordinates[i][1]) { isEqual = false; break; } } return isEqual; } }, { key: 'containsPoint', value: function (point) { var minX = this._coordinates[0][0]; var maxX = this._coordinates[0][0]; var minY = this._coordinates[0][1]; var maxY = this._coordinates[0][1]; for (var i = 1; i < this._coordinates.length; i += 1) { var p = this._coordinates[i]; minX = Math.min(p[0], minX); maxX = Math.max(p[0], maxX); minY = Math.min(p[1], minY); maxY = Math.max(p[1], maxY); } var outside = point.latitude < minX || point.latitude > maxX || point.longitude < minY || point.longitude > maxY; if (outside) { return false; } var inside = false; for (var _i = 0, j = this._coordinates.length - 1; _i < this._coordinates.length; j = _i++) { var startX = this._coordinates[_i][0]; var startY = this._coordinates[_i][1]; var endX = this._coordinates[j][0]; var endY = this._coordinates[j][1]; var intersect = startY > point.longitude != endY > point.longitude && point.latitude < (endX - startX) * (point.longitude - startY) / (endY - startY) + startX; if (intersect) { inside = !inside; } } return inside; } /** * Throws an exception if the given lat-long is out of bounds. * @return {Array} */ }, { key: 'coordinates', get: function () { return this._coordinates; }, set: function (coords) { this._coordinates = ParsePolygon._validate(coords); } }], [{ key: '_validate', value: function (coords) { if (!Array.isArray(coords)) { throw new TypeError('Coordinates must be an Array'); } if (coords.length < 3) { throw new TypeError('Polygon must have at least 3 GeoPoints or Points'); } var points = []; for (var i = 0; i < coords.length; i += 1) { var coord = coords[i]; var geoPoint = void 0; if (coord instanceof _ParseGeoPoint2.default) { geoPoint = coord; } else if (Array.isArray(coord) && coord.length === 2) { geoPoint = new _ParseGeoPoint2.default(coord[0], coord[1]); } else { throw new TypeError('Coordinates must be an Array of GeoPoints or Points'); } points.push([geoPoint.latitude, geoPoint.longitude]); } return points; } }]); return ParsePolygon; }(); /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ exports.default = ParsePolygon; },{"./ParseGeoPoint":15,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58}],21:[function(_dereq_,module,exports){ (function (process){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _getIterator2 = _dereq_('babel-runtime/core-js/get-iterator'); var _getIterator3 = _interopRequireDefault(_getIterator2); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ var _isPromisesAPlusCompliant = true; /** * A Promise is returned by async methods as a hook to provide callbacks to be * called when the async task is fulfilled. * * <p>Typical usage would be like:<pre> * query.find().then(function(results) { * results[0].set("foo", "bar"); * return results[0].saveAsync(); * }).then(function(result) { * console.log("Updated " + result.id); * }); * </pre></p> * * @class Parse.Promise * @constructor */ var ParsePromise = function () { function ParsePromise(executor) { (0, _classCallCheck3.default)(this, ParsePromise); this._resolved = false; this._rejected = false; this._resolvedCallbacks = []; this._rejectedCallbacks = []; if (typeof executor === 'function') { executor(this.resolve.bind(this), this.reject.bind(this)); } } /** * Marks this promise as fulfilled, firing any callbacks waiting on it. * @method resolve * @param {Object} result the result to pass to the callbacks. */ (0, _createClass3.default)(ParsePromise, [{ key: 'resolve', value: function () { if (this._resolved || this._rejected) { throw new Error('A promise was resolved even though it had already been ' + (this._resolved ? 'resolved' : 'rejected') + '.'); } this._resolved = true; for (var _len = arguments.length, results = Array(_len), _key = 0; _key < _len; _key++) { results[_key] = arguments[_key]; } this._result = results; for (var i = 0; i < this._resolvedCallbacks.length; i++) { this._resolvedCallbacks[i].apply(this, results); } this._resolvedCallbacks = []; this._rejectedCallbacks = []; } /** * Marks this promise as fulfilled, firing any callbacks waiting on it. * @method reject * @param {Object} error the error to pass to the callbacks. */ }, { key: 'reject', value: function (error) { if (this._resolved || this._rejected) { throw new Error('A promise was rejected even though it had already been ' + (this._resolved ? 'resolved' : 'rejected') + '.'); } this._rejected = true; this._error = error; for (var i = 0; i < this._rejectedCallbacks.length; i++) { this._rejectedCallbacks[i](error); } this._resolvedCallbacks = []; this._rejectedCallbacks = []; } /** * Adds callbacks to be called when this promise is fulfilled. Returns a new * Promise that will be fulfilled when the callback is complete. It allows * chaining. If the callback itself returns a Promise, then the one returned * by "then" will not be fulfilled until that one returned by the callback * is fulfilled. * @method then * @param {Function} resolvedCallback Function that is called when this * Promise is resolved. Once the callback is complete, then the Promise * returned by "then" will also be fulfilled. * @param {Function} rejectedCallback Function that is called when this * Promise is rejected with an error. Once the callback is complete, then * the promise returned by "then" with be resolved successfully. If * rejectedCallback is null, or it returns a rejected Promise, then the * Promise returned by "then" will be rejected with that error. * @return {Parse.Promise} A new Promise that will be fulfilled after this * Promise is fulfilled and either callback has completed. If the callback * returned a Promise, then this Promise will not be fulfilled until that * one is. */ }, { key: 'then', value: function (resolvedCallback, rejectedCallback) { var _this = this; var promise = new ParsePromise(); var wrappedResolvedCallback = function () { for (var _len2 = arguments.length, results = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { results[_key2] = arguments[_key2]; } if (typeof resolvedCallback === 'function') { if (_isPromisesAPlusCompliant) { try { results = [resolvedCallback.apply(this, results)]; } catch (e) { results = [ParsePromise.error(e)]; } } else { results = [resolvedCallback.apply(this, results)]; } } if (results.length === 1 && ParsePromise.is(results[0])) { results[0].then(function () { promise.resolve.apply(promise, arguments); }, function (error) { promise.reject(error); }); } else { promise.resolve.apply(promise, results); } }; var wrappedRejectedCallback = function (error) { var result = []; if (typeof rejectedCallback === 'function') { if (_isPromisesAPlusCompliant) { try { result = [rejectedCallback(error)]; } catch (e) { result = [ParsePromise.error(e)]; } } else { result = [rejectedCallback(error)]; } if (result.length === 1 && ParsePromise.is(result[0])) { result[0].then(function () { promise.resolve.apply(promise, arguments); }, function (error) { promise.reject(error); }); } else { if (_isPromisesAPlusCompliant) { promise.resolve.apply(promise, result); } else { promise.reject(result[0]); } } } else { promise.reject(error); } }; var runLater = function (fn) { fn.call(); }; if (_isPromisesAPlusCompliant) { if (typeof process !== 'undefined' && typeof process.nextTick === 'function') { runLater = function (fn) { process.nextTick(fn); }; } else if (typeof setTimeout === 'function') { runLater = function (fn) { setTimeout(fn, 0); }; } } if (this._resolved) { runLater(function () { wrappedResolvedCallback.apply(_this, _this._result); }); } else if (this._rejected) { runLater(function () { wrappedRejectedCallback(_this._error); }); } else { this._resolvedCallbacks.push(wrappedResolvedCallback); this._rejectedCallbacks.push(wrappedRejectedCallback); } return promise; } /** * Add handlers to be called when the promise * is either resolved or rejected * @method always */ }, { key: 'always', value: function (callback) { return this.then(callback, callback); } /** * Add handlers to be called when the Promise object is resolved * @method done */ }, { key: 'done', value: function (callback) { return this.then(callback); } /** * Add handlers to be called when the Promise object is rejected * Alias for catch(). * @method fail */ }, { key: 'fail', value: function (callback) { return this.then(null, callback); } /** * Add handlers to be called when the Promise object is rejected * @method catch */ }, { key: 'catch', value: function (callback) { return this.then(null, callback); } /** * Run the given callbacks after this promise is fulfilled. * @method _thenRunCallbacks * @param optionsOrCallback {} A Backbone-style options callback, or a * callback function. If this is an options object and contains a "model" * attributes, that will be passed to error callbacks as the first argument. * @param model {} If truthy, this will be passed as the first result of * error callbacks. This is for Backbone-compatability. * @return {Parse.Promise} A promise that will be resolved after the * callbacks are run, with the same result as this. */ }, { key: '_thenRunCallbacks', value: function (optionsOrCallback, model) { var options = {}; if (typeof optionsOrCallback === 'function') { options.success = function (result) { optionsOrCallback(result, null); }; options.error = function (error) { optionsOrCallback(null, error); }; } else if ((typeof optionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOrCallback)) === 'object') { if (typeof optionsOrCallback.success === 'function') { options.success = optionsOrCallback.success; } if (typeof optionsOrCallback.error === 'function') { options.error = optionsOrCallback.error; } } return this.then(function () { for (var _len3 = arguments.length, results = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { results[_key3] = arguments[_key3]; } if (options.success) { options.success.apply(this, results); } return ParsePromise.as.apply(ParsePromise, arguments); }, function (error) { if (options.error) { if (typeof model !== 'undefined') { options.error(model, error); } else { options.error(error); } } // By explicitly returning a rejected Promise, this will work with // either jQuery or Promises/A+ semantics. return ParsePromise.error(error); }); } /** * Adds a callback function that should be called regardless of whether * this promise failed or succeeded. The callback will be given either the * array of results for its first argument, or the error as its second, * depending on whether this Promise was rejected or resolved. Returns a * new Promise, like "then" would. * @method _continueWith * @param {Function} continuation the callback. */ }, { key: '_continueWith', value: function (continuation) { return this.then(function () { for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return continuation(args, null); }, function (error) { return continuation(null, error); }); } /** * Returns true iff the given object fulfils the Promise interface. * @method is * @param {Object} promise The object to test * @static * @return {Boolean} */ }], [{ key: 'is', value: function (promise) { return promise != null && typeof promise.then === 'function'; } /** * Returns a new promise that is resolved with a given value. * @method as * @param value The value to resolve the promise with * @static * @return {Parse.Promise} the new promise. */ }, { key: 'as', value: function () { var promise = new ParsePromise(); for (var _len5 = arguments.length, values = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { values[_key5] = arguments[_key5]; } promise.resolve.apply(promise, values); return promise; } /** * Returns a new promise that is resolved with a given value. * If that value is a thenable Promise (has a .then() prototype * method), the new promise will be chained to the end of the * value. * @method resolve * @param value The value to resolve the promise with * @static * @return {Parse.Promise} the new promise. */ }, { key: 'resolve', value: function (value) { return new ParsePromise(function (resolve, reject) { if (ParsePromise.is(value)) { value.then(resolve, reject); } else { resolve(value); } }); } /** * Returns a new promise that is rejected with a given error. * @method error * @param error The error to reject the promise with * @static * @return {Parse.Promise} the new promise. */ }, { key: 'error', value: function () { var promise = new ParsePromise(); for (var _len6 = arguments.length, errors = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { errors[_key6] = arguments[_key6]; } promise.reject.apply(promise, errors); return promise; } /** * Returns a new promise that is rejected with a given error. * This is an alias for Parse.Promise.error, for compliance with * the ES6 implementation. * @method reject * @param error The error to reject the promise with * @static * @return {Parse.Promise} the new promise. */ }, { key: 'reject', value: function () { for (var _len7 = arguments.length, errors = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { errors[_key7] = arguments[_key7]; } return ParsePromise.error.apply(null, errors); } /** * Returns a new promise that is fulfilled when all of the input promises * are resolved. If any promise in the list fails, then the returned promise * will be rejected with an array containing the error from each promise. * If they all succeed, then the returned promise will succeed, with the * results being the results of all the input * promises. For example: <pre> * var p1 = Parse.Promise.as(1); * var p2 = Parse.Promise.as(2); * var p3 = Parse.Promise.as(3); * * Parse.Promise.when(p1, p2, p3).then(function(r1, r2, r3) { * console.log(r1); // prints 1 * console.log(r2); // prints 2 * console.log(r3); // prints 3 * });</pre> * * The input promises can also be specified as an array: <pre> * var promises = [p1, p2, p3]; * Parse.Promise.when(promises).then(function(results) { * console.log(results); // prints [1,2,3] * }); * </pre> * @method when * @param {Array} promises a list of promises to wait for. * @static * @return {Parse.Promise} the new promise. */ }, { key: 'when', value: function (promises) { var objects; var arrayArgument = Array.isArray(promises); if (arrayArgument) { objects = promises; } else { objects = arguments; } var total = objects.length; var hadError = false; var results = []; var returnValue = arrayArgument ? [results] : results; var errors = []; results.length = objects.length; errors.length = objects.length; if (total === 0) { return ParsePromise.as.apply(this, returnValue); } var promise = new ParsePromise(); var resolveOne = function () { total--; if (total <= 0) { if (hadError) { promise.reject(errors); } else { promise.resolve.apply(promise, returnValue); } } }; var chain = function (object, index) { if (ParsePromise.is(object)) { object.then(function (result) { results[index] = result; resolveOne(); }, function (error) { errors[index] = error; hadError = true; resolveOne(); }); } else { results[i] = object; resolveOne(); } }; for (var i = 0; i < objects.length; i++) { chain(objects[i], i); } return promise; } /** * Returns a new promise that is fulfilled when all of the promises in the * iterable argument are resolved. If any promise in the list fails, then * the returned promise will be immediately rejected with the reason that * single promise rejected. If they all succeed, then the returned promise * will succeed, with the results being the results of all the input * promises. If the iterable provided is empty, the returned promise will * be immediately resolved. * * For example: <pre> * var p1 = Parse.Promise.as(1); * var p2 = Parse.Promise.as(2); * var p3 = Parse.Promise.as(3); * * Parse.Promise.all([p1, p2, p3]).then(function([r1, r2, r3]) { * console.log(r1); // prints 1 * console.log(r2); // prints 2 * console.log(r3); // prints 3 * });</pre> * * @method all * @param {Iterable} promises an iterable of promises to wait for. * @static * @return {Parse.Promise} the new promise. */ }, { key: 'all', value: function (promises) { var total = 0; var objects = []; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = (0, _getIterator3.default)(promises), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var p = _step.value; objects[total++] = p; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } if (total === 0) { return ParsePromise.as([]); } var hadError = false; var promise = new ParsePromise(); var resolved = 0; var results = []; objects.forEach(function (object, i) { if (ParsePromise.is(object)) { object.then(function (result) { if (hadError) { return false; } results[i] = result; resolved++; if (resolved >= total) { promise.resolve(results); } }, function (error) { // Reject immediately promise.reject(error); hadError = true; }); } else { results[i] = object; resolved++; if (!hadError && resolved >= total) { promise.resolve(results); } } }); return promise; } /** * Returns a new promise that is immediately fulfilled when any of the * promises in the iterable argument are resolved or rejected. If the * first promise to complete is resolved, the returned promise will be * resolved with the same value. Likewise, if the first promise to * complete is rejected, the returned promise will be rejected with the * same reason. * * @method race * @param {Iterable} promises an iterable of promises to wait for. * @static * @return {Parse.Promise} the new promise. */ }, { key: 'race', value: function (promises) { var completed = false; var promise = new ParsePromise(); var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = (0, _getIterator3.default)(promises), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var p = _step2.value; if (ParsePromise.is(p)) { p.then(function (result) { if (completed) { return; } completed = true; promise.resolve(result); }, function (error) { if (completed) { return; } completed = true; promise.reject(error); }); } else if (!completed) { completed = true; promise.resolve(p); } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } return promise; } /** * Runs the given asyncFunction repeatedly, as long as the predicate * function returns a truthy value. Stops repeating if asyncFunction returns * a rejected promise. * @method _continueWhile * @param {Function} predicate should return false when ready to stop. * @param {Function} asyncFunction should return a Promise. * @static */ }, { key: '_continueWhile', value: function (predicate, asyncFunction) { if (predicate()) { return asyncFunction().then(function () { return ParsePromise._continueWhile(predicate, asyncFunction); }); } return ParsePromise.as(); } }, { key: 'isPromisesAPlusCompliant', value: function () { return _isPromisesAPlusCompliant; } }, { key: 'enableAPlusCompliant', value: function () { _isPromisesAPlusCompliant = true; } }, { key: 'disableAPlusCompliant', value: function () { _isPromisesAPlusCompliant = false; } }]); return ParsePromise; }(); exports.default = ParsePromise; }).call(this,_dereq_('_process')) },{"_process":63,"babel-runtime/core-js/get-iterator":44,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/typeof":62}],22:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _keys = _dereq_('babel-runtime/core-js/object/keys'); var _keys2 = _interopRequireDefault(_keys); var _CoreManager = _dereq_('./CoreManager'); var _CoreManager2 = _interopRequireDefault(_CoreManager); var _encode = _dereq_('./encode'); var _encode2 = _interopRequireDefault(_encode); var _ParseError = _dereq_('./ParseError'); var _ParseError2 = _interopRequireDefault(_ParseError); var _ParseGeoPoint = _dereq_('./ParseGeoPoint'); var _ParseGeoPoint2 = _interopRequireDefault(_ParseGeoPoint); var _ParsePolygon = _dereq_('./ParsePolygon'); var _ParsePolygon2 = _interopRequireDefault(_ParsePolygon); var _ParseObject = _dereq_('./ParseObject'); var _ParseObject2 = _interopRequireDefault(_ParseObject); var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Converts a string into a regex that matches it. * Surrounding with \Q .. \E does this, we just need to escape any \E's in * the text separately. */ function quote(s) { return '\\Q' + s.replace('\\E', '\\E\\\\E\\Q') + '\\E'; } /** * Handles pre-populating the result data of a query with select fields, * making sure that the data object contains keys for all objects that have * been requested with a select, so that our cached state updates correctly. */ /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function handleSelectResult(data, select) { var serverDataMask = {}; select.forEach(function (field) { var hasSubObjectSelect = field.indexOf(".") !== -1; if (!hasSubObjectSelect && !data.hasOwnProperty(field)) { // this field was selected, but is missing from the retrieved data data[field] = undefined; } else if (hasSubObjectSelect) { // this field references a sub-object, // so we need to walk down the path components var pathComponents = field.split("."); var obj = data; var serverMask = serverDataMask; pathComponents.forEach(function (component, index, arr) { // add keys if the expected data is missing if (obj && !obj.hasOwnProperty(component)) { obj[component] = undefined; } if (obj !== undefined) { obj = obj[component]; } //add this path component to the server mask so we can fill it in later if needed if (index < arr.length - 1) { if (!serverMask[component]) { serverMask[component] = {}; } serverMask = serverMask[component]; } }); } }); if ((0, _keys2.default)(serverDataMask).length > 0) { var copyMissingDataWithMask = function copyMissingDataWithMask(src, dest, mask, copyThisLevel) { //copy missing elements at this level if (copyThisLevel) { for (var key in src) { if (src.hasOwnProperty(key) && !dest.hasOwnProperty(key)) { dest[key] = src[key]; } } } for (var key in mask) { if (dest[key] !== undefined && dest[key] !== null && src !== undefined && src !== null) { //traverse into objects as needed copyMissingDataWithMask(src[key], dest[key], mask[key], true); } } }; // When selecting from sub-objects, we don't want to blow away the missing // information that we may have retrieved before. We've already added any // missing selected keys to sub-objects, but we still need to add in the // data for any previously retrieved sub-objects that were not selected. var serverData = _CoreManager2.default.getObjectStateController().getServerData({ id: data.objectId, className: data.className }); copyMissingDataWithMask(serverData, data, serverDataMask, false); } } /** * Creates a new parse Parse.Query for the given Parse.Object subclass. * @class Parse.Query * @constructor * @param {} objectClass An instance of a subclass of Parse.Object, or a Parse className string. * * <p>Parse.Query defines a query that is used to fetch Parse.Objects. The * most common use case is finding all objects that match a query through the * <code>find</code> method. For example, this sample code fetches all objects * of class <code>MyClass</code>. It calls a different function depending on * whether the fetch succeeded or not. * * <pre> * var query = new Parse.Query(MyClass); * query.find({ * success: function(results) { * // results is an array of Parse.Object. * }, * * error: function(error) { * // error is an instance of Parse.Error. * } * });</pre></p> * * <p>A Parse.Query can also be used to retrieve a single object whose id is * known, through the get method. For example, this sample code fetches an * object of class <code>MyClass</code> and id <code>myId</code>. It calls a * different function depending on whether the fetch succeeded or not. * * <pre> * var query = new Parse.Query(MyClass); * query.get(myId, { * success: function(object) { * // object is an instance of Parse.Object. * }, * * error: function(object, error) { * // error is an instance of Parse.Error. * } * });</pre></p> * * <p>A Parse.Query can also be used to count the number of objects that match * the query without retrieving all of those objects. For example, this * sample code counts the number of objects of the class <code>MyClass</code> * <pre> * var query = new Parse.Query(MyClass); * query.count({ * success: function(number) { * // There are number instances of MyClass. * }, * * error: function(error) { * // error is an instance of Parse.Error. * } * });</pre></p> */ var ParseQuery = function () { function ParseQuery(objectClass) { (0, _classCallCheck3.default)(this, ParseQuery); if (typeof objectClass === 'string') { if (objectClass === 'User' && _CoreManager2.default.get('PERFORM_USER_REWRITE')) { this.className = '_User'; } else { this.className = objectClass; } } else if (objectClass instanceof _ParseObject2.default) { this.className = objectClass.className; } else if (typeof objectClass === 'function') { if (typeof objectClass.className === 'string') { this.className = objectClass.className; } else { var obj = new objectClass(); this.className = obj.className; } } else { throw new TypeError('A ParseQuery must be constructed with a ParseObject or class name.'); } this._where = {}; this._include = []; this._limit = -1; // negative limit is not sent in the server request this._skip = 0; this._extraOptions = {}; } /** * Adds constraint that at least one of the passed in queries matches. * @method _orQuery * @param {Array} queries * @return {Parse.Query} Returns the query, so you can chain this call. */ (0, _createClass3.default)(ParseQuery, [{ key: '_orQuery', value: function (queries) { var queryJSON = queries.map(function (q) { return q.toJSON().where; }); this._where.$or = queryJSON; return this; } /** * Helper for condition queries */ }, { key: '_addCondition', value: function (key, condition, value) { if (!this._where[key] || typeof this._where[key] === 'string') { this._where[key] = {}; } this._where[key][condition] = (0, _encode2.default)(value, false, true); return this; } /** * Returns a JSON representation of this query. * @method toJSON * @return {Object} The JSON representation of the query. */ }, { key: 'toJSON', value: function () { var params = { where: this._where }; if (this._include.length) { params.include = this._include.join(','); } if (this._select) { params.keys = this._select.join(','); } if (this._limit >= 0) { params.limit = this._limit; } if (this._skip > 0) { params.skip = this._skip; } if (this._order) { params.order = this._order.join(','); } for (var key in this._extraOptions) { params[key] = this._extraOptions[key]; } return params; } /** * Return a query with conditions from json, can be useful to send query from server side to client * Not static, all query conditions was set before calling this method will be deleted. * For example on the server side we have * var query = new Parse.Query("className"); * query.equalTo(key: value); * query.limit(100); * ... (others queries) * Create JSON representation of Query Object * var jsonFromServer = query.fromJSON(); * * On client side getting query: * var query = new Parse.Query("className"); * query.fromJSON(jsonFromServer); * * and continue to query... * query.skip(100).find().then(...); * @method withJSON * @param {QueryJSON} json from Parse.Query.toJSON() method * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'withJSON', value: function (json) { if (json.where) { this._where = json.where; } if (json.include) { this._include = json.include.split(","); } if (json.keys) { this._select = json.keys.split(","); } if (json.limit) { this._limit = json.limit; } if (json.skip) { this._skip = json.skip; } if (json.order) { this._order = json.order.split(","); } for (var _key in json) { if (json.hasOwnProperty(_key)) { if (["where", "include", "keys", "limit", "skip", "order"].indexOf(_key) === -1) { this._extraOptions[_key] = json[_key]; } } }return this; } /** * Static method to restore Parse.Query by json representation * Internally calling Parse.Query.withJSON * @param {String} className * @param {QueryJSON} json from Parse.Query.toJSON() method * @returns {Parse.Query} new created query */ }, { key: 'get', /** * Constructs a Parse.Object whose id is already known by fetching data from * the server. Either options.success or options.error is called when the * find completes. * * @method get * @param {String} objectId The id of the object to be fetched. * @param {Object} options A Backbone-style options object. * Valid options are:<ul> * <li>success: A Backbone-style success callback * <li>error: An Backbone-style error callback. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to * be used for this request. * <li>sessionToken: A valid session token, used for making a request on * behalf of a specific user. * </ul> * * @return {Parse.Promise} A promise that is resolved with the result when * the query completes. */ value: function (objectId, options) { this.equalTo('objectId', objectId); var firstOptions = {}; if (options && options.hasOwnProperty('useMasterKey')) { firstOptions.useMasterKey = options.useMasterKey; } if (options && options.hasOwnProperty('sessionToken')) { firstOptions.sessionToken = options.sessionToken; } return this.first(firstOptions).then(function (response) { if (response) { return response; } var errorObject = new _ParseError2.default(_ParseError2.default.OBJECT_NOT_FOUND, 'Object not found.'); return _ParsePromise2.default.error(errorObject); })._thenRunCallbacks(options, null); } /** * Retrieves a list of ParseObjects that satisfy this query. * Either options.success or options.error is called when the find * completes. * * @method find * @param {Object} options A Backbone-style options object. Valid options * are:<ul> * <li>success: Function to call when the find completes successfully. * <li>error: Function to call when the find fails. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to * be used for this request. * <li>sessionToken: A valid session token, used for making a request on * behalf of a specific user. * </ul> * * @return {Parse.Promise} A promise that is resolved with the results when * the query completes. */ }, { key: 'find', value: function (options) { var _this = this; options = options || {}; var findOptions = {}; if (options.hasOwnProperty('useMasterKey')) { findOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('sessionToken')) { findOptions.sessionToken = options.sessionToken; } var controller = _CoreManager2.default.getQueryController(); var select = this._select; return controller.find(this.className, this.toJSON(), findOptions).then(function (response) { return response.results.map(function (data) { // In cases of relations, the server may send back a className // on the top level of the payload var override = response.className || _this.className; if (!data.className) { data.className = override; } // Make sure the data object contains keys for all objects that // have been requested with a select, so that our cached state // updates correctly. if (select) { handleSelectResult(data, select); } return _ParseObject2.default.fromJSON(data, !select); }); })._thenRunCallbacks(options); } /** * Counts the number of objects that match this query. * Either options.success or options.error is called when the count * completes. * * @method count * @param {Object} options A Backbone-style options object. Valid options * are:<ul> * <li>success: Function to call when the count completes successfully. * <li>error: Function to call when the find fails. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to * be used for this request. * <li>sessionToken: A valid session token, used for making a request on * behalf of a specific user. * </ul> * * @return {Parse.Promise} A promise that is resolved with the count when * the query completes. */ }, { key: 'count', value: function (options) { options = options || {}; var findOptions = {}; if (options.hasOwnProperty('useMasterKey')) { findOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('sessionToken')) { findOptions.sessionToken = options.sessionToken; } var controller = _CoreManager2.default.getQueryController(); var params = this.toJSON(); params.limit = 0; params.count = 1; return controller.find(this.className, params, findOptions).then(function (result) { return result.count; })._thenRunCallbacks(options); } /** * Retrieves at most one Parse.Object that satisfies this query. * * Either options.success or options.error is called when it completes. * success is passed the object if there is one. otherwise, undefined. * * @method first * @param {Object} options A Backbone-style options object. Valid options * are:<ul> * <li>success: Function to call when the find completes successfully. * <li>error: Function to call when the find fails. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to * be used for this request. * <li>sessionToken: A valid session token, used for making a request on * behalf of a specific user. * </ul> * * @return {Parse.Promise} A promise that is resolved with the object when * the query completes. */ }, { key: 'first', value: function (options) { var _this2 = this; options = options || {}; var findOptions = {}; if (options.hasOwnProperty('useMasterKey')) { findOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('sessionToken')) { findOptions.sessionToken = options.sessionToken; } var controller = _CoreManager2.default.getQueryController(); var params = this.toJSON(); params.limit = 1; var select = this._select; return controller.find(this.className, params, findOptions).then(function (response) { var objects = response.results; if (!objects[0]) { return undefined; } if (!objects[0].className) { objects[0].className = _this2.className; } // Make sure the data object contains keys for all objects that // have been requested with a select, so that our cached state // updates correctly. if (select) { handleSelectResult(objects[0], select); } return _ParseObject2.default.fromJSON(objects[0], !select); })._thenRunCallbacks(options); } /** * Iterates over each result of a query, calling a callback for each one. If * the callback returns a promise, the iteration will not continue until * that promise has been fulfilled. If the callback returns a rejected * promise, then iteration will stop with that error. The items are * processed in an unspecified order. The query may not have any sort order, * and may not use limit or skip. * @method each * @param {Function} callback Callback that will be called with each result * of the query. * @param {Object} options A Backbone-style options object. Valid options * are:<ul> * <li>success: Function to call when the iteration completes successfully. * <li>error: Function to call when the iteration fails. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to * be used for this request. * <li>sessionToken: A valid session token, used for making a request on * behalf of a specific user. * </ul> * @return {Parse.Promise} A promise that will be fulfilled once the * iteration has completed. */ }, { key: 'each', value: function (callback, options) { options = options || {}; if (this._order || this._skip || this._limit >= 0) { return _ParsePromise2.default.error('Cannot iterate on a query with sort, skip, or limit.')._thenRunCallbacks(options); } new _ParsePromise2.default(); var query = new ParseQuery(this.className); // We can override the batch size from the options. // This is undocumented, but useful for testing. query._limit = options.batchSize || 100; query._include = this._include.map(function (i) { return i; }); if (this._select) { query._select = this._select.map(function (s) { return s; }); } query._where = {}; for (var attr in this._where) { var val = this._where[attr]; if (Array.isArray(val)) { query._where[attr] = val.map(function (v) { return v; }); } else if (val && (typeof val === 'undefined' ? 'undefined' : (0, _typeof3.default)(val)) === 'object') { var conditionMap = {}; query._where[attr] = conditionMap; for (var cond in val) { conditionMap[cond] = val[cond]; } } else { query._where[attr] = val; } } query.ascending('objectId'); var findOptions = {}; if (options.hasOwnProperty('useMasterKey')) { findOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('sessionToken')) { findOptions.sessionToken = options.sessionToken; } var finished = false; return _ParsePromise2.default._continueWhile(function () { return !finished; }, function () { return query.find(findOptions).then(function (results) { var callbacksDone = _ParsePromise2.default.as(); results.forEach(function (result) { callbacksDone = callbacksDone.then(function () { return callback(result); }); }); return callbacksDone.then(function () { if (results.length >= query._limit) { query.greaterThan('objectId', results[results.length - 1].id); } else { finished = true; } }); }); })._thenRunCallbacks(options); } /** Query Conditions **/ /** * Adds a constraint to the query that requires a particular key's value to * be equal to the provided value. * @method equalTo * @param {String} key The key to check. * @param value The value that the Parse.Object must contain. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'equalTo', value: function (key, value) { if (typeof value === 'undefined') { return this.doesNotExist(key); } this._where[key] = (0, _encode2.default)(value, false, true); return this; } /** * Adds a constraint to the query that requires a particular key's value to * be not equal to the provided value. * @method notEqualTo * @param {String} key The key to check. * @param value The value that must not be equalled. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'notEqualTo', value: function (key, value) { return this._addCondition(key, '$ne', value); } /** * Adds a constraint to the query that requires a particular key's value to * be less than the provided value. * @method lessThan * @param {String} key The key to check. * @param value The value that provides an upper bound. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'lessThan', value: function (key, value) { return this._addCondition(key, '$lt', value); } /** * Adds a constraint to the query that requires a particular key's value to * be greater than the provided value. * @method greaterThan * @param {String} key The key to check. * @param value The value that provides an lower bound. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'greaterThan', value: function (key, value) { return this._addCondition(key, '$gt', value); } /** * Adds a constraint to the query that requires a particular key's value to * be less than or equal to the provided value. * @method lessThanOrEqualTo * @param {String} key The key to check. * @param value The value that provides an upper bound. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'lessThanOrEqualTo', value: function (key, value) { return this._addCondition(key, '$lte', value); } /** * Adds a constraint to the query that requires a particular key's value to * be greater than or equal to the provided value. * @method greaterThanOrEqualTo * @param {String} key The key to check. * @param value The value that provides an lower bound. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'greaterThanOrEqualTo', value: function (key, value) { return this._addCondition(key, '$gte', value); } /** * Adds a constraint to the query that requires a particular key's value to * be contained in the provided list of values. * @method containedIn * @param {String} key The key to check. * @param {Array} values The values that will match. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'containedIn', value: function (key, value) { return this._addCondition(key, '$in', value); } /** * Adds a constraint to the query that requires a particular key's value to * not be contained in the provided list of values. * @method notContainedIn * @param {String} key The key to check. * @param {Array} values The values that will not match. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'notContainedIn', value: function (key, value) { return this._addCondition(key, '$nin', value); } /** * Adds a constraint to the query that requires a particular key's value to * contain each one of the provided list of values. * @method containsAll * @param {String} key The key to check. This key's value must be an array. * @param {Array} values The values that will match. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'containsAll', value: function (key, values) { return this._addCondition(key, '$all', values); } /** * Adds a constraint for finding objects that contain the given key. * @method exists * @param {String} key The key that should exist. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'exists', value: function (key) { return this._addCondition(key, '$exists', true); } /** * Adds a constraint for finding objects that do not contain a given key. * @method doesNotExist * @param {String} key The key that should not exist * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'doesNotExist', value: function (key) { return this._addCondition(key, '$exists', false); } /** * Adds a regular expression constraint for finding string values that match * the provided regular expression. * This may be slow for large datasets. * @method matches * @param {String} key The key that the string to match is stored in. * @param {RegExp} regex The regular expression pattern to match. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'matches', value: function (key, regex, modifiers) { this._addCondition(key, '$regex', regex); if (!modifiers) { modifiers = ''; } if (regex.ignoreCase) { modifiers += 'i'; } if (regex.multiline) { modifiers += 'm'; } if (modifiers.length) { this._addCondition(key, '$options', modifiers); } return this; } /** * Adds a constraint that requires that a key's value matches a Parse.Query * constraint. * @method matchesQuery * @param {String} key The key that the contains the object to match the * query. * @param {Parse.Query} query The query that should match. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'matchesQuery', value: function (key, query) { var queryJSON = query.toJSON(); queryJSON.className = query.className; return this._addCondition(key, '$inQuery', queryJSON); } /** * Adds a constraint that requires that a key's value not matches a * Parse.Query constraint. * @method doesNotMatchQuery * @param {String} key The key that the contains the object to match the * query. * @param {Parse.Query} query The query that should not match. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'doesNotMatchQuery', value: function (key, query) { var queryJSON = query.toJSON(); queryJSON.className = query.className; return this._addCondition(key, '$notInQuery', queryJSON); } /** * Adds a constraint that requires that a key's value matches a value in * an object returned by a different Parse.Query. * @method matchesKeyInQuery * @param {String} key The key that contains the value that is being * matched. * @param {String} queryKey The key in the objects returned by the query to * match against. * @param {Parse.Query} query The query to run. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'matchesKeyInQuery', value: function (key, queryKey, query) { var queryJSON = query.toJSON(); queryJSON.className = query.className; return this._addCondition(key, '$select', { key: queryKey, query: queryJSON }); } /** * Adds a constraint that requires that a key's value not match a value in * an object returned by a different Parse.Query. * @method doesNotMatchKeyInQuery * @param {String} key The key that contains the value that is being * excluded. * @param {String} queryKey The key in the objects returned by the query to * match against. * @param {Parse.Query} query The query to run. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'doesNotMatchKeyInQuery', value: function (key, queryKey, query) { var queryJSON = query.toJSON(); queryJSON.className = query.className; return this._addCondition(key, '$dontSelect', { key: queryKey, query: queryJSON }); } /** * Adds a constraint for finding string values that contain a provided * string. This may be slow for large datasets. * @method contains * @param {String} key The key that the string to match is stored in. * @param {String} substring The substring that the value must contain. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'contains', value: function (key, value) { if (typeof value !== 'string') { throw new Error('The value being searched for must be a string.'); } return this._addCondition(key, '$regex', quote(value)); } /** * Adds a constraint for finding string values that start with a provided * string. This query will use the backend index, so it will be fast even * for large datasets. * @method startsWith * @param {String} key The key that the string to match is stored in. * @param {String} prefix The substring that the value must start with. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'startsWith', value: function (key, value) { if (typeof value !== 'string') { throw new Error('The value being searched for must be a string.'); } return this._addCondition(key, '$regex', '^' + quote(value)); } /** * Adds a constraint for finding string values that end with a provided * string. This will be slow for large datasets. * @method endsWith * @param {String} key The key that the string to match is stored in. * @param {String} suffix The substring that the value must end with. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'endsWith', value: function (key, value) { if (typeof value !== 'string') { throw new Error('The value being searched for must be a string.'); } return this._addCondition(key, '$regex', quote(value) + '$'); } /** * Adds a proximity based constraint for finding objects with key point * values near the point given. * @method near * @param {String} key The key that the Parse.GeoPoint is stored in. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'near', value: function (key, point) { if (!(point instanceof _ParseGeoPoint2.default)) { // Try to cast it as a GeoPoint point = new _ParseGeoPoint2.default(point); } return this._addCondition(key, '$nearSphere', point); } /** * Adds a proximity based constraint for finding objects with key point * values near the point given and within the maximum distance given. * @method withinRadians * @param {String} key The key that the Parse.GeoPoint is stored in. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. * @param {Number} maxDistance Maximum distance (in radians) of results to * return. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'withinRadians', value: function (key, point, distance) { this.near(key, point); return this._addCondition(key, '$maxDistance', distance); } /** * Adds a proximity based constraint for finding objects with key point * values near the point given and within the maximum distance given. * Radius of earth used is 3958.8 miles. * @method withinMiles * @param {String} key The key that the Parse.GeoPoint is stored in. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. * @param {Number} maxDistance Maximum distance (in miles) of results to * return. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'withinMiles', value: function (key, point, distance) { return this.withinRadians(key, point, distance / 3958.8); } /** * Adds a proximity based constraint for finding objects with key point * values near the point given and within the maximum distance given. * Radius of earth used is 6371.0 kilometers. * @method withinKilometers * @param {String} key The key that the Parse.GeoPoint is stored in. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. * @param {Number} maxDistance Maximum distance (in kilometers) of results * to return. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'withinKilometers', value: function (key, point, distance) { return this.withinRadians(key, point, distance / 6371.0); } /** * Adds a constraint to the query that requires a particular key's * coordinates be contained within a given rectangular geographic bounding * box. * @method withinGeoBox * @param {String} key The key to be constrained. * @param {Parse.GeoPoint} southwest * The lower-left inclusive corner of the box. * @param {Parse.GeoPoint} northeast * The upper-right inclusive corner of the box. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'withinGeoBox', value: function (key, southwest, northeast) { if (!(southwest instanceof _ParseGeoPoint2.default)) { southwest = new _ParseGeoPoint2.default(southwest); } if (!(northeast instanceof _ParseGeoPoint2.default)) { northeast = new _ParseGeoPoint2.default(northeast); } this._addCondition(key, '$within', { '$box': [southwest, northeast] }); return this; } /** * Adds a constraint to the query that requires a particular key's * coordinates be contained within and on the bounds of a given polygon. * Supports closed and open (last point is connected to first) paths * * Polygon must have at least 3 points * * @method withinPolygon * @param {String} key The key to be constrained. * @param {Array} array of geopoints * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'withinPolygon', value: function (key, points) { return this._addCondition(key, '$geoWithin', { '$polygon': points }); } /** * Add a constraint to the query that requires a particular key's * coordinates that contains a ParseGeoPoint * * @method polygonContains * @param {String} key The key to be constrained. * @param {Parse.GeoPoint} GeoPoint * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'polygonContains', value: function (key, point) { return this._addCondition(key, '$geoIntersects', { '$point': point }); } /** Query Orderings **/ /** * Sorts the results in ascending order by the given key. * * @method ascending * @param {(String|String[]|...String} key The key to order by, which is a * string of comma separated values, or an Array of keys, or multiple keys. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'ascending', value: function () { this._order = []; for (var _len = arguments.length, keys = Array(_len), _key2 = 0; _key2 < _len; _key2++) { keys[_key2] = arguments[_key2]; } return this.addAscending.apply(this, keys); } /** * Sorts the results in ascending order by the given key, * but can also add secondary sort descriptors without overwriting _order. * * @method addAscending * @param {(String|String[]|...String} key The key to order by, which is a * string of comma separated values, or an Array of keys, or multiple keys. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'addAscending', value: function () { var _this3 = this; if (!this._order) { this._order = []; } for (var _len2 = arguments.length, keys = Array(_len2), _key3 = 0; _key3 < _len2; _key3++) { keys[_key3] = arguments[_key3]; } keys.forEach(function (key) { if (Array.isArray(key)) { key = key.join(); } _this3._order = _this3._order.concat(key.replace(/\s/g, '').split(',')); }); return this; } /** * Sorts the results in descending order by the given key. * * @method descending * @param {(String|String[]|...String} key The key to order by, which is a * string of comma separated values, or an Array of keys, or multiple keys. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'descending', value: function () { this._order = []; for (var _len3 = arguments.length, keys = Array(_len3), _key4 = 0; _key4 < _len3; _key4++) { keys[_key4] = arguments[_key4]; } return this.addDescending.apply(this, keys); } /** * Sorts the results in descending order by the given key, * but can also add secondary sort descriptors without overwriting _order. * * @method addDescending * @param {(String|String[]|...String} key The key to order by, which is a * string of comma separated values, or an Array of keys, or multiple keys. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'addDescending', value: function () { var _this4 = this; if (!this._order) { this._order = []; } for (var _len4 = arguments.length, keys = Array(_len4), _key5 = 0; _key5 < _len4; _key5++) { keys[_key5] = arguments[_key5]; } keys.forEach(function (key) { if (Array.isArray(key)) { key = key.join(); } _this4._order = _this4._order.concat(key.replace(/\s/g, '').split(',').map(function (k) { return '-' + k; })); }); return this; } /** Query Options **/ /** * Sets the number of results to skip before returning any results. * This is useful for pagination. * Default is to skip zero results. * @method skip * @param {Number} n the number of results to skip. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'skip', value: function (n) { if (typeof n !== 'number' || n < 0) { throw new Error('You can only skip by a positive number'); } this._skip = n; return this; } /** * Sets the limit of the number of results to return. The default limit is * 100, with a maximum of 1000 results being returned at a time. * @method limit * @param {Number} n the number of results to limit to. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'limit', value: function (n) { if (typeof n !== 'number') { throw new Error('You can only set the limit to a numeric value'); } this._limit = n; return this; } /** * Includes nested Parse.Objects for the provided key. You can use dot * notation to specify which fields in the included object are also fetched. * @method include * @param {String} key The name of the key to include. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'include', value: function () { var _this5 = this; for (var _len5 = arguments.length, keys = Array(_len5), _key6 = 0; _key6 < _len5; _key6++) { keys[_key6] = arguments[_key6]; } keys.forEach(function (key) { if (Array.isArray(key)) { _this5._include = _this5._include.concat(key); } else { _this5._include.push(key); } }); return this; } /** * Restricts the fields of the returned Parse.Objects to include only the * provided keys. If this is called multiple times, then all of the keys * specified in each of the calls will be included. * @method select * @param {Array} keys The names of the keys to include. * @return {Parse.Query} Returns the query, so you can chain this call. */ }, { key: 'select', value: function () { var _this6 = this; if (!this._select) { this._select = []; } for (var _len6 = arguments.length, keys = Array(_len6), _key7 = 0; _key7 < _len6; _key7++) { keys[_key7] = arguments[_key7]; } keys.forEach(function (key) { if (Array.isArray(key)) { _this6._select = _this6._select.concat(key); } else { _this6._select.push(key); } }); return this; } /** * Subscribe this query to get liveQuery updates * @method subscribe * @return {LiveQuerySubscription} Returns the liveQuerySubscription, it's an event emitter * which can be used to get liveQuery updates. */ }, { key: 'subscribe', value: function () { var controller = _CoreManager2.default.getLiveQueryController(); return controller.subscribe(this); } /** * Constructs a Parse.Query that is the OR of the passed in queries. For * example: * <pre>var compoundQuery = Parse.Query.or(query1, query2, query3);</pre> * * will create a compoundQuery that is an or of the query1, query2, and * query3. * @method or * @param {...Parse.Query} var_args The list of queries to OR. * @static * @return {Parse.Query} The query that is the OR of the passed in queries. */ }], [{ key: 'fromJSON', value: function (className, json) { var query = new ParseQuery(className); return query.withJSON(json); } }, { key: 'or', value: function () { var className = null; for (var _len7 = arguments.length, queries = Array(_len7), _key8 = 0; _key8 < _len7; _key8++) { queries[_key8] = arguments[_key8]; } queries.forEach(function (q) { if (!className) { className = q.className; } if (className !== q.className) { throw new Error('All queries must be for the same class.'); } }); var query = new ParseQuery(className); query._orQuery(queries); return query; } }]); return ParseQuery; }(); exports.default = ParseQuery; var DefaultController = { find: function (className, params, options) { var RESTController = _CoreManager2.default.getRESTController(); return RESTController.request('GET', 'classes/' + className, params, options); } }; _CoreManager2.default.setQueryController(DefaultController); },{"./CoreManager":3,"./ParseError":13,"./ParseGeoPoint":15,"./ParseObject":18,"./ParsePolygon":20,"./ParsePromise":21,"./encode":37,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/typeof":62}],23:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _ParseOp = _dereq_('./ParseOp'); var _ParseObject = _dereq_('./ParseObject'); var _ParseObject2 = _interopRequireDefault(_ParseObject); var _ParseQuery = _dereq_('./ParseQuery'); var _ParseQuery2 = _interopRequireDefault(_ParseQuery); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Creates a new Relation for the given parent object and key. This * constructor should rarely be used directly, but rather created by * Parse.Object.relation. * @class Parse.Relation * @constructor * @param {Parse.Object} parent The parent of this relation. * @param {String} key The key for this relation on the parent. * * <p> * A class that is used to access all of the children of a many-to-many * relationship. Each instance of Parse.Relation is associated with a * particular parent object and key. * </p> */ var ParseRelation = function () { function ParseRelation(parent, key) { (0, _classCallCheck3.default)(this, ParseRelation); this.parent = parent; this.key = key; this.targetClassName = null; } /** * Makes sure that this relation has the right parent and key. */ (0, _createClass3.default)(ParseRelation, [{ key: '_ensureParentAndKey', value: function (parent, key) { this.key = this.key || key; if (this.key !== key) { throw new Error('Internal Error. Relation retrieved from two different keys.'); } if (this.parent) { if (this.parent.className !== parent.className) { throw new Error('Internal Error. Relation retrieved from two different Objects.'); } if (this.parent.id) { if (this.parent.id !== parent.id) { throw new Error('Internal Error. Relation retrieved from two different Objects.'); } } else if (parent.id) { this.parent = parent; } } else { this.parent = parent; } } /** * Adds a Parse.Object or an array of Parse.Objects to the relation. * @method add * @param {} objects The item or items to add. */ }, { key: 'add', value: function (objects) { if (!Array.isArray(objects)) { objects = [objects]; } var change = new _ParseOp.RelationOp(objects, []); var parent = this.parent; if (!parent) { throw new Error('Cannot add to a Relation without a parent'); } parent.set(this.key, change); this.targetClassName = change._targetClassName; return parent; } /** * Removes a Parse.Object or an array of Parse.Objects from this relation. * @method remove * @param {} objects The item or items to remove. */ }, { key: 'remove', value: function (objects) { if (!Array.isArray(objects)) { objects = [objects]; } var change = new _ParseOp.RelationOp([], objects); if (!this.parent) { throw new Error('Cannot remove from a Relation without a parent'); } this.parent.set(this.key, change); this.targetClassName = change._targetClassName; } /** * Returns a JSON version of the object suitable for saving to disk. * @method toJSON * @return {Object} */ }, { key: 'toJSON', value: function () { return { __type: 'Relation', className: this.targetClassName }; } /** * Returns a Parse.Query that is limited to objects in this * relation. * @method query * @return {Parse.Query} */ }, { key: 'query', value: function () { var query; var parent = this.parent; if (!parent) { throw new Error('Cannot construct a query for a Relation without a parent'); } if (!this.targetClassName) { query = new _ParseQuery2.default(parent.className); query._extraOptions.redirectClassNameForKey = this.key; } else { query = new _ParseQuery2.default(this.targetClassName); } query._addCondition('$relatedTo', 'object', { __type: 'Pointer', className: parent.className, objectId: parent.id }); query._addCondition('$relatedTo', 'key', this.key); return query; } }]); return ParseRelation; }(); /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ exports.default = ParseRelation; },{"./ParseObject":18,"./ParseOp":19,"./ParseQuery":22,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58}],24:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _get2 = _dereq_('babel-runtime/helpers/get'); var _get3 = _interopRequireDefault(_get2); var _inherits2 = _dereq_('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _ParseACL = _dereq_('./ParseACL'); var _ParseACL2 = _interopRequireDefault(_ParseACL); var _ParseError = _dereq_('./ParseError'); var _ParseError2 = _interopRequireDefault(_ParseError); var _ParseObject2 = _dereq_('./ParseObject'); var _ParseObject3 = _interopRequireDefault(_ParseObject2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Represents a Role on the Parse server. Roles represent groupings of * Users for the purposes of granting permissions (e.g. specifying an ACL * for an Object). Roles are specified by their sets of child users and * child roles, all of which are granted any permissions that the parent * role has. * * <p>Roles must have a name (which cannot be changed after creation of the * role), and must specify an ACL.</p> * @class Parse.Role * @constructor * @param {String} name The name of the Role to create. * @param {Parse.ACL} acl The ACL for this role. Roles must have an ACL. * A Parse.Role is a local representation of a role persisted to the Parse * cloud. */ var ParseRole = function (_ParseObject) { (0, _inherits3.default)(ParseRole, _ParseObject); function ParseRole(name, acl) { (0, _classCallCheck3.default)(this, ParseRole); var _this = (0, _possibleConstructorReturn3.default)(this, (ParseRole.__proto__ || (0, _getPrototypeOf2.default)(ParseRole)).call(this, '_Role')); if (typeof name === 'string' && acl instanceof _ParseACL2.default) { _this.setName(name); _this.setACL(acl); } return _this; } /** * Gets the name of the role. You can alternatively call role.get("name") * * @method getName * @return {String} the name of the role. */ (0, _createClass3.default)(ParseRole, [{ key: 'getName', value: function () { var name = this.get('name'); if (name == null || typeof name === 'string') { return name; } return ''; } /** * Sets the name for a role. This value must be set before the role has * been saved to the server, and cannot be set once the role has been * saved. * * <p> * A role's name can only contain alphanumeric characters, _, -, and * spaces. * </p> * * <p>This is equivalent to calling role.set("name", name)</p> * * @method setName * @param {String} name The name of the role. * @param {Object} options Standard options object with success and error * callbacks. */ }, { key: 'setName', value: function (name, options) { return this.set('name', name, options); } /** * Gets the Parse.Relation for the Parse.Users that are direct * children of this role. These users are granted any privileges that this * role has been granted (e.g. read or write access through ACLs). You can * add or remove users from the role through this relation. * * <p>This is equivalent to calling role.relation("users")</p> * * @method getUsers * @return {Parse.Relation} the relation for the users belonging to this * role. */ }, { key: 'getUsers', value: function () { return this.relation('users'); } /** * Gets the Parse.Relation for the Parse.Roles that are direct * children of this role. These roles' users are granted any privileges that * this role has been granted (e.g. read or write access through ACLs). You * can add or remove child roles from this role through this relation. * * <p>This is equivalent to calling role.relation("roles")</p> * * @method getRoles * @return {Parse.Relation} the relation for the roles belonging to this * role. */ }, { key: 'getRoles', value: function () { return this.relation('roles'); } }, { key: 'validate', value: function (attrs, options) { var isInvalid = (0, _get3.default)(ParseRole.prototype.__proto__ || (0, _getPrototypeOf2.default)(ParseRole.prototype), 'validate', this).call(this, attrs, options); if (isInvalid) { return isInvalid; } if ('name' in attrs && attrs.name !== this.getName()) { var newName = attrs.name; if (this.id && this.id !== attrs.objectId) { // Check to see if the objectId being set matches this.id // This happens during a fetch -- the id is set before calling fetch // Let the name be set in this case return new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'A role\'s name can only be set before it has been saved.'); } if (typeof newName !== 'string') { return new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'A role\'s name must be a String.'); } if (!/^[0-9a-zA-Z\-_ ]+$/.test(newName)) { return new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'A role\'s name can be only contain alphanumeric characters, _, ' + '-, and spaces.'); } } return false; } }]); return ParseRole; }(_ParseObject3.default); /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ exports.default = ParseRole; _ParseObject3.default.registerSubclass('_Role', ParseRole); },{"./ParseACL":11,"./ParseError":13,"./ParseObject":18,"babel-runtime/core-js/object/get-prototype-of":51,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/get":59,"babel-runtime/helpers/inherits":60,"babel-runtime/helpers/possibleConstructorReturn":61}],25:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = _dereq_('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _CoreManager = _dereq_('./CoreManager'); var _CoreManager2 = _interopRequireDefault(_CoreManager); var _isRevocableSession = _dereq_('./isRevocableSession'); var _isRevocableSession2 = _interopRequireDefault(_isRevocableSession); var _ParseObject2 = _dereq_('./ParseObject'); var _ParseObject3 = _interopRequireDefault(_ParseObject2); var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); var _ParseUser = _dereq_('./ParseUser'); var _ParseUser2 = _interopRequireDefault(_ParseUser); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * @class Parse.Session * @constructor * * <p>A Parse.Session object is a local representation of a revocable session. * This class is a subclass of a Parse.Object, and retains the same * functionality of a Parse.Object.</p> */ var ParseSession = function (_ParseObject) { (0, _inherits3.default)(ParseSession, _ParseObject); function ParseSession(attributes) { (0, _classCallCheck3.default)(this, ParseSession); var _this = (0, _possibleConstructorReturn3.default)(this, (ParseSession.__proto__ || (0, _getPrototypeOf2.default)(ParseSession)).call(this, '_Session')); if (attributes && (typeof attributes === 'undefined' ? 'undefined' : (0, _typeof3.default)(attributes)) === 'object') { if (!_this.set(attributes || {})) { throw new Error('Can\'t create an invalid Session'); } } return _this; } /** * Returns the session token string. * @method getSessionToken * @return {String} */ (0, _createClass3.default)(ParseSession, [{ key: 'getSessionToken', value: function () { var token = this.get('sessionToken'); if (typeof token === 'string') { return token; } return ''; } }], [{ key: 'readOnlyAttributes', value: function () { return ['createdWith', 'expiresAt', 'installationId', 'restricted', 'sessionToken', 'user']; } /** * Retrieves the Session object for the currently logged in session. * @method current * @static * @return {Parse.Promise} A promise that is resolved with the Parse.Session * object after it has been fetched. If there is no current user, the * promise will be rejected. */ }, { key: 'current', value: function (options) { options = options || {}; var controller = _CoreManager2.default.getSessionController(); var sessionOptions = {}; if (options.hasOwnProperty('useMasterKey')) { sessionOptions.useMasterKey = options.useMasterKey; } return _ParseUser2.default.currentAsync().then(function (user) { if (!user) { return _ParsePromise2.default.error('There is no current user.'); } user.getSessionToken(); sessionOptions.sessionToken = user.getSessionToken(); return controller.getSession(sessionOptions); }); } /** * Determines whether the current session token is revocable. * This method is useful for migrating Express.js or Node.js web apps to * use revocable sessions. If you are migrating an app that uses the Parse * SDK in the browser only, please use Parse.User.enableRevocableSession() * instead, so that sessions can be automatically upgraded. * @method isCurrentSessionRevocable * @static * @return {Boolean} */ }, { key: 'isCurrentSessionRevocable', value: function () { var currentUser = _ParseUser2.default.current(); if (currentUser) { return (0, _isRevocableSession2.default)(currentUser.getSessionToken() || ''); } return false; } }]); return ParseSession; }(_ParseObject3.default); /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ exports.default = ParseSession; _ParseObject3.default.registerSubclass('_Session', ParseSession); var DefaultController = { getSession: function (options) { var RESTController = _CoreManager2.default.getRESTController(); var session = new ParseSession(); return RESTController.request('GET', 'sessions/me', {}, options).then(function (sessionData) { session._finishFetch(sessionData); session._setExisted(true); return session; }); } }; _CoreManager2.default.setSessionController(DefaultController); },{"./CoreManager":3,"./ParseObject":18,"./ParsePromise":21,"./ParseUser":26,"./isRevocableSession":40,"babel-runtime/core-js/object/get-prototype-of":51,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/inherits":60,"babel-runtime/helpers/possibleConstructorReturn":61,"babel-runtime/helpers/typeof":62}],26:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stringify = _dereq_('babel-runtime/core-js/json/stringify'); var _stringify2 = _interopRequireDefault(_stringify); var _defineProperty = _dereq_('babel-runtime/core-js/object/define-property'); var _defineProperty2 = _interopRequireDefault(_defineProperty); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _get2 = _dereq_('babel-runtime/helpers/get'); var _get3 = _interopRequireDefault(_get2); var _inherits2 = _dereq_('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _CoreManager = _dereq_('./CoreManager'); var _CoreManager2 = _interopRequireDefault(_CoreManager); var _isRevocableSession = _dereq_('./isRevocableSession'); var _isRevocableSession2 = _interopRequireDefault(_isRevocableSession); var _ParseError = _dereq_('./ParseError'); var _ParseError2 = _interopRequireDefault(_ParseError); var _ParseObject2 = _dereq_('./ParseObject'); var _ParseObject3 = _interopRequireDefault(_ParseObject2); var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); var _ParseSession = _dereq_('./ParseSession'); var _ParseSession2 = _interopRequireDefault(_ParseSession); var _Storage = _dereq_('./Storage'); var _Storage2 = _interopRequireDefault(_Storage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var CURRENT_USER_KEY = 'currentUser'; /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var canUseCurrentUser = !_CoreManager2.default.get('IS_NODE'); var currentUserCacheMatchesDisk = false; var currentUserCache = null; var authProviders = {}; /** * @class Parse.User * @constructor * * <p>A Parse.User object is a local representation of a user persisted to the * Parse cloud. This class is a subclass of a Parse.Object, and retains the * same functionality of a Parse.Object, but also extends it with various * user specific methods, like authentication, signing up, and validation of * uniqueness.</p> */ var ParseUser = function (_ParseObject) { (0, _inherits3.default)(ParseUser, _ParseObject); function ParseUser(attributes) { (0, _classCallCheck3.default)(this, ParseUser); var _this = (0, _possibleConstructorReturn3.default)(this, (ParseUser.__proto__ || (0, _getPrototypeOf2.default)(ParseUser)).call(this, '_User')); if (attributes && (typeof attributes === 'undefined' ? 'undefined' : (0, _typeof3.default)(attributes)) === 'object') { if (!_this.set(attributes || {})) { throw new Error('Can\'t create an invalid Parse User'); } } return _this; } /** * Request a revocable session token to replace the older style of token. * @method _upgradeToRevocableSession * @param {Object} options A Backbone-style options object. * @return {Parse.Promise} A promise that is resolved when the replacement * token has been fetched. */ (0, _createClass3.default)(ParseUser, [{ key: '_upgradeToRevocableSession', value: function (options) { options = options || {}; var upgradeOptions = {}; if (options.hasOwnProperty('useMasterKey')) { upgradeOptions.useMasterKey = options.useMasterKey; } var controller = _CoreManager2.default.getUserController(); return controller.upgradeToRevocableSession(this, upgradeOptions)._thenRunCallbacks(options); } /** * Unlike in the Android/iOS SDKs, logInWith is unnecessary, since you can * call linkWith on the user (even if it doesn't exist yet on the server). * @method _linkWith */ }, { key: '_linkWith', value: function (provider, options) { var _this2 = this; var authType; if (typeof provider === 'string') { authType = provider; provider = authProviders[provider]; } else { authType = provider.getAuthType(); } if (options && options.hasOwnProperty('authData')) { var authData = this.get('authData') || {}; if ((typeof authData === 'undefined' ? 'undefined' : (0, _typeof3.default)(authData)) !== 'object') { throw new Error('Invalid type: authData field should be an object'); } authData[authType] = options.authData; var controller = _CoreManager2.default.getUserController(); return controller.linkWith(this, authData)._thenRunCallbacks(options, this); } else { var promise = new _ParsePromise2.default(); provider.authenticate({ success: function (provider, result) { var opts = {}; opts.authData = result; if (options.success) { opts.success = options.success; } if (options.error) { opts.error = options.error; } _this2._linkWith(provider, opts).then(function () { promise.resolve(_this2); }, function (error) { promise.reject(error); }); }, error: function (provider, _error) { if (typeof options.error === 'function') { options.error(_this2, _error); } promise.reject(_error); } }); return promise; } } /** * Synchronizes auth data for a provider (e.g. puts the access token in the * right place to be used by the Facebook SDK). * @method _synchronizeAuthData */ }, { key: '_synchronizeAuthData', value: function (provider) { if (!this.isCurrent() || !provider) { return; } var authType; if (typeof provider === 'string') { authType = provider; provider = authProviders[authType]; } else { authType = provider.getAuthType(); } var authData = this.get('authData'); if (!provider || !authData || (typeof authData === 'undefined' ? 'undefined' : (0, _typeof3.default)(authData)) !== 'object') { return; } var success = provider.restoreAuthentication(authData[authType]); if (!success) { this._unlinkFrom(provider); } } /** * Synchronizes authData for all providers. * @method _synchronizeAllAuthData */ }, { key: '_synchronizeAllAuthData', value: function () { var authData = this.get('authData'); if ((typeof authData === 'undefined' ? 'undefined' : (0, _typeof3.default)(authData)) !== 'object') { return; } for (var key in authData) { this._synchronizeAuthData(key); } } /** * Removes null values from authData (which exist temporarily for * unlinking) * @method _cleanupAuthData */ }, { key: '_cleanupAuthData', value: function () { if (!this.isCurrent()) { return; } var authData = this.get('authData'); if ((typeof authData === 'undefined' ? 'undefined' : (0, _typeof3.default)(authData)) !== 'object') { return; } for (var key in authData) { if (!authData[key]) { delete authData[key]; } } } /** * Unlinks a user from a service. * @method _unlinkFrom */ }, { key: '_unlinkFrom', value: function (provider, options) { var _this3 = this; if (typeof provider === 'string') { provider = authProviders[provider]; } else { provider.getAuthType(); } return this._linkWith(provider, { authData: null }).then(function () { _this3._synchronizeAuthData(provider); return _ParsePromise2.default.as(_this3); })._thenRunCallbacks(options); } /** * Checks whether a user is linked to a service. * @method _isLinked */ }, { key: '_isLinked', value: function (provider) { var authType; if (typeof provider === 'string') { authType = provider; } else { authType = provider.getAuthType(); } var authData = this.get('authData') || {}; if ((typeof authData === 'undefined' ? 'undefined' : (0, _typeof3.default)(authData)) !== 'object') { return false; } return !!authData[authType]; } /** * Deauthenticates all providers. * @method _logOutWithAll */ }, { key: '_logOutWithAll', value: function () { var authData = this.get('authData'); if ((typeof authData === 'undefined' ? 'undefined' : (0, _typeof3.default)(authData)) !== 'object') { return; } for (var key in authData) { this._logOutWith(key); } } /** * Deauthenticates a single provider (e.g. removing access tokens from the * Facebook SDK). * @method _logOutWith */ }, { key: '_logOutWith', value: function (provider) { if (!this.isCurrent()) { return; } if (typeof provider === 'string') { provider = authProviders[provider]; } if (provider && provider.deauthenticate) { provider.deauthenticate(); } } /** * Class instance method used to maintain specific keys when a fetch occurs. * Used to ensure that the session token is not lost. */ }, { key: '_preserveFieldsOnFetch', value: function () { return { sessionToken: this.get('sessionToken') }; } /** * Returns true if <code>current</code> would return this user. * @method isCurrent * @return {Boolean} */ }, { key: 'isCurrent', value: function () { var current = ParseUser.current(); return !!current && current.id === this.id; } /** * Returns get("username"). * @method getUsername * @return {String} */ }, { key: 'getUsername', value: function () { var username = this.get('username'); if (username == null || typeof username === 'string') { return username; } return ''; } /** * Calls set("username", username, options) and returns the result. * @method setUsername * @param {String} username * @param {Object} options A Backbone-style options object. * @return {Boolean} */ }, { key: 'setUsername', value: function (username) { // Strip anonymity, even we do not support anonymous user in js SDK, we may // encounter anonymous user created by android/iOS in cloud code. var authData = this.get('authData'); if (authData && (typeof authData === 'undefined' ? 'undefined' : (0, _typeof3.default)(authData)) === 'object' && authData.hasOwnProperty('anonymous')) { // We need to set anonymous to null instead of deleting it in order to remove it from Parse. authData.anonymous = null; } this.set('username', username); } /** * Calls set("password", password, options) and returns the result. * @method setPassword * @param {String} password * @param {Object} options A Backbone-style options object. * @return {Boolean} */ }, { key: 'setPassword', value: function (password) { this.set('password', password); } /** * Returns get("email"). * @method getEmail * @return {String} */ }, { key: 'getEmail', value: function () { var email = this.get('email'); if (email == null || typeof email === 'string') { return email; } return ''; } /** * Calls set("email", email, options) and returns the result. * @method setEmail * @param {String} email * @param {Object} options A Backbone-style options object. * @return {Boolean} */ }, { key: 'setEmail', value: function (email) { this.set('email', email); } /** * Returns the session token for this user, if the user has been logged in, * or if it is the result of a query with the master key. Otherwise, returns * undefined. * @method getSessionToken * @return {String} the session token, or undefined */ }, { key: 'getSessionToken', value: function () { var token = this.get('sessionToken'); if (token == null || typeof token === 'string') { return token; } return ''; } /** * Checks whether this user is the current user and has been authenticated. * @method authenticated * @return (Boolean) whether this user is the current user and is logged in. */ }, { key: 'authenticated', value: function () { var current = ParseUser.current(); return !!this.get('sessionToken') && !!current && current.id === this.id; } /** * Signs up a new user. You should call this instead of save for * new Parse.Users. This will create a new Parse.User on the server, and * also persist the session on disk so that you can access the user using * <code>current</code>. * * <p>A username and password must be set before calling signUp.</p> * * <p>Calls options.success or options.error on completion.</p> * * @method signUp * @param {Object} attrs Extra fields to set on the new user, or null. * @param {Object} options A Backbone-style options object. * @return {Parse.Promise} A promise that is fulfilled when the signup * finishes. */ }, { key: 'signUp', value: function (attrs, options) { options = options || {}; var signupOptions = {}; if (options.hasOwnProperty('useMasterKey')) { signupOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('installationId')) { signupOptions.installationId = options.installationId; } var controller = _CoreManager2.default.getUserController(); return controller.signUp(this, attrs, signupOptions)._thenRunCallbacks(options, this); } /** * Logs in a Parse.User. On success, this saves the session to disk, * so you can retrieve the currently logged in user using * <code>current</code>. * * <p>A username and password must be set before calling logIn.</p> * * <p>Calls options.success or options.error on completion.</p> * * @method logIn * @param {Object} options A Backbone-style options object. * @return {Parse.Promise} A promise that is fulfilled with the user when * the login is complete. */ }, { key: 'logIn', value: function (options) { options = options || {}; var loginOptions = {}; if (options.hasOwnProperty('useMasterKey')) { loginOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('installationId')) { loginOptions.installationId = options.installationId; } var controller = _CoreManager2.default.getUserController(); return controller.logIn(this, loginOptions)._thenRunCallbacks(options, this); } /** * Wrap the default save behavior with functionality to save to local * storage if this is current user. */ }, { key: 'save', value: function () { var _this4 = this; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return (0, _get3.default)(ParseUser.prototype.__proto__ || (0, _getPrototypeOf2.default)(ParseUser.prototype), 'save', this).apply(this, args).then(function () { if (_this4.isCurrent()) { return _CoreManager2.default.getUserController().updateUserOnDisk(_this4); } return _this4; }); } /** * Wrap the default destroy behavior with functionality that logs out * the current user when it is destroyed */ }, { key: 'destroy', value: function () { var _this5 = this; for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return (0, _get3.default)(ParseUser.prototype.__proto__ || (0, _getPrototypeOf2.default)(ParseUser.prototype), 'destroy', this).apply(this, args).then(function () { if (_this5.isCurrent()) { return _CoreManager2.default.getUserController().removeUserFromDisk(); } return _this5; }); } /** * Wrap the default fetch behavior with functionality to save to local * storage if this is current user. */ }, { key: 'fetch', value: function () { var _this6 = this; for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return (0, _get3.default)(ParseUser.prototype.__proto__ || (0, _getPrototypeOf2.default)(ParseUser.prototype), 'fetch', this).apply(this, args).then(function () { if (_this6.isCurrent()) { return _CoreManager2.default.getUserController().updateUserOnDisk(_this6); } return _this6; }); } }], [{ key: 'readOnlyAttributes', value: function () { return ['sessionToken']; } /** * Adds functionality to the existing Parse.User class * @method extend * @param {Object} protoProps A set of properties to add to the prototype * @param {Object} classProps A set of static properties to add to the class * @static * @return {Class} The newly extended Parse.User class */ }, { key: 'extend', value: function (protoProps, classProps) { if (protoProps) { for (var prop in protoProps) { if (prop !== 'className') { (0, _defineProperty2.default)(ParseUser.prototype, prop, { value: protoProps[prop], enumerable: false, writable: true, configurable: true }); } } } if (classProps) { for (var prop in classProps) { if (prop !== 'className') { (0, _defineProperty2.default)(ParseUser, prop, { value: classProps[prop], enumerable: false, writable: true, configurable: true }); } } } return ParseUser; } /** * Retrieves the currently logged in ParseUser with a valid session, * either from memory or localStorage, if necessary. * @method current * @static * @return {Parse.Object} The currently logged in Parse.User. */ }, { key: 'current', value: function () { if (!canUseCurrentUser) { return null; } var controller = _CoreManager2.default.getUserController(); return controller.currentUser(); } /** * Retrieves the currently logged in ParseUser from asynchronous Storage. * @method currentAsync * @static * @return {Parse.Promise} A Promise that is resolved with the currently * logged in Parse User */ }, { key: 'currentAsync', value: function () { if (!canUseCurrentUser) { return _ParsePromise2.default.as(null); } var controller = _CoreManager2.default.getUserController(); return controller.currentUserAsync(); } /** * Signs up a new user with a username (or email) and password. * This will create a new Parse.User on the server, and also persist the * session in localStorage so that you can access the user using * {@link #current}. * * <p>Calls options.success or options.error on completion.</p> * * @method signUp * @param {String} username The username (or email) to sign up with. * @param {String} password The password to sign up with. * @param {Object} attrs Extra fields to set on the new user. * @param {Object} options A Backbone-style options object. * @static * @return {Parse.Promise} A promise that is fulfilled with the user when * the signup completes. */ }, { key: 'signUp', value: function (username, password, attrs, options) { attrs = attrs || {}; attrs.username = username; attrs.password = password; var user = new ParseUser(attrs); return user.signUp({}, options); } /** * Logs in a user with a username (or email) and password. On success, this * saves the session to disk, so you can retrieve the currently logged in * user using <code>current</code>. * * <p>Calls options.success or options.error on completion.</p> * * @method logIn * @param {String} username The username (or email) to log in with. * @param {String} password The password to log in with. * @param {Object} options A Backbone-style options object. * @static * @return {Parse.Promise} A promise that is fulfilled with the user when * the login completes. */ }, { key: 'logIn', value: function (username, password, options) { if (typeof username !== 'string') { return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'Username must be a string.')); } else if (typeof password !== 'string') { return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'Password must be a string.')); } var user = new ParseUser(); user._finishFetch({ username: username, password: password }); return user.logIn(options); } /** * Logs in a user with a session token. On success, this saves the session * to disk, so you can retrieve the currently logged in user using * <code>current</code>. * * <p>Calls options.success or options.error on completion.</p> * * @method become * @param {String} sessionToken The sessionToken to log in with. * @param {Object} options A Backbone-style options object. * @static * @return {Parse.Promise} A promise that is fulfilled with the user when * the login completes. */ }, { key: 'become', value: function (sessionToken, options) { if (!canUseCurrentUser) { throw new Error('It is not memory-safe to become a user in a server environment'); } options = options || {}; var becomeOptions = { sessionToken: sessionToken }; if (options.hasOwnProperty('useMasterKey')) { becomeOptions.useMasterKey = options.useMasterKey; } var controller = _CoreManager2.default.getUserController(); return controller.become(becomeOptions)._thenRunCallbacks(options); } }, { key: 'logInWith', value: function (provider, options) { return ParseUser._logInWith(provider, options); } /** * Logs out the currently logged in user session. This will remove the * session from disk, log out of linked services, and future calls to * <code>current</code> will return <code>null</code>. * @method logOut * @static * @return {Parse.Promise} A promise that is resolved when the session is * destroyed on the server. */ }, { key: 'logOut', value: function () { if (!canUseCurrentUser) { throw new Error('There is no current user on a node.js server environment.'); } var controller = _CoreManager2.default.getUserController(); return controller.logOut(); } /** * Requests a password reset email to be sent to the specified email address * associated with the user account. This email allows the user to securely * reset their password on the Parse site. * * <p>Calls options.success or options.error on completion.</p> * * @method requestPasswordReset * @param {String} email The email address associated with the user that * forgot their password. * @param {Object} options A Backbone-style options object. * @static */ }, { key: 'requestPasswordReset', value: function (email, options) { options = options || {}; var requestOptions = {}; if (options.hasOwnProperty('useMasterKey')) { requestOptions.useMasterKey = options.useMasterKey; } var controller = _CoreManager2.default.getUserController(); return controller.requestPasswordReset(email, requestOptions)._thenRunCallbacks(options); } /** * Allow someone to define a custom User class without className * being rewritten to _User. The default behavior is to rewrite * User to _User for legacy reasons. This allows developers to * override that behavior. * * @method allowCustomUserClass * @param {Boolean} isAllowed Whether or not to allow custom User class * @static */ }, { key: 'allowCustomUserClass', value: function (isAllowed) { _CoreManager2.default.set('PERFORM_USER_REWRITE', !isAllowed); } /** * Allows a legacy application to start using revocable sessions. If the * current session token is not revocable, a request will be made for a new, * revocable session. * It is not necessary to call this method from cloud code unless you are * handling user signup or login from the server side. In a cloud code call, * this function will not attempt to upgrade the current token. * @method enableRevocableSession * @param {Object} options A Backbone-style options object. * @static * @return {Parse.Promise} A promise that is resolved when the process has * completed. If a replacement session token is requested, the promise * will be resolved after a new token has been fetched. */ }, { key: 'enableRevocableSession', value: function (options) { options = options || {}; _CoreManager2.default.set('FORCE_REVOCABLE_SESSION', true); if (canUseCurrentUser) { var current = ParseUser.current(); if (current) { return current._upgradeToRevocableSession(options); } } return _ParsePromise2.default.as()._thenRunCallbacks(options); } /** * Enables the use of become or the current user in a server * environment. These features are disabled by default, since they depend on * global objects that are not memory-safe for most servers. * @method enableUnsafeCurrentUser * @static */ }, { key: 'enableUnsafeCurrentUser', value: function () { canUseCurrentUser = true; } /** * Disables the use of become or the current user in any environment. * These features are disabled on servers by default, since they depend on * global objects that are not memory-safe for most servers. * @method disableUnsafeCurrentUser * @static */ }, { key: 'disableUnsafeCurrentUser', value: function () { canUseCurrentUser = false; } }, { key: '_registerAuthenticationProvider', value: function (provider) { authProviders[provider.getAuthType()] = provider; // Synchronize the current user with the auth provider. ParseUser.currentAsync().then(function (current) { if (current) { current._synchronizeAuthData(provider.getAuthType()); } }); } }, { key: '_logInWith', value: function (provider, options) { var user = new ParseUser(); return user._linkWith(provider, options); } }, { key: '_clearCache', value: function () { currentUserCache = null; currentUserCacheMatchesDisk = false; } }, { key: '_setCurrentUserCache', value: function (user) { currentUserCache = user; } }]); return ParseUser; }(_ParseObject3.default); exports.default = ParseUser; _ParseObject3.default.registerSubclass('_User', ParseUser); var DefaultController = { updateUserOnDisk: function (user) { var path = _Storage2.default.generatePath(CURRENT_USER_KEY); var json = user.toJSON(); json.className = '_User'; return _Storage2.default.setItemAsync(path, (0, _stringify2.default)(json)).then(function () { return user; }); }, removeUserFromDisk: function () { var path = _Storage2.default.generatePath(CURRENT_USER_KEY); currentUserCacheMatchesDisk = true; currentUserCache = null; return _Storage2.default.removeItemAsync(path); }, setCurrentUser: function (user) { currentUserCache = user; user._cleanupAuthData(); user._synchronizeAllAuthData(); return DefaultController.updateUserOnDisk(user); }, currentUser: function () { if (currentUserCache) { return currentUserCache; } if (currentUserCacheMatchesDisk) { return null; } if (_Storage2.default.async()) { throw new Error('Cannot call currentUser() when using a platform with an async ' + 'storage system. Call currentUserAsync() instead.'); } var path = _Storage2.default.generatePath(CURRENT_USER_KEY); var userData = _Storage2.default.getItem(path); currentUserCacheMatchesDisk = true; if (!userData) { currentUserCache = null; return null; } userData = JSON.parse(userData); if (!userData.className) { userData.className = '_User'; } if (userData._id) { if (userData.objectId !== userData._id) { userData.objectId = userData._id; } delete userData._id; } if (userData._sessionToken) { userData.sessionToken = userData._sessionToken; delete userData._sessionToken; } var current = _ParseObject3.default.fromJSON(userData); currentUserCache = current; current._synchronizeAllAuthData(); return current; }, currentUserAsync: function () { if (currentUserCache) { return _ParsePromise2.default.as(currentUserCache); } if (currentUserCacheMatchesDisk) { return _ParsePromise2.default.as(null); } var path = _Storage2.default.generatePath(CURRENT_USER_KEY); return _Storage2.default.getItemAsync(path).then(function (userData) { currentUserCacheMatchesDisk = true; if (!userData) { currentUserCache = null; return _ParsePromise2.default.as(null); } userData = JSON.parse(userData); if (!userData.className) { userData.className = '_User'; } if (userData._id) { if (userData.objectId !== userData._id) { userData.objectId = userData._id; } delete userData._id; } if (userData._sessionToken) { userData.sessionToken = userData._sessionToken; delete userData._sessionToken; } var current = _ParseObject3.default.fromJSON(userData); currentUserCache = current; current._synchronizeAllAuthData(); return _ParsePromise2.default.as(current); }); }, signUp: function (user, attrs, options) { var username = attrs && attrs.username || user.get('username'); var password = attrs && attrs.password || user.get('password'); if (!username || !username.length) { return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'Cannot sign up user with an empty name.')); } if (!password || !password.length) { return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'Cannot sign up user with an empty password.')); } return user.save(attrs, options).then(function () { // Clear the password field user._finishFetch({ password: undefined }); if (canUseCurrentUser) { return DefaultController.setCurrentUser(user); } return user; }); }, logIn: function (user, options) { var RESTController = _CoreManager2.default.getRESTController(); var stateController = _CoreManager2.default.getObjectStateController(); var auth = { username: user.get('username'), password: user.get('password') }; return RESTController.request('GET', 'login', auth, options).then(function (response) { user._migrateId(response.objectId); user._setExisted(true); stateController.setPendingOp(user._getStateIdentifier(), 'username', undefined); stateController.setPendingOp(user._getStateIdentifier(), 'password', undefined); response.password = undefined; user._finishFetch(response); if (!canUseCurrentUser) { // We can't set the current user, so just return the one we logged in return _ParsePromise2.default.as(user); } return DefaultController.setCurrentUser(user); }); }, become: function (options) { var user = new ParseUser(); var RESTController = _CoreManager2.default.getRESTController(); return RESTController.request('GET', 'users/me', {}, options).then(function (response) { user._finishFetch(response); user._setExisted(true); return DefaultController.setCurrentUser(user); }); }, logOut: function () { return DefaultController.currentUserAsync().then(function (currentUser) { var path = _Storage2.default.generatePath(CURRENT_USER_KEY); var promise = _Storage2.default.removeItemAsync(path); var RESTController = _CoreManager2.default.getRESTController(); if (currentUser !== null) { var currentSession = currentUser.getSessionToken(); if (currentSession && (0, _isRevocableSession2.default)(currentSession)) { promise = promise.then(function () { return RESTController.request('POST', 'logout', {}, { sessionToken: currentSession }); }); } currentUser._logOutWithAll(); currentUser._finishFetch({ sessionToken: undefined }); } currentUserCacheMatchesDisk = true; currentUserCache = null; return promise; }); }, requestPasswordReset: function (email, options) { var RESTController = _CoreManager2.default.getRESTController(); return RESTController.request('POST', 'requestPasswordReset', { email: email }, options); }, upgradeToRevocableSession: function (user, options) { var token = user.getSessionToken(); if (!token) { return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.SESSION_MISSING, 'Cannot upgrade a user with no session token')); } options.sessionToken = token; var RESTController = _CoreManager2.default.getRESTController(); return RESTController.request('POST', 'upgradeToRevocableSession', {}, options).then(function (result) { var session = new _ParseSession2.default(); session._finishFetch(result); user._finishFetch({ sessionToken: session.getSessionToken() }); if (user.isCurrent()) { return DefaultController.setCurrentUser(user); } return _ParsePromise2.default.as(user); }); }, linkWith: function (user, authData) { return user.save({ authData: authData }).then(function () { if (canUseCurrentUser) { return DefaultController.setCurrentUser(user); } return user; }); } }; _CoreManager2.default.setUserController(DefaultController); },{"./CoreManager":3,"./ParseError":13,"./ParseObject":18,"./ParsePromise":21,"./ParseSession":25,"./Storage":30,"./isRevocableSession":40,"babel-runtime/core-js/json/stringify":45,"babel-runtime/core-js/object/define-property":48,"babel-runtime/core-js/object/get-prototype-of":51,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/get":59,"babel-runtime/helpers/inherits":60,"babel-runtime/helpers/possibleConstructorReturn":61,"babel-runtime/helpers/typeof":62}],27:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); exports.send = send; var _CoreManager = _dereq_('./CoreManager'); var _CoreManager2 = _interopRequireDefault(_CoreManager); var _ParseQuery = _dereq_('./ParseQuery'); var _ParseQuery2 = _interopRequireDefault(_ParseQuery); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Contains functions to deal with Push in Parse. * @class Parse.Push * @static */ /** * Sends a push notification. * @method send * @param {Object} data - The data of the push notification. Valid fields * are: * <ol> * <li>channels - An Array of channels to push to.</li> * <li>push_time - A Date object for when to send the push.</li> * <li>expiration_time - A Date object for when to expire * the push.</li> * <li>expiration_interval - The seconds from now to expire the push.</li> * <li>where - A Parse.Query over Parse.Installation that is used to match * a set of installations to push to.</li> * <li>data - The data to send as part of the push</li> * <ol> * @param {Object} options An object that has an optional success function, * that takes no arguments and will be called on a successful push, and * an error function that takes a Parse.Error and will be called if the push * failed. * @return {Parse.Promise} A promise that is fulfilled when the push request * completes. */ /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function send(data, options) { options = options || {}; if (data.where && data.where instanceof _ParseQuery2.default) { data.where = data.where.toJSON().where; } if (data.push_time && (0, _typeof3.default)(data.push_time) === 'object') { data.push_time = data.push_time.toJSON(); } if (data.expiration_time && (0, _typeof3.default)(data.expiration_time) === 'object') { data.expiration_time = data.expiration_time.toJSON(); } if (data.expiration_time && data.expiration_interval) { throw new Error('expiration_time and expiration_interval cannot both be set.'); } return _CoreManager2.default.getPushController().send(data, { useMasterKey: options.useMasterKey })._thenRunCallbacks(options); } var DefaultController = { send: function (data, options) { var RESTController = _CoreManager2.default.getRESTController(); var request = RESTController.request('POST', 'push', data, { useMasterKey: !!options.useMasterKey }); return request._thenRunCallbacks(options); } }; _CoreManager2.default.setPushController(DefaultController); },{"./CoreManager":3,"./ParseQuery":22,"babel-runtime/helpers/typeof":62}],28:[function(_dereq_,module,exports){ (function (process){ 'use strict'; var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); var _stringify = _dereq_('babel-runtime/core-js/json/stringify'); var _stringify2 = _interopRequireDefault(_stringify); var _CoreManager = _dereq_('./CoreManager'); var _CoreManager2 = _interopRequireDefault(_CoreManager); var _ParseError = _dereq_('./ParseError'); var _ParseError2 = _interopRequireDefault(_ParseError); var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); var _Storage = _dereq_('./Storage'); var _Storage2 = _interopRequireDefault(_Storage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var XHR = null; if (typeof XMLHttpRequest !== 'undefined') { XHR = XMLHttpRequest; } var useXDomainRequest = false; if (typeof XDomainRequest !== 'undefined' && !('withCredentials' in new XMLHttpRequest())) { useXDomainRequest = true; } function ajaxIE9(method, url, data) { var promise = new _ParsePromise2.default(); var xdr = new XDomainRequest(); xdr.onload = function () { var response; try { response = JSON.parse(xdr.responseText); } catch (e) { promise.reject(e); } if (response) { promise.resolve(response); } }; xdr.onerror = xdr.ontimeout = function () { // Let's fake a real error message. var fakeResponse = { responseText: (0, _stringify2.default)({ code: _ParseError2.default.X_DOMAIN_REQUEST, error: 'IE\'s XDomainRequest does not supply error info.' }) }; promise.reject(fakeResponse); }; xdr.onprogress = function () {}; xdr.open(method, url); xdr.send(data); return promise; } var RESTController = { ajax: function (method, url, data, headers) { if (useXDomainRequest) { return ajaxIE9(method, url, data, headers); } var promise = new _ParsePromise2.default(); var attempts = 0; (function dispatch() { if (XHR == null) { throw new Error('Cannot make a request: No definition of XMLHttpRequest was found.'); } var handled = false; var xhr = new XHR(); xhr.onreadystatechange = function () { if (xhr.readyState !== 4 || handled) { return; } handled = true; if (xhr.status >= 200 && xhr.status < 300) { var response; try { response = JSON.parse(xhr.responseText); } catch (e) { promise.reject(e.toString()); } if (response) { promise.resolve(response, xhr.status, xhr); } } else if (xhr.status >= 500 || xhr.status === 0) { // retry on 5XX or node-xmlhttprequest error if (++attempts < _CoreManager2.default.get('REQUEST_ATTEMPT_LIMIT')) { // Exponentially-growing random delay var delay = Math.round(Math.random() * 125 * Math.pow(2, attempts)); setTimeout(dispatch, delay); } else if (xhr.status === 0) { promise.reject('Unable to connect to the Parse API'); } else { // After the retry limit is reached, fail promise.reject(xhr); } } else { promise.reject(xhr); } }; headers = headers || {}; if (typeof headers['Content-Type'] !== 'string') { headers['Content-Type'] = 'text/plain'; // Avoid pre-flight } if (_CoreManager2.default.get('IS_NODE')) { headers['User-Agent'] = 'Parse/' + _CoreManager2.default.get('VERSION') + ' (NodeJS ' + process.versions.node + ')'; } xhr.open(method, url, true); for (var h in headers) { xhr.setRequestHeader(h, headers[h]); } xhr.send(data); })(); return promise; }, request: function (method, path, data, options) { options = options || {}; var url = _CoreManager2.default.get('SERVER_URL'); if (url[url.length - 1] !== '/') { url += '/'; } url += path; var payload = {}; if (data && (typeof data === 'undefined' ? 'undefined' : (0, _typeof3.default)(data)) === 'object') { for (var k in data) { payload[k] = data[k]; } } if (method !== 'POST') { payload._method = method; method = 'POST'; } payload._ApplicationId = _CoreManager2.default.get('APPLICATION_ID'); var jsKey = _CoreManager2.default.get('JAVASCRIPT_KEY'); if (jsKey) { payload._JavaScriptKey = jsKey; } payload._ClientVersion = _CoreManager2.default.get('VERSION'); var useMasterKey = options.useMasterKey; if (typeof useMasterKey === 'undefined') { useMasterKey = _CoreManager2.default.get('USE_MASTER_KEY'); } if (useMasterKey) { if (_CoreManager2.default.get('MASTER_KEY')) { delete payload._JavaScriptKey; payload._MasterKey = _CoreManager2.default.get('MASTER_KEY'); } else { throw new Error('Cannot use the Master Key, it has not been provided.'); } } if (_CoreManager2.default.get('FORCE_REVOCABLE_SESSION')) { payload._RevocableSession = '1'; } var installationId = options.installationId; var installationIdPromise; if (installationId && typeof installationId === 'string') { installationIdPromise = _ParsePromise2.default.as(installationId); } else { var installationController = _CoreManager2.default.getInstallationController(); installationIdPromise = installationController.currentInstallationId(); } return installationIdPromise.then(function (iid) { payload._InstallationId = iid; var userController = _CoreManager2.default.getUserController(); if (options && typeof options.sessionToken === 'string') { return _ParsePromise2.default.as(options.sessionToken); } else if (userController) { return userController.currentUserAsync().then(function (user) { if (user) { return _ParsePromise2.default.as(user.getSessionToken()); } return _ParsePromise2.default.as(null); }); } return _ParsePromise2.default.as(null); }).then(function (token) { if (token) { payload._SessionToken = token; } var payloadString = (0, _stringify2.default)(payload); return RESTController.ajax(method, url, payloadString); }).then(null, function (response) { // Transform the error into an instance of ParseError by trying to parse // the error string as JSON var error; if (response && response.responseText) { try { var errorJSON = JSON.parse(response.responseText); error = new _ParseError2.default(errorJSON.code, errorJSON.error); } catch (e) { // If we fail to parse the error text, that's okay. error = new _ParseError2.default(_ParseError2.default.INVALID_JSON, 'Received an error with invalid JSON from Parse: ' + response.responseText); } } else { error = new _ParseError2.default(_ParseError2.default.CONNECTION_FAILED, 'XMLHttpRequest failed: ' + (0, _stringify2.default)(response)); } return _ParsePromise2.default.error(error); }); }, _setXHR: function (xhr) { XHR = xhr; } }; module.exports = RESTController; }).call(this,_dereq_('_process')) },{"./CoreManager":3,"./ParseError":13,"./ParsePromise":21,"./Storage":30,"_process":63,"babel-runtime/core-js/json/stringify":45,"babel-runtime/helpers/typeof":62}],29:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getState = getState; exports.initializeState = initializeState; exports.removeState = removeState; exports.getServerData = getServerData; exports.setServerData = setServerData; exports.getPendingOps = getPendingOps; exports.setPendingOp = setPendingOp; exports.pushPendingState = pushPendingState; exports.popPendingState = popPendingState; exports.mergeFirstPendingState = mergeFirstPendingState; exports.getObjectCache = getObjectCache; exports.estimateAttribute = estimateAttribute; exports.estimateAttributes = estimateAttributes; exports.commitServerChanges = commitServerChanges; exports.enqueueTask = enqueueTask; exports.clearAllState = clearAllState; exports.duplicateState = duplicateState; var _ObjectStateMutations = _dereq_('./ObjectStateMutations'); var ObjectStateMutations = _interopRequireWildcard(_ObjectStateMutations); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } var objectState = {}; /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function getState(obj) { var classData = objectState[obj.className]; if (classData) { return classData[obj.id] || null; } return null; } function initializeState(obj, initial) { var state = getState(obj); if (state) { return state; } if (!objectState[obj.className]) { objectState[obj.className] = {}; } if (!initial) { initial = ObjectStateMutations.defaultState(); } state = objectState[obj.className][obj.id] = initial; return state; } function removeState(obj) { var state = getState(obj); if (state === null) { return null; } delete objectState[obj.className][obj.id]; return state; } function getServerData(obj) { var state = getState(obj); if (state) { return state.serverData; } return {}; } function setServerData(obj, attributes) { var serverData = initializeState(obj).serverData; ObjectStateMutations.setServerData(serverData, attributes); } function getPendingOps(obj) { var state = getState(obj); if (state) { return state.pendingOps; } return [{}]; } function setPendingOp(obj, attr, op) { var pendingOps = initializeState(obj).pendingOps; ObjectStateMutations.setPendingOp(pendingOps, attr, op); } function pushPendingState(obj) { var pendingOps = initializeState(obj).pendingOps; ObjectStateMutations.pushPendingState(pendingOps); } function popPendingState(obj) { var pendingOps = initializeState(obj).pendingOps; return ObjectStateMutations.popPendingState(pendingOps); } function mergeFirstPendingState(obj) { var pendingOps = getPendingOps(obj); ObjectStateMutations.mergeFirstPendingState(pendingOps); } function getObjectCache(obj) { var state = getState(obj); if (state) { return state.objectCache; } return {}; } function estimateAttribute(obj, attr) { var serverData = getServerData(obj); var pendingOps = getPendingOps(obj); return ObjectStateMutations.estimateAttribute(serverData, pendingOps, obj.className, obj.id, attr); } function estimateAttributes(obj) { var serverData = getServerData(obj); var pendingOps = getPendingOps(obj); return ObjectStateMutations.estimateAttributes(serverData, pendingOps, obj.className, obj.id); } function commitServerChanges(obj, changes) { var state = initializeState(obj); ObjectStateMutations.commitServerChanges(state.serverData, state.objectCache, changes); } function enqueueTask(obj, task) { var state = initializeState(obj); return state.tasks.enqueue(task); } function clearAllState() { objectState = {}; } function duplicateState(source, dest) { dest.id = source.id; } },{"./ObjectStateMutations":9}],30:[function(_dereq_,module,exports){ 'use strict'; var _CoreManager = _dereq_('./CoreManager'); var _CoreManager2 = _interopRequireDefault(_CoreManager); var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var Storage = { async: function () { var controller = _CoreManager2.default.getStorageController(); return !!controller.async; }, getItem: function (path) { var controller = _CoreManager2.default.getStorageController(); if (controller.async === 1) { throw new Error('Synchronous storage is not supported by the current storage controller'); } return controller.getItem(path); }, getItemAsync: function (path) { var controller = _CoreManager2.default.getStorageController(); if (controller.async === 1) { return controller.getItemAsync(path); } return _ParsePromise2.default.as(controller.getItem(path)); }, setItem: function (path, value) { var controller = _CoreManager2.default.getStorageController(); if (controller.async === 1) { throw new Error('Synchronous storage is not supported by the current storage controller'); } return controller.setItem(path, value); }, setItemAsync: function (path, value) { var controller = _CoreManager2.default.getStorageController(); if (controller.async === 1) { return controller.setItemAsync(path, value); } return _ParsePromise2.default.as(controller.setItem(path, value)); }, removeItem: function (path) { var controller = _CoreManager2.default.getStorageController(); if (controller.async === 1) { throw new Error('Synchronous storage is not supported by the current storage controller'); } return controller.removeItem(path); }, removeItemAsync: function (path) { var controller = _CoreManager2.default.getStorageController(); if (controller.async === 1) { return controller.removeItemAsync(path); } return _ParsePromise2.default.as(controller.removeItem(path)); }, generatePath: function (path) { if (!_CoreManager2.default.get('APPLICATION_ID')) { throw new Error('You need to call Parse.initialize before using Parse.'); } if (typeof path !== 'string') { throw new Error('Tried to get a Storage path that was not a String.'); } if (path[0] === '/') { path = path.substr(1); } return 'Parse/' + _CoreManager2.default.get('APPLICATION_ID') + '/' + path; }, _clear: function () { var controller = _CoreManager2.default.getStorageController(); if (controller.hasOwnProperty('clear')) { controller.clear(); } } }; module.exports = Storage; _CoreManager2.default.setStorageController(_dereq_('./StorageController.browser')); },{"./CoreManager":3,"./ParsePromise":21,"./StorageController.browser":31}],31:[function(_dereq_,module,exports){ 'use strict'; var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var StorageController = { async: 0, getItem: function (path) { return localStorage.getItem(path); }, setItem: function (path, value) { try { localStorage.setItem(path, value); } catch (e) { // Quota exceeded, possibly due to Safari Private Browsing mode } }, removeItem: function (path) { localStorage.removeItem(path); }, clear: function () { localStorage.clear(); } }; /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ module.exports = StorageController; },{"./ParsePromise":21}],32:[function(_dereq_,module,exports){ 'use strict'; var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _ParsePromise = _dereq_('./ParsePromise'); var _ParsePromise2 = _interopRequireDefault(_ParsePromise); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TaskQueue = function () { function TaskQueue() { (0, _classCallCheck3.default)(this, TaskQueue); this.queue = []; } (0, _createClass3.default)(TaskQueue, [{ key: 'enqueue', value: function (task) { var _this = this; var taskComplete = new _ParsePromise2.default(); this.queue.push({ task: task, _completion: taskComplete }); if (this.queue.length === 1) { task().then(function () { _this._dequeue(); taskComplete.resolve(); }, function (error) { _this._dequeue(); taskComplete.reject(error); }); } return taskComplete; } }, { key: '_dequeue', value: function () { var _this2 = this; this.queue.shift(); if (this.queue.length) { var next = this.queue[0]; next.task().then(function () { _this2._dequeue(); next._completion.resolve(); }, function (error) { _this2._dequeue(); next._completion.reject(error); }); } } }]); return TaskQueue; }(); /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ module.exports = TaskQueue; },{"./ParsePromise":21,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58}],33:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _weakMap = _dereq_('babel-runtime/core-js/weak-map'); var _weakMap2 = _interopRequireDefault(_weakMap); exports.getState = getState; exports.initializeState = initializeState; exports.removeState = removeState; exports.getServerData = getServerData; exports.setServerData = setServerData; exports.getPendingOps = getPendingOps; exports.setPendingOp = setPendingOp; exports.pushPendingState = pushPendingState; exports.popPendingState = popPendingState; exports.mergeFirstPendingState = mergeFirstPendingState; exports.getObjectCache = getObjectCache; exports.estimateAttribute = estimateAttribute; exports.estimateAttributes = estimateAttributes; exports.commitServerChanges = commitServerChanges; exports.enqueueTask = enqueueTask; exports.duplicateState = duplicateState; exports.clearAllState = clearAllState; var _ObjectStateMutations = _dereq_('./ObjectStateMutations'); var ObjectStateMutations = _interopRequireWildcard(_ObjectStateMutations); var _TaskQueue = _dereq_('./TaskQueue'); var _TaskQueue2 = _interopRequireDefault(_TaskQueue); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var objectState = new _weakMap2.default(); function getState(obj) { var classData = objectState.get(obj); return classData || null; } function initializeState(obj, initial) { var state = getState(obj); if (state) { return state; } if (!initial) { initial = { serverData: {}, pendingOps: [{}], objectCache: {}, tasks: new _TaskQueue2.default(), existed: false }; } state = initial; objectState.set(obj, state); return state; } function removeState(obj) { var state = getState(obj); if (state === null) { return null; } objectState.delete(obj); return state; } function getServerData(obj) { var state = getState(obj); if (state) { return state.serverData; } return {}; } function setServerData(obj, attributes) { var serverData = initializeState(obj).serverData; ObjectStateMutations.setServerData(serverData, attributes); } function getPendingOps(obj) { var state = getState(obj); if (state) { return state.pendingOps; } return [{}]; } function setPendingOp(obj, attr, op) { var pendingOps = initializeState(obj).pendingOps; ObjectStateMutations.setPendingOp(pendingOps, attr, op); } function pushPendingState(obj) { var pendingOps = initializeState(obj).pendingOps; ObjectStateMutations.pushPendingState(pendingOps); } function popPendingState(obj) { var pendingOps = initializeState(obj).pendingOps; return ObjectStateMutations.popPendingState(pendingOps); } function mergeFirstPendingState(obj) { var pendingOps = getPendingOps(obj); ObjectStateMutations.mergeFirstPendingState(pendingOps); } function getObjectCache(obj) { var state = getState(obj); if (state) { return state.objectCache; } return {}; } function estimateAttribute(obj, attr) { var serverData = getServerData(obj); var pendingOps = getPendingOps(obj); return ObjectStateMutations.estimateAttribute(serverData, pendingOps, obj.className, obj.id, attr); } function estimateAttributes(obj) { var serverData = getServerData(obj); var pendingOps = getPendingOps(obj); return ObjectStateMutations.estimateAttributes(serverData, pendingOps, obj.className, obj.id); } function commitServerChanges(obj, changes) { var state = initializeState(obj); ObjectStateMutations.commitServerChanges(state.serverData, state.objectCache, changes); } function enqueueTask(obj, task) { var state = initializeState(obj); return state.tasks.enqueue(task); } function duplicateState(source, dest) { var oldState = initializeState(source); var newState = initializeState(dest); for (var key in oldState.serverData) { newState.serverData[key] = oldState.serverData[key]; } for (var index = 0; index < oldState.pendingOps.length; index++) { for (var _key in oldState.pendingOps[index]) { newState.pendingOps[index][_key] = oldState.pendingOps[index][_key]; } } for (var _key2 in oldState.objectCache) { newState.objectCache[_key2] = oldState.objectCache[_key2]; } newState.existed = oldState.existed; } function clearAllState() { objectState = new _weakMap2.default(); } },{"./ObjectStateMutations":9,"./TaskQueue":32,"babel-runtime/core-js/weak-map":56}],34:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = arrayContainsObject; var _ParseObject = _dereq_('./ParseObject'); var _ParseObject2 = _interopRequireDefault(_ParseObject); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function arrayContainsObject(array, object) { if (array.indexOf(object) > -1) { return true; } for (var i = 0; i < array.length; i++) { if (array[i] instanceof _ParseObject2.default && array[i].className === object.className && array[i]._getId() === object._getId()) { return true; } } return false; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ },{"./ParseObject":18}],35:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); exports.default = canBeSerialized; var _ParseFile = _dereq_('./ParseFile'); var _ParseFile2 = _interopRequireDefault(_ParseFile); var _ParseObject = _dereq_('./ParseObject'); var _ParseObject2 = _interopRequireDefault(_ParseObject); var _ParseRelation = _dereq_('./ParseRelation'); var _ParseRelation2 = _interopRequireDefault(_ParseRelation); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function canBeSerialized(obj) { if (!(obj instanceof _ParseObject2.default)) { return true; } var attributes = obj.attributes; for (var attr in attributes) { var val = attributes[attr]; if (!canBeSerializedHelper(val)) { return false; } } return true; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function canBeSerializedHelper(value) { if ((typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value)) !== 'object') { return true; } if (value instanceof _ParseRelation2.default) { return true; } if (value instanceof _ParseObject2.default) { return !!value.id; } if (value instanceof _ParseFile2.default) { if (value.url()) { return true; } return false; } if (Array.isArray(value)) { for (var i = 0; i < value.length; i++) { if (!canBeSerializedHelper(value[i])) { return false; } } return true; } for (var k in value) { if (!canBeSerializedHelper(value[k])) { return false; } } return true; } },{"./ParseFile":14,"./ParseObject":18,"./ParseRelation":23,"babel-runtime/helpers/typeof":62}],36:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); exports.default = decode; var _ParseACL = _dereq_('./ParseACL'); var _ParseACL2 = _interopRequireDefault(_ParseACL); var _ParseFile = _dereq_('./ParseFile'); var _ParseFile2 = _interopRequireDefault(_ParseFile); var _ParseGeoPoint = _dereq_('./ParseGeoPoint'); var _ParseGeoPoint2 = _interopRequireDefault(_ParseGeoPoint); var _ParsePolygon = _dereq_('./ParsePolygon'); var _ParsePolygon2 = _interopRequireDefault(_ParsePolygon); var _ParseObject = _dereq_('./ParseObject'); var _ParseObject2 = _interopRequireDefault(_ParseObject); var _ParseOp = _dereq_('./ParseOp'); var _ParseRelation = _dereq_('./ParseRelation'); var _ParseRelation2 = _interopRequireDefault(_ParseRelation); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function decode(value) { if (value === null || (typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value)) !== 'object') { return value; } if (Array.isArray(value)) { var dup = []; value.forEach(function (v, i) { dup[i] = decode(v); }); return dup; } if (typeof value.__op === 'string') { return (0, _ParseOp.opFromJSON)(value); } if (value.__type === 'Pointer' && value.className) { return _ParseObject2.default.fromJSON(value); } if (value.__type === 'Object' && value.className) { return _ParseObject2.default.fromJSON(value); } if (value.__type === 'Relation') { // The parent and key fields will be populated by the parent var relation = new _ParseRelation2.default(null, null); relation.targetClassName = value.className; return relation; } if (value.__type === 'Date') { return new Date(value.iso); } if (value.__type === 'File') { return _ParseFile2.default.fromJSON(value); } if (value.__type === 'GeoPoint') { return new _ParseGeoPoint2.default({ latitude: value.latitude, longitude: value.longitude }); } if (value.__type === 'Polygon') { return new _ParsePolygon2.default(value.coordinates); } var copy = {}; for (var k in value) { copy[k] = decode(value[k]); } return copy; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ },{"./ParseACL":11,"./ParseFile":14,"./ParseGeoPoint":15,"./ParseObject":18,"./ParseOp":19,"./ParsePolygon":20,"./ParseRelation":23,"babel-runtime/helpers/typeof":62}],37:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); var _keys = _dereq_('babel-runtime/core-js/object/keys'); var _keys2 = _interopRequireDefault(_keys); exports.default = function (value, disallowObjects, forcePointers, seen) { return encode(value, !!disallowObjects, !!forcePointers, seen || []); }; var _ParseACL = _dereq_('./ParseACL'); var _ParseACL2 = _interopRequireDefault(_ParseACL); var _ParseFile = _dereq_('./ParseFile'); var _ParseFile2 = _interopRequireDefault(_ParseFile); var _ParseGeoPoint = _dereq_('./ParseGeoPoint'); var _ParseGeoPoint2 = _interopRequireDefault(_ParseGeoPoint); var _ParsePolygon = _dereq_('./ParsePolygon'); var _ParsePolygon2 = _interopRequireDefault(_ParsePolygon); var _ParseObject = _dereq_('./ParseObject'); var _ParseObject2 = _interopRequireDefault(_ParseObject); var _ParseOp = _dereq_('./ParseOp'); var _ParseRelation = _dereq_('./ParseRelation'); var _ParseRelation2 = _interopRequireDefault(_ParseRelation); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var toString = Object.prototype.toString; /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function encode(value, disallowObjects, forcePointers, seen) { if (value instanceof _ParseObject2.default) { if (disallowObjects) { throw new Error('Parse Objects not allowed here'); } var seenEntry = value.id ? value.className + ':' + value.id : value; if (forcePointers || !seen || seen.indexOf(seenEntry) > -1 || value.dirty() || (0, _keys2.default)(value._getServerData()).length < 1) { return value.toPointer(); } seen = seen.concat(seenEntry); return value._toFullJSON(seen); } if (value instanceof _ParseOp.Op || value instanceof _ParseACL2.default || value instanceof _ParseGeoPoint2.default || value instanceof _ParsePolygon2.default || value instanceof _ParseRelation2.default) { return value.toJSON(); } if (value instanceof _ParseFile2.default) { if (!value.url()) { throw new Error('Tried to encode an unsaved file.'); } return value.toJSON(); } if (toString.call(value) === '[object Date]') { if (isNaN(value)) { throw new Error('Tried to encode an invalid date.'); } return { __type: 'Date', iso: value.toJSON() }; } if (toString.call(value) === '[object RegExp]' && typeof value.source === 'string') { return value.source; } if (Array.isArray(value)) { return value.map(function (v) { return encode(v, disallowObjects, forcePointers, seen); }); } if (value && (typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value)) === 'object') { var output = {}; for (var k in value) { output[k] = encode(value[k], disallowObjects, forcePointers, seen); } return output; } return value; } },{"./ParseACL":11,"./ParseFile":14,"./ParseGeoPoint":15,"./ParseObject":18,"./ParseOp":19,"./ParsePolygon":20,"./ParseRelation":23,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/typeof":62}],38:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _keys = _dereq_('babel-runtime/core-js/object/keys'); var _keys2 = _interopRequireDefault(_keys); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); exports.default = equals; var _ParseACL = _dereq_('./ParseACL'); var _ParseACL2 = _interopRequireDefault(_ParseACL); var _ParseFile = _dereq_('./ParseFile'); var _ParseFile2 = _interopRequireDefault(_ParseFile); var _ParseGeoPoint = _dereq_('./ParseGeoPoint'); var _ParseGeoPoint2 = _interopRequireDefault(_ParseGeoPoint); var _ParseObject = _dereq_('./ParseObject'); var _ParseObject2 = _interopRequireDefault(_ParseObject); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function equals(a, b) { if ((typeof a === 'undefined' ? 'undefined' : (0, _typeof3.default)(a)) !== (typeof b === 'undefined' ? 'undefined' : (0, _typeof3.default)(b))) { return false; } if (!a || (typeof a === 'undefined' ? 'undefined' : (0, _typeof3.default)(a)) !== 'object') { // a is a primitive return a === b; } if (Array.isArray(a) || Array.isArray(b)) { if (!Array.isArray(a) || !Array.isArray(b)) { return false; } if (a.length !== b.length) { return false; } for (var i = a.length; i--;) { if (!equals(a[i], b[i])) { return false; } } return true; } if (a instanceof _ParseACL2.default || a instanceof _ParseFile2.default || a instanceof _ParseGeoPoint2.default || a instanceof _ParseObject2.default) { return a.equals(b); } if ((0, _keys2.default)(a).length !== (0, _keys2.default)(b).length) { return false; } for (var k in a) { if (!equals(a[k], b[k])) { return false; } } return true; } },{"./ParseACL":11,"./ParseFile":14,"./ParseGeoPoint":15,"./ParseObject":18,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/typeof":62}],39:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = escape; /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var encoded = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '/': '&#x2F;', '\'': '&#x27;', '"': '&quot;' }; function escape(str) { return str.replace(/[&<>\/'"]/g, function (char) { return encoded[char]; }); } },{}],40:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isRevocableSession; /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function isRevocableSession(token) { return token.indexOf('r:') > -1; } },{}],41:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = parseDate; /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function parseDate(iso8601) { var regexp = new RegExp('^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})' + 'T' + '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})' + '(.([0-9]+))?' + 'Z$'); var match = regexp.exec(iso8601); if (!match) { return null; } var year = match[1] || 0; var month = (match[2] || 1) - 1; var day = match[3] || 0; var hour = match[4] || 0; var minute = match[5] || 0; var second = match[6] || 0; var milli = match[8] || 0; return new Date(Date.UTC(year, month, day, hour, minute, second, milli)); } },{}],42:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = unique; var _arrayContainsObject = _dereq_('./arrayContainsObject'); var _arrayContainsObject2 = _interopRequireDefault(_arrayContainsObject); var _ParseObject = _dereq_('./ParseObject'); var _ParseObject2 = _interopRequireDefault(_ParseObject); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function unique(arr) { var uniques = []; arr.forEach(function (value) { if (value instanceof _ParseObject2.default) { if (!(0, _arrayContainsObject2.default)(uniques, value)) { uniques.push(value); } } else { if (uniques.indexOf(value) < 0) { uniques.push(value); } } }); return uniques; } },{"./ParseObject":18,"./arrayContainsObject":34}],43:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); exports.default = unsavedChildren; var _ParseFile = _dereq_('./ParseFile'); var _ParseFile2 = _interopRequireDefault(_ParseFile); var _ParseObject = _dereq_('./ParseObject'); var _ParseObject2 = _interopRequireDefault(_ParseObject); var _ParseRelation = _dereq_('./ParseRelation'); var _ParseRelation2 = _interopRequireDefault(_ParseRelation); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Return an array of unsaved children, which are either Parse Objects or Files. * If it encounters any dirty Objects without Ids, it will throw an exception. */ function unsavedChildren(obj, allowDeepUnsaved) { var encountered = { objects: {}, files: [] }; var identifier = obj.className + ':' + obj._getId(); encountered.objects[identifier] = obj.dirty() ? obj : true; var attributes = obj.attributes; for (var attr in attributes) { if ((0, _typeof3.default)(attributes[attr]) === 'object') { traverse(attributes[attr], encountered, false, !!allowDeepUnsaved); } } var unsaved = []; for (var id in encountered.objects) { if (id !== identifier && encountered.objects[id] !== true) { unsaved.push(encountered.objects[id]); } } return unsaved.concat(encountered.files); } /** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function traverse(obj, encountered, shouldThrow, allowDeepUnsaved) { if (obj instanceof _ParseObject2.default) { if (!obj.id && shouldThrow) { throw new Error('Cannot create a pointer to an unsaved Object.'); } var identifier = obj.className + ':' + obj._getId(); if (!encountered.objects[identifier]) { encountered.objects[identifier] = obj.dirty() ? obj : true; var attributes = obj.attributes; for (var attr in attributes) { if ((0, _typeof3.default)(attributes[attr]) === 'object') { traverse(attributes[attr], encountered, !allowDeepUnsaved, allowDeepUnsaved); } } } return; } if (obj instanceof _ParseFile2.default) { if (!obj.url() && encountered.files.indexOf(obj) < 0) { encountered.files.push(obj); } return; } if (obj instanceof _ParseRelation2.default) { return; } if (Array.isArray(obj)) { obj.forEach(function (el) { if ((typeof el === 'undefined' ? 'undefined' : (0, _typeof3.default)(el)) === 'object') { traverse(el, encountered, shouldThrow, allowDeepUnsaved); } }); } for (var k in obj) { if ((0, _typeof3.default)(obj[k]) === 'object') { traverse(obj[k], encountered, shouldThrow, allowDeepUnsaved); } } } },{"./ParseFile":14,"./ParseObject":18,"./ParseRelation":23,"babel-runtime/helpers/typeof":62}],44:[function(_dereq_,module,exports){ module.exports = { "default": _dereq_("core-js/library/fn/get-iterator"), __esModule: true }; },{"core-js/library/fn/get-iterator":64}],45:[function(_dereq_,module,exports){ module.exports = { "default": _dereq_("core-js/library/fn/json/stringify"), __esModule: true }; },{"core-js/library/fn/json/stringify":65}],46:[function(_dereq_,module,exports){ module.exports = { "default": _dereq_("core-js/library/fn/map"), __esModule: true }; },{"core-js/library/fn/map":66}],47:[function(_dereq_,module,exports){ module.exports = { "default": _dereq_("core-js/library/fn/object/create"), __esModule: true }; },{"core-js/library/fn/object/create":67}],48:[function(_dereq_,module,exports){ module.exports = { "default": _dereq_("core-js/library/fn/object/define-property"), __esModule: true }; },{"core-js/library/fn/object/define-property":68}],49:[function(_dereq_,module,exports){ module.exports = { "default": _dereq_("core-js/library/fn/object/freeze"), __esModule: true }; },{"core-js/library/fn/object/freeze":69}],50:[function(_dereq_,module,exports){ module.exports = { "default": _dereq_("core-js/library/fn/object/get-own-property-descriptor"), __esModule: true }; },{"core-js/library/fn/object/get-own-property-descriptor":70}],51:[function(_dereq_,module,exports){ module.exports = { "default": _dereq_("core-js/library/fn/object/get-prototype-of"), __esModule: true }; },{"core-js/library/fn/object/get-prototype-of":71}],52:[function(_dereq_,module,exports){ module.exports = { "default": _dereq_("core-js/library/fn/object/keys"), __esModule: true }; },{"core-js/library/fn/object/keys":72}],53:[function(_dereq_,module,exports){ module.exports = { "default": _dereq_("core-js/library/fn/object/set-prototype-of"), __esModule: true }; },{"core-js/library/fn/object/set-prototype-of":73}],54:[function(_dereq_,module,exports){ module.exports = { "default": _dereq_("core-js/library/fn/symbol"), __esModule: true }; },{"core-js/library/fn/symbol":74}],55:[function(_dereq_,module,exports){ module.exports = { "default": _dereq_("core-js/library/fn/symbol/iterator"), __esModule: true }; },{"core-js/library/fn/symbol/iterator":75}],56:[function(_dereq_,module,exports){ module.exports = { "default": _dereq_("core-js/library/fn/weak-map"), __esModule: true }; },{"core-js/library/fn/weak-map":76}],57:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; exports.default = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; },{}],58:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; var _defineProperty = _dereq_("../core-js/object/define-property"); var _defineProperty2 = _interopRequireDefault(_defineProperty); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; (0, _defineProperty2.default)(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); },{"../core-js/object/define-property":48}],59:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; var _getPrototypeOf = _dereq_("../core-js/object/get-prototype-of"); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _getOwnPropertyDescriptor = _dereq_("../core-js/object/get-own-property-descriptor"); var _getOwnPropertyDescriptor2 = _interopRequireDefault(_getOwnPropertyDescriptor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = (0, _getOwnPropertyDescriptor2.default)(object, property); if (desc === undefined) { var parent = (0, _getPrototypeOf2.default)(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; },{"../core-js/object/get-own-property-descriptor":50,"../core-js/object/get-prototype-of":51}],60:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; var _setPrototypeOf = _dereq_("../core-js/object/set-prototype-of"); var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf); var _create = _dereq_("../core-js/object/create"); var _create2 = _interopRequireDefault(_create); var _typeof2 = _dereq_("../helpers/typeof"); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); } subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; }; },{"../core-js/object/create":47,"../core-js/object/set-prototype-of":53,"../helpers/typeof":62}],61:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; var _typeof2 = _dereq_("../helpers/typeof"); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; }; },{"../helpers/typeof":62}],62:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; var _iterator = _dereq_("../core-js/symbol/iterator"); var _iterator2 = _interopRequireDefault(_iterator); var _symbol = _dereq_("../core-js/symbol"); var _symbol2 = _interopRequireDefault(_symbol); var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { return typeof obj === "undefined" ? "undefined" : _typeof(obj); } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); }; },{"../core-js/symbol":54,"../core-js/symbol/iterator":55}],63:[function(_dereq_,module,exports){ },{}],64:[function(_dereq_,module,exports){ _dereq_('../modules/web.dom.iterable'); _dereq_('../modules/es6.string.iterator'); module.exports = _dereq_('../modules/core.get-iterator'); },{"../modules/core.get-iterator":152,"../modules/es6.string.iterator":163,"../modules/web.dom.iterable":169}],65:[function(_dereq_,module,exports){ var core = _dereq_('../../modules/_core') , $JSON = core.JSON || (core.JSON = {stringify: JSON.stringify}); module.exports = function stringify(it){ // eslint-disable-line no-unused-vars return $JSON.stringify.apply($JSON, arguments); }; },{"../../modules/_core":92}],66:[function(_dereq_,module,exports){ _dereq_('../modules/es6.object.to-string'); _dereq_('../modules/es6.string.iterator'); _dereq_('../modules/web.dom.iterable'); _dereq_('../modules/es6.map'); _dereq_('../modules/es7.map.to-json'); module.exports = _dereq_('../modules/_core').Map; },{"../modules/_core":92,"../modules/es6.map":154,"../modules/es6.object.to-string":162,"../modules/es6.string.iterator":163,"../modules/es7.map.to-json":166,"../modules/web.dom.iterable":169}],67:[function(_dereq_,module,exports){ _dereq_('../../modules/es6.object.create'); var $Object = _dereq_('../../modules/_core').Object; module.exports = function create(P, D){ return $Object.create(P, D); }; },{"../../modules/_core":92,"../../modules/es6.object.create":155}],68:[function(_dereq_,module,exports){ _dereq_('../../modules/es6.object.define-property'); var $Object = _dereq_('../../modules/_core').Object; module.exports = function defineProperty(it, key, desc){ return $Object.defineProperty(it, key, desc); }; },{"../../modules/_core":92,"../../modules/es6.object.define-property":156}],69:[function(_dereq_,module,exports){ _dereq_('../../modules/es6.object.freeze'); module.exports = _dereq_('../../modules/_core').Object.freeze; },{"../../modules/_core":92,"../../modules/es6.object.freeze":157}],70:[function(_dereq_,module,exports){ _dereq_('../../modules/es6.object.get-own-property-descriptor'); var $Object = _dereq_('../../modules/_core').Object; module.exports = function getOwnPropertyDescriptor(it, key){ return $Object.getOwnPropertyDescriptor(it, key); }; },{"../../modules/_core":92,"../../modules/es6.object.get-own-property-descriptor":158}],71:[function(_dereq_,module,exports){ _dereq_('../../modules/es6.object.get-prototype-of'); module.exports = _dereq_('../../modules/_core').Object.getPrototypeOf; },{"../../modules/_core":92,"../../modules/es6.object.get-prototype-of":159}],72:[function(_dereq_,module,exports){ _dereq_('../../modules/es6.object.keys'); module.exports = _dereq_('../../modules/_core').Object.keys; },{"../../modules/_core":92,"../../modules/es6.object.keys":160}],73:[function(_dereq_,module,exports){ _dereq_('../../modules/es6.object.set-prototype-of'); module.exports = _dereq_('../../modules/_core').Object.setPrototypeOf; },{"../../modules/_core":92,"../../modules/es6.object.set-prototype-of":161}],74:[function(_dereq_,module,exports){ _dereq_('../../modules/es6.symbol'); _dereq_('../../modules/es6.object.to-string'); _dereq_('../../modules/es7.symbol.async-iterator'); _dereq_('../../modules/es7.symbol.observable'); module.exports = _dereq_('../../modules/_core').Symbol; },{"../../modules/_core":92,"../../modules/es6.object.to-string":162,"../../modules/es6.symbol":164,"../../modules/es7.symbol.async-iterator":167,"../../modules/es7.symbol.observable":168}],75:[function(_dereq_,module,exports){ _dereq_('../../modules/es6.string.iterator'); _dereq_('../../modules/web.dom.iterable'); module.exports = _dereq_('../../modules/_wks-ext').f('iterator'); },{"../../modules/_wks-ext":149,"../../modules/es6.string.iterator":163,"../../modules/web.dom.iterable":169}],76:[function(_dereq_,module,exports){ _dereq_('../modules/es6.object.to-string'); _dereq_('../modules/web.dom.iterable'); _dereq_('../modules/es6.weak-map'); module.exports = _dereq_('../modules/_core').WeakMap; },{"../modules/_core":92,"../modules/es6.object.to-string":162,"../modules/es6.weak-map":165,"../modules/web.dom.iterable":169}],77:[function(_dereq_,module,exports){ module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; },{}],78:[function(_dereq_,module,exports){ module.exports = function(){ /* empty */ }; },{}],79:[function(_dereq_,module,exports){ module.exports = function(it, Constructor, name, forbiddenField){ if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){ throw TypeError(name + ': incorrect invocation!'); } return it; }; },{}],80:[function(_dereq_,module,exports){ var isObject = _dereq_('./_is-object'); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; },{"./_is-object":110}],81:[function(_dereq_,module,exports){ var forOf = _dereq_('./_for-of'); module.exports = function(iter, ITERATOR){ var result = []; forOf(iter, false, result.push, result, ITERATOR); return result; }; },{"./_for-of":101}],82:[function(_dereq_,module,exports){ // false -> Array#indexOf // true -> Array#includes var toIObject = _dereq_('./_to-iobject') , toLength = _dereq_('./_to-length') , toIndex = _dereq_('./_to-index'); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = toIObject($this) , length = toLength(O.length) , index = toIndex(fromIndex, length) , value; // Array#includes uses SameValueZero equality algorithm if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; // Array#toIndex ignores holes, Array#includes - not } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; },{"./_to-index":141,"./_to-iobject":143,"./_to-length":144}],83:[function(_dereq_,module,exports){ // 0 -> Array#forEach // 1 -> Array#map // 2 -> Array#filter // 3 -> Array#some // 4 -> Array#every // 5 -> Array#find // 6 -> Array#findIndex var ctx = _dereq_('./_ctx') , IObject = _dereq_('./_iobject') , toObject = _dereq_('./_to-object') , toLength = _dereq_('./_to-length') , asc = _dereq_('./_array-species-create'); module.exports = function(TYPE, $create){ var IS_MAP = TYPE == 1 , IS_FILTER = TYPE == 2 , IS_SOME = TYPE == 3 , IS_EVERY = TYPE == 4 , IS_FIND_INDEX = TYPE == 6 , NO_HOLES = TYPE == 5 || IS_FIND_INDEX , create = $create || asc; return function($this, callbackfn, that){ var O = toObject($this) , self = IObject(O) , f = ctx(callbackfn, that, 3) , length = toLength(self.length) , index = 0 , result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined , val, res; for(;length > index; index++)if(NO_HOLES || index in self){ val = self[index]; res = f(val, index, O); if(TYPE){ if(IS_MAP)result[index] = res; // map else if(res)switch(TYPE){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(IS_EVERY)return false; // every } } return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; }; }; },{"./_array-species-create":85,"./_ctx":93,"./_iobject":107,"./_to-length":144,"./_to-object":145}],84:[function(_dereq_,module,exports){ var isObject = _dereq_('./_is-object') , isArray = _dereq_('./_is-array') , SPECIES = _dereq_('./_wks')('species'); module.exports = function(original){ var C; if(isArray(original)){ C = original.constructor; // cross-realm fallback if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined; if(isObject(C)){ C = C[SPECIES]; if(C === null)C = undefined; } } return C === undefined ? Array : C; }; },{"./_is-array":109,"./_is-object":110,"./_wks":150}],85:[function(_dereq_,module,exports){ // 9.4.2.3 ArraySpeciesCreate(originalArray, length) var speciesConstructor = _dereq_('./_array-species-constructor'); module.exports = function(original, length){ return new (speciesConstructor(original))(length); }; },{"./_array-species-constructor":84}],86:[function(_dereq_,module,exports){ // getting tag from 19.1.3.6 Object.prototype.toString() var cof = _dereq_('./_cof') , TAG = _dereq_('./_wks')('toStringTag') // ES3 wrong here , ARG = cof(function(){ return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function(it, key){ try { return it[key]; } catch(e){ /* empty */ } }; module.exports = function(it){ var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; },{"./_cof":87,"./_wks":150}],87:[function(_dereq_,module,exports){ var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; },{}],88:[function(_dereq_,module,exports){ 'use strict'; var dP = _dereq_('./_object-dp').f , create = _dereq_('./_object-create') , redefineAll = _dereq_('./_redefine-all') , ctx = _dereq_('./_ctx') , anInstance = _dereq_('./_an-instance') , defined = _dereq_('./_defined') , forOf = _dereq_('./_for-of') , $iterDefine = _dereq_('./_iter-define') , step = _dereq_('./_iter-step') , setSpecies = _dereq_('./_set-species') , DESCRIPTORS = _dereq_('./_descriptors') , fastKey = _dereq_('./_meta').fastKey , SIZE = DESCRIPTORS ? '_s' : 'size'; var getEntry = function(that, key){ // fast case var index = fastKey(key), entry; if(index !== 'F')return that._i[index]; // frozen object case for(entry = that._f; entry; entry = entry.n){ if(entry.k == key)return entry; } }; module.exports = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ anInstance(that, C, NAME, '_i'); that._i = create(null); // index that._f = undefined; // first entry that._l = undefined; // last entry that[SIZE] = 0; // size if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); redefineAll(C.prototype, { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function clear(){ for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){ entry.r = true; if(entry.p)entry.p = entry.p.n = undefined; delete data[entry.i]; } that._f = that._l = undefined; that[SIZE] = 0; }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var that = this , entry = getEntry(that, key); if(entry){ var next = entry.n , prev = entry.p; delete that._i[entry.i]; entry.r = true; if(prev)prev.n = next; if(next)next.p = prev; if(that._f == entry)that._f = next; if(that._l == entry)that._l = prev; that[SIZE]--; } return !!entry; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function forEach(callbackfn /*, that = undefined */){ anInstance(this, C, 'forEach'); var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3) , entry; while(entry = entry ? entry.n : this._f){ f(entry.v, entry.k, this); // revert to the last existing entry while(entry && entry.r)entry = entry.p; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function has(key){ return !!getEntry(this, key); } }); if(DESCRIPTORS)dP(C.prototype, 'size', { get: function(){ return defined(this[SIZE]); } }); return C; }, def: function(that, key, value){ var entry = getEntry(that, key) , prev, index; // change existing entry if(entry){ entry.v = value; // create new entry } else { that._l = entry = { i: index = fastKey(key, true), // <- index k: key, // <- key v: value, // <- value p: prev = that._l, // <- previous entry n: undefined, // <- next entry r: false // <- removed }; if(!that._f)that._f = entry; if(prev)prev.n = entry; that[SIZE]++; // add to index if(index !== 'F')that._i[index] = entry; } return that; }, getEntry: getEntry, setStrong: function(C, NAME, IS_MAP){ // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 $iterDefine(C, NAME, function(iterated, kind){ this._t = iterated; // target this._k = kind; // kind this._l = undefined; // previous }, function(){ var that = this , kind = that._k , entry = that._l; // revert to the last existing entry while(entry && entry.r)entry = entry.p; // get next entry if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){ // or finish the iteration that._t = undefined; return step(1); } // return step by kind if(kind == 'keys' )return step(0, entry.k); if(kind == 'values')return step(0, entry.v); return step(0, [entry.k, entry.v]); }, IS_MAP ? 'entries' : 'values' , !IS_MAP, true); // add [@@species], 23.1.2.2, 23.2.2.2 setSpecies(NAME); } }; },{"./_an-instance":79,"./_ctx":93,"./_defined":94,"./_descriptors":95,"./_for-of":101,"./_iter-define":113,"./_iter-step":114,"./_meta":118,"./_object-create":120,"./_object-dp":121,"./_redefine-all":133,"./_set-species":136}],89:[function(_dereq_,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON var classof = _dereq_('./_classof') , from = _dereq_('./_array-from-iterable'); module.exports = function(NAME){ return function toJSON(){ if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic"); return from(this); }; }; },{"./_array-from-iterable":81,"./_classof":86}],90:[function(_dereq_,module,exports){ 'use strict'; var redefineAll = _dereq_('./_redefine-all') , getWeak = _dereq_('./_meta').getWeak , anObject = _dereq_('./_an-object') , isObject = _dereq_('./_is-object') , anInstance = _dereq_('./_an-instance') , forOf = _dereq_('./_for-of') , createArrayMethod = _dereq_('./_array-methods') , $has = _dereq_('./_has') , arrayFind = createArrayMethod(5) , arrayFindIndex = createArrayMethod(6) , id = 0; // fallback for uncaught frozen keys var uncaughtFrozenStore = function(that){ return that._l || (that._l = new UncaughtFrozenStore); }; var UncaughtFrozenStore = function(){ this.a = []; }; var findUncaughtFrozen = function(store, key){ return arrayFind(store.a, function(it){ return it[0] === key; }); }; UncaughtFrozenStore.prototype = { get: function(key){ var entry = findUncaughtFrozen(this, key); if(entry)return entry[1]; }, has: function(key){ return !!findUncaughtFrozen(this, key); }, set: function(key, value){ var entry = findUncaughtFrozen(this, key); if(entry)entry[1] = value; else this.a.push([key, value]); }, 'delete': function(key){ var index = arrayFindIndex(this.a, function(it){ return it[0] === key; }); if(~index)this.a.splice(index, 1); return !!~index; } }; module.exports = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ anInstance(that, C, NAME, '_i'); that._i = id++; // collection id that._l = undefined; // leak store for uncaught frozen objects if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); redefineAll(C.prototype, { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function(key){ if(!isObject(key))return false; var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this)['delete'](key); return data && $has(data, this._i) && delete data[this._i]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: function has(key){ if(!isObject(key))return false; var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this).has(key); return data && $has(data, this._i); } }); return C; }, def: function(that, key, value){ var data = getWeak(anObject(key), true); if(data === true)uncaughtFrozenStore(that).set(key, value); else data[that._i] = value; return that; }, ufstore: uncaughtFrozenStore }; },{"./_an-instance":79,"./_an-object":80,"./_array-methods":83,"./_for-of":101,"./_has":103,"./_is-object":110,"./_meta":118,"./_redefine-all":133}],91:[function(_dereq_,module,exports){ 'use strict'; var global = _dereq_('./_global') , $export = _dereq_('./_export') , meta = _dereq_('./_meta') , fails = _dereq_('./_fails') , hide = _dereq_('./_hide') , redefineAll = _dereq_('./_redefine-all') , forOf = _dereq_('./_for-of') , anInstance = _dereq_('./_an-instance') , isObject = _dereq_('./_is-object') , setToStringTag = _dereq_('./_set-to-string-tag') , dP = _dereq_('./_object-dp').f , each = _dereq_('./_array-methods')(0) , DESCRIPTORS = _dereq_('./_descriptors'); module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){ var Base = global[NAME] , C = Base , ADDER = IS_MAP ? 'set' : 'add' , proto = C && C.prototype , O = {}; if(!DESCRIPTORS || typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){ new C().entries().next(); }))){ // create collection constructor C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); redefineAll(C.prototype, methods); meta.NEED = true; } else { C = wrapper(function(target, iterable){ anInstance(target, C, NAME, '_c'); target._c = new Base; if(iterable != undefined)forOf(iterable, IS_MAP, target[ADDER], target); }); each('add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON'.split(','),function(KEY){ var IS_ADDER = KEY == 'add' || KEY == 'set'; if(KEY in proto && !(IS_WEAK && KEY == 'clear'))hide(C.prototype, KEY, function(a, b){ anInstance(this, C, KEY); if(!IS_ADDER && IS_WEAK && !isObject(a))return KEY == 'get' ? undefined : false; var result = this._c[KEY](a === 0 ? 0 : a, b); return IS_ADDER ? this : result; }); }); if('size' in proto)dP(C.prototype, 'size', { get: function(){ return this._c.size; } }); } setToStringTag(C, NAME); O[NAME] = C; $export($export.G + $export.W + $export.F, O); if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP); return C; }; },{"./_an-instance":79,"./_array-methods":83,"./_descriptors":95,"./_export":99,"./_fails":100,"./_for-of":101,"./_global":102,"./_hide":104,"./_is-object":110,"./_meta":118,"./_object-dp":121,"./_redefine-all":133,"./_set-to-string-tag":137}],92:[function(_dereq_,module,exports){ var core = module.exports = {version: '2.4.0'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef },{}],93:[function(_dereq_,module,exports){ // optional / simple context binding var aFunction = _dereq_('./_a-function'); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; },{"./_a-function":77}],94:[function(_dereq_,module,exports){ // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; },{}],95:[function(_dereq_,module,exports){ // Thank's IE8 for his funny defineProperty module.exports = !_dereq_('./_fails')(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); },{"./_fails":100}],96:[function(_dereq_,module,exports){ var isObject = _dereq_('./_is-object') , document = _dereq_('./_global').document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; },{"./_global":102,"./_is-object":110}],97:[function(_dereq_,module,exports){ // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); },{}],98:[function(_dereq_,module,exports){ // all enumerable object keys, includes symbols var getKeys = _dereq_('./_object-keys') , gOPS = _dereq_('./_object-gops') , pIE = _dereq_('./_object-pie'); module.exports = function(it){ var result = getKeys(it) , getSymbols = gOPS.f; if(getSymbols){ var symbols = getSymbols(it) , isEnum = pIE.f , i = 0 , key; while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key); } return result; }; },{"./_object-gops":126,"./_object-keys":129,"./_object-pie":130}],99:[function(_dereq_,module,exports){ var global = _dereq_('./_global') , core = _dereq_('./_core') , ctx = _dereq_('./_ctx') , hide = _dereq_('./_hide') , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , IS_WRAP = type & $export.W , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , expProto = exports[PROTOTYPE] , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] , key, own, out; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && target[key] !== undefined; if(own && key in exports)continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function(C){ var F = function(a, b, c){ if(this instanceof C){ switch(arguments.length){ case 0: return new C; case 1: return new C(a); case 2: return new C(a, b); } return new C(a, b, c); } return C.apply(this, arguments); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% if(IS_PROTO){ (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out); } } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; },{"./_core":92,"./_ctx":93,"./_global":102,"./_hide":104}],100:[function(_dereq_,module,exports){ module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; },{}],101:[function(_dereq_,module,exports){ var ctx = _dereq_('./_ctx') , call = _dereq_('./_iter-call') , isArrayIter = _dereq_('./_is-array-iter') , anObject = _dereq_('./_an-object') , toLength = _dereq_('./_to-length') , getIterFn = _dereq_('./core.get-iterator-method') , BREAK = {} , RETURN = {}; var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){ var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable) , f = ctx(fn, that, entries ? 2 : 1) , index = 0 , length, step, iterator, result; if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!'); // fast case for arrays with default iterator if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){ result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); if(result === BREAK || result === RETURN)return result; } else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){ result = call(iterator, f, step.value, entries); if(result === BREAK || result === RETURN)return result; } }; exports.BREAK = BREAK; exports.RETURN = RETURN; },{"./_an-object":80,"./_ctx":93,"./_is-array-iter":108,"./_iter-call":111,"./_to-length":144,"./core.get-iterator-method":151}],102:[function(_dereq_,module,exports){ // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef },{}],103:[function(_dereq_,module,exports){ var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; },{}],104:[function(_dereq_,module,exports){ var dP = _dereq_('./_object-dp') , createDesc = _dereq_('./_property-desc'); module.exports = _dereq_('./_descriptors') ? function(object, key, value){ return dP.f(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; },{"./_descriptors":95,"./_object-dp":121,"./_property-desc":132}],105:[function(_dereq_,module,exports){ module.exports = _dereq_('./_global').document && document.documentElement; },{"./_global":102}],106:[function(_dereq_,module,exports){ module.exports = !_dereq_('./_descriptors') && !_dereq_('./_fails')(function(){ return Object.defineProperty(_dereq_('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7; }); },{"./_descriptors":95,"./_dom-create":96,"./_fails":100}],107:[function(_dereq_,module,exports){ // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = _dereq_('./_cof'); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; },{"./_cof":87}],108:[function(_dereq_,module,exports){ // check on default Array iterator var Iterators = _dereq_('./_iterators') , ITERATOR = _dereq_('./_wks')('iterator') , ArrayProto = Array.prototype; module.exports = function(it){ return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; },{"./_iterators":115,"./_wks":150}],109:[function(_dereq_,module,exports){ // 7.2.2 IsArray(argument) var cof = _dereq_('./_cof'); module.exports = Array.isArray || function isArray(arg){ return cof(arg) == 'Array'; }; },{"./_cof":87}],110:[function(_dereq_,module,exports){ module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; },{}],111:[function(_dereq_,module,exports){ // call something on iterator step with safe closing on error var anObject = _dereq_('./_an-object'); module.exports = function(iterator, fn, value, entries){ try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch(e){ var ret = iterator['return']; if(ret !== undefined)anObject(ret.call(iterator)); throw e; } }; },{"./_an-object":80}],112:[function(_dereq_,module,exports){ 'use strict'; var create = _dereq_('./_object-create') , descriptor = _dereq_('./_property-desc') , setToStringTag = _dereq_('./_set-to-string-tag') , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() _dereq_('./_hide')(IteratorPrototype, _dereq_('./_wks')('iterator'), function(){ return this; }); module.exports = function(Constructor, NAME, next){ Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); }; },{"./_hide":104,"./_object-create":120,"./_property-desc":132,"./_set-to-string-tag":137,"./_wks":150}],113:[function(_dereq_,module,exports){ 'use strict'; var LIBRARY = _dereq_('./_library') , $export = _dereq_('./_export') , redefine = _dereq_('./_redefine') , hide = _dereq_('./_hide') , has = _dereq_('./_has') , Iterators = _dereq_('./_iterators') , $iterCreate = _dereq_('./_iter-create') , setToStringTag = _dereq_('./_set-to-string-tag') , getPrototypeOf = _dereq_('./_object-gpo') , ITERATOR = _dereq_('./_wks')('iterator') , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values'; var returnThis = function(){ return this; }; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ $iterCreate(Constructor, NAME, next); var getMethod = function(kind){ if(!BUGGY && kind in proto)return proto[kind]; switch(kind){ case KEYS: return function keys(){ return new Constructor(this, kind); }; case VALUES: return function values(){ return new Constructor(this, kind); }; } return function entries(){ return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator' , DEF_VALUES = DEFAULT == VALUES , VALUES_BUG = false , proto = Base.prototype , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , $default = $native || getMethod(DEFAULT) , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined , $anyNative = NAME == 'Array' ? proto.entries || $native : $native , methods, key, IteratorPrototype; // Fix native if($anyNative){ IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); if(IteratorPrototype !== Object.prototype){ // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if(DEF_VALUES && $native && $native.name !== VALUES){ VALUES_BUG = true; $default = function values(){ return $native.call(this); }; } // Define iterator if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if(DEFAULT){ methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if(FORCED)for(key in methods){ if(!(key in proto))redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; },{"./_export":99,"./_has":103,"./_hide":104,"./_iter-create":112,"./_iterators":115,"./_library":117,"./_object-gpo":127,"./_redefine":134,"./_set-to-string-tag":137,"./_wks":150}],114:[function(_dereq_,module,exports){ module.exports = function(done, value){ return {value: value, done: !!done}; }; },{}],115:[function(_dereq_,module,exports){ module.exports = {}; },{}],116:[function(_dereq_,module,exports){ var getKeys = _dereq_('./_object-keys') , toIObject = _dereq_('./_to-iobject'); module.exports = function(object, el){ var O = toIObject(object) , keys = getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; },{"./_object-keys":129,"./_to-iobject":143}],117:[function(_dereq_,module,exports){ module.exports = true; },{}],118:[function(_dereq_,module,exports){ var META = _dereq_('./_uid')('meta') , isObject = _dereq_('./_is-object') , has = _dereq_('./_has') , setDesc = _dereq_('./_object-dp').f , id = 0; var isExtensible = Object.isExtensible || function(){ return true; }; var FREEZE = !_dereq_('./_fails')(function(){ return isExtensible(Object.preventExtensions({})); }); var setMeta = function(it){ setDesc(it, META, {value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs }}); }; var fastKey = function(it, create){ // return primitive with prefix if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return 'F'; // not necessary to add metadata if(!create)return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function(it, create){ if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return true; // not necessary to add metadata if(!create)return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function(it){ if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; },{"./_fails":100,"./_has":103,"./_is-object":110,"./_object-dp":121,"./_uid":147}],119:[function(_dereq_,module,exports){ 'use strict'; // 19.1.2.1 Object.assign(target, source, ...) var getKeys = _dereq_('./_object-keys') , gOPS = _dereq_('./_object-gops') , pIE = _dereq_('./_object-pie') , toObject = _dereq_('./_to-object') , IObject = _dereq_('./_iobject') , $assign = Object.assign; // should work with symbols and should have deterministic property order (V8 bug) module.exports = !$assign || _dereq_('./_fails')(function(){ var A = {} , B = {} , S = Symbol() , K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function(k){ B[k] = k; }); return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; }) ? function assign(target, source){ // eslint-disable-line no-unused-vars var T = toObject(target) , aLen = arguments.length , index = 1 , getSymbols = gOPS.f , isEnum = pIE.f; while(aLen > index){ var S = IObject(arguments[index++]) , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) , length = keys.length , j = 0 , key; while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; } return T; } : $assign; },{"./_fails":100,"./_iobject":107,"./_object-gops":126,"./_object-keys":129,"./_object-pie":130,"./_to-object":145}],120:[function(_dereq_,module,exports){ // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = _dereq_('./_an-object') , dPs = _dereq_('./_object-dps') , enumBugKeys = _dereq_('./_enum-bug-keys') , IE_PROTO = _dereq_('./_shared-key')('IE_PROTO') , Empty = function(){ /* empty */ } , PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = _dereq_('./_dom-create')('iframe') , i = enumBugKeys.length , lt = '<' , gt = '>' , iframeDocument; iframe.style.display = 'none'; _dereq_('./_html').appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties){ var result; if(O !== null){ Empty[PROTOTYPE] = anObject(O); result = new Empty; Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; },{"./_an-object":80,"./_dom-create":96,"./_enum-bug-keys":97,"./_html":105,"./_object-dps":122,"./_shared-key":138}],121:[function(_dereq_,module,exports){ var anObject = _dereq_('./_an-object') , IE8_DOM_DEFINE = _dereq_('./_ie8-dom-define') , toPrimitive = _dereq_('./_to-primitive') , dP = Object.defineProperty; exports.f = _dereq_('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){ anObject(O); P = toPrimitive(P, true); anObject(Attributes); if(IE8_DOM_DEFINE)try { return dP(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)O[P] = Attributes.value; return O; }; },{"./_an-object":80,"./_descriptors":95,"./_ie8-dom-define":106,"./_to-primitive":146}],122:[function(_dereq_,module,exports){ var dP = _dereq_('./_object-dp') , anObject = _dereq_('./_an-object') , getKeys = _dereq_('./_object-keys'); module.exports = _dereq_('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties){ anObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)dP.f(O, P = keys[i++], Properties[P]); return O; }; },{"./_an-object":80,"./_descriptors":95,"./_object-dp":121,"./_object-keys":129}],123:[function(_dereq_,module,exports){ var pIE = _dereq_('./_object-pie') , createDesc = _dereq_('./_property-desc') , toIObject = _dereq_('./_to-iobject') , toPrimitive = _dereq_('./_to-primitive') , has = _dereq_('./_has') , IE8_DOM_DEFINE = _dereq_('./_ie8-dom-define') , gOPD = Object.getOwnPropertyDescriptor; exports.f = _dereq_('./_descriptors') ? gOPD : function getOwnPropertyDescriptor(O, P){ O = toIObject(O); P = toPrimitive(P, true); if(IE8_DOM_DEFINE)try { return gOPD(O, P); } catch(e){ /* empty */ } if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]); }; },{"./_descriptors":95,"./_has":103,"./_ie8-dom-define":106,"./_object-pie":130,"./_property-desc":132,"./_to-iobject":143,"./_to-primitive":146}],124:[function(_dereq_,module,exports){ // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = _dereq_('./_to-iobject') , gOPN = _dereq_('./_object-gopn').f , toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function(it){ try { return gOPN(it); } catch(e){ return windowNames.slice(); } }; module.exports.f = function getOwnPropertyNames(it){ return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; },{"./_object-gopn":125,"./_to-iobject":143}],125:[function(_dereq_,module,exports){ // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = _dereq_('./_object-keys-internal') , hiddenKeys = _dereq_('./_enum-bug-keys').concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){ return $keys(O, hiddenKeys); }; },{"./_enum-bug-keys":97,"./_object-keys-internal":128}],126:[function(_dereq_,module,exports){ exports.f = Object.getOwnPropertySymbols; },{}],127:[function(_dereq_,module,exports){ // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = _dereq_('./_has') , toObject = _dereq_('./_to-object') , IE_PROTO = _dereq_('./_shared-key')('IE_PROTO') , ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function(O){ O = toObject(O); if(has(O, IE_PROTO))return O[IE_PROTO]; if(typeof O.constructor == 'function' && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; },{"./_has":103,"./_shared-key":138,"./_to-object":145}],128:[function(_dereq_,module,exports){ var has = _dereq_('./_has') , toIObject = _dereq_('./_to-iobject') , arrayIndexOf = _dereq_('./_array-includes')(false) , IE_PROTO = _dereq_('./_shared-key')('IE_PROTO'); module.exports = function(object, names){ var O = toIObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(names.length > i)if(has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); } return result; }; },{"./_array-includes":82,"./_has":103,"./_shared-key":138,"./_to-iobject":143}],129:[function(_dereq_,module,exports){ // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = _dereq_('./_object-keys-internal') , enumBugKeys = _dereq_('./_enum-bug-keys'); module.exports = Object.keys || function keys(O){ return $keys(O, enumBugKeys); }; },{"./_enum-bug-keys":97,"./_object-keys-internal":128}],130:[function(_dereq_,module,exports){ exports.f = {}.propertyIsEnumerable; },{}],131:[function(_dereq_,module,exports){ // most Object methods by ES6 should accept primitives var $export = _dereq_('./_export') , core = _dereq_('./_core') , fails = _dereq_('./_fails'); module.exports = function(KEY, exec){ var fn = (core.Object || {})[KEY] || Object[KEY] , exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); }; },{"./_core":92,"./_export":99,"./_fails":100}],132:[function(_dereq_,module,exports){ module.exports = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; },{}],133:[function(_dereq_,module,exports){ var hide = _dereq_('./_hide'); module.exports = function(target, src, safe){ for(var key in src){ if(safe && target[key])target[key] = src[key]; else hide(target, key, src[key]); } return target; }; },{"./_hide":104}],134:[function(_dereq_,module,exports){ module.exports = _dereq_('./_hide'); },{"./_hide":104}],135:[function(_dereq_,module,exports){ // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var isObject = _dereq_('./_is-object') , anObject = _dereq_('./_an-object'); var check = function(O, proto){ anObject(O); if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); }; module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line function(test, buggy, set){ try { set = _dereq_('./_ctx')(Function.call, _dereq_('./_object-gopd').f(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }({}, false) : undefined), check: check }; },{"./_an-object":80,"./_ctx":93,"./_is-object":110,"./_object-gopd":123}],136:[function(_dereq_,module,exports){ 'use strict'; var global = _dereq_('./_global') , core = _dereq_('./_core') , dP = _dereq_('./_object-dp') , DESCRIPTORS = _dereq_('./_descriptors') , SPECIES = _dereq_('./_wks')('species'); module.exports = function(KEY){ var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY]; if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, { configurable: true, get: function(){ return this; } }); }; },{"./_core":92,"./_descriptors":95,"./_global":102,"./_object-dp":121,"./_wks":150}],137:[function(_dereq_,module,exports){ var def = _dereq_('./_object-dp').f , has = _dereq_('./_has') , TAG = _dereq_('./_wks')('toStringTag'); module.exports = function(it, tag, stat){ if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); }; },{"./_has":103,"./_object-dp":121,"./_wks":150}],138:[function(_dereq_,module,exports){ var shared = _dereq_('./_shared')('keys') , uid = _dereq_('./_uid'); module.exports = function(key){ return shared[key] || (shared[key] = uid(key)); }; },{"./_shared":139,"./_uid":147}],139:[function(_dereq_,module,exports){ var global = _dereq_('./_global') , SHARED = '__core-js_shared__' , store = global[SHARED] || (global[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; },{"./_global":102}],140:[function(_dereq_,module,exports){ var toInteger = _dereq_('./_to-integer') , defined = _dereq_('./_defined'); // true -> String#at // false -> String#codePointAt module.exports = function(TO_STRING){ return function(that, pos){ var s = String(defined(that)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; },{"./_defined":94,"./_to-integer":142}],141:[function(_dereq_,module,exports){ var toInteger = _dereq_('./_to-integer') , max = Math.max , min = Math.min; module.exports = function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; },{"./_to-integer":142}],142:[function(_dereq_,module,exports){ // 7.1.4 ToInteger var ceil = Math.ceil , floor = Math.floor; module.exports = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; },{}],143:[function(_dereq_,module,exports){ // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = _dereq_('./_iobject') , defined = _dereq_('./_defined'); module.exports = function(it){ return IObject(defined(it)); }; },{"./_defined":94,"./_iobject":107}],144:[function(_dereq_,module,exports){ // 7.1.15 ToLength var toInteger = _dereq_('./_to-integer') , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; },{"./_to-integer":142}],145:[function(_dereq_,module,exports){ // 7.1.13 ToObject(argument) var defined = _dereq_('./_defined'); module.exports = function(it){ return Object(defined(it)); }; },{"./_defined":94}],146:[function(_dereq_,module,exports){ // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = _dereq_('./_is-object'); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function(it, S){ if(!isObject(it))return it; var fn, val; if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to primitive value"); }; },{"./_is-object":110}],147:[function(_dereq_,module,exports){ var id = 0 , px = Math.random(); module.exports = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; },{}],148:[function(_dereq_,module,exports){ var global = _dereq_('./_global') , core = _dereq_('./_core') , LIBRARY = _dereq_('./_library') , wksExt = _dereq_('./_wks-ext') , defineProperty = _dereq_('./_object-dp').f; module.exports = function(name){ var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)}); }; },{"./_core":92,"./_global":102,"./_library":117,"./_object-dp":121,"./_wks-ext":149}],149:[function(_dereq_,module,exports){ exports.f = _dereq_('./_wks'); },{"./_wks":150}],150:[function(_dereq_,module,exports){ var store = _dereq_('./_shared')('wks') , uid = _dereq_('./_uid') , Symbol = _dereq_('./_global').Symbol , USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function(name){ return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; },{"./_global":102,"./_shared":139,"./_uid":147}],151:[function(_dereq_,module,exports){ var classof = _dereq_('./_classof') , ITERATOR = _dereq_('./_wks')('iterator') , Iterators = _dereq_('./_iterators'); module.exports = _dereq_('./_core').getIteratorMethod = function(it){ if(it != undefined)return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; },{"./_classof":86,"./_core":92,"./_iterators":115,"./_wks":150}],152:[function(_dereq_,module,exports){ var anObject = _dereq_('./_an-object') , get = _dereq_('./core.get-iterator-method'); module.exports = _dereq_('./_core').getIterator = function(it){ var iterFn = get(it); if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!'); return anObject(iterFn.call(it)); }; },{"./_an-object":80,"./_core":92,"./core.get-iterator-method":151}],153:[function(_dereq_,module,exports){ 'use strict'; var addToUnscopables = _dereq_('./_add-to-unscopables') , step = _dereq_('./_iter-step') , Iterators = _dereq_('./_iterators') , toIObject = _dereq_('./_to-iobject'); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = _dereq_('./_iter-define')(Array, 'Array', function(iterated, kind){ this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var O = this._t , kind = this._k , index = this._i++; if(!O || index >= O.length){ this._t = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); },{"./_add-to-unscopables":78,"./_iter-define":113,"./_iter-step":114,"./_iterators":115,"./_to-iobject":143}],154:[function(_dereq_,module,exports){ 'use strict'; var strong = _dereq_('./_collection-strong'); // 23.1 Map Objects module.exports = _dereq_('./_collection')('Map', function(get){ return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.1.3.6 Map.prototype.get(key) get: function get(key){ var entry = strong.getEntry(this, key); return entry && entry.v; }, // 23.1.3.9 Map.prototype.set(key, value) set: function set(key, value){ return strong.def(this, key === 0 ? 0 : key, value); } }, strong, true); },{"./_collection":91,"./_collection-strong":88}],155:[function(_dereq_,module,exports){ var $export = _dereq_('./_export') // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) $export($export.S, 'Object', {create: _dereq_('./_object-create')}); },{"./_export":99,"./_object-create":120}],156:[function(_dereq_,module,exports){ var $export = _dereq_('./_export'); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) $export($export.S + $export.F * !_dereq_('./_descriptors'), 'Object', {defineProperty: _dereq_('./_object-dp').f}); },{"./_descriptors":95,"./_export":99,"./_object-dp":121}],157:[function(_dereq_,module,exports){ // 19.1.2.5 Object.freeze(O) var isObject = _dereq_('./_is-object') , meta = _dereq_('./_meta').onFreeze; _dereq_('./_object-sap')('freeze', function($freeze){ return function freeze(it){ return $freeze && isObject(it) ? $freeze(meta(it)) : it; }; }); },{"./_is-object":110,"./_meta":118,"./_object-sap":131}],158:[function(_dereq_,module,exports){ // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) var toIObject = _dereq_('./_to-iobject') , $getOwnPropertyDescriptor = _dereq_('./_object-gopd').f; _dereq_('./_object-sap')('getOwnPropertyDescriptor', function(){ return function getOwnPropertyDescriptor(it, key){ return $getOwnPropertyDescriptor(toIObject(it), key); }; }); },{"./_object-gopd":123,"./_object-sap":131,"./_to-iobject":143}],159:[function(_dereq_,module,exports){ // 19.1.2.9 Object.getPrototypeOf(O) var toObject = _dereq_('./_to-object') , $getPrototypeOf = _dereq_('./_object-gpo'); _dereq_('./_object-sap')('getPrototypeOf', function(){ return function getPrototypeOf(it){ return $getPrototypeOf(toObject(it)); }; }); },{"./_object-gpo":127,"./_object-sap":131,"./_to-object":145}],160:[function(_dereq_,module,exports){ // 19.1.2.14 Object.keys(O) var toObject = _dereq_('./_to-object') , $keys = _dereq_('./_object-keys'); _dereq_('./_object-sap')('keys', function(){ return function keys(it){ return $keys(toObject(it)); }; }); },{"./_object-keys":129,"./_object-sap":131,"./_to-object":145}],161:[function(_dereq_,module,exports){ // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = _dereq_('./_export'); $export($export.S, 'Object', {setPrototypeOf: _dereq_('./_set-proto').set}); },{"./_export":99,"./_set-proto":135}],162:[function(_dereq_,module,exports){ arguments[4][63][0].apply(exports,arguments) },{"dup":63}],163:[function(_dereq_,module,exports){ 'use strict'; var $at = _dereq_('./_string-at')(true); // 21.1.3.27 String.prototype[@@iterator]() _dereq_('./_iter-define')(String, 'String', function(iterated){ this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var O = this._t , index = this._i , point; if(index >= O.length)return {value: undefined, done: true}; point = $at(O, index); this._i += point.length; return {value: point, done: false}; }); },{"./_iter-define":113,"./_string-at":140}],164:[function(_dereq_,module,exports){ 'use strict'; // ECMAScript 6 symbols shim var global = _dereq_('./_global') , has = _dereq_('./_has') , DESCRIPTORS = _dereq_('./_descriptors') , $export = _dereq_('./_export') , redefine = _dereq_('./_redefine') , META = _dereq_('./_meta').KEY , $fails = _dereq_('./_fails') , shared = _dereq_('./_shared') , setToStringTag = _dereq_('./_set-to-string-tag') , uid = _dereq_('./_uid') , wks = _dereq_('./_wks') , wksExt = _dereq_('./_wks-ext') , wksDefine = _dereq_('./_wks-define') , keyOf = _dereq_('./_keyof') , enumKeys = _dereq_('./_enum-keys') , isArray = _dereq_('./_is-array') , anObject = _dereq_('./_an-object') , toIObject = _dereq_('./_to-iobject') , toPrimitive = _dereq_('./_to-primitive') , createDesc = _dereq_('./_property-desc') , _create = _dereq_('./_object-create') , gOPNExt = _dereq_('./_object-gopn-ext') , $GOPD = _dereq_('./_object-gopd') , $DP = _dereq_('./_object-dp') , $keys = _dereq_('./_object-keys') , gOPD = $GOPD.f , dP = $DP.f , gOPN = gOPNExt.f , $Symbol = global.Symbol , $JSON = global.JSON , _stringify = $JSON && $JSON.stringify , PROTOTYPE = 'prototype' , HIDDEN = wks('_hidden') , TO_PRIMITIVE = wks('toPrimitive') , isEnum = {}.propertyIsEnumerable , SymbolRegistry = shared('symbol-registry') , AllSymbols = shared('symbols') , OPSymbols = shared('op-symbols') , ObjectProto = Object[PROTOTYPE] , USE_NATIVE = typeof $Symbol == 'function' , QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function(){ return _create(dP({}, 'a', { get: function(){ return dP(this, 'a', {value: 7}).a; } })).a != 7; }) ? function(it, key, D){ var protoDesc = gOPD(ObjectProto, key); if(protoDesc)delete ObjectProto[key]; dP(it, key, D); if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc); } : dP; var wrap = function(tag){ var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){ return typeof it == 'symbol'; } : function(it){ return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D){ if(it === ObjectProto)$defineProperty(OPSymbols, key, D); anObject(it); key = toPrimitive(key, true); anObject(D); if(has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D = _create(D, {enumerable: createDesc(0, false)}); } return setSymbolDesc(it, key, D); } return dP(it, key, D); }; var $defineProperties = function defineProperties(it, P){ anObject(it); var keys = enumKeys(P = toIObject(P)) , i = 0 , l = keys.length , key; while(l > i)$defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P){ return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key){ var E = isEnum.call(this, key = toPrimitive(key, true)); if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false; return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ it = toIObject(it); key = toPrimitive(key, true); if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return; var D = gOPD(it, key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it){ var names = gOPN(toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ var IS_OP = it === ObjectProto , names = gOPN(IS_OP ? OPSymbols : toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if(!USE_NATIVE){ $Symbol = function Symbol(){ if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!'); var tag = uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function(value){ if(this === ObjectProto)$set.call(OPSymbols, value); if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); }; if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set}); return wrap(tag); }; redefine($Symbol[PROTOTYPE], 'toString', function toString(){ return this._k; }); $GOPD.f = $getOwnPropertyDescriptor; $DP.f = $defineProperty; _dereq_('./_object-gopn').f = gOPNExt.f = $getOwnPropertyNames; _dereq_('./_object-pie').f = $propertyIsEnumerable; _dereq_('./_object-gops').f = $getOwnPropertySymbols; if(DESCRIPTORS && !_dereq_('./_library')){ redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } wksExt.f = function(name){ return wrap(wks(name)); } } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol}); for(var symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), i = 0; symbols.length > i; )wks(symbols[i++]); for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]); $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ if(isSymbol(key))return keyOf(SymbolRegistry, key); throw TypeError(key + ' is not a symbol!'); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }); $export($export.S + $export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){ var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it){ if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined var args = [it] , i = 1 , replacer, $replacer; while(arguments.length > i)args.push(arguments[i++]); replacer = args[1]; if(typeof replacer == 'function')$replacer = replacer; if($replacer || !isArray(replacer))replacer = function(key, value){ if($replacer)value = $replacer.call(this, key, value); if(!isSymbol(value))return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE][TO_PRIMITIVE] || _dereq_('./_hide')($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); },{"./_an-object":80,"./_descriptors":95,"./_enum-keys":98,"./_export":99,"./_fails":100,"./_global":102,"./_has":103,"./_hide":104,"./_is-array":109,"./_keyof":116,"./_library":117,"./_meta":118,"./_object-create":120,"./_object-dp":121,"./_object-gopd":123,"./_object-gopn":125,"./_object-gopn-ext":124,"./_object-gops":126,"./_object-keys":129,"./_object-pie":130,"./_property-desc":132,"./_redefine":134,"./_set-to-string-tag":137,"./_shared":139,"./_to-iobject":143,"./_to-primitive":146,"./_uid":147,"./_wks":150,"./_wks-define":148,"./_wks-ext":149}],165:[function(_dereq_,module,exports){ 'use strict'; var each = _dereq_('./_array-methods')(0) , redefine = _dereq_('./_redefine') , meta = _dereq_('./_meta') , assign = _dereq_('./_object-assign') , weak = _dereq_('./_collection-weak') , isObject = _dereq_('./_is-object') , getWeak = meta.getWeak , isExtensible = Object.isExtensible , uncaughtFrozenStore = weak.ufstore , tmp = {} , InternalMap; var wrapper = function(get){ return function WeakMap(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }; var methods = { // 23.3.3.3 WeakMap.prototype.get(key) get: function get(key){ if(isObject(key)){ var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this).get(key); return data ? data[this._i] : undefined; } }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function set(key, value){ return weak.def(this, key, value); } }; // 23.3 WeakMap Objects var $WeakMap = module.exports = _dereq_('./_collection')('WeakMap', wrapper, methods, weak, true, true); // IE11 WeakMap frozen keys fix if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){ InternalMap = weak.getConstructor(wrapper); assign(InternalMap.prototype, methods); meta.NEED = true; each(['delete', 'has', 'get', 'set'], function(key){ var proto = $WeakMap.prototype , method = proto[key]; redefine(proto, key, function(a, b){ // store frozen objects on internal weakmap shim if(isObject(a) && !isExtensible(a)){ if(!this._f)this._f = new InternalMap; var result = this._f[key](a, b); return key == 'set' ? this : result; // store all the rest on native weakmap } return method.call(this, a, b); }); }); } },{"./_array-methods":83,"./_collection":91,"./_collection-weak":90,"./_is-object":110,"./_meta":118,"./_object-assign":119,"./_redefine":134}],166:[function(_dereq_,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $export = _dereq_('./_export'); $export($export.P + $export.R, 'Map', {toJSON: _dereq_('./_collection-to-json')('Map')}); },{"./_collection-to-json":89,"./_export":99}],167:[function(_dereq_,module,exports){ _dereq_('./_wks-define')('asyncIterator'); },{"./_wks-define":148}],168:[function(_dereq_,module,exports){ _dereq_('./_wks-define')('observable'); },{"./_wks-define":148}],169:[function(_dereq_,module,exports){ _dereq_('./es6.array.iterator'); var global = _dereq_('./_global') , hide = _dereq_('./_hide') , Iterators = _dereq_('./_iterators') , TO_STRING_TAG = _dereq_('./_wks')('toStringTag'); for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ var NAME = collections[i] , Collection = global[NAME] , proto = Collection && Collection.prototype; if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = Iterators.Array; } },{"./_global":102,"./_hide":104,"./_iterators":115,"./_wks":150,"./es6.array.iterator":153}],170:[function(_dereq_,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}]},{},[10])(10) });
seogi1004/cdnjs
ajax/libs/parse/1.10.2/parse.js
JavaScript
mit
460,269
<?php /* * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@prestashop.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <contact@prestashop.com> * @copyright 2007-2015 PrestaShop SA * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ class DeliveryCore extends ObjectModel { /** @var int */ public $id_delivery; /** @var int **/ public $id_shop; /** @var int **/ public $id_shop_group; /** @var int */ public $id_carrier; /** @var int */ public $id_range_price; /** @var int */ public $id_range_weight; /** @var int */ public $id_zone; /** @var float */ public $price; /** * @see ObjectModel::$definition */ public static $definition = array( 'table' => 'delivery', 'primary' => 'id_delivery', 'fields' => array( 'id_carrier' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true), 'id_range_price' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true), 'id_range_weight' =>array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true), 'id_zone' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true), 'id_shop' => array('type' => self::TYPE_INT), 'id_shop_group' => array('type' => self::TYPE_INT), 'price' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice', 'required' => true), ), ); protected $webserviceParameters = array( 'objectsNodeName' => 'deliveries', 'fields' => array( 'id_carrier' => array('xlink_resource' => 'carriers'), 'id_range_price' => array('xlink_resource' => 'price_ranges'), 'id_range_weight' => array('xlink_resource' => 'weight_ranges'), 'id_zone' => array('xlink_resource' => 'zones'), ) ); public function getFields() { $fields = parent::getFields(); // @todo add null management in definitions if ($this->id_shop) { $fields['id_shop'] = (int)$this->id_shop; } else { $fields['id_shop'] = null; } if ($this->id_shop_group) { $fields['id_shop_group'] = (int)$this->id_shop_group; } else { $fields['id_shop_group'] = null; } return $fields; } }
insbadia-dawm8/gitteam
proyecto/classes/Delivery.php
PHP
mit
3,194
<?php namespace Sabre\CardDAV; use Sabre\DAV; /** * Parses the addressbook-query report request body. * * Whoever designed this format, and the CalDAV equivalent even more so, * has no feel for design. * * @copyright Copyright (C) 2007-2014 fruux GmbH (https://fruux.com/). * @author Evert Pot (http://evertpot.com/) * @license http://sabre.io/license/ Modified BSD License */ class AddressBookQueryParser { const TEST_ANYOF = 'anyof'; const TEST_ALLOF = 'allof'; /** * List of requested properties the client wanted * * @var array */ public $requestedProperties; /** * The number of results the client wants * * null means it wasn't specified, which in most cases means 'all results'. * * @var int|null */ public $limit; /** * List of property filters. * * @var array */ public $filters; /** * Either TEST_ANYOF or TEST_ALLOF * * @var string */ public $test; /** * DOM Document * * @var DOMDocument */ protected $dom; /** * DOM XPath object * * @var DOMXPath */ protected $xpath; /** * Creates the parser * * @param \DOMDocument $dom */ public function __construct(\DOMDocument $dom) { $this->dom = $dom; $this->xpath = new \DOMXPath($dom); $this->xpath->registerNameSpace('card',Plugin::NS_CARDDAV); } /** * Parses the request. * * @return void */ public function parse() { $filterNode = null; $limit = $this->xpath->evaluate('number(/card:addressbook-query/card:limit/card:nresults)'); if (is_nan($limit)) $limit = null; $filter = $this->xpath->query('/card:addressbook-query/card:filter'); // According to the CardDAV spec there needs to be exactly 1 filter // element. However, KDE 4.8.2 contains a bug that will encode 0 filter // elements, so this is a workaround for that. // // See: https://bugs.kde.org/show_bug.cgi?id=300047 if ($filter->length === 0) { $test = null; $filter = null; } elseif ($filter->length === 1) { $filter = $filter->item(0); $test = $this->xpath->evaluate('string(@test)', $filter); } else { throw new DAV\Exception\BadRequest('Only one filter element is allowed'); } if (!$test) $test = self::TEST_ANYOF; if ($test !== self::TEST_ANYOF && $test !== self::TEST_ALLOF) { throw new DAV\Exception\BadRequest('The test attribute must either hold "anyof" or "allof"'); } $propFilters = array(); $propFilterNodes = $this->xpath->query('card:prop-filter', $filter); for($ii=0; $ii < $propFilterNodes->length; $ii++) { $propFilters[] = $this->parsePropFilterNode($propFilterNodes->item($ii)); } $this->filters = $propFilters; $this->limit = $limit; $this->requestedProperties = array_keys(DAV\XMLUtil::parseProperties($this->dom->firstChild)); $this->test = $test; } /** * Parses the prop-filter xml element * * @param \DOMElement $propFilterNode * @return array */ protected function parsePropFilterNode(\DOMElement $propFilterNode) { $propFilter = array(); $propFilter['name'] = $propFilterNode->getAttribute('name'); $propFilter['test'] = $propFilterNode->getAttribute('test'); if (!$propFilter['test']) $propFilter['test'] = 'anyof'; $propFilter['is-not-defined'] = $this->xpath->query('card:is-not-defined', $propFilterNode)->length>0; $paramFilterNodes = $this->xpath->query('card:param-filter', $propFilterNode); $propFilter['param-filters'] = array(); for($ii=0;$ii<$paramFilterNodes->length;$ii++) { $propFilter['param-filters'][] = $this->parseParamFilterNode($paramFilterNodes->item($ii)); } $propFilter['text-matches'] = array(); $textMatchNodes = $this->xpath->query('card:text-match', $propFilterNode); for($ii=0;$ii<$textMatchNodes->length;$ii++) { $propFilter['text-matches'][] = $this->parseTextMatchNode($textMatchNodes->item($ii)); } return $propFilter; } /** * Parses the param-filter element * * @param \DOMElement $paramFilterNode * @return array */ public function parseParamFilterNode(\DOMElement $paramFilterNode) { $paramFilter = array(); $paramFilter['name'] = $paramFilterNode->getAttribute('name'); $paramFilter['is-not-defined'] = $this->xpath->query('card:is-not-defined', $paramFilterNode)->length>0; $paramFilter['text-match'] = null; $textMatch = $this->xpath->query('card:text-match', $paramFilterNode); if ($textMatch->length>0) { $paramFilter['text-match'] = $this->parseTextMatchNode($textMatch->item(0)); } return $paramFilter; } /** * Text match * * @param \DOMElement $textMatchNode * @return array */ public function parseTextMatchNode(\DOMElement $textMatchNode) { $matchType = $textMatchNode->getAttribute('match-type'); if (!$matchType) $matchType = 'contains'; if (!in_array($matchType, array('contains', 'equals', 'starts-with', 'ends-with'))) { throw new DAV\Exception\BadRequest('Unknown match-type: ' . $matchType); } $negateCondition = $textMatchNode->getAttribute('negate-condition'); $negateCondition = $negateCondition==='yes'; $collation = $textMatchNode->getAttribute('collation'); if (!$collation) $collation = 'i;unicode-casemap'; return array( 'negate-condition' => $negateCondition, 'collation' => $collation, 'match-type' => $matchType, 'value' => $textMatchNode->nodeValue ); } }
zzottel/hubzilla
vendor/sabre/dav/lib/Sabre/CardDAV/AddressBookQueryParser.php
PHP
mit
6,043
Meteor.publish('settings', function() { var options = {}; if(!isAdminById(this.userId)){ options = _.extend(options, { fields: { mailChimpAPIKey: false, mailChimpListId: false } }); } return Settings.find({}, options); }); Meteor.publish('invites', function(){ if(canViewById(this.userId)){ return Invites.find({invitingUserId:this.userId}); } });
UCSC-MedBook/MedBook-Telescope3
webapp/server/publications/other.js
JavaScript
mit
400
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Functions to load the test cases ("koans") that make up the Path to Enlightenment. ''' import io import unittest # The path to enlightenment starts with the following: KOANS_FILENAME = 'koans.txt' def filter_koan_names(lines): ''' Strips leading and trailing whitespace, then filters out blank lines and comment lines. ''' for line in lines: line = line.strip() if line.startswith('#'): continue if line: yield line return def names_from_file(filename): ''' Opens the given ``filename`` and yields the fully-qualified names of TestCases found inside (one per line). ''' with io.open(filename, 'rt', encoding='utf8') as names_file: for name in filter_koan_names(names_file): yield name return def koans_suite(names): ''' Returns a ``TestSuite`` loaded with all tests found in the given ``names``, preserving the order in which they are found. ''' suite = unittest.TestSuite() loader = unittest.TestLoader() loader.sortTestMethodsUsing = None for name in names: tests = loader.loadTestsFromName(name) suite.addTests(tests) return suite def koans(filename=KOANS_FILENAME): ''' Returns a ``TestSuite`` loaded with all the koans (``TestCase``s) listed in ``filename``. ''' names = names_from_file(filename) return koans_suite(names)
haroldtreen/python_koans
runner/path_to_enlightenment.py
Python
mit
1,482
(function(){var d=window.AmCharts;d.AmRadarChart=d.Class({inherits:d.AmCoordinateChart,construct:function(a){this.type="radar";d.AmRadarChart.base.construct.call(this,a);this.cname="AmRadarChart";this.marginRight=this.marginBottom=this.marginTop=this.marginLeft=0;this.radius="35%";d.applyTheme(this,a,this.cname)},initChart:function(){d.AmRadarChart.base.initChart.call(this);if(this.dataChanged)this.parseData();else this.onDataUpdated()},onDataUpdated:function(){this.drawChart()},updateGraphs:function(){var a= this.graphs,b;for(b=0;b<a.length;b++){var c=a[b];c.index=b;c.width=this.realRadius;c.height=this.realRadius;c.x=this.marginLeftReal;c.y=this.marginTopReal;c.data=this.chartData}},parseData:function(){d.AmRadarChart.base.parseData.call(this);this.parseSerialData(this.dataProvider)},updateValueAxes:function(){var a=this.valueAxes,b;for(b=0;b<a.length;b++){var c=a[b];c.axisRenderer=d.RadAxis;c.guideFillRenderer=d.RadarFill;c.axisItemRenderer=d.RadItem;c.autoGridCount=!1;c.rMultiplier=1;c.x=this.marginLeftReal; c.y=this.marginTopReal;c.width=this.realRadius;c.height=this.realRadius;c.marginsChanged=!0;c.titleDY=c.y}},drawChart:function(){d.AmRadarChart.base.drawChart.call(this);var a=this.updateWidth(),b=this.updateHeight(),c=this.marginTop+this.getTitleHeight(),f=this.marginLeft,m=this.marginBottom,n=this.marginRight,e=b-c-m;this.marginLeftReal=f+(a-f-n)/2;this.marginTopReal=c+e/2;this.realRadius=d.toCoordinate(this.radius,Math.min(a-f-n,b-c-m),e);this.updateValueAxes();this.updateGraphs();a=this.chartData; if(d.ifArray(a)){if(0<this.realWidth&&0<this.realHeight){a=a.length-1;c=this.valueAxes;for(b=0;b<c.length;b++)c[b].zoom(0,a);c=this.graphs;for(b=0;b<c.length;b++)c[b].zoom(0,a);(a=this.legend)&&a.invalidateSize()}}else this.cleanChart();this.dispDUpd();this.gridSet.toBack();this.axesSet.toBack();this.set.toBack()},formatString:function(a,b,c){var f=b.graph;-1!=a.indexOf("[[category]]")&&(a=a.replace(/\[\[category\]\]/g,String(b.serialDataItem.category)));f=f.numberFormatter;f||(f=this.nf);a=d.formatValue(a, b.values,["value"],f,"",this.usePrefixes,this.prefixesOfSmallNumbers,this.prefixesOfBigNumbers);-1!=a.indexOf("[[")&&(a=d.formatDataContextValue(a,b.dataContext));return a=d.AmRadarChart.base.formatString.call(this,a,b,c)},cleanChart:function(){d.callMethod("destroy",[this.valueAxes,this.graphs])}})})();(function(){var d=window.AmCharts;d.RadAxis=d.Class({construct:function(a){var b=a.chart,c=a.axisThickness,f=a.axisColor,m=a.axisAlpha;this.set=b.container.set();this.set.translate(a.x,a.y);b.axesSet.push(this.set);var n=a.axisTitleOffset,e=a.radarCategoriesEnabled,r=a.chart.fontFamily,h=a.fontSize;void 0===h&&(h=a.chart.fontSize);var k=a.color;void 0===k&&(k=a.chart.color);if(b){this.axisWidth=a.height;var p=b.chartData,l=p.length,w,z=this.axisWidth;"middle"==a.pointPosition&&"circles"!=a.gridType&& (a.rMultiplier=Math.cos(180/l*Math.PI/180),z*=a.rMultiplier);for(w=0;w<l;w+=a.axisFrequency){var q=180-360/l*w,g=q;"middle"==a.pointPosition&&(g-=180/l);var t=this.axisWidth*Math.sin(q/180*Math.PI),q=this.axisWidth*Math.cos(q/180*Math.PI);0<m&&(t=d.line(b.container,[0,t],[0,q],f,m,c),this.set.push(t),d.setCN(b,t,a.bcn+"line"));if(e){var x="start",t=(z+n)*Math.sin(g/180*Math.PI),q=(z+n)*Math.cos(g/180*Math.PI);if(180==g||0===g)x="middle",t-=5;0>g&&(x="end",t-=10);180==g&&(q-=5);0===g&&(q+=5);g=d.text(b.container, p[w].category,k,r,h,x);g.translate(t+5,q);this.set.push(g);d.setCN(b,g,a.bcn+"title")}}}}})})();(function(){var d=window.AmCharts;d.RadItem=d.Class({construct:function(a,b,c,f,m,n,e,r){f=a.chart;void 0===c&&(c="");var h=a.chart.fontFamily,k=a.fontSize;void 0===k&&(k=a.chart.fontSize);var p=a.color;void 0===p&&(p=a.chart.color);var l=a.chart.container;this.set=m=l.set();var w=a.axisColor,z=a.axisAlpha,q=a.tickLength,g=a.gridAlpha,t=a.gridThickness,x=a.gridColor,D=a.dashLength,E=a.fillColor,B=a.fillAlpha,F=a.labelsEnabled;n=a.counter;var G=a.inside,H=a.gridType,u,J=a.labelOffset,A;b-=a.height; var y;e?(F=!0,void 0!==e.id&&(A=f.classNamePrefix+"-guide-"+e.id),isNaN(e.tickLength)||(q=e.tickLength),void 0!=e.lineColor&&(x=e.lineColor),isNaN(e.lineAlpha)||(g=e.lineAlpha),isNaN(e.dashLength)||(D=e.dashLength),isNaN(e.lineThickness)||(t=e.lineThickness),!0===e.inside&&(G=!0),void 0!==e.boldLabel&&(r=e.boldLabel)):c||(g/=3,q/=2);var I="end",C=-1;G&&(I="start",C=1);var v;F&&(v=d.text(l,c,p,h,k,I,r),v.translate((q+3+J)*C,b),m.push(v),d.setCN(f,v,a.bcn+"label"),e&&d.setCN(f,v,"guide"),d.setCN(f, v,A,!0),this.label=v,y=d.line(l,[0,q*C],[b,b],w,z,t),m.push(y),d.setCN(f,y,a.bcn+"tick"),e&&d.setCN(f,y,"guide"),d.setCN(f,y,A,!0));b=Math.abs(b);r=[];h=[];if(0<g){if("polygons"==H){u=a.data.length;for(k=0;k<u;k++)p=180-360/u*k,r.push(b*Math.sin(p/180*Math.PI)),h.push(b*Math.cos(p/180*Math.PI));r.push(r[0]);h.push(h[0]);g=d.line(l,r,h,x,g,t,D)}else g=d.circle(l,b,"#FFFFFF",0,t,x,g);m.push(g);d.setCN(f,g,a.bcn+"grid");d.setCN(f,g,A,!0);e&&d.setCN(f,g,"guide")}if(1==n&&0<B&&!e&&""!==c){e=a.previousCoord; if("polygons"==H){for(k=u;0<=k;k--)p=180-360/u*k,r.push(e*Math.sin(p/180*Math.PI)),h.push(e*Math.cos(p/180*Math.PI));u=d.polygon(l,r,h,E,B)}else u=d.wedge(l,0,0,0,360,b,b,e,0,{fill:E,"fill-opacity":B,stroke:"#000","stroke-opacity":0,"stroke-width":1});m.push(u);d.setCN(f,u,a.bcn+"fill");d.setCN(f,u,A,!0)}!1===a.visible&&(y&&y.hide(),v&&v.hide());""!==c&&(a.counter=0===n?1:0,a.previousCoord=b)},graphics:function(){return this.set},getLabel:function(){return this.label}})})();(function(){var d=window.AmCharts;d.RadarFill=d.Class({construct:function(a,b,c,f){b-=a.axisWidth;c-=a.axisWidth;var m=Math.min(b,c);c=Math.max(b,c);b=a.chart;var n=b.container,e=f.fillAlpha,r=f.fillColor;c=Math.abs(c);var m=Math.abs(m),h=Math.min(c,m);c=Math.max(c,m);var m=h,h=f.angle+90,k=f.toAngle+90;isNaN(h)&&(h=0);isNaN(k)&&(k=360);this.set=n.set();void 0===r&&(r="#000000");isNaN(e)&&(e=0);if("polygons"==a.gridType){var k=[],p=[];a=a.data.length;var l;for(l=0;l<a;l++)h=180-360/a*l,k.push(c*Math.sin(h/ 180*Math.PI)),p.push(c*Math.cos(h/180*Math.PI));k.push(k[0]);p.push(p[0]);for(l=a;0<=l;l--)h=180-360/a*l,k.push(m*Math.sin(h/180*Math.PI)),p.push(m*Math.cos(h/180*Math.PI));n=d.polygon(n,k,p,r,e)}else n=d.wedge(n,0,0,h,k-h,c,c,m,0,{fill:r,"fill-opacity":e,stroke:"#000","stroke-opacity":0,"stroke-width":1});d.setCN(b,n,"guide-fill");f.id&&d.setCN(b,n,"guide-fill-"+f.id);this.set.push(n);this.fill=n},graphics:function(){return this.set},getLabel:function(){}})})();
ahocevar/cdnjs
ajax/libs/amcharts/3.19.5/radar.js
JavaScript
mit
6,454
# # Makefile for the drm device driver. This driver provides support for the # Direct Rendering Infrastructure (DRI) in XFree86 4.1.0 and higher. ccflags-y := -Iinclude/drm radeon-y := radeon_drv.o radeon_cp.o radeon_state.o radeon_mem.o radeon_irq.o r300_cmdbuf.o r600_cp.o radeon-$(CONFIG_COMPAT) += radeon_ioc32.o obj-$(CONFIG_DRM_RADEON)+= radeon.o
pichina/linux-bcache
drivers/gpu/drm/radeon/Makefile
Makefile
gpl-2.0
357
/* * Compressed RAM block device * * Copyright (C) 2008, 2009, 2010 Nitin Gupta * * This code is released using a dual license strategy: BSD/GPL * You can choose the licence that better fits your requirements. * * Released under the terms of 3-clause BSD License * Released under the terms of GNU General Public License Version 2.0 * * Project home: http://compcache.googlecode.com */ #define KMSG_COMPONENT "zram" #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt #ifdef CONFIG_ZRAM_DEBUG #define DEBUG #endif #include <linux/module.h> #include <linux/kernel.h> #include <linux/bio.h> #include <linux/bitops.h> #include <linux/blkdev.h> #include <linux/buffer_head.h> #include <linux/device.h> #include <linux/genhd.h> #include <linux/highmem.h> #include <linux/slab.h> #include <linux/lz4.h> #include <linux/lzo.h> #include <linux/string.h> #include <linux/vmalloc.h> #include <linux/ratelimit.h> #include <linux/show_mem_notifier.h> #include "zram_drv.h" static inline int z_decompress_safe(const unsigned char *src, size_t src_len, unsigned char *dest, size_t *dest_len) { #ifdef CONFIG_ZRAM_LZ4_COMPRESS return lz4_decompress_unknownoutputsize(src, src_len, dest, dest_len); #else return lzo1x_decompress_safe(src, src_len, dest, dest_len); #endif } static inline int z_compress(const unsigned char *src, size_t src_len, unsigned char *dst, size_t *dst_len, void *wrkmem) { #ifdef CONFIG_ZRAM_LZ4_COMPRESS return lz4_compress(src, src_len, dst, dst_len, wrkmem); #else return lzo1x_1_compress(src, src_len, dst, dst_len, wrkmem); #endif } static inline size_t z_scratch_size(void) { #ifdef CONFIG_ZRAM_LZ4_COMPRESS return LZ4_MEM_COMPRESS; #else return LZO1X_MEM_COMPRESS; #endif } /* Globals */ static int zram_major; static struct zram *zram_devices; /* * We don't need to see memory allocation errors more than once every 1 * second to know that a problem is occurring. */ #define ALLOC_ERROR_LOG_RATE_MS 1000 /* Module params (documentation at end) */ static unsigned int num_devices = 1; static int zram_show_mem_notifier(struct notifier_block *nb, unsigned long action, void *data) { int i; if (!zram_devices) return 0; for (i = 0; i < num_devices; i++) { struct zram *zram = &zram_devices[i]; struct zram_meta *meta = zram->meta; if (!down_read_trylock(&zram->init_lock)) continue; if (zram->init_done) { u64 val; u64 data_size; val = zs_get_total_size_bytes(meta->mem_pool); data_size = atomic64_read(&zram->stats.compr_size); pr_info("Zram[%d] mem_used_total = %llu\n", i, val); pr_info("Zram[%d] compr_data_size = %llu\n", i, (unsigned long long)data_size); pr_info("Zram[%d] orig_data_size = %u\n", i, zram->stats.pages_stored); } up_read(&zram->init_lock); } return 0; } static struct notifier_block zram_show_mem_notifier_block = { .notifier_call = zram_show_mem_notifier }; static inline struct zram *dev_to_zram(struct device *dev) { return (struct zram *)dev_to_disk(dev)->private_data; } static ssize_t disksize_show(struct device *dev, struct device_attribute *attr, char *buf) { struct zram *zram = dev_to_zram(dev); return sprintf(buf, "%llu\n", zram->disksize); } static ssize_t initstate_show(struct device *dev, struct device_attribute *attr, char *buf) { struct zram *zram = dev_to_zram(dev); return sprintf(buf, "%u\n", zram->init_done); } static ssize_t num_reads_show(struct device *dev, struct device_attribute *attr, char *buf) { struct zram *zram = dev_to_zram(dev); return sprintf(buf, "%llu\n", (u64)atomic64_read(&zram->stats.num_reads)); } static ssize_t num_writes_show(struct device *dev, struct device_attribute *attr, char *buf) { struct zram *zram = dev_to_zram(dev); return sprintf(buf, "%llu\n", (u64)atomic64_read(&zram->stats.num_writes)); } static ssize_t invalid_io_show(struct device *dev, struct device_attribute *attr, char *buf) { struct zram *zram = dev_to_zram(dev); return sprintf(buf, "%llu\n", (u64)atomic64_read(&zram->stats.invalid_io)); } static ssize_t notify_free_show(struct device *dev, struct device_attribute *attr, char *buf) { struct zram *zram = dev_to_zram(dev); return sprintf(buf, "%llu\n", (u64)atomic64_read(&zram->stats.notify_free)); } static ssize_t zero_pages_show(struct device *dev, struct device_attribute *attr, char *buf) { struct zram *zram = dev_to_zram(dev); return sprintf(buf, "%u\n", zram->stats.pages_zero); } static ssize_t orig_data_size_show(struct device *dev, struct device_attribute *attr, char *buf) { struct zram *zram = dev_to_zram(dev); return sprintf(buf, "%llu\n", (u64)(zram->stats.pages_stored) << PAGE_SHIFT); } static ssize_t compr_data_size_show(struct device *dev, struct device_attribute *attr, char *buf) { struct zram *zram = dev_to_zram(dev); return sprintf(buf, "%llu\n", (u64)atomic64_read(&zram->stats.compr_size)); } static ssize_t mem_used_total_show(struct device *dev, struct device_attribute *attr, char *buf) { u64 val = 0; struct zram *zram = dev_to_zram(dev); struct zram_meta *meta = zram->meta; down_read(&zram->init_lock); if (zram->init_done) val = zs_get_total_size_bytes(meta->mem_pool); up_read(&zram->init_lock); return sprintf(buf, "%llu\n", val); } static int zram_test_flag(struct zram_meta *meta, u32 index, enum zram_pageflags flag) { return meta->table[index].flags & BIT(flag); } static void zram_set_flag(struct zram_meta *meta, u32 index, enum zram_pageflags flag) { meta->table[index].flags |= BIT(flag); } static void zram_clear_flag(struct zram_meta *meta, u32 index, enum zram_pageflags flag) { meta->table[index].flags &= ~BIT(flag); } static inline int is_partial_io(struct bio_vec *bvec) { return bvec->bv_len != PAGE_SIZE; } /* * Check if request is within bounds and aligned on zram logical blocks. */ static inline int valid_io_request(struct zram *zram, struct bio *bio) { u64 start, end, bound; /* unaligned request */ if (unlikely(bio->bi_sector & (ZRAM_SECTOR_PER_LOGICAL_BLOCK - 1))) return 0; if (unlikely(bio->bi_size & (ZRAM_LOGICAL_BLOCK_SIZE - 1))) return 0; start = bio->bi_sector; end = start + (bio->bi_size >> SECTOR_SHIFT); bound = zram->disksize >> SECTOR_SHIFT; /* out of range range */ if (unlikely(start >= bound || end > bound || start > end)) return 0; /* I/O request is valid */ return 1; } static void zram_meta_free(struct zram_meta *meta) { zs_destroy_pool(meta->mem_pool); kfree(meta->compress_workmem); free_pages((unsigned long)meta->compress_buffer, 1); vfree(meta->table); kfree(meta); } static struct zram_meta *zram_meta_alloc(u64 disksize) { size_t num_pages; struct zram_meta *meta = kmalloc(sizeof(*meta), GFP_KERNEL); if (!meta) goto out; meta->compress_workmem = kzalloc(z_scratch_size(), GFP_KERNEL); if (!meta->compress_workmem) goto free_meta; meta->compress_buffer = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO, 1); if (!meta->compress_buffer) { pr_err("Error allocating compressor buffer space\n"); goto free_workmem; } num_pages = disksize >> PAGE_SHIFT; meta->table = vzalloc(num_pages * sizeof(*meta->table)); if (!meta->table) { pr_err("Error allocating zram address table\n"); goto free_buffer; } meta->mem_pool = zs_create_pool(GFP_NOIO | __GFP_HIGHMEM | __GFP_NOWARN); if (!meta->mem_pool) { pr_err("Error creating memory pool\n"); goto free_table; } return meta; free_table: vfree(meta->table); free_buffer: free_pages((unsigned long)meta->compress_buffer, 1); free_workmem: kfree(meta->compress_workmem); free_meta: kfree(meta); meta = NULL; out: return meta; } static void update_position(u32 *index, int *offset, struct bio_vec *bvec) { if (*offset + bvec->bv_len >= PAGE_SIZE) (*index)++; *offset = (*offset + bvec->bv_len) % PAGE_SIZE; } static int page_zero_filled(void *ptr) { unsigned int pos; unsigned long *page; page = (unsigned long *)ptr; for (pos = 0; pos != PAGE_SIZE / sizeof(*page); pos++) { if (page[pos]) return 0; } return 1; } static void handle_zero_page(struct bio_vec *bvec) { struct page *page = bvec->bv_page; void *user_mem; user_mem = kmap_atomic(page); if (is_partial_io(bvec)) memset(user_mem + bvec->bv_offset, 0, bvec->bv_len); else clear_page(user_mem); kunmap_atomic(user_mem); flush_dcache_page(page); } static void zram_free_page(struct zram *zram, size_t index) { struct zram_meta *meta = zram->meta; unsigned long handle = meta->table[index].handle; u16 size = meta->table[index].size; if (unlikely(!handle)) { /* * No memory is allocated for zero filled pages. * Simply clear zero page flag. */ if (zram_test_flag(meta, index, ZRAM_ZERO)) { zram_clear_flag(meta, index, ZRAM_ZERO); zram->stats.pages_zero--; } return; } if (unlikely(size > max_zpage_size)) zram->stats.bad_compress--; zs_free(meta->mem_pool, handle); if (size <= PAGE_SIZE / 2) zram->stats.good_compress--; atomic64_sub(meta->table[index].size, &zram->stats.compr_size); zram->stats.pages_stored--; meta->table[index].handle = 0; meta->table[index].size = 0; } static int zram_decompress_page(struct zram *zram, char *mem, u32 index) { int ret = LZO_E_OK; size_t clen = PAGE_SIZE; unsigned char *cmem; struct zram_meta *meta = zram->meta; unsigned long handle = meta->table[index].handle; if (!handle || zram_test_flag(meta, index, ZRAM_ZERO)) { clear_page(mem); return 0; } cmem = zs_map_object(meta->mem_pool, handle, ZS_MM_RO); if (meta->table[index].size == PAGE_SIZE) copy_page(mem, cmem); else ret = z_decompress_safe(cmem, meta->table[index].size, mem, &clen); zs_unmap_object(meta->mem_pool, handle); /* Should NEVER happen. Return bio error if it does. */ if (unlikely(ret != LZO_E_OK)) { pr_err("Decompression failed! err=%d, page=%u\n", ret, index); atomic64_inc(&zram->stats.failed_reads); return ret; } return 0; } static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec, u32 index, int offset, struct bio *bio) { int ret; struct page *page; unsigned char *user_mem, *uncmem = NULL; struct zram_meta *meta = zram->meta; page = bvec->bv_page; if (unlikely(!meta->table[index].handle) || zram_test_flag(meta, index, ZRAM_ZERO)) { handle_zero_page(bvec); return 0; } if (is_partial_io(bvec)) /* Use a temporary buffer to decompress the page */ uncmem = kmalloc(PAGE_SIZE, GFP_NOIO); user_mem = kmap_atomic(page); if (!is_partial_io(bvec)) uncmem = user_mem; if (!uncmem) { pr_info("Unable to allocate temp memory\n"); ret = -ENOMEM; goto out_cleanup; } ret = zram_decompress_page(zram, uncmem, index); /* Should NEVER happen. Return bio error if it does. */ if (unlikely(ret != LZO_E_OK)) goto out_cleanup; if (is_partial_io(bvec)) memcpy(user_mem + bvec->bv_offset, uncmem + offset, bvec->bv_len); flush_dcache_page(page); ret = 0; out_cleanup: kunmap_atomic(user_mem); if (is_partial_io(bvec)) kfree(uncmem); return ret; } static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec, u32 index, int offset) { int ret = 0; size_t clen; unsigned long handle; struct page *page; unsigned char *user_mem, *cmem, *src, *uncmem = NULL; struct zram_meta *meta = zram->meta; static unsigned long zram_rs_time; page = bvec->bv_page; src = meta->compress_buffer; if (is_partial_io(bvec)) { /* * This is a partial IO. We need to read the full page * before to write the changes. */ uncmem = kmalloc(PAGE_SIZE, GFP_NOIO); if (!uncmem) { ret = -ENOMEM; goto out; } ret = zram_decompress_page(zram, uncmem, index); if (ret) goto out; } user_mem = kmap_atomic(page); if (is_partial_io(bvec)) { memcpy(uncmem + offset, user_mem + bvec->bv_offset, bvec->bv_len); kunmap_atomic(user_mem); user_mem = NULL; } else { uncmem = user_mem; } if (page_zero_filled(uncmem)) { kunmap_atomic(user_mem); /* Free memory associated with this sector now. */ zram_free_page(zram, index); zram->stats.pages_zero++; zram_set_flag(meta, index, ZRAM_ZERO); ret = 0; goto out; } /* * zram_slot_free_notify could miss free so that let's * double check. */ if (unlikely(meta->table[index].handle || zram_test_flag(meta, index, ZRAM_ZERO))) zram_free_page(zram, index); ret = z_compress(uncmem, PAGE_SIZE, src, &clen, meta->compress_workmem); if (!is_partial_io(bvec)) { kunmap_atomic(user_mem); user_mem = NULL; uncmem = NULL; } if (unlikely(ret != LZO_E_OK)) { pr_err("Compression failed! err=%d\n", ret); goto out; } if (unlikely(clen > max_zpage_size)) { zram->stats.bad_compress++; clen = PAGE_SIZE; src = NULL; if (is_partial_io(bvec)) src = uncmem; } handle = zs_malloc(meta->mem_pool, clen); if (!handle) { if (printk_timed_ratelimit(&zram_rs_time, ALLOC_ERROR_LOG_RATE_MS)) pr_info("Error allocating memory for compressed page: %u, size=%zu\n", index, clen); ret = -ENOMEM; goto out; } cmem = zs_map_object(meta->mem_pool, handle, ZS_MM_WO); if ((clen == PAGE_SIZE) && !is_partial_io(bvec)) { src = kmap_atomic(page); copy_page(cmem, src); kunmap_atomic(src); } else { memcpy(cmem, src, clen); } zs_unmap_object(meta->mem_pool, handle); /* * Free memory associated with this sector * before overwriting unused sectors. */ zram_free_page(zram, index); meta->table[index].handle = handle; meta->table[index].size = clen; /* Update stats */ atomic64_add(clen, &zram->stats.compr_size); zram->stats.pages_stored++; if (clen <= PAGE_SIZE / 2) zram->stats.good_compress++; out: if (is_partial_io(bvec)) kfree(uncmem); if (ret) atomic64_inc(&zram->stats.failed_writes); return ret; } static void handle_pending_slot_free(struct zram *zram) { struct zram_slot_free *free_rq; spin_lock(&zram->slot_free_lock); while (zram->slot_free_rq) { free_rq = zram->slot_free_rq; zram->slot_free_rq = free_rq->next; zram_free_page(zram, free_rq->index); kfree(free_rq); } spin_unlock(&zram->slot_free_lock); } static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index, int offset, struct bio *bio, int rw) { int ret; if (rw == READ) { down_read(&zram->lock); handle_pending_slot_free(zram); ret = zram_bvec_read(zram, bvec, index, offset, bio); up_read(&zram->lock); } else { down_write(&zram->lock); handle_pending_slot_free(zram); ret = zram_bvec_write(zram, bvec, index, offset); up_write(&zram->lock); } return ret; } static void zram_reset_device(struct zram *zram, bool reset_capacity) { size_t index; struct zram_meta *meta; flush_work(&zram->free_work); down_write(&zram->init_lock); if (!zram->init_done) { up_write(&zram->init_lock); return; } meta = zram->meta; zram->init_done = 0; /* Free all pages that are still in this zram device */ for (index = 0; index < zram->disksize >> PAGE_SHIFT; index++) { unsigned long handle = meta->table[index].handle; if (!handle) continue; zs_free(meta->mem_pool, handle); } zram_meta_free(zram->meta); zram->meta = NULL; /* Reset stats */ memset(&zram->stats, 0, sizeof(zram->stats)); zram->disksize = 0; if (reset_capacity) set_capacity(zram->disk, 0); up_write(&zram->init_lock); } static void zram_init_device(struct zram *zram, struct zram_meta *meta) { if (zram->disksize > 2 * (totalram_pages << PAGE_SHIFT)) { pr_info( "There is little point creating a zram of greater than " "twice the size of memory since we expect a 2:1 compression " "ratio. Note that zram uses about 0.1%% of the size of " "the disk when not in use so a huge zram is " "wasteful.\n" "\tMemory Size: %lu kB\n" "\tSize you selected: %llu kB\n" "Continuing anyway ...\n", (totalram_pages << PAGE_SHIFT) >> 10, zram->disksize >> 10 ); } /* zram devices sort of resembles non-rotational disks */ queue_flag_set_unlocked(QUEUE_FLAG_NONROT, zram->disk->queue); zram->meta = meta; zram->init_done = 1; pr_debug("Initialization done!\n"); } static ssize_t disksize_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { u64 disksize; struct zram_meta *meta; struct zram *zram = dev_to_zram(dev); disksize = memparse(buf, NULL); if (!disksize) return -EINVAL; disksize = PAGE_ALIGN(disksize); meta = zram_meta_alloc(disksize); down_write(&zram->init_lock); if (zram->init_done) { up_write(&zram->init_lock); zram_meta_free(meta); pr_info("Cannot change disksize for initialized device\n"); return -EBUSY; } zram->disksize = disksize; set_capacity(zram->disk, zram->disksize >> SECTOR_SHIFT); zram_init_device(zram, meta); up_write(&zram->init_lock); return len; } static ssize_t reset_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { int ret; unsigned short do_reset; struct zram *zram; struct block_device *bdev; zram = dev_to_zram(dev); bdev = bdget_disk(zram->disk, 0); /* Do not reset an active device! */ if (bdev->bd_holders) return -EBUSY; ret = kstrtou16(buf, 10, &do_reset); if (ret) return ret; if (!do_reset) return -EINVAL; /* Make sure all pending I/O is finished */ if (bdev) fsync_bdev(bdev); zram_reset_device(zram, true); return len; } static void __zram_make_request(struct zram *zram, struct bio *bio, int rw) { int i, offset; u32 index; struct bio_vec *bvec; switch (rw) { case READ: atomic64_inc(&zram->stats.num_reads); break; case WRITE: atomic64_inc(&zram->stats.num_writes); break; } index = bio->bi_sector >> SECTORS_PER_PAGE_SHIFT; offset = (bio->bi_sector & (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT; bio_for_each_segment(bvec, bio, i) { int max_transfer_size = PAGE_SIZE - offset; if (bvec->bv_len > max_transfer_size) { /* * zram_bvec_rw() can only make operation on a single * zram page. Split the bio vector. */ struct bio_vec bv; bv.bv_page = bvec->bv_page; bv.bv_len = max_transfer_size; bv.bv_offset = bvec->bv_offset; if (zram_bvec_rw(zram, &bv, index, offset, bio, rw) < 0) goto out; bv.bv_len = bvec->bv_len - max_transfer_size; bv.bv_offset += max_transfer_size; if (zram_bvec_rw(zram, &bv, index+1, 0, bio, rw) < 0) goto out; } else if (zram_bvec_rw(zram, bvec, index, offset, bio, rw) < 0) goto out; update_position(&index, &offset, bvec); } set_bit(BIO_UPTODATE, &bio->bi_flags); bio_endio(bio, 0); return; out: bio_io_error(bio); } /* * Handler function for all zram I/O requests. */ static void zram_make_request(struct request_queue *queue, struct bio *bio) { struct zram *zram = queue->queuedata; down_read(&zram->init_lock); if (unlikely(!zram->init_done)) goto error; if (!valid_io_request(zram, bio)) { atomic64_inc(&zram->stats.invalid_io); goto error; } __zram_make_request(zram, bio, bio_data_dir(bio)); up_read(&zram->init_lock); return; error: up_read(&zram->init_lock); bio_io_error(bio); } static void zram_slot_free(struct work_struct *work) { struct zram *zram; zram = container_of(work, struct zram, free_work); down_write(&zram->lock); handle_pending_slot_free(zram); up_write(&zram->lock); } static void add_slot_free(struct zram *zram, struct zram_slot_free *free_rq) { spin_lock(&zram->slot_free_lock); free_rq->next = zram->slot_free_rq; zram->slot_free_rq = free_rq; spin_unlock(&zram->slot_free_lock); } static void zram_slot_free_notify(struct block_device *bdev, unsigned long index) { struct zram *zram; struct zram_slot_free *free_rq; zram = bdev->bd_disk->private_data; atomic64_inc(&zram->stats.notify_free); free_rq = kmalloc(sizeof(struct zram_slot_free), GFP_ATOMIC); if (!free_rq) return; free_rq->index = index; add_slot_free(zram, free_rq); schedule_work(&zram->free_work); } static const struct block_device_operations zram_devops = { .swap_slot_free_notify = zram_slot_free_notify, .owner = THIS_MODULE }; static DEVICE_ATTR(disksize, S_IRUGO | S_IWUSR, disksize_show, disksize_store); static DEVICE_ATTR(initstate, S_IRUGO, initstate_show, NULL); static DEVICE_ATTR(reset, S_IWUSR, NULL, reset_store); static DEVICE_ATTR(num_reads, S_IRUGO, num_reads_show, NULL); static DEVICE_ATTR(num_writes, S_IRUGO, num_writes_show, NULL); static DEVICE_ATTR(invalid_io, S_IRUGO, invalid_io_show, NULL); static DEVICE_ATTR(notify_free, S_IRUGO, notify_free_show, NULL); static DEVICE_ATTR(zero_pages, S_IRUGO, zero_pages_show, NULL); static DEVICE_ATTR(orig_data_size, S_IRUGO, orig_data_size_show, NULL); static DEVICE_ATTR(compr_data_size, S_IRUGO, compr_data_size_show, NULL); static DEVICE_ATTR(mem_used_total, S_IRUGO, mem_used_total_show, NULL); static struct attribute *zram_disk_attrs[] = { &dev_attr_disksize.attr, &dev_attr_initstate.attr, &dev_attr_reset.attr, &dev_attr_num_reads.attr, &dev_attr_num_writes.attr, &dev_attr_invalid_io.attr, &dev_attr_notify_free.attr, &dev_attr_zero_pages.attr, &dev_attr_orig_data_size.attr, &dev_attr_compr_data_size.attr, &dev_attr_mem_used_total.attr, NULL, }; static struct attribute_group zram_disk_attr_group = { .attrs = zram_disk_attrs, }; static int create_device(struct zram *zram, int device_id) { int ret = -ENOMEM; init_rwsem(&zram->lock); init_rwsem(&zram->init_lock); INIT_WORK(&zram->free_work, zram_slot_free); spin_lock_init(&zram->slot_free_lock); zram->slot_free_rq = NULL; zram->queue = blk_alloc_queue(GFP_KERNEL); if (!zram->queue) { pr_err("Error allocating disk queue for device %d\n", device_id); goto out; } blk_queue_make_request(zram->queue, zram_make_request); zram->queue->queuedata = zram; /* gendisk structure */ zram->disk = alloc_disk(1); if (!zram->disk) { pr_warn("Error allocating disk structure for device %d\n", device_id); goto out_free_queue; } zram->disk->major = zram_major; zram->disk->first_minor = device_id; zram->disk->fops = &zram_devops; zram->disk->queue = zram->queue; zram->disk->private_data = zram; snprintf(zram->disk->disk_name, 16, "zram%d", device_id); /* Actual capacity set using syfs (/sys/block/zram<id>/disksize */ set_capacity(zram->disk, 0); /* * To ensure that we always get PAGE_SIZE aligned * and n*PAGE_SIZED sized I/O requests. */ blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE); blk_queue_logical_block_size(zram->disk->queue, ZRAM_LOGICAL_BLOCK_SIZE); blk_queue_io_min(zram->disk->queue, PAGE_SIZE); blk_queue_io_opt(zram->disk->queue, PAGE_SIZE); add_disk(zram->disk); ret = sysfs_create_group(&disk_to_dev(zram->disk)->kobj, &zram_disk_attr_group); if (ret < 0) { pr_warn("Error creating sysfs group"); goto out_free_disk; } zram->init_done = 0; return 0; out_free_disk: del_gendisk(zram->disk); put_disk(zram->disk); out_free_queue: blk_cleanup_queue(zram->queue); out: return ret; } static void destroy_device(struct zram *zram) { sysfs_remove_group(&disk_to_dev(zram->disk)->kobj, &zram_disk_attr_group); if (zram->disk) { del_gendisk(zram->disk); put_disk(zram->disk); } if (zram->queue) blk_cleanup_queue(zram->queue); } static int __init zram_init(void) { int ret, dev_id; if (num_devices > max_num_devices) { pr_warn("Invalid value for num_devices: %u\n", num_devices); ret = -EINVAL; goto out; } zram_major = register_blkdev(0, "zram"); if (zram_major <= 0) { pr_warn("Unable to get major number\n"); ret = -EBUSY; goto out; } /* Allocate the device array and initialize each one */ zram_devices = kzalloc(num_devices * sizeof(struct zram), GFP_KERNEL); if (!zram_devices) { ret = -ENOMEM; goto unregister; } for (dev_id = 0; dev_id < num_devices; dev_id++) { ret = create_device(&zram_devices[dev_id], dev_id); if (ret) goto free_devices; } show_mem_notifier_register(&zram_show_mem_notifier_block); pr_info("Created %u device(s) ...\n", num_devices); return 0; free_devices: while (dev_id) destroy_device(&zram_devices[--dev_id]); kfree(zram_devices); unregister: unregister_blkdev(zram_major, "zram"); out: return ret; } static void __exit zram_exit(void) { int i; struct zram *zram; for (i = 0; i < num_devices; i++) { zram = &zram_devices[i]; get_disk(zram->disk); destroy_device(zram); /* * Shouldn't access zram->disk after destroy_device * because destroy_device already released zram->disk. */ zram_reset_device(zram, false); } unregister_blkdev(zram_major, "zram"); kfree(zram_devices); pr_debug("Cleanup done!\n"); } module_init(zram_init); module_exit(zram_exit); module_param(num_devices, uint, 0); MODULE_PARM_DESC(num_devices, "Number of zram devices"); MODULE_LICENSE("Dual BSD/GPL"); MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>"); MODULE_DESCRIPTION("Compressed RAM Block Device"); MODULE_ALIAS("devname:zram");
PRJosh/kernel_motorola_msm8916
drivers/staging/zram/zram_drv.c
C
gpl-2.0
24,872
/* * User-space Probes (UProbes) * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Copyright (C) IBM Corporation, 2008-2012 * Authors: * Srikar Dronamraju * Jim Keniston * Copyright (C) 2011-2012 Red Hat, Inc., Peter Zijlstra */ #include <linux/kernel.h> #include <linux/highmem.h> #include <linux/pagemap.h> /* read_mapping_page */ #include <linux/slab.h> #include <linux/sched.h> #include <linux/sched/mm.h> #include <linux/sched/coredump.h> #include <linux/export.h> #include <linux/rmap.h> /* anon_vma_prepare */ #include <linux/mmu_notifier.h> /* set_pte_at_notify */ #include <linux/swap.h> /* try_to_free_swap */ #include <linux/ptrace.h> /* user_enable_single_step */ #include <linux/kdebug.h> /* notifier mechanism */ #include "../../mm/internal.h" /* munlock_vma_page */ #include <linux/percpu-rwsem.h> #include <linux/task_work.h> #include <linux/shmem_fs.h> #include <linux/uprobes.h> #define UINSNS_PER_PAGE (PAGE_SIZE/UPROBE_XOL_SLOT_BYTES) #define MAX_UPROBE_XOL_SLOTS UINSNS_PER_PAGE static struct rb_root uprobes_tree = RB_ROOT; /* * allows us to skip the uprobe_mmap if there are no uprobe events active * at this time. Probably a fine grained per inode count is better? */ #define no_uprobe_events() RB_EMPTY_ROOT(&uprobes_tree) static DEFINE_SPINLOCK(uprobes_treelock); /* serialize rbtree access */ #define UPROBES_HASH_SZ 13 /* serialize uprobe->pending_list */ static struct mutex uprobes_mmap_mutex[UPROBES_HASH_SZ]; #define uprobes_mmap_hash(v) (&uprobes_mmap_mutex[((unsigned long)(v)) % UPROBES_HASH_SZ]) static struct percpu_rw_semaphore dup_mmap_sem; /* Have a copy of original instruction */ #define UPROBE_COPY_INSN 0 struct uprobe { struct rb_node rb_node; /* node in the rb tree */ atomic_t ref; struct rw_semaphore register_rwsem; struct rw_semaphore consumer_rwsem; struct list_head pending_list; struct uprobe_consumer *consumers; struct inode *inode; /* Also hold a ref to inode */ loff_t offset; unsigned long flags; /* * The generic code assumes that it has two members of unknown type * owned by the arch-specific code: * * insn - copy_insn() saves the original instruction here for * arch_uprobe_analyze_insn(). * * ixol - potentially modified instruction to execute out of * line, copied to xol_area by xol_get_insn_slot(). */ struct arch_uprobe arch; }; /* * Execute out of line area: anonymous executable mapping installed * by the probed task to execute the copy of the original instruction * mangled by set_swbp(). * * On a breakpoint hit, thread contests for a slot. It frees the * slot after singlestep. Currently a fixed number of slots are * allocated. */ struct xol_area { wait_queue_head_t wq; /* if all slots are busy */ atomic_t slot_count; /* number of in-use slots */ unsigned long *bitmap; /* 0 = free slot */ struct vm_special_mapping xol_mapping; struct page *pages[2]; /* * We keep the vma's vm_start rather than a pointer to the vma * itself. The probed process or a naughty kernel module could make * the vma go away, and we must handle that reasonably gracefully. */ unsigned long vaddr; /* Page(s) of instruction slots */ }; /* * valid_vma: Verify if the specified vma is an executable vma * Relax restrictions while unregistering: vm_flags might have * changed after breakpoint was inserted. * - is_register: indicates if we are in register context. * - Return 1 if the specified virtual address is in an * executable vma. */ static bool valid_vma(struct vm_area_struct *vma, bool is_register) { vm_flags_t flags = VM_HUGETLB | VM_MAYEXEC | VM_MAYSHARE; if (is_register) flags |= VM_WRITE; return vma->vm_file && (vma->vm_flags & flags) == VM_MAYEXEC; } static unsigned long offset_to_vaddr(struct vm_area_struct *vma, loff_t offset) { return vma->vm_start + offset - ((loff_t)vma->vm_pgoff << PAGE_SHIFT); } static loff_t vaddr_to_offset(struct vm_area_struct *vma, unsigned long vaddr) { return ((loff_t)vma->vm_pgoff << PAGE_SHIFT) + (vaddr - vma->vm_start); } /** * __replace_page - replace page in vma by new page. * based on replace_page in mm/ksm.c * * @vma: vma that holds the pte pointing to page * @addr: address the old @page is mapped at * @page: the cowed page we are replacing by kpage * @kpage: the modified page we replace page by * * Returns 0 on success, -EFAULT on failure. */ static int __replace_page(struct vm_area_struct *vma, unsigned long addr, struct page *old_page, struct page *new_page) { struct mm_struct *mm = vma->vm_mm; struct page_vma_mapped_walk pvmw = { .page = old_page, .vma = vma, .address = addr, }; int err; /* For mmu_notifiers */ const unsigned long mmun_start = addr; const unsigned long mmun_end = addr + PAGE_SIZE; struct mem_cgroup *memcg; VM_BUG_ON_PAGE(PageTransHuge(old_page), old_page); err = mem_cgroup_try_charge(new_page, vma->vm_mm, GFP_KERNEL, &memcg, false); if (err) return err; /* For try_to_free_swap() and munlock_vma_page() below */ lock_page(old_page); mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); err = -EAGAIN; if (!page_vma_mapped_walk(&pvmw)) { mem_cgroup_cancel_charge(new_page, memcg, false); goto unlock; } VM_BUG_ON_PAGE(addr != pvmw.address, old_page); get_page(new_page); page_add_new_anon_rmap(new_page, vma, addr, false); mem_cgroup_commit_charge(new_page, memcg, false, false); lru_cache_add_active_or_unevictable(new_page, vma); if (!PageAnon(old_page)) { dec_mm_counter(mm, mm_counter_file(old_page)); inc_mm_counter(mm, MM_ANONPAGES); } flush_cache_page(vma, addr, pte_pfn(*pvmw.pte)); ptep_clear_flush_notify(vma, addr, pvmw.pte); set_pte_at_notify(mm, addr, pvmw.pte, mk_pte(new_page, vma->vm_page_prot)); page_remove_rmap(old_page, false); if (!page_mapped(old_page)) try_to_free_swap(old_page); page_vma_mapped_walk_done(&pvmw); if (vma->vm_flags & VM_LOCKED) munlock_vma_page(old_page); put_page(old_page); err = 0; unlock: mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); unlock_page(old_page); return err; } /** * is_swbp_insn - check if instruction is breakpoint instruction. * @insn: instruction to be checked. * Default implementation of is_swbp_insn * Returns true if @insn is a breakpoint instruction. */ bool __weak is_swbp_insn(uprobe_opcode_t *insn) { return *insn == UPROBE_SWBP_INSN; } /** * is_trap_insn - check if instruction is breakpoint instruction. * @insn: instruction to be checked. * Default implementation of is_trap_insn * Returns true if @insn is a breakpoint instruction. * * This function is needed for the case where an architecture has multiple * trap instructions (like powerpc). */ bool __weak is_trap_insn(uprobe_opcode_t *insn) { return is_swbp_insn(insn); } static void copy_from_page(struct page *page, unsigned long vaddr, void *dst, int len) { void *kaddr = kmap_atomic(page); memcpy(dst, kaddr + (vaddr & ~PAGE_MASK), len); kunmap_atomic(kaddr); } static void copy_to_page(struct page *page, unsigned long vaddr, const void *src, int len) { void *kaddr = kmap_atomic(page); memcpy(kaddr + (vaddr & ~PAGE_MASK), src, len); kunmap_atomic(kaddr); } static int verify_opcode(struct page *page, unsigned long vaddr, uprobe_opcode_t *new_opcode) { uprobe_opcode_t old_opcode; bool is_swbp; /* * Note: We only check if the old_opcode is UPROBE_SWBP_INSN here. * We do not check if it is any other 'trap variant' which could * be conditional trap instruction such as the one powerpc supports. * * The logic is that we do not care if the underlying instruction * is a trap variant; uprobes always wins over any other (gdb) * breakpoint. */ copy_from_page(page, vaddr, &old_opcode, UPROBE_SWBP_INSN_SIZE); is_swbp = is_swbp_insn(&old_opcode); if (is_swbp_insn(new_opcode)) { if (is_swbp) /* register: already installed? */ return 0; } else { if (!is_swbp) /* unregister: was it changed by us? */ return 0; } return 1; } /* * NOTE: * Expect the breakpoint instruction to be the smallest size instruction for * the architecture. If an arch has variable length instruction and the * breakpoint instruction is not of the smallest length instruction * supported by that architecture then we need to modify is_trap_at_addr and * uprobe_write_opcode accordingly. This would never be a problem for archs * that have fixed length instructions. * * uprobe_write_opcode - write the opcode at a given virtual address. * @mm: the probed process address space. * @vaddr: the virtual address to store the opcode. * @opcode: opcode to be written at @vaddr. * * Called with mm->mmap_sem held for write. * Return 0 (success) or a negative errno. */ int uprobe_write_opcode(struct mm_struct *mm, unsigned long vaddr, uprobe_opcode_t opcode) { struct page *old_page, *new_page; struct vm_area_struct *vma; int ret; retry: /* Read the page with vaddr into memory */ ret = get_user_pages_remote(NULL, mm, vaddr, 1, FOLL_FORCE | FOLL_SPLIT, &old_page, &vma, NULL); if (ret <= 0) return ret; ret = verify_opcode(old_page, vaddr, &opcode); if (ret <= 0) goto put_old; ret = anon_vma_prepare(vma); if (ret) goto put_old; ret = -ENOMEM; new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vaddr); if (!new_page) goto put_old; __SetPageUptodate(new_page); copy_highpage(new_page, old_page); copy_to_page(new_page, vaddr, &opcode, UPROBE_SWBP_INSN_SIZE); ret = __replace_page(vma, vaddr, old_page, new_page); put_page(new_page); put_old: put_page(old_page); if (unlikely(ret == -EAGAIN)) goto retry; return ret; } /** * set_swbp - store breakpoint at a given address. * @auprobe: arch specific probepoint information. * @mm: the probed process address space. * @vaddr: the virtual address to insert the opcode. * * For mm @mm, store the breakpoint instruction at @vaddr. * Return 0 (success) or a negative errno. */ int __weak set_swbp(struct arch_uprobe *auprobe, struct mm_struct *mm, unsigned long vaddr) { return uprobe_write_opcode(mm, vaddr, UPROBE_SWBP_INSN); } /** * set_orig_insn - Restore the original instruction. * @mm: the probed process address space. * @auprobe: arch specific probepoint information. * @vaddr: the virtual address to insert the opcode. * * For mm @mm, restore the original opcode (opcode) at @vaddr. * Return 0 (success) or a negative errno. */ int __weak set_orig_insn(struct arch_uprobe *auprobe, struct mm_struct *mm, unsigned long vaddr) { return uprobe_write_opcode(mm, vaddr, *(uprobe_opcode_t *)&auprobe->insn); } static struct uprobe *get_uprobe(struct uprobe *uprobe) { atomic_inc(&uprobe->ref); return uprobe; } static void put_uprobe(struct uprobe *uprobe) { if (atomic_dec_and_test(&uprobe->ref)) kfree(uprobe); } static int match_uprobe(struct uprobe *l, struct uprobe *r) { if (l->inode < r->inode) return -1; if (l->inode > r->inode) return 1; if (l->offset < r->offset) return -1; if (l->offset > r->offset) return 1; return 0; } static struct uprobe *__find_uprobe(struct inode *inode, loff_t offset) { struct uprobe u = { .inode = inode, .offset = offset }; struct rb_node *n = uprobes_tree.rb_node; struct uprobe *uprobe; int match; while (n) { uprobe = rb_entry(n, struct uprobe, rb_node); match = match_uprobe(&u, uprobe); if (!match) return get_uprobe(uprobe); if (match < 0) n = n->rb_left; else n = n->rb_right; } return NULL; } /* * Find a uprobe corresponding to a given inode:offset * Acquires uprobes_treelock */ static struct uprobe *find_uprobe(struct inode *inode, loff_t offset) { struct uprobe *uprobe; spin_lock(&uprobes_treelock); uprobe = __find_uprobe(inode, offset); spin_unlock(&uprobes_treelock); return uprobe; } static struct uprobe *__insert_uprobe(struct uprobe *uprobe) { struct rb_node **p = &uprobes_tree.rb_node; struct rb_node *parent = NULL; struct uprobe *u; int match; while (*p) { parent = *p; u = rb_entry(parent, struct uprobe, rb_node); match = match_uprobe(uprobe, u); if (!match) return get_uprobe(u); if (match < 0) p = &parent->rb_left; else p = &parent->rb_right; } u = NULL; rb_link_node(&uprobe->rb_node, parent, p); rb_insert_color(&uprobe->rb_node, &uprobes_tree); /* get access + creation ref */ atomic_set(&uprobe->ref, 2); return u; } /* * Acquire uprobes_treelock. * Matching uprobe already exists in rbtree; * increment (access refcount) and return the matching uprobe. * * No matching uprobe; insert the uprobe in rb_tree; * get a double refcount (access + creation) and return NULL. */ static struct uprobe *insert_uprobe(struct uprobe *uprobe) { struct uprobe *u; spin_lock(&uprobes_treelock); u = __insert_uprobe(uprobe); spin_unlock(&uprobes_treelock); return u; } static struct uprobe *alloc_uprobe(struct inode *inode, loff_t offset) { struct uprobe *uprobe, *cur_uprobe; uprobe = kzalloc(sizeof(struct uprobe), GFP_KERNEL); if (!uprobe) return NULL; uprobe->inode = igrab(inode); uprobe->offset = offset; init_rwsem(&uprobe->register_rwsem); init_rwsem(&uprobe->consumer_rwsem); /* add to uprobes_tree, sorted on inode:offset */ cur_uprobe = insert_uprobe(uprobe); /* a uprobe exists for this inode:offset combination */ if (cur_uprobe) { kfree(uprobe); uprobe = cur_uprobe; iput(inode); } return uprobe; } static void consumer_add(struct uprobe *uprobe, struct uprobe_consumer *uc) { down_write(&uprobe->consumer_rwsem); uc->next = uprobe->consumers; uprobe->consumers = uc; up_write(&uprobe->consumer_rwsem); } /* * For uprobe @uprobe, delete the consumer @uc. * Return true if the @uc is deleted successfully * or return false. */ static bool consumer_del(struct uprobe *uprobe, struct uprobe_consumer *uc) { struct uprobe_consumer **con; bool ret = false; down_write(&uprobe->consumer_rwsem); for (con = &uprobe->consumers; *con; con = &(*con)->next) { if (*con == uc) { *con = uc->next; ret = true; break; } } up_write(&uprobe->consumer_rwsem); return ret; } static int __copy_insn(struct address_space *mapping, struct file *filp, void *insn, int nbytes, loff_t offset) { struct page *page; /* * Ensure that the page that has the original instruction is populated * and in page-cache. If ->readpage == NULL it must be shmem_mapping(), * see uprobe_register(). */ if (mapping->a_ops->readpage) page = read_mapping_page(mapping, offset >> PAGE_SHIFT, filp); else page = shmem_read_mapping_page(mapping, offset >> PAGE_SHIFT); if (IS_ERR(page)) return PTR_ERR(page); copy_from_page(page, offset, insn, nbytes); put_page(page); return 0; } static int copy_insn(struct uprobe *uprobe, struct file *filp) { struct address_space *mapping = uprobe->inode->i_mapping; loff_t offs = uprobe->offset; void *insn = &uprobe->arch.insn; int size = sizeof(uprobe->arch.insn); int len, err = -EIO; /* Copy only available bytes, -EIO if nothing was read */ do { if (offs >= i_size_read(uprobe->inode)) break; len = min_t(int, size, PAGE_SIZE - (offs & ~PAGE_MASK)); err = __copy_insn(mapping, filp, insn, len, offs); if (err) break; insn += len; offs += len; size -= len; } while (size); return err; } static int prepare_uprobe(struct uprobe *uprobe, struct file *file, struct mm_struct *mm, unsigned long vaddr) { int ret = 0; if (test_bit(UPROBE_COPY_INSN, &uprobe->flags)) return ret; /* TODO: move this into _register, until then we abuse this sem. */ down_write(&uprobe->consumer_rwsem); if (test_bit(UPROBE_COPY_INSN, &uprobe->flags)) goto out; ret = copy_insn(uprobe, file); if (ret) goto out; ret = -ENOTSUPP; if (is_trap_insn((uprobe_opcode_t *)&uprobe->arch.insn)) goto out; ret = arch_uprobe_analyze_insn(&uprobe->arch, mm, vaddr); if (ret) goto out; /* uprobe_write_opcode() assumes we don't cross page boundary */ BUG_ON((uprobe->offset & ~PAGE_MASK) + UPROBE_SWBP_INSN_SIZE > PAGE_SIZE); smp_wmb(); /* pairs with rmb() in find_active_uprobe() */ set_bit(UPROBE_COPY_INSN, &uprobe->flags); out: up_write(&uprobe->consumer_rwsem); return ret; } static inline bool consumer_filter(struct uprobe_consumer *uc, enum uprobe_filter_ctx ctx, struct mm_struct *mm) { return !uc->filter || uc->filter(uc, ctx, mm); } static bool filter_chain(struct uprobe *uprobe, enum uprobe_filter_ctx ctx, struct mm_struct *mm) { struct uprobe_consumer *uc; bool ret = false; down_read(&uprobe->consumer_rwsem); for (uc = uprobe->consumers; uc; uc = uc->next) { ret = consumer_filter(uc, ctx, mm); if (ret) break; } up_read(&uprobe->consumer_rwsem); return ret; } static int install_breakpoint(struct uprobe *uprobe, struct mm_struct *mm, struct vm_area_struct *vma, unsigned long vaddr) { bool first_uprobe; int ret; ret = prepare_uprobe(uprobe, vma->vm_file, mm, vaddr); if (ret) return ret; /* * set MMF_HAS_UPROBES in advance for uprobe_pre_sstep_notifier(), * the task can hit this breakpoint right after __replace_page(). */ first_uprobe = !test_bit(MMF_HAS_UPROBES, &mm->flags); if (first_uprobe) set_bit(MMF_HAS_UPROBES, &mm->flags); ret = set_swbp(&uprobe->arch, mm, vaddr); if (!ret) clear_bit(MMF_RECALC_UPROBES, &mm->flags); else if (first_uprobe) clear_bit(MMF_HAS_UPROBES, &mm->flags); return ret; } static int remove_breakpoint(struct uprobe *uprobe, struct mm_struct *mm, unsigned long vaddr) { set_bit(MMF_RECALC_UPROBES, &mm->flags); return set_orig_insn(&uprobe->arch, mm, vaddr); } static inline bool uprobe_is_active(struct uprobe *uprobe) { return !RB_EMPTY_NODE(&uprobe->rb_node); } /* * There could be threads that have already hit the breakpoint. They * will recheck the current insn and restart if find_uprobe() fails. * See find_active_uprobe(). */ static void delete_uprobe(struct uprobe *uprobe) { if (WARN_ON(!uprobe_is_active(uprobe))) return; spin_lock(&uprobes_treelock); rb_erase(&uprobe->rb_node, &uprobes_tree); spin_unlock(&uprobes_treelock); RB_CLEAR_NODE(&uprobe->rb_node); /* for uprobe_is_active() */ iput(uprobe->inode); put_uprobe(uprobe); } struct map_info { struct map_info *next; struct mm_struct *mm; unsigned long vaddr; }; static inline struct map_info *free_map_info(struct map_info *info) { struct map_info *next = info->next; kfree(info); return next; } static struct map_info * build_map_info(struct address_space *mapping, loff_t offset, bool is_register) { unsigned long pgoff = offset >> PAGE_SHIFT; struct vm_area_struct *vma; struct map_info *curr = NULL; struct map_info *prev = NULL; struct map_info *info; int more = 0; again: i_mmap_lock_read(mapping); vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) { if (!valid_vma(vma, is_register)) continue; if (!prev && !more) { /* * Needs GFP_NOWAIT to avoid i_mmap_rwsem recursion through * reclaim. This is optimistic, no harm done if it fails. */ prev = kmalloc(sizeof(struct map_info), GFP_NOWAIT | __GFP_NOMEMALLOC | __GFP_NOWARN); if (prev) prev->next = NULL; } if (!prev) { more++; continue; } if (!mmget_not_zero(vma->vm_mm)) continue; info = prev; prev = prev->next; info->next = curr; curr = info; info->mm = vma->vm_mm; info->vaddr = offset_to_vaddr(vma, offset); } i_mmap_unlock_read(mapping); if (!more) goto out; prev = curr; while (curr) { mmput(curr->mm); curr = curr->next; } do { info = kmalloc(sizeof(struct map_info), GFP_KERNEL); if (!info) { curr = ERR_PTR(-ENOMEM); goto out; } info->next = prev; prev = info; } while (--more); goto again; out: while (prev) prev = free_map_info(prev); return curr; } static int register_for_each_vma(struct uprobe *uprobe, struct uprobe_consumer *new) { bool is_register = !!new; struct map_info *info; int err = 0; percpu_down_write(&dup_mmap_sem); info = build_map_info(uprobe->inode->i_mapping, uprobe->offset, is_register); if (IS_ERR(info)) { err = PTR_ERR(info); goto out; } while (info) { struct mm_struct *mm = info->mm; struct vm_area_struct *vma; if (err && is_register) goto free; down_write(&mm->mmap_sem); vma = find_vma(mm, info->vaddr); if (!vma || !valid_vma(vma, is_register) || file_inode(vma->vm_file) != uprobe->inode) goto unlock; if (vma->vm_start > info->vaddr || vaddr_to_offset(vma, info->vaddr) != uprobe->offset) goto unlock; if (is_register) { /* consult only the "caller", new consumer. */ if (consumer_filter(new, UPROBE_FILTER_REGISTER, mm)) err = install_breakpoint(uprobe, mm, vma, info->vaddr); } else if (test_bit(MMF_HAS_UPROBES, &mm->flags)) { if (!filter_chain(uprobe, UPROBE_FILTER_UNREGISTER, mm)) err |= remove_breakpoint(uprobe, mm, info->vaddr); } unlock: up_write(&mm->mmap_sem); free: mmput(mm); info = free_map_info(info); } out: percpu_up_write(&dup_mmap_sem); return err; } static int __uprobe_register(struct uprobe *uprobe, struct uprobe_consumer *uc) { consumer_add(uprobe, uc); return register_for_each_vma(uprobe, uc); } static void __uprobe_unregister(struct uprobe *uprobe, struct uprobe_consumer *uc) { int err; if (WARN_ON(!consumer_del(uprobe, uc))) return; err = register_for_each_vma(uprobe, NULL); /* TODO : cant unregister? schedule a worker thread */ if (!uprobe->consumers && !err) delete_uprobe(uprobe); } /* * uprobe_register - register a probe * @inode: the file in which the probe has to be placed. * @offset: offset from the start of the file. * @uc: information on howto handle the probe.. * * Apart from the access refcount, uprobe_register() takes a creation * refcount (thro alloc_uprobe) if and only if this @uprobe is getting * inserted into the rbtree (i.e first consumer for a @inode:@offset * tuple). Creation refcount stops uprobe_unregister from freeing the * @uprobe even before the register operation is complete. Creation * refcount is released when the last @uc for the @uprobe * unregisters. * * Return errno if it cannot successully install probes * else return 0 (success) */ int uprobe_register(struct inode *inode, loff_t offset, struct uprobe_consumer *uc) { struct uprobe *uprobe; int ret; /* Uprobe must have at least one set consumer */ if (!uc->handler && !uc->ret_handler) return -EINVAL; /* copy_insn() uses read_mapping_page() or shmem_read_mapping_page() */ if (!inode->i_mapping->a_ops->readpage && !shmem_mapping(inode->i_mapping)) return -EIO; /* Racy, just to catch the obvious mistakes */ if (offset > i_size_read(inode)) return -EINVAL; retry: uprobe = alloc_uprobe(inode, offset); if (!uprobe) return -ENOMEM; /* * We can race with uprobe_unregister()->delete_uprobe(). * Check uprobe_is_active() and retry if it is false. */ down_write(&uprobe->register_rwsem); ret = -EAGAIN; if (likely(uprobe_is_active(uprobe))) { ret = __uprobe_register(uprobe, uc); if (ret) __uprobe_unregister(uprobe, uc); } up_write(&uprobe->register_rwsem); put_uprobe(uprobe); if (unlikely(ret == -EAGAIN)) goto retry; return ret; } EXPORT_SYMBOL_GPL(uprobe_register); /* * uprobe_apply - unregister a already registered probe. * @inode: the file in which the probe has to be removed. * @offset: offset from the start of the file. * @uc: consumer which wants to add more or remove some breakpoints * @add: add or remove the breakpoints */ int uprobe_apply(struct inode *inode, loff_t offset, struct uprobe_consumer *uc, bool add) { struct uprobe *uprobe; struct uprobe_consumer *con; int ret = -ENOENT; uprobe = find_uprobe(inode, offset); if (WARN_ON(!uprobe)) return ret; down_write(&uprobe->register_rwsem); for (con = uprobe->consumers; con && con != uc ; con = con->next) ; if (con) ret = register_for_each_vma(uprobe, add ? uc : NULL); up_write(&uprobe->register_rwsem); put_uprobe(uprobe); return ret; } /* * uprobe_unregister - unregister a already registered probe. * @inode: the file in which the probe has to be removed. * @offset: offset from the start of the file. * @uc: identify which probe if multiple probes are colocated. */ void uprobe_unregister(struct inode *inode, loff_t offset, struct uprobe_consumer *uc) { struct uprobe *uprobe; uprobe = find_uprobe(inode, offset); if (WARN_ON(!uprobe)) return; down_write(&uprobe->register_rwsem); __uprobe_unregister(uprobe, uc); up_write(&uprobe->register_rwsem); put_uprobe(uprobe); } EXPORT_SYMBOL_GPL(uprobe_unregister); static int unapply_uprobe(struct uprobe *uprobe, struct mm_struct *mm) { struct vm_area_struct *vma; int err = 0; down_read(&mm->mmap_sem); for (vma = mm->mmap; vma; vma = vma->vm_next) { unsigned long vaddr; loff_t offset; if (!valid_vma(vma, false) || file_inode(vma->vm_file) != uprobe->inode) continue; offset = (loff_t)vma->vm_pgoff << PAGE_SHIFT; if (uprobe->offset < offset || uprobe->offset >= offset + vma->vm_end - vma->vm_start) continue; vaddr = offset_to_vaddr(vma, uprobe->offset); err |= remove_breakpoint(uprobe, mm, vaddr); } up_read(&mm->mmap_sem); return err; } static struct rb_node * find_node_in_range(struct inode *inode, loff_t min, loff_t max) { struct rb_node *n = uprobes_tree.rb_node; while (n) { struct uprobe *u = rb_entry(n, struct uprobe, rb_node); if (inode < u->inode) { n = n->rb_left; } else if (inode > u->inode) { n = n->rb_right; } else { if (max < u->offset) n = n->rb_left; else if (min > u->offset) n = n->rb_right; else break; } } return n; } /* * For a given range in vma, build a list of probes that need to be inserted. */ static void build_probe_list(struct inode *inode, struct vm_area_struct *vma, unsigned long start, unsigned long end, struct list_head *head) { loff_t min, max; struct rb_node *n, *t; struct uprobe *u; INIT_LIST_HEAD(head); min = vaddr_to_offset(vma, start); max = min + (end - start) - 1; spin_lock(&uprobes_treelock); n = find_node_in_range(inode, min, max); if (n) { for (t = n; t; t = rb_prev(t)) { u = rb_entry(t, struct uprobe, rb_node); if (u->inode != inode || u->offset < min) break; list_add(&u->pending_list, head); get_uprobe(u); } for (t = n; (t = rb_next(t)); ) { u = rb_entry(t, struct uprobe, rb_node); if (u->inode != inode || u->offset > max) break; list_add(&u->pending_list, head); get_uprobe(u); } } spin_unlock(&uprobes_treelock); } /* * Called from mmap_region/vma_adjust with mm->mmap_sem acquired. * * Currently we ignore all errors and always return 0, the callers * can't handle the failure anyway. */ int uprobe_mmap(struct vm_area_struct *vma) { struct list_head tmp_list; struct uprobe *uprobe, *u; struct inode *inode; if (no_uprobe_events() || !valid_vma(vma, true)) return 0; inode = file_inode(vma->vm_file); if (!inode) return 0; mutex_lock(uprobes_mmap_hash(inode)); build_probe_list(inode, vma, vma->vm_start, vma->vm_end, &tmp_list); /* * We can race with uprobe_unregister(), this uprobe can be already * removed. But in this case filter_chain() must return false, all * consumers have gone away. */ list_for_each_entry_safe(uprobe, u, &tmp_list, pending_list) { if (!fatal_signal_pending(current) && filter_chain(uprobe, UPROBE_FILTER_MMAP, vma->vm_mm)) { unsigned long vaddr = offset_to_vaddr(vma, uprobe->offset); install_breakpoint(uprobe, vma->vm_mm, vma, vaddr); } put_uprobe(uprobe); } mutex_unlock(uprobes_mmap_hash(inode)); return 0; } static bool vma_has_uprobes(struct vm_area_struct *vma, unsigned long start, unsigned long end) { loff_t min, max; struct inode *inode; struct rb_node *n; inode = file_inode(vma->vm_file); min = vaddr_to_offset(vma, start); max = min + (end - start) - 1; spin_lock(&uprobes_treelock); n = find_node_in_range(inode, min, max); spin_unlock(&uprobes_treelock); return !!n; } /* * Called in context of a munmap of a vma. */ void uprobe_munmap(struct vm_area_struct *vma, unsigned long start, unsigned long end) { if (no_uprobe_events() || !valid_vma(vma, false)) return; if (!atomic_read(&vma->vm_mm->mm_users)) /* called by mmput() ? */ return; if (!test_bit(MMF_HAS_UPROBES, &vma->vm_mm->flags) || test_bit(MMF_RECALC_UPROBES, &vma->vm_mm->flags)) return; if (vma_has_uprobes(vma, start, end)) set_bit(MMF_RECALC_UPROBES, &vma->vm_mm->flags); } /* Slot allocation for XOL */ static int xol_add_vma(struct mm_struct *mm, struct xol_area *area) { struct vm_area_struct *vma; int ret; if (down_write_killable(&mm->mmap_sem)) return -EINTR; if (mm->uprobes_state.xol_area) { ret = -EALREADY; goto fail; } if (!area->vaddr) { /* Try to map as high as possible, this is only a hint. */ area->vaddr = get_unmapped_area(NULL, TASK_SIZE - PAGE_SIZE, PAGE_SIZE, 0, 0); if (area->vaddr & ~PAGE_MASK) { ret = area->vaddr; goto fail; } } vma = _install_special_mapping(mm, area->vaddr, PAGE_SIZE, VM_EXEC|VM_MAYEXEC|VM_DONTCOPY|VM_IO, &area->xol_mapping); if (IS_ERR(vma)) { ret = PTR_ERR(vma); goto fail; } ret = 0; /* pairs with get_xol_area() */ smp_store_release(&mm->uprobes_state.xol_area, area); /* ^^^ */ fail: up_write(&mm->mmap_sem); return ret; } static struct xol_area *__create_xol_area(unsigned long vaddr) { struct mm_struct *mm = current->mm; uprobe_opcode_t insn = UPROBE_SWBP_INSN; struct xol_area *area; area = kmalloc(sizeof(*area), GFP_KERNEL); if (unlikely(!area)) goto out; area->bitmap = kzalloc(BITS_TO_LONGS(UINSNS_PER_PAGE) * sizeof(long), GFP_KERNEL); if (!area->bitmap) goto free_area; area->xol_mapping.name = "[uprobes]"; area->xol_mapping.fault = NULL; area->xol_mapping.pages = area->pages; area->pages[0] = alloc_page(GFP_HIGHUSER); if (!area->pages[0]) goto free_bitmap; area->pages[1] = NULL; area->vaddr = vaddr; init_waitqueue_head(&area->wq); /* Reserve the 1st slot for get_trampoline_vaddr() */ set_bit(0, area->bitmap); atomic_set(&area->slot_count, 1); arch_uprobe_copy_ixol(area->pages[0], 0, &insn, UPROBE_SWBP_INSN_SIZE); if (!xol_add_vma(mm, area)) return area; __free_page(area->pages[0]); free_bitmap: kfree(area->bitmap); free_area: kfree(area); out: return NULL; } /* * get_xol_area - Allocate process's xol_area if necessary. * This area will be used for storing instructions for execution out of line. * * Returns the allocated area or NULL. */ static struct xol_area *get_xol_area(void) { struct mm_struct *mm = current->mm; struct xol_area *area; if (!mm->uprobes_state.xol_area) __create_xol_area(0); /* Pairs with xol_add_vma() smp_store_release() */ area = READ_ONCE(mm->uprobes_state.xol_area); /* ^^^ */ return area; } /* * uprobe_clear_state - Free the area allocated for slots. */ void uprobe_clear_state(struct mm_struct *mm) { struct xol_area *area = mm->uprobes_state.xol_area; if (!area) return; put_page(area->pages[0]); kfree(area->bitmap); kfree(area); } void uprobe_start_dup_mmap(void) { percpu_down_read(&dup_mmap_sem); } void uprobe_end_dup_mmap(void) { percpu_up_read(&dup_mmap_sem); } void uprobe_dup_mmap(struct mm_struct *oldmm, struct mm_struct *newmm) { if (test_bit(MMF_HAS_UPROBES, &oldmm->flags)) { set_bit(MMF_HAS_UPROBES, &newmm->flags); /* unconditionally, dup_mmap() skips VM_DONTCOPY vmas */ set_bit(MMF_RECALC_UPROBES, &newmm->flags); } } /* * - search for a free slot. */ static unsigned long xol_take_insn_slot(struct xol_area *area) { unsigned long slot_addr; int slot_nr; do { slot_nr = find_first_zero_bit(area->bitmap, UINSNS_PER_PAGE); if (slot_nr < UINSNS_PER_PAGE) { if (!test_and_set_bit(slot_nr, area->bitmap)) break; slot_nr = UINSNS_PER_PAGE; continue; } wait_event(area->wq, (atomic_read(&area->slot_count) < UINSNS_PER_PAGE)); } while (slot_nr >= UINSNS_PER_PAGE); slot_addr = area->vaddr + (slot_nr * UPROBE_XOL_SLOT_BYTES); atomic_inc(&area->slot_count); return slot_addr; } /* * xol_get_insn_slot - allocate a slot for xol. * Returns the allocated slot address or 0. */ static unsigned long xol_get_insn_slot(struct uprobe *uprobe) { struct xol_area *area; unsigned long xol_vaddr; area = get_xol_area(); if (!area) return 0; xol_vaddr = xol_take_insn_slot(area); if (unlikely(!xol_vaddr)) return 0; arch_uprobe_copy_ixol(area->pages[0], xol_vaddr, &uprobe->arch.ixol, sizeof(uprobe->arch.ixol)); return xol_vaddr; } /* * xol_free_insn_slot - If slot was earlier allocated by * @xol_get_insn_slot(), make the slot available for * subsequent requests. */ static void xol_free_insn_slot(struct task_struct *tsk) { struct xol_area *area; unsigned long vma_end; unsigned long slot_addr; if (!tsk->mm || !tsk->mm->uprobes_state.xol_area || !tsk->utask) return; slot_addr = tsk->utask->xol_vaddr; if (unlikely(!slot_addr)) return; area = tsk->mm->uprobes_state.xol_area; vma_end = area->vaddr + PAGE_SIZE; if (area->vaddr <= slot_addr && slot_addr < vma_end) { unsigned long offset; int slot_nr; offset = slot_addr - area->vaddr; slot_nr = offset / UPROBE_XOL_SLOT_BYTES; if (slot_nr >= UINSNS_PER_PAGE) return; clear_bit(slot_nr, area->bitmap); atomic_dec(&area->slot_count); smp_mb__after_atomic(); /* pairs with prepare_to_wait() */ if (waitqueue_active(&area->wq)) wake_up(&area->wq); tsk->utask->xol_vaddr = 0; } } void __weak arch_uprobe_copy_ixol(struct page *page, unsigned long vaddr, void *src, unsigned long len) { /* Initialize the slot */ copy_to_page(page, vaddr, src, len); /* * We probably need flush_icache_user_range() but it needs vma. * This should work on most of architectures by default. If * architecture needs to do something different it can define * its own version of the function. */ flush_dcache_page(page); } /** * uprobe_get_swbp_addr - compute address of swbp given post-swbp regs * @regs: Reflects the saved state of the task after it has hit a breakpoint * instruction. * Return the address of the breakpoint instruction. */ unsigned long __weak uprobe_get_swbp_addr(struct pt_regs *regs) { return instruction_pointer(regs) - UPROBE_SWBP_INSN_SIZE; } unsigned long uprobe_get_trap_addr(struct pt_regs *regs) { struct uprobe_task *utask = current->utask; if (unlikely(utask && utask->active_uprobe)) return utask->vaddr; return instruction_pointer(regs); } static struct return_instance *free_ret_instance(struct return_instance *ri) { struct return_instance *next = ri->next; put_uprobe(ri->uprobe); kfree(ri); return next; } /* * Called with no locks held. * Called in context of a exiting or a exec-ing thread. */ void uprobe_free_utask(struct task_struct *t) { struct uprobe_task *utask = t->utask; struct return_instance *ri; if (!utask) return; if (utask->active_uprobe) put_uprobe(utask->active_uprobe); ri = utask->return_instances; while (ri) ri = free_ret_instance(ri); xol_free_insn_slot(t); kfree(utask); t->utask = NULL; } /* * Allocate a uprobe_task object for the task if if necessary. * Called when the thread hits a breakpoint. * * Returns: * - pointer to new uprobe_task on success * - NULL otherwise */ static struct uprobe_task *get_utask(void) { if (!current->utask) current->utask = kzalloc(sizeof(struct uprobe_task), GFP_KERNEL); return current->utask; } static int dup_utask(struct task_struct *t, struct uprobe_task *o_utask) { struct uprobe_task *n_utask; struct return_instance **p, *o, *n; n_utask = kzalloc(sizeof(struct uprobe_task), GFP_KERNEL); if (!n_utask) return -ENOMEM; t->utask = n_utask; p = &n_utask->return_instances; for (o = o_utask->return_instances; o; o = o->next) { n = kmalloc(sizeof(struct return_instance), GFP_KERNEL); if (!n) return -ENOMEM; *n = *o; get_uprobe(n->uprobe); n->next = NULL; *p = n; p = &n->next; n_utask->depth++; } return 0; } static void uprobe_warn(struct task_struct *t, const char *msg) { pr_warn("uprobe: %s:%d failed to %s\n", current->comm, current->pid, msg); } static void dup_xol_work(struct callback_head *work) { if (current->flags & PF_EXITING) return; if (!__create_xol_area(current->utask->dup_xol_addr) && !fatal_signal_pending(current)) uprobe_warn(current, "dup xol area"); } /* * Called in context of a new clone/fork from copy_process. */ void uprobe_copy_process(struct task_struct *t, unsigned long flags) { struct uprobe_task *utask = current->utask; struct mm_struct *mm = current->mm; struct xol_area *area; t->utask = NULL; if (!utask || !utask->return_instances) return; if (mm == t->mm && !(flags & CLONE_VFORK)) return; if (dup_utask(t, utask)) return uprobe_warn(t, "dup ret instances"); /* The task can fork() after dup_xol_work() fails */ area = mm->uprobes_state.xol_area; if (!area) return uprobe_warn(t, "dup xol area"); if (mm == t->mm) return; t->utask->dup_xol_addr = area->vaddr; init_task_work(&t->utask->dup_xol_work, dup_xol_work); task_work_add(t, &t->utask->dup_xol_work, true); } /* * Current area->vaddr notion assume the trampoline address is always * equal area->vaddr. * * Returns -1 in case the xol_area is not allocated. */ static unsigned long get_trampoline_vaddr(void) { struct xol_area *area; unsigned long trampoline_vaddr = -1; /* Pairs with xol_add_vma() smp_store_release() */ area = READ_ONCE(current->mm->uprobes_state.xol_area); /* ^^^ */ if (area) trampoline_vaddr = area->vaddr; return trampoline_vaddr; } static void cleanup_return_instances(struct uprobe_task *utask, bool chained, struct pt_regs *regs) { struct return_instance *ri = utask->return_instances; enum rp_check ctx = chained ? RP_CHECK_CHAIN_CALL : RP_CHECK_CALL; while (ri && !arch_uretprobe_is_alive(ri, ctx, regs)) { ri = free_ret_instance(ri); utask->depth--; } utask->return_instances = ri; } static void prepare_uretprobe(struct uprobe *uprobe, struct pt_regs *regs) { struct return_instance *ri; struct uprobe_task *utask; unsigned long orig_ret_vaddr, trampoline_vaddr; bool chained; if (!get_xol_area()) return; utask = get_utask(); if (!utask) return; if (utask->depth >= MAX_URETPROBE_DEPTH) { printk_ratelimited(KERN_INFO "uprobe: omit uretprobe due to" " nestedness limit pid/tgid=%d/%d\n", current->pid, current->tgid); return; } ri = kmalloc(sizeof(struct return_instance), GFP_KERNEL); if (!ri) return; trampoline_vaddr = get_trampoline_vaddr(); orig_ret_vaddr = arch_uretprobe_hijack_return_addr(trampoline_vaddr, regs); if (orig_ret_vaddr == -1) goto fail; /* drop the entries invalidated by longjmp() */ chained = (orig_ret_vaddr == trampoline_vaddr); cleanup_return_instances(utask, chained, regs); /* * We don't want to keep trampoline address in stack, rather keep the * original return address of first caller thru all the consequent * instances. This also makes breakpoint unwrapping easier. */ if (chained) { if (!utask->return_instances) { /* * This situation is not possible. Likely we have an * attack from user-space. */ uprobe_warn(current, "handle tail call"); goto fail; } orig_ret_vaddr = utask->return_instances->orig_ret_vaddr; } ri->uprobe = get_uprobe(uprobe); ri->func = instruction_pointer(regs); ri->stack = user_stack_pointer(regs); ri->orig_ret_vaddr = orig_ret_vaddr; ri->chained = chained; utask->depth++; ri->next = utask->return_instances; utask->return_instances = ri; return; fail: kfree(ri); } /* Prepare to single-step probed instruction out of line. */ static int pre_ssout(struct uprobe *uprobe, struct pt_regs *regs, unsigned long bp_vaddr) { struct uprobe_task *utask; unsigned long xol_vaddr; int err; utask = get_utask(); if (!utask) return -ENOMEM; xol_vaddr = xol_get_insn_slot(uprobe); if (!xol_vaddr) return -ENOMEM; utask->xol_vaddr = xol_vaddr; utask->vaddr = bp_vaddr; err = arch_uprobe_pre_xol(&uprobe->arch, regs); if (unlikely(err)) { xol_free_insn_slot(current); return err; } utask->active_uprobe = uprobe; utask->state = UTASK_SSTEP; return 0; } /* * If we are singlestepping, then ensure this thread is not connected to * non-fatal signals until completion of singlestep. When xol insn itself * triggers the signal, restart the original insn even if the task is * already SIGKILL'ed (since coredump should report the correct ip). This * is even more important if the task has a handler for SIGSEGV/etc, The * _same_ instruction should be repeated again after return from the signal * handler, and SSTEP can never finish in this case. */ bool uprobe_deny_signal(void) { struct task_struct *t = current; struct uprobe_task *utask = t->utask; if (likely(!utask || !utask->active_uprobe)) return false; WARN_ON_ONCE(utask->state != UTASK_SSTEP); if (signal_pending(t)) { spin_lock_irq(&t->sighand->siglock); clear_tsk_thread_flag(t, TIF_SIGPENDING); spin_unlock_irq(&t->sighand->siglock); if (__fatal_signal_pending(t) || arch_uprobe_xol_was_trapped(t)) { utask->state = UTASK_SSTEP_TRAPPED; set_tsk_thread_flag(t, TIF_UPROBE); } } return true; } static void mmf_recalc_uprobes(struct mm_struct *mm) { struct vm_area_struct *vma; for (vma = mm->mmap; vma; vma = vma->vm_next) { if (!valid_vma(vma, false)) continue; /* * This is not strictly accurate, we can race with * uprobe_unregister() and see the already removed * uprobe if delete_uprobe() was not yet called. * Or this uprobe can be filtered out. */ if (vma_has_uprobes(vma, vma->vm_start, vma->vm_end)) return; } clear_bit(MMF_HAS_UPROBES, &mm->flags); } static int is_trap_at_addr(struct mm_struct *mm, unsigned long vaddr) { struct page *page; uprobe_opcode_t opcode; int result; pagefault_disable(); result = __get_user(opcode, (uprobe_opcode_t __user *)vaddr); pagefault_enable(); if (likely(result == 0)) goto out; /* * The NULL 'tsk' here ensures that any faults that occur here * will not be accounted to the task. 'mm' *is* current->mm, * but we treat this as a 'remote' access since it is * essentially a kernel access to the memory. */ result = get_user_pages_remote(NULL, mm, vaddr, 1, FOLL_FORCE, &page, NULL, NULL); if (result < 0) return result; copy_from_page(page, vaddr, &opcode, UPROBE_SWBP_INSN_SIZE); put_page(page); out: /* This needs to return true for any variant of the trap insn */ return is_trap_insn(&opcode); } static struct uprobe *find_active_uprobe(unsigned long bp_vaddr, int *is_swbp) { struct mm_struct *mm = current->mm; struct uprobe *uprobe = NULL; struct vm_area_struct *vma; down_read(&mm->mmap_sem); vma = find_vma(mm, bp_vaddr); if (vma && vma->vm_start <= bp_vaddr) { if (valid_vma(vma, false)) { struct inode *inode = file_inode(vma->vm_file); loff_t offset = vaddr_to_offset(vma, bp_vaddr); uprobe = find_uprobe(inode, offset); } if (!uprobe) *is_swbp = is_trap_at_addr(mm, bp_vaddr); } else { *is_swbp = -EFAULT; } if (!uprobe && test_and_clear_bit(MMF_RECALC_UPROBES, &mm->flags)) mmf_recalc_uprobes(mm); up_read(&mm->mmap_sem); return uprobe; } static void handler_chain(struct uprobe *uprobe, struct pt_regs *regs) { struct uprobe_consumer *uc; int remove = UPROBE_HANDLER_REMOVE; bool need_prep = false; /* prepare return uprobe, when needed */ down_read(&uprobe->register_rwsem); for (uc = uprobe->consumers; uc; uc = uc->next) { int rc = 0; if (uc->handler) { rc = uc->handler(uc, regs); WARN(rc & ~UPROBE_HANDLER_MASK, "bad rc=0x%x from %pf()\n", rc, uc->handler); } if (uc->ret_handler) need_prep = true; remove &= rc; } if (need_prep && !remove) prepare_uretprobe(uprobe, regs); /* put bp at return */ if (remove && uprobe->consumers) { WARN_ON(!uprobe_is_active(uprobe)); unapply_uprobe(uprobe, current->mm); } up_read(&uprobe->register_rwsem); } static void handle_uretprobe_chain(struct return_instance *ri, struct pt_regs *regs) { struct uprobe *uprobe = ri->uprobe; struct uprobe_consumer *uc; down_read(&uprobe->register_rwsem); for (uc = uprobe->consumers; uc; uc = uc->next) { if (uc->ret_handler) uc->ret_handler(uc, ri->func, regs); } up_read(&uprobe->register_rwsem); } static struct return_instance *find_next_ret_chain(struct return_instance *ri) { bool chained; do { chained = ri->chained; ri = ri->next; /* can't be NULL if chained */ } while (chained); return ri; } static void handle_trampoline(struct pt_regs *regs) { struct uprobe_task *utask; struct return_instance *ri, *next; bool valid; utask = current->utask; if (!utask) goto sigill; ri = utask->return_instances; if (!ri) goto sigill; do { /* * We should throw out the frames invalidated by longjmp(). * If this chain is valid, then the next one should be alive * or NULL; the latter case means that nobody but ri->func * could hit this trampoline on return. TODO: sigaltstack(). */ next = find_next_ret_chain(ri); valid = !next || arch_uretprobe_is_alive(next, RP_CHECK_RET, regs); instruction_pointer_set(regs, ri->orig_ret_vaddr); do { if (valid) handle_uretprobe_chain(ri, regs); ri = free_ret_instance(ri); utask->depth--; } while (ri != next); } while (!valid); utask->return_instances = ri; return; sigill: uprobe_warn(current, "handle uretprobe, sending SIGILL."); force_sig_info(SIGILL, SEND_SIG_FORCED, current); } bool __weak arch_uprobe_ignore(struct arch_uprobe *aup, struct pt_regs *regs) { return false; } bool __weak arch_uretprobe_is_alive(struct return_instance *ret, enum rp_check ctx, struct pt_regs *regs) { return true; } /* * Run handler and ask thread to singlestep. * Ensure all non-fatal signals cannot interrupt thread while it singlesteps. */ static void handle_swbp(struct pt_regs *regs) { struct uprobe *uprobe; unsigned long bp_vaddr; int uninitialized_var(is_swbp); bp_vaddr = uprobe_get_swbp_addr(regs); if (bp_vaddr == get_trampoline_vaddr()) return handle_trampoline(regs); uprobe = find_active_uprobe(bp_vaddr, &is_swbp); if (!uprobe) { if (is_swbp > 0) { /* No matching uprobe; signal SIGTRAP. */ send_sig(SIGTRAP, current, 0); } else { /* * Either we raced with uprobe_unregister() or we can't * access this memory. The latter is only possible if * another thread plays with our ->mm. In both cases * we can simply restart. If this vma was unmapped we * can pretend this insn was not executed yet and get * the (correct) SIGSEGV after restart. */ instruction_pointer_set(regs, bp_vaddr); } return; } /* change it in advance for ->handler() and restart */ instruction_pointer_set(regs, bp_vaddr); /* * TODO: move copy_insn/etc into _register and remove this hack. * After we hit the bp, _unregister + _register can install the * new and not-yet-analyzed uprobe at the same address, restart. */ smp_rmb(); /* pairs with wmb() in install_breakpoint() */ if (unlikely(!test_bit(UPROBE_COPY_INSN, &uprobe->flags))) goto out; /* Tracing handlers use ->utask to communicate with fetch methods */ if (!get_utask()) goto out; if (arch_uprobe_ignore(&uprobe->arch, regs)) goto out; handler_chain(uprobe, regs); if (arch_uprobe_skip_sstep(&uprobe->arch, regs)) goto out; if (!pre_ssout(uprobe, regs, bp_vaddr)) return; /* arch_uprobe_skip_sstep() succeeded, or restart if can't singlestep */ out: put_uprobe(uprobe); } /* * Perform required fix-ups and disable singlestep. * Allow pending signals to take effect. */ static void handle_singlestep(struct uprobe_task *utask, struct pt_regs *regs) { struct uprobe *uprobe; int err = 0; uprobe = utask->active_uprobe; if (utask->state == UTASK_SSTEP_ACK) err = arch_uprobe_post_xol(&uprobe->arch, regs); else if (utask->state == UTASK_SSTEP_TRAPPED) arch_uprobe_abort_xol(&uprobe->arch, regs); else WARN_ON_ONCE(1); put_uprobe(uprobe); utask->active_uprobe = NULL; utask->state = UTASK_RUNNING; xol_free_insn_slot(current); spin_lock_irq(&current->sighand->siglock); recalc_sigpending(); /* see uprobe_deny_signal() */ spin_unlock_irq(&current->sighand->siglock); if (unlikely(err)) { uprobe_warn(current, "execute the probed insn, sending SIGILL."); force_sig_info(SIGILL, SEND_SIG_FORCED, current); } } /* * On breakpoint hit, breakpoint notifier sets the TIF_UPROBE flag and * allows the thread to return from interrupt. After that handle_swbp() * sets utask->active_uprobe. * * On singlestep exception, singlestep notifier sets the TIF_UPROBE flag * and allows the thread to return from interrupt. * * While returning to userspace, thread notices the TIF_UPROBE flag and calls * uprobe_notify_resume(). */ void uprobe_notify_resume(struct pt_regs *regs) { struct uprobe_task *utask; clear_thread_flag(TIF_UPROBE); utask = current->utask; if (utask && utask->active_uprobe) handle_singlestep(utask, regs); else handle_swbp(regs); } /* * uprobe_pre_sstep_notifier gets called from interrupt context as part of * notifier mechanism. Set TIF_UPROBE flag and indicate breakpoint hit. */ int uprobe_pre_sstep_notifier(struct pt_regs *regs) { if (!current->mm) return 0; if (!test_bit(MMF_HAS_UPROBES, &current->mm->flags) && (!current->utask || !current->utask->return_instances)) return 0; set_thread_flag(TIF_UPROBE); return 1; } /* * uprobe_post_sstep_notifier gets called in interrupt context as part of notifier * mechanism. Set TIF_UPROBE flag and indicate completion of singlestep. */ int uprobe_post_sstep_notifier(struct pt_regs *regs) { struct uprobe_task *utask = current->utask; if (!current->mm || !utask || !utask->active_uprobe) /* task is currently not uprobed */ return 0; utask->state = UTASK_SSTEP_ACK; set_thread_flag(TIF_UPROBE); return 1; } static struct notifier_block uprobe_exception_nb = { .notifier_call = arch_uprobe_exception_notify, .priority = INT_MAX-1, /* notified after kprobes, kgdb */ }; static int __init init_uprobes(void) { int i; for (i = 0; i < UPROBES_HASH_SZ; i++) mutex_init(&uprobes_mmap_mutex[i]); if (percpu_init_rwsem(&dup_mmap_sem)) return -ENOMEM; return register_die_notifier(&uprobe_exception_nb); } __initcall(init_uprobes);
HarveyHunt/linux
kernel/events/uprobes.c
C
gpl-2.0
51,206
<?php if ($classes) { $classes = ' class="'. $classes . ' "'; } ?> <?php if( theme_get_setting('mothership_poorthemers_helper') ){ ?> <!-- comment.tpl.php --> <?php } ?> <article<?php print $classes; ?><?php print $attributes; ?>> <?php print render($title_prefix); ?> <?php if ($title): ?> <h3<?php print $title_attributes; ?>> <?php print $title; ?> </h3> <?php endif; ?> <?php print render($title_suffix); ?> <footer> <?php if ($new): ?> <mark><?php print $new; ?></mark> <?php endif; ?> <figure> <?php print $picture; ?> <figcaption><?php print $author; ?></figcaption> </figure> <span class="date"><time><?php print $created; ?></time></span> <span class="changed">(<?php print t('changed'); ?> <time><?php print $changed; ?></time>)</span> <?php print $permalink; ?> </footer> <div class="content"<?php print $content_attributes; ?>> <?php // We hide the comments and links now so that we can render them later. hide($content['links']); print render($content); ?> <?php if ($signature): ?> <aside class="user-signature"> <?php print $signature; ?> </aside> <?php endif; ?> </div> <?php print render($content['links']) ?> </article> <?php if( theme_get_setting('mothership_poorthemers_helper') ){ ?> <!-- comment.tpl.php --> <?php } ?>
alexdbrown/gabbin-gosling
themes/mothership/mothership/templates/comment.tpl.php
PHP
gpl-2.0
1,386
@CHARSET "ISO-8859-1"; /* ----- Strip Panel ------- */ .ug-videoskin-right-title-only .ug-strip-panel{ background-color:#232323; } /* ----- Thumb Wrapper ------- */ .ug-videoskin-right-title-only .ug-thumb-wrapper{ background-color:#232323; border-bottom:1px solid #393939; width:360px; height:60px; cursor:pointer; text-align:left; } .ug-videoskin-right-title-only .ug-thumb-wrapper:last-child{ border-bottom:none; } /* - thumb selected and over - */ .ug-videoskin-right-title-only .ug-thumb-wrapper.ug-thumb-over{ cursor:pointer; background-color:#1A1A1A; } .ug-videoskin-right-title-only .ug-thumb-wrapper.ug-thumb-selected{ cursor:default; background-color:#176DB3; } /* ----- Thumb Inner data ------- */ .ug-videoskin-right-title-only .ug-thumb-inner{ padding-top:18px; padding-left:20px; padding-right:10px; } .ug-videoskin-right-title-only .ug-thumb-title{ color:white; font-size:14px; } /* ----- Buttons Panel ------- */ .ug-videoskin-right-title-only .ug-video-buttons-panel{ height:42px; background-color:#000; position:absolute; display:none; } .ug-videoskin-right-title-only .ug-button-prev-video{ width:50%; height:42px; float:left; background-image:url('images/arrow_left.png'); cursor:pointer; background-repeat:no-repeat; background-position:center; box-sizing:border-box; border-right:1px solid #444; } .ug-videoskin-right-title-only .ug-button-prev-video:hover, .ug-videoskin-right-title-only .ug-button-next-video:hover { background-color:#444; } .ug-videoskin-right-title-only .ug-button-next-video{ width:50%; height:42px; float:right; background-image:url('images/arrow_right.png'); cursor:pointer; background-repeat:no-repeat; background-position:center; } /* ----- Under 960 ------- */ .ug-under-960.ug-videoskin-right-title-only .ug-thumb-wrapper { width:300px; } .ug-under-960.ug-videoskin-right-title-only .ug-thumb-title { width: 289px; height:18px; font-size:14px; } .ug-under-960.ug-videoskin-right-title-only .ug-video-buttons-panel{ display:none; } /* ----- Under 780 ------- */ .ug-under-780.ug-videoskin-right-title-only .ug-thumb-wrapper { width:240px; } .ug-under-780.ug-videoskin-right-title-only .ug-thumb-icon { width:40px; } .ug-under-780.ug-videoskin-right-title-only .ug-thumb-title { width: 167px; height:18px; font-size:14px; } .ug-under-780.ug-videoskin-right-title-only .ug-video-buttons-panel{ display:none; } /* ----- Under 480 ------- */ .ug-under-480.ug-videoskin-right-title-only .ug-thumb-wrapper { width:0px; } .ug-under-480.ug-videoskin-right-title-only .ug-thumb-title { display:none; } .ug-under-480.ug-videoskin-right-title-only .ug-thumb-inner { padding-left: 8px; padding-right: 5px; padding-top: 12px; } .ug-under-480.ug-videoskin-right-title-only .ug-thumb-icon { width:40px; } .ug-under-480.ug-videoskin-right-title-only .ug-video-buttons-panel{ display:block; }
silverboxdev/shottsyarts.com
wp-content/plugins/unitegallery/unitegallery-plugin/themes/video/skin-right-title-only.css
CSS
gpl-2.0
2,958
/* tc-i386.c -- Assemble Intel syntax code for ix86/x86-64 Copyright (C) 2009-2015 Free Software Foundation, Inc. This file is part of GAS, the GNU Assembler. GAS 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, or (at your option) any later version. GAS 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 GAS; see the file COPYING. If not, write to the Free Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ static struct { operatorT op_modifier; /* Operand modifier. */ int is_mem; /* 1 if operand is memory reference. */ int is_indirect; /* 1 if operand is indirect reference. */ int has_offset; /* 1 if operand has offset. */ unsigned int in_offset; /* >=1 if processing operand of offset. */ unsigned int in_bracket; /* >=1 if processing operand in brackets. */ unsigned int in_scale; /* >=1 if processing multipication operand * in brackets. */ i386_operand_type reloc_types; /* Value obtained from lex_got(). */ const reg_entry *base; /* Base register (if any). */ const reg_entry *index; /* Index register (if any). */ offsetT scale_factor; /* Accumulated scale factor. */ symbolS *seg; } intel_state; /* offset X_add_symbol */ #define O_offset O_md32 /* offset X_add_symbol */ #define O_short O_md31 /* near ptr X_add_symbol */ #define O_near_ptr O_md30 /* far ptr X_add_symbol */ #define O_far_ptr O_md29 /* byte ptr X_add_symbol */ #define O_byte_ptr O_md28 /* word ptr X_add_symbol */ #define O_word_ptr O_md27 /* dword ptr X_add_symbol */ #define O_dword_ptr O_md26 /* qword ptr X_add_symbol */ #define O_qword_ptr O_md25 /* oword ptr X_add_symbol */ #define O_oword_ptr O_md24 /* fword ptr X_add_symbol */ #define O_fword_ptr O_md23 /* tbyte ptr X_add_symbol */ #define O_tbyte_ptr O_md22 /* xmmword ptr X_add_symbol */ #define O_xmmword_ptr O_md21 /* ymmword ptr X_add_symbol */ #define O_ymmword_ptr O_md20 /* zmmword ptr X_add_symbol */ #define O_zmmword_ptr O_md19 static struct { const char *name; operatorT op; unsigned int operands; } const i386_operators[] = { { "and", O_bit_and, 2 }, { "eq", O_eq, 2 }, { "ge", O_ge, 2 }, { "gt", O_gt, 2 }, { "le", O_le, 2 }, { "lt", O_lt, 2 }, { "mod", O_modulus, 2 }, { "ne", O_ne, 2 }, { "not", O_bit_not, 1 }, { "offset", O_offset, 1 }, { "or", O_bit_inclusive_or, 2 }, { "shl", O_left_shift, 2 }, { "short", O_short, 1 }, { "shr", O_right_shift, 2 }, { "xor", O_bit_exclusive_or, 2 }, { NULL, O_illegal, 0 } }; static struct { const char *name; operatorT op; unsigned short sz[3]; } const i386_types[] = { #define I386_TYPE(t, n) { #t, O_##t##_ptr, { n, n, n } } I386_TYPE(byte, 1), I386_TYPE(word, 2), I386_TYPE(dword, 4), I386_TYPE(fword, 6), I386_TYPE(qword, 8), I386_TYPE(tbyte, 10), I386_TYPE(oword, 16), I386_TYPE(xmmword, 16), I386_TYPE(ymmword, 32), I386_TYPE(zmmword, 64), #undef I386_TYPE { "near", O_near_ptr, { 0xff04, 0xff02, 0xff08 } }, { "far", O_far_ptr, { 0xff06, 0xff05, 0xff06 } }, { NULL, O_illegal, { 0, 0, 0 } } }; operatorT i386_operator (const char *name, unsigned int operands, char *pc) { unsigned int j; if (!intel_syntax) return O_absent; if (!name) { if (operands != 2) return O_illegal; switch (*input_line_pointer) { case ':': ++input_line_pointer; return O_full_ptr; case '[': ++input_line_pointer; return O_index; case '@': if (this_operand >= 0 && i.reloc[this_operand] == NO_RELOC) { int adjust = 0; char *gotfree_input_line = lex_got (&i.reloc[this_operand], &adjust, &intel_state.reloc_types); if (!gotfree_input_line) break; free (gotfree_input_line); *input_line_pointer++ = '+'; memset (input_line_pointer, '0', adjust - 1); input_line_pointer[adjust - 1] = ' '; return O_add; } break; } return O_illegal; } for (j = 0; i386_operators[j].name; ++j) if (strcasecmp (i386_operators[j].name, name) == 0) { if (i386_operators[j].operands && i386_operators[j].operands != operands) return O_illegal; return i386_operators[j].op; } for (j = 0; i386_types[j].name; ++j) if (strcasecmp (i386_types[j].name, name) == 0) break; if (i386_types[j].name && *pc == ' ') { char *pname = ++input_line_pointer; char c = get_symbol_end (); if (strcasecmp (pname, "ptr") == 0) { pname[-1] = *pc; *pc = c; if (intel_syntax > 0 || operands != 1) return O_illegal; return i386_types[j].op; } *input_line_pointer = c; input_line_pointer = pname - 1; } return O_absent; } static int i386_intel_parse_name (const char *name, expressionS *e) { unsigned int j; if (! strcmp (name, "$")) { current_location (e); return 1; } for (j = 0; i386_types[j].name; ++j) if (strcasecmp(i386_types[j].name, name) == 0) { e->X_op = O_constant; e->X_add_number = i386_types[j].sz[flag_code]; e->X_add_symbol = NULL; e->X_op_symbol = NULL; return 1; } return 0; } static INLINE int i386_intel_check (const reg_entry *rreg, const reg_entry *base, const reg_entry *iindex) { if ((this_operand >= 0 && rreg != i.op[this_operand].regs) || base != intel_state.base || iindex != intel_state.index) { as_bad (_("invalid use of register")); return 0; } return 1; } static INLINE void i386_intel_fold (expressionS *e, symbolS *sym) { expressionS *exp = symbol_get_value_expression (sym); if (S_GET_SEGMENT (sym) == absolute_section) { offsetT val = e->X_add_number; *e = *exp; e->X_add_number += val; } else { if (exp->X_op == O_symbol && strcmp (S_GET_NAME (exp->X_add_symbol), GLOBAL_OFFSET_TABLE_NAME) == 0) sym = exp->X_add_symbol; e->X_add_symbol = sym; e->X_op_symbol = NULL; e->X_op = O_symbol; } } static int i386_intel_simplify_register (expressionS *e) { int reg_num; if (this_operand < 0 || intel_state.in_offset) { as_bad (_("invalid use of register")); return 0; } if (e->X_op == O_register) reg_num = e->X_add_number; else reg_num = e->X_md - 1; if (!intel_state.in_bracket) { if (i.op[this_operand].regs) { as_bad (_("invalid use of register")); return 0; } if (i386_regtab[reg_num].reg_type.bitfield.sreg3 && i386_regtab[reg_num].reg_num == RegFlat) { as_bad (_("invalid use of pseudo-register")); return 0; } i.op[this_operand].regs = i386_regtab + reg_num; } else if (!intel_state.index && (i386_regtab[reg_num].reg_type.bitfield.regxmm || i386_regtab[reg_num].reg_type.bitfield.regymm || i386_regtab[reg_num].reg_type.bitfield.regzmm)) intel_state.index = i386_regtab + reg_num; else if (!intel_state.base && !intel_state.in_scale) intel_state.base = i386_regtab + reg_num; else if (!intel_state.index) { if (intel_state.in_scale || current_templates->start->base_opcode == 0xf30f1b /* bndmk */ || (current_templates->start->base_opcode & ~1) == 0x0f1a /* bnd{ld,st}x */ || i386_regtab[reg_num].reg_type.bitfield.baseindex) intel_state.index = i386_regtab + reg_num; else { /* Convert base to index and make ESP/RSP the base. */ intel_state.index = intel_state.base; intel_state.base = i386_regtab + reg_num; } } else { /* esp is invalid as index */ intel_state.index = i386_regtab + REGNAM_EAX + ESP_REG_NUM; } return 2; } static int i386_intel_simplify (expressionS *); static INLINE int i386_intel_simplify_symbol(symbolS *sym) { int ret = i386_intel_simplify (symbol_get_value_expression (sym)); if (ret == 2) { S_SET_SEGMENT(sym, absolute_section); ret = 1; } return ret; } static int i386_intel_simplify (expressionS *e) { const reg_entry *the_reg = (this_operand >= 0 ? i.op[this_operand].regs : NULL); const reg_entry *base = intel_state.base; const reg_entry *state_index = intel_state.index; int ret; if (!intel_syntax) return 1; switch (e->X_op) { case O_index: if (e->X_add_symbol) { if (!i386_intel_simplify_symbol (e->X_add_symbol) || !i386_intel_check(the_reg, intel_state.base, intel_state.index)) return 0; } if (!intel_state.in_offset) ++intel_state.in_bracket; ret = i386_intel_simplify_symbol (e->X_op_symbol); if (!intel_state.in_offset) --intel_state.in_bracket; if (!ret) return 0; if (e->X_add_symbol) e->X_op = O_add; else i386_intel_fold (e, e->X_op_symbol); break; case O_offset: intel_state.has_offset = 1; ++intel_state.in_offset; ret = i386_intel_simplify_symbol (e->X_add_symbol); --intel_state.in_offset; if (!ret || !i386_intel_check(the_reg, base, state_index)) return 0; i386_intel_fold (e, e->X_add_symbol); return ret; case O_byte_ptr: case O_word_ptr: case O_dword_ptr: case O_fword_ptr: case O_qword_ptr: case O_tbyte_ptr: case O_oword_ptr: case O_xmmword_ptr: case O_ymmword_ptr: case O_zmmword_ptr: case O_near_ptr: case O_far_ptr: if (intel_state.op_modifier == O_absent) intel_state.op_modifier = e->X_op; /* FALLTHROUGH */ case O_short: if (symbol_get_value_expression (e->X_add_symbol)->X_op == O_register) { as_bad (_("invalid use of register")); return 0; } if (!i386_intel_simplify_symbol (e->X_add_symbol)) return 0; i386_intel_fold (e, e->X_add_symbol); break; case O_full_ptr: if (symbol_get_value_expression (e->X_op_symbol)->X_op == O_register) { as_bad (_("invalid use of register")); return 0; } if (!i386_intel_simplify_symbol (e->X_op_symbol) || !i386_intel_check(the_reg, intel_state.base, intel_state.index)) return 0; if (!intel_state.in_offset) intel_state.seg = e->X_add_symbol; i386_intel_fold (e, e->X_op_symbol); break; case O_multiply: if (this_operand >= 0 && intel_state.in_bracket) { expressionS *scale = NULL; int has_index = (intel_state.index != NULL); if (!intel_state.in_scale++) intel_state.scale_factor = 1; ret = i386_intel_simplify_symbol (e->X_add_symbol); if (ret && !has_index && intel_state.index) scale = symbol_get_value_expression (e->X_op_symbol); if (ret) ret = i386_intel_simplify_symbol (e->X_op_symbol); if (ret && !scale && !has_index && intel_state.index) scale = symbol_get_value_expression (e->X_add_symbol); if (ret && scale) { resolve_expression (scale); if (scale->X_op != O_constant || intel_state.index->reg_type.bitfield.reg16) scale->X_add_number = 0; intel_state.scale_factor *= scale->X_add_number; } --intel_state.in_scale; if (!ret) return 0; if (!intel_state.in_scale) switch (intel_state.scale_factor) { case 1: i.log2_scale_factor = 0; break; case 2: i.log2_scale_factor = 1; break; case 4: i.log2_scale_factor = 2; break; case 8: i.log2_scale_factor = 3; break; default: /* esp is invalid as index */ intel_state.index = i386_regtab + REGNAM_EAX + ESP_REG_NUM; break; } break; } goto fallthrough; case O_register: ret = i386_intel_simplify_register (e); if (ret == 2) { gas_assert (e->X_add_number < (unsigned short) -1); e->X_md = (unsigned short) e->X_add_number + 1; e->X_op = O_constant; e->X_add_number = 0; } return ret; case O_constant: if (e->X_md) return i386_intel_simplify_register (e); /* FALLTHROUGH */ default: fallthrough: if (e->X_add_symbol && !i386_intel_simplify_symbol (e->X_add_symbol)) return 0; if (e->X_op == O_add || e->X_op == O_subtract) { base = intel_state.base; state_index = intel_state.index; } if (!i386_intel_check (the_reg, base, state_index) || (e->X_op_symbol && !i386_intel_simplify_symbol (e->X_op_symbol)) || !i386_intel_check (the_reg, (e->X_op != O_add ? base : intel_state.base), (e->X_op != O_add ? state_index : intel_state.index))) return 0; break; } if (this_operand >= 0 && e->X_op == O_symbol && !intel_state.in_offset) { segT seg = S_GET_SEGMENT (e->X_add_symbol); if (seg != absolute_section && seg != reg_section && seg != expr_section) intel_state.is_mem |= 2 - !intel_state.in_bracket; } return 1; } int i386_need_index_operator (void) { return intel_syntax < 0; } static int i386_intel_operand (char *operand_string, int got_a_float) { char *saved_input_line_pointer, *buf; segT exp_seg; expressionS exp, *expP; char suffix = 0; int ret; /* Handle vector immediates. */ if (RC_SAE_immediate (operand_string)) return 1; /* Initialize state structure. */ intel_state.op_modifier = O_absent; intel_state.is_mem = 0; intel_state.is_indirect = 0; intel_state.has_offset = 0; intel_state.base = NULL; intel_state.index = NULL; intel_state.seg = NULL; operand_type_set (&intel_state.reloc_types, ~0); gas_assert (!intel_state.in_offset); gas_assert (!intel_state.in_bracket); gas_assert (!intel_state.in_scale); saved_input_line_pointer = input_line_pointer; input_line_pointer = buf = xstrdup (operand_string); intel_syntax = -1; memset (&exp, 0, sizeof(exp)); exp_seg = expression (&exp); ret = i386_intel_simplify (&exp); intel_syntax = 1; SKIP_WHITESPACE (); /* Handle vector operations. */ if (*input_line_pointer == '{') { char *end = check_VecOperations (input_line_pointer, NULL); if (end) input_line_pointer = end; else ret = 0; } if (!is_end_of_line[(unsigned char) *input_line_pointer]) { as_bad (_("junk `%s' after expression"), input_line_pointer); ret = 0; } else if (exp.X_op == O_illegal || exp.X_op == O_absent) { as_bad (_("invalid expression")); ret = 0; } else if (!intel_state.has_offset && input_line_pointer > buf && *(input_line_pointer - 1) == ']') { intel_state.is_mem |= 1; intel_state.is_indirect = 1; } input_line_pointer = saved_input_line_pointer; free (buf); gas_assert (!intel_state.in_offset); gas_assert (!intel_state.in_bracket); gas_assert (!intel_state.in_scale); if (!ret) return 0; if (intel_state.op_modifier != O_absent && current_templates->start->base_opcode != 0x8d /* lea */) { i.types[this_operand].bitfield.unspecified = 0; switch (intel_state.op_modifier) { case O_byte_ptr: i.types[this_operand].bitfield.byte = 1; suffix = BYTE_MNEM_SUFFIX; break; case O_word_ptr: i.types[this_operand].bitfield.word = 1; if ((current_templates->start->name[0] == 'l' && current_templates->start->name[2] == 's' && current_templates->start->name[3] == 0) || current_templates->start->base_opcode == 0x62 /* bound */) suffix = BYTE_MNEM_SUFFIX; /* so it will cause an error */ else if (got_a_float == 2) /* "fi..." */ suffix = SHORT_MNEM_SUFFIX; else suffix = WORD_MNEM_SUFFIX; break; case O_dword_ptr: i.types[this_operand].bitfield.dword = 1; if ((current_templates->start->name[0] == 'l' && current_templates->start->name[2] == 's' && current_templates->start->name[3] == 0) || current_templates->start->base_opcode == 0x62 /* bound */) suffix = WORD_MNEM_SUFFIX; else if (flag_code == CODE_16BIT && (current_templates->start->opcode_modifier.jump || current_templates->start->opcode_modifier.jumpdword)) suffix = LONG_DOUBLE_MNEM_SUFFIX; else if (got_a_float == 1) /* "f..." */ suffix = SHORT_MNEM_SUFFIX; else suffix = LONG_MNEM_SUFFIX; break; case O_fword_ptr: i.types[this_operand].bitfield.fword = 1; if (current_templates->start->name[0] == 'l' && current_templates->start->name[2] == 's' && current_templates->start->name[3] == 0) suffix = LONG_MNEM_SUFFIX; else if (!got_a_float) { if (flag_code == CODE_16BIT) add_prefix (DATA_PREFIX_OPCODE); suffix = LONG_DOUBLE_MNEM_SUFFIX; } else suffix = BYTE_MNEM_SUFFIX; /* so it will cause an error */ break; case O_qword_ptr: i.types[this_operand].bitfield.qword = 1; if (current_templates->start->base_opcode == 0x62 /* bound */ || got_a_float == 1) /* "f..." */ suffix = LONG_MNEM_SUFFIX; else suffix = QWORD_MNEM_SUFFIX; break; case O_tbyte_ptr: i.types[this_operand].bitfield.tbyte = 1; if (got_a_float == 1) suffix = LONG_DOUBLE_MNEM_SUFFIX; else suffix = BYTE_MNEM_SUFFIX; /* so it will cause an error */ break; case O_oword_ptr: case O_xmmword_ptr: i.types[this_operand].bitfield.xmmword = 1; suffix = XMMWORD_MNEM_SUFFIX; break; case O_ymmword_ptr: i.types[this_operand].bitfield.ymmword = 1; suffix = YMMWORD_MNEM_SUFFIX; break; case O_zmmword_ptr: i.types[this_operand].bitfield.zmmword = 1; suffix = ZMMWORD_MNEM_SUFFIX; break; case O_far_ptr: suffix = LONG_DOUBLE_MNEM_SUFFIX; /* FALLTHROUGH */ case O_near_ptr: if (!current_templates->start->opcode_modifier.jump && !current_templates->start->opcode_modifier.jumpdword) suffix = got_a_float /* so it will cause an error */ ? BYTE_MNEM_SUFFIX : LONG_DOUBLE_MNEM_SUFFIX; break; default: BAD_CASE (intel_state.op_modifier); break; } if (!i.suffix) i.suffix = suffix; else if (i.suffix != suffix) { as_bad (_("conflicting operand size modifiers")); return 0; } } /* Operands for jump/call need special consideration. */ if (current_templates->start->opcode_modifier.jump || current_templates->start->opcode_modifier.jumpdword || current_templates->start->opcode_modifier.jumpintersegment) { if (i.op[this_operand].regs || intel_state.base || intel_state.index || intel_state.is_mem > 1) i.types[this_operand].bitfield.jumpabsolute = 1; else switch (intel_state.op_modifier) { case O_near_ptr: if (intel_state.seg) i.types[this_operand].bitfield.jumpabsolute = 1; else intel_state.is_mem = 1; break; case O_far_ptr: case O_absent: if (!intel_state.seg) { intel_state.is_mem = 1; if (intel_state.op_modifier == O_absent) { if (intel_state.is_indirect == 1) i.types[this_operand].bitfield.jumpabsolute = 1; break; } as_bad (_("cannot infer the segment part of the operand")); return 0; } else if (S_GET_SEGMENT (intel_state.seg) == reg_section) i.types[this_operand].bitfield.jumpabsolute = 1; else { i386_operand_type types; if (i.imm_operands >= MAX_IMMEDIATE_OPERANDS) { as_bad (_("at most %d immediate operands are allowed"), MAX_IMMEDIATE_OPERANDS); return 0; } expP = &im_expressions[i.imm_operands++]; memset (expP, 0, sizeof(*expP)); expP->X_op = O_symbol; expP->X_add_symbol = intel_state.seg; i.op[this_operand].imms = expP; resolve_expression (expP); operand_type_set (&types, ~0); if (!i386_finalize_immediate (S_GET_SEGMENT (intel_state.seg), expP, types, operand_string)) return 0; if (i.operands < MAX_OPERANDS) { this_operand = i.operands++; i.types[this_operand].bitfield.unspecified = 1; } if (suffix == LONG_DOUBLE_MNEM_SUFFIX) i.suffix = 0; intel_state.seg = NULL; intel_state.is_mem = 0; } break; default: i.types[this_operand].bitfield.jumpabsolute = 1; break; } if (i.types[this_operand].bitfield.jumpabsolute) intel_state.is_mem |= 1; } else if (intel_state.seg) intel_state.is_mem |= 1; if (i.op[this_operand].regs) { i386_operand_type temp; /* Register operand. */ if (intel_state.base || intel_state.index || intel_state.seg) { as_bad (_("invalid operand")); return 0; } temp = i.op[this_operand].regs->reg_type; temp.bitfield.baseindex = 0; i.types[this_operand] = operand_type_or (i.types[this_operand], temp); i.types[this_operand].bitfield.unspecified = 0; ++i.reg_operands; } else if (intel_state.base || intel_state.index || intel_state.seg || intel_state.is_mem) { /* Memory operand. */ if ((int) i.mem_operands >= 2 - !current_templates->start->opcode_modifier.isstring) { /* Handle call 0x9090,0x90909090 lcall 0x9090,0x90909090 jmp 0x9090,0x90909090 ljmp 0x9090,0x90909090 */ if ((current_templates->start->opcode_modifier.jumpintersegment || current_templates->start->opcode_modifier.jumpdword || current_templates->start->opcode_modifier.jump) && this_operand == 1 && intel_state.seg == NULL && i.mem_operands == 1 && i.disp_operands == 1 && intel_state.op_modifier == O_absent) { /* Try to process the first operand as immediate, */ this_operand = 0; if (i386_finalize_immediate (exp_seg, i.op[0].imms, intel_state.reloc_types, NULL)) { this_operand = 1; expP = &im_expressions[0]; i.op[this_operand].imms = expP; *expP = exp; /* Try to process the second operand as immediate, */ if (i386_finalize_immediate (exp_seg, expP, intel_state.reloc_types, NULL)) { i.mem_operands = 0; i.disp_operands = 0; i.imm_operands = 2; i.types[0].bitfield.mem = 0; i.types[0].bitfield.disp16 = 0; i.types[0].bitfield.disp32 = 0; i.types[0].bitfield.disp32s = 0; return 1; } } } as_bad (_("too many memory references for `%s'"), current_templates->start->name); return 0; } expP = &disp_expressions[i.disp_operands]; memcpy (expP, &exp, sizeof(exp)); resolve_expression (expP); if (expP->X_op != O_constant || expP->X_add_number || (!intel_state.base && !intel_state.index)) { i.op[this_operand].disps = expP; i.disp_operands++; if (flag_code == CODE_64BIT) { i.types[this_operand].bitfield.disp32 = 1; if (!i.prefix[ADDR_PREFIX]) { i.types[this_operand].bitfield.disp64 = 1; i.types[this_operand].bitfield.disp32s = 1; } } else if (!i.prefix[ADDR_PREFIX] ^ (flag_code == CODE_16BIT)) i.types[this_operand].bitfield.disp32 = 1; else i.types[this_operand].bitfield.disp16 = 1; #if defined (OBJ_AOUT) || defined (OBJ_MAYBE_AOUT) /* * exp_seg is used only for verification in * i386_finalize_displacement, and we can end up seeing reg_section * here - but we know we removed all registers from the expression * (or error-ed on any remaining ones) in i386_intel_simplify. I * consider the check in i386_finalize_displacement bogus anyway, in * particular because it doesn't allow for expr_section, so I'd * rather see that check (and the similar one in * i386_finalize_immediate) use SEG_NORMAL(), but not being an a.out * expert I can't really say whether that would have other bad side * effects. */ if (OUTPUT_FLAVOR == bfd_target_aout_flavour && exp_seg == reg_section) exp_seg = expP->X_op != O_constant ? undefined_section : absolute_section; #endif if (!i386_finalize_displacement (exp_seg, expP, intel_state.reloc_types, operand_string)) return 0; } if (intel_state.base || intel_state.index) i.types[this_operand].bitfield.baseindex = 1; if (intel_state.seg) { for (;;) { expP = symbol_get_value_expression (intel_state.seg); if (expP->X_op != O_full_ptr) break; intel_state.seg = expP->X_add_symbol; } if (expP->X_op != O_register) { as_bad (_("segment register name expected")); return 0; } if (!i386_regtab[expP->X_add_number].reg_type.bitfield.sreg2 && !i386_regtab[expP->X_add_number].reg_type.bitfield.sreg3) { as_bad (_("invalid use of register")); return 0; } switch (i386_regtab[expP->X_add_number].reg_num) { case 0: i.seg[i.mem_operands] = &es; break; case 1: i.seg[i.mem_operands] = &cs; break; case 2: i.seg[i.mem_operands] = &ss; break; case 3: i.seg[i.mem_operands] = &ds; break; case 4: i.seg[i.mem_operands] = &fs; break; case 5: i.seg[i.mem_operands] = &gs; break; case RegFlat: i.seg[i.mem_operands] = NULL; break; } } /* Swap base and index in 16-bit memory operands like [si+bx]. Since i386_index_check is also used in AT&T mode we have to do that here. */ if (intel_state.base && intel_state.index && intel_state.base->reg_type.bitfield.reg16 && intel_state.index->reg_type.bitfield.reg16 && intel_state.base->reg_num >= 6 && intel_state.index->reg_num < 6) { i.base_reg = intel_state.index; i.index_reg = intel_state.base; } else { i.base_reg = intel_state.base; i.index_reg = intel_state.index; } if (!i386_index_check (operand_string)) return 0; i.types[this_operand].bitfield.mem = 1; ++i.mem_operands; } else { /* Immediate. */ if (i.imm_operands >= MAX_IMMEDIATE_OPERANDS) { as_bad (_("at most %d immediate operands are allowed"), MAX_IMMEDIATE_OPERANDS); return 0; } expP = &im_expressions[i.imm_operands++]; i.op[this_operand].imms = expP; *expP = exp; return i386_finalize_immediate (exp_seg, expP, intel_state.reloc_types, operand_string); } return 1; }
a0u/binutils-gdb
gas/config/tc-i386-intel.c
C
gpl-2.0
26,445
/* Common hooks for Adapteva Epiphany Copyright (C) 1994-2013 Free Software Foundation, Inc. Contributed by Embecosm on behalf of Adapteva, Inc. This file is part of GCC. GCC 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, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "common/common-target.h" #include "opts.h" #include "flags.h" #define TARGET_OPTION_OPTIMIZATION_TABLE epiphany_option_optimization_table #define TARGET_DEFAULT_TARGET_FLAGS \ (MASK_CMOVE | MASK_SOFT_CMPSF | MASK_SPLIT_LOHI | MASK_ROUND_NEAREST \ | MASK_VECT_DOUBLE | MASK_POST_INC | MASK_POST_MODIFY) #define TARGET_HAVE_NAMED_SECTIONS true #include "common/common-target-def.h" /* Implement TARGET_OPTION_OPTIMIZATION_TABLE. */ static const struct default_options epiphany_option_optimization_table[] = { { OPT_LEVELS_1_PLUS, OPT_fomit_frame_pointer, NULL, 1 }, { OPT_LEVELS_NONE, 0, NULL, 0 } }; struct gcc_targetm_common targetm_common = TARGETM_COMMON_INITIALIZER;
atgreen/gcc
gcc/common/config/epiphany/epiphany-common.c
C
gpl-2.0
1,543
/* ** $Id: lobject.c,v 1.97 2003/04/03 13:35:34 roberto Exp $ ** Some generic functions over Lua objects ** See Copyright Notice in lua.h */ #include <ctype.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #define lobject_c #include "lua.h" #include "ldo.h" #include "lmem.h" #include "lobject.h" #include "lstate.h" #include "lstring.h" #include "lvm.h" /* function to convert a string to a lua_Number */ #ifndef lua_str2number #define lua_str2number(s,p) strtod((s), (p)) #endif const TObject luaO_nilobject = {LUA_TNIL, {NULL}}; /* ** converts an integer to a "floating point byte", represented as ** (mmmmmxxx), where the real value is (xxx) * 2^(mmmmm) */ int luaO_int2fb (unsigned int x) { int m = 0; /* mantissa */ while (x >= (1<<3)) { x = (x+1) >> 1; m++; } return (m << 3) | cast(int, x); } int luaO_log2 (unsigned int x) { static const lu_byte log_8[255] = { 0, 1,1, 2,2,2,2, 3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7 }; if (x >= 0x00010000) { if (x >= 0x01000000) return log_8[((x>>24) & 0xff) - 1]+24; else return log_8[((x>>16) & 0xff) - 1]+16; } else { if (x >= 0x00000100) return log_8[((x>>8) & 0xff) - 1]+8; else if (x) return log_8[(x & 0xff) - 1]; return -1; /* special `log' for 0 */ } } int luaO_rawequalObj (const TObject *t1, const TObject *t2) { if (ttype(t1) != ttype(t2)) return 0; else switch (ttype(t1)) { case LUA_TNIL: return 1; case LUA_TNUMBER: return nvalue(t1) == nvalue(t2); case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* boolean true must be 1 !! */ case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2); default: lua_assert(iscollectable(t1)); return gcvalue(t1) == gcvalue(t2); } } int luaO_str2d (const char *s, lua_Number *result) { char *endptr; lua_Number res = lua_str2number(s, &endptr); if (endptr == s) return 0; /* no conversion */ while (isspace((unsigned char)(*endptr))) endptr++; if (*endptr != '\0') return 0; /* invalid trailing characters? */ *result = res; return 1; } static void pushstr (lua_State *L, const char *str) { setsvalue2s(L->top, luaS_new(L, str)); incr_top(L); } /* this function handles only `%d', `%c', %f, and `%s' formats */ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { int n = 1; pushstr(L, ""); for (;;) { const char *e = strchr(fmt, '%'); if (e == NULL) break; setsvalue2s(L->top, luaS_newlstr(L, fmt, e-fmt)); incr_top(L); switch (*(e+1)) { case 's': pushstr(L, va_arg(argp, char *)); break; case 'c': { char buff[2]; buff[0] = cast(char, va_arg(argp, int)); buff[1] = '\0'; pushstr(L, buff); break; } case 'd': setnvalue(L->top, cast(lua_Number, va_arg(argp, int))); incr_top(L); break; case 'f': setnvalue(L->top, cast(lua_Number, va_arg(argp, l_uacNumber))); incr_top(L); break; case '%': pushstr(L, "%"); break; default: lua_assert(0); } n += 2; fmt = e+2; } pushstr(L, fmt); luaV_concat(L, n+1, L->top - L->base - 1); L->top -= n; return svalue(L->top - 1); } const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) { const char *msg; va_list argp; va_start(argp, fmt); msg = luaO_pushvfstring(L, fmt, argp); va_end(argp); return msg; } void luaO_chunkid (char *out, const char *source, int bufflen) { if (*source == '=') { strncpy(out, source+1, bufflen); /* remove first char */ out[bufflen-1] = '\0'; /* ensures null termination */ } else { /* out = "source", or "...source" */ if (*source == '@') { int l; source++; /* skip the `@' */ bufflen -= sizeof(" `...' "); l = strlen(source); strcpy(out, ""); if (l>bufflen) { source += (l-bufflen); /* get last part of file name */ strcat(out, "..."); } strcat(out, source); } else { /* out = [string "string"] */ int len = strcspn(source, "\n"); /* stop at first newline */ bufflen -= sizeof(" [string \"...\"] "); if (len > bufflen) len = bufflen; strcpy(out, "[string \""); if (source[len] != '\0') { /* must truncate? */ strncat(out, source, len); strcat(out, "..."); } else strcat(out, source); strcat(out, "\"]"); } } }
kidmaple/CoolWall
user/lua/src/lobject.c
C
gpl-2.0
4,994
/*********************************************************************** filename: CEGUIForwardRefs.h created: 21/2/2004 author: Paul D Turner purpose: Forward declares all core system classes *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS 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. ***************************************************************************/ #ifndef _CEGUIForwardRefs_h_ #define _CEGUIForwardRefs_h_ // Start of CEGUI namespace section namespace CEGUI { /************************************************************************* Forward declare majority of core classes *************************************************************************/ class Affector; class Animation; class AnimationInstance; class AnimationManager; class BasicRenderedStringParser; class BiDiVisualMapping; class CentredRenderedString; class colour; class ColourRect; class CoordConverter; class DefaultLogger; class DefaultRenderedStringParser; class DefaultResourceProvider; class DynamicModule; class Event; class EventArgs; class EventSet; class Exception; class FactoryModule; class Font; class FontGlyph; class FontManager; class FormattedRenderedString; class GeometryBuffer; class GlobalEventSet; class Image; class ImageCodec; class ImagerySection; class Imageset; class ImagesetManager; class Interpolator; class JustifiedRenderedString; class KeyFrame; class LeftAlignedRenderedString; class Logger; class MouseCursor; class Property; class PropertyHelper; class PropertyReceiver; class PropertySet; class RawDataContainer; class Rect; class RegexMatcher; class RenderedString; class RenderedStringComponent; class RenderedStringImageComponent; class RenderedStringParser; class RenderedStringTextComponent; class RenderedStringWidgetComponent; class Renderer; class RenderEffect; class RenderEffectManager; struct RenderingContext; class RenderingRoot; class RenderingSurface; class RenderingWindow; class RenderQueue; class RenderSystem; class RenderTarget; class ResourceEventSet; class ResourceProvider; class RightAlignedRenderedString; class Scheme; class SchemeManager; class ScriptFunctor; class ScriptModule; class Size; class String; class System; class Texture; class TextureTarget; class TextUtils; class UBox; class UDim; class URect; class UVector2; class Vector2; class Vector3; struct Vertex; class WidgetLookFeel; class Window; class WindowFactory; class WindowFactoryManager; class WindowManager; class WindowRenderer; class WindowRendererModule; class WRFactoryRegisterer; class XMLAttributes; class XMLHandler; class XMLParser; /************************************************************************* Forward declare window / widget classes. *************************************************************************/ class ButtonBase; class Checkbox; class ClippedContainer; class Combobox; class ComboDropList; class DragContainer; class Editbox; class FrameWindow; class GridLayoutContainer; class GUISheet; class HorizontalLayoutContainer; class ItemEntry; class ItemListBase; class ItemListbox; class LayoutContainer; class Listbox; class ListboxItem; class ListboxTextItem; class ListHeader; class ListHeaderSegment; class Menubar; class MenuBase; class MenuItem; class MultiColumnList; class MultiLineEditbox; class PopupMenu; class ProgressBar; class PushButton; class RadioButton; class ScrollablePane; class Scrollbar; class ScrolledContainer; class ScrolledItemListBase; class SequentialLayoutContainer; class Slider; class Spinner; class TabButton; class TabControl; class Thumb; class Titlebar; class Tooltip; class Tree; class TreeItem; class VerticalLayoutContainer; /************************************************************************* Forward declare EventArg based classes. *************************************************************************/ class ActivationEventArgs; class DisplayEventArgs; class DragDropEventArgs; class HeaderSequenceEventArgs; class KeyEventArgs; class MouseCursorEventArgs; class MouseEventArgs; class RenderQueueEventArgs; class ResourceEventArgs; class TreeEventArgs; class UpdateEventArgs; class WindowEventArgs; } // End of CEGUI namespace section #endif // end of guard _CEGUIForwardRefs_h_
gorkinovich/DefendersOfMankind
dependencies/include/cegui/CEGUIForwardRefs.h
C
gpl-3.0
5,430
SET PATH=%PATH%;..\..\lib Debug\qt_example.exe
batmancn/MyLife
works/SipWrapper/sipstack/resiprocate-1.7/tfm/contrib/cppunit/examples/qt/run.bat
Batchfile
gpl-3.0
47
// Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). package org.pantsbuild.tools.jar; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.List; import java.util.jar.Attributes.Name; import java.util.jar.Manifest; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.annotation.Nullable; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.MoreObjects; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.io.Closer; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.kohsuke.args4j.OptionDef; import org.kohsuke.args4j.spi.Setter; import org.pantsbuild.args4j.ArgfileOptionHandler; import org.pantsbuild.args4j.CollectionOptionHandler; import org.pantsbuild.args4j.InvalidCmdLineArgumentException; import org.pantsbuild.args4j.Parser; import org.pantsbuild.tools.jar.JarBuilder.DuplicateAction; import org.pantsbuild.tools.jar.JarBuilder.DuplicateEntryException; import org.pantsbuild.tools.jar.JarBuilder.DuplicateHandler; import org.pantsbuild.tools.jar.JarBuilder.DuplicatePolicy; import org.pantsbuild.tools.jar.JarBuilder.Entry; import org.pantsbuild.tools.jar.JarBuilder.Listener; import org.pantsbuild.tools.jar.JarBuilder.Source; public final class Main { public static class Options { public static class DuplicatePolicyParser extends CollectionOptionHandler<DuplicatePolicy> { private static final Splitter REGEX_ACTION_SPLITTER = Splitter.on('=').trimResults().omitEmptyStrings(); public DuplicatePolicyParser( CmdLineParser parser, OptionDef option, Setter<? super DuplicatePolicy> setter) { super(parser, option, setter, "DUPLICATE_POLICY", new ItemParser<DuplicatePolicy>() { @Override public DuplicatePolicy parse(String item) { List<String> components = ImmutableList.copyOf(REGEX_ACTION_SPLITTER.split(item)); Preconditions.checkArgument(components.size() == 2, "Failed to parse jar path regex/action pair %s", item); String regex = components.get(0); DuplicateAction action = DuplicateAction.valueOf(components.get(1)); return DuplicatePolicy.pathMatches(regex, action); } }); } } static class FileSource { private static final Splitter JAR_PATH_SPLITTER = Splitter.on('/'); private final File source; @Nullable private final String destination; FileSource(File source, @Nullable String destination) { if (!source.exists() || !source.canRead()) { throw new IllegalArgumentException( String.format("The source %s is not a readable path", source)); } if (!source.isDirectory() && destination == null) { throw new IllegalArgumentException( String.format("The source file %s must have a jar destination specified.", source)); } if (destination != null) { Preconditions.checkArgument(!Strings.isNullOrEmpty(destination.trim()), "The destination path cannot be blank"); Preconditions.checkArgument( !destination.startsWith("/"), "The destination path cannot be absolute, given: %s", destination); Preconditions.checkArgument( !ImmutableSet.copyOf(JAR_PATH_SPLITTER.split(destination)).contains(".."), "The destination path cannot be relative, given: %s", destination); } this.source = source; this.destination = destination; } void addTo(JarBuilder jarBuilder) { if (source.isDirectory()) { jarBuilder.addDirectory(source, Optional.fromNullable(destination)); } else { jarBuilder.addFile(source, destination); } } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("source", source) .add("destination", destination) .toString(); } } public static class FileSourceOptionHandler extends CollectionOptionHandler<FileSource> { private static final Splitter DESTINATION_SPLITTER = Splitter.on('=').trimResults().omitEmptyStrings(); public FileSourceOptionHandler( CmdLineParser parser, OptionDef option, Setter<? super FileSource> setter) { super(parser, option, setter, "FILE_SOURCE", new ItemParser<FileSource>() { @Override public FileSource parse(String item) { List<String> components = ImmutableList.copyOf(DESTINATION_SPLITTER.split(item)); Preconditions.checkArgument(1 <= components.size() && components.size() <= 2, "Failed to parse entry %s", item); File source = new File(components.get(0)); @Nullable String destination = components.size() == 2 ? components.get(1) : null; return new FileSource(source, destination); } }); } } @Option(name = "-h", aliases = {"-help"}, help = true, usage = "Display this help screen.") private boolean help; @Option(name = "-main", usage = "The name of the fully qualified main class. " + "If a -manifest is specified its contents will be used but this -main will override " + "any entry already present.") private String mainClass; public static class ClassPathOptionHandler extends ArgfileOptionHandler<String> { public ClassPathOptionHandler( CmdLineParser parser, OptionDef option, Setter<? super String> setter) { super(new CollectionOptionHandler<String>( parser, option, setter, "CLASS_PATH_ENTRY", CollectionOptionHandler.ItemParser.IDENTITY)); } } @Option(name = "-classpath", usage = "A list of comma-separated classpath entries. " + "If a -manifest is specified its contents will be used but this -classpath will " + "override any entry already present.", handler = ClassPathOptionHandler.class) private List<String> classPath = null; private File manifest; @Option(name = "-manifest", usage = "A path to a manifest file to use. If -main or -classpath is specified those " + "values will overwrite the corresponding entry in this manifest.") void setManifest(File manifest) { if (manifest == null) { throw new InvalidCmdLineArgumentException("-manifest", manifest, "Cannot be null."); } if (!manifest.exists()) { throw new InvalidCmdLineArgumentException("-manifest", manifest, "Must exist."); } if (!manifest.isFile()) { throw new InvalidCmdLineArgumentException("-manifest", manifest, "Must be a file."); } if (!manifest.canRead()) { throw new InvalidCmdLineArgumentException("-manifest", manifest, "Must be readable."); } this.manifest = manifest; } @Option(name = "-update", usage = "Update the jar if it already exists, otherwise create it.") private boolean update; @Option(name = "-compress", usage = "Compress jar entries.") private boolean compress; public static class FilesOptionHandler extends ArgfileOptionHandler<FileSource> { public FilesOptionHandler( CmdLineParser parser, OptionDef option, Setter<? super FileSource> setter) { super(new FileSourceOptionHandler(parser, option, setter)); } } @Option(name = "-files", usage = "A mapping from filesystem paths to jar paths. The mapping is specified in the " + "form [fs path1](=[jar path1]),[fs path2](=[jar path2]). For example: " + "/etc/hosts=hosts,/var/log=logs would create a jar with a hosts file entry and the " + "contents of the /var/log tree added as individual entries under the logs/ directory " + "in the jar. For directories, the mapping can be skipped in which case the directory " + "tree is added as-is to the resulting jar.", handler = FilesOptionHandler.class) private List<FileSource> files = Lists.newArrayList(); public static class JarsOptionHandler extends ArgfileOptionHandler<File> { public JarsOptionHandler( CmdLineParser parser, OptionDef option, Setter<? super File> setter) { super(new CollectionOptionHandler<File>( parser, option, setter, "JAR", new CollectionOptionHandler.ItemParser<File>() { @Override public File parse(String item) { return new File(item); } })); } } @Option(name = "-jars", usage = "A list of comma-separated jar files whose entries to add to the output jar.", handler = JarsOptionHandler.class) private List<File> jars = Lists.newArrayList(); public static class PatternOptionHandler extends CollectionOptionHandler<Pattern> { public PatternOptionHandler( CmdLineParser parser, OptionDef option, Setter<? super Pattern> setter) { super(parser, option, setter, "PATTERN", new ItemParser<Pattern>() { @Override public Pattern parse(String item) { try { return Pattern.compile(item); } catch (PatternSyntaxException e) { throw new IllegalArgumentException(e); } } }); } } @Option(name = "-skip", usage = "A list of regular expressions identifying entries to skip.", handler = PatternOptionHandler.class) private List<Pattern> skip = Lists.newArrayList(); private static final String ACTIONS = "SKIP|REPLACE|CONCAT|CONCAT_TEXT|THROW"; @Option(name = "-default_action", usage = "The default duplicate action to apply if no policies match. Can be any of " + ACTIONS) private DuplicateAction defaultAction = DuplicateAction.SKIP; @Option(name = "-policies", usage = "A list of duplicate policies to apply. Policies are specified as " + "[regex]=[action], and the action can be any one of " + ACTIONS + ". For example: " + "^META-INF/services/=CONCAT_TEXT would concatenate duplicate service files into one " + "large service file.", handler = DuplicatePolicyParser.class) private List<DuplicatePolicy> policies = Lists.newArrayList(); @Argument(metaVar = "TARGET_JAR", usage = "The target jar file path to write.", required = true) private File targetJar; } private static final Logger LOG = Logger.getLogger(Main.class.getName()); private static class LoggingListener implements Listener { private Source source = null; private final File target; LoggingListener(File target) { this.target = target; } @Override public void onSkip(Optional<? extends Entry> original, Iterable<? extends Entry> skipped) { if (LOG.isLoggable(Level.FINE)) { if (original.isPresent()) { LOG.fine(String.format("Retaining %s and skipping %s", identify(original.get()), identify(skipped))); } else { LOG.fine(String.format("Skipping %s", identify(skipped))); } } } @Override public void onReplace(Iterable<? extends Entry> originals, Entry replacement) { if (LOG.isLoggable(Level.FINE)) { LOG.fine(String.format("Using %s to replace %s", identify(replacement), identify(originals))); } } @Override public void onConcat(String entryName, Iterable<? extends Entry> entries) { if (LOG.isLoggable(Level.FINE)) { LOG.fine(String.format("Concatenating %s!%s from %s", target.getPath(), entryName, identify(entries))); } } @Override public void onWrite(Entry entry) { if (!entry.getSource().equals(source)) { source = entry.getSource(); LOG.fine(entry.getSource().name()); } LOG.log(Level.FINER, "\t{0}", entry.getName()); } private static String identify(Entry entry) { return entry.getSource().identify(entry.getName()); } private static String identify(Iterable<? extends Entry> entries) { return Joiner.on(",").join( FluentIterable.from(entries).transform(new Function<Entry, String>() { @Override public String apply(Entry input) { return identify(input); } })); } } private final Options options; private Main(Options options) { this.options = options; } static class ExitException extends Exception { private final int code; ExitException(int code, String message, Object... args) { super(String.format(message, args)); this.code = code; } } private void run() throws ExitException { if (options.mainClass != null && options.manifest != null) { throw new ExitException(1, "Can specify main or manifest but not both."); } if (!options.update && options.targetJar.exists() && !options.targetJar.delete()) { throw new ExitException(1, "Failed to delete file at requested target path %s", options.targetJar); } final Closer closer = Closer.create(); try { doRun(closer, options.targetJar); } finally { try { closer.close(); } catch (IOException e) { LOG.warning("Failed to close one or more resources: " + e); } } } private void doRun(Closer closer, final File targetJar) throws ExitException { JarBuilder jarBuilder = closer.register(new JarBuilder(targetJar, new LoggingListener(targetJar))); try { @Nullable Manifest mf = getManifest(); if (mf != null) { jarBuilder.useCustomManifest(mf); } } catch (IOException e) { throw new ExitException(1, "Failed to configure custom manifest: %s", e); } for (Options.FileSource fileSource : options.files) { fileSource.addTo(jarBuilder); } for (File jar : options.jars) { jarBuilder.addJar(jar); } DuplicateHandler duplicateHandler = new DuplicateHandler(options.defaultAction, options.policies); try { jarBuilder.write(options.compress, duplicateHandler, options.skip); } catch (DuplicateEntryException e) { throw new ExitException(1, "Refusing to write duplicate entry: %s", e); } catch (IOException e) { throw new ExitException(1, "Unexpected problem writing target jar %s: %s", targetJar, e); } } private static final Splitter CLASS_PATH_SPLITTER = Splitter.on(File.pathSeparatorChar).omitEmptyStrings(); private static final Function<String, Iterable<String>> ENTRY_TO_PATHS = new Function<String, Iterable<String>>() { @Override public Iterable<String> apply(String entry) { return CLASS_PATH_SPLITTER.split(entry); } }; private static final Joiner CLASS_PATH_JOINER = Joiner.on(' '); @Nullable private Manifest getManifest() throws IOException { if (options.manifest == null && options.mainClass == null && options.classPath == null) { return null; } Manifest mf = loadManifest(); if (options.mainClass != null) { mf.getMainAttributes().put(Name.MAIN_CLASS, options.mainClass); } if (options.classPath != null) { String classpath = CLASS_PATH_JOINER.join( FluentIterable.from(options.classPath).transformAndConcat(ENTRY_TO_PATHS)); mf.getMainAttributes().put(Name.CLASS_PATH, classpath); } return mf; } private Manifest loadManifest() throws IOException { Manifest mf = new Manifest(); if (options.manifest != null) { Closer closer = Closer.create(); try { FileInputStream input = closer.register(new FileInputStream(options.manifest)); mf.read(input); } catch (IOException e) { throw closer.rethrow( new IOException("Failed to load manifest from " + options.manifest, e)); } finally { closer.close(); } } return JarBuilder.ensureDefaultManifestEntries(mf); } /** * Creates or updates a jar with specified files, directories and jar files. * * @param args The command line arguments. */ public static void main(String[] args) { ConsoleHandler handler = new ConsoleHandler(); handler.setFormatter(new SimpleFormatter()); handler.setLevel(Level.WARNING); Logger.getLogger("").addHandler(handler); Options options = new Options(); Parser.Result result = Parser.parse(options, args); if (result.isFailure()) { result.printUsage(System.err); exit(1); } else if (options.help) { result.printUsage(System.out); exit(0); } Main main = new Main(options); try { main.run(); } catch (ExitException e) { System.err.println(e.getMessage()); exit(e.code); } exit(0); } private static void exit(int code) { // We're a main - its fine to exit. // SUPPRESS CHECKSTYLE RegexpSinglelineJava System.exit(code); } }
cevaris/pants
src/java/org/pantsbuild/tools/jar/Main.java
Java
apache-2.0
17,907
// (C) Copyright 2015 Martin Dougiamas // // 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. angular.module('mm.core.fileuploader') /** * Service to interact with addons to be shown in the file picker to upload a file. * * @module mm.core.fileuploader * @ngdoc provider * @name $mmFileUploaderDelegate */ .provider('$mmFileUploaderDelegate', function() { var handlers = {}, self = {}; /** * Register a file picker handler. * * @module mm.core.fileuploader * @ngdoc method * @name $mmFileUploaderDelegate#registerHandler * @param {String} addon The addon's name (mmaFiles, mmaMessages, ...) * @param {String|Object|Function} handler Must be resolved to an object defining the following functions. Or to a function * returning an object defining these functions. See {@link $mmUtil#resolveObject}. * - isEnabled (Boolean|Promise) Whether or not the handler is enabled on a site level. * When using a promise, it should return a boolean. * - getController (Object) Returns the object that will act as controller. This is the list of * expected scope variables: * * class Optional. Class to add to the handler's row. * * title Required. Title to show in the handler's row. * * icon Optional. Icon to show in the handler's row. * * action Required. A function called when the handler is clicked, receives maxSize * as parameter. It must return an object - or a promise resolved with an object - * containing these properties: * - uploaded Boolean. Whether the handler uploaded the file. * - path String. Ignored if uploaded=true. The path of the file to upload. * - fileEntry Object. Ignored if uploaded=true. The fileEntry to upload. * - delete Boolean. Ignored if uploaded=true. Whether the file should be * deleted after upload. * - result Object. Ignored if uploaded=false. The result of the upload. */ self.registerHandler = function(addon, handler, priority) { if (typeof handlers[addon] !== 'undefined') { console.log("$mmFileUploaderDelegate: Addon '" + handlers[addon].addon + "' already registered as handler"); return false; } console.log("$mmFileUploaderDelegate: Registered addon '" + addon + "' as handler."); handlers[addon] = { addon: addon, handler: handler, instance: undefined, priority: priority }; return true; }; self.$get = function($mmUtil, $q, $log, $mmSite) { var enabledHandlers = {}, self = {}, lastUpdateHandlersStart; $log = $log.getInstance('$mmFileUploaderDelegate'); /** * Clear current site handlers. Reserved for core use. * * @module mm.core.fileuploader * @ngdoc method * @name $mmFileUploaderDelegate#clearSiteHandlers * @return {Void} */ self.clearSiteHandlers = function() { enabledHandlers = {}; }; /** * Get the handlers for the current site. * * @module mm.core.fileuploader * @ngdoc method * @name $mmFileUploaderDelegate#getHandlers * @return {Promise} Resolved with an array of objects containing 'priority' and 'controller'. */ self.getHandlers = function() { var handlers = []; angular.forEach(enabledHandlers, function(handler) { handlers.push({ controller: handler.instance.getController(), priority: handler.priority }); }); return handlers; }; /** * Check if a time belongs to the last update handlers call. * This is to handle the cases where updateHandlers don't finish in the same order as they're called. * * @module mm.core.fileuploader * @ngdoc method * @name $mmFileUploaderDelegate#isLastUpdateCall * @param {Number} time Time to check. * @return {Boolean} True if equal, false otherwise. */ self.isLastUpdateCall = function(time) { if (!lastUpdateHandlersStart) { return true; } return time == lastUpdateHandlersStart; }; /** * Update the handler for the current site. * * @module mm.core.fileuploader * @ngdoc method * @name $mmFileUploaderDelegate#updateHandler * @param {String} addon The addon. * @param {Object} handlerInfo The handler details. * @param {Number} time Time this update process started. * @return {Promise} Resolved when enabled, rejected when not. * @protected */ self.updateHandler = function(addon, handlerInfo, time) { var promise, siteId = $mmSite.getId(); if (typeof handlerInfo.instance === 'undefined') { handlerInfo.instance = $mmUtil.resolveObject(handlerInfo.handler, true); } if (!$mmSite.isLoggedIn()) { promise = $q.reject(); } else { promise = $q.when(handlerInfo.instance.isEnabled()); } // Checks if the content is enabled. return promise.catch(function() { return false; }).then(function(enabled) { // Verify that this call is the last one that was started. // Check that site hasn't changed since the check started. if (self.isLastUpdateCall(time) && $mmSite.isLoggedIn() && $mmSite.getId() === siteId) { if (enabled) { enabledHandlers[addon] = { instance: handlerInfo.instance, priority: handlerInfo.priority }; } else { delete enabledHandlers[addon]; } } }); }; /** * Update the handlers for the current site. * * @module mm.core.fileuploader * @ngdoc method * @name $mmFileUploaderDelegate#updateHandlers * @return {Promise} Resolved when done. * @protected */ self.updateHandlers = function() { var promises = [], now = new Date().getTime(); $log.debug('Updating navigation handlers for current site.'); lastUpdateHandlersStart = now; // Loop over all the content handlers. angular.forEach(handlers, function(handlerInfo, addon) { promises.push(self.updateHandler(addon, handlerInfo, now)); }); return $q.all(promises).then(function() { return true; }, function() { // Never reject. return true; }); }; return self; }; return self; });
gethanos/leoapp
www/core/components/fileuploader/services/delegate.js
JavaScript
apache-2.0
8,373
/** * Copyright 2016 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. */ import { stringToBytes, bytesToString, getCryptoRandomBytesArray, utf8Encode, utf8Decode, } from '../../../src/utils/bytes'; describe('stringToBytes', function() { let fakeWin; beforeEach(() => { fakeWin = { crypto: { getRandomValues: array => { for (let i = 0; i < array.length; i++) { array[i] = i + 1; } }, }, }; }); it('should map a sample string appropriately', () => { const bytes = stringToBytes('abÿ'); expect(bytes.length).to.equal(3); expect(bytes[0]).to.equal(97); expect(bytes[1]).to.equal(98); expect(bytes[2]).to.equal(255); }); it('should signal an error with a character >255', () => { expect(() => { return stringToBytes('ab☺'); }).to.throw(); }); it('should convert bytes array to string', () => { const str = bytesToString(new Uint8Array([102, 111, 111])); expect(str).to.equal('foo'); }); it('should generate random bytes array when win.crypto is availble', () => { expect(getCryptoRandomBytesArray(fakeWin, 1)).to.deep .equal(new Uint8Array([1])); expect(getCryptoRandomBytesArray(fakeWin, 2)).to.deep .equal(new Uint8Array([1, 2])); expect(getCryptoRandomBytesArray(fakeWin, 3)).to.deep .equal(new Uint8Array([1, 2, 3])); }); it('should return null when trying to generate random bytes array if ' + 'win.crypto is not availble', () => { fakeWin.crypto = undefined; expect(getCryptoRandomBytesArray(fakeWin, 1)).to.be.null; }); }); describe('utf8', function() { // Examples here courtesy of StackOverflow: // http://stackoverflow.com/questions/478201/how-to-test-an-application-for // -correct-encoding-e-g-utf-8 const strings = [ 'ユーザー別サイト', '简体中文', '크로스플랫폼으로', 'מדוריםמבוקשים', 'أفضلالبحوث', 'Σὲγνωρίζωἀπὸ', 'ДесятуюМеждународную', 'แผ่นดินฮั่นเสื่อมโทรมแสนสังเวช', ]; const bytes = [ [0xe3, 0x83, 0xa6, 0xe3, 0x83, 0xbc, 0xe3, 0x82, 0xb6, 0xe3, 0x83, 0xbc, 0xe5, 0x88, 0xa5, 0xe3, 0x82, 0xb5, 0xe3, 0x82, 0xa4, 0xe3, 0x83, 0x88], [0xe7, 0xae, 0x80, 0xe4, 0xbd, 0x93, 0xe4, 0xb8, 0xad, 0xe6, 0x96, 0x87], [0xed, 0x81, 0xac, 0xeb, 0xa1, 0x9c, 0xec, 0x8a, 0xa4, 0xed, 0x94, 0x8c, 0xeb, 0x9e, 0xab, 0xed, 0x8f, 0xbc, 0xec, 0x9c, 0xbc, 0xeb, 0xa1, 0x9c], [0xd7, 0x9e, 0xd7, 0x93, 0xd7, 0x95, 0xd7, 0xa8, 0xd7, 0x99, 0xd7, 0x9d, 0xd7, 0x9e, 0xd7, 0x91, 0xd7, 0x95, 0xd7, 0xa7, 0xd7, 0xa9, 0xd7, 0x99, 0xd7, 0x9d], [0xd8, 0xa3, 0xd9, 0x81, 0xd8, 0xb6, 0xd9, 0x84, 0xd8, 0xa7, 0xd9, 0x84, 0xd8, 0xa8, 0xd8, 0xad, 0xd9, 0x88, 0xd8, 0xab], [0xce, 0xa3, 0xe1, 0xbd, 0xb2, 0xce, 0xb3, 0xce, 0xbd, 0xcf, 0x89, 0xcf, 0x81, 0xce, 0xaf, 0xce, 0xb6, 0xcf, 0x89, 0xe1, 0xbc, 0x80, 0xcf, 0x80, 0xe1, 0xbd, 0xb8], [0xd0, 0x94, 0xd0, 0xb5, 0xd1, 0x81, 0xd1, 0x8f, 0xd1, 0x82, 0xd1, 0x83, 0xd1, 0x8e, 0xd0, 0x9c, 0xd0, 0xb5, 0xd0, 0xb6, 0xd0, 0xb4, 0xd1, 0x83, 0xd0, 0xbd, 0xd0, 0xb0, 0xd1, 0x80, 0xd0, 0xbe, 0xd0, 0xb4, 0xd0, 0xbd, 0xd1, 0x83, 0xd1, 0x8e], [0xe0, 0xb9, 0x81, 0xe0, 0xb8, 0x9c, 0xe0, 0xb9, 0x88, 0xe0, 0xb8, 0x99, 0xe0, 0xb8, 0x94, 0xe0, 0xb8, 0xb4, 0xe0, 0xb8, 0x99, 0xe0, 0xb8, 0xae, 0xe0, 0xb8, 0xb1, 0xe0, 0xb9, 0x88, 0xe0, 0xb8, 0x99, 0xe0, 0xb9, 0x80, 0xe0, 0xb8, 0xaa, 0xe0, 0xb8, 0xb7, 0xe0, 0xb9, 0x88, 0xe0, 0xb8, 0xad, 0xe0, 0xb8, 0xa1, 0xe0, 0xb9, 0x82, 0xe0, 0xb8, 0x97, 0xe0, 0xb8, 0xa3, 0xe0, 0xb8, 0xa1, 0xe0, 0xb9, 0x81, 0xe0, 0xb8, 0xaa, 0xe0, 0xb8, 0x99, 0xe0, 0xb8, 0xaa, 0xe0, 0xb8, 0xb1, 0xe0, 0xb8, 0x87, 0xe0, 0xb9, 0x80, 0xe0, 0xb8, 0xa7, 0xe0, 0xb8, 0x8a], ]; it('should encode given string into utf-8 byte array', () => { for (let i = 0; i < strings.length; i++) { utf8Encode(strings[i]).then(byteArray => expect(byteArray).to.deep .equal(new Uint8Array(bytes[i]))); } }); it('should decode given utf-8 bytes into string', () => { for (let i = 0; i < bytes.length; i++) { utf8Decode(new Uint8Array(bytes[i])).then(string => expect(string).to .equal(strings[i])); } }); });
DistroScale/amphtml
test/functional/utils/test-bytes.js
JavaScript
apache-2.0
4,931
#include <stdarg.h> #include <stddef.h> #include <setjmp.h> #include "cmockery.h" #include "../auth.c" #ifdef ENABLE_GSS /* Unit tests for check_valid_until_for_gssapi() function */ void test_checkValidUntilForGssapi1(void **state) { int result = -1; Port *port = (Port *) malloc(sizeof(Port)); port->user_name = "foo"; expect_any(get_role_line, role); will_return(get_role_line, NULL); result = check_valid_until_for_gssapi(port); assert_true(result == STATUS_ERROR); } void test_checkValidUntilForGssapi2(void **state) { int result = -1; List *list = list_make1("foo"); List **line = &list; Port *port = (Port *) malloc(sizeof(Port)); port->user_name = "foo"; expect_any(get_role_line, role); will_return(get_role_line, line); result = check_valid_until_for_gssapi(port); assert_true(result == STATUS_OK); } void test_checkValidUntilForGssapi3(void **state) { int result = -1; ListCell *cell; List *list = list_make1(cell); List **line = &list; Port *port = (Port *) malloc(sizeof(Port)); port->user_name = "foo"; expect_any(get_role_line, role); will_return(get_role_line, line); result = check_valid_until_for_gssapi(port); assert_true(result == STATUS_OK); } void test_checkValidUntilForGssapi4(void **state) { int result = -1; ListCell *cell; ListCell *cell1; List *list = list_make2(cell, cell1); List **line = &list; Port *port = (Port *) malloc(sizeof(Port)); port->user_name = "foo"; expect_any(get_role_line, role); will_return(get_role_line, line); result = check_valid_until_for_gssapi(port); assert_true(result == STATUS_OK); } void test_checkValidUntilForGssapi5(void **state) { int result = -1; ListCell *cell; ListCell *cell1; ListCell *cell2; List *list = list_make3(cell, "foo", "bar"); List **line = &list; Port *port = (Port *) malloc(sizeof(Port)); port->user_name = "foo"; expect_any(get_role_line, role); will_return(get_role_line, line); expect_any(DirectFunctionCall3, func); expect_any(DirectFunctionCall3, arg1); expect_any(DirectFunctionCall3, arg2); expect_any(DirectFunctionCall3, arg3); will_return(DirectFunctionCall3, 10293842); will_return(GetCurrentTimestamp, 10293843); result = check_valid_until_for_gssapi(port); assert_true(result == STATUS_ERROR); } void test_checkValidUntilForGssapi6(void **state) { int result = -1; ListCell *cell; ListCell *cell1; ListCell *cell2; List *list = list_make3(cell, "foo", "bar"); List **line = &list; Port *port = (Port *) malloc(sizeof(Port)); port->user_name = "foo"; expect_any(get_role_line, role); will_return(get_role_line, line); expect_any(DirectFunctionCall3, func); expect_any(DirectFunctionCall3, arg1); expect_any(DirectFunctionCall3, arg2); expect_any(DirectFunctionCall3, arg3); will_return(DirectFunctionCall3, 10293844); will_return(GetCurrentTimestamp, 10293843); result = check_valid_until_for_gssapi(port); assert_true(result == STATUS_OK); } #endif int main(int argc, char* argv[]) { cmockery_parse_arguments(argc, argv); const UnitTest tests[] = { #ifdef ENABLE_GSS unit_test(test_checkValidUntilForGssapi1), unit_test(test_checkValidUntilForGssapi2), unit_test(test_checkValidUntilForGssapi3), unit_test(test_checkValidUntilForGssapi4), unit_test(test_checkValidUntilForGssapi5), unit_test(test_checkValidUntilForGssapi6) #endif }; MemoryContextInit(); return run_tests(tests); }
rubikloud/gpdb
src/backend/libpq/test/auth_test.c
C
apache-2.0
3,458
/* Copyright 2019 The Knative 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 testing includes utilities for testing controllers. package testing import ( "errors" "sync" "time" "go.uber.org/atomic" "k8s.io/apimachinery/pkg/runtime" kubetesting "k8s.io/client-go/testing" ) // HookResult is the return value of hook functions. type HookResult bool const ( // HookComplete indicates the hook function completed, and WaitForHooks should // not wait for it. HookComplete HookResult = true // HookIncomplete indicates the hook function is incomplete, and WaitForHooks // should wait for it to complete. HookIncomplete HookResult = false ) /* CreateHookFunc is a function for handling a Create hook. Its runtime.Object parameter will be the Kubernetes resource created. The resource can be cast to its actual type like this: pod := obj.(*v1.Pod) A return value of true marks the hook as completed. Returning false allows the hook to run again when the next resource of the requested type is created. */ type CreateHookFunc func(runtime.Object) HookResult /* UpdateHookFunc is a function for handling an update hook. its runtime.Object parameter will be the Kubernetes resource updated. The resource can be cast to its actual type like this: pod := obj.(*v1.Pod) A return value of true marks the hook as completed. Returning false allows the hook to run again when the next resource of the requested type is updated. */ type UpdateHookFunc func(runtime.Object) HookResult /* DeleteHookFunc is a function for handling a delete hook. Its name parameter will be the name of the resource deleted. The resource itself is not available to the reactor. */ type DeleteHookFunc func(string) HookResult /* Hooks is a utility struct that simplifies controller testing with fake clients. A Hooks struct allows attaching hook functions to actions (create, update, delete) on a specified resource type within a fake client and ensuring that all hooks complete in a timely manner. */ type Hooks struct { completionCh chan int32 completionIndex *atomic.Int32 // Denotes whether or not the registered hooks should no longer be called // because they have already been waited upon. // This uses a Mutex over a channel to guarantee that after WaitForHooks // returns no hooked functions will be called. closed bool mutex sync.RWMutex } // NewHooks returns a Hooks struct that can be used to attach hooks to one or // more fake clients and wait for all hooks to complete. // TODO(grantr): Allow validating that a hook never fires func NewHooks() *Hooks { return &Hooks{ completionCh: make(chan int32, 100), completionIndex: atomic.NewInt32(-1), } } // OnCreate attaches a create hook to the given Fake. The hook function is // executed every time a resource of the given type is created. func (h *Hooks) OnCreate(fake *kubetesting.Fake, resource string, rf CreateHookFunc) { index := h.completionIndex.Inc() fake.PrependReactor("create", resource, func(a kubetesting.Action) (bool, runtime.Object, error) { obj := a.(kubetesting.CreateActionImpl).Object h.mutex.RLock() defer h.mutex.RUnlock() if !h.closed && rf(obj) == HookComplete { h.completionCh <- index } return false, nil, nil }) } // OnUpdate attaches an update hook to the given Fake. The hook function is // executed every time a resource of the given type is updated. func (h *Hooks) OnUpdate(fake *kubetesting.Fake, resource string, rf UpdateHookFunc) { index := h.completionIndex.Inc() fake.PrependReactor("update", resource, func(a kubetesting.Action) (bool, runtime.Object, error) { obj := a.(kubetesting.UpdateActionImpl).Object h.mutex.RLock() defer h.mutex.RUnlock() if !h.closed && rf(obj) == HookComplete { h.completionCh <- index } return false, nil, nil }) } // OnDelete attaches a delete hook to the given Fake. The hook function is // executed every time a resource of the given type is deleted. func (h *Hooks) OnDelete(fake *kubetesting.Fake, resource string, rf DeleteHookFunc) { index := h.completionIndex.Inc() fake.PrependReactor("delete", resource, func(a kubetesting.Action) (bool, runtime.Object, error) { name := a.(kubetesting.DeleteActionImpl).Name h.mutex.RLock() defer h.mutex.RUnlock() if !h.closed && rf(name) == HookComplete { h.completionCh <- index } return false, nil, nil }) } // WaitForHooks waits until all attached hooks have returned true at least once. // If the given timeout expires before that happens, an error is returned. // The registered actions will no longer be executed after WaitForHooks has // returned. func (h *Hooks) WaitForHooks(timeout time.Duration) error { defer func() { h.mutex.Lock() defer h.mutex.Unlock() h.closed = true }() ci := int(h.completionIndex.Load()) if ci == -1 { return nil } // Convert index to count. ci++ timer := time.After(timeout) hookCompletions := map[int32]HookResult{} for { select { case i := <-h.completionCh: hookCompletions[i] = HookComplete if len(hookCompletions) == ci { h.completionIndex.Dec() return nil } case <-timer: return errors.New("timed out waiting for hooks to complete") } } }
knative-sandbox/net-gateway-api
vendor/knative.dev/pkg/reconciler/testing/hooks.go
GO
apache-2.0
5,679
require 'cxxstdlib' require 'exceptions' require 'formula' require 'keg' require 'tab' require 'bottles' require 'caveats' require 'cleaner' require 'formula_cellar_checks' require 'install_renamed' require 'cmd/tap' require 'hooks/bottles' require 'debrew' class FormulaInstaller include FormulaCellarChecks def self.mode_attr_accessor(*names) attr_accessor(*names) private(*names) names.each do |name| predicate = "#{name}?" define_method(predicate) { !!send(name) } private(predicate) end end attr_reader :formula attr_accessor :options mode_attr_accessor :show_summary_heading, :show_header mode_attr_accessor :build_from_source, :build_bottle, :force_bottle mode_attr_accessor :ignore_deps, :only_deps, :interactive, :git mode_attr_accessor :verbose, :debug, :quieter def initialize(formula) @formula = formula @show_header = false @ignore_deps = false @only_deps = false @build_from_source = false @build_bottle = false @force_bottle = false @interactive = false @git = false @verbose = false @quieter = false @debug = false @options = Options.new @@attempted ||= Set.new @poured_bottle = false @pour_failed = false end def pour_bottle? install_bottle_options={:warn=>false} return true if Homebrew::Hooks::Bottles.formula_has_bottle?(formula) return false if @pour_failed bottle = formula.bottle return true if force_bottle? && bottle return false if build_from_source? || build_bottle? || interactive? return false unless options.empty? return true if formula.local_bottle_path return false unless bottle && formula.pour_bottle? unless bottle.compatible_cellar? if install_bottle_options[:warn] opoo "Building source; cellar of #{formula.name}'s bottle is #{bottle.cellar}" end return false end true end def install_bottle_for?(dep, build) return pour_bottle? if dep == formula return false if build_from_source? return false unless dep.bottle && dep.pour_bottle? return false unless build.used_options.empty? return false unless dep.bottle.compatible_cellar? return true end def prelude verify_deps_exist unless ignore_deps? lock check_install_sanity end def verify_deps_exist begin formula.recursive_dependencies.map(&:to_formula) rescue TapFormulaUnavailableError => e if Homebrew.install_tap(e.user, e.repo) retry else raise end end rescue FormulaUnavailableError => e e.dependent = formula.name raise end def check_install_sanity raise FormulaInstallationAlreadyAttemptedError, formula if @@attempted.include?(formula) unless ignore_deps? unlinked_deps = formula.recursive_dependencies.map(&:to_formula).select do |dep| dep.installed? and not dep.keg_only? and not dep.linked_keg.directory? end raise CannotInstallFormulaError, "You must `brew link #{unlinked_deps*' '}' before #{formula.name} can be installed" unless unlinked_deps.empty? end end def build_bottle_preinstall @etc_var_glob ||= "#{HOMEBREW_PREFIX}/{etc,var}/**/*" @etc_var_preinstall = Dir[@etc_var_glob] end def build_bottle_postinstall @etc_var_postinstall = Dir[@etc_var_glob] (@etc_var_postinstall - @etc_var_preinstall).each do |file| Pathname.new(file).cp_path_sub(HOMEBREW_PREFIX, formula.bottle_prefix) end end def install # not in initialize so upgrade can unlink the active keg before calling this # function but after instantiating this class so that it can avoid having to # relink the active keg if possible (because it is slow). if formula.linked_keg.directory? # some other version is already installed *and* linked raise CannotInstallFormulaError, <<-EOS.undent #{formula.name}-#{formula.linked_keg.resolved_path.basename} already installed To install this version, first `brew unlink #{formula.name}' EOS end check_conflicts compute_and_install_dependencies unless ignore_deps? return if only_deps? if build_bottle? && (arch = ARGV.bottle_arch) && !Hardware::CPU.optimization_flags.include?(arch) raise "Unrecognized architecture for --bottle-arch: #{arch}" end formula.deprecated_flags.each do |deprecated_option| old_flag = deprecated_option.old_flag new_flag = deprecated_option.current_flag opoo "#{formula.name}: #{old_flag} was deprecated; using #{new_flag} instead!" end oh1 "Installing #{Tty.green}#{formula.name}#{Tty.reset}" if show_header? @@attempted << formula if pour_bottle?(:warn => true) begin pour rescue => e raise if ARGV.homebrew_developer? @pour_failed = true onoe e.message opoo "Bottle installation failed: building from source." else @poured_bottle = true end end build_bottle_preinstall if build_bottle? unless @poured_bottle compute_and_install_dependencies if @pour_failed and not ignore_deps? build clean end build_bottle_postinstall if build_bottle? opoo "Nothing was installed to #{formula.prefix}" unless formula.installed? end def check_conflicts return if ARGV.force? conflicts = formula.conflicts.select do |c| f = Formulary.factory(c.name) f.linked_keg.exist? && f.opt_prefix.exist? end raise FormulaConflictError.new(formula, conflicts) unless conflicts.empty? end def compute_and_install_dependencies req_map, req_deps = expand_requirements check_requirements(req_map) deps = expand_dependencies(req_deps + formula.deps) if deps.empty? and only_deps? puts "All dependencies for #{formula.name} are satisfied." else install_dependencies(deps) end end def check_requirements(req_map) fatals = [] req_map.each_pair do |dependent, reqs| reqs.each do |req| puts "#{dependent}: #{req.message}" fatals << req if req.fatal? end end raise UnsatisfiedRequirements.new(fatals) unless fatals.empty? end def install_requirement_default_formula?(req, dependent, build) return false unless req.default_formula? return true unless req.satisfied? install_bottle_for?(dependent, build) || build_bottle? end def expand_requirements unsatisfied_reqs = Hash.new { |h, k| h[k] = [] } deps = [] formulae = [formula] while f = formulae.pop f.recursive_requirements do |dependent, req| build = effective_build_options_for(dependent) if (req.optional? || req.recommended?) && build.without?(req) Requirement.prune elsif req.build? && install_bottle_for?(dependent, build) Requirement.prune elsif install_requirement_default_formula?(req, dependent, build) dep = req.to_dependency deps.unshift(dep) formulae.unshift(dep.to_formula) Requirement.prune elsif req.satisfied? Requirement.prune else unsatisfied_reqs[dependent] << req end end end return unsatisfied_reqs, deps end def expand_dependencies(deps) inherited_options = {} expanded_deps = Dependency.expand(formula, deps) do |dependent, dep| options = inherited_options[dep.name] = inherited_options_for(dep) build = effective_build_options_for( dependent, inherited_options.fetch(dependent.name, []) ) if (dep.optional? || dep.recommended?) && build.without?(dep) Dependency.prune elsif dep.build? && install_bottle_for?(dependent, build) Dependency.prune elsif dep.satisfied?(options) Dependency.skip end end expanded_deps.map { |dep| [dep, inherited_options[dep.name]] } end def effective_build_options_for(dependent, inherited_options=[]) args = dependent.build.used_options args |= dependent == formula ? options : inherited_options args |= Tab.for_formula(dependent).used_options BuildOptions.new(args, dependent.options) end def inherited_options_for(dep) inherited_options = Options.new u = Option.new("universal") if (options.include?(u) || formula.require_universal_deps?) && !dep.build? && dep.to_formula.option_defined?(u) inherited_options << u end inherited_options end def install_dependencies(deps) if deps.length > 1 oh1 "Installing dependencies for #{formula.name}: #{Tty.green}#{deps.map(&:first)*", "}#{Tty.reset}" end deps.each { |dep, options| install_dependency(dep, options) } @show_header = true unless deps.empty? end class DependencyInstaller < FormulaInstaller def initialize(*) super @ignore_deps = true end def sanitized_ARGV_options args = super args.delete "--ignore-dependencies" args end end def install_dependency(dep, inherited_options) df = dep.to_formula tab = Tab.for_formula(df) if df.linked_keg.directory? linked_keg = Keg.new(df.linked_keg.resolved_path) linked_keg.unlink end if df.installed? installed_keg = Keg.new(df.prefix) tmp_keg = Pathname.new("#{installed_keg}.tmp") installed_keg.rename(tmp_keg) end fi = DependencyInstaller.new(df) fi.options |= tab.used_options fi.options |= dep.options fi.options |= inherited_options fi.build_from_source = build_from_source? fi.verbose = verbose? && !quieter? fi.debug = debug? fi.prelude oh1 "Installing #{formula.name} dependency: #{Tty.green}#{dep.name}#{Tty.reset}" fi.install fi.caveats fi.finish rescue Exception ignore_interrupts do tmp_keg.rename(installed_keg) if tmp_keg && !installed_keg.directory? linked_keg.link if linked_keg end raise else ignore_interrupts { tmp_keg.rmtree if tmp_keg && tmp_keg.directory? } end def caveats return if only_deps? audit_installed if ARGV.homebrew_developer? and not formula.keg_only? c = Caveats.new(formula) unless c.empty? @show_summary_heading = true ohai 'Caveats', c.caveats end end def finish return if only_deps? ohai 'Finishing up' if verbose? install_plist keg = Keg.new(formula.prefix) link(keg) fix_install_names(keg) if OS.mac? if build_bottle? && formula.post_install_defined? ohai "Not running post_install as we're building a bottle" puts "You can run it manually using `brew postinstall #{formula.name}`" else post_install end ohai "Summary" if verbose? or show_summary_heading? puts summary ensure unlock if hold_locks? end def emoji ENV['HOMEBREW_INSTALL_BADGE'] || "\xf0\x9f\x8d\xba" end def summary s = "" s << "#{emoji} " if MacOS.version >= :lion and not ENV['HOMEBREW_NO_EMOJI'] s << "#{formula.prefix}: #{formula.prefix.abv}" s << ", built in #{pretty_duration build_time}" if build_time s end def build_time @build_time ||= Time.now - @start_time if @start_time && !interactive? end def sanitized_ARGV_options args = [] args << "--ignore-dependencies" if ignore_deps? if build_bottle? args << "--build-bottle" args << "--bottle-arch=#{ARGV.bottle_arch}" if ARGV.bottle_arch end args << "--git" if git? args << "--interactive" if interactive? args << "--verbose" if verbose? args << "--debug" if debug? args << "--cc=#{ARGV.cc}" if ARGV.cc args << "--env=#{ARGV.env}" if ARGV.env if formula.head? args << "--HEAD" elsif formula.devel? args << "--devel" end formula.options.each do |opt| name = opt.name[/\A(.+)=\z$/, 1] value = ARGV.value(name) args << "--#{name}=#{value}" if name && value end args end def build_argv sanitized_ARGV_options + options.as_flags end def build FileUtils.rm Dir["#{HOMEBREW_LOGS}/#{formula.name}/*"] @start_time = Time.now # 1. formulae can modify ENV, so we must ensure that each # installation has a pristine ENV when it starts, forking now is # the easiest way to do this read, write = IO.pipe # I'm guessing this is not a good way to do this, but I'm no UNIX guru ENV['HOMEBREW_ERROR_PIPE'] = write.to_i.to_s args = %W[ nice #{RUBY_PATH} -W0 -I #{HOMEBREW_LIBRARY_PATH} -- #{HOMEBREW_LIBRARY_PATH}/build.rb #{formula.path} ].concat(build_argv) # Ruby 2.0+ sets close-on-exec on all file descriptors except for # 0, 1, and 2 by default, so we have to specify that we want the pipe # to remain open in the child process. args << { write => write } if RUBY_VERSION >= "2.0" pid = fork do begin read.close exec(*args) rescue Exception => e Marshal.dump(e, write) write.close exit! 1 end end ignore_interrupts(:quietly) do # the child will receive the interrupt and marshal it back write.close data = read.read read.close Process.wait(pid) raise Marshal.load(data) unless data.nil? or data.empty? raise Interrupt if $?.exitstatus == 130 raise "Suspicious installation failure" unless $?.success? end raise "Empty installation" if Dir["#{formula.prefix}/*"].empty? rescue Exception ignore_interrupts do # any exceptions must leave us with nothing installed formula.prefix.rmtree if formula.prefix.directory? formula.rack.rmdir_if_possible end raise end def link(keg) if formula.keg_only? begin keg.optlink rescue Keg::LinkError => e onoe "Failed to create #{formula.opt_prefix}" puts "Things that depend on #{formula.name} will probably not build." puts e Homebrew.failed = true end return end if keg.linked? opoo "This keg was marked linked already, continuing anyway" keg.remove_linked_keg_record end begin keg.link rescue Keg::ConflictError => e onoe "The `brew link` step did not complete successfully" puts "The formula built, but is not symlinked into #{HOMEBREW_PREFIX}" puts e puts puts "Possible conflicting files are:" mode = OpenStruct.new(:dry_run => true, :overwrite => true) keg.link(mode) @show_summary_heading = true Homebrew.failed = true rescue Keg::LinkError => e onoe "The `brew link` step did not complete successfully" puts "The formula built, but is not symlinked into #{HOMEBREW_PREFIX}" puts e puts puts "You can try again using:" puts " brew link #{formula.name}" @show_summary_heading = true Homebrew.failed = true rescue Exception => e onoe "An unexpected error occurred during the `brew link` step" puts "The formula built, but is not symlinked into #{HOMEBREW_PREFIX}" puts e puts e.backtrace if debug? @show_summary_heading = true ignore_interrupts { keg.unlink } Homebrew.failed = true raise end end def install_plist return unless formula.plist formula.plist_path.atomic_write(formula.plist) formula.plist_path.chmod 0644 rescue Exception => e onoe "Failed to install plist file" ohai e, e.backtrace if debug? Homebrew.failed = true end def fix_install_names(keg) keg.fix_install_names(:keg_only => formula.keg_only?) if @poured_bottle keg.relocate_install_names Keg::PREFIX_PLACEHOLDER, HOMEBREW_PREFIX.to_s, Keg::CELLAR_PLACEHOLDER, HOMEBREW_CELLAR.to_s, :keg_only => formula.keg_only? end rescue Exception => e onoe "Failed to fix install names" puts "The formula built, but you may encounter issues using it or linking other" puts "formula against it." ohai e, e.backtrace if debug? Homebrew.failed = true @show_summary_heading = true end def clean ohai "Cleaning" if verbose? Cleaner.new(formula).clean rescue Exception => e opoo "The cleaning step did not complete successfully" puts "Still, the installation was successful, so we will link it into your prefix" ohai e, e.backtrace if debug? Homebrew.failed = true @show_summary_heading = true end def post_install formula.run_post_install rescue Exception => e opoo "The post-install step did not complete successfully" puts "You can try again using `brew postinstall #{formula.name}`" ohai e, e.backtrace if debug? Homebrew.failed = true @show_summary_heading = true end def pour if Homebrew::Hooks::Bottles.formula_has_bottle?(formula) return if Homebrew::Hooks::Bottles.pour_formula_bottle(formula) end if formula.local_bottle_path downloader = LocalBottleDownloadStrategy.new(formula) else downloader = formula.bottle downloader.verify_download_integrity(downloader.fetch) end HOMEBREW_CELLAR.cd do downloader.stage end Pathname.glob("#{formula.bottle_prefix}/{etc,var}/**/*") do |path| path.extend(InstallRenamed) path.cp_path_sub(formula.bottle_prefix, HOMEBREW_PREFIX) end FileUtils.rm_rf formula.bottle_prefix CxxStdlib.check_compatibility( formula, formula.recursive_dependencies, Keg.new(formula.prefix), MacOS.default_compiler ) tab = Tab.for_keg(formula.prefix) tab.poured_from_bottle = true tab.write end def audit_check_output(output) if output opoo output @show_summary_heading = true end end def audit_installed audit_check_output(check_PATH(formula.bin)) audit_check_output(check_PATH(formula.sbin)) super end private def hold_locks? @hold_locks || false end def lock if (@@locked ||= []).empty? formula.recursive_dependencies.each do |dep| @@locked << dep.to_formula end unless ignore_deps? @@locked.unshift(formula) @@locked.uniq! @@locked.each(&:lock) @hold_locks = true end end def unlock if hold_locks? @@locked.each(&:unlock) @@locked.clear @hold_locks = false end end end class Formula def keg_only_text s = "This formula is keg-only, which means it was not symlinked into #{HOMEBREW_PREFIX}." s << "\n\n#{keg_only_reason.to_s}" if lib.directory? or include.directory? s << <<-EOS.undent_________________________________________________________72 Generally there are no consequences of this for you. If you build your own software and it requires this formula, you'll need to add to your build variables: EOS s << " LDFLAGS: -L#{opt_lib}\n" if lib.directory? s << " CPPFLAGS: -I#{opt_include}\n" if include.directory? end s << "\n" end end
dalguji/homebrew
Library/Homebrew/formula_installer.rb
Ruby
bsd-2-clause
19,071
<?php /** * * This file is part of the phpBB Forum Software package. * * @copyright (c) phpBB Limited <https://www.phpbb.com> * @license GNU General Public License, version 2 (GPL-2.0) * * For full copyright and license information, please see * the docs/CREDITS.txt file. * */ /** */ if (!defined('IN_PHPBB')) { exit; } // DEVELOPERS PLEASE NOTE // // All language files should use UTF-8 as their encoding and the files must not contain a BOM. // // Placeholders can now contain order information, e.g. instead of // 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows // translators to re-order the output of data while ensuring it remains correct // // You do not need this where single placeholders are used, e.g. 'Message %d' is fine // equally where a string contains only two placeholders which are used to wrap text // in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine $help = array( array( 0 => '--', 1 => 'Login and Registration Issues' ), array( 0 => 'Why do I need to register?', 1 => 'You may not have to, it is up to the administrator of the board as to whether you need to register in order to post messages. However; registration will give you access to additional features not available to guest users such as definable avatar images, private messaging, emailing of fellow users, usergroup subscription, etc. It only takes a few moments to register so it is recommended you do so.' ), array( 0 => 'What is COPPA?', 1 => 'COPPA, or the Children’s Online Privacy Protection Act of 1998, is a law in the United States requiring websites which can potentially collect information from minors under the age of 13 to have written parental consent or some other method of legal guardian acknowledgment, allowing the collection of personally identifiable information from a minor under the age of 13. If you are unsure if this applies to you as someone trying to register or to the website you are trying to register on, contact legal counsel for assistance. Please note that phpBB Limited and the owners of this board cannot provide legal advice and is not a point of contact for legal concerns of any kind, except as outlined in question “Who do I contact about abusive and/or legal matters related to this board?”.', ), array( 0 => 'Why can’t I register?', 1 => 'It is possible a board administrator has disabled registration to prevent new visitors from signing up. A board administrator could have also banned your IP address or disallowed the username you are attempting to register. Contact a board administrator for assistance.', ), array( 0 => 'I registered but cannot login!', 1 => 'First, check your username and password. If they are correct, then one of two things may have happened. If COPPA support is enabled and you specified being under 13 years old during registration, you will have to follow the instructions you received. Some boards will also require new registrations to be activated, either by yourself or by an administrator before you can logon; this information was present during registration. If you were sent an email, follow the instructions. If you did not receive an email, you may have provided an incorrect email address or the email may have been picked up by a spam filer. If you are sure the email address you provided is correct, try contacting an administrator.' ), array( 0 => 'Why can’t I login?', 1 => 'There are several reasons why this could occur. First, ensure your username and password are correct. If they are, contact a board administrator to make sure you haven’t been banned. It is also possible the website owner has a configuration error on their end, and they would need to fix it.', ), array( 0 => 'I registered in the past but cannot login any more?!', 1 => 'It is possible an administrator has deactivated or deleted your account for some reason. Also, many boards periodically remove users who have not posted for a long time to reduce the size of the database. If this has happened, try registering again and being more involved in discussions.' ), array( 0 => 'I’ve lost my password!', 1 => 'Don’t panic! While your password cannot be retrieved, it can easily be reset. Visit the login page and click <em>I forgot my password</em>. Follow the instructions and you should be able to log in again shortly.<br />However, if you are not able to reset your password, contact a board administrator.', ), array( 0 => 'Why do I get logged off automatically?', 1 => 'If you do not check the <em>Remember me</em> box when you login, the board will only keep you logged in for a preset time. This prevents misuse of your account by anyone else. To stay logged in, check the <em>Remember me</em> box during login. This is not recommended if you access the board from a shared computer, e.g. library, internet cafe, university computer lab, etc. If you do not see this checkbox, it means a board administrator has disabled this feature.', ), array( 0 => 'What does the “Delete all board cookies” do?', 1 => '“Delete all board cookies” deletes the cookies created by phpBB which keep you authenticated and logged into the board. Cookies also provide functions such as read tracking if they have been enabled by a board administrator. If you are having login or logout problems, deleting board cookies may help.', ), array( 0 => '--', 1 => 'User Preferences and settings' ), array( 0 => 'How do I change my settings?', 1 => 'If you are a registered user, all your settings are stored in the board database. To alter them, visit your User Control Panel; a link can usually be found by clicking on your username at the top of board pages. This system will allow you to change all your settings and preferences.', ), array( 0 => 'How do I prevent my username appearing in the online user listings?', 1 => 'Within your User Control Panel, under “Board preferences”, you will find the option <em>Hide your online status</em>. Enable this option and you will only appear to the administrators, moderators and yourself. You will be counted as a hidden user.' ), array( 0 => 'The times are not correct!', 1 => 'It is possible the time displayed is from a timezone different from the one you are in. If this is the case, visit your User Control Panel and change your timezone to match your particular area, e.g. London, Paris, New York, Sydney, etc. Please note that changing the timezone, like most settings, can only be done by registered users. If you are not registered, this is a good time to do so.' ), array( 0 => 'I changed the timezone and the time is still wrong!', 1 => 'If you are sure you have set the timezone correctly and the time is still incorrect, then the time stored on the server clock is incorrect. Please notify an administrator to correct the problem.' ), array( 0 => 'My language is not in the list!', 1 => 'Either the administrator has not installed your language or nobody has translated this board into your language. Try asking a board administrator if they can install the language pack you need. If the language pack does not exist, feel free to create a new translation. More information can be found at the <a href="https://www.phpbb.com/">phpBB</a>&reg; website.', ), array( 0 => 'What are the images next to my username?', 1 => 'There are two images which may appear along with a username when viewing posts. One of them may be an image associated with your rank, generally in the form of stars, blocks or dots, indicating how many posts you have made or your status on the board. Another, usually larger, image is known as an avatar and is generally unique or personal to each user.', ), array( 0 => 'How do I display an avatar?', 1 => 'Within your User Control Panel, under “Profile” you can add an avatar by using one of the four following methods: Gravatar, Gallery, Remote or Upload. It is up to the board administrator to enable avatars and to choose the way in which avatars can be made available. If you are unable to use avatars, contact a board administrator.', ), array( 0 => 'What is my rank and how do I change it?', 1 => 'Ranks, which appear below your username, indicate the number of posts you have made or identify certain users, e.g. moderators and administrators. In general, you cannot directly change the wording of any board ranks as they are set by the board administrator. Please do not abuse the board by posting unnecessarily just to increase your rank. Most boards will not tolerate this and the moderator or administrator will simply lower your post count.' ), array( 0 => 'When I click the email link for a user it asks me to login?', 1 => 'Only registered users can send email to other users via the built-in email form, and only if the administrator has enabled this feature. This is to prevent malicious use of the email system by anonymous users.' ), array( 0 => '--', 1 => 'Posting Issues' ), array( 0 => 'How do I create a new topic or post a reply?', 1 => 'To post a new topic in a forum, click "New Topic". To post a reply to a topic, click "Post Reply". You may need to register before you can post a message. A list of your permissions in each forum is available at the bottom of the forum and topic screens. Example: You can post new topics, You can post attachments, etc.', ), array( 0 => 'How do I edit or delete a post?', 1 => 'Unless you are a board administrator or moderator, you can only edit or delete your own posts. You can edit a post by clicking the edit button for the relevant post, sometimes for only a limited time after the post was made. If someone has already replied to the post, you will find a small piece of text output below the post when you return to the topic which lists the number of times you edited it along with the date and time. This will only appear if someone has made a reply; it will not appear if a moderator or administrator edited the post, though they may leave a note as to why they’ve edited the post at their own discretion. Please note that normal users cannot delete a post once someone has replied.' ), array( 0 => 'How do I add a signature to my post?', 1 => 'To add a signature to a post you must first create one via your User Control Panel. Once created, you can check the <em>Attach a signature</em> box on the posting form to add your signature. You can also add a signature by default to all your posts by checking the appropriate radio button in the User Control Panel. If you do so, you can still prevent a signature being added to individual posts by un-checking the add signature box within the posting form.' ), array( 0 => 'How do I create a poll?', 1 => 'When posting a new topic or editing the first post of a topic, click the “Poll creation” tab below the main posting form; if you cannot see this, you do not have appropriate permissions to create polls. Enter a title and at least two options in the appropriate fields, making sure each option is on a separate line in the textarea. You can also set the number of options users may select during voting under “Options per user”, a time limit in days for the poll (0 for infinite duration) and lastly the option to allow users to amend their votes.' ), array( 0 => 'Why can’t I add more poll options?', 1 => 'The limit for poll options is set by the board administrator. If you feel you need to add more options to your poll than the allowed amount, contact the board administrator.' ), array( 0 => 'How do I edit or delete a poll?', 1 => 'As with posts, polls can only be edited by the original poster, a moderator or an administrator. To edit a poll, click to edit the first post in the topic; this always has the poll associated with it. If no one has cast a vote, users can delete the poll or edit any poll option. However, if members have already placed votes, only moderators or administrators can edit or delete it. This prevents the poll’s options from being changed mid-way through a poll.' ), array( 0 => 'Why can’t I access a forum?', 1 => 'Some forums may be limited to certain users or groups. To view, read, post or perform another action you may need special permissions. Contact a moderator or board administrator to grant you access.' ), array( 0 => 'Why can’t I add attachments?', 1 => 'Attachment permissions are granted on a per forum, per group, or per user basis. The board administrator may not have allowed attachments to be added for the specific forum you are posting in, or perhaps only certain groups can post attachments. Contact the board administrator if you are unsure about why you are unable to add attachments.' ), array( 0 => 'Why did I receive a warning?', 1 => 'Each board administrator has their own set of rules for their site. If you have broken a rule, you may be issued a warning. Please note that this is the board administrator’s decision, and the phpBB Limited has nothing to do with the warnings on the given site. Contact the board administrator if you are unsure about why you were issued a warning.' ), array( 0 => 'How can I report posts to a moderator?', 1 => 'If the board administrator has allowed it, you should see a button for reporting posts next to the post you wish to report. Clicking this will walk you through the steps necessary to report the post.' ), array( 0 => 'What is the “Save” button for in topic posting?', 1 => 'This allows you to save drafts to be completed and submitted at a later date. To reload a saved draft, visit the User Control Panel.' ), array( 0 => 'Why does my post need to be approved?', 1 => 'The board administrator may have decided that posts in the forum you are posting to require review before submission. It is also possible that the administrator has placed you in a group of users whose posts require review before submission. Please contact the board administrator for further details.' ), array( 0 => 'How do I bump my topic?', 1 => 'By clicking the “Bump topic” link when you are viewing it, you can “bump” the topic to the top of the forum on the first page. However, if you do not see this, then topic bumping may be disabled or the time allowance between bumps has not yet been reached. It is also possible to bump the topic simply by replying to it, however, be sure to follow the board rules when doing so.' ), array( 0 => '--', 1 => 'Formatting and Topic Types' ), array( 0 => 'What is BBCode?', 1 => 'BBCode is a special implementation of HTML, offering great formatting control on particular objects in a post. The use of BBCode is granted by the administrator, but it can also be disabled on a per post basis from the posting form. BBCode itself is similar in style to HTML, but tags are enclosed in square brackets [ and ] rather than &lt; and &gt;. For more information on BBCode see the guide which can be accessed from the posting page.' ), array( 0 => 'Can I use HTML?', 1 => 'No. It is not possible to post HTML on this board and have it rendered as HTML. Most formatting which can be carried out using HTML can be applied using BBCode instead.' ), array( 0 => 'What are Smilies?', 1 => 'Smilies, or Emoticons, are small images which can be used to express a feeling using a short code, e.g. :) denotes happy, while :( denotes sad. The full list of emoticons can be seen in the posting form. Try not to overuse smilies, however, as they can quickly render a post unreadable and a moderator may edit them out or remove the post altogether. The board administrator may also have set a limit to the number of smilies you may use within a post.' ), array( 0 => 'Can I post images?', 1 => 'Yes, images can be shown in your posts. If the administrator has allowed attachments, you may be able to upload the image to the board. Otherwise, you must link to an image stored on a publicly accessible web server, e.g. http://www.example.com/my-picture.gif. You cannot link to pictures stored on your own PC (unless it is a publicly accessible server) nor images stored behind authentication mechanisms, e.g. hotmail or yahoo mailboxes, password protected sites, etc. To display the image use the BBCode [img] tag.' ), array( 0 => 'What are global announcements?', 1 => 'Global announcements contain important information and you should read them whenever possible. They will appear at the top of every forum and within your User Control Panel. Global announcement permissions are granted by the board administrator.' ), array( 0 => 'What are announcements?', 1 => 'Announcements often contain important information for the forum you are currently reading and you should read them whenever possible. Announcements appear at the top of every page in the forum to which they are posted. As with global announcements, announcement permissions are granted by the board administrator.' ), array( 0 => 'What are sticky topics?', 1 => 'Sticky topics within the forum appear below announcements and only on the first page. They are often quite important so you should read them whenever possible. As with announcements and global announcements, sticky topic permissions are granted by the board administrator.' ), array( 0 => 'What are locked topics?', 1 => 'Locked topics are topics where users can no longer reply and any poll it contained was automatically ended. Topics may be locked for many reasons and were set this way by either the forum moderator or board administrator. You may also be able to lock your own topics depending on the permissions you are granted by the board administrator.' ), array( 0 => 'What are topic icons?', 1 => 'Topic icons are author chosen images associated with posts to indicate their content. The ability to use topic icons depends on the permissions set by the board administrator.' ), // This block will switch the FAQ-Questions to the second template column array( 0 => '--', 1 => '--' ), array( 0 => '--', 1 => 'User Levels and Groups' ), array( 0 => 'What are Administrators?', 1 => 'Administrators are members assigned with the highest level of control over the entire board. These members can control all facets of board operation, including setting permissions, banning users, creating usergroups or moderators, etc., dependent upon the board founder and what permissions he or she has given the other administrators. They may also have full moderator capabilities in all forums, depending on the settings put forth by the board founder.' ), array( 0 => 'What are Moderators?', 1 => 'Moderators are individuals (or groups of individuals) who look after the forums from day to day. They have the authority to edit or delete posts and lock, unlock, move, delete and split topics in the forum they moderate. Generally, moderators are present to prevent users from going off-topic or posting abusive or offensive material.' ), array( 0 => 'What are usergroups?', 1 => 'Usergroups are groups of users that divide the community into manageable sections board administrators can work with. Each user can belong to several groups and each group can be assigned individual permissions. This provides an easy way for administrators to change permissions for many users at once, such as changing moderator permissions or granting users access to a private forum.' ), array( 0 => 'Where are the usergroups and how do I join one?', 1 => 'You can view all usergroups via the “Usergroups” link within your User Control Panel. If you would like to join one, proceed by clicking the appropriate button. Not all groups have open access, however. Some may require approval to join, some may be closed and some may even have hidden memberships. If the group is open, you can join it by clicking the appropriate button. If a group requires approval to join you may request to join by clicking the appropriate button. The user group leader will need to approve your request and may ask why you want to join the group. Please do not harass a group leader if they reject your request; they will have their reasons.' ), array( 0 => 'How do I become a usergroup leader?', 1 => 'A usergroup leader is usually assigned when usergroups are initially created by a board administrator. If you are interested in creating a usergroup, your first point of contact should be an administrator; try sending a private message.', ), array( 0 => 'Why do some usergroups appear in a different colour?', 1 => 'It is possible for the board administrator to assign a colour to the members of a usergroup to make it easy to identify the members of this group.' ), array( 0 => 'What is a “Default usergroup”?', 1 => 'If you are a member of more than one usergroup, your default is used to determine which group colour and group rank should be shown for you by default. The board administrator may grant you permission to change your default usergroup via your User Control Panel.' ), array( 0 => 'What is “The team” link?', 1 => 'This page provides you with a list of board staff, including board administrators and moderators and other details such as the forums they moderate.' ), array( 0 => '--', 1 => 'Private Messaging' ), array( 0 => 'I cannot send private messages!', 1 => 'There are three reasons for this; you are not registered and/or not logged on, the board administrator has disabled private messaging for the entire board, or the board administrator has prevented you from sending messages. Contact a board administrator for more information.' ), array( 0 => 'I keep getting unwanted private messages!', 1 => 'You can automatically delete private messages from a user by using message rules within your User Control Panel. If you are receiving abusive private messages from a particular user, report the messages to the moderators; they have the power to prevent a user from sending private messages.' ), array( 0 => 'I have received a spamming or abusive email from someone on this board!', 1 => 'We are sorry to hear that. The email form feature of this board includes safeguards to try and track users who send such posts, so email the board administrator with a full copy of the email you received. It is very important that this includes the headers that contain the details of the user that sent the email. The board administrator can then take action.' ), array( 0 => '--', 1 => 'Friends and Foes' ), array( 0 => 'What are my Friends and Foes lists?', 1 => 'You can use these lists to organise other members of the board. Members added to your friends list will be listed within your User Control Panel for quick access to see their online status and to send them private messages. Subject to template support, posts from these users may also be highlighted. If you add a user to your foes list, any posts they make will be hidden by default.' ), array( 0 => 'How can I add / remove users to my Friends or Foes list?', 1 => 'You can add users to your list in two ways. Within each user’s profile, there is a link to add them to either your Friend or Foe list. Alternatively, from your User Control Panel, you can directly add users by entering their member name. You may also remove users from your list using the same page.' ), array( 0 => '--', 1 => 'Searching the Forums' ), array( 0 => 'How can I search a forum or forums?', 1 => 'Enter a search term in the search box located on the index, forum or topic pages. Advanced search can be accessed by clicking the “Advance Search” link which is available on all pages on the forum. How to access the search may depend on the style used.' ), array( 0 => 'Why does my search return no results?', 1 => 'Your search was probably too vague and included many common terms which are not indexed by phpBB. Be more specific and use the options available within Advanced search.', ), array( 0 => 'Why does my search return a blank page!?', 1 => 'Your search returned too many results for the webserver to handle. Use “Advanced search” and be more specific in the terms used and forums that are to be searched.' ), array( 0 => 'How do I search for members?', 1 => 'Visit to the “Members” page and click the “Find a member” link.' ), array( 0 => 'How can I find my own posts and topics?', 1 => 'Your own posts can be retrieved either by clicking the “Show your posts” link within the User Control Panel or by clicking the “Search user’s posts” link via your own profile page or by clicking the “Quick links” menu at the top of the board. To search for your topics, use the Advanced search page and fill in the various options appropriately.', ), array( 0 => '--', 1 => 'Subscriptions and Bookmarks', ), array( 0 => 'What is the difference between bookmarking and subscribing?', 1 => 'In phpBB 3.0, bookmarking topics worked much like bookmarking in a web browser. You were not alerted when there was an update. As of phpBB 3.1, bookmarking is more like subscribing to a topic. You can be notified when a bookmarked topic is updated. Subscribing, however, will notify you when there is an update to a topic or forum on the board. Notification options for bookmarks and subscriptions can be configured in the User Control Panel, under “Board preferences”.', ), array( 0 => 'How do I bookmark or subscribe to specific topics?', 1 => 'You can bookmark or subscribe to a specific topic by clicking the appropriate link in the “Topic tools” menu, conveniently located near the top and bottom of a topic discussion.<br />Replying to a topic with the “Notify me when a reply is posted” option checked will also subscribe you to the topic.', ), array( 0 => 'How do I subscribe to specific forums?', 1 => 'To subscribe to a specific forum, click the “Subscribe forum” link, at the bottom of page, upon entering the forum.', ), array( 0 => 'How do I remove my subscriptions?', 1 => 'To remove your subscriptions, go to your User Control Panel and follow the links to your subscriptions.' ), array( 0 => '--', 1 => 'Attachments' ), array( 0 => 'What attachments are allowed on this board?', 1 => 'Each board administrator can allow or disallow certain attachment types. If you are unsure what is allowed to be uploaded, contact the board administrator for assistance.' ), array( 0 => 'How do I find all my attachments?', 1 => 'To find your list of attachments that you have uploaded, go to your User Control Panel and follow the links to the attachments section.' ), array( 0 => '--', 1 => 'phpBB Issues', ), array( 0 => 'Who wrote this bulletin board?', 1 => 'This software (in its unmodified form) is produced, released and is copyright <a href="https://www.phpbb.com/">phpBB Limited</a>. It is made available under the GNU General Public License, version 2 (GPL-2.0) and may be freely distributed. See <a href="https://www.phpbb.com/about/">About phpBB</a> for more details.', ), array( 0 => 'Why isn’t X feature available?', 1 => 'This software was written by and licensed through phpBB Limited. If you believe a feature needs to be added please visit the <a href="https://www.phpbb.com/ideas/">phpBB Ideas Centre</a>, where you can upvote existing ideas or suggest new features.' ), array( 0 => 'Who do I contact about abusive and/or legal matters related to this board?', 1 => 'Any of the administrators listed on the “The team” page should be an appropriate point of contact for your complaints. If this still gets no response then you should contact the owner of the domain (do a <a href="http://www.google.com/search?q=whois">whois lookup</a>) or, if this is running on a free service (e.g. Yahoo!, free.fr, f2s.com, etc.), the management or abuse department of that service. Please note that the phpBB Limited has <strong>absolutely no jurisdiction</strong> and cannot in any way be held liable over how, where or by whom this board is used. Do not contact the phpBB Limited in relation to any legal (cease and desist, liable, defamatory comment, etc.) matter <strong>not directly related</strong> to the phpBB.com website or the discrete software of phpBB itself. If you do email phpBB Limited <strong>about any third party</strong> use of this software then you should expect a terse response or no response at all.' ), array( 0 => 'How do I contact a board administrator?', 1 => 'All users of the board can use the “Contact us” form, if the option was enabled by the board administrator.<br />Members of the board can also use the “The team” link.', ), );
kivi8/ars-poetica
www/forum/language/en/help_faq.php
PHP
bsd-3-clause
28,732
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>CSS Grid Layout Test: parsing grid-area with valid values</title> <link rel="author" title="Eric Willigers" href="mailto:ericwilligers@chromium.org"> <link rel="help" href="https://drafts.csswg.org/css-grid-1/#propdef-grid-area"> <meta name="assert" content="grid-area supports the full grammar '<grid-line> [ / <grid-line> ]{0,3}'."> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/css/support/parsing-testcommon.js"></script> </head> <body> <script> // auto test_valid_value("grid-area", "auto"); test_valid_value("grid-area", "auto / auto", "auto"); test_valid_value("grid-area", "auto / auto / auto", "auto"); test_valid_value("grid-area", "auto / auto / auto / auto", "auto"); test_valid_value("grid-area", "AuTo", "auto"); test_valid_value("grid-row", "auto"); test_valid_value("grid-row", "auto/auto", "auto"); test_valid_value("grid-column-end", "AuTo", "auto"); // <custom-ident> test_valid_value("grid-area", "--a"); test_valid_value("grid-row", "-zπ"); test_valid_value("grid-row", "-zπ/-zπ", "-zπ"); test_valid_value("grid-row", "i / i", "i"); test_valid_value("grid-row-start", "AZ"); test_valid_value("grid-column-start", "-_π"); test_valid_value("grid-row-end", "_9"); // <integer> && <custom-ident>? test_valid_value("grid-area", "1"); test_valid_value("grid-area", "+90 -a-", "90 -a-"); test_valid_value("grid-row", "az 2", "2 az"); test_valid_value("grid-column", "9"); test_valid_value("grid-column", "-19 zA"); test_valid_value("grid-column", "-A0 33", "33 -A0"); test_valid_value("grid-row-start", "-19"); test_valid_value("grid-row-start", "9 -Z_"); test_valid_value("grid-column-start", "+90", "90"); test_valid_value("grid-column-start", "Z -44", "-44 Z"); test_valid_value("grid-row-end", "1 -πA"); test_valid_value("grid-column-end", "π_ +5", "5 π_"); // span && [ <integer> || <custom-ident> ] test_valid_value("grid-area", "span 2 i"); test_valid_value("grid-area", "i 2 SpAn", "span 2 i"); test_valid_value("grid-row", "span 2"); test_valid_value("grid-column", "i SpAn", "span i"); test_valid_value("grid-row-start", "span i"); test_valid_value("grid-column-start", "SpAn i 2", "span 2 i"); test_valid_value("grid-row-end", "2 i span", "span 2 i"); test_valid_value("grid-column-end", "2 SpAn", "span 2"); // <grid-line> [ / <grid-line> ]{0,3} test_valid_value("grid-area", "auto / i"); test_valid_value("grid-area", "auto / i / auto / i", "auto / i"); test_valid_value("grid-area", "auto / i / auto / 2 i"); test_valid_value("grid-area", "1 / i / auto / i", "1 / i"); test_valid_value("grid-area", "1 / auto / auto / auto", "1"); test_valid_value("grid-area", "1 / auto / i / auto", "1 / auto / i"); test_valid_value("grid-area", "1 / j / i / k"); test_valid_value("grid-area", "1 / auto / 2 / auto", "1 / auto / 2"); test_valid_value("grid-area", "1 / i / 2 / auto"); test_valid_value("grid-area", "i / i / auto / auto"); test_valid_value("grid-area", "i / auto / i / auto", "i / auto"); test_valid_value("grid-area", "auto / i / 2 j"); test_valid_value("grid-area", "auto / i / 2 j / span 3 k"); test_valid_value("grid-row", "auto / i"); test_valid_value("grid-row", "i / auto"); test_valid_value("grid-row", "2 i / auto", "2 i"); test_valid_value("grid-row", "1 / auto", "1"); test_valid_value("grid-column", "2 j / span 3 k"); // https://github.com/w3c/csswg-drafts/issues/2858 // '\\31 st' in Blink, Firefox, EdgeHTML and Safari serialize invalid values. test_valid_value("grid-column-end", "\\31st", ["\\31 st", "\\31st"]); test_valid_value("grid-column-end", "\\31 st", ["\\31 st", "\\31st"]); test_valid_value("grid-column", "\\31st / \\31 st", ["\\31 st", "\\31st"]); </script> </body> </html>
scheib/chromium
third_party/blink/web_tests/external/wpt/css/css-grid/parsing/grid-area-valid.html
HTML
bsd-3-clause
3,782
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Scrolling Logo/Thumbnail Slider Demo - Jssor Slider, Carousel, Slideshow with Javascript Source Code</title> </head> <body style="font-family:Arial, Verdana;background-color:#fff;"> <!-- use jssor.slider.min.js instead for release --> <!-- jssor.slider.min.js = (jssor.js + jssor.slider.js) --> <script type="text/javascript" src="../js/jssor.js"></script> <script type="text/javascript" src="../js/jssor.slider.js"></script> <script> jssor_slider1_starter = function (containerId) { var options = { $AutoPlay: true, //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false $AutoPlaySteps: 1, //[Optional] Steps to go for each navigation request (this options applys only when slideshow disabled), the default value is 1 $AutoPlayInterval: 0, //[Optional] Interval (in milliseconds) to go for next slide since the previous stopped if the slider is auto playing, default value is 3000 $PauseOnHover: 4, //[Optional] Whether to pause when mouse over if a slider is auto playing, 0 no pause, 1 pause for desktop, 2 pause for touch device, 3 pause for desktop and touch device, 4 freeze for desktop, 8 freeze for touch device, 12 freeze for desktop and touch device, default value is 1 $ArrowKeyNavigation: true, //[Optional] Allows keyboard (arrow key) navigation or not, default value is false $SlideEasing: $JssorEasing$.$EaseLinear, //[Optional] Specifies easing for right to left animation, default value is $JssorEasing$.$EaseOutQuad $SlideDuration: 1600, //[Optional] Specifies default duration (swipe) for slide in milliseconds, default value is 500 $MinDragOffsetToSlide: 20, //[Optional] Minimum drag offset to trigger slide , default value is 20 $SlideWidth: 140, //[Optional] Width of every slide in pixels, default value is width of 'slides' container //$SlideHeight: 100, //[Optional] Height of every slide in pixels, default value is height of 'slides' container $SlideSpacing: 0, //[Optional] Space between each slide in pixels, default value is 0 $DisplayPieces: 7, //[Optional] Number of pieces to display (the slideshow would be disabled if the value is set to greater than 1), the default value is 1 $ParkingPosition: 0, //[Optional] The offset position to park slide (this options applys only when slideshow disabled), default value is 0. $UISearchMode: 1, //[Optional] The way (0 parellel, 1 recursive, default value is 1) to search UI components (slides container, loading screen, navigator container, arrow navigator container, thumbnail navigator container etc). $PlayOrientation: 1, //[Optional] Orientation to play slide (for auto play, navigation), 1 horizental, 2 vertical, 5 horizental reverse, 6 vertical reverse, default value is 1 $DragOrientation: 1 //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0) }; var jssor_slider1 = new $JssorSlider$(containerId, options); //responsive code begin //you can remove responsive code if you don't want the slider scales while window resizes function ScaleSlider() { var parentWidth = jssor_slider1.$Elmt.parentNode.clientWidth; if (parentWidth) jssor_slider1.$ScaleWidth(Math.min(parentWidth, 980)); else $Jssor$.$Delay(ScaleSlider, 30); } ScaleSlider(); $Jssor$.$AddEvent(window, "load", ScaleSlider); $Jssor$.$AddEvent(window, "resize", $Jssor$.$WindowResizeFilter(window, ScaleSlider)); $Jssor$.$AddEvent(window, "orientationchange", ScaleSlider); //responsive code end }; </script> <!-- Jssor Slider Begin --> <!-- To move inline styles to css file/block, please specify a class name for each element. --> <div id="slider1_container" style="position: relative; top: 0px; left: 0px; width: 980px; height: 100px; overflow: hidden; "> <!-- Loading Screen --> <div u="loading" style="position: absolute; top: 0px; left: 0px;"> <div style="filter: alpha(opacity=70); opacity:0.7; position: absolute; display: block; background-color: #000; top: 0px; left: 0px;width: 100%;height:100%;"> </div> <div style="position: absolute; display: block; background: url(../img/loading.gif) no-repeat center center; top: 0px; left: 0px;width: 100%;height:100%;"> </div> </div> <!-- Slides Container --> <div u="slides" style="cursor: move; position: absolute; left: 0px; top: 0px; width: 980px; height: 100px; overflow: hidden;"> <div><img u="image" alt="amazon" src="../img/logo/amazon.jpg" /></div> <div><img u="image" alt="android" src="../img/logo/android.jpg" /></div> <div><img u="image" alt="bitly" src="../img/logo/bitly.jpg" /></div> <div><img u="image" alt="blogger" src="../img/logo/blogger.jpg" /></div> <div><img u="image" alt="dnn" src="../img/logo/dnn.jpg" /></div> <div><img u="image" alt="drupal" src="../img/logo/drupal.jpg" /></div> <div><img u="image" alt="ebay" src="../img/logo/ebay.jpg" /></div> <div><img u="image" alt="facebook" src="../img/logo/facebook.jpg" /></div> <div><img u="image" alt="google" src="../img/logo/google.jpg" /></div> <div><img u="image" alt="ibm" src="../img/logo/ibm.jpg" /></div> <div><img u="image" alt="ios" src="../img/logo/ios.jpg" /></div> <div><img u="image" alt="joomla" src="../img/logo/joomla.jpg" /></div> <div><img u="image" alt="linkedin" src="../img/logo/linkedin.jpg" /></div> <div><img u="image" alt="mac" src="../img/logo/mac.jpg" /></div> <div><img u="image" alt="magento" src="../img/logo/magento.jpg" /></div> <div><img u="image" alt="pinterest" src="../img/logo/pinterest.jpg" /></div> <div><img u="image" alt="samsung" src="../img/logo/samsung.jpg" /></div> <div><img u="image" alt="twitter" src="../img/logo/twitter.jpg" /></div> <div><img u="image" alt="windows" src="../img/logo/windows.jpg" /></div> <div><img u="image" alt="wordpress" src="../img/logo/wordpress.jpg" /></div> <div><img u="image" alt="youtube" src="../img/logo/youtube.jpg" /></div> </div> <a style="display: none" href="http://www.jssor.com">Image Slider</a> <!-- Trigger --> <script> jssor_slider1_starter('slider1_container'); </script> </div> <!-- Jssor Slider End --> </body> </html>
bhdm/wzc
src/Wzc/MainBundle/Resources/public/JssorSlider/demos-no-jquery/scrolling-logo-thumbnail-slider.source.html
HTML
mit
7,712
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Snapping & Splitting</title> <link rel="stylesheet" href="../theme/default/style.css" type="text/css" /> <link rel="stylesheet" href="style.css" type="text/css" /> <style type="text/css"> .olControlEditingToolbar .olControlModifyFeatureItemInactive { background-position: -1px 0px ; } .olControlEditingToolbar .olControlModifyFeatureItemActive { background-position: -1px -23px ; } label.head { font-weight: bold; padding: 1em 0 0.1em 0; border-bottom: 1px solid grey; } td { padding: 0.25em 1em; } tr.head td { text-align: center; font-weight: bold; } </style> <script src="../lib/Firebug/firebug.js"></script> <script src="../lib/OpenLayers.js"></script> <script type="text/javascript"> OpenLayers.Feature.Vector.style['default']['strokeWidth'] = '2'; function init() { initMap(); initUI(); } var map, draw, modify, snap, split, vectors; function initMap() { map = new OpenLayers.Map('map'); var styles = new OpenLayers.StyleMap({ "default": new OpenLayers.Style(null, { rules: [ new OpenLayers.Rule({ symbolizer: { "Point": { pointRadius: 5, graphicName: "square", fillColor: "white", fillOpacity: 0.25, strokeWidth: 1, strokeOpacity: 1, strokeColor: "#333333" }, "Line": { strokeWidth: 3, strokeOpacity: 1, strokeColor: "#666666" } } }) ] }), "select": new OpenLayers.Style({ strokeColor: "#00ccff", strokeWidth: 4 }), "temporary": new OpenLayers.Style(null, { rules: [ new OpenLayers.Rule({ symbolizer: { "Point": { pointRadius: 5, graphicName: "square", fillColor: "white", fillOpacity: 0.25, strokeWidth: 1, strokeOpacity: 1, strokeColor: "#333333" }, "Line": { strokeWidth: 3, strokeOpacity: 1, strokeColor: "#00ccff" } } }) ] }) }); // create three vector layers vectors = new OpenLayers.Layer.Vector("Lines", { isBaseLayer: true, strategies: [new OpenLayers.Strategy.Fixed()], protocol: new OpenLayers.Protocol.HTTP({ url: "data/roads.json", format: new OpenLayers.Format.GeoJSON() }), styleMap: styles, maxExtent: new OpenLayers.Bounds( 1549471.9221, 6403610.94, 1550001.32545, 6404015.8 ) }); map.addLayer(vectors); // configure the snapping agent snap = new OpenLayers.Control.Snapping({layer: vectors}); map.addControl(snap); snap.activate(); // configure split agent split = new OpenLayers.Control.Split({ layer: vectors, source: vectors, tolerance: 0.0001, eventListeners: { aftersplit: function(event) { flashFeatures(event.features); } } }); map.addControl(split); split.activate(); // add some editing tools to a panel var panel = new OpenLayers.Control.Panel({ displayClass: "olControlEditingToolbar" }); draw = new OpenLayers.Control.DrawFeature( vectors, OpenLayers.Handler.Path, {displayClass: "olControlDrawFeaturePoint", title: "Draw Features"} ); modify = new OpenLayers.Control.ModifyFeature( vectors, {displayClass: "olControlModifyFeature", title: "Modify Features"} ); panel.addControls([ new OpenLayers.Control.Navigation({title: "Navigate"}), draw, modify ]); map.addControl(panel); map.addControl(new OpenLayers.Control.MousePosition()); map.zoomToMaxExtent(); } function flashFeatures(features, index) { if(!index) { index = 0; } var current = features[index]; if(current && current.layer === vectors) { vectors.drawFeature(features[index], "select"); } var prev = features[index-1]; if(prev && prev.layer === vectors) { vectors.drawFeature(prev, "default"); } ++index; if(index <= features.length) { window.setTimeout(function() {flashFeatures(features, index)}, 75); } } /** * Add behavior to page elements. This basically lets us set snapping * target properties with the checkboxes and text inputs. The checkboxes * toggle the target node, vertex, or edge (boolean) values. The * text inputs set the nodeTolerance, vertexTolerance, or edgeTolerance * property values. */ function initUI() { // add behavior to snap elements var snapCheck = $("snap_toggle"); snapCheck.checked = true; snapCheck.onclick = function() { if(snapCheck.checked) { snap.activate(); $("snap_options").style.display = "block"; } else { snap.deactivate(); $("snap_options").style.display = "none"; } }; var target, type, tog, tol; var types = ["node", "vertex", "edge"]; var target = snap.targets[0]; for(var j=0; j<types.length; ++j) { type = types[j]; tog = $("target_" + type); tog.checked = target[type]; tog.onclick = (function(tog, type, target) { return function() {target[type] = tog.checked;} })(tog, type, target); tol = $("target_" + type + "Tolerance"); tol.value = target[type + "Tolerance"]; tol.onchange = (function(tol, type, target) { return function() { target[type + "Tolerance"] = Number(tol.value) || 0; } })(tol, type, target); } // add behavior to split elements var splitCheck = $("split_toggle"); splitCheck.checked = true; splitCheck.onclick = function() { if(splitCheck.checked) { split.activate(); $("split_options").style.display = "block"; } else { split.deactivate(); $("split_options").style.display = "none"; } }; var edgeCheck = $("edge_toggle"); edgeCheck.checked = split.edge; edgeCheck.onclick = function() { split.edge = edgeCheck.checked; }; $("clear").onclick = function() { modify.deactivate(); vectors.destroyFeatures(); }; } </script> </head> <body onload="init()"> <h1 id="title">Snapping & Splitting Example</h1> <div id="shortdesc">A demonstration snapping and splitting while editing vector features.</div> <div id="map" class="smallmap"></div> <br/> <input type="checkbox" id="snap_toggle" /> <label for="snap_toggle" class="head">Enable Snapping</label> <table id="snap_options"> <tbody> <tr class="head"> <td>target</td><td>node</td><td>vertex</td><td>edge</td> </tr> <tr> <td>roads</td> <td><input type="checkbox" id="target_node" /><input id="target_nodeTolerance" type="text" size="3" /></td> <td><input type="checkbox" id="target_vertex" /><input id="target_vertexTolerance" type="text" size="3" /></td> <td><input type="checkbox" id="target_edge" /><input id="target_edgeTolerance" type="text" size="3" /></td> </tr> </tbody> </table> <br /> <input type="checkbox" id="split_toggle" /> <label for="split_toggle" class="head">Enable Splitting</label> <table id="split_options"> <tbody> <tr> <td><label for="edge_toggle">edges split</label></td> <td><input type="checkbox" id="edge_toggle" /></td> </tr> </tbody> </table> <br /> <button id="clear">clear</button> Clear all features. </body> </html>
spatindsaongo/geos
web/js/openlayers/examples/snap-split.html
HTML
mit
10,359
/******************************************************************************* * Copyright 2018 Intel 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. *******************************************************************************/ #include "jit_generator.hpp" #include "common.hpp" namespace mkldnn { namespace impl { namespace cpu { jit_avx512_core_u8_copy_sum_at_kern::jit_avx512_core_u8_copy_sum_at_kern(): jit_generator(nullptr, GEMM_CODE_SIZE) { #ifndef _WIN32 #define M rdi #define N rsi #define A rdx #define LDA rcx #define ALPHA r8 #define B r9 #define I rax #define A1 r10 #define A2 r8 #define LDA3 r11 #define ARG_BIAS 24+stacksize+rsp #else #define M rcx #define N rdx #define A r8 #define LDA r9 #define ALPHA rax #define B rdi #define I rax #define A1 rsi #define A2 r10 #define LDA3 r11 #define ARG_ALPHA 40+stacksize+rsp #define ARG_B 48+stacksize+rsp #define ARG_BIAS 72+stacksize+rsp #endif inLocalLabel(); { Xbyak::Label l1750; Xbyak::Label l1b6c; Xbyak::Label l1e14; Xbyak::Label l20; Xbyak::Label l2068; Xbyak::Label l226c; Xbyak::Label l22b8; Xbyak::Label l22c4; Xbyak::Label l22f4; Xbyak::Label l26b4; Xbyak::Label l28cc; Xbyak::Label l2a2c; Xbyak::Label l2b5c; Xbyak::Label l2c64; Xbyak::Label l2c94; Xbyak::Label l2ca0; Xbyak::Label l2cc8; Xbyak::Label l2eac; Xbyak::Label l2fc0; Xbyak::Label l3078; Xbyak::Label l3118; Xbyak::Label l319c; Xbyak::Label l31c0; Xbyak::Label l31cc; Xbyak::Label l31ec; Xbyak::Label l32e4; Xbyak::Label l3378; Xbyak::Label l33dc; Xbyak::Label l3434; Xbyak::Label l347c; Xbyak::Label l349c; Xbyak::Label l34a8; Xbyak::Label l34c8; Xbyak::Label l3558; Xbyak::Label l35b0; Xbyak::Label l35f4; Xbyak::Label l3638; Xbyak::Label l366c; Xbyak::Label l368a; Xbyak::Label l3694; Xbyak::Label l36a8; Xbyak::Label l36ec; Xbyak::Label l3728; Xbyak::Label l3760; Xbyak::Label l3794; Xbyak::Label l37b8; Xbyak::Label l37d8; Xbyak::Label l5cc; Xbyak::Label l6c; Xbyak::Label l968; Xbyak::Label lc80; Xbyak::Label lf1c; Xbyak::Label lf64; Xbyak::Label lf70; Xbyak::Label lfb4; preamble(); auto stacksize = get_size_of_abi_save_regs(); #ifdef _WIN32 mov(ALPHA, ptr[ARG_ALPHA]); mov(B, ptr[ARG_B]); #endif mov(N, qword[N]); mov(M, qword[M]); mov(LDA, qword[LDA]); sub(A, -128); sub(B, -128); lea(LDA3, ptr[LDA+LDA*2]); cmp(N, 0x30); jl(lf64, T_NEAR); align(4); L(l20); mov(A1, A); mov(I, LDA); shl(I, 0x5); lea(I, ptr[I+LDA*8]); lea(I, ptr[I+LDA*8]); add(A, I); vxorps(ymm8, ymm8, ymm8); vxorps(ymm9, ymm9, ymm9); vxorps(ymm10, ymm10, ymm10); vxorps(ymm11, ymm11, ymm11); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(I, M); sar(I, 0x3); jle(l5cc, T_NEAR); align(4); L(l6c); vmovq(xmm0, qword[A1-0x80]); vmovq(xmm1, qword[A1+LDA*1-0x80]); vmovq(xmm2, qword[A1+LDA*2-0x80]); vmovq(xmm3, qword[A1+LDA3*1-0x80]); lea(A2, ptr[A1+LDA*4]); vpunpckldq(xmm1, xmm0, xmm1); vpunpckldq(xmm3, xmm2, xmm3); vpunpcklqdq(xmm0, xmm1, xmm3); vpunpckhqdq(xmm1, xmm1, xmm3); vmovdqu(xword[B-0x80], xmm0); vmovdqu(xword[B+0x40], xmm1); vmovq(xmm2, qword[A2-0x80]); vmovq(xmm3, qword[A2+LDA*1-0x80]); vmovq(xmm4, qword[A2+LDA*2-0x80]); vmovq(xmm5, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm3, xmm2, xmm3); vpunpckldq(xmm5, xmm4, xmm5); vpunpcklqdq(xmm2, xmm3, xmm5); vpunpckhqdq(xmm3, xmm3, xmm5); vmovdqu(xword[B-0x70], xmm2); vmovdqu(xword[B+0x50], xmm3); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm2); vmovhlps(xmm7, xmm2, xmm2); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm8, ymm8, ymm5); vpmovsxbw(ymm5, xmm1); vmovhlps(xmm6, xmm1, xmm1); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm3); vmovhlps(xmm7, xmm3, xmm3); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm8, ymm8, ymm5); vmovq(xmm0, qword[A2-0x80]); vmovq(xmm1, qword[A2+LDA*1-0x80]); vmovq(xmm2, qword[A2+LDA*2-0x80]); vmovq(xmm3, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm1, xmm0, xmm1); vpunpckldq(xmm3, xmm2, xmm3); vpunpcklqdq(xmm0, xmm1, xmm3); vpunpckhqdq(xmm1, xmm1, xmm3); vmovdqu(xword[B-0x60], xmm0); vmovdqu(xword[B+0x60], xmm1); vmovq(xmm2, qword[A2-0x80]); vmovq(xmm3, qword[A2+LDA*1-0x80]); vmovq(xmm4, qword[A2+LDA*2-0x80]); vmovq(xmm5, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm3, xmm2, xmm3); vpunpckldq(xmm5, xmm4, xmm5); vpunpcklqdq(xmm2, xmm3, xmm5); vpunpckhqdq(xmm3, xmm3, xmm5); vmovdqu(xword[B-0x50], xmm2); vmovdqu(xword[B+0x70], xmm3); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm2); vmovhlps(xmm7, xmm2, xmm2); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm9, ymm9, ymm5); vpmovsxbw(ymm5, xmm1); vmovhlps(xmm6, xmm1, xmm1); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm3); vmovhlps(xmm7, xmm3, xmm3); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm9, ymm9, ymm5); vmovq(xmm0, qword[A2-0x80]); vmovq(xmm1, qword[A2+LDA*1-0x80]); vmovq(xmm2, qword[A2+LDA*2-0x80]); vmovq(xmm3, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm1, xmm0, xmm1); vpunpckldq(xmm3, xmm2, xmm3); vpunpcklqdq(xmm0, xmm1, xmm3); vpunpckhqdq(xmm1, xmm1, xmm3); vmovdqu(xword[B-0x40], xmm0); vmovdqu(xword[B+0x80], xmm1); vmovq(xmm2, qword[A2-0x80]); vmovq(xmm3, qword[A2+LDA*1-0x80]); vmovq(xmm4, qword[A2+LDA*2-0x80]); vmovq(xmm5, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm3, xmm2, xmm3); vpunpckldq(xmm5, xmm4, xmm5); vpunpcklqdq(xmm2, xmm3, xmm5); vpunpckhqdq(xmm3, xmm3, xmm5); vmovdqu(xword[B-0x30], xmm2); vmovdqu(xword[B+0x90], xmm3); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm2); vmovhlps(xmm7, xmm2, xmm2); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm10, ymm10, ymm5); vpmovsxbw(ymm5, xmm1); vmovhlps(xmm6, xmm1, xmm1); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm3); vmovhlps(xmm7, xmm3, xmm3); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm10, ymm10, ymm5); vmovq(xmm0, qword[A2-0x80]); vmovq(xmm1, qword[A2+LDA*1-0x80]); vmovq(xmm2, qword[A2+LDA*2-0x80]); vmovq(xmm3, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm1, xmm0, xmm1); vpunpckldq(xmm3, xmm2, xmm3); vpunpcklqdq(xmm0, xmm1, xmm3); vpunpckhqdq(xmm1, xmm1, xmm3); vmovdqu(xword[B-0x20], xmm0); vmovdqu(xword[B+0xa0], xmm1); vmovq(xmm2, qword[A2-0x80]); vmovq(xmm3, qword[A2+LDA*1-0x80]); vmovq(xmm4, qword[A2+LDA*2-0x80]); vmovq(xmm5, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm3, xmm2, xmm3); vpunpckldq(xmm5, xmm4, xmm5); vpunpcklqdq(xmm2, xmm3, xmm5); vpunpckhqdq(xmm3, xmm3, xmm5); vmovdqu(xword[B-0x10], xmm2); vmovdqu(xword[B+0xb0], xmm3); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm2); vmovhlps(xmm7, xmm2, xmm2); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm11, ymm11, ymm5); vpmovsxbw(ymm5, xmm1); vmovhlps(xmm6, xmm1, xmm1); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm3); vmovhlps(xmm7, xmm3, xmm3); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm11, ymm11, ymm5); vmovq(xmm0, qword[A2-0x80]); vmovq(xmm1, qword[A2+LDA*1-0x80]); vmovq(xmm2, qword[A2+LDA*2-0x80]); vmovq(xmm3, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm1, xmm0, xmm1); vpunpckldq(xmm3, xmm2, xmm3); vpunpcklqdq(xmm0, xmm1, xmm3); vpunpckhqdq(xmm1, xmm1, xmm3); vmovdqu(xword[B], xmm0); vmovdqu(xword[B+0xc0], xmm1); vmovq(xmm2, qword[A2-0x80]); vmovq(xmm3, qword[A2+LDA*1-0x80]); vmovq(xmm4, qword[A2+LDA*2-0x80]); vmovq(xmm5, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm3, xmm2, xmm3); vpunpckldq(xmm5, xmm4, xmm5); vpunpcklqdq(xmm2, xmm3, xmm5); vpunpckhqdq(xmm3, xmm3, xmm5); vmovdqu(xword[B+0x10], xmm2); vmovdqu(xword[B+0xd0], xmm3); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm2); vmovhlps(xmm7, xmm2, xmm2); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm12, ymm12, ymm5); vpmovsxbw(ymm5, xmm1); vmovhlps(xmm6, xmm1, xmm1); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm3); vmovhlps(xmm7, xmm3, xmm3); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm12, ymm12, ymm5); vmovq(xmm0, qword[A2-0x80]); vmovq(xmm1, qword[A2+LDA*1-0x80]); vmovq(xmm2, qword[A2+LDA*2-0x80]); vmovq(xmm3, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm1, xmm0, xmm1); vpunpckldq(xmm3, xmm2, xmm3); vpunpcklqdq(xmm0, xmm1, xmm3); vpunpckhqdq(xmm1, xmm1, xmm3); vmovdqu(xword[B+0x20], xmm0); vmovdqu(xword[B+0xe0], xmm1); vmovq(xmm2, qword[A2-0x80]); vmovq(xmm3, qword[A2+LDA*1-0x80]); vmovq(xmm4, qword[A2+LDA*2-0x80]); vmovq(xmm5, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm3, xmm2, xmm3); vpunpckldq(xmm5, xmm4, xmm5); vpunpcklqdq(xmm2, xmm3, xmm5); vpunpckhqdq(xmm3, xmm3, xmm5); vmovdqu(xword[B+0x30], xmm2); vmovdqu(xword[B+0xf0], xmm3); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm2); vmovhlps(xmm7, xmm2, xmm2); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm13, ymm13, ymm5); vpmovsxbw(ymm5, xmm1); vmovhlps(xmm6, xmm1, xmm1); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm3); vmovhlps(xmm7, xmm3, xmm3); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm13, ymm13, ymm5); sub(A1, -8); sub(B, -384); dec(I); jg(l6c, T_NEAR); align(4); L(l5cc); test(M, 0x4); jle(l968, T_NEAR); vmovd(xmm0, dword[A1-0x80]); vmovd(xmm1, dword[A1+LDA*1-0x80]); vmovd(xmm2, dword[A1+LDA*2-0x80]); vmovd(xmm3, dword[A1+LDA3*1-0x80]); lea(A2, ptr[A1+LDA*4]); vpunpckldq(xmm0, xmm0, xmm1); vpunpckldq(xmm2, xmm2, xmm3); vpunpcklqdq(xmm0, xmm0, xmm2); vmovdqu(xword[B-0x80], xmm0); vmovd(xmm1, dword[A2-0x80]); vmovd(xmm2, dword[A2+LDA*1-0x80]); vmovd(xmm3, dword[A2+LDA*2-0x80]); vmovd(xmm4, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm1, xmm1, xmm2); vpunpckldq(xmm3, xmm3, xmm4); vpunpcklqdq(xmm1, xmm1, xmm3); vmovdqu(xword[B-0x70], xmm1); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm1); vmovhlps(xmm7, xmm1, xmm1); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm8, ymm8, ymm5); vmovd(xmm0, dword[A2-0x80]); vmovd(xmm1, dword[A2+LDA*1-0x80]); vmovd(xmm2, dword[A2+LDA*2-0x80]); vmovd(xmm3, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm0, xmm0, xmm1); vpunpckldq(xmm2, xmm2, xmm3); vpunpcklqdq(xmm0, xmm0, xmm2); vmovdqu(xword[B-0x60], xmm0); vmovd(xmm1, dword[A2-0x80]); vmovd(xmm2, dword[A2+LDA*1-0x80]); vmovd(xmm3, dword[A2+LDA*2-0x80]); vmovd(xmm4, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm1, xmm1, xmm2); vpunpckldq(xmm3, xmm3, xmm4); vpunpcklqdq(xmm1, xmm1, xmm3); vmovdqu(xword[B-0x50], xmm1); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm1); vmovhlps(xmm7, xmm1, xmm1); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm9, ymm9, ymm5); vmovd(xmm0, dword[A2-0x80]); vmovd(xmm1, dword[A2+LDA*1-0x80]); vmovd(xmm2, dword[A2+LDA*2-0x80]); vmovd(xmm3, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm0, xmm0, xmm1); vpunpckldq(xmm2, xmm2, xmm3); vpunpcklqdq(xmm0, xmm0, xmm2); vmovdqu(xword[B-0x40], xmm0); vmovd(xmm1, dword[A2-0x80]); vmovd(xmm2, dword[A2+LDA*1-0x80]); vmovd(xmm3, dword[A2+LDA*2-0x80]); vmovd(xmm4, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm1, xmm1, xmm2); vpunpckldq(xmm3, xmm3, xmm4); vpunpcklqdq(xmm1, xmm1, xmm3); vmovdqu(xword[B-0x30], xmm1); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm1); vmovhlps(xmm7, xmm1, xmm1); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm10, ymm10, ymm5); vmovd(xmm0, dword[A2-0x80]); vmovd(xmm1, dword[A2+LDA*1-0x80]); vmovd(xmm2, dword[A2+LDA*2-0x80]); vmovd(xmm3, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm0, xmm0, xmm1); vpunpckldq(xmm2, xmm2, xmm3); vpunpcklqdq(xmm0, xmm0, xmm2); vmovdqu(xword[B-0x20], xmm0); vmovd(xmm1, dword[A2-0x80]); vmovd(xmm2, dword[A2+LDA*1-0x80]); vmovd(xmm3, dword[A2+LDA*2-0x80]); vmovd(xmm4, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm1, xmm1, xmm2); vpunpckldq(xmm3, xmm3, xmm4); vpunpcklqdq(xmm1, xmm1, xmm3); vmovdqu(xword[B-0x10], xmm1); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm1); vmovhlps(xmm7, xmm1, xmm1); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm11, ymm11, ymm5); vmovd(xmm0, dword[A2-0x80]); vmovd(xmm1, dword[A2+LDA*1-0x80]); vmovd(xmm2, dword[A2+LDA*2-0x80]); vmovd(xmm3, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm0, xmm0, xmm1); vpunpckldq(xmm2, xmm2, xmm3); vpunpcklqdq(xmm0, xmm0, xmm2); vmovdqu(xword[B], xmm0); vmovd(xmm1, dword[A2-0x80]); vmovd(xmm2, dword[A2+LDA*1-0x80]); vmovd(xmm3, dword[A2+LDA*2-0x80]); vmovd(xmm4, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm1, xmm1, xmm2); vpunpckldq(xmm3, xmm3, xmm4); vpunpcklqdq(xmm1, xmm1, xmm3); vmovdqu(xword[B+0x10], xmm1); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm1); vmovhlps(xmm7, xmm1, xmm1); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm12, ymm12, ymm5); vmovd(xmm0, dword[A2-0x80]); vmovd(xmm1, dword[A2+LDA*1-0x80]); vmovd(xmm2, dword[A2+LDA*2-0x80]); vmovd(xmm3, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm0, xmm0, xmm1); vpunpckldq(xmm2, xmm2, xmm3); vpunpcklqdq(xmm0, xmm0, xmm2); vmovdqu(xword[B+0x20], xmm0); vmovd(xmm1, dword[A2-0x80]); vmovd(xmm2, dword[A2+LDA*1-0x80]); vmovd(xmm3, dword[A2+LDA*2-0x80]); vmovd(xmm4, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpunpckldq(xmm1, xmm1, xmm2); vpunpckldq(xmm3, xmm3, xmm4); vpunpcklqdq(xmm1, xmm1, xmm3); vmovdqu(xword[B+0x30], xmm1); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxbw(ymm6, xmm1); vmovhlps(xmm7, xmm1, xmm1); vpmovsxbw(ymm7, xmm7); vphaddw(ymm6, ymm6, ymm7); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm13, ymm13, ymm5); sub(A1, -4); sub(B, -192); align(4); L(l968); test(M, 0x2); jle(lc80, T_NEAR); mov(ax, word[A1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x0); mov(ax, word[A1+LDA*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x1); mov(ax, word[A1+LDA*2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x2); mov(ax, word[A1+LDA3*1-0x80]); lea(A2, ptr[A1+LDA*4]); vpinsrw(xmm0, xmm0, eax, 0x3); mov(ax, word[A2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x4); mov(ax, word[A2+LDA*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x5); mov(ax, word[A2+LDA*2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x6); mov(ax, word[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrw(xmm0, xmm0, eax, 0x7); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm8, ymm8, ymm5); vmovdqu(xword[B-0x80], xmm0); mov(ax, word[A2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x0); mov(ax, word[A2+LDA*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x1); mov(ax, word[A2+LDA*2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x2); mov(ax, word[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrw(xmm0, xmm0, eax, 0x3); mov(ax, word[A2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x4); mov(ax, word[A2+LDA*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x5); mov(ax, word[A2+LDA*2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x6); mov(ax, word[A2+LDA3*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x7); lea(A2, ptr[A2+LDA*4]); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm9, ymm9, ymm5); vmovdqu(xword[B-0x70], xmm0); mov(ax, word[A2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x0); mov(ax, word[A2+LDA*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x1); mov(ax, word[A2+LDA*2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x2); mov(ax, word[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrw(xmm0, xmm0, eax, 0x3); mov(ax, word[A2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x4); mov(ax, word[A2+LDA*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x5); mov(ax, word[A2+LDA*2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x6); mov(ax, word[A2+LDA3*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x7); lea(A2, ptr[A2+LDA*4]); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm10, ymm10, ymm5); vmovdqu(xword[B-0x60], xmm0); mov(ax, word[A2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x0); mov(ax, word[A2+LDA*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x1); mov(ax, word[A2+LDA*2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x2); mov(ax, word[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrw(xmm0, xmm0, eax, 0x3); mov(ax, word[A2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x4); mov(ax, word[A2+LDA*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x5); mov(ax, word[A2+LDA*2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x6); mov(ax, word[A2+LDA3*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x7); lea(A2, ptr[A2+LDA*4]); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm11, ymm11, ymm5); vmovdqu(xword[B-0x50], xmm0); mov(ax, word[A2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x0); mov(ax, word[A2+LDA*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x1); mov(ax, word[A2+LDA*2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x2); mov(ax, word[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrw(xmm0, xmm0, eax, 0x3); mov(ax, word[A2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x4); mov(ax, word[A2+LDA*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x5); mov(ax, word[A2+LDA*2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x6); mov(ax, word[A2+LDA3*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x7); lea(A2, ptr[A2+LDA*4]); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm12, ymm12, ymm5); vmovdqu(xword[B-0x40], xmm0); mov(ax, word[A2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x0); mov(ax, word[A2+LDA*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x1); mov(ax, word[A2+LDA*2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x2); mov(ax, word[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrw(xmm0, xmm0, eax, 0x3); mov(ax, word[A2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x4); mov(ax, word[A2+LDA*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x5); mov(ax, word[A2+LDA*2-0x80]); vpinsrw(xmm0, xmm0, eax, 0x6); mov(ax, word[A2+LDA3*1-0x80]); vpinsrw(xmm0, xmm0, eax, 0x7); lea(A2, ptr[A2+LDA*4]); vpmovsxbw(ymm5, xmm0); vmovhlps(xmm6, xmm0, xmm0); vpmovsxbw(ymm6, xmm6); vphaddw(ymm5, ymm5, ymm6); vpmovsxwd(ymm5, xmm5); vpaddd(ymm13, ymm13, ymm5); vmovdqu(xword[B-0x30], xmm0); sub(A1, -2); sub(B, -96); align(4); L(lc80); test(M, 0x1); jle(lf1c, T_NEAR); mov(al, byte[A1-0x80]); vpinsrb(xmm0, xmm0, eax, 0x0); mov(al, byte[A1+LDA*1-0x80]); vpinsrb(xmm0, xmm0, eax, 0x1); mov(al, byte[A1+LDA*2-0x80]); vpinsrb(xmm0, xmm0, eax, 0x2); mov(al, byte[A1+LDA3*1-0x80]); lea(A2, ptr[A1+LDA*4]); vpinsrb(xmm0, xmm0, eax, 0x3); mov(al, byte[A2-0x80]); vpinsrb(xmm0, xmm0, eax, 0x4); mov(al, byte[A2+LDA*1-0x80]); vpinsrb(xmm0, xmm0, eax, 0x5); mov(al, byte[A2+LDA*2-0x80]); vpinsrb(xmm0, xmm0, eax, 0x6); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrb(xmm0, xmm0, eax, 0x7); mov(al, byte[A2-0x80]); vpinsrb(xmm0, xmm0, eax, 0x8); mov(al, byte[A2+LDA*1-0x80]); vpinsrb(xmm0, xmm0, eax, 0x9); mov(al, byte[A2+LDA*2-0x80]); vpinsrb(xmm0, xmm0, eax, 0xa); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrb(xmm0, xmm0, eax, 0xb); mov(al, byte[A2-0x80]); vpinsrb(xmm0, xmm0, eax, 0xc); mov(al, byte[A2+LDA*1-0x80]); vpinsrb(xmm0, xmm0, eax, 0xd); mov(al, byte[A2+LDA*2-0x80]); vpinsrb(xmm0, xmm0, eax, 0xe); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrb(xmm0, xmm0, eax, 0xf); vpmovsxbd(ymm7, xmm0); vpaddd(ymm8, ymm8, ymm7); vmovhlps(xmm7, xmm0, xmm0); vpmovsxbd(ymm7, xmm7); vpaddd(ymm9, ymm9, ymm7); vmovdqu(xword[B-0x80], xmm0); mov(al, byte[A2-0x80]); vpinsrb(xmm0, xmm0, eax, 0x0); mov(al, byte[A2+LDA*1-0x80]); vpinsrb(xmm0, xmm0, eax, 0x1); mov(al, byte[A2+LDA*2-0x80]); vpinsrb(xmm0, xmm0, eax, 0x2); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrb(xmm0, xmm0, eax, 0x3); mov(al, byte[A2-0x80]); vpinsrb(xmm0, xmm0, eax, 0x4); mov(al, byte[A2+LDA*1-0x80]); vpinsrb(xmm0, xmm0, eax, 0x5); mov(al, byte[A2+LDA*2-0x80]); vpinsrb(xmm0, xmm0, eax, 0x6); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrb(xmm0, xmm0, eax, 0x7); mov(al, byte[A2-0x80]); vpinsrb(xmm0, xmm0, eax, 0x8); mov(al, byte[A2+LDA*1-0x80]); vpinsrb(xmm0, xmm0, eax, 0x9); mov(al, byte[A2+LDA*2-0x80]); vpinsrb(xmm0, xmm0, eax, 0xa); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrb(xmm0, xmm0, eax, 0xb); mov(al, byte[A2-0x80]); vpinsrb(xmm0, xmm0, eax, 0xc); mov(al, byte[A2+LDA*1-0x80]); vpinsrb(xmm0, xmm0, eax, 0xd); mov(al, byte[A2+LDA*2-0x80]); vpinsrb(xmm0, xmm0, eax, 0xe); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrb(xmm0, xmm0, eax, 0xf); vpmovsxbd(ymm7, xmm0); vpaddd(ymm10, ymm10, ymm7); vmovhlps(xmm7, xmm0, xmm0); vpmovsxbd(ymm7, xmm7); vpaddd(ymm11, ymm11, ymm7); vmovdqu(xword[B-0x70], xmm0); mov(al, byte[A2-0x80]); vpinsrb(xmm0, xmm0, eax, 0x0); mov(al, byte[A2+LDA*1-0x80]); vpinsrb(xmm0, xmm0, eax, 0x1); mov(al, byte[A2+LDA*2-0x80]); vpinsrb(xmm0, xmm0, eax, 0x2); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrb(xmm0, xmm0, eax, 0x3); mov(al, byte[A2-0x80]); vpinsrb(xmm0, xmm0, eax, 0x4); mov(al, byte[A2+LDA*1-0x80]); vpinsrb(xmm0, xmm0, eax, 0x5); mov(al, byte[A2+LDA*2-0x80]); vpinsrb(xmm0, xmm0, eax, 0x6); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrb(xmm0, xmm0, eax, 0x7); mov(al, byte[A2-0x80]); vpinsrb(xmm0, xmm0, eax, 0x8); mov(al, byte[A2+LDA*1-0x80]); vpinsrb(xmm0, xmm0, eax, 0x9); mov(al, byte[A2+LDA*2-0x80]); vpinsrb(xmm0, xmm0, eax, 0xa); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrb(xmm0, xmm0, eax, 0xb); mov(al, byte[A2-0x80]); vpinsrb(xmm0, xmm0, eax, 0xc); mov(al, byte[A2+LDA*1-0x80]); vpinsrb(xmm0, xmm0, eax, 0xd); mov(al, byte[A2+LDA*2-0x80]); vpinsrb(xmm0, xmm0, eax, 0xe); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); vpinsrb(xmm0, xmm0, eax, 0xf); vpmovsxbd(ymm7, xmm0); vpaddd(ymm12, ymm12, ymm7); vmovhlps(xmm7, xmm0, xmm0); vpmovsxbd(ymm7, xmm7); vpaddd(ymm13, ymm13, ymm7); vmovdqu(xword[B-0x60], xmm0); sub(B, -48); align(4); L(lf1c); mov(A1, qword[ARG_BIAS]); vmovdqu(yword[A1], ymm8); vmovdqu(yword[A1+0x20], ymm9); vmovdqu(yword[A1+0x40], ymm10); vmovdqu(yword[A1+0x60], ymm11); vmovdqu(yword[A1+0x80], ymm12); vmovdqu(yword[A1+0xa0], ymm13); add(qword[ARG_BIAS], 0xc0); sub(N, 0x30); cmp(N, 0x30); jge(l20, T_NEAR); vzeroupper(); align(4); L(lf64); cmp(N, 0x20); jl(l22b8, T_NEAR); align(4); L(lf70); mov(A1, A); mov(I, LDA); shl(I, 0x5); add(A, I); pxor(xmm8, xmm8); pxor(xmm9, xmm9); pxor(xmm10, xmm10); pxor(xmm11, xmm11); pxor(xmm12, xmm12); pxor(xmm13, xmm13); pxor(xmm14, xmm14); pxor(xmm15, xmm15); mov(I, M); sar(I, 0x4); jle(l1750, T_NEAR); align(4); L(lfb4); movdqu(xmm0, xword[A1-0x80]); movdqu(xmm1, xword[A1+LDA*1-0x80]); movdqu(xmm2, xword[A1+LDA*2-0x80]); movdqu(xmm3, xword[A1+LDA3*1-0x80]); lea(A2, ptr[A1+LDA*4]); movdqa(xmm4, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm4, xmm1); movdqa(xmm5, xmm2); punpckldq(xmm2, xmm3); punpckhdq(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); movdqa(xmm3, xmm4); punpcklqdq(xmm4, xmm5); punpckhqdq(xmm3, xmm5); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B-0x80], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B], xmm1); pmovsxbw(xmm5, xmm4); movhlps(xmm6, xmm4); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B+0x80], xmm4); pmovsxbw(xmm5, xmm3); movhlps(xmm6, xmm3); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B+0x100], xmm3); movdqu(xmm0, xword[A2-0x80]); movdqu(xmm1, xword[A2+LDA*1-0x80]); movdqu(xmm2, xword[A2+LDA*2-0x80]); movdqu(xmm3, xword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); movdqa(xmm4, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm4, xmm1); movdqa(xmm5, xmm2); punpckldq(xmm2, xmm3); punpckhdq(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); movdqa(xmm3, xmm4); punpcklqdq(xmm4, xmm5); punpckhqdq(xmm3, xmm5); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B-0x70], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B+0x10], xmm1); pmovsxbw(xmm5, xmm4); movhlps(xmm6, xmm4); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B+0x90], xmm4); pmovsxbw(xmm5, xmm3); movhlps(xmm6, xmm3); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B+0x110], xmm3); movdqu(xmm0, xword[A2-0x80]); movdqu(xmm1, xword[A2+LDA*1-0x80]); movdqu(xmm2, xword[A2+LDA*2-0x80]); movdqu(xmm3, xword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); movdqa(xmm4, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm4, xmm1); movdqa(xmm5, xmm2); punpckldq(xmm2, xmm3); punpckhdq(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); movdqa(xmm3, xmm4); punpcklqdq(xmm4, xmm5); punpckhqdq(xmm3, xmm5); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movdqu(xword[B-0x60], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movdqu(xword[B+0x20], xmm1); pmovsxbw(xmm5, xmm4); movhlps(xmm6, xmm4); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movdqu(xword[B+0xa0], xmm4); pmovsxbw(xmm5, xmm3); movhlps(xmm6, xmm3); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movdqu(xword[B+0x120], xmm3); movdqu(xmm0, xword[A2-0x80]); movdqu(xmm1, xword[A2+LDA*1-0x80]); movdqu(xmm2, xword[A2+LDA*2-0x80]); movdqu(xmm3, xword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); movdqa(xmm4, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm4, xmm1); movdqa(xmm5, xmm2); punpckldq(xmm2, xmm3); punpckhdq(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); movdqa(xmm3, xmm4); punpcklqdq(xmm4, xmm5); punpckhqdq(xmm3, xmm5); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm11, xmm5); movdqu(xword[B-0x50], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm11, xmm5); movdqu(xword[B+0x30], xmm1); pmovsxbw(xmm5, xmm4); movhlps(xmm6, xmm4); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm11, xmm5); movdqu(xword[B+0xb0], xmm4); pmovsxbw(xmm5, xmm3); movhlps(xmm6, xmm3); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm11, xmm5); movdqu(xword[B+0x130], xmm3); movdqu(xmm0, xword[A2-0x80]); movdqu(xmm1, xword[A2+LDA*1-0x80]); movdqu(xmm2, xword[A2+LDA*2-0x80]); movdqu(xmm3, xword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); movdqa(xmm4, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm4, xmm1); movdqa(xmm5, xmm2); punpckldq(xmm2, xmm3); punpckhdq(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); movdqa(xmm3, xmm4); punpcklqdq(xmm4, xmm5); punpckhqdq(xmm3, xmm5); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm12, xmm5); movdqu(xword[B-0x40], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm12, xmm5); movdqu(xword[B+0x40], xmm1); pmovsxbw(xmm5, xmm4); movhlps(xmm6, xmm4); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm12, xmm5); movdqu(xword[B+0xc0], xmm4); pmovsxbw(xmm5, xmm3); movhlps(xmm6, xmm3); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm12, xmm5); movdqu(xword[B+0x140], xmm3); movdqu(xmm0, xword[A2-0x80]); movdqu(xmm1, xword[A2+LDA*1-0x80]); movdqu(xmm2, xword[A2+LDA*2-0x80]); movdqu(xmm3, xword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); movdqa(xmm4, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm4, xmm1); movdqa(xmm5, xmm2); punpckldq(xmm2, xmm3); punpckhdq(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); movdqa(xmm3, xmm4); punpcklqdq(xmm4, xmm5); punpckhqdq(xmm3, xmm5); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm13, xmm5); movdqu(xword[B-0x30], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm13, xmm5); movdqu(xword[B+0x50], xmm1); pmovsxbw(xmm5, xmm4); movhlps(xmm6, xmm4); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm13, xmm5); movdqu(xword[B+0xd0], xmm4); pmovsxbw(xmm5, xmm3); movhlps(xmm6, xmm3); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm13, xmm5); movdqu(xword[B+0x150], xmm3); movdqu(xmm0, xword[A2-0x80]); movdqu(xmm1, xword[A2+LDA*1-0x80]); movdqu(xmm2, xword[A2+LDA*2-0x80]); movdqu(xmm3, xword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); movdqa(xmm4, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm4, xmm1); movdqa(xmm5, xmm2); punpckldq(xmm2, xmm3); punpckhdq(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); movdqa(xmm3, xmm4); punpcklqdq(xmm4, xmm5); punpckhqdq(xmm3, xmm5); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm14, xmm5); movdqu(xword[B-0x20], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm14, xmm5); movdqu(xword[B+0x60], xmm1); pmovsxbw(xmm5, xmm4); movhlps(xmm6, xmm4); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm14, xmm5); movdqu(xword[B+0xe0], xmm4); pmovsxbw(xmm5, xmm3); movhlps(xmm6, xmm3); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm14, xmm5); movdqu(xword[B+0x160], xmm3); movdqu(xmm0, xword[A2-0x80]); movdqu(xmm1, xword[A2+LDA*1-0x80]); movdqu(xmm2, xword[A2+LDA*2-0x80]); movdqu(xmm3, xword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); movdqa(xmm4, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm4, xmm1); movdqa(xmm5, xmm2); punpckldq(xmm2, xmm3); punpckhdq(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); movdqa(xmm3, xmm4); punpcklqdq(xmm4, xmm5); punpckhqdq(xmm3, xmm5); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm15, xmm5); movdqu(xword[B-0x10], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm15, xmm5); movdqu(xword[B+0x70], xmm1); pmovsxbw(xmm5, xmm4); movhlps(xmm6, xmm4); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm15, xmm5); movdqu(xword[B+0xf0], xmm4); pmovsxbw(xmm5, xmm3); movhlps(xmm6, xmm3); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm15, xmm5); movdqu(xword[B+0x170], xmm3); sub(A1, -16); sub(B, -512); dec(I); jg(lfb4, T_NEAR); align(4); L(l1750); test(M, 0x8); jle(l1b6c, T_NEAR); movq(xmm0, qword[A1-0x80]); movq(xmm1, qword[A1+LDA*1-0x80]); movq(xmm2, qword[A1+LDA*2-0x80]); movq(xmm3, qword[A1+LDA3*1-0x80]); lea(A2, ptr[A1+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B-0x80], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B], xmm1); movq(xmm0, qword[A2-0x80]); movq(xmm1, qword[A2+LDA*1-0x80]); movq(xmm2, qword[A2+LDA*2-0x80]); movq(xmm3, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B-0x70], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B+0x10], xmm1); movq(xmm0, qword[A2-0x80]); movq(xmm1, qword[A2+LDA*1-0x80]); movq(xmm2, qword[A2+LDA*2-0x80]); movq(xmm3, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movdqu(xword[B-0x60], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movdqu(xword[B+0x20], xmm1); movq(xmm0, qword[A2-0x80]); movq(xmm1, qword[A2+LDA*1-0x80]); movq(xmm2, qword[A2+LDA*2-0x80]); movq(xmm3, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm11, xmm5); movdqu(xword[B-0x50], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm11, xmm5); movdqu(xword[B+0x30], xmm1); movq(xmm0, qword[A2-0x80]); movq(xmm1, qword[A2+LDA*1-0x80]); movq(xmm2, qword[A2+LDA*2-0x80]); movq(xmm3, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm12, xmm5); movdqu(xword[B-0x40], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm12, xmm5); movdqu(xword[B+0x40], xmm1); movq(xmm0, qword[A2-0x80]); movq(xmm1, qword[A2+LDA*1-0x80]); movq(xmm2, qword[A2+LDA*2-0x80]); movq(xmm3, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm13, xmm5); movdqu(xword[B-0x30], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm13, xmm5); movdqu(xword[B+0x50], xmm1); movq(xmm0, qword[A2-0x80]); movq(xmm1, qword[A2+LDA*1-0x80]); movq(xmm2, qword[A2+LDA*2-0x80]); movq(xmm3, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm14, xmm5); movdqu(xword[B-0x20], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm14, xmm5); movdqu(xword[B+0x60], xmm1); movq(xmm0, qword[A2-0x80]); movq(xmm1, qword[A2+LDA*1-0x80]); movq(xmm2, qword[A2+LDA*2-0x80]); movq(xmm3, qword[A2+LDA3*1-0x80]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm15, xmm5); movdqu(xword[B-0x10], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm15, xmm5); movdqu(xword[B+0x70], xmm1); sub(A1, -8); sub(B, -256); align(4); L(l1b6c); test(M, 0x4); jle(l1e14, T_NEAR); movd(xmm0, dword[A1-0x80]); movd(xmm1, dword[A1+LDA*1-0x80]); movd(xmm2, dword[A1+LDA*2-0x80]); movd(xmm3, dword[A1+LDA3*1-0x80]); lea(A2, ptr[A1+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); punpcklqdq(xmm0, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B-0x80], xmm0); movd(xmm0, dword[A2-0x80]); movd(xmm1, dword[A2+LDA*1-0x80]); movd(xmm2, dword[A2+LDA*2-0x80]); movd(xmm3, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); punpcklqdq(xmm0, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B-0x70], xmm0); movd(xmm0, dword[A2-0x80]); movd(xmm1, dword[A2+LDA*1-0x80]); movd(xmm2, dword[A2+LDA*2-0x80]); movd(xmm3, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); punpcklqdq(xmm0, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movdqu(xword[B-0x60], xmm0); movd(xmm0, dword[A2-0x80]); movd(xmm1, dword[A2+LDA*1-0x80]); movd(xmm2, dword[A2+LDA*2-0x80]); movd(xmm3, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); punpcklqdq(xmm0, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm11, xmm5); movdqu(xword[B-0x50], xmm0); movd(xmm0, dword[A2-0x80]); movd(xmm1, dword[A2+LDA*1-0x80]); movd(xmm2, dword[A2+LDA*2-0x80]); movd(xmm3, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); punpcklqdq(xmm0, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm12, xmm5); movdqu(xword[B-0x40], xmm0); movd(xmm0, dword[A2-0x80]); movd(xmm1, dword[A2+LDA*1-0x80]); movd(xmm2, dword[A2+LDA*2-0x80]); movd(xmm3, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); punpcklqdq(xmm0, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm13, xmm5); movdqu(xword[B-0x30], xmm0); movd(xmm0, dword[A2-0x80]); movd(xmm1, dword[A2+LDA*1-0x80]); movd(xmm2, dword[A2+LDA*2-0x80]); movd(xmm3, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); punpcklqdq(xmm0, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm14, xmm5); movdqu(xword[B-0x20], xmm0); movd(xmm0, dword[A2-0x80]); movd(xmm1, dword[A2+LDA*1-0x80]); movd(xmm2, dword[A2+LDA*2-0x80]); movd(xmm3, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); punpcklqdq(xmm0, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm15, xmm5); movdqu(xword[B-0x10], xmm0); sub(A1, -4); sub(B, -128); align(4); L(l1e14); test(M, 0x2); jle(l2068, T_NEAR); mov(ax, word[A1-0x80]); pinsrw(xmm0, eax, 0x0); mov(ax, word[A1+LDA*1-0x80]); pinsrw(xmm0, eax, 0x1); mov(ax, word[A1+LDA*2-0x80]); pinsrw(xmm0, eax, 0x2); mov(ax, word[A1+LDA3*1-0x80]); lea(A2, ptr[A1+LDA*4]); pinsrw(xmm0, eax, 0x3); mov(ax, word[A2-0x80]); pinsrw(xmm0, eax, 0x4); mov(ax, word[A2+LDA*1-0x80]); pinsrw(xmm0, eax, 0x5); mov(ax, word[A2+LDA*2-0x80]); pinsrw(xmm0, eax, 0x6); mov(ax, word[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); pinsrw(xmm0, eax, 0x7); pmovsxbw(xmm5, xmm0); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm6, xmm6); pmovsxwd(xmm6, xmm6); paddd(xmm9, xmm6); movdqu(xword[B-0x80], xmm0); mov(ax, word[A2-0x80]); pinsrw(xmm0, eax, 0x0); mov(ax, word[A2+LDA*1-0x80]); pinsrw(xmm0, eax, 0x1); mov(ax, word[A2+LDA*2-0x80]); pinsrw(xmm0, eax, 0x2); mov(ax, word[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); pinsrw(xmm0, eax, 0x3); mov(ax, word[A2-0x80]); pinsrw(xmm0, eax, 0x4); mov(ax, word[A2+LDA*1-0x80]); pinsrw(xmm0, eax, 0x5); mov(ax, word[A2+LDA*2-0x80]); pinsrw(xmm0, eax, 0x6); mov(ax, word[A2+LDA3*1-0x80]); pinsrw(xmm0, eax, 0x7); lea(A2, ptr[A2+LDA*4]); pmovsxbw(xmm5, xmm0); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm6, xmm6); pmovsxwd(xmm6, xmm6); paddd(xmm11, xmm6); movdqu(xword[B-0x70], xmm0); mov(ax, word[A2-0x80]); pinsrw(xmm0, eax, 0x0); mov(ax, word[A2+LDA*1-0x80]); pinsrw(xmm0, eax, 0x1); mov(ax, word[A2+LDA*2-0x80]); pinsrw(xmm0, eax, 0x2); mov(ax, word[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); pinsrw(xmm0, eax, 0x3); mov(ax, word[A2-0x80]); pinsrw(xmm0, eax, 0x4); mov(ax, word[A2+LDA*1-0x80]); pinsrw(xmm0, eax, 0x5); mov(ax, word[A2+LDA*2-0x80]); pinsrw(xmm0, eax, 0x6); mov(ax, word[A2+LDA3*1-0x80]); pinsrw(xmm0, eax, 0x7); lea(A2, ptr[A2+LDA*4]); pmovsxbw(xmm5, xmm0); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm12, xmm5); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm6, xmm6); pmovsxwd(xmm6, xmm6); paddd(xmm13, xmm6); movdqu(xword[B-0x60], xmm0); mov(ax, word[A2-0x80]); pinsrw(xmm0, eax, 0x0); mov(ax, word[A2+LDA*1-0x80]); pinsrw(xmm0, eax, 0x1); mov(ax, word[A2+LDA*2-0x80]); pinsrw(xmm0, eax, 0x2); mov(ax, word[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); pinsrw(xmm0, eax, 0x3); mov(ax, word[A2-0x80]); pinsrw(xmm0, eax, 0x4); mov(ax, word[A2+LDA*1-0x80]); pinsrw(xmm0, eax, 0x5); mov(ax, word[A2+LDA*2-0x80]); pinsrw(xmm0, eax, 0x6); mov(ax, word[A2+LDA3*1-0x80]); pinsrw(xmm0, eax, 0x7); lea(A2, ptr[A2+LDA*4]); pmovsxbw(xmm5, xmm0); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm14, xmm5); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm6, xmm6); pmovsxwd(xmm6, xmm6); paddd(xmm15, xmm6); movdqu(xword[B-0x50], xmm0); sub(A1, -2); sub(B, -64); align(4); L(l2068); test(M, 0x1); jle(l226c, T_NEAR); mov(al, byte[A1-0x80]); pinsrb(xmm0, eax, 0x0); mov(al, byte[A1+LDA*1-0x80]); pinsrb(xmm0, eax, 0x1); mov(al, byte[A1+LDA*2-0x80]); pinsrb(xmm0, eax, 0x2); mov(al, byte[A1+LDA3*1-0x80]); lea(A2, ptr[A1+LDA*4]); pinsrb(xmm0, eax, 0x3); mov(al, byte[A2-0x80]); pinsrb(xmm0, eax, 0x4); mov(al, byte[A2+LDA*1-0x80]); pinsrb(xmm0, eax, 0x5); mov(al, byte[A2+LDA*2-0x80]); pinsrb(xmm0, eax, 0x6); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); pinsrb(xmm0, eax, 0x7); mov(al, byte[A2-0x80]); pinsrb(xmm0, eax, 0x8); mov(al, byte[A2+LDA*1-0x80]); pinsrb(xmm0, eax, 0x9); mov(al, byte[A2+LDA*2-0x80]); pinsrb(xmm0, eax, 0xa); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); pinsrb(xmm0, eax, 0xb); mov(al, byte[A2-0x80]); pinsrb(xmm0, eax, 0xc); mov(al, byte[A2+LDA*1-0x80]); pinsrb(xmm0, eax, 0xd); mov(al, byte[A2+LDA*2-0x80]); pinsrb(xmm0, eax, 0xe); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); pinsrb(xmm0, eax, 0xf); pmovsxbd(xmm5, xmm0); paddd(xmm8, xmm5); pshufd(xmm6, xmm0, 0x55); pmovsxbd(xmm6, xmm6); paddd(xmm9, xmm6); pshufd(xmm5, xmm0, 0xaa); pmovsxbd(xmm5, xmm5); paddd(xmm10, xmm5); pshufd(xmm6, xmm0, 0xff); pmovsxbd(xmm6, xmm6); paddd(xmm11, xmm6); movdqu(xword[B-0x80], xmm0); mov(al, byte[A2-0x80]); pinsrb(xmm0, eax, 0x0); mov(al, byte[A2+LDA*1-0x80]); pinsrb(xmm0, eax, 0x1); mov(al, byte[A2+LDA*2-0x80]); pinsrb(xmm0, eax, 0x2); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); pinsrb(xmm0, eax, 0x3); mov(al, byte[A2-0x80]); pinsrb(xmm0, eax, 0x4); mov(al, byte[A2+LDA*1-0x80]); pinsrb(xmm0, eax, 0x5); mov(al, byte[A2+LDA*2-0x80]); pinsrb(xmm0, eax, 0x6); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); pinsrb(xmm0, eax, 0x7); mov(al, byte[A2-0x80]); pinsrb(xmm0, eax, 0x8); mov(al, byte[A2+LDA*1-0x80]); pinsrb(xmm0, eax, 0x9); mov(al, byte[A2+LDA*2-0x80]); pinsrb(xmm0, eax, 0xa); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); pinsrb(xmm0, eax, 0xb); mov(al, byte[A2-0x80]); pinsrb(xmm0, eax, 0xc); mov(al, byte[A2+LDA*1-0x80]); pinsrb(xmm0, eax, 0xd); mov(al, byte[A2+LDA*2-0x80]); pinsrb(xmm0, eax, 0xe); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); pinsrb(xmm0, eax, 0xf); pmovsxbd(xmm5, xmm0); paddd(xmm12, xmm5); pshufd(xmm6, xmm0, 0x55); pmovsxbd(xmm6, xmm6); paddd(xmm13, xmm6); pshufd(xmm5, xmm0, 0xaa); pmovsxbd(xmm5, xmm5); paddd(xmm14, xmm5); pshufd(xmm6, xmm0, 0xff); pmovsxbd(xmm6, xmm6); paddd(xmm15, xmm6); movdqu(xword[B-0x70], xmm0); sub(B, -32); align(4); L(l226c); mov(A1, qword[ARG_BIAS]); movdqu(xword[A1], xmm8); movdqu(xword[A1+0x10], xmm9); movdqu(xword[A1+0x20], xmm10); movdqu(xword[A1+0x30], xmm11); movdqu(xword[A1+0x40], xmm12); movdqu(xword[A1+0x50], xmm13); movdqu(xword[A1+0x60], xmm14); movdqu(xword[A1+0x70], xmm15); add(qword[ARG_BIAS], 0x80); sub(N, 0x20); cmp(N, 0x20); jge(lf70, T_NEAR); align(4); L(l22b8); cmp(N, 0x10); jl(l2c94, T_NEAR); align(4); L(l22c4); mov(A1, A); mov(I, LDA); shl(I, 0x4); add(A, I); pxor(xmm8, xmm8); pxor(xmm9, xmm9); pxor(xmm10, xmm10); pxor(xmm11, xmm11); mov(I, M); sar(I, 0x4); jle(l26b4, T_NEAR); align(4); L(l22f4); movdqu(xmm0, xword[A1-0x80]); movdqu(xmm1, xword[A1+LDA*1-0x80]); movdqu(xmm2, xword[A1+LDA*2-0x80]); movdqu(xmm3, xword[A1+LDA3*1-0x80]); lea(A2, ptr[A1+LDA*4]); movdqa(xmm4, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm4, xmm1); movdqa(xmm5, xmm2); punpckldq(xmm2, xmm3); punpckhdq(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); movdqa(xmm3, xmm4); punpcklqdq(xmm4, xmm5); punpckhqdq(xmm3, xmm5); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B-0x80], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B-0x40], xmm1); pmovsxbw(xmm5, xmm4); movhlps(xmm6, xmm4); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B], xmm4); pmovsxbw(xmm5, xmm3); movhlps(xmm6, xmm3); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B+0x40], xmm3); movdqu(xmm0, xword[A2-0x80]); movdqu(xmm1, xword[A2+LDA*1-0x80]); movdqu(xmm2, xword[A2+LDA*2-0x80]); movdqu(xmm3, xword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); movdqa(xmm4, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm4, xmm1); movdqa(xmm5, xmm2); punpckldq(xmm2, xmm3); punpckhdq(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); movdqa(xmm3, xmm4); punpcklqdq(xmm4, xmm5); punpckhqdq(xmm3, xmm5); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B-0x70], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B-0x30], xmm1); pmovsxbw(xmm5, xmm4); movhlps(xmm6, xmm4); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B+0x10], xmm4); pmovsxbw(xmm5, xmm3); movhlps(xmm6, xmm3); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B+0x50], xmm3); movdqu(xmm0, xword[A2-0x80]); movdqu(xmm1, xword[A2+LDA*1-0x80]); movdqu(xmm2, xword[A2+LDA*2-0x80]); movdqu(xmm3, xword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); movdqa(xmm4, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm4, xmm1); movdqa(xmm5, xmm2); punpckldq(xmm2, xmm3); punpckhdq(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); movdqa(xmm3, xmm4); punpcklqdq(xmm4, xmm5); punpckhqdq(xmm3, xmm5); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movdqu(xword[B-0x60], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movdqu(xword[B-0x20], xmm1); pmovsxbw(xmm5, xmm4); movhlps(xmm6, xmm4); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movdqu(xword[B+0x20], xmm4); pmovsxbw(xmm5, xmm3); movhlps(xmm6, xmm3); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movdqu(xword[B+0x60], xmm3); movdqu(xmm0, xword[A2-0x80]); movdqu(xmm1, xword[A2+LDA*1-0x80]); movdqu(xmm2, xword[A2+LDA*2-0x80]); movdqu(xmm3, xword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); movdqa(xmm4, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm4, xmm1); movdqa(xmm5, xmm2); punpckldq(xmm2, xmm3); punpckhdq(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); movdqa(xmm3, xmm4); punpcklqdq(xmm4, xmm5); punpckhqdq(xmm3, xmm5); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm11, xmm5); movdqu(xword[B-0x50], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm11, xmm5); movdqu(xword[B-0x10], xmm1); pmovsxbw(xmm5, xmm4); movhlps(xmm6, xmm4); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm11, xmm5); movdqu(xword[B+0x30], xmm4); pmovsxbw(xmm5, xmm3); movhlps(xmm6, xmm3); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm11, xmm5); movdqu(xword[B+0x70], xmm3); sub(A1, -16); sub(B, -256); dec(I); jg(l22f4, T_NEAR); align(4); L(l26b4); test(M, 0x8); jle(l28cc, T_NEAR); movq(xmm0, qword[A1-0x80]); movq(xmm1, qword[A1+LDA*1-0x80]); movq(xmm2, qword[A1+LDA*2-0x80]); movq(xmm3, qword[A1+LDA3*1-0x80]); lea(A2, ptr[A1+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B-0x80], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B-0x40], xmm1); movq(xmm0, qword[A2-0x80]); movq(xmm1, qword[A2+LDA*1-0x80]); movq(xmm2, qword[A2+LDA*2-0x80]); movq(xmm3, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B-0x70], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B-0x30], xmm1); movq(xmm0, qword[A2-0x80]); movq(xmm1, qword[A2+LDA*1-0x80]); movq(xmm2, qword[A2+LDA*2-0x80]); movq(xmm3, qword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movdqu(xword[B-0x60], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movdqu(xword[B-0x20], xmm1); movq(xmm0, qword[A2-0x80]); movq(xmm1, qword[A2+LDA*1-0x80]); movq(xmm2, qword[A2+LDA*2-0x80]); movq(xmm3, qword[A2+LDA3*1-0x80]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm11, xmm5); movdqu(xword[B-0x50], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm11, xmm5); movdqu(xword[B-0x10], xmm1); sub(A1, -8); sub(B, -128); align(4); L(l28cc); test(M, 0x4); jle(l2a2c, T_NEAR); movd(xmm0, dword[A1-0x80]); movd(xmm1, dword[A1+LDA*1-0x80]); movd(xmm2, dword[A1+LDA*2-0x80]); movd(xmm3, dword[A1+LDA3*1-0x80]); lea(A2, ptr[A1+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); punpcklqdq(xmm0, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B-0x80], xmm0); movd(xmm0, dword[A2-0x80]); movd(xmm1, dword[A2+LDA*1-0x80]); movd(xmm2, dword[A2+LDA*2-0x80]); movd(xmm3, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); punpcklqdq(xmm0, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B-0x70], xmm0); movd(xmm0, dword[A2-0x80]); movd(xmm1, dword[A2+LDA*1-0x80]); movd(xmm2, dword[A2+LDA*2-0x80]); movd(xmm3, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); punpcklqdq(xmm0, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movdqu(xword[B-0x60], xmm0); movd(xmm0, dword[A2-0x80]); movd(xmm1, dword[A2+LDA*1-0x80]); movd(xmm2, dword[A2+LDA*2-0x80]); movd(xmm3, dword[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); punpcklqdq(xmm0, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm11, xmm5); movdqu(xword[B-0x50], xmm0); sub(A1, -4); sub(B, -64); align(4); L(l2a2c); test(M, 0x2); jle(l2b5c, T_NEAR); mov(ax, word[A1-0x80]); pinsrw(xmm0, eax, 0x0); mov(ax, word[A1+LDA*1-0x80]); pinsrw(xmm0, eax, 0x1); mov(ax, word[A1+LDA*2-0x80]); pinsrw(xmm0, eax, 0x2); mov(ax, word[A1+LDA3*1-0x80]); lea(A2, ptr[A1+LDA*4]); pinsrw(xmm0, eax, 0x3); mov(ax, word[A2-0x80]); pinsrw(xmm0, eax, 0x4); mov(ax, word[A2+LDA*1-0x80]); pinsrw(xmm0, eax, 0x5); mov(ax, word[A2+LDA*2-0x80]); pinsrw(xmm0, eax, 0x6); mov(ax, word[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); pinsrw(xmm0, eax, 0x7); pmovsxbw(xmm5, xmm0); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm6, xmm6); pmovsxwd(xmm6, xmm6); paddd(xmm9, xmm6); movdqu(xword[B-0x80], xmm0); mov(ax, word[A2-0x80]); pinsrw(xmm0, eax, 0x0); mov(ax, word[A2+LDA*1-0x80]); pinsrw(xmm0, eax, 0x1); mov(ax, word[A2+LDA*2-0x80]); pinsrw(xmm0, eax, 0x2); mov(ax, word[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); pinsrw(xmm0, eax, 0x3); mov(ax, word[A2-0x80]); pinsrw(xmm0, eax, 0x4); mov(ax, word[A2+LDA*1-0x80]); pinsrw(xmm0, eax, 0x5); mov(ax, word[A2+LDA*2-0x80]); pinsrw(xmm0, eax, 0x6); mov(ax, word[A2+LDA3*1-0x80]); pinsrw(xmm0, eax, 0x7); pmovsxbw(xmm5, xmm0); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm10, xmm5); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm6, xmm6); pmovsxwd(xmm6, xmm6); paddd(xmm11, xmm6); movdqu(xword[B-0x70], xmm0); sub(A1, -2); sub(B, -32); align(4); L(l2b5c); test(M, 0x1); jle(l2c64, T_NEAR); mov(al, byte[A1-0x80]); pinsrb(xmm0, eax, 0x0); mov(al, byte[A1+LDA*1-0x80]); pinsrb(xmm0, eax, 0x1); mov(al, byte[A1+LDA*2-0x80]); pinsrb(xmm0, eax, 0x2); mov(al, byte[A1+LDA3*1-0x80]); lea(A2, ptr[A1+LDA*4]); pinsrb(xmm0, eax, 0x3); mov(al, byte[A2-0x80]); pinsrb(xmm0, eax, 0x4); mov(al, byte[A2+LDA*1-0x80]); pinsrb(xmm0, eax, 0x5); mov(al, byte[A2+LDA*2-0x80]); pinsrb(xmm0, eax, 0x6); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); pinsrb(xmm0, eax, 0x7); mov(al, byte[A2-0x80]); pinsrb(xmm0, eax, 0x8); mov(al, byte[A2+LDA*1-0x80]); pinsrb(xmm0, eax, 0x9); mov(al, byte[A2+LDA*2-0x80]); pinsrb(xmm0, eax, 0xa); mov(al, byte[A2+LDA3*1-0x80]); lea(A2, ptr[A2+LDA*4]); pinsrb(xmm0, eax, 0xb); mov(al, byte[A2-0x80]); pinsrb(xmm0, eax, 0xc); mov(al, byte[A2+LDA*1-0x80]); pinsrb(xmm0, eax, 0xd); mov(al, byte[A2+LDA*2-0x80]); pinsrb(xmm0, eax, 0xe); mov(al, byte[A2+LDA3*1-0x80]); pinsrb(xmm0, eax, 0xf); pmovsxbd(xmm5, xmm0); paddd(xmm8, xmm5); pshufd(xmm6, xmm0, 0x55); pmovsxbd(xmm6, xmm6); paddd(xmm9, xmm6); pshufd(xmm5, xmm0, 0xaa); pmovsxbd(xmm5, xmm5); paddd(xmm10, xmm5); pshufd(xmm6, xmm0, 0xff); pmovsxbd(xmm6, xmm6); paddd(xmm11, xmm6); movdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l2c64); mov(A1, qword[ARG_BIAS]); movdqu(xword[A1], xmm8); movdqu(xword[A1+0x10], xmm9); movdqu(xword[A1+0x20], xmm10); movdqu(xword[A1+0x30], xmm11); add(qword[ARG_BIAS], 0x40); sub(N, 0x10); cmp(N, 0x10); jge(l22c4, T_NEAR); align(4); L(l2c94); cmp(N, 0x8); jl(l31c0, T_NEAR); align(4); L(l2ca0); mov(A1, A); lea(A2, ptr[A1+LDA*4]); lea(I, ptr[A1+LDA*8]); mov(A, I); pxor(xmm8, xmm8); pxor(xmm9, xmm9); mov(I, M); sar(I, 0x4); jle(l2eac, T_NEAR); align(4); L(l2cc8); movdqu(xmm0, xword[A1-0x80]); movdqu(xmm1, xword[A1+LDA*1-0x80]); movdqu(xmm2, xword[A1+LDA*2-0x80]); movdqu(xmm3, xword[A1+LDA3*1-0x80]); sub(A1, -16); movdqa(xmm4, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm4, xmm1); movdqa(xmm5, xmm2); punpckldq(xmm2, xmm3); punpckhdq(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); movdqa(xmm3, xmm4); punpcklqdq(xmm4, xmm5); punpckhqdq(xmm3, xmm5); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B-0x80], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B-0x60], xmm1); pmovsxbw(xmm5, xmm4); movhlps(xmm6, xmm4); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B-0x40], xmm4); pmovsxbw(xmm5, xmm3); movhlps(xmm6, xmm3); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B-0x20], xmm3); movdqu(xmm0, xword[A2-0x80]); movdqu(xmm1, xword[A2+LDA*1-0x80]); movdqu(xmm2, xword[A2+LDA*2-0x80]); movdqu(xmm3, xword[A2+LDA3*1-0x80]); sub(A2, -16); movdqa(xmm4, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm4, xmm1); movdqa(xmm5, xmm2); punpckldq(xmm2, xmm3); punpckhdq(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); movdqa(xmm3, xmm4); punpcklqdq(xmm4, xmm5); punpckhqdq(xmm3, xmm5); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B-0x70], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B-0x50], xmm1); pmovsxbw(xmm5, xmm4); movhlps(xmm6, xmm4); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B-0x30], xmm4); pmovsxbw(xmm5, xmm3); movhlps(xmm6, xmm3); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B-0x10], xmm3); sub(B, -128); dec(I); jg(l2cc8, T_NEAR); align(4); L(l2eac); test(M, 0x8); jle(l2fc0, T_NEAR); movq(xmm0, qword[A1-0x80]); movq(xmm1, qword[A1+LDA*1-0x80]); movq(xmm2, qword[A1+LDA*2-0x80]); movq(xmm3, qword[A1+LDA3*1-0x80]); sub(A1, -8); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B-0x80], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B-0x60], xmm1); movq(xmm0, qword[A2-0x80]); movq(xmm1, qword[A2+LDA*1-0x80]); movq(xmm2, qword[A2+LDA*2-0x80]); movq(xmm3, qword[A2+LDA3*1-0x80]); sub(A2, -8); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B-0x70], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B-0x50], xmm1); sub(B, -64); align(4); L(l2fc0); test(M, 0x4); jle(l3078, T_NEAR); movd(xmm0, dword[A1-0x80]); movd(xmm1, dword[A1+LDA*1-0x80]); movd(xmm2, dword[A1+LDA*2-0x80]); movd(xmm3, dword[A1+LDA3*1-0x80]); sub(A1, -4); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); punpcklqdq(xmm0, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movdqu(xword[B-0x80], xmm0); movd(xmm0, dword[A2-0x80]); movd(xmm1, dword[A2+LDA*1-0x80]); movd(xmm2, dword[A2+LDA*2-0x80]); movd(xmm3, dword[A2+LDA3*1-0x80]); sub(A2, -4); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); punpcklqdq(xmm0, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm9, xmm5); movdqu(xword[B-0x70], xmm0); sub(B, -32); align(4); L(l3078); test(M, 0x2); jle(l3118, T_NEAR); mov(ax, word[A1-0x80]); pinsrw(xmm0, eax, 0x0); mov(ax, word[A1+LDA*1-0x80]); pinsrw(xmm0, eax, 0x1); mov(ax, word[A1+LDA*2-0x80]); pinsrw(xmm0, eax, 0x2); mov(ax, word[A1+LDA3*1-0x80]); sub(A1, -2); pinsrw(xmm0, eax, 0x3); mov(ax, word[A2-0x80]); pinsrw(xmm0, eax, 0x4); mov(ax, word[A2+LDA*1-0x80]); pinsrw(xmm0, eax, 0x5); mov(ax, word[A2+LDA*2-0x80]); pinsrw(xmm0, eax, 0x6); mov(ax, word[A2+LDA3*1-0x80]); sub(A2, -2); pinsrw(xmm0, eax, 0x7); pmovsxbw(xmm5, xmm0); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm8, xmm5); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm6, xmm6); pmovsxwd(xmm6, xmm6); paddd(xmm9, xmm6); movdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l3118); test(M, 0x1); jle(l319c, T_NEAR); mov(al, byte[A1-0x80]); pinsrb(xmm0, eax, 0x0); mov(al, byte[A1+LDA*1-0x80]); pinsrb(xmm0, eax, 0x1); mov(al, byte[A1+LDA*2-0x80]); pinsrb(xmm0, eax, 0x2); mov(al, byte[A1+LDA3*1-0x80]); pinsrb(xmm0, eax, 0x3); mov(al, byte[A2-0x80]); pinsrb(xmm0, eax, 0x4); mov(al, byte[A2+LDA*1-0x80]); pinsrb(xmm0, eax, 0x5); mov(al, byte[A2+LDA*2-0x80]); pinsrb(xmm0, eax, 0x6); mov(al, byte[A2+LDA3*1-0x80]); pinsrb(xmm0, eax, 0x7); pmovsxbd(xmm5, xmm0); pshufd(xmm6, xmm0, 0x55); pmovsxbd(xmm6, xmm6); paddd(xmm8, xmm5); paddd(xmm9, xmm6); movq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l319c); mov(A1, qword[ARG_BIAS]); movdqu(xword[A1], xmm8); movdqu(xword[A1+0x10], xmm9); add(qword[ARG_BIAS], 0x20); sub(N, 0x8); cmp(N, 0x8); jge(l2ca0, T_NEAR); align(4); L(l31c0); cmp(N, 0x4); jl(l349c, T_NEAR); align(4); L(l31cc); mov(A1, A); lea(A2, ptr[A1+LDA*2]); lea(I, ptr[A1+LDA*4]); mov(A, I); pxor(xmm7, xmm7); mov(I, M); sar(I, 0x4); jle(l32e4, T_NEAR); align(4); L(l31ec); movdqu(xmm0, xword[A1-0x80]); movdqu(xmm1, xword[A1+LDA*1-0x80]); sub(A1, -16); movdqu(xmm2, xword[A2-0x80]); movdqu(xmm3, xword[A2+LDA*1-0x80]); sub(A2, -16); movdqa(xmm4, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm4, xmm1); movdqa(xmm5, xmm2); punpckldq(xmm2, xmm3); punpckhdq(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); movdqa(xmm3, xmm4); punpcklqdq(xmm4, xmm5); punpckhqdq(xmm3, xmm5); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movdqu(xword[B-0x80], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movdqu(xword[B-0x70], xmm1); pmovsxbw(xmm5, xmm4); movhlps(xmm6, xmm4); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movdqu(xword[B-0x60], xmm4); pmovsxbw(xmm5, xmm3); movhlps(xmm6, xmm3); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movdqu(xword[B-0x50], xmm3); sub(B, -64); dec(I); jg(l31ec, T_NEAR); align(4); L(l32e4); test(M, 0x8); jle(l3378, T_NEAR); movq(xmm0, qword[A1-0x80]); movq(xmm1, qword[A1+LDA*1-0x80]); sub(A1, -8); movq(xmm2, qword[A2-0x80]); movq(xmm3, qword[A2+LDA*1-0x80]); sub(A2, -8); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklqdq(xmm0, xmm2); punpckhqdq(xmm1, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movdqu(xword[B-0x80], xmm0); pmovsxbw(xmm5, xmm1); movhlps(xmm6, xmm1); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movdqu(xword[B-0x70], xmm1); sub(B, -32); align(4); L(l3378); test(M, 0x4); jle(l33dc, T_NEAR); movd(xmm0, dword[A1-0x80]); movd(xmm1, dword[A1+LDA*1-0x80]); sub(A1, -4); movd(xmm2, dword[A2-0x80]); movd(xmm3, dword[A2+LDA*1-0x80]); sub(A2, -4); punpckldq(xmm0, xmm1); punpckldq(xmm2, xmm3); punpcklqdq(xmm0, xmm2); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l33dc); test(M, 0x2); jle(l3434, T_NEAR); mov(ax, word[A1-0x80]); pinsrw(xmm0, eax, 0x0); mov(ax, word[A1+LDA*1-0x80]); sub(A1, -2); pinsrw(xmm0, eax, 0x1); mov(ax, word[A2-0x80]); pinsrw(xmm0, eax, 0x2); mov(ax, word[A2+LDA*1-0x80]); sub(A2, -2); pinsrw(xmm0, eax, 0x3); pmovsxbw(xmm5, xmm0); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l3434); test(M, 0x1); jle(l347c, T_NEAR); mov(al, byte[A1-0x80]); pinsrb(xmm0, eax, 0x0); mov(al, byte[A1+LDA*1-0x80]); pinsrb(xmm0, eax, 0x1); mov(al, byte[A2-0x80]); pinsrb(xmm0, eax, 0x2); mov(al, byte[A2+LDA*1-0x80]); pinsrb(xmm0, eax, 0x3); pmovsxbd(xmm5, xmm0); paddd(xmm7, xmm5); movd(dword[B-0x80], xmm0); sub(B, -4); align(4); L(l347c); mov(A1, qword[ARG_BIAS]); movdqu(xword[A1], xmm7); add(qword[ARG_BIAS], 0x10); sub(N, 0x4); cmp(N, 0x4); jge(l31cc, T_NEAR); align(4); L(l349c); cmp(N, 0x2); jl(l368a, T_NEAR); align(4); L(l34a8); mov(A1, A); lea(A2, ptr[A1+LDA*1]); lea(I, ptr[A1+LDA*2]); mov(A, I); pxor(xmm7, xmm7); mov(I, M); sar(I, 0x4); jle(l3558, T_NEAR); align(4); L(l34c8); movdqu(xmm0, xword[A1-0x80]); sub(A1, -16); movdqu(xmm1, xword[A2-0x80]); sub(A2, -16); movdqa(xmm2, xmm0); punpckldq(xmm0, xmm1); punpckhdq(xmm2, xmm1); pshufd(xmm6, xmm0, 0xd8); pmovsxbw(xmm5, xmm6); movhlps(xmm6, xmm6); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movdqu(xword[B-0x80], xmm0); pshufd(xmm6, xmm2, 0xd8); pmovsxbw(xmm5, xmm6); movhlps(xmm6, xmm6); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movdqu(xword[B-0x70], xmm2); sub(B, -32); dec(I); jg(l34c8, T_NEAR); align(4); L(l3558); test(M, 0x8); jle(l35b0, T_NEAR); movq(xmm0, qword[A1-0x80]); sub(A1, -8); movq(xmm1, qword[A2-0x80]); sub(A2, -8); punpckldq(xmm0, xmm1); pshufd(xmm6, xmm0, 0xd8); pmovsxbw(xmm5, xmm6); movhlps(xmm6, xmm6); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l35b0); test(M, 0x4); jle(l35f4, T_NEAR); movd(xmm0, dword[A1-0x80]); sub(A1, -4); movd(xmm1, dword[A2-0x80]); sub(A2, -4); punpckldq(xmm0, xmm1); pmovsxbw(xmm5, xmm0); phaddw(xmm5, xmm5); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l35f4); test(M, 0x2); jle(l3638, T_NEAR); mov(ax, word[A1-0x80]); sub(A1, -2); pinsrw(xmm0, eax, 0x0); mov(ax, word[A2-0x80]); sub(A2, -2); pinsrw(xmm0, eax, 0x1); pmovsxbw(xmm5, xmm0); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movd(dword[B-0x80], xmm0); sub(B, -4); align(4); L(l3638); test(M, 0x1); jle(l366c, T_NEAR); mov(al, byte[A1-0x80]); pinsrb(xmm0, eax, 0x0); mov(byte[B-0x80], al); mov(al, byte[A2-0x80]); pinsrb(xmm0, eax, 0x1); mov(byte[B-0x7f], al); sub(B, -2); pmovsxbd(xmm5, xmm0); paddd(xmm7, xmm5); align(4); L(l366c); mov(A1, qword[ARG_BIAS]); movq(qword[A1], xmm7); add(qword[ARG_BIAS], 0x8); sub(N, 0x2); cmp(N, 0x2); jge(l34a8, T_NEAR); align(4); L(l368a); cmp(N, 0x1); jl(l37d8, T_NEAR); align(4); L(l3694); mov(A1, A); add(A, LDA); pxor(xmm7, xmm7); mov(I, M); sar(I, 0x4); jle(l36ec, T_NEAR); align(4); L(l36a8); movdqu(xmm0, xword[A1-0x80]); sub(A1, -16); pmovsxbw(xmm5, xmm0); movhlps(xmm6, xmm0); pmovsxbw(xmm6, xmm6); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); phaddw(xmm5, xmm5); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movdqu(xword[B-0x80], xmm0); sub(B, -16); dec(I); jg(l36a8, T_NEAR); align(4); L(l36ec); test(M, 0x8); jle(l3728, T_NEAR); movq(xmm0, qword[A1-0x80]); sub(A1, -8); pmovsxbw(xmm5, xmm0); phaddw(xmm5, xmm6); phaddw(xmm5, xmm5); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l3728); test(M, 0x4); jle(l3760, T_NEAR); movd(xmm0, dword[A1-0x80]); sub(A1, -4); pmovsxbw(xmm5, xmm0); phaddw(xmm5, xmm5); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); movd(dword[B-0x80], xmm0); sub(B, -4); align(4); L(l3760); test(M, 0x2); jle(l3794, T_NEAR); mov(ax, word[A1-0x80]); pinsrw(xmm0, eax, 0x0); pmovsxbw(xmm5, xmm0); phaddw(xmm5, xmm5); pmovsxwd(xmm5, xmm5); paddd(xmm7, xmm5); mov(word[B-0x80], ax); sub(A1, -2); sub(B, -2); align(4); L(l3794); test(M, 0x1); jle(l37b8, T_NEAR); mov(al, byte[A1-0x80]); pinsrb(xmm0, eax, 0x0); pmovsxbd(xmm5, xmm0); paddd(xmm7, xmm5); mov(byte[B-0x80], al); sub(B, -1); align(4); L(l37b8); mov(A1, qword[ARG_BIAS]); movd(dword[A1], xmm7); add(qword[ARG_BIAS], 0x4); sub(N, 0x1); cmp(N, 0x1); jge(l3694, T_NEAR); align(4); L(l37d8); postamble(); } outLocalLabel(); #undef M #undef N #undef A #undef LDA #undef ALPHA #undef B #undef I #undef A1 #undef A2 #undef LDA3 #ifdef _WIN32 #undef ARG_ALPHA #undef ARG_B #endif #undef ARG_BIAS } } } }
honix/godot
thirdparty/oidn/mkl-dnn/src/cpu/gemm/s8x8s32/jit_avx512_core_u8_copy_sum_at_kern.cpp
C++
mit
76,165
// ======================================================================== // // Copyright 2009-2019 Intel 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. // // ======================================================================== // #pragma once #include "platform.h" #include <vector> #include <map> namespace oidn { template<typename T> using shared_vector = std::shared_ptr<std::vector<T>>; // Generic tensor struct Tensor { float* data; std::vector<int64_t> dims; std::string format; shared_vector<char> buffer; // optional, only for reference counting __forceinline Tensor() : data(nullptr) {} __forceinline Tensor(const std::vector<int64_t>& dims, const std::string& format) : dims(dims), format(format) { buffer = std::make_shared<std::vector<char>>(size() * sizeof(float)); data = (float*)buffer->data(); } __forceinline operator bool() const { return data != nullptr; } __forceinline int ndims() const { return (int)dims.size(); } // Returns the number of values __forceinline size_t size() const { size_t size = 1; for (int i = 0; i < ndims(); ++i) size *= dims[i]; return size; } __forceinline float& operator [](size_t i) { return data[i]; } __forceinline const float& operator [](size_t i) const { return data[i]; } }; // Parses tensors from a buffer std::map<std::string, Tensor> parseTensors(void* buffer); } // namespace oidn
Paulloz/godot
thirdparty/oidn/common/tensor.h
C
mit
2,439
export { ColorSwitch20 as default } from "../../";
georgemarshall/DefinitelyTyped
types/carbon__icons-react/es/color-switch/20.d.ts
TypeScript
mit
51
loadIonicon('<svg width="1em" height="1em" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M248.03 116.81l24.68-24.678 19.232 19.234-24.678 24.677zM176 125.7c-45.3 0-82.3 37-82.3 82.3 0 17.5 5.5 33.7 14.9 47 15.3-13 33.9-22.6 54.7-27.6l13.2-16.6c13.6-17.1 30.7-30.2 50.8-38.9 6.1-2.6 12.4-4.8 19-6.6-14.5-23.7-40.6-39.6-70.3-39.6zM162 64h28v41h-28zM32 194h41v28H32zM81.6 276.8l-.8-.8-24.7 24.7 19.2 19.2 24.7-24.7zM79.29 92.13l24.677 24.678-19.233 19.233-24.678-24.677zM405.6 288.6C394.7 233.4 346.2 192 288 192c-34 0-65.1 11.9-86.5 38.8 29.4 2.2 56.7 13 77.8 33.9 15.6 15.6 26.6 34.6 32.1 55.3h-28.7c-13.1-37.3-48-64-90.6-64-5.1 0-12.3.6-17.7 1.7C128.6 267.1 96 305 96 352c0 53 43 96 96 96h208c44.2 0 80-35.8 80-80 0-42.2-32.8-76.5-74.4-79.4z"/></svg>','md-partly-sunny');
sashberd/cdnjs
ajax/libs/ionicons/4.0.0-6/ionicons/svg/md-partly-sunny.js
JavaScript
mit
791
export { ChemistryReference20 as default } from "../../";
markogresak/DefinitelyTyped
types/carbon__icons-react/es/chemistry--reference/20.d.ts
TypeScript
mit
58
// 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 "base/time/time.h" #include "chrome/browser/extensions/activity_log/activity_action_constants.h" #include "chrome/browser/extensions/activity_log/uma_policy.h" #include "chrome/common/extensions/dom_action_types.h" #include "chrome/test/base/testing_profile.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { class UmaPolicyTest : public testing::Test { public: UmaPolicyTest() { profile_.reset(new TestingProfile()); } protected: scoped_ptr<TestingProfile> profile_; }; TEST_F(UmaPolicyTest, Construct) { ActivityLogPolicy* policy = new UmaPolicy(profile_.get()); policy->Close(); } TEST_F(UmaPolicyTest, MatchActionToStatusTest) { UmaPolicy* policy = new UmaPolicy(profile_.get()); scoped_refptr<Action> action = new Action( "id", base::Time::Now(), Action::ACTION_API_CALL, "extension.connect"); ASSERT_EQ(UmaPolicy::NONE, policy->MatchActionToStatus(action)); action = new Action( "id", base::Time::Now(), Action::ACTION_API_CALL, "tabs.executeScript"); ASSERT_EQ( (1 << UmaPolicy::CONTENT_SCRIPT), policy->MatchActionToStatus(action)); action = new Action( "id", base::Time::Now(), Action::ACTION_CONTENT_SCRIPT, ""); ASSERT_TRUE( (1 << UmaPolicy::CONTENT_SCRIPT) & policy->MatchActionToStatus(action)); ASSERT_EQ( (1 << UmaPolicy::CONTENT_SCRIPT), policy->MatchActionToStatus(action)); action = new Action( "id", base::Time::Now(), Action::ACTION_DOM_ACCESS, "Document.location"); action->mutable_other()->SetInteger(activity_log_constants::kActionDomVerb, DomActionType::GETTER); ASSERT_TRUE((1 << UmaPolicy::READ_DOM) & policy->MatchActionToStatus(action)); ASSERT_EQ((1 << UmaPolicy::READ_DOM), policy->MatchActionToStatus(action)); action->mutable_other()->SetInteger(activity_log_constants::kActionDomVerb, DomActionType::SETTER); ASSERT_TRUE( (1 << UmaPolicy::MODIFIED_DOM) & policy->MatchActionToStatus(action)); ASSERT_EQ( (1 << UmaPolicy::MODIFIED_DOM), policy->MatchActionToStatus(action)); action = new Action( "id", base::Time::Now(), Action::ACTION_DOM_ACCESS, "HTMLDocument.write"); action->mutable_other()->SetInteger(activity_log_constants::kActionDomVerb, DomActionType::METHOD); ASSERT_TRUE( (1 << UmaPolicy::DOCUMENT_WRITE) & policy->MatchActionToStatus(action)); ASSERT_TRUE( (1 << UmaPolicy::DOM_METHOD) & policy->MatchActionToStatus(action)); action = new Action("id", base::Time::Now(), Action::ACTION_DOM_ACCESS, "Document.createElement"); scoped_ptr<base::ListValue> args(new base::ListValue()); args->Set(0, new base::StringValue("script")); action->set_args(args.Pass()); ASSERT_EQ(UmaPolicy::NONE, policy->MatchActionToStatus(action)); action->mutable_other()->SetInteger(activity_log_constants::kActionDomVerb, DomActionType::METHOD); ASSERT_TRUE( (1 << UmaPolicy::CREATED_SCRIPT) & policy->MatchActionToStatus(action)); ASSERT_TRUE( (1 << UmaPolicy::DOM_METHOD) & policy->MatchActionToStatus(action)); policy->Close(); } TEST_F(UmaPolicyTest, SiteUrlTest) { UmaPolicy* policy = new UmaPolicy(profile_.get()); const std::string site0 = "http://www.zzz.com"; const std::string site1 = "http://www.foo.com"; const std::string site2 = "http://www.google.com#a"; const std::string site3 = "http://www.google.com#bb"; // Record some opened sites. policy->SetupOpenedPage(site1); policy->SetupOpenedPage(site2); policy->SetupOpenedPage(site2); policy->SetupOpenedPage(site3); policy->SetupOpenedPage(site3); policy->SetupOpenedPage(site3); // Check that site1, site2, and site3 were recorded. ASSERT_EQ(3u, policy->url_status().size()); ASSERT_EQ(1, policy->url_status()[site1][UmaPolicy::kNumberOfTabs]); ASSERT_EQ(2, policy->url_status()[site2][UmaPolicy::kNumberOfTabs]); ASSERT_EQ(3, policy->url_status()[site3][UmaPolicy::kNumberOfTabs]); // Remove some sites. policy->CleanupClosedPage(site0); policy->CleanupClosedPage(site2); policy->CleanupClosedPage(site2); policy->CleanupClosedPage(site3); // Check that the removal worked. ASSERT_EQ(2u, policy->url_status().size()); ASSERT_EQ(1, policy->url_status()[site1][UmaPolicy::kNumberOfTabs]); ASSERT_EQ(2, policy->url_status()[site3][UmaPolicy::kNumberOfTabs]); policy->Close(); } TEST_F(UmaPolicyTest, ProcessActionTest) { const std::string site_a = "http://www.zzz.com/"; const std::string site_b = "http://www.foo.com/"; const std::string ext_a = "a"; const std::string ext_b = "b"; UmaPolicy* policy = new UmaPolicy(profile_.get()); // Populate with a few different pages. policy->SetupOpenedPage(site_a); policy->SetupOpenedPage(site_b); // Process a few actions for site_a. scoped_refptr<Action> action1 = new Action( ext_a, base::Time::Now(), Action::ACTION_CONTENT_SCRIPT, ""); action1->set_page_url(GURL(site_a)); policy->ProcessAction(action1); scoped_refptr<Action> action2 = new Action( ext_a, base::Time::Now(), Action::ACTION_CONTENT_SCRIPT, ""); action2->set_page_url(GURL(site_a)); policy->ProcessAction(action2); scoped_refptr<Action> action3 = new Action( ext_b, base::Time::Now(), Action::ACTION_DOM_ACCESS, "Document.location"); action3->mutable_other()->SetInteger(activity_log_constants::kActionDomVerb, DomActionType::GETTER); action3->set_page_url(GURL(site_a)); policy->ProcessAction(action3); // Process an action for site_b. scoped_refptr<Action> action4 = new Action( ext_a, base::Time::Now(), Action::ACTION_DOM_ACCESS, "Document.location"); action4->mutable_other()->SetInteger(activity_log_constants::kActionDomVerb, DomActionType::SETTER); action4->set_page_url(GURL(site_b)); policy->ProcessAction(action4); scoped_refptr<Action> action5 = new Action( ext_b, base::Time::Now(), Action::ACTION_DOM_ACCESS, "Document.location"); action5->mutable_other()->SetInteger(activity_log_constants::kActionDomVerb, DomActionType::SETTER); action5->set_page_url(GURL(site_b)); policy->ProcessAction(action5); scoped_refptr<Action> action6 = new Action( ext_b, base::Time::Now(), Action::ACTION_API_CALL, "tabs.executeScript"); action6->set_arg_url(GURL(site_b)); policy->ProcessAction(action6); // Now check what's been recorded. ASSERT_EQ(2u, policy->url_status().size()); ASSERT_EQ(3u, policy->url_status()[site_a].size()); ASSERT_TRUE( (1 << UmaPolicy::CONTENT_SCRIPT) & policy->url_status()[site_a][ext_a]); ASSERT_FALSE( (1 << UmaPolicy::CONTENT_SCRIPT) & policy->url_status()[site_a][ext_b]); ASSERT_TRUE((1 << UmaPolicy::READ_DOM) & policy->url_status()[site_a][ext_b]); ASSERT_FALSE( (1 << UmaPolicy::READ_DOM) & policy->url_status()[site_a][ext_a]); ASSERT_EQ(3u, policy->url_status()[site_b].size()); ASSERT_TRUE( (1 << UmaPolicy::MODIFIED_DOM) & policy->url_status()[site_b][ext_a]); ASSERT_TRUE( (1 << UmaPolicy::MODIFIED_DOM) & policy->url_status()[site_b][ext_b]); ASSERT_TRUE( (1 << UmaPolicy::CONTENT_SCRIPT) & policy->url_status()[site_b][ext_b]); policy->Close(); } TEST_F(UmaPolicyTest, CleanURLTest) { ASSERT_EQ("http://www.google.com/", UmaPolicy::CleanURL(GURL("http://www.google.com/"))); ASSERT_EQ("http://www.google.com/", UmaPolicy::CleanURL(GURL("http://www.google.com"))); ASSERT_EQ("http://www.google.com:8080/a.html", UmaPolicy::CleanURL(GURL("http://www.google.com:8080/a.html"))); ASSERT_EQ("http://www.google.com/", UmaPolicy::CleanURL(GURL("http://www.google.com/#a"))); ASSERT_EQ("http://www.google.com/", UmaPolicy::CleanURL(GURL("http://www.google.com/#aaaa"))); ASSERT_EQ("http://www.google.com/?q=a", UmaPolicy::CleanURL(GURL("http://www.google.com/?q=a"))); ASSERT_EQ("http://www.cnn.com/", UmaPolicy::CleanURL(GURL("http://www.cnn.com/"))); ASSERT_EQ("http://www.cnn.com:8080/a.html", UmaPolicy::CleanURL(GURL("http://www.cnn.com:8080/a.html"))); ASSERT_EQ("http://www.cnn.com/", UmaPolicy::CleanURL(GURL("http://www.cnn.com"))); ASSERT_EQ("http://www.cnn.com/", UmaPolicy::CleanURL(GURL("http://www.cnn.com/#a"))); ASSERT_EQ("http://www.cnn.com/", UmaPolicy::CleanURL(GURL("http://www.cnn.com/#aaaa"))); ASSERT_EQ("http://www.cnn.com/?q=a", UmaPolicy::CleanURL(GURL("http://www.cnn.com/?q=a"))); } } // namespace extensions
qtekfun/htcDesire820Kernel
external/chromium_org/chrome/browser/extensions/activity_log/uma_policy_unittest.cc
C++
gpl-2.0
8,976
/* * checkgridheader.{cc,hh} -- element checks Grid header for correctness * (checksums, lengths) * Douglas S. J. De Couto * from checkipheader.{cc,hh} by Robert Morris * * Copyright (c) 1999-2000 Massachusetts Institute of Technology * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #include <click/args.hh> #include "checkgridheader.hh" #include <click/glue.hh> #include "grid.hh" #include <clicknet/ether.h> #include <clicknet/ip.h> CLICK_DECLS CheckGridHeader::CheckGridHeader() : _drops(0) { } CheckGridHeader::~CheckGridHeader() { } void CheckGridHeader::drop_it(Packet *p) { if (_drops == 0) click_chatter("CheckGridHeader %s: Grid checksum failed", name().c_str()); _drops++; if (noutputs() == 2) output(1).push(p); else p->kill(); } Packet * CheckGridHeader::simple_action(Packet *p) { grid_hdr *gh = (grid_hdr *) (p->data() + sizeof(click_ether)); if(p->length() < sizeof(click_ether) + sizeof(grid_hdr)) { #if 1 click_chatter("%s: packet truncated", name().c_str()); #endif goto bad; } unsigned int hlen, tlen; hlen = gh->hdr_len; tlen = ntohs(gh->total_len); /* grid header size keeps changing if(hlen < sizeof(grid_hdr)) goto bad; */ if (ntohl(gh->version) != grid_hdr::GRID_VERSION) { click_chatter ("%s: unknown grid version %x", name().c_str(), ntohl(gh->version)); p->kill(); return 0; } if (tlen + sizeof(click_ether) > p->length()) { /* can only check inequality, as short packets are padded to a minimum frame size for wavelan and ethernet */ #if 1 click_chatter("%s: bad packet size, wanted %d, only got %d", name().c_str(), tlen + sizeof(click_ether), p->length()); #endif goto bad; } if (click_in_cksum((unsigned char *) gh, tlen) != 0) { #if 1 click_chatter("%s: bad Grid checksum", name().c_str()); click_chatter("%s: length: %d, cksum: 0x%.4x", name().c_str(), p->length(), (unsigned long) ntohs(gh->cksum)); #endif goto bad; } return(p); bad: drop_it(p); return 0; } static String CheckGridHeader_read_drops(Element *xf, void *) { CheckGridHeader *f = (CheckGridHeader *)xf; return String(f->drops()) + "\n"; } void CheckGridHeader::add_handlers() { add_read_handler("drops", CheckGridHeader_read_drops, 0); } CLICK_ENDDECLS EXPORT_ELEMENT(CheckGridHeader)
NetSys/click
elements/grid/checkgridheader.cc
C++
gpl-2.0
2,941
/* SPDX-License-Identifier: GPL-2.0 */ /* * Block data types and constants. Directly include this file only to * break include dependency loop. */ #ifndef __LINUX_BLK_TYPES_H #define __LINUX_BLK_TYPES_H #include <linux/types.h> #include <linux/bvec.h> #include <linux/ktime.h> struct bio_set; struct bio; struct bio_integrity_payload; struct page; struct block_device; struct io_context; struct cgroup_subsys_state; typedef void (bio_end_io_t) (struct bio *); /* * Block error status values. See block/blk-core:blk_errors for the details. * Alpha cannot write a byte atomically, so we need to use 32-bit value. */ #if defined(CONFIG_ALPHA) && !defined(__alpha_bwx__) typedef u32 __bitwise blk_status_t; #else typedef u8 __bitwise blk_status_t; #endif #define BLK_STS_OK 0 #define BLK_STS_NOTSUPP ((__force blk_status_t)1) #define BLK_STS_TIMEOUT ((__force blk_status_t)2) #define BLK_STS_NOSPC ((__force blk_status_t)3) #define BLK_STS_TRANSPORT ((__force blk_status_t)4) #define BLK_STS_TARGET ((__force blk_status_t)5) #define BLK_STS_NEXUS ((__force blk_status_t)6) #define BLK_STS_MEDIUM ((__force blk_status_t)7) #define BLK_STS_PROTECTION ((__force blk_status_t)8) #define BLK_STS_RESOURCE ((__force blk_status_t)9) #define BLK_STS_IOERR ((__force blk_status_t)10) /* hack for device mapper, don't use elsewhere: */ #define BLK_STS_DM_REQUEUE ((__force blk_status_t)11) #define BLK_STS_AGAIN ((__force blk_status_t)12) /* * BLK_STS_DEV_RESOURCE is returned from the driver to the block layer if * device related resources are unavailable, but the driver can guarantee * that the queue will be rerun in the future once resources become * available again. This is typically the case for device specific * resources that are consumed for IO. If the driver fails allocating these * resources, we know that inflight (or pending) IO will free these * resource upon completion. * * This is different from BLK_STS_RESOURCE in that it explicitly references * a device specific resource. For resources of wider scope, allocation * failure can happen without having pending IO. This means that we can't * rely on request completions freeing these resources, as IO may not be in * flight. Examples of that are kernel memory allocations, DMA mappings, or * any other system wide resources. */ #define BLK_STS_DEV_RESOURCE ((__force blk_status_t)13) /** * blk_path_error - returns true if error may be path related * @error: status the request was completed with * * Description: * This classifies block error status into non-retryable errors and ones * that may be successful if retried on a failover path. * * Return: * %false - retrying failover path will not help * %true - may succeed if retried */ static inline bool blk_path_error(blk_status_t error) { switch (error) { case BLK_STS_NOTSUPP: case BLK_STS_NOSPC: case BLK_STS_TARGET: case BLK_STS_NEXUS: case BLK_STS_MEDIUM: case BLK_STS_PROTECTION: return false; } /* Anything else could be a path failure, so should be retried */ return true; } /* * From most significant bit: * 1 bit: reserved for other usage, see below * 12 bits: original size of bio * 51 bits: issue time of bio */ #define BIO_ISSUE_RES_BITS 1 #define BIO_ISSUE_SIZE_BITS 12 #define BIO_ISSUE_RES_SHIFT (64 - BIO_ISSUE_RES_BITS) #define BIO_ISSUE_SIZE_SHIFT (BIO_ISSUE_RES_SHIFT - BIO_ISSUE_SIZE_BITS) #define BIO_ISSUE_TIME_MASK ((1ULL << BIO_ISSUE_SIZE_SHIFT) - 1) #define BIO_ISSUE_SIZE_MASK \ (((1ULL << BIO_ISSUE_SIZE_BITS) - 1) << BIO_ISSUE_SIZE_SHIFT) #define BIO_ISSUE_RES_MASK (~((1ULL << BIO_ISSUE_RES_SHIFT) - 1)) /* Reserved bit for blk-throtl */ #define BIO_ISSUE_THROTL_SKIP_LATENCY (1ULL << 63) struct bio_issue { u64 value; }; static inline u64 __bio_issue_time(u64 time) { return time & BIO_ISSUE_TIME_MASK; } static inline u64 bio_issue_time(struct bio_issue *issue) { return __bio_issue_time(issue->value); } static inline sector_t bio_issue_size(struct bio_issue *issue) { return ((issue->value & BIO_ISSUE_SIZE_MASK) >> BIO_ISSUE_SIZE_SHIFT); } static inline void bio_issue_init(struct bio_issue *issue, sector_t size) { size &= (1ULL << BIO_ISSUE_SIZE_BITS) - 1; issue->value = ((issue->value & BIO_ISSUE_RES_MASK) | (ktime_get_ns() & BIO_ISSUE_TIME_MASK) | ((u64)size << BIO_ISSUE_SIZE_SHIFT)); } /* * main unit of I/O for the block layer and lower layers (ie drivers and * stacking drivers) */ struct bio { struct bio *bi_next; /* request queue link */ struct gendisk *bi_disk; unsigned int bi_opf; /* bottom bits req flags, * top bits REQ_OP. Use * accessors. */ unsigned short bi_flags; /* status, etc and bvec pool number */ unsigned short bi_ioprio; unsigned short bi_write_hint; blk_status_t bi_status; u8 bi_partno; /* Number of segments in this BIO after * physical address coalescing is performed. */ unsigned int bi_phys_segments; /* * To keep track of the max segment size, we account for the * sizes of the first and last mergeable segments in this bio. */ unsigned int bi_seg_front_size; unsigned int bi_seg_back_size; struct bvec_iter bi_iter; atomic_t __bi_remaining; bio_end_io_t *bi_end_io; void *bi_private; #ifdef CONFIG_BLK_CGROUP /* * Optional ioc and css associated with this bio. Put on bio * release. Read comment on top of bio_associate_current(). */ struct io_context *bi_ioc; struct cgroup_subsys_state *bi_css; struct blkcg_gq *bi_blkg; struct bio_issue bi_issue; #endif union { #if defined(CONFIG_BLK_DEV_INTEGRITY) struct bio_integrity_payload *bi_integrity; /* data integrity */ #endif }; unsigned short bi_vcnt; /* how many bio_vec's */ /* * Everything starting with bi_max_vecs will be preserved by bio_reset() */ unsigned short bi_max_vecs; /* max bvl_vecs we can hold */ atomic_t __bi_cnt; /* pin count */ struct bio_vec *bi_io_vec; /* the actual vec list */ struct bio_set *bi_pool; /* * We can inline a number of vecs at the end of the bio, to avoid * double allocations for a small number of bio_vecs. This member * MUST obviously be kept at the very end of the bio. */ struct bio_vec bi_inline_vecs[0]; }; #define BIO_RESET_BYTES offsetof(struct bio, bi_max_vecs) /* * bio flags */ #define BIO_SEG_VALID 1 /* bi_phys_segments valid */ #define BIO_CLONED 2 /* doesn't own data */ #define BIO_BOUNCED 3 /* bio is a bounce bio */ #define BIO_USER_MAPPED 4 /* contains user pages */ #define BIO_NULL_MAPPED 5 /* contains invalid user pages */ #define BIO_QUIET 6 /* Make BIO Quiet */ #define BIO_CHAIN 7 /* chained bio, ->bi_remaining in effect */ #define BIO_REFFED 8 /* bio has elevated ->bi_cnt */ #define BIO_THROTTLED 9 /* This bio has already been subjected to * throttling rules. Don't do it again. */ #define BIO_TRACE_COMPLETION 10 /* bio_endio() should trace the final completion * of this bio. */ #define BIO_QUEUE_ENTERED 11 /* can use blk_queue_enter_live() */ /* See BVEC_POOL_OFFSET below before adding new flags */ /* * We support 6 different bvec pools, the last one is magic in that it * is backed by a mempool. */ #define BVEC_POOL_NR 6 #define BVEC_POOL_MAX (BVEC_POOL_NR - 1) /* * Top 3 bits of bio flags indicate the pool the bvecs came from. We add * 1 to the actual index so that 0 indicates that there are no bvecs to be * freed. */ #define BVEC_POOL_BITS (3) #define BVEC_POOL_OFFSET (16 - BVEC_POOL_BITS) #define BVEC_POOL_IDX(bio) ((bio)->bi_flags >> BVEC_POOL_OFFSET) #if (1<< BVEC_POOL_BITS) < (BVEC_POOL_NR+1) # error "BVEC_POOL_BITS is too small" #endif /* * Flags starting here get preserved by bio_reset() - this includes * only BVEC_POOL_IDX() */ #define BIO_RESET_BITS BVEC_POOL_OFFSET typedef __u32 __bitwise blk_mq_req_flags_t; /* * Operations and flags common to the bio and request structures. * We use 8 bits for encoding the operation, and the remaining 24 for flags. * * The least significant bit of the operation number indicates the data * transfer direction: * * - if the least significant bit is set transfers are TO the device * - if the least significant bit is not set transfers are FROM the device * * If a operation does not transfer data the least significant bit has no * meaning. */ #define REQ_OP_BITS 8 #define REQ_OP_MASK ((1 << REQ_OP_BITS) - 1) #define REQ_FLAG_BITS 24 enum req_opf { /* read sectors from the device */ REQ_OP_READ = 0, /* write sectors to the device */ REQ_OP_WRITE = 1, /* flush the volatile write cache */ REQ_OP_FLUSH = 2, /* discard sectors */ REQ_OP_DISCARD = 3, /* get zone information */ REQ_OP_ZONE_REPORT = 4, /* securely erase sectors */ REQ_OP_SECURE_ERASE = 5, /* seset a zone write pointer */ REQ_OP_ZONE_RESET = 6, /* write the same sector many times */ REQ_OP_WRITE_SAME = 7, /* write the zero filled sector many times */ REQ_OP_WRITE_ZEROES = 9, /* SCSI passthrough using struct scsi_request */ REQ_OP_SCSI_IN = 32, REQ_OP_SCSI_OUT = 33, /* Driver private requests */ REQ_OP_DRV_IN = 34, REQ_OP_DRV_OUT = 35, REQ_OP_LAST, }; enum req_flag_bits { __REQ_FAILFAST_DEV = /* no driver retries of device errors */ REQ_OP_BITS, __REQ_FAILFAST_TRANSPORT, /* no driver retries of transport errors */ __REQ_FAILFAST_DRIVER, /* no driver retries of driver errors */ __REQ_SYNC, /* request is sync (sync write or read) */ __REQ_META, /* metadata io request */ __REQ_PRIO, /* boost priority in cfq */ __REQ_NOMERGE, /* don't touch this for merging */ __REQ_IDLE, /* anticipate more IO after this one */ __REQ_INTEGRITY, /* I/O includes block integrity payload */ __REQ_FUA, /* forced unit access */ __REQ_PREFLUSH, /* request for cache flush */ __REQ_RAHEAD, /* read ahead, can fail anytime */ __REQ_BACKGROUND, /* background IO */ __REQ_NOWAIT, /* Don't wait if request will block */ /* command specific flags for REQ_OP_WRITE_ZEROES: */ __REQ_NOUNMAP, /* do not free blocks when zeroing */ /* for driver use */ __REQ_DRV, __REQ_SWAP, /* swapping request. */ __REQ_NR_BITS, /* stops here */ }; #define REQ_FAILFAST_DEV (1ULL << __REQ_FAILFAST_DEV) #define REQ_FAILFAST_TRANSPORT (1ULL << __REQ_FAILFAST_TRANSPORT) #define REQ_FAILFAST_DRIVER (1ULL << __REQ_FAILFAST_DRIVER) #define REQ_SYNC (1ULL << __REQ_SYNC) #define REQ_META (1ULL << __REQ_META) #define REQ_PRIO (1ULL << __REQ_PRIO) #define REQ_NOMERGE (1ULL << __REQ_NOMERGE) #define REQ_IDLE (1ULL << __REQ_IDLE) #define REQ_INTEGRITY (1ULL << __REQ_INTEGRITY) #define REQ_FUA (1ULL << __REQ_FUA) #define REQ_PREFLUSH (1ULL << __REQ_PREFLUSH) #define REQ_RAHEAD (1ULL << __REQ_RAHEAD) #define REQ_BACKGROUND (1ULL << __REQ_BACKGROUND) #define REQ_NOWAIT (1ULL << __REQ_NOWAIT) #define REQ_NOUNMAP (1ULL << __REQ_NOUNMAP) #define REQ_DRV (1ULL << __REQ_DRV) #define REQ_SWAP (1ULL << __REQ_SWAP) #define REQ_FAILFAST_MASK \ (REQ_FAILFAST_DEV | REQ_FAILFAST_TRANSPORT | REQ_FAILFAST_DRIVER) #define REQ_NOMERGE_FLAGS \ (REQ_NOMERGE | REQ_PREFLUSH | REQ_FUA) enum stat_group { STAT_READ, STAT_WRITE, STAT_DISCARD, NR_STAT_GROUPS }; #define bio_op(bio) \ ((bio)->bi_opf & REQ_OP_MASK) #define req_op(req) \ ((req)->cmd_flags & REQ_OP_MASK) /* obsolete, don't use in new code */ static inline void bio_set_op_attrs(struct bio *bio, unsigned op, unsigned op_flags) { bio->bi_opf = op | op_flags; } static inline bool op_is_write(unsigned int op) { return (op & 1); } /* * Check if the bio or request is one that needs special treatment in the * flush state machine. */ static inline bool op_is_flush(unsigned int op) { return op & (REQ_FUA | REQ_PREFLUSH); } /* * Reads are always treated as synchronous, as are requests with the FUA or * PREFLUSH flag. Other operations may be marked as synchronous using the * REQ_SYNC flag. */ static inline bool op_is_sync(unsigned int op) { return (op & REQ_OP_MASK) == REQ_OP_READ || (op & (REQ_SYNC | REQ_FUA | REQ_PREFLUSH)); } static inline bool op_is_discard(unsigned int op) { return (op & REQ_OP_MASK) == REQ_OP_DISCARD; } static inline int op_stat_group(unsigned int op) { if (op_is_discard(op)) return STAT_DISCARD; return op_is_write(op); } typedef unsigned int blk_qc_t; #define BLK_QC_T_NONE -1U #define BLK_QC_T_SHIFT 16 #define BLK_QC_T_INTERNAL (1U << 31) static inline bool blk_qc_t_valid(blk_qc_t cookie) { return cookie != BLK_QC_T_NONE; } static inline blk_qc_t blk_tag_to_qc_t(unsigned int tag, unsigned int queue_num, bool internal) { blk_qc_t ret = tag | (queue_num << BLK_QC_T_SHIFT); if (internal) ret |= BLK_QC_T_INTERNAL; return ret; } static inline unsigned int blk_qc_t_to_queue_num(blk_qc_t cookie) { return (cookie & ~BLK_QC_T_INTERNAL) >> BLK_QC_T_SHIFT; } static inline unsigned int blk_qc_t_to_tag(blk_qc_t cookie) { return cookie & ((1u << BLK_QC_T_SHIFT) - 1); } static inline bool blk_qc_t_is_internal(blk_qc_t cookie) { return (cookie & BLK_QC_T_INTERNAL) != 0; } struct blk_rq_stat { u64 mean; u64 min; u64 max; u32 nr_samples; u64 batch; }; #endif /* __LINUX_BLK_TYPES_H */
BPI-SINOVOIP/BPI-Mainline-kernel
linux-4.19/include/linux/blk_types.h
C
gpl-2.0
13,164
/* * Adaptec AAC series RAID controller driver * (c) Copyright 2001 Red Hat Inc. * * based on the old aacraid driver that is.. * Adaptec aacraid device driver for Linux. * * Copyright (c) 2000-2010 Adaptec, Inc. * 2010-2015 PMC-Sierra, Inc. (aacraid@pmc-sierra.com) * 2016-2017 Microsemi Corp. (aacraid@microsemi.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, 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; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * * Module Name: * linit.c * * Abstract: Linux Driver entry module for Adaptec RAID Array Controller */ #include <linux/compat.h> #include <linux/blkdev.h> #include <linux/completion.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/pci.h> #include <linux/aer.h> #include <linux/pci-aspm.h> #include <linux/slab.h> #include <linux/mutex.h> #include <linux/spinlock.h> #include <linux/syscalls.h> #include <linux/delay.h> #include <linux/kthread.h> #include <scsi/scsi.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_device.h> #include <scsi/scsi_host.h> #include <scsi/scsi_tcq.h> #include <scsi/scsicam.h> #include <scsi/scsi_eh.h> #include "aacraid.h" #define AAC_DRIVER_VERSION "1.2.1" #ifndef AAC_DRIVER_BRANCH #define AAC_DRIVER_BRANCH "" #endif #define AAC_DRIVERNAME "aacraid" #ifdef AAC_DRIVER_BUILD #define _str(x) #x #define str(x) _str(x) #define AAC_DRIVER_FULL_VERSION AAC_DRIVER_VERSION "[" str(AAC_DRIVER_BUILD) "]" AAC_DRIVER_BRANCH #else #define AAC_DRIVER_FULL_VERSION AAC_DRIVER_VERSION AAC_DRIVER_BRANCH #endif MODULE_AUTHOR("Red Hat Inc and Adaptec"); MODULE_DESCRIPTION("Dell PERC2, 2/Si, 3/Si, 3/Di, " "Adaptec Advanced Raid Products, " "HP NetRAID-4M, IBM ServeRAID & ICP SCSI driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(AAC_DRIVER_FULL_VERSION); static DEFINE_MUTEX(aac_mutex); static LIST_HEAD(aac_devices); static int aac_cfg_major = AAC_CHARDEV_UNREGISTERED; char aac_driver_version[] = AAC_DRIVER_FULL_VERSION; /* * Because of the way Linux names scsi devices, the order in this table has * become important. Check for on-board Raid first, add-in cards second. * * Note: The last field is used to index into aac_drivers below. */ static const struct pci_device_id aac_pci_tbl[] = { { 0x1028, 0x0001, 0x1028, 0x0001, 0, 0, 0 }, /* PERC 2/Si (Iguana/PERC2Si) */ { 0x1028, 0x0002, 0x1028, 0x0002, 0, 0, 1 }, /* PERC 3/Di (Opal/PERC3Di) */ { 0x1028, 0x0003, 0x1028, 0x0003, 0, 0, 2 }, /* PERC 3/Si (SlimFast/PERC3Si */ { 0x1028, 0x0004, 0x1028, 0x00d0, 0, 0, 3 }, /* PERC 3/Di (Iguana FlipChip/PERC3DiF */ { 0x1028, 0x0002, 0x1028, 0x00d1, 0, 0, 4 }, /* PERC 3/Di (Viper/PERC3DiV) */ { 0x1028, 0x0002, 0x1028, 0x00d9, 0, 0, 5 }, /* PERC 3/Di (Lexus/PERC3DiL) */ { 0x1028, 0x000a, 0x1028, 0x0106, 0, 0, 6 }, /* PERC 3/Di (Jaguar/PERC3DiJ) */ { 0x1028, 0x000a, 0x1028, 0x011b, 0, 0, 7 }, /* PERC 3/Di (Dagger/PERC3DiD) */ { 0x1028, 0x000a, 0x1028, 0x0121, 0, 0, 8 }, /* PERC 3/Di (Boxster/PERC3DiB) */ { 0x9005, 0x0283, 0x9005, 0x0283, 0, 0, 9 }, /* catapult */ { 0x9005, 0x0284, 0x9005, 0x0284, 0, 0, 10 }, /* tomcat */ { 0x9005, 0x0285, 0x9005, 0x0286, 0, 0, 11 }, /* Adaptec 2120S (Crusader) */ { 0x9005, 0x0285, 0x9005, 0x0285, 0, 0, 12 }, /* Adaptec 2200S (Vulcan) */ { 0x9005, 0x0285, 0x9005, 0x0287, 0, 0, 13 }, /* Adaptec 2200S (Vulcan-2m) */ { 0x9005, 0x0285, 0x17aa, 0x0286, 0, 0, 14 }, /* Legend S220 (Legend Crusader) */ { 0x9005, 0x0285, 0x17aa, 0x0287, 0, 0, 15 }, /* Legend S230 (Legend Vulcan) */ { 0x9005, 0x0285, 0x9005, 0x0288, 0, 0, 16 }, /* Adaptec 3230S (Harrier) */ { 0x9005, 0x0285, 0x9005, 0x0289, 0, 0, 17 }, /* Adaptec 3240S (Tornado) */ { 0x9005, 0x0285, 0x9005, 0x028a, 0, 0, 18 }, /* ASR-2020ZCR SCSI PCI-X ZCR (Skyhawk) */ { 0x9005, 0x0285, 0x9005, 0x028b, 0, 0, 19 }, /* ASR-2025ZCR SCSI SO-DIMM PCI-X ZCR (Terminator) */ { 0x9005, 0x0286, 0x9005, 0x028c, 0, 0, 20 }, /* ASR-2230S + ASR-2230SLP PCI-X (Lancer) */ { 0x9005, 0x0286, 0x9005, 0x028d, 0, 0, 21 }, /* ASR-2130S (Lancer) */ { 0x9005, 0x0286, 0x9005, 0x029b, 0, 0, 22 }, /* AAR-2820SA (Intruder) */ { 0x9005, 0x0286, 0x9005, 0x029c, 0, 0, 23 }, /* AAR-2620SA (Intruder) */ { 0x9005, 0x0286, 0x9005, 0x029d, 0, 0, 24 }, /* AAR-2420SA (Intruder) */ { 0x9005, 0x0286, 0x9005, 0x029e, 0, 0, 25 }, /* ICP9024RO (Lancer) */ { 0x9005, 0x0286, 0x9005, 0x029f, 0, 0, 26 }, /* ICP9014RO (Lancer) */ { 0x9005, 0x0286, 0x9005, 0x02a0, 0, 0, 27 }, /* ICP9047MA (Lancer) */ { 0x9005, 0x0286, 0x9005, 0x02a1, 0, 0, 28 }, /* ICP9087MA (Lancer) */ { 0x9005, 0x0286, 0x9005, 0x02a3, 0, 0, 29 }, /* ICP5445AU (Hurricane44) */ { 0x9005, 0x0285, 0x9005, 0x02a4, 0, 0, 30 }, /* ICP9085LI (Marauder-X) */ { 0x9005, 0x0285, 0x9005, 0x02a5, 0, 0, 31 }, /* ICP5085BR (Marauder-E) */ { 0x9005, 0x0286, 0x9005, 0x02a6, 0, 0, 32 }, /* ICP9067MA (Intruder-6) */ { 0x9005, 0x0287, 0x9005, 0x0800, 0, 0, 33 }, /* Themisto Jupiter Platform */ { 0x9005, 0x0200, 0x9005, 0x0200, 0, 0, 33 }, /* Themisto Jupiter Platform */ { 0x9005, 0x0286, 0x9005, 0x0800, 0, 0, 34 }, /* Callisto Jupiter Platform */ { 0x9005, 0x0285, 0x9005, 0x028e, 0, 0, 35 }, /* ASR-2020SA SATA PCI-X ZCR (Skyhawk) */ { 0x9005, 0x0285, 0x9005, 0x028f, 0, 0, 36 }, /* ASR-2025SA SATA SO-DIMM PCI-X ZCR (Terminator) */ { 0x9005, 0x0285, 0x9005, 0x0290, 0, 0, 37 }, /* AAR-2410SA PCI SATA 4ch (Jaguar II) */ { 0x9005, 0x0285, 0x1028, 0x0291, 0, 0, 38 }, /* CERC SATA RAID 2 PCI SATA 6ch (DellCorsair) */ { 0x9005, 0x0285, 0x9005, 0x0292, 0, 0, 39 }, /* AAR-2810SA PCI SATA 8ch (Corsair-8) */ { 0x9005, 0x0285, 0x9005, 0x0293, 0, 0, 40 }, /* AAR-21610SA PCI SATA 16ch (Corsair-16) */ { 0x9005, 0x0285, 0x9005, 0x0294, 0, 0, 41 }, /* ESD SO-DIMM PCI-X SATA ZCR (Prowler) */ { 0x9005, 0x0285, 0x103C, 0x3227, 0, 0, 42 }, /* AAR-2610SA PCI SATA 6ch */ { 0x9005, 0x0285, 0x9005, 0x0296, 0, 0, 43 }, /* ASR-2240S (SabreExpress) */ { 0x9005, 0x0285, 0x9005, 0x0297, 0, 0, 44 }, /* ASR-4005 */ { 0x9005, 0x0285, 0x1014, 0x02F2, 0, 0, 45 }, /* IBM 8i (AvonPark) */ { 0x9005, 0x0285, 0x1014, 0x0312, 0, 0, 45 }, /* IBM 8i (AvonPark Lite) */ { 0x9005, 0x0286, 0x1014, 0x9580, 0, 0, 46 }, /* IBM 8k/8k-l8 (Aurora) */ { 0x9005, 0x0286, 0x1014, 0x9540, 0, 0, 47 }, /* IBM 8k/8k-l4 (Aurora Lite) */ { 0x9005, 0x0285, 0x9005, 0x0298, 0, 0, 48 }, /* ASR-4000 (BlackBird) */ { 0x9005, 0x0285, 0x9005, 0x0299, 0, 0, 49 }, /* ASR-4800SAS (Marauder-X) */ { 0x9005, 0x0285, 0x9005, 0x029a, 0, 0, 50 }, /* ASR-4805SAS (Marauder-E) */ { 0x9005, 0x0286, 0x9005, 0x02a2, 0, 0, 51 }, /* ASR-3800 (Hurricane44) */ { 0x9005, 0x0285, 0x1028, 0x0287, 0, 0, 52 }, /* Perc 320/DC*/ { 0x1011, 0x0046, 0x9005, 0x0365, 0, 0, 53 }, /* Adaptec 5400S (Mustang)*/ { 0x1011, 0x0046, 0x9005, 0x0364, 0, 0, 54 }, /* Adaptec 5400S (Mustang)*/ { 0x1011, 0x0046, 0x9005, 0x1364, 0, 0, 55 }, /* Dell PERC2/QC */ { 0x1011, 0x0046, 0x103c, 0x10c2, 0, 0, 56 }, /* HP NetRAID-4M */ { 0x9005, 0x0285, 0x1028, PCI_ANY_ID, 0, 0, 57 }, /* Dell Catchall */ { 0x9005, 0x0285, 0x17aa, PCI_ANY_ID, 0, 0, 58 }, /* Legend Catchall */ { 0x9005, 0x0285, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 59 }, /* Adaptec Catch All */ { 0x9005, 0x0286, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 60 }, /* Adaptec Rocket Catch All */ { 0x9005, 0x0288, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 61 }, /* Adaptec NEMER/ARK Catch All */ { 0x9005, 0x028b, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 62 }, /* Adaptec PMC Series 6 (Tupelo) */ { 0x9005, 0x028c, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 63 }, /* Adaptec PMC Series 7 (Denali) */ { 0x9005, 0x028d, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 64 }, /* Adaptec PMC Series 8 */ { 0,} }; MODULE_DEVICE_TABLE(pci, aac_pci_tbl); /* * dmb - For now we add the number of channels to this structure. * In the future we should add a fib that reports the number of channels * for the card. At that time we can remove the channels from here */ static struct aac_driver_ident aac_drivers[] = { { aac_rx_init, "percraid", "DELL ", "PERCRAID ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* PERC 2/Si (Iguana/PERC2Si) */ { aac_rx_init, "percraid", "DELL ", "PERCRAID ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* PERC 3/Di (Opal/PERC3Di) */ { aac_rx_init, "percraid", "DELL ", "PERCRAID ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* PERC 3/Si (SlimFast/PERC3Si */ { aac_rx_init, "percraid", "DELL ", "PERCRAID ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* PERC 3/Di (Iguana FlipChip/PERC3DiF */ { aac_rx_init, "percraid", "DELL ", "PERCRAID ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* PERC 3/Di (Viper/PERC3DiV) */ { aac_rx_init, "percraid", "DELL ", "PERCRAID ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* PERC 3/Di (Lexus/PERC3DiL) */ { aac_rx_init, "percraid", "DELL ", "PERCRAID ", 1, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* PERC 3/Di (Jaguar/PERC3DiJ) */ { aac_rx_init, "percraid", "DELL ", "PERCRAID ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* PERC 3/Di (Dagger/PERC3DiD) */ { aac_rx_init, "percraid", "DELL ", "PERCRAID ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* PERC 3/Di (Boxster/PERC3DiB) */ { aac_rx_init, "aacraid", "ADAPTEC ", "catapult ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* catapult */ { aac_rx_init, "aacraid", "ADAPTEC ", "tomcat ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* tomcat */ { aac_rx_init, "aacraid", "ADAPTEC ", "Adaptec 2120S ", 1, AAC_QUIRK_31BIT | AAC_QUIRK_34SG }, /* Adaptec 2120S (Crusader) */ { aac_rx_init, "aacraid", "ADAPTEC ", "Adaptec 2200S ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG }, /* Adaptec 2200S (Vulcan) */ { aac_rx_init, "aacraid", "ADAPTEC ", "Adaptec 2200S ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* Adaptec 2200S (Vulcan-2m) */ { aac_rx_init, "aacraid", "Legend ", "Legend S220 ", 1, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* Legend S220 (Legend Crusader) */ { aac_rx_init, "aacraid", "Legend ", "Legend S230 ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* Legend S230 (Legend Vulcan) */ { aac_rx_init, "aacraid", "ADAPTEC ", "Adaptec 3230S ", 2 }, /* Adaptec 3230S (Harrier) */ { aac_rx_init, "aacraid", "ADAPTEC ", "Adaptec 3240S ", 2 }, /* Adaptec 3240S (Tornado) */ { aac_rx_init, "aacraid", "ADAPTEC ", "ASR-2020ZCR ", 2 }, /* ASR-2020ZCR SCSI PCI-X ZCR (Skyhawk) */ { aac_rx_init, "aacraid", "ADAPTEC ", "ASR-2025ZCR ", 2 }, /* ASR-2025ZCR SCSI SO-DIMM PCI-X ZCR (Terminator) */ { aac_rkt_init, "aacraid", "ADAPTEC ", "ASR-2230S PCI-X ", 2 }, /* ASR-2230S + ASR-2230SLP PCI-X (Lancer) */ { aac_rkt_init, "aacraid", "ADAPTEC ", "ASR-2130S PCI-X ", 1 }, /* ASR-2130S (Lancer) */ { aac_rkt_init, "aacraid", "ADAPTEC ", "AAR-2820SA ", 1 }, /* AAR-2820SA (Intruder) */ { aac_rkt_init, "aacraid", "ADAPTEC ", "AAR-2620SA ", 1 }, /* AAR-2620SA (Intruder) */ { aac_rkt_init, "aacraid", "ADAPTEC ", "AAR-2420SA ", 1 }, /* AAR-2420SA (Intruder) */ { aac_rkt_init, "aacraid", "ICP ", "ICP9024RO ", 2 }, /* ICP9024RO (Lancer) */ { aac_rkt_init, "aacraid", "ICP ", "ICP9014RO ", 1 }, /* ICP9014RO (Lancer) */ { aac_rkt_init, "aacraid", "ICP ", "ICP9047MA ", 1 }, /* ICP9047MA (Lancer) */ { aac_rkt_init, "aacraid", "ICP ", "ICP9087MA ", 1 }, /* ICP9087MA (Lancer) */ { aac_rkt_init, "aacraid", "ICP ", "ICP5445AU ", 1 }, /* ICP5445AU (Hurricane44) */ { aac_rx_init, "aacraid", "ICP ", "ICP9085LI ", 1 }, /* ICP9085LI (Marauder-X) */ { aac_rx_init, "aacraid", "ICP ", "ICP5085BR ", 1 }, /* ICP5085BR (Marauder-E) */ { aac_rkt_init, "aacraid", "ICP ", "ICP9067MA ", 1 }, /* ICP9067MA (Intruder-6) */ { NULL , "aacraid", "ADAPTEC ", "Themisto ", 0, AAC_QUIRK_SLAVE }, /* Jupiter Platform */ { aac_rkt_init, "aacraid", "ADAPTEC ", "Callisto ", 2, AAC_QUIRK_MASTER }, /* Jupiter Platform */ { aac_rx_init, "aacraid", "ADAPTEC ", "ASR-2020SA ", 1 }, /* ASR-2020SA SATA PCI-X ZCR (Skyhawk) */ { aac_rx_init, "aacraid", "ADAPTEC ", "ASR-2025SA ", 1 }, /* ASR-2025SA SATA SO-DIMM PCI-X ZCR (Terminator) */ { aac_rx_init, "aacraid", "ADAPTEC ", "AAR-2410SA SATA ", 1, AAC_QUIRK_17SG }, /* AAR-2410SA PCI SATA 4ch (Jaguar II) */ { aac_rx_init, "aacraid", "DELL ", "CERC SR2 ", 1, AAC_QUIRK_17SG }, /* CERC SATA RAID 2 PCI SATA 6ch (DellCorsair) */ { aac_rx_init, "aacraid", "ADAPTEC ", "AAR-2810SA SATA ", 1, AAC_QUIRK_17SG }, /* AAR-2810SA PCI SATA 8ch (Corsair-8) */ { aac_rx_init, "aacraid", "ADAPTEC ", "AAR-21610SA SATA", 1, AAC_QUIRK_17SG }, /* AAR-21610SA PCI SATA 16ch (Corsair-16) */ { aac_rx_init, "aacraid", "ADAPTEC ", "ASR-2026ZCR ", 1 }, /* ESD SO-DIMM PCI-X SATA ZCR (Prowler) */ { aac_rx_init, "aacraid", "ADAPTEC ", "AAR-2610SA ", 1 }, /* SATA 6Ch (Bearcat) */ { aac_rx_init, "aacraid", "ADAPTEC ", "ASR-2240S ", 1 }, /* ASR-2240S (SabreExpress) */ { aac_rx_init, "aacraid", "ADAPTEC ", "ASR-4005 ", 1 }, /* ASR-4005 */ { aac_rx_init, "ServeRAID","IBM ", "ServeRAID 8i ", 1 }, /* IBM 8i (AvonPark) */ { aac_rkt_init, "ServeRAID","IBM ", "ServeRAID 8k-l8 ", 1 }, /* IBM 8k/8k-l8 (Aurora) */ { aac_rkt_init, "ServeRAID","IBM ", "ServeRAID 8k-l4 ", 1 }, /* IBM 8k/8k-l4 (Aurora Lite) */ { aac_rx_init, "aacraid", "ADAPTEC ", "ASR-4000 ", 1 }, /* ASR-4000 (BlackBird & AvonPark) */ { aac_rx_init, "aacraid", "ADAPTEC ", "ASR-4800SAS ", 1 }, /* ASR-4800SAS (Marauder-X) */ { aac_rx_init, "aacraid", "ADAPTEC ", "ASR-4805SAS ", 1 }, /* ASR-4805SAS (Marauder-E) */ { aac_rkt_init, "aacraid", "ADAPTEC ", "ASR-3800 ", 1 }, /* ASR-3800 (Hurricane44) */ { aac_rx_init, "percraid", "DELL ", "PERC 320/DC ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG }, /* Perc 320/DC*/ { aac_sa_init, "aacraid", "ADAPTEC ", "Adaptec 5400S ", 4, AAC_QUIRK_34SG }, /* Adaptec 5400S (Mustang)*/ { aac_sa_init, "aacraid", "ADAPTEC ", "AAC-364 ", 4, AAC_QUIRK_34SG }, /* Adaptec 5400S (Mustang)*/ { aac_sa_init, "percraid", "DELL ", "PERCRAID ", 4, AAC_QUIRK_34SG }, /* Dell PERC2/QC */ { aac_sa_init, "hpnraid", "HP ", "NetRAID ", 4, AAC_QUIRK_34SG }, /* HP NetRAID-4M */ { aac_rx_init, "aacraid", "DELL ", "RAID ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* Dell Catchall */ { aac_rx_init, "aacraid", "Legend ", "RAID ", 2, AAC_QUIRK_31BIT | AAC_QUIRK_34SG | AAC_QUIRK_SCSI_32 }, /* Legend Catchall */ { aac_rx_init, "aacraid", "ADAPTEC ", "RAID ", 2 }, /* Adaptec Catch All */ { aac_rkt_init, "aacraid", "ADAPTEC ", "RAID ", 2 }, /* Adaptec Rocket Catch All */ { aac_nark_init, "aacraid", "ADAPTEC ", "RAID ", 2 }, /* Adaptec NEMER/ARK Catch All */ { aac_src_init, "aacraid", "ADAPTEC ", "RAID ", 2, AAC_QUIRK_SRC }, /* Adaptec PMC Series 6 (Tupelo) */ { aac_srcv_init, "aacraid", "ADAPTEC ", "RAID ", 2, AAC_QUIRK_SRC }, /* Adaptec PMC Series 7 (Denali) */ { aac_srcv_init, "aacraid", "ADAPTEC ", "RAID ", 2, AAC_QUIRK_SRC }, /* Adaptec PMC Series 8 */ }; /** * aac_queuecommand - queue a SCSI command * @cmd: SCSI command to queue * @done: Function to call on command completion * * Queues a command for execution by the associated Host Adapter. * * TODO: unify with aac_scsi_cmd(). */ static int aac_queuecommand(struct Scsi_Host *shost, struct scsi_cmnd *cmd) { int r = 0; cmd->SCp.phase = AAC_OWNER_LOWLEVEL; r = (aac_scsi_cmd(cmd) ? FAILED : 0); return r; } /** * aac_info - Returns the host adapter name * @shost: Scsi host to report on * * Returns a static string describing the device in question */ static const char *aac_info(struct Scsi_Host *shost) { struct aac_dev *dev = (struct aac_dev *)shost->hostdata; return aac_drivers[dev->cardtype].name; } /** * aac_get_driver_ident * @devtype: index into lookup table * * Returns a pointer to the entry in the driver lookup table. */ struct aac_driver_ident* aac_get_driver_ident(int devtype) { return &aac_drivers[devtype]; } /** * aac_biosparm - return BIOS parameters for disk * @sdev: The scsi device corresponding to the disk * @bdev: the block device corresponding to the disk * @capacity: the sector capacity of the disk * @geom: geometry block to fill in * * Return the Heads/Sectors/Cylinders BIOS Disk Parameters for Disk. * The default disk geometry is 64 heads, 32 sectors, and the appropriate * number of cylinders so as not to exceed drive capacity. In order for * disks equal to or larger than 1 GB to be addressable by the BIOS * without exceeding the BIOS limitation of 1024 cylinders, Extended * Translation should be enabled. With Extended Translation enabled, * drives between 1 GB inclusive and 2 GB exclusive are given a disk * geometry of 128 heads and 32 sectors, and drives above 2 GB inclusive * are given a disk geometry of 255 heads and 63 sectors. However, if * the BIOS detects that the Extended Translation setting does not match * the geometry in the partition table, then the translation inferred * from the partition table will be used by the BIOS, and a warning may * be displayed. */ static int aac_biosparm(struct scsi_device *sdev, struct block_device *bdev, sector_t capacity, int *geom) { struct diskparm *param = (struct diskparm *)geom; unsigned char *buf; dprintk((KERN_DEBUG "aac_biosparm.\n")); /* * Assuming extended translation is enabled - #REVISIT# */ if (capacity >= 2 * 1024 * 1024) { /* 1 GB in 512 byte sectors */ if(capacity >= 4 * 1024 * 1024) { /* 2 GB in 512 byte sectors */ param->heads = 255; param->sectors = 63; } else { param->heads = 128; param->sectors = 32; } } else { param->heads = 64; param->sectors = 32; } param->cylinders = cap_to_cyls(capacity, param->heads * param->sectors); /* * Read the first 1024 bytes from the disk device, if the boot * sector partition table is valid, search for a partition table * entry whose end_head matches one of the standard geometry * translations ( 64/32, 128/32, 255/63 ). */ buf = scsi_bios_ptable(bdev); if (!buf) return 0; if(*(__le16 *)(buf + 0x40) == cpu_to_le16(0xaa55)) { struct partition *first = (struct partition * )buf; struct partition *entry = first; int saved_cylinders = param->cylinders; int num; unsigned char end_head, end_sec; for(num = 0; num < 4; num++) { end_head = entry->end_head; end_sec = entry->end_sector & 0x3f; if(end_head == 63) { param->heads = 64; param->sectors = 32; break; } else if(end_head == 127) { param->heads = 128; param->sectors = 32; break; } else if(end_head == 254) { param->heads = 255; param->sectors = 63; break; } entry++; } if (num == 4) { end_head = first->end_head; end_sec = first->end_sector & 0x3f; } param->cylinders = cap_to_cyls(capacity, param->heads * param->sectors); if (num < 4 && end_sec == param->sectors) { if (param->cylinders != saved_cylinders) dprintk((KERN_DEBUG "Adopting geometry: heads=%d, sectors=%d from partition table %d.\n", param->heads, param->sectors, num)); } else if (end_head > 0 || end_sec > 0) { dprintk((KERN_DEBUG "Strange geometry: heads=%d, sectors=%d in partition table %d.\n", end_head + 1, end_sec, num)); dprintk((KERN_DEBUG "Using geometry: heads=%d, sectors=%d.\n", param->heads, param->sectors)); } } kfree(buf); return 0; } /** * aac_slave_configure - compute queue depths * @sdev: SCSI device we are considering * * Selects queue depths for each target device based on the host adapter's * total capacity and the queue depth supported by the target device. * A queue depth of one automatically disables tagged queueing. */ static int aac_slave_configure(struct scsi_device *sdev) { struct aac_dev *aac = (struct aac_dev *)sdev->host->hostdata; int chn, tid; unsigned int depth = 0; unsigned int set_timeout = 0; bool set_qd_dev_type = false; u8 devtype = 0; chn = aac_logical_to_phys(sdev_channel(sdev)); tid = sdev_id(sdev); if (chn < AAC_MAX_BUSES && tid < AAC_MAX_TARGETS && aac->sa_firmware) { devtype = aac->hba_map[chn][tid].devtype; if (devtype == AAC_DEVTYPE_NATIVE_RAW) depth = aac->hba_map[chn][tid].qd_limit; else if (devtype == AAC_DEVTYPE_ARC_RAW) set_qd_dev_type = true; set_timeout = 1; goto common_config; } if (aac->jbod && (sdev->type == TYPE_DISK)) sdev->removable = 1; if (sdev->type == TYPE_DISK && sdev_channel(sdev) != CONTAINER_CHANNEL && (!aac->jbod || sdev->inq_periph_qual) && (!aac->raid_scsi_mode || (sdev_channel(sdev) != 2))) { if (expose_physicals == 0) return -ENXIO; if (expose_physicals < 0) sdev->no_uld_attach = 1; } if (sdev->tagged_supported && sdev->type == TYPE_DISK && (!aac->raid_scsi_mode || (sdev_channel(sdev) != 2)) && !sdev->no_uld_attach) { struct scsi_device * dev; struct Scsi_Host *host = sdev->host; unsigned num_lsu = 0; unsigned num_one = 0; unsigned cid; set_timeout = 1; for (cid = 0; cid < aac->maximum_num_containers; ++cid) if (aac->fsa_dev[cid].valid) ++num_lsu; __shost_for_each_device(dev, host) { if (dev->tagged_supported && dev->type == TYPE_DISK && (!aac->raid_scsi_mode || (sdev_channel(sdev) != 2)) && !dev->no_uld_attach) { if ((sdev_channel(dev) != CONTAINER_CHANNEL) || !aac->fsa_dev[sdev_id(dev)].valid) { ++num_lsu; } } else { ++num_one; } } if (num_lsu == 0) ++num_lsu; depth = (host->can_queue - num_one) / num_lsu; if (sdev_channel(sdev) != NATIVE_CHANNEL) goto common_config; set_qd_dev_type = true; } common_config: /* * Check if SATA drive */ if (set_qd_dev_type) { if (strncmp(sdev->vendor, "ATA", 3) == 0) depth = 32; else depth = 64; } /* * Firmware has an individual device recovery time typically * of 35 seconds, give us a margin. */ if (set_timeout && sdev->request_queue->rq_timeout < (45 * HZ)) blk_queue_rq_timeout(sdev->request_queue, 45*HZ); if (depth > 256) depth = 256; else if (depth < 1) depth = 1; scsi_change_queue_depth(sdev, depth); sdev->tagged_supported = 1; return 0; } /** * aac_change_queue_depth - alter queue depths * @sdev: SCSI device we are considering * @depth: desired queue depth * * Alters queue depths for target device based on the host adapter's * total capacity and the queue depth supported by the target device. */ static int aac_change_queue_depth(struct scsi_device *sdev, int depth) { struct aac_dev *aac = (struct aac_dev *)(sdev->host->hostdata); int chn, tid, is_native_device = 0; chn = aac_logical_to_phys(sdev_channel(sdev)); tid = sdev_id(sdev); if (chn < AAC_MAX_BUSES && tid < AAC_MAX_TARGETS && aac->hba_map[chn][tid].devtype == AAC_DEVTYPE_NATIVE_RAW) is_native_device = 1; if (sdev->tagged_supported && (sdev->type == TYPE_DISK) && (sdev_channel(sdev) == CONTAINER_CHANNEL)) { struct scsi_device * dev; struct Scsi_Host *host = sdev->host; unsigned num = 0; __shost_for_each_device(dev, host) { if (dev->tagged_supported && (dev->type == TYPE_DISK) && (sdev_channel(dev) == CONTAINER_CHANNEL)) ++num; ++num; } if (num >= host->can_queue) num = host->can_queue - 1; if (depth > (host->can_queue - num)) depth = host->can_queue - num; if (depth > 256) depth = 256; else if (depth < 2) depth = 2; return scsi_change_queue_depth(sdev, depth); } else if (is_native_device) { scsi_change_queue_depth(sdev, aac->hba_map[chn][tid].qd_limit); } else { scsi_change_queue_depth(sdev, 1); } return sdev->queue_depth; } static ssize_t aac_show_raid_level(struct device *dev, struct device_attribute *attr, char *buf) { struct scsi_device *sdev = to_scsi_device(dev); struct aac_dev *aac = (struct aac_dev *)(sdev->host->hostdata); if (sdev_channel(sdev) != CONTAINER_CHANNEL) return snprintf(buf, PAGE_SIZE, sdev->no_uld_attach ? "Hidden\n" : ((aac->jbod && (sdev->type == TYPE_DISK)) ? "JBOD\n" : "")); return snprintf(buf, PAGE_SIZE, "%s\n", get_container_type(aac->fsa_dev[sdev_id(sdev)].type)); } static struct device_attribute aac_raid_level_attr = { .attr = { .name = "level", .mode = S_IRUGO, }, .show = aac_show_raid_level }; static ssize_t aac_show_unique_id(struct device *dev, struct device_attribute *attr, char *buf) { struct scsi_device *sdev = to_scsi_device(dev); struct aac_dev *aac = (struct aac_dev *)(sdev->host->hostdata); unsigned char sn[16]; memset(sn, 0, sizeof(sn)); if (sdev_channel(sdev) == CONTAINER_CHANNEL) memcpy(sn, aac->fsa_dev[sdev_id(sdev)].identifier, sizeof(sn)); return snprintf(buf, 16 * 2 + 2, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X\n", sn[0], sn[1], sn[2], sn[3], sn[4], sn[5], sn[6], sn[7], sn[8], sn[9], sn[10], sn[11], sn[12], sn[13], sn[14], sn[15]); } static struct device_attribute aac_unique_id_attr = { .attr = { .name = "unique_id", .mode = 0444, }, .show = aac_show_unique_id }; static struct device_attribute *aac_dev_attrs[] = { &aac_raid_level_attr, &aac_unique_id_attr, NULL, }; static int aac_ioctl(struct scsi_device *sdev, int cmd, void __user * arg) { struct aac_dev *dev = (struct aac_dev *)sdev->host->hostdata; if (!capable(CAP_SYS_RAWIO)) return -EPERM; return aac_do_ioctl(dev, cmd, arg); } static int get_num_of_incomplete_fibs(struct aac_dev *aac) { unsigned long flags; struct scsi_device *sdev = NULL; struct Scsi_Host *shost = aac->scsi_host_ptr; struct scsi_cmnd *scmnd = NULL; struct device *ctrl_dev; int mlcnt = 0; int llcnt = 0; int ehcnt = 0; int fwcnt = 0; int krlcnt = 0; __shost_for_each_device(sdev, shost) { spin_lock_irqsave(&sdev->list_lock, flags); list_for_each_entry(scmnd, &sdev->cmd_list, list) { switch (scmnd->SCp.phase) { case AAC_OWNER_FIRMWARE: fwcnt++; break; case AAC_OWNER_ERROR_HANDLER: ehcnt++; break; case AAC_OWNER_LOWLEVEL: llcnt++; break; case AAC_OWNER_MIDLEVEL: mlcnt++; break; default: krlcnt++; break; } } spin_unlock_irqrestore(&sdev->list_lock, flags); } ctrl_dev = &aac->pdev->dev; dev_info(ctrl_dev, "outstanding cmd: midlevel-%d\n", mlcnt); dev_info(ctrl_dev, "outstanding cmd: lowlevel-%d\n", llcnt); dev_info(ctrl_dev, "outstanding cmd: error handler-%d\n", ehcnt); dev_info(ctrl_dev, "outstanding cmd: firmware-%d\n", fwcnt); dev_info(ctrl_dev, "outstanding cmd: kernel-%d\n", krlcnt); return mlcnt + llcnt + ehcnt + fwcnt; } static int aac_eh_abort(struct scsi_cmnd* cmd) { struct scsi_device * dev = cmd->device; struct Scsi_Host * host = dev->host; struct aac_dev * aac = (struct aac_dev *)host->hostdata; int count, found; u32 bus, cid; int ret = FAILED; bus = aac_logical_to_phys(scmd_channel(cmd)); cid = scmd_id(cmd); if (aac->hba_map[bus][cid].devtype == AAC_DEVTYPE_NATIVE_RAW) { struct fib *fib; struct aac_hba_tm_req *tmf; int status; u64 address; __le32 managed_request_id; pr_err("%s: Host adapter abort request (%d,%d,%d,%d)\n", AAC_DRIVERNAME, host->host_no, sdev_channel(dev), sdev_id(dev), (int)dev->lun); found = 0; for (count = 0; count < (host->can_queue + AAC_NUM_MGT_FIB); ++count) { fib = &aac->fibs[count]; if (*(u8 *)fib->hw_fib_va != 0 && (fib->flags & FIB_CONTEXT_FLAG_NATIVE_HBA) && (fib->callback_data == cmd)) { found = 1; managed_request_id = ((struct aac_hba_cmd_req *) fib->hw_fib_va)->request_id; break; } } if (!found) return ret; /* start a HBA_TMF_ABORT_TASK TMF request */ fib = aac_fib_alloc(aac); if (!fib) return ret; tmf = (struct aac_hba_tm_req *)fib->hw_fib_va; memset(tmf, 0, sizeof(*tmf)); tmf->tmf = HBA_TMF_ABORT_TASK; tmf->it_nexus = aac->hba_map[bus][cid].rmw_nexus; tmf->lun[1] = cmd->device->lun; address = (u64)fib->hw_error_pa; tmf->error_ptr_hi = cpu_to_le32((u32)(address >> 32)); tmf->error_ptr_lo = cpu_to_le32((u32)(address & 0xffffffff)); tmf->error_length = cpu_to_le32(FW_ERROR_BUFFER_SIZE); fib->hbacmd_size = sizeof(*tmf); cmd->SCp.sent_command = 0; status = aac_hba_send(HBA_IU_TYPE_SCSI_TM_REQ, fib, (fib_callback) aac_hba_callback, (void *) cmd); /* Wait up to 15 secs for completion */ for (count = 0; count < 15; ++count) { if (cmd->SCp.sent_command) { ret = SUCCESS; break; } msleep(1000); } if (ret != SUCCESS) pr_err("%s: Host adapter abort request timed out\n", AAC_DRIVERNAME); } else { pr_err( "%s: Host adapter abort request.\n" "%s: Outstanding commands on (%d,%d,%d,%d):\n", AAC_DRIVERNAME, AAC_DRIVERNAME, host->host_no, sdev_channel(dev), sdev_id(dev), (int)dev->lun); switch (cmd->cmnd[0]) { case SERVICE_ACTION_IN_16: if (!(aac->raw_io_interface) || !(aac->raw_io_64) || ((cmd->cmnd[1] & 0x1f) != SAI_READ_CAPACITY_16)) break; case INQUIRY: case READ_CAPACITY: /* * Mark associated FIB to not complete, * eh handler does this */ for (count = 0; count < (host->can_queue + AAC_NUM_MGT_FIB); ++count) { struct fib *fib = &aac->fibs[count]; if (fib->hw_fib_va->header.XferState && (fib->flags & FIB_CONTEXT_FLAG) && (fib->callback_data == cmd)) { fib->flags |= FIB_CONTEXT_FLAG_TIMED_OUT; cmd->SCp.phase = AAC_OWNER_ERROR_HANDLER; ret = SUCCESS; } } break; case TEST_UNIT_READY: /* * Mark associated FIB to not complete, * eh handler does this */ for (count = 0; count < (host->can_queue + AAC_NUM_MGT_FIB); ++count) { struct scsi_cmnd *command; struct fib *fib = &aac->fibs[count]; command = fib->callback_data; if ((fib->hw_fib_va->header.XferState & cpu_to_le32 (Async | NoResponseExpected)) && (fib->flags & FIB_CONTEXT_FLAG) && ((command)) && (command->device == cmd->device)) { fib->flags |= FIB_CONTEXT_FLAG_TIMED_OUT; command->SCp.phase = AAC_OWNER_ERROR_HANDLER; if (command == cmd) ret = SUCCESS; } } break; } } return ret; } /* * aac_eh_reset - Reset command handling * @scsi_cmd: SCSI command block causing the reset * */ static int aac_eh_reset(struct scsi_cmnd* cmd) { struct scsi_device * dev = cmd->device; struct Scsi_Host * host = dev->host; struct aac_dev * aac = (struct aac_dev *)host->hostdata; int count; u32 bus, cid; int ret = FAILED; int status = 0; __le32 supported_options2 = 0; bool is_mu_reset; bool is_ignore_reset; bool is_doorbell_reset; bus = aac_logical_to_phys(scmd_channel(cmd)); cid = scmd_id(cmd); if (bus < AAC_MAX_BUSES && cid < AAC_MAX_TARGETS && aac->hba_map[bus][cid].devtype == AAC_DEVTYPE_NATIVE_RAW) { struct fib *fib; int status; u64 address; u8 command; pr_err("%s: Host adapter reset request. SCSI hang ?\n", AAC_DRIVERNAME); fib = aac_fib_alloc(aac); if (!fib) return ret; if (aac->hba_map[bus][cid].reset_state == 0) { struct aac_hba_tm_req *tmf; /* start a HBA_TMF_LUN_RESET TMF request */ tmf = (struct aac_hba_tm_req *)fib->hw_fib_va; memset(tmf, 0, sizeof(*tmf)); tmf->tmf = HBA_TMF_LUN_RESET; tmf->it_nexus = aac->hba_map[bus][cid].rmw_nexus; tmf->lun[1] = cmd->device->lun; address = (u64)fib->hw_error_pa; tmf->error_ptr_hi = cpu_to_le32 ((u32)(address >> 32)); tmf->error_ptr_lo = cpu_to_le32 ((u32)(address & 0xffffffff)); tmf->error_length = cpu_to_le32(FW_ERROR_BUFFER_SIZE); fib->hbacmd_size = sizeof(*tmf); command = HBA_IU_TYPE_SCSI_TM_REQ; aac->hba_map[bus][cid].reset_state++; } else if (aac->hba_map[bus][cid].reset_state >= 1) { struct aac_hba_reset_req *rst; /* already tried, start a hard reset now */ rst = (struct aac_hba_reset_req *)fib->hw_fib_va; memset(rst, 0, sizeof(*rst)); /* reset_type is already zero... */ rst->it_nexus = aac->hba_map[bus][cid].rmw_nexus; address = (u64)fib->hw_error_pa; rst->error_ptr_hi = cpu_to_le32((u32)(address >> 32)); rst->error_ptr_lo = cpu_to_le32 ((u32)(address & 0xffffffff)); rst->error_length = cpu_to_le32(FW_ERROR_BUFFER_SIZE); fib->hbacmd_size = sizeof(*rst); command = HBA_IU_TYPE_SATA_REQ; aac->hba_map[bus][cid].reset_state = 0; } cmd->SCp.sent_command = 0; status = aac_hba_send(command, fib, (fib_callback) aac_hba_callback, (void *) cmd); /* Wait up to 15 seconds for completion */ for (count = 0; count < 15; ++count) { if (cmd->SCp.sent_command) { ret = SUCCESS; break; } msleep(1000); } if (ret == SUCCESS) goto out; } else { /* Mark the assoc. FIB to not complete, eh handler does this */ for (count = 0; count < (host->can_queue + AAC_NUM_MGT_FIB); ++count) { struct fib *fib = &aac->fibs[count]; if (fib->hw_fib_va->header.XferState && (fib->flags & FIB_CONTEXT_FLAG) && (fib->callback_data == cmd)) { fib->flags |= FIB_CONTEXT_FLAG_TIMED_OUT; cmd->SCp.phase = AAC_OWNER_ERROR_HANDLER; } } } pr_err("%s: Host adapter reset request. SCSI hang ?\n", AAC_DRIVERNAME); /* * Check the health of the controller */ status = aac_adapter_check_health(aac); if (status) dev_err(&aac->pdev->dev, "Adapter health - %d\n", status); count = get_num_of_incomplete_fibs(aac); if (count == 0) return SUCCESS; /* * Check if reset is supported by the firmware */ supported_options2 = aac->supplement_adapter_info.supported_options2; is_mu_reset = supported_options2 & AAC_OPTION_MU_RESET; is_doorbell_reset = supported_options2 & AAC_OPTION_DOORBELL_RESET; is_ignore_reset = supported_options2 & AAC_OPTION_IGNORE_RESET; /* * This adapter needs a blind reset, only do so for * Adapters that support a register, instead of a commanded, * reset. */ if ((is_mu_reset || is_doorbell_reset) && aac_check_reset && (aac_check_reset != -1 || !is_ignore_reset)) { /* Bypass wait for command quiesce */ aac_reset_adapter(aac, 2, IOP_HWSOFT_RESET); } ret = SUCCESS; out: return ret; } /** * aac_cfg_open - open a configuration file * @inode: inode being opened * @file: file handle attached * * Called when the configuration device is opened. Does the needed * set up on the handle and then returns * * Bugs: This needs extending to check a given adapter is present * so we can support hot plugging, and to ref count adapters. */ static int aac_cfg_open(struct inode *inode, struct file *file) { struct aac_dev *aac; unsigned minor_number = iminor(inode); int err = -ENODEV; mutex_lock(&aac_mutex); /* BKL pushdown: nothing else protects this list */ list_for_each_entry(aac, &aac_devices, entry) { if (aac->id == minor_number) { file->private_data = aac; err = 0; break; } } mutex_unlock(&aac_mutex); return err; } /** * aac_cfg_ioctl - AAC configuration request * @inode: inode of device * @file: file handle * @cmd: ioctl command code * @arg: argument * * Handles a configuration ioctl. Currently this involves wrapping it * up and feeding it into the nasty windowsalike glue layer. * * Bugs: Needs locking against parallel ioctls lower down * Bugs: Needs to handle hot plugging */ static long aac_cfg_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct aac_dev *aac = (struct aac_dev *)file->private_data; if (!capable(CAP_SYS_RAWIO)) return -EPERM; return aac_do_ioctl(aac, cmd, (void __user *)arg); } #ifdef CONFIG_COMPAT static long aac_compat_do_ioctl(struct aac_dev *dev, unsigned cmd, unsigned long arg) { long ret; switch (cmd) { case FSACTL_MINIPORT_REV_CHECK: case FSACTL_SENDFIB: case FSACTL_OPEN_GET_ADAPTER_FIB: case FSACTL_CLOSE_GET_ADAPTER_FIB: case FSACTL_SEND_RAW_SRB: case FSACTL_GET_PCI_INFO: case FSACTL_QUERY_DISK: case FSACTL_DELETE_DISK: case FSACTL_FORCE_DELETE_DISK: case FSACTL_GET_CONTAINERS: case FSACTL_SEND_LARGE_FIB: ret = aac_do_ioctl(dev, cmd, (void __user *)arg); break; case FSACTL_GET_NEXT_ADAPTER_FIB: { struct fib_ioctl __user *f; f = compat_alloc_user_space(sizeof(*f)); ret = 0; if (clear_user(f, sizeof(*f))) ret = -EFAULT; if (copy_in_user(f, (void __user *)arg, sizeof(struct fib_ioctl) - sizeof(u32))) ret = -EFAULT; if (!ret) ret = aac_do_ioctl(dev, cmd, f); break; } default: ret = -ENOIOCTLCMD; break; } return ret; } static int aac_compat_ioctl(struct scsi_device *sdev, int cmd, void __user *arg) { struct aac_dev *dev = (struct aac_dev *)sdev->host->hostdata; if (!capable(CAP_SYS_RAWIO)) return -EPERM; return aac_compat_do_ioctl(dev, cmd, (unsigned long)arg); } static long aac_compat_cfg_ioctl(struct file *file, unsigned cmd, unsigned long arg) { if (!capable(CAP_SYS_RAWIO)) return -EPERM; return aac_compat_do_ioctl(file->private_data, cmd, arg); } #endif static ssize_t aac_show_model(struct device *device, struct device_attribute *attr, char *buf) { struct aac_dev *dev = (struct aac_dev*)class_to_shost(device)->hostdata; int len; if (dev->supplement_adapter_info.adapter_type_text[0]) { char *cp = dev->supplement_adapter_info.adapter_type_text; while (*cp && *cp != ' ') ++cp; while (*cp == ' ') ++cp; len = snprintf(buf, PAGE_SIZE, "%s\n", cp); } else len = snprintf(buf, PAGE_SIZE, "%s\n", aac_drivers[dev->cardtype].model); return len; } static ssize_t aac_show_vendor(struct device *device, struct device_attribute *attr, char *buf) { struct aac_dev *dev = (struct aac_dev*)class_to_shost(device)->hostdata; struct aac_supplement_adapter_info *sup_adap_info; int len; sup_adap_info = &dev->supplement_adapter_info; if (sup_adap_info->adapter_type_text[0]) { char *cp = sup_adap_info->adapter_type_text; while (*cp && *cp != ' ') ++cp; len = snprintf(buf, PAGE_SIZE, "%.*s\n", (int)(cp - (char *)sup_adap_info->adapter_type_text), sup_adap_info->adapter_type_text); } else len = snprintf(buf, PAGE_SIZE, "%s\n", aac_drivers[dev->cardtype].vname); return len; } static ssize_t aac_show_flags(struct device *cdev, struct device_attribute *attr, char *buf) { int len = 0; struct aac_dev *dev = (struct aac_dev*)class_to_shost(cdev)->hostdata; if (nblank(dprintk(x))) len = snprintf(buf, PAGE_SIZE, "dprintk\n"); #ifdef AAC_DETAILED_STATUS_INFO len += snprintf(buf + len, PAGE_SIZE - len, "AAC_DETAILED_STATUS_INFO\n"); #endif if (dev->raw_io_interface && dev->raw_io_64) len += snprintf(buf + len, PAGE_SIZE - len, "SAI_READ_CAPACITY_16\n"); if (dev->jbod) len += snprintf(buf + len, PAGE_SIZE - len, "SUPPORTED_JBOD\n"); if (dev->supplement_adapter_info.supported_options2 & AAC_OPTION_POWER_MANAGEMENT) len += snprintf(buf + len, PAGE_SIZE - len, "SUPPORTED_POWER_MANAGEMENT\n"); if (dev->msi) len += snprintf(buf + len, PAGE_SIZE - len, "PCI_HAS_MSI\n"); return len; } static ssize_t aac_show_kernel_version(struct device *device, struct device_attribute *attr, char *buf) { struct aac_dev *dev = (struct aac_dev*)class_to_shost(device)->hostdata; int len, tmp; tmp = le32_to_cpu(dev->adapter_info.kernelrev); len = snprintf(buf, PAGE_SIZE, "%d.%d-%d[%d]\n", tmp >> 24, (tmp >> 16) & 0xff, tmp & 0xff, le32_to_cpu(dev->adapter_info.kernelbuild)); return len; } static ssize_t aac_show_monitor_version(struct device *device, struct device_attribute *attr, char *buf) { struct aac_dev *dev = (struct aac_dev*)class_to_shost(device)->hostdata; int len, tmp; tmp = le32_to_cpu(dev->adapter_info.monitorrev); len = snprintf(buf, PAGE_SIZE, "%d.%d-%d[%d]\n", tmp >> 24, (tmp >> 16) & 0xff, tmp & 0xff, le32_to_cpu(dev->adapter_info.monitorbuild)); return len; } static ssize_t aac_show_bios_version(struct device *device, struct device_attribute *attr, char *buf) { struct aac_dev *dev = (struct aac_dev*)class_to_shost(device)->hostdata; int len, tmp; tmp = le32_to_cpu(dev->adapter_info.biosrev); len = snprintf(buf, PAGE_SIZE, "%d.%d-%d[%d]\n", tmp >> 24, (tmp >> 16) & 0xff, tmp & 0xff, le32_to_cpu(dev->adapter_info.biosbuild)); return len; } static ssize_t aac_show_driver_version(struct device *device, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%s\n", aac_driver_version); } static ssize_t aac_show_serial_number(struct device *device, struct device_attribute *attr, char *buf) { struct aac_dev *dev = (struct aac_dev*)class_to_shost(device)->hostdata; int len = 0; if (le32_to_cpu(dev->adapter_info.serial[0]) != 0xBAD0) len = snprintf(buf, 16, "%06X\n", le32_to_cpu(dev->adapter_info.serial[0])); if (len && !memcmp(&dev->supplement_adapter_info.mfg_pcba_serial_no[ sizeof(dev->supplement_adapter_info.mfg_pcba_serial_no)-len], buf, len-1)) len = snprintf(buf, 16, "%.*s\n", (int)sizeof(dev->supplement_adapter_info.mfg_pcba_serial_no), dev->supplement_adapter_info.mfg_pcba_serial_no); return min(len, 16); } static ssize_t aac_show_max_channel(struct device *device, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", class_to_shost(device)->max_channel); } static ssize_t aac_show_max_id(struct device *device, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", class_to_shost(device)->max_id); } static ssize_t aac_store_reset_adapter(struct device *device, struct device_attribute *attr, const char *buf, size_t count) { int retval = -EACCES; int bled = 0; struct aac_dev *aac; if (!capable(CAP_SYS_ADMIN)) return retval; aac = (struct aac_dev *)class_to_shost(device)->hostdata; bled = buf[0] == '!' ? 1:0; retval = aac_reset_adapter(aac, bled, IOP_HWSOFT_RESET); if (retval >= 0) retval = count; return retval; } static ssize_t aac_show_reset_adapter(struct device *device, struct device_attribute *attr, char *buf) { struct aac_dev *dev = (struct aac_dev*)class_to_shost(device)->hostdata; int len, tmp; tmp = aac_adapter_check_health(dev); if ((tmp == 0) && dev->in_reset) tmp = -EBUSY; len = snprintf(buf, PAGE_SIZE, "0x%x\n", tmp); return len; } static struct device_attribute aac_model = { .attr = { .name = "model", .mode = S_IRUGO, }, .show = aac_show_model, }; static struct device_attribute aac_vendor = { .attr = { .name = "vendor", .mode = S_IRUGO, }, .show = aac_show_vendor, }; static struct device_attribute aac_flags = { .attr = { .name = "flags", .mode = S_IRUGO, }, .show = aac_show_flags, }; static struct device_attribute aac_kernel_version = { .attr = { .name = "hba_kernel_version", .mode = S_IRUGO, }, .show = aac_show_kernel_version, }; static struct device_attribute aac_monitor_version = { .attr = { .name = "hba_monitor_version", .mode = S_IRUGO, }, .show = aac_show_monitor_version, }; static struct device_attribute aac_bios_version = { .attr = { .name = "hba_bios_version", .mode = S_IRUGO, }, .show = aac_show_bios_version, }; static struct device_attribute aac_lld_version = { .attr = { .name = "driver_version", .mode = 0444, }, .show = aac_show_driver_version, }; static struct device_attribute aac_serial_number = { .attr = { .name = "serial_number", .mode = S_IRUGO, }, .show = aac_show_serial_number, }; static struct device_attribute aac_max_channel = { .attr = { .name = "max_channel", .mode = S_IRUGO, }, .show = aac_show_max_channel, }; static struct device_attribute aac_max_id = { .attr = { .name = "max_id", .mode = S_IRUGO, }, .show = aac_show_max_id, }; static struct device_attribute aac_reset = { .attr = { .name = "reset_host", .mode = S_IWUSR|S_IRUGO, }, .store = aac_store_reset_adapter, .show = aac_show_reset_adapter, }; static struct device_attribute *aac_attrs[] = { &aac_model, &aac_vendor, &aac_flags, &aac_kernel_version, &aac_monitor_version, &aac_bios_version, &aac_lld_version, &aac_serial_number, &aac_max_channel, &aac_max_id, &aac_reset, NULL }; ssize_t aac_get_serial_number(struct device *device, char *buf) { return aac_show_serial_number(device, &aac_serial_number, buf); } static const struct file_operations aac_cfg_fops = { .owner = THIS_MODULE, .unlocked_ioctl = aac_cfg_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = aac_compat_cfg_ioctl, #endif .open = aac_cfg_open, .llseek = noop_llseek, }; static struct scsi_host_template aac_driver_template = { .module = THIS_MODULE, .name = "AAC", .proc_name = AAC_DRIVERNAME, .info = aac_info, .ioctl = aac_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = aac_compat_ioctl, #endif .queuecommand = aac_queuecommand, .bios_param = aac_biosparm, .shost_attrs = aac_attrs, .slave_configure = aac_slave_configure, .change_queue_depth = aac_change_queue_depth, .sdev_attrs = aac_dev_attrs, .eh_abort_handler = aac_eh_abort, .eh_host_reset_handler = aac_eh_reset, .can_queue = AAC_NUM_IO_FIB, .this_id = MAXIMUM_NUM_CONTAINERS, .sg_tablesize = 16, .max_sectors = 128, #if (AAC_NUM_IO_FIB > 256) .cmd_per_lun = 256, #else .cmd_per_lun = AAC_NUM_IO_FIB, #endif .use_clustering = ENABLE_CLUSTERING, .emulated = 1, .no_write_same = 1, }; static void __aac_shutdown(struct aac_dev * aac) { int i; aac->adapter_shutdown = 1; aac_send_shutdown(aac); if (aac->aif_thread) { int i; /* Clear out events first */ for (i = 0; i < (aac->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB); i++) { struct fib *fib = &aac->fibs[i]; if (!(fib->hw_fib_va->header.XferState & cpu_to_le32(NoResponseExpected | Async)) && (fib->hw_fib_va->header.XferState & cpu_to_le32(ResponseExpected))) up(&fib->event_wait); } kthread_stop(aac->thread); } aac_adapter_disable_int(aac); if (aac_is_src(aac)) { if (aac->max_msix > 1) { for (i = 0; i < aac->max_msix; i++) { free_irq(pci_irq_vector(aac->pdev, i), &(aac->aac_msix[i])); } } else { free_irq(aac->pdev->irq, &(aac->aac_msix[0])); } } else { free_irq(aac->pdev->irq, aac); } if (aac->msi) pci_disable_msi(aac->pdev); else if (aac->max_msix > 1) pci_disable_msix(aac->pdev); } static void aac_init_char(void) { aac_cfg_major = register_chrdev(0, "aac", &aac_cfg_fops); if (aac_cfg_major < 0) { pr_err("aacraid: unable to register \"aac\" device.\n"); } } static int aac_probe_one(struct pci_dev *pdev, const struct pci_device_id *id) { unsigned index = id->driver_data; struct Scsi_Host *shost; struct aac_dev *aac; struct list_head *insert = &aac_devices; int error = -ENODEV; int unique_id = 0; u64 dmamask; int mask_bits = 0; extern int aac_sync_mode; /* * Only series 7 needs freset. */ if (pdev->device == PMC_DEVICE_S7) pdev->needs_freset = 1; list_for_each_entry(aac, &aac_devices, entry) { if (aac->id > unique_id) break; insert = &aac->entry; unique_id++; } pci_disable_link_state(pdev, PCIE_LINK_STATE_L0S | PCIE_LINK_STATE_L1 | PCIE_LINK_STATE_CLKPM); error = pci_enable_device(pdev); if (error) goto out; error = -ENODEV; if (!(aac_drivers[index].quirks & AAC_QUIRK_SRC)) { error = pci_set_dma_mask(pdev, DMA_BIT_MASK(32)); if (error) { dev_err(&pdev->dev, "PCI 32 BIT dma mask set failed"); goto out_disable_pdev; } } /* * If the quirk31 bit is set, the adapter needs adapter * to driver communication memory to be allocated below 2gig */ if (aac_drivers[index].quirks & AAC_QUIRK_31BIT) { dmamask = DMA_BIT_MASK(31); mask_bits = 31; } else { dmamask = DMA_BIT_MASK(32); mask_bits = 32; } error = pci_set_consistent_dma_mask(pdev, dmamask); if (error) { dev_err(&pdev->dev, "PCI %d B consistent dma mask set failed\n" , mask_bits); goto out_disable_pdev; } pci_set_master(pdev); shost = scsi_host_alloc(&aac_driver_template, sizeof(struct aac_dev)); if (!shost) goto out_disable_pdev; shost->irq = pdev->irq; shost->unique_id = unique_id; shost->max_cmd_len = 16; shost->use_cmd_list = 1; if (aac_cfg_major == AAC_CHARDEV_NEEDS_REINIT) aac_init_char(); aac = (struct aac_dev *)shost->hostdata; aac->base_start = pci_resource_start(pdev, 0); aac->scsi_host_ptr = shost; aac->pdev = pdev; aac->name = aac_driver_template.name; aac->id = shost->unique_id; aac->cardtype = index; INIT_LIST_HEAD(&aac->entry); aac->fibs = kzalloc(sizeof(struct fib) * (shost->can_queue + AAC_NUM_MGT_FIB), GFP_KERNEL); if (!aac->fibs) goto out_free_host; spin_lock_init(&aac->fib_lock); mutex_init(&aac->ioctl_mutex); /* * Map in the registers from the adapter. */ aac->base_size = AAC_MIN_FOOTPRINT_SIZE; if ((*aac_drivers[index].init)(aac)) goto out_unmap; if (aac->sync_mode) { if (aac_sync_mode) printk(KERN_INFO "%s%d: Sync. mode enforced " "by driver parameter. This will cause " "a significant performance decrease!\n", aac->name, aac->id); else printk(KERN_INFO "%s%d: Async. mode not supported " "by current driver, sync. mode enforced." "\nPlease update driver to get full performance.\n", aac->name, aac->id); } /* * Start any kernel threads needed */ aac->thread = kthread_run(aac_command_thread, aac, AAC_DRIVERNAME); if (IS_ERR(aac->thread)) { printk(KERN_ERR "aacraid: Unable to create command thread.\n"); error = PTR_ERR(aac->thread); aac->thread = NULL; goto out_deinit; } aac->maximum_num_channels = aac_drivers[index].channels; error = aac_get_adapter_info(aac); if (error < 0) goto out_deinit; /* * Lets override negotiations and drop the maximum SG limit to 34 */ if ((aac_drivers[index].quirks & AAC_QUIRK_34SG) && (shost->sg_tablesize > 34)) { shost->sg_tablesize = 34; shost->max_sectors = (shost->sg_tablesize * 8) + 112; } if ((aac_drivers[index].quirks & AAC_QUIRK_17SG) && (shost->sg_tablesize > 17)) { shost->sg_tablesize = 17; shost->max_sectors = (shost->sg_tablesize * 8) + 112; } error = pci_set_dma_max_seg_size(pdev, (aac->adapter_info.options & AAC_OPT_NEW_COMM) ? (shost->max_sectors << 9) : 65536); if (error) goto out_deinit; /* * Firmware printf works only with older firmware. */ if (aac_drivers[index].quirks & AAC_QUIRK_34SG) aac->printf_enabled = 1; else aac->printf_enabled = 0; /* * max channel will be the physical channels plus 1 virtual channel * all containers are on the virtual channel 0 (CONTAINER_CHANNEL) * physical channels are address by their actual physical number+1 */ if (aac->nondasd_support || expose_physicals || aac->jbod) shost->max_channel = aac->maximum_num_channels; else shost->max_channel = 0; aac_get_config_status(aac, 0); aac_get_containers(aac); list_add(&aac->entry, insert); shost->max_id = aac->maximum_num_containers; if (shost->max_id < aac->maximum_num_physicals) shost->max_id = aac->maximum_num_physicals; if (shost->max_id < MAXIMUM_NUM_CONTAINERS) shost->max_id = MAXIMUM_NUM_CONTAINERS; else shost->this_id = shost->max_id; if (!aac->sa_firmware && aac_drivers[index].quirks & AAC_QUIRK_SRC) aac_intr_normal(aac, 0, 2, 0, NULL); /* * dmb - we may need to move the setting of these parms somewhere else once * we get a fib that can report the actual numbers */ shost->max_lun = AAC_MAX_LUN; pci_set_drvdata(pdev, shost); error = scsi_add_host(shost, &pdev->dev); if (error) goto out_deinit; scsi_scan_host(shost); pci_enable_pcie_error_reporting(pdev); pci_save_state(pdev); return 0; out_deinit: __aac_shutdown(aac); out_unmap: aac_fib_map_free(aac); if (aac->comm_addr) dma_free_coherent(&aac->pdev->dev, aac->comm_size, aac->comm_addr, aac->comm_phys); kfree(aac->queues); aac_adapter_ioremap(aac, 0); kfree(aac->fibs); kfree(aac->fsa_dev); out_free_host: scsi_host_put(shost); out_disable_pdev: pci_disable_device(pdev); out: return error; } static void aac_release_resources(struct aac_dev *aac) { aac_adapter_disable_int(aac); aac_free_irq(aac); } static int aac_acquire_resources(struct aac_dev *dev) { unsigned long status; /* * First clear out all interrupts. Then enable the one's that we * can handle. */ while (!((status = src_readl(dev, MUnit.OMR)) & KERNEL_UP_AND_RUNNING) || status == 0xffffffff) msleep(20); aac_adapter_disable_int(dev); aac_adapter_enable_int(dev); if (aac_is_src(dev)) aac_define_int_mode(dev); if (dev->msi_enabled) aac_src_access_devreg(dev, AAC_ENABLE_MSIX); if (aac_acquire_irq(dev)) goto error_iounmap; aac_adapter_enable_int(dev); /*max msix may change after EEH * Re-assign vectors to fibs */ aac_fib_vector_assign(dev); if (!dev->sync_mode) { /* After EEH recovery or suspend resume, max_msix count * may change, therefore updating in init as well. */ dev->init->r7.no_of_msix_vectors = cpu_to_le32(dev->max_msix); aac_adapter_start(dev); } return 0; error_iounmap: return -1; } #if (defined(CONFIG_PM)) static int aac_suspend(struct pci_dev *pdev, pm_message_t state) { struct Scsi_Host *shost = pci_get_drvdata(pdev); struct aac_dev *aac = (struct aac_dev *)shost->hostdata; scsi_block_requests(shost); aac_send_shutdown(aac); aac_release_resources(aac); pci_set_drvdata(pdev, shost); pci_save_state(pdev); pci_disable_device(pdev); pci_set_power_state(pdev, pci_choose_state(pdev, state)); return 0; } static int aac_resume(struct pci_dev *pdev) { struct Scsi_Host *shost = pci_get_drvdata(pdev); struct aac_dev *aac = (struct aac_dev *)shost->hostdata; int r; pci_set_power_state(pdev, PCI_D0); pci_enable_wake(pdev, PCI_D0, 0); pci_restore_state(pdev); r = pci_enable_device(pdev); if (r) goto fail_device; pci_set_master(pdev); if (aac_acquire_resources(aac)) goto fail_device; /* * reset this flag to unblock ioctl() as it was set at * aac_send_shutdown() to block ioctls from upperlayer */ aac->adapter_shutdown = 0; scsi_unblock_requests(shost); return 0; fail_device: printk(KERN_INFO "%s%d: resume failed.\n", aac->name, aac->id); scsi_host_put(shost); pci_disable_device(pdev); return -ENODEV; } #endif static void aac_shutdown(struct pci_dev *dev) { struct Scsi_Host *shost = pci_get_drvdata(dev); scsi_block_requests(shost); __aac_shutdown((struct aac_dev *)shost->hostdata); } static void aac_remove_one(struct pci_dev *pdev) { struct Scsi_Host *shost = pci_get_drvdata(pdev); struct aac_dev *aac = (struct aac_dev *)shost->hostdata; scsi_remove_host(shost); __aac_shutdown(aac); aac_fib_map_free(aac); dma_free_coherent(&aac->pdev->dev, aac->comm_size, aac->comm_addr, aac->comm_phys); kfree(aac->queues); aac_adapter_ioremap(aac, 0); kfree(aac->fibs); kfree(aac->fsa_dev); list_del(&aac->entry); scsi_host_put(shost); pci_disable_device(pdev); if (list_empty(&aac_devices)) { unregister_chrdev(aac_cfg_major, "aac"); aac_cfg_major = AAC_CHARDEV_NEEDS_REINIT; } } static void aac_flush_ios(struct aac_dev *aac) { int i; struct scsi_cmnd *cmd; for (i = 0; i < aac->scsi_host_ptr->can_queue; i++) { cmd = (struct scsi_cmnd *)aac->fibs[i].callback_data; if (cmd && (cmd->SCp.phase == AAC_OWNER_FIRMWARE)) { scsi_dma_unmap(cmd); if (aac->handle_pci_error) cmd->result = DID_NO_CONNECT << 16; else cmd->result = DID_RESET << 16; cmd->scsi_done(cmd); } } } static pci_ers_result_t aac_pci_error_detected(struct pci_dev *pdev, enum pci_channel_state error) { struct Scsi_Host *shost = pci_get_drvdata(pdev); struct aac_dev *aac = shost_priv(shost); dev_err(&pdev->dev, "aacraid: PCI error detected %x\n", error); switch (error) { case pci_channel_io_normal: return PCI_ERS_RESULT_CAN_RECOVER; case pci_channel_io_frozen: aac->handle_pci_error = 1; scsi_block_requests(aac->scsi_host_ptr); aac_flush_ios(aac); aac_release_resources(aac); pci_disable_pcie_error_reporting(pdev); aac_adapter_ioremap(aac, 0); return PCI_ERS_RESULT_NEED_RESET; case pci_channel_io_perm_failure: aac->handle_pci_error = 1; aac_flush_ios(aac); return PCI_ERS_RESULT_DISCONNECT; } return PCI_ERS_RESULT_NEED_RESET; } static pci_ers_result_t aac_pci_mmio_enabled(struct pci_dev *pdev) { dev_err(&pdev->dev, "aacraid: PCI error - mmio enabled\n"); return PCI_ERS_RESULT_NEED_RESET; } static pci_ers_result_t aac_pci_slot_reset(struct pci_dev *pdev) { dev_err(&pdev->dev, "aacraid: PCI error - slot reset\n"); pci_restore_state(pdev); if (pci_enable_device(pdev)) { dev_warn(&pdev->dev, "aacraid: failed to enable slave\n"); goto fail_device; } pci_set_master(pdev); if (pci_enable_device_mem(pdev)) { dev_err(&pdev->dev, "pci_enable_device_mem failed\n"); goto fail_device; } return PCI_ERS_RESULT_RECOVERED; fail_device: dev_err(&pdev->dev, "aacraid: PCI error - slot reset failed\n"); return PCI_ERS_RESULT_DISCONNECT; } static void aac_pci_resume(struct pci_dev *pdev) { struct Scsi_Host *shost = pci_get_drvdata(pdev); struct scsi_device *sdev = NULL; struct aac_dev *aac = (struct aac_dev *)shost_priv(shost); pci_cleanup_aer_uncorrect_error_status(pdev); if (aac_adapter_ioremap(aac, aac->base_size)) { dev_err(&pdev->dev, "aacraid: ioremap failed\n"); /* remap failed, go back ... */ aac->comm_interface = AAC_COMM_PRODUCER; if (aac_adapter_ioremap(aac, AAC_MIN_FOOTPRINT_SIZE)) { dev_warn(&pdev->dev, "aacraid: unable to map adapter.\n"); return; } } msleep(10000); aac_acquire_resources(aac); /* * reset this flag to unblock ioctl() as it was set * at aac_send_shutdown() to block ioctls from upperlayer */ aac->adapter_shutdown = 0; aac->handle_pci_error = 0; shost_for_each_device(sdev, shost) if (sdev->sdev_state == SDEV_OFFLINE) sdev->sdev_state = SDEV_RUNNING; scsi_unblock_requests(aac->scsi_host_ptr); scsi_scan_host(aac->scsi_host_ptr); pci_save_state(pdev); dev_err(&pdev->dev, "aacraid: PCI error - resume\n"); } static struct pci_error_handlers aac_pci_err_handler = { .error_detected = aac_pci_error_detected, .mmio_enabled = aac_pci_mmio_enabled, .slot_reset = aac_pci_slot_reset, .resume = aac_pci_resume, }; static struct pci_driver aac_pci_driver = { .name = AAC_DRIVERNAME, .id_table = aac_pci_tbl, .probe = aac_probe_one, .remove = aac_remove_one, #if (defined(CONFIG_PM)) .suspend = aac_suspend, .resume = aac_resume, #endif .shutdown = aac_shutdown, .err_handler = &aac_pci_err_handler, }; static int __init aac_init(void) { int error; printk(KERN_INFO "Adaptec %s driver %s\n", AAC_DRIVERNAME, aac_driver_version); error = pci_register_driver(&aac_pci_driver); if (error < 0) return error; aac_init_char(); return 0; } static void __exit aac_exit(void) { if (aac_cfg_major > -1) unregister_chrdev(aac_cfg_major, "aac"); pci_unregister_driver(&aac_pci_driver); } module_init(aac_init); module_exit(aac_exit);
bw-oss/linux
drivers/scsi/aacraid/linit.c
C
gpl-2.0
59,827
/* $XFree86: xc/lib/GL/dri/dri_util.h,v 1.1 2002/02/22 21:32:52 dawes Exp $ */ /** * \file dri_util.h * DRI utility functions definitions. * * This module acts as glue between GLX and the actual hardware driver. A DRI * driver doesn't really \e have to use any of this - it's optional. But, some * useful stuff is done here that otherwise would have to be duplicated in most * drivers. * * Basically, these utility functions take care of some of the dirty details of * screen initialization, context creation, context binding, DRM setup, etc. * * These functions are compiled into each DRI driver so libGL.so knows nothing * about them. * * \sa dri_util.c. * * \author Kevin E. Martin <kevin@precisioninsight.com> * \author Brian Paul <brian@precisioninsight.com> */ /* * Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _DRI_UTIL_H_ #define _DRI_UTIL_H_ #include <GL/gl.h> #include <drm.h> #include <drm_sarea.h> #include <xf86drm.h> #include "glheader.h" #include "GL/internal/glcore.h" #include "GL/internal/dri_interface.h" #include "GL/internal/dri_sarea.h" #define GLX_BAD_CONTEXT 5 typedef struct __DRIswapInfoRec __DRIswapInfo; /* Typedefs to avoid rewriting the world. */ typedef struct __DRIscreenRec __DRIscreenPrivate; typedef struct __DRIdrawableRec __DRIdrawablePrivate; typedef struct __DRIcontextRec __DRIcontextPrivate; /** * Extensions. */ extern const __DRIlegacyExtension driLegacyExtension; extern const __DRIcoreExtension driCoreExtension; extern const __DRIextension driReadDrawableExtension; extern const __DRIcopySubBufferExtension driCopySubBufferExtension; extern const __DRIswapControlExtension driSwapControlExtension; extern const __DRIframeTrackingExtension driFrameTrackingExtension; extern const __DRImediaStreamCounterExtension driMediaStreamCounterExtension; /** * Used by DRI_VALIDATE_DRAWABLE_INFO */ #define DRI_VALIDATE_DRAWABLE_INFO_ONCE(pDrawPriv) \ do { \ if (*(pDrawPriv->pStamp) != pDrawPriv->lastStamp) { \ __driUtilUpdateDrawableInfo(pDrawPriv); \ } \ } while (0) /** * Utility macro to validate the drawable information. * * See __DRIdrawable::pStamp and __DRIdrawable::lastStamp. */ #define DRI_VALIDATE_DRAWABLE_INFO(psp, pdp) \ do { \ while (*(pdp->pStamp) != pdp->lastStamp) { \ register unsigned int hwContext = psp->pSAREA->lock.lock & \ ~(DRM_LOCK_HELD | DRM_LOCK_CONT); \ DRM_UNLOCK(psp->fd, &psp->pSAREA->lock, hwContext); \ \ DRM_SPINLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID); \ DRI_VALIDATE_DRAWABLE_INFO_ONCE(pdp); \ DRM_SPINUNLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID); \ \ DRM_LIGHT_LOCK(psp->fd, &psp->pSAREA->lock, hwContext); \ } \ } while (0) /** * Driver callback functions. * * Each DRI driver must have one of these structures with all the pointers set * to appropriate functions within the driver. * * When glXCreateContext() is called, for example, it'll call a helper function * dri_util.c which in turn will jump through the \a CreateContext pointer in * this structure. */ struct __DriverAPIRec { const __DRIconfig **(*InitScreen) (__DRIscreen * priv); /** * Screen destruction callback */ void (*DestroyScreen)(__DRIscreen *driScrnPriv); /** * Context creation callback */ GLboolean (*CreateContext)(const __GLcontextModes *glVis, __DRIcontext *driContextPriv, void *sharedContextPrivate); /** * Context destruction callback */ void (*DestroyContext)(__DRIcontext *driContextPriv); /** * Buffer (drawable) creation callback */ GLboolean (*CreateBuffer)(__DRIscreen *driScrnPriv, __DRIdrawable *driDrawPriv, const __GLcontextModes *glVis, GLboolean pixmapBuffer); /** * Buffer (drawable) destruction callback */ void (*DestroyBuffer)(__DRIdrawable *driDrawPriv); /** * Buffer swapping callback */ void (*SwapBuffers)(__DRIdrawable *driDrawPriv); /** * Context activation callback */ GLboolean (*MakeCurrent)(__DRIcontext *driContextPriv, __DRIdrawable *driDrawPriv, __DRIdrawable *driReadPriv); /** * Context unbinding callback */ GLboolean (*UnbindContext)(__DRIcontext *driContextPriv); /** * Retrieves statistics about buffer swap operations. Required if * GLX_OML_sync_control or GLX_MESA_swap_frame_usage is supported. */ int (*GetSwapInfo)( __DRIdrawable *dPriv, __DRIswapInfo * sInfo ); /** * These are required if GLX_OML_sync_control is supported. */ /*@{*/ int (*WaitForMSC)( __DRIdrawable *priv, int64_t target_msc, int64_t divisor, int64_t remainder, int64_t * msc ); int (*WaitForSBC)( __DRIdrawable *priv, int64_t target_sbc, int64_t * msc, int64_t * sbc ); int64_t (*SwapBuffersMSC)( __DRIdrawable *priv, int64_t target_msc, int64_t divisor, int64_t remainder ); /*@}*/ void (*CopySubBuffer)(__DRIdrawable *driDrawPriv, int x, int y, int w, int h); /** * New version of GetMSC so we can pass drawable data to the low * level DRM driver (e.g. pipe info). Required if * GLX_SGI_video_sync or GLX_OML_sync_control is supported. */ int (*GetDrawableMSC) ( __DRIscreen * priv, __DRIdrawable *drawablePrivate, int64_t *count); /* DRI2 Entry points */ const __DRIconfig **(*InitScreen2) (__DRIscreen * priv); void (*HandleDrawableConfig)(__DRIdrawable *dPriv, __DRIcontext *pcp, __DRIDrawableConfigEvent *event); void (*HandleBufferAttach)(__DRIdrawable *dPriv, __DRIcontext *pcp, __DRIBufferAttachEvent *ba); }; extern const struct __DriverAPIRec driDriverAPI; struct __DRIswapInfoRec { /** * Number of swapBuffers operations that have been *completed*. */ u_int64_t swap_count; /** * Unadjusted system time of the last buffer swap. This is the time * when the swap completed, not the time when swapBuffers was called. */ int64_t swap_ust; /** * Number of swap operations that occurred after the swap deadline. That * is if a swap happens more than swap_interval frames after the previous * swap, it has missed its deadline. If swap_interval is 0, then the * swap deadline is 1 frame after the previous swap. */ u_int64_t swap_missed_count; /** * Amount of time used by the last swap that missed its deadline. This * is calculated as (__glXGetUST() - swap_ust) / (swap_interval * * time_for_single_vrefresh)). If the actual value of swap_interval is * 0, then 1 is used instead. If swap_missed_count is non-zero, this * should be greater-than 1.0. */ float swap_missed_usage; }; /** * Per-drawable private DRI driver information. */ struct __DRIdrawableRec { /** * Kernel drawable handle */ drm_drawable_t hHWDrawable; /** * Driver's private drawable information. * * This structure is opaque. */ void *driverPrivate; /** * Private data from the loader. We just hold on to it and pass * it back when calling into loader provided functions. */ void *loaderPrivate; /** * Reference count for number of context's currently bound to this * drawable. * * Once it reaches zero, the drawable can be destroyed. * * \note This behavior will change with GLX 1.3. */ int refcount; /** * Index of this drawable information in the SAREA. */ unsigned int index; /** * Pointer to the "drawable has changed ID" stamp in the SAREA. */ unsigned int *pStamp; /** * Last value of the stamp. * * If this differs from the value stored at __DRIdrawable::pStamp, * then the drawable information has been modified by the X server, and the * drawable information (below) should be retrieved from the X server. */ unsigned int lastStamp; /** * \name Drawable * * Drawable information used in software fallbacks. */ /*@{*/ int x; int y; int w; int h; int numClipRects; drm_clip_rect_t *pClipRects; /*@}*/ /** * \name Back and depthbuffer * * Information about the back and depthbuffer where different from above. */ /*@{*/ int backX; int backY; int backClipRectType; int numBackClipRects; drm_clip_rect_t *pBackClipRects; /*@}*/ /** * \name Vertical blank tracking information * Used for waiting on vertical blank events. */ /*@{*/ unsigned int vblSeq; unsigned int vblFlags; /*@}*/ /** * \name Monotonic MSC tracking * * Low level driver is responsible for updating msc_base and * vblSeq values so that higher level code can calculate * a new msc value or msc target for a WaitMSC call. The new value * will be: * msc = msc_base + get_vblank_count() - vblank_base; * * And for waiting on a value, core code will use: * actual_target = target_msc - msc_base + vblank_base; */ /*@{*/ int64_t vblank_base; int64_t msc_base; /*@}*/ /** * Pointer to context to which this drawable is currently bound. */ __DRIcontext *driContextPriv; /** * Pointer to screen on which this drawable was created. */ __DRIscreen *driScreenPriv; /** * Controls swap interval as used by GLX_SGI_swap_control and * GLX_MESA_swap_control. */ unsigned int swap_interval; struct { unsigned int tail; unsigned int drawable_id; } dri2; }; /** * Per-context private driver information. */ struct __DRIcontextRec { /** * Kernel context handle used to access the device lock. */ drm_context_t hHWContext; /** * Device driver's private context data. This structure is opaque. */ void *driverPrivate; /** * Pointer back to the \c __DRIcontext that contains this structure. */ __DRIcontext *pctx; /** * Pointer to drawable currently bound to this context for drawing. */ __DRIdrawable *driDrawablePriv; /** * Pointer to drawable currently bound to this context for reading. */ __DRIdrawable *driReadablePriv; /** * Pointer to screen on which this context was created. */ __DRIscreen *driScreenPriv; }; /** * Per-screen private driver information. */ struct __DRIscreenRec { /** * Current screen's number */ int myNum; /** * Callback functions into the hardware-specific DRI driver code. */ struct __DriverAPIRec DriverAPI; const __DRIextension **extensions; /** * DDX / 2D driver version information. */ __DRIversion ddx_version; /** * DRI X extension version information. */ __DRIversion dri_version; /** * DRM (kernel module) version information. */ __DRIversion drm_version; /** * ID used when the client sets the drawable lock. * * The X server uses this value to detect if the client has died while * holding the drawable lock. */ int drawLockID; /** * File descriptor returned when the kernel device driver is opened. * * Used to: * - authenticate client to kernel * - map the frame buffer, SAREA, etc. * - close the kernel device driver */ int fd; /** * SAREA pointer * * Used to access: * - the device lock * - the device-independent per-drawable and per-context(?) information */ drm_sarea_t *pSAREA; /** * \name Direct frame buffer access information * Used for software fallbacks. */ /*@{*/ unsigned char *pFB; int fbSize; int fbOrigin; int fbStride; int fbWidth; int fbHeight; int fbBPP; /*@}*/ /** * \name Device-dependent private information (stored in the SAREA). * * This data is accessed by the client driver only. */ /*@{*/ void *pDevPriv; int devPrivSize; /*@}*/ /** * Dummy context to which drawables are bound when not bound to any * other context. * * A dummy hHWContext is created for this context, and is used by the GL * core when a hardware lock is required but the drawable is not currently * bound (e.g., potentially during a SwapBuffers request). The dummy * context is created when the first "real" context is created on this * screen. */ __DRIcontext dummyContextPriv; /** * Device-dependent private information (not stored in the SAREA). * * This pointer is never touched by the DRI layer. */ void *private; /** * Pointer back to the \c __DRIscreen that contains this structure. */ __DRIscreen *psc; /* Extensions provided by the loader. */ const __DRIgetDrawableInfoExtension *getDrawableInfo; const __DRIsystemTimeExtension *systemTime; const __DRIdamageExtension *damage; struct { /* Flag to indicate that this is a DRI2 screen. Many of the above * fields will not be valid or initializaed in that case. */ int enabled; #ifdef TTM_API drmBO sareaBO; #endif void *sarea; __DRIEventBuffer *buffer; __DRILock *lock; __DRIloaderExtension *loader; } dri2; /* The lock actually in use, old sarea or DRI2 */ drmLock *lock; }; extern void __driUtilMessage(const char *f, ...); extern void __driUtilUpdateDrawableInfo(__DRIdrawable *pdp); extern int __driParseEvents(__DRIcontext *psp, __DRIdrawable *pdp); extern float driCalculateSwapUsage( __DRIdrawable *dPriv, int64_t last_swap_ust, int64_t current_ust ); extern GLint driIntersectArea( drm_clip_rect_t rect1, drm_clip_rect_t rect2 ); #endif /* _DRI_UTIL_H_ */
yuyuyu101/VirtualBox-NetBSD
src/VBox/Additions/x11/x11include/mesa-7.2/src/mesa/drivers/dri/common/dri_util.h
C
gpl-2.0
15,844
#!/usr/bin/python # # Copyright (c) 2017 Zim Kalinowski, <zikalino@microsoft.com> # Copyright (c) 2019 Matti Ranta, (@techknowlogick) # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: azure_rm_mariadbdatabase_info version_added: "2.9" short_description: Get Azure MariaDB Database facts description: - Get facts of MariaDB Database. options: resource_group: description: - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. required: True type: str server_name: description: - The name of the server. required: True type: str name: description: - The name of the database. type: str extends_documentation_fragment: - azure author: - Zim Kalinowski (@zikalino) - Matti Ranta (@techknowlogick) ''' EXAMPLES = ''' - name: Get instance of MariaDB Database azure_rm_mariadbdatabase_info: resource_group: myResourceGroup server_name: server_name name: database_name - name: List instances of MariaDB Database azure_rm_mariadbdatabase_info: resource_group: myResourceGroup server_name: server_name ''' RETURN = ''' databases: description: - A list of dictionaries containing facts for MariaDB Databases. returned: always type: complex contains: id: description: - Resource ID. returned: always type: str sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforMariaDB/servers/testser ver/databases/db1" resource_group: description: - Resource group name. returned: always type: str sample: testrg server_name: description: - Server name. returned: always type: str sample: testserver name: description: - Resource name. returned: always type: str sample: db1 charset: description: - The charset of the database. returned: always type: str sample: UTF8 collation: description: - The collation of the database. returned: always type: str sample: English_United States.1252 ''' from ansible.module_utils.azure_rm_common import AzureRMModuleBase try: from msrestazure.azure_exceptions import CloudError from azure.mgmt.rdbms.mariadb import MariaDBManagementClient from msrest.serialization import Model except ImportError: # This is handled in azure_rm_common pass class AzureRMMariaDbDatabaseInfo(AzureRMModuleBase): def __init__(self): # define user inputs into argument self.module_arg_spec = dict( resource_group=dict( type='str', required=True ), server_name=dict( type='str', required=True ), name=dict( type='str' ) ) # store the results of the module operation self.results = dict( changed=False ) self.resource_group = None self.server_name = None self.name = None super(AzureRMMariaDbDatabaseInfo, self).__init__(self.module_arg_spec, supports_tags=False) def exec_module(self, **kwargs): is_old_facts = self.module._name == 'azure_rm_mariadbdatabase_facts' if is_old_facts: self.module.deprecate("The 'azure_rm_mariadbdatabase_facts' module has been renamed to 'azure_rm_mariadbdatabase_info'", version='2.13') for key in self.module_arg_spec: setattr(self, key, kwargs[key]) if (self.resource_group is not None and self.server_name is not None and self.name is not None): self.results['databases'] = self.get() elif (self.resource_group is not None and self.server_name is not None): self.results['databases'] = self.list_by_server() return self.results def get(self): response = None results = [] try: response = self.mariadb_client.databases.get(resource_group_name=self.resource_group, server_name=self.server_name, database_name=self.name) self.log("Response : {0}".format(response)) except CloudError as e: self.log('Could not get facts for Databases.') if response is not None: results.append(self.format_item(response)) return results def list_by_server(self): response = None results = [] try: response = self.mariadb_client.databases.list_by_server(resource_group_name=self.resource_group, server_name=self.server_name) self.log("Response : {0}".format(response)) except CloudError as e: self.fail("Error listing for server {0} - {1}".format(self.server_name, str(e))) if response is not None: for item in response: results.append(self.format_item(item)) return results def format_item(self, item): d = item.as_dict() d = { 'resource_group': self.resource_group, 'server_name': self.server_name, 'name': d['name'], 'charset': d['charset'], 'collation': d['collation'] } return d def main(): AzureRMMariaDbDatabaseInfo() if __name__ == '__main__': main()
ilpianista/ansible
test/support/integration/plugins/modules/azure_rm_mariadbdatabase_info.py
Python
gpl-3.0
6,304
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * DDL layer tests. * * @package core_ddl * @category phpunit * @copyright 2008 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); class core_ddl_testcase extends database_driver_testcase { /** @var xmldb_table[] keys are table name. Created in setUp. */ private $tables = array(); /** @var array table name => array of stdClass test records loaded into that table. Created in setUp. */ private $records = array(); protected function setUp(): void { parent::setUp(); $dbman = $this->tdb->get_manager(); // Loads DDL libs. $table = new xmldb_table('test_table0'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('type', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'general'); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null); $table->add_field('intro', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null); $table->add_field('logo', XMLDB_TYPE_BINARY, 'big', null, null, null); $table->add_field('assessed', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('assesstimestart', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('assesstimefinish', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('scale', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('maxbytes', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('forcesubscribe', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0'); $table->add_field('trackingtype', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '1'); $table->add_field('rsstype', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0'); $table->add_field('rssarticles', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0'); $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('grade', XMLDB_TYPE_NUMBER, '20,0', null, null, null, null); $table->add_field('percent', XMLDB_TYPE_NUMBER, '5,2', null, null, null, 66.6); $table->add_field('bignum', XMLDB_TYPE_NUMBER, '38,18', null, null, null, 1234567890.1234); $table->add_field('warnafter', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('blockafter', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('blockperiod', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_key('course', XMLDB_KEY_UNIQUE, array('course')); $table->add_index('type-name', XMLDB_INDEX_UNIQUE, array('type', 'name')); $table->add_index('rsstype', XMLDB_INDEX_NOTUNIQUE, array('rsstype')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; // Define 2 initial records for this table. $this->records[$table->getName()] = array( (object)array( 'course' => '1', 'type' => 'general', 'name' => 'record', 'intro' => 'first record'), (object)array( 'course' => '2', 'type' => 'social', 'name' => 'record', 'intro' => 'second record')); // Second, smaller table. $table = new xmldb_table ('test_table1'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '30', null, null, null, 'Moodle'); $table->add_field('secondname', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null); $table->add_field('thirdname', XMLDB_TYPE_CHAR, '30', null, null, null, ''); // Nullable column with empty default. $table->add_field('intro', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null); $table->add_field('avatar', XMLDB_TYPE_BINARY, 'medium', null, null, null, null); $table->add_field('grade', XMLDB_TYPE_NUMBER, '20,10', null, null, null); $table->add_field('gradefloat', XMLDB_TYPE_FLOAT, '20,0', null, null, null, null); $table->add_field('percentfloat', XMLDB_TYPE_FLOAT, '5,2', null, null, null, 99.9); $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_key('course', XMLDB_KEY_FOREIGN_UNIQUE, array('course'), 'test_table0', array('course')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; // Define 2 initial records for this table. $this->records[$table->getName()] = array( (object)array( 'course' => '1', 'secondname' => 'first record', // Less than 10 cc, please don't modify. Some tests below depend of this. 'intro' => 'first record'), (object)array( 'course' => '2', 'secondname' => 'second record', // More than 10 cc, please don't modify. Some tests below depend of this. 'intro' => 'second record')); } private function create_deftable($tablename) { $dbman = $this->tdb->get_manager(); if (!isset($this->tables[$tablename])) { return null; } $table = $this->tables[$tablename]; if ($dbman->table_exists($table)) { $dbman->drop_table($table); } $dbman->create_table($table); return $table; } /** * Fill the given test table with some records, as far as * DDL behaviour must be tested both with real data and * with empty tables * @param string $tablename * @return int count of records */ private function fill_deftable($tablename) { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); if (!isset($this->records[$tablename])) { return null; } if ($dbman->table_exists($tablename)) { foreach ($this->records[$tablename] as $row) { $DB->insert_record($tablename, $row); } } else { return null; } return count($this->records[$tablename]); } /** * Test behaviour of table_exists() */ public function test_table_exists() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); // First make sure it returns false if table does not exist. $table = $this->tables['test_table0']; try { $result = $DB->get_records('test_table0'); } catch (dml_exception $e) { $result = false; } $this->resetDebugging(); $this->assertFalse($result); $this->assertFalse($dbman->table_exists('test_table0')); // By name.. $this->assertFalse($dbman->table_exists($table)); // By xmldb_table.. // Create table and test again. $dbman->create_table($table); $this->assertSame(array(), $DB->get_records('test_table0')); $this->assertTrue($dbman->table_exists('test_table0')); // By name. $this->assertTrue($dbman->table_exists($table)); // By xmldb_table. // Drop table and test again. $dbman->drop_table($table); try { $result = $DB->get_records('test_table0'); } catch (dml_exception $e) { $result = false; } $this->resetDebugging(); $this->assertFalse($result); $this->assertFalse($dbman->table_exists('test_table0')); // By name. $this->assertFalse($dbman->table_exists($table)); // By xmldb_table. } /** * Test behaviour of create_table() */ public function test_create_table() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); // Create table. $table = $this->tables['test_table1']; $dbman->create_table($table); $this->assertTrue($dbman->table_exists($table)); // Basic get_tables() test. $tables = $DB->get_tables(); $this->assertArrayHasKey('test_table1', $tables); // Basic get_columns() tests. $columns = $DB->get_columns('test_table1'); $this->assertSame('R', $columns['id']->meta_type); $this->assertSame('I', $columns['course']->meta_type); $this->assertSame('C', $columns['name']->meta_type); $this->assertSame('C', $columns['secondname']->meta_type); $this->assertSame('C', $columns['thirdname']->meta_type); $this->assertSame('X', $columns['intro']->meta_type); $this->assertSame('B', $columns['avatar']->meta_type); $this->assertSame('N', $columns['grade']->meta_type); $this->assertSame('N', $columns['percentfloat']->meta_type); $this->assertSame('I', $columns['userid']->meta_type); // Some defaults. $this->assertTrue($columns['course']->has_default); $this->assertEquals(0, $columns['course']->default_value); $this->assertTrue($columns['name']->has_default); $this->assertSame('Moodle', $columns['name']->default_value); $this->assertTrue($columns['secondname']->has_default); $this->assertSame('', $columns['secondname']->default_value); $this->assertTrue($columns['thirdname']->has_default); $this->assertSame('', $columns['thirdname']->default_value); $this->assertTrue($columns['percentfloat']->has_default); $this->assertEquals(99.9, $columns['percentfloat']->default_value); $this->assertTrue($columns['userid']->has_default); $this->assertEquals(0, $columns['userid']->default_value); // Basic get_indexes() test. $indexes = $DB->get_indexes('test_table1'); $courseindex = reset($indexes); $this->assertEquals(1, $courseindex['unique']); $this->assertSame('course', $courseindex['columns'][0]); // Check sequence returns 1 for first insert. $rec = (object)array( 'course' => 10, 'secondname' => 'not important', 'intro' => 'not important'); $this->assertSame(1, $DB->insert_record('test_table1', $rec)); // Check defined defaults are working ok. $dbrec = $DB->get_record('test_table1', array('id' => 1)); $this->assertSame('Moodle', $dbrec->name); $this->assertSame('', $dbrec->thirdname); // Check exceptions if multiple R columns. $table = new xmldb_table ('test_table2'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('rid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_key('primaryx', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_exception', $e); } // Check exceptions missing primary key on R column. $table = new xmldb_table ('test_table2'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_exception', $e); } // Long table name names - the largest allowed by the configuration which exclude the prefix to ensure it's created. $tablechars = str_repeat('a', xmldb_table::NAME_MAX_LENGTH); $table = new xmldb_table($tablechars); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '2'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; $dbman->create_table($table); $this->assertTrue($dbman->table_exists($table)); $dbman->drop_table($table); // Table name is too long, ignoring any prefix size set. $tablechars = str_repeat('a', xmldb_table::NAME_MAX_LENGTH + 1); $table = new xmldb_table($tablechars); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '2'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Invalid table name. $table = new xmldb_table('test_tableCD'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '2'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Weird column names - the largest allowed. $table = new xmldb_table('test_table3'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field(str_repeat('b', xmldb_field::NAME_MAX_LENGTH), XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '2'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; $dbman->create_table($table); $this->assertTrue($dbman->table_exists($table)); $dbman->drop_table($table); // Too long field name. $table = new xmldb_table('test_table4'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field(str_repeat('a', xmldb_field::NAME_MAX_LENGTH + 1), XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '2'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Invalid field name. $table = new xmldb_table('test_table4'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('abCD', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '2'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Invalid integer length. $table = new xmldb_table('test_table4'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '21', null, XMLDB_NOTNULL, null, '2'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Invalid integer default. $table = new xmldb_table('test_table4'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, 'x'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Invalid decimal length - max precision is 38 digits. $table = new xmldb_table('test_table4'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('num', XMLDB_TYPE_NUMBER, '39,19', null, XMLDB_NOTNULL, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Invalid decimal decimals - number of decimals can't be higher than total number of digits. $table = new xmldb_table('test_table4'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('num', XMLDB_TYPE_NUMBER, '10,11', null, XMLDB_NOTNULL, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Invalid decimal whole number - the whole number part can't have more digits than integer fields. $table = new xmldb_table('test_table4'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('num', XMLDB_TYPE_NUMBER, '38,17', null, XMLDB_NOTNULL, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Invalid decimal decimals - negative scale not supported. $table = new xmldb_table('test_table4'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('num', XMLDB_TYPE_NUMBER, '30,-5', null, XMLDB_NOTNULL, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Invalid decimal default. $table = new xmldb_table('test_table4'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('num', XMLDB_TYPE_NUMBER, '10,5', null, XMLDB_NOTNULL, null, 'x'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Invalid float length. $table = new xmldb_table('test_table4'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('num', XMLDB_TYPE_FLOAT, '21,10', null, XMLDB_NOTNULL, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Invalid float decimals. $table = new xmldb_table('test_table4'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('num', XMLDB_TYPE_FLOAT, '10,11', null, XMLDB_NOTNULL, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Invalid float default. $table = new xmldb_table('test_table4'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('num', XMLDB_TYPE_FLOAT, '10,5', null, XMLDB_NOTNULL, null, 'x'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table->getName()] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } } /** * Test if database supports tables with many TEXT fields, * InnoDB is known to failed during data insertion instead * of table creation when text fields contain actual data. */ public function test_row_size_limits() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); $text = str_repeat('š', 1333); $data = new stdClass(); $data->name = 'test'; $table = new xmldb_table('test_innodb'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '30', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); for ($i = 0; $i < 20; $i++) { $table->add_field('text'.$i, XMLDB_TYPE_TEXT, null, null, null, null, null); $data->{'text'.$i} = $text; } $dbman->create_table($table); try { $id = $DB->insert_record('test_innodb', $data); $expected = (array)$data; $expected['id'] = (string)$id; $this->assertEqualsCanonicalizing($expected, (array)$DB->get_record('test_innodb', array('id' => $id))); } catch (dml_exception $e) { // Give some nice error message when known problematic MySQL with InnoDB detected. if ($DB->get_dbfamily() === 'mysql') { $engine = strtolower($DB->get_dbengine()); if ($engine === 'innodb' or $engine === 'xtradb') { if (!$DB->is_compressed_row_format_supported()) { $this->fail("Row size limit reached in MySQL using InnoDB, configure server to use innodb_file_format=Barracuda and innodb_file_per_table=1"); } } } throw $e; } $dbman->drop_table($table); $data = new stdClass(); $data->name = 'test'; $table = new xmldb_table('test_innodb'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '30', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record('test_innodb', array('name' => 'test')); for ($i = 0; $i < 20; $i++) { $field = new xmldb_field('text'.$i, XMLDB_TYPE_TEXT, null, null, null, null, null); $dbman->add_field($table, $field); $data->{'text'.$i} = $text; $id = $DB->insert_record('test_innodb', $data); $expected = (array)$data; $expected['id'] = (string)$id; $this->assertEqualsCanonicalizing($expected, (array)$DB->get_record('test_innodb', array('id' => $id))); } $dbman->drop_table($table); // MySQL VARCHAR fields may hit a different 65535 row size limit when creating tables. $data = new stdClass(); $data->name = 'test'; $table = new xmldb_table('test_innodb'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '30', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); for ($i = 0; $i < 12; $i++) { $table->add_field('text'.$i, XMLDB_TYPE_CHAR, '1333', null, null, null, null); $data->{'text'.$i} = $text; } $dbman->create_table($table); $id = $DB->insert_record('test_innodb', $data); $expected = (array)$data; $expected['id'] = (string)$id; $this->assertEqualsCanonicalizing($expected, (array)$DB->get_record('test_innodb', array('id' => $id))); $dbman->drop_table($table); } /** * Test behaviour of drop_table() */ public function test_drop_table() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); // Initially table doesn't exist. $this->assertFalse($dbman->table_exists('test_table0')); // Create table with contents. $table = $this->create_deftable('test_table0'); $this->assertTrue($dbman->table_exists('test_table0')); // Fill the table with some records before dropping it. $this->fill_deftable('test_table0'); // Drop by xmldb_table object. $dbman->drop_table($table); $this->assertFalse($dbman->table_exists('test_table0')); // Basic get_tables() test. $tables = $DB->get_tables(); $this->assertArrayNotHasKey('test_table0', $tables); // Columns cache must be empty. $columns = $DB->get_columns('test_table0'); $this->assertEmpty($columns); $indexes = $DB->get_indexes('test_table0'); $this->assertEmpty($indexes); } /** * Test behaviour of rename_table() */ public function test_rename_table() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table1'); // Fill the table with some records before renaming it. $insertedrows = $this->fill_deftable('test_table1'); $this->assertFalse($dbman->table_exists('test_table_cust1')); $dbman->rename_table($table, 'test_table_cust1'); $this->assertTrue($dbman->table_exists('test_table_cust1')); // Check sequence returns $insertedrows + 1 for this insert (after rename). $rec = (object)array( 'course' => 20, 'secondname' => 'not important', 'intro' => 'not important'); $this->assertSame($insertedrows+1, $DB->insert_record('test_table_cust1', $rec)); // Verify behavior when target table already exists. $sourcetable = $this->create_deftable('test_table0'); $targettable = $this->create_deftable('test_table1'); try { $dbman->rename_table($sourcetable, $targettable->getName()); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_exception', $e); $this->assertEquals('Table "test_table1" already exists (can not rename table)', $e->getMessage()); } } /** * Test behaviour of field_exists() */ public function test_field_exists() { $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table0'); // String params. // Give a nonexistent table as first param (throw exception). try { $dbman->field_exists('nonexistenttable', 'id'); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('moodle_exception', $e); } // Give a nonexistent field as second param (return false). $this->assertFalse($dbman->field_exists('test_table0', 'nonexistentfield')); // Correct string params. $this->assertTrue($dbman->field_exists('test_table0', 'id')); // Object params. $realfield = $table->getField('id'); // Give a nonexistent table as first param (throw exception). $nonexistenttable = new xmldb_table('nonexistenttable'); try { $dbman->field_exists($nonexistenttable, $realfield); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('moodle_exception', $e); } // Give a nonexistent field as second param (return false). $nonexistentfield = new xmldb_field('nonexistentfield'); $this->assertFalse($dbman->field_exists($table, $nonexistentfield)); // Correct object params. $this->assertTrue($dbman->field_exists($table, $realfield)); // Mix string and object params. // Correct ones. $this->assertTrue($dbman->field_exists($table, 'id')); $this->assertTrue($dbman->field_exists('test_table0', $realfield)); // Non existing tables (throw exception). try { $this->assertFalse($dbman->field_exists($nonexistenttable, 'id')); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('moodle_exception', $e); } try { $this->assertFalse($dbman->field_exists('nonexistenttable', $realfield)); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('moodle_exception', $e); } // Non existing fields (return false). $this->assertFalse($dbman->field_exists($table, 'nonexistentfield')); $this->assertFalse($dbman->field_exists('test_table0', $nonexistentfield)); } /** * Test behaviour of add_field() */ public function test_add_field() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table1'); // Fill the table with some records before adding fields. $this->fill_deftable('test_table1'); // Add one not null field without specifying default value (throws ddl_exception). $field = new xmldb_field('onefield'); $field->set_attributes(XMLDB_TYPE_INTEGER, '6', null, XMLDB_NOTNULL, null, null); try { $dbman->add_field($table, $field); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_exception', $e); } // Add one existing field (throws ddl_exception). $field = new xmldb_field('course'); $field->set_attributes(XMLDB_TYPE_INTEGER, '6', null, XMLDB_NOTNULL, null, 2); try { $dbman->add_field($table, $field); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_exception', $e); } // TODO: add one field with invalid type, must throw exception. // TODO: add one text field with default, must throw exception. // TODO: add one binary field with default, must throw exception. // Add one integer field and check it. $field = new xmldb_field('oneinteger'); $field->set_attributes(XMLDB_TYPE_INTEGER, '6', null, XMLDB_NOTNULL, null, 2); $dbman->add_field($table, $field); $this->assertTrue($dbman->field_exists($table, 'oneinteger')); $columns = $DB->get_columns('test_table1'); $this->assertEquals('oneinteger', $columns['oneinteger']->name); $this->assertTrue($columns['oneinteger']->not_null); // Max_length and scale cannot be checked under all DBs at all for integer fields. $this->assertFalse($columns['oneinteger']->primary_key); $this->assertFalse($columns['oneinteger']->binary); $this->assertTrue($columns['oneinteger']->has_default); $this->assertEquals(2, $columns['oneinteger']->default_value); $this->assertSame('I', $columns['oneinteger']->meta_type); $this->assertEquals(2, $DB->get_field('test_table1', 'oneinteger', array(), IGNORE_MULTIPLE)); // Check default has been applied. // Add one numeric field and check it. $field = new xmldb_field('onenumber'); $field->set_attributes(XMLDB_TYPE_NUMBER, '6,3', null, XMLDB_NOTNULL, null, 2.55); $dbman->add_field($table, $field); $this->assertTrue($dbman->field_exists($table, 'onenumber')); $columns = $DB->get_columns('test_table1'); $this->assertSame('onenumber', $columns['onenumber']->name); $this->assertEquals(6, $columns['onenumber']->max_length); $this->assertEquals(3, $columns['onenumber']->scale); $this->assertTrue($columns['onenumber']->not_null); $this->assertFalse($columns['onenumber']->primary_key); $this->assertFalse($columns['onenumber']->binary); $this->assertTrue($columns['onenumber']->has_default); $this->assertEquals(2.550, $columns['onenumber']->default_value); $this->assertSame('N', $columns['onenumber']->meta_type); $this->assertEquals(2.550, $DB->get_field('test_table1', 'onenumber', array(), IGNORE_MULTIPLE)); // Check default has been applied. // Add one numeric field with scale of 0 and check it. $field = new xmldb_field('onenumberwith0scale'); $field->set_attributes(XMLDB_TYPE_NUMBER, '6,0', null, XMLDB_NOTNULL, null, 2); $dbman->add_field($table, $field); $this->assertTrue($dbman->field_exists($table, 'onenumberwith0scale')); $columns = $DB->get_columns('test_table1'); $this->assertEquals(6, $columns['onenumberwith0scale']->max_length); // We can not use assertEquals as that accepts null/false as a valid value. $this->assertSame('0', strval($columns['onenumberwith0scale']->scale)); // Add one float field and check it (not official type - must work as number). $field = new xmldb_field('onefloat'); $field->set_attributes(XMLDB_TYPE_FLOAT, '6,3', null, XMLDB_NOTNULL, null, 3.550); $dbman->add_field($table, $field); $this->assertTrue($dbman->field_exists($table, 'onefloat')); $columns = $DB->get_columns('test_table1'); $this->assertSame('onefloat', $columns['onefloat']->name); $this->assertTrue($columns['onefloat']->not_null); // Max_length and scale cannot be checked under all DBs at all for float fields. $this->assertFalse($columns['onefloat']->primary_key); $this->assertFalse($columns['onefloat']->binary); $this->assertTrue($columns['onefloat']->has_default); $this->assertEquals(3.550, $columns['onefloat']->default_value); $this->assertSame('N', $columns['onefloat']->meta_type); // Just rounding DB information to 7 decimal digits. Fair enough to test 3.550 and avoids one nasty bug // in MSSQL core returning wrong floats (http://social.msdn.microsoft.com/Forums/en-US/sqldataaccess/thread/5e08de63-16bb-4f24-b645-0cf8fc669de3) // In any case, floats aren't officially supported by Moodle, with number/decimal type being the correct ones, so // this isn't a real problem at all. $this->assertEquals(3.550, round($DB->get_field('test_table1', 'onefloat', array(), IGNORE_MULTIPLE), 7)); // Check default has been applied. // Add one char field and check it. $field = new xmldb_field('onechar'); $field->set_attributes(XMLDB_TYPE_CHAR, '25', null, XMLDB_NOTNULL, null, 'Nice dflt!'); $dbman->add_field($table, $field); $this->assertTrue($dbman->field_exists($table, 'onechar')); $columns = $DB->get_columns('test_table1'); $this->assertSame('onechar', $columns['onechar']->name); $this->assertEquals(25, $columns['onechar']->max_length); $this->assertNull($columns['onechar']->scale); $this->assertTrue($columns['onechar']->not_null); $this->assertFalse($columns['onechar']->primary_key); $this->assertFalse($columns['onechar']->binary); $this->assertTrue($columns['onechar']->has_default); $this->assertSame('Nice dflt!', $columns['onechar']->default_value); $this->assertSame('C', $columns['onechar']->meta_type); $this->assertEquals('Nice dflt!', $DB->get_field('test_table1', 'onechar', array(), IGNORE_MULTIPLE)); // Check default has been applied. // Add one big text field and check it. $field = new xmldb_field('onetext'); $field->set_attributes(XMLDB_TYPE_TEXT, 'big'); $dbman->add_field($table, $field); $this->assertTrue($dbman->field_exists($table, 'onetext')); $columns = $DB->get_columns('test_table1'); $this->assertSame('onetext', $columns['onetext']->name); $this->assertEquals(-1, $columns['onetext']->max_length); // -1 means unknown or big. $this->assertNull($columns['onetext']->scale); $this->assertFalse($columns['onetext']->not_null); $this->assertFalse($columns['onetext']->primary_key); $this->assertFalse($columns['onetext']->binary); $this->assertFalse($columns['onetext']->has_default); $this->assertNull($columns['onetext']->default_value); $this->assertSame('X', $columns['onetext']->meta_type); // Add one medium text field and check it. $field = new xmldb_field('mediumtext'); $field->set_attributes(XMLDB_TYPE_TEXT, 'medium'); $dbman->add_field($table, $field); $columns = $DB->get_columns('test_table1'); $this->assertTrue(($columns['mediumtext']->max_length == -1) or ($columns['mediumtext']->max_length >= 16777215)); // -1 means unknown or big. // Add one small text field and check it. $field = new xmldb_field('smalltext'); $field->set_attributes(XMLDB_TYPE_TEXT, 'small'); $dbman->add_field($table, $field); $columns = $DB->get_columns('test_table1'); $this->assertTrue(($columns['smalltext']->max_length == -1) or ($columns['smalltext']->max_length >= 65535)); // -1 means unknown or big. // Add one binary field and check it. $field = new xmldb_field('onebinary'); $field->set_attributes(XMLDB_TYPE_BINARY); $dbman->add_field($table, $field); $this->assertTrue($dbman->field_exists($table, 'onebinary')); $columns = $DB->get_columns('test_table1'); $this->assertSame('onebinary', $columns['onebinary']->name); $this->assertEquals(-1, $columns['onebinary']->max_length); $this->assertNull($columns['onebinary']->scale); $this->assertFalse($columns['onebinary']->not_null); $this->assertFalse($columns['onebinary']->primary_key); $this->assertTrue($columns['onebinary']->binary); $this->assertFalse($columns['onebinary']->has_default); $this->assertNull($columns['onebinary']->default_value); $this->assertSame('B', $columns['onebinary']->meta_type); // TODO: check datetime type. Although unused should be fully supported. } /** * Test behaviour of drop_field() */ public function test_drop_field() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table0'); // Fill the table with some records before dropping fields. $this->fill_deftable('test_table0'); // Drop field with simple xmldb_field having indexes, must return exception. $field = new xmldb_field('type'); // Field has indexes and default clause. $this->assertTrue($dbman->field_exists($table, 'type')); try { $dbman->drop_field($table, $field); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_dependency_exception', $e); } $this->assertTrue($dbman->field_exists($table, 'type')); // Continues existing, drop aborted. // Drop field with complete xmldb_field object and related indexes, must return exception. $field = $table->getField('course'); // Field has indexes and default clause. $this->assertTrue($dbman->field_exists($table, $field)); try { $dbman->drop_field($table, $field); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_dependency_exception', $e); } $this->assertTrue($dbman->field_exists($table, $field)); // Continues existing, drop aborted. // Drop one non-existing field, must return exception. $field = new xmldb_field('nonexistingfield'); $this->assertFalse($dbman->field_exists($table, $field)); try { $dbman->drop_field($table, $field); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_field_missing_exception', $e); } // Drop field with simple xmldb_field, not having related indexes. $field = new xmldb_field('forcesubscribe'); // Field has default clause. $this->assertTrue($dbman->field_exists($table, 'forcesubscribe')); $dbman->drop_field($table, $field); $this->assertFalse($dbman->field_exists($table, 'forcesubscribe')); // Drop field with complete xmldb_field object, not having related indexes. $field = new xmldb_field('trackingtype'); // Field has default clause. $this->assertTrue($dbman->field_exists($table, $field)); $dbman->drop_field($table, $field); $this->assertFalse($dbman->field_exists($table, $field)); } /** * Test behaviour of change_field_type() */ public function test_change_field_type() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); // Create table with indexed field and not indexed field to // perform tests in both fields, both having defaults. $table = new xmldb_table('test_table_cust0'); $table->add_field('id', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('onenumber', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '2'); $table->add_field('anothernumber', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '4'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_index('onenumber', XMLDB_INDEX_NOTUNIQUE, array('onenumber')); $dbman->create_table($table); $record = new stdClass(); $record->onenumber = 2; $record->anothernumber = 4; $recoriginal = $DB->insert_record('test_table_cust0', $record); // Change column from integer to varchar. Must return exception because of dependent index. $field = new xmldb_field('onenumber'); $field->set_attributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, 'test'); try { $dbman->change_field_type($table, $field); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_dependency_exception', $e); } // Column continues being integer 10 not null default 2. $columns = $DB->get_columns('test_table_cust0'); $this->assertSame('I', $columns['onenumber']->meta_type); // TODO: check the rest of attributes. // Change column from integer to varchar. Must work because column has no dependencies. $field = new xmldb_field('anothernumber'); $field->set_attributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, 'test'); $dbman->change_field_type($table, $field); // Column is char 30 not null default 'test' now. $columns = $DB->get_columns('test_table_cust0'); $this->assertSame('C', $columns['anothernumber']->meta_type); // TODO: check the rest of attributes. // Change column back from char to integer. $field = new xmldb_field('anothernumber'); $field->set_attributes(XMLDB_TYPE_INTEGER, '8', null, XMLDB_NOTNULL, null, '5'); $dbman->change_field_type($table, $field); // Column is integer 8 not null default 5 now. $columns = $DB->get_columns('test_table_cust0'); $this->assertSame('I', $columns['anothernumber']->meta_type); // TODO: check the rest of attributes. // Change column once more from integer to char. $field = new xmldb_field('anothernumber'); $field->set_attributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, "test'n drop"); $dbman->change_field_type($table, $field); // Column is char 30 not null default "test'n drop" now. $columns = $DB->get_columns('test_table_cust0'); $this->assertSame('C', $columns['anothernumber']->meta_type); // TODO: check the rest of attributes. // Insert one string value and try to convert to integer. Must throw exception. $record = new stdClass(); $record->onenumber = 7; $record->anothernumber = 'string value'; $rectodrop = $DB->insert_record('test_table_cust0', $record); $field = new xmldb_field('anothernumber'); $field->set_attributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '5'); try { $dbman->change_field_type($table, $field); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_change_structure_exception', $e); } // Column continues being char 30 not null default "test'n drop" now. $this->assertSame('C', $columns['anothernumber']->meta_type); // TODO: check the rest of attributes. $DB->delete_records('test_table_cust0', array('id' => $rectodrop)); // Delete the string record. // Change the column from varchar to float. $field = new xmldb_field('anothernumber'); $field->set_attributes(XMLDB_TYPE_FLOAT, '20,10', null, null, null, null); $dbman->change_field_type($table, $field); // Column is float 20,10 null default null. $columns = $DB->get_columns('test_table_cust0'); $this->assertSame('N', $columns['anothernumber']->meta_type); // Floats are seen as number. // TODO: check the rest of attributes. // Change the column back from float to varchar. $field = new xmldb_field('anothernumber'); $field->set_attributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'test'); $dbman->change_field_type($table, $field); // Column is char 20 not null default "test" now. $columns = $DB->get_columns('test_table_cust0'); $this->assertSame('C', $columns['anothernumber']->meta_type); // TODO: check the rest of attributes. // Change the column from varchar to number. $field = new xmldb_field('anothernumber'); $field->set_attributes(XMLDB_TYPE_NUMBER, '20,10', null, null, null, null); $dbman->change_field_type($table, $field); // Column is number 20,10 null default null now. $columns = $DB->get_columns('test_table_cust0'); $this->assertSame('N', $columns['anothernumber']->meta_type); // TODO: check the rest of attributes. // Change the column from number to integer. $field = new xmldb_field('anothernumber'); $field->set_attributes(XMLDB_TYPE_INTEGER, '2', null, null, null, null); $dbman->change_field_type($table, $field); // Column is integer 2 null default null now. $columns = $DB->get_columns('test_table_cust0'); $this->assertSame('I', $columns['anothernumber']->meta_type); // TODO: check the rest of attributes. // Change the column from integer to text. $field = new xmldb_field('anothernumber'); $field->set_attributes(XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null); $dbman->change_field_type($table, $field); // Column is char text not null default null. $columns = $DB->get_columns('test_table_cust0'); $this->assertSame('X', $columns['anothernumber']->meta_type); // Change the column back from text to number. $field = new xmldb_field('anothernumber'); $field->set_attributes(XMLDB_TYPE_NUMBER, '20,10', null, null, null, null); $dbman->change_field_type($table, $field); // Column is number 20,10 null default null now. $columns = $DB->get_columns('test_table_cust0'); $this->assertSame('N', $columns['anothernumber']->meta_type); // TODO: check the rest of attributes. // Change the column from number to text. $field = new xmldb_field('anothernumber'); $field->set_attributes(XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null); $dbman->change_field_type($table, $field); // Column is char text not null default "test" now. $columns = $DB->get_columns('test_table_cust0'); $this->assertSame('X', $columns['anothernumber']->meta_type); // TODO: check the rest of attributes. // Change the column back from text to integer. $field = new xmldb_field('anothernumber'); $field->set_attributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, 10); $dbman->change_field_type($table, $field); // Column is integer 10 not null default 10. $columns = $DB->get_columns('test_table_cust0'); $this->assertSame('I', $columns['anothernumber']->meta_type); // TODO: check the rest of attributes. // Check original value has survived to all the type changes. $this->assertnotEmpty($rec = $DB->get_record('test_table_cust0', array('id' => $recoriginal))); $this->assertEquals(4, $rec->anothernumber); $dbman->drop_table($table); $this->assertFalse($dbman->table_exists($table)); } /** * Test behaviour of test_change_field_precision() */ public function test_change_field_precision() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table1'); // Fill the table with some records before dropping fields. $this->fill_deftable('test_table1'); // Change text field from medium to big. $field = new xmldb_field('intro'); $field->set_attributes(XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null); $dbman->change_field_precision($table, $field); $columns = $DB->get_columns('test_table1'); // Cannot check the text type, only the metatype. $this->assertSame('X', $columns['intro']->meta_type); // TODO: check the rest of attributes. // Change char field from 30 to 20. $field = new xmldb_field('secondname'); $field->set_attributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null); $dbman->change_field_precision($table, $field); $columns = $DB->get_columns('test_table1'); $this->assertSame('C', $columns['secondname']->meta_type); // TODO: check the rest of attributes. // Change char field from 20 to 10, having contents > 10cc. Throw exception. $field = new xmldb_field('secondname'); $field->set_attributes(XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, null, null); try { $dbman->change_field_precision($table, $field); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_change_structure_exception', $e); } // No changes in field specs at all. $columns = $DB->get_columns('test_table1'); $this->assertSame('C', $columns['secondname']->meta_type); // TODO: check the rest of attributes. // Change number field from 20,10 to 10,2. $field = new xmldb_field('grade'); $field->set_attributes(XMLDB_TYPE_NUMBER, '10,2', null, null, null, null); $dbman->change_field_precision($table, $field); $columns = $DB->get_columns('test_table1'); $this->assertSame('N', $columns['grade']->meta_type); // TODO: check the rest of attributes. // Change integer field from 10 to 2. $field = new xmldb_field('userid'); $field->set_attributes(XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0'); $dbman->change_field_precision($table, $field); $columns = $DB->get_columns('test_table1'); $this->assertSame('I', $columns['userid']->meta_type); // TODO: check the rest of attributes. // Change the column from integer (2) to integer (6) (forces change of type in some DBs). $field = new xmldb_field('userid'); $field->set_attributes(XMLDB_TYPE_INTEGER, '6', null, null, null, null); $dbman->change_field_precision($table, $field); // Column is integer 6 null default null now. $columns = $DB->get_columns('test_table1'); $this->assertSame('I', $columns['userid']->meta_type); // TODO: check the rest of attributes. // Insert one record with 6-digit field. $record = new stdClass(); $record->course = 10; $record->secondname = 'third record'; $record->intro = 'third record'; $record->userid = 123456; $DB->insert_record('test_table1', $record); // Change integer field from 6 to 2, contents are bigger, must throw exception. $field = new xmldb_field('userid'); $field->set_attributes(XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0'); try { $dbman->change_field_precision($table, $field); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_change_structure_exception', $e); } // No changes in field specs at all. $columns = $DB->get_columns('test_table1'); $this->assertSame('I', $columns['userid']->meta_type); // TODO: check the rest of attributes. // Change integer field from 10 to 3, in field used by index. must throw exception. $field = new xmldb_field('course'); $field->set_attributes(XMLDB_TYPE_INTEGER, '3', null, XMLDB_NOTNULL, null, '0'); try { $dbman->change_field_precision($table, $field); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_dependency_exception', $e); } // No changes in field specs at all. $columns = $DB->get_columns('test_table1'); $this->assertSame('I', $columns['course']->meta_type); // TODO: check the rest of attributes. } public function testChangeFieldNullability() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); $table = new xmldb_table('test_table_cust0'); $table->add_field('id', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $record = new stdClass(); $record->name = null; try { $result = $DB->insert_record('test_table_cust0', $record, false); } catch (dml_exception $e) { $result = false; } $this->resetDebugging(); $this->assertFalse($result); $field = new xmldb_field('name'); $field->set_attributes(XMLDB_TYPE_CHAR, '30', null, null, null, null); $dbman->change_field_notnull($table, $field); $this->assertTrue($DB->insert_record('test_table_cust0', $record, false)); // TODO: add some tests with existing data in table. $DB->delete_records('test_table_cust0'); $field = new xmldb_field('name'); $field->set_attributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null); $dbman->change_field_notnull($table, $field); try { $result = $DB->insert_record('test_table_cust0', $record, false); } catch (dml_exception $e) { $result = false; } $this->resetDebugging(); $this->assertFalse($result); $dbman->drop_table($table); } public function testChangeFieldDefault() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); $table = new xmldb_table('test_table_cust0'); $table->add_field('id', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('onenumber', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, 'Moodle'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $field = new xmldb_field('name'); $field->set_attributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, 'Moodle2'); $dbman->change_field_default($table, $field); $record = new stdClass(); $record->onenumber = 666; $id = $DB->insert_record('test_table_cust0', $record); $record = $DB->get_record('test_table_cust0', array('id'=>$id)); $this->assertSame('Moodle2', $record->name); $field = new xmldb_field('onenumber'); $field->set_attributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, 666); $dbman->change_field_default($table, $field); $record = new stdClass(); $record->name = 'something'; $id = $DB->insert_record('test_table_cust0', $record); $record = $DB->get_record('test_table_cust0', array('id'=>$id)); $this->assertSame('666', $record->onenumber); $dbman->drop_table($table); } public function testAddUniqueIndex() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); $table = new xmldb_table('test_table_cust0'); $table->add_field('id', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('onenumber', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, 'Moodle'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $record = new stdClass(); $record->onenumber = 666; $record->name = 'something'; $DB->insert_record('test_table_cust0', $record, false); $index = new xmldb_index('onenumber-name'); $index->set_attributes(XMLDB_INDEX_UNIQUE, array('onenumber', 'name')); $dbman->add_index($table, $index); try { $result = $DB->insert_record('test_table_cust0', $record, false); } catch (dml_exception $e) { $result = false; } $this->resetDebugging(); $this->assertFalse($result); $dbman->drop_table($table); } public function testAddNonUniqueIndex() { $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table1'); $index = new xmldb_index('secondname'); $index->set_attributes(XMLDB_INDEX_NOTUNIQUE, array('course', 'name')); $dbman->add_index($table, $index); $this->assertTrue($dbman->index_exists($table, $index)); try { $dbman->add_index($table, $index); $this->fail('Exception expected for duplicate indexes'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_exception', $e); } $index = new xmldb_index('third'); $index->set_attributes(XMLDB_INDEX_NOTUNIQUE, array('course')); try { $dbman->add_index($table, $index); $this->fail('Exception expected for duplicate indexes'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_exception', $e); } $table = new xmldb_table('test_table_cust0'); $table->add_field('id', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('onenumber', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, 'Moodle'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_key('onenumber', XMLDB_KEY_FOREIGN, array('onenumber')); try { $table->add_index('onenumber', XMLDB_INDEX_NOTUNIQUE, array('onenumber')); $this->fail('Coding exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } $table = new xmldb_table('test_table_cust0'); $table->add_field('id', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('onenumber', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, 'Moodle'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_index('onenumber', XMLDB_INDEX_NOTUNIQUE, array('onenumber')); try { $table->add_key('onenumber', XMLDB_KEY_FOREIGN, array('onenumber')); $this->fail('Coding exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } } public function testFindIndexName() { $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table1'); $index = new xmldb_index('secondname'); $index->set_attributes(XMLDB_INDEX_NOTUNIQUE, array('course', 'name')); $dbman->add_index($table, $index); // DBM Systems name their indices differently - do not test the actual index name. $result = $dbman->find_index_name($table, $index); $this->assertTrue(!empty($result)); $nonexistentindex = new xmldb_index('nonexistentindex'); $nonexistentindex->set_attributes(XMLDB_INDEX_NOTUNIQUE, array('name')); $this->assertFalse($dbman->find_index_name($table, $nonexistentindex)); } public function testDropIndex() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table1'); $index = new xmldb_index('secondname'); $index->set_attributes(XMLDB_INDEX_NOTUNIQUE, array('course', 'name')); $dbman->add_index($table, $index); $dbman->drop_index($table, $index); $this->assertFalse($dbman->find_index_name($table, $index)); // Test we are able to drop indexes having hyphens MDL-22804. // Create index with hyphens (by hand). $indexname = 'test-index-with-hyphens'; switch ($DB->get_dbfamily()) { case 'mysql': $indexname = '`' . $indexname . '`'; break; default: $indexname = '"' . $indexname . '"'; } $stmt = "CREATE INDEX {$indexname} ON {$DB->get_prefix()}test_table1 (course, name)"; $DB->change_database_structure($stmt); $this->assertNotEmpty($dbman->find_index_name($table, $index)); // Index created, let's drop it using db manager stuff. $index = new xmldb_index('indexname', XMLDB_INDEX_NOTUNIQUE, array('course', 'name')); $dbman->drop_index($table, $index); $this->assertFalse($dbman->find_index_name($table, $index)); } public function testAddUniqueKey() { $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table1'); $key = new xmldb_key('id-course-grade'); $key->set_attributes(XMLDB_KEY_UNIQUE, array('id', 'course', 'grade')); $dbman->add_key($table, $key); // No easy way to test it, this just makes sure no errors are encountered. $this->assertTrue(true); } public function testAddForeignUniqueKey() { $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table1'); $this->create_deftable('test_table0'); $key = new xmldb_key('course'); $key->set_attributes(XMLDB_KEY_FOREIGN_UNIQUE, array('course'), 'test_table0', array('id')); $dbman->add_key($table, $key); // No easy way to test it, this just makes sure no errors are encountered. $this->assertTrue(true); } public function testDropKey() { $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table1'); $this->create_deftable('test_table0'); $key = new xmldb_key('course'); $key->set_attributes(XMLDB_KEY_FOREIGN_UNIQUE, array('course'), 'test_table0', array('id')); $dbman->add_key($table, $key); $dbman->drop_key($table, $key); // No easy way to test it, this just makes sure no errors are encountered. $this->assertTrue(true); } public function testAddForeignKey() { $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table1'); $this->create_deftable('test_table0'); $key = new xmldb_key('course'); $key->set_attributes(XMLDB_KEY_FOREIGN, array('course'), 'test_table0', array('id')); $dbman->add_key($table, $key); // No easy way to test it, this just makes sure no errors are encountered. $this->assertTrue(true); } public function testDropForeignKey() { $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table1'); $this->create_deftable('test_table0'); $key = new xmldb_key('course'); $key->set_attributes(XMLDB_KEY_FOREIGN, array('course'), 'test_table0', array('id')); $dbman->add_key($table, $key); $dbman->drop_key($table, $key); // No easy way to test it, this just makes sure no errors are encountered. $this->assertTrue(true); } public function testRenameField() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table0'); $field = new xmldb_field('type'); $field->set_attributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'general', 'course'); // 1. Rename the 'type' field into a generic new valid name. // This represents the standard use case. $dbman->rename_field($table, $field, 'newfieldname'); $columns = $DB->get_columns('test_table0'); $this->assertArrayNotHasKey('type', $columns); $this->assertArrayHasKey('newfieldname', $columns); $field->setName('newfieldname'); // 2. Rename the 'newfieldname' field into a reserved word, for testing purposes. // This represents a questionable use case: we should support it but discourage the use of it on peer reviewing. $dbman->rename_field($table, $field, 'where'); $columns = $DB->get_columns('test_table0'); $this->assertArrayNotHasKey('newfieldname', $columns); $this->assertArrayHasKey('where', $columns); // 3. Create a table with a column name named w/ a reserved word and get rid of it. // This represents a "recovering" use case: a field name could be a reserved word in the future, at least for a DB type. $table = new xmldb_table('test_table_res_word'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('where', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->setComment("This is a test'n drop table. You can drop it safely"); $dbman->create_table($table); $dbman->table_exists('test_table_res_word'); $columns = $DB->get_columns('test_table_res_word'); $this->assertArrayHasKey('where', $columns); $field = $table->getField('where'); $dbman->rename_field($table, $field, 'newfieldname'); $columns = $DB->get_columns('test_table_res_word'); $this->assertArrayNotHasKey('where', $columns); $this->assertArrayHasKey('newfieldname', $columns); } public function testIndexExists() { // Skipping: this is just a test of find_index_name. } public function testFindKeyName() { $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table0'); $key = $table->getKey('primary'); // With Mysql, the return value is actually "mdl_test_id_pk". $result = $dbman->find_key_name($table, $key); $this->assertTrue(!empty($result)); } public function testDeleteTablesFromXmldbFile() { $dbman = $this->tdb->get_manager(); $this->create_deftable('test_table1'); $this->assertTrue($dbman->table_exists('test_table1')); // Feed nonexistent file. try { $dbman->delete_tables_from_xmldb_file('fpsoiudfposui'); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->resetDebugging(); $this->assertInstanceOf('moodle_exception', $e); } try { $dbman->delete_tables_from_xmldb_file(__DIR__ . '/fixtures/invalid.xml'); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->resetDebugging(); $this->assertInstanceOf('moodle_exception', $e); } // Check that the table has not been deleted from DB. $this->assertTrue($dbman->table_exists('test_table1')); // Real and valid xml file. // TODO: drop UNSINGED completely in Moodle 2.4. $dbman->delete_tables_from_xmldb_file(__DIR__ . '/fixtures/xmldb_table.xml'); // Check that the table has been deleted from DB. $this->assertFalse($dbman->table_exists('test_table1')); } public function testInstallFromXmldbFile() { $dbman = $this->tdb->get_manager(); // Feed nonexistent file. try { $dbman->install_from_xmldb_file('fpsoiudfposui'); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->resetDebugging(); $this->assertInstanceOf('moodle_exception', $e); } try { $dbman->install_from_xmldb_file(__DIR__ . '/fixtures/invalid.xml'); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->resetDebugging(); $this->assertInstanceOf('moodle_exception', $e); } // Check that the table has not yet been created in DB. $this->assertFalse($dbman->table_exists('test_table1')); // Real and valid xml file. $dbman->install_from_xmldb_file(__DIR__ . '/fixtures/xmldb_table.xml'); $this->assertTrue($dbman->table_exists('test_table1')); } public function test_temp_tables() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); // Create temp table0. $table0 = $this->tables['test_table0']; $dbman->create_temp_table($table0); $this->assertTrue($dbman->table_exists('test_table0')); // Try to create temp table with same name, must throw exception. $dupetable = $this->tables['test_table0']; try { $dbman->create_temp_table($dupetable); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_exception', $e); } // Try to create table with same name, must throw exception. $dupetable = $this->tables['test_table0']; try { $dbman->create_table($dupetable); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_exception', $e); } // Create another temp table1. $table1 = $this->tables['test_table1']; $dbman->create_temp_table($table1); $this->assertTrue($dbman->table_exists('test_table1')); // Get columns and perform some basic tests. $columns = $DB->get_columns('test_table1'); $this->assertCount(11, $columns); $this->assertTrue($columns['name'] instanceof database_column_info); $this->assertEquals(30, $columns['name']->max_length); $this->assertTrue($columns['name']->has_default); $this->assertEquals('Moodle', $columns['name']->default_value); // Insert some records. $inserted = $this->fill_deftable('test_table1'); $records = $DB->get_records('test_table1'); $this->assertCount($inserted, $records); $this->assertSame($records[1]->course, $this->records['test_table1'][0]->course); $this->assertSame($records[1]->secondname, $this->records['test_table1'][0]->secondname); $this->assertSame($records[2]->intro, $this->records['test_table1'][1]->intro); // Collect statistics about the data in the temp table. $DB->update_temp_table_stats(); // Drop table1. $dbman->drop_table($table1); $this->assertFalse($dbman->table_exists('test_table1')); // Try to drop non-existing temp table, must throw exception. $noetable = $this->tables['test_table1']; try { $dbman->drop_table($noetable); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('ddl_table_missing_exception', $e); } // Collect statistics about the data in the temp table with less tables. $DB->update_temp_table_stats(); // Fill/modify/delete a few table0 records. // Drop table0. $dbman->drop_table($table0); $this->assertFalse($dbman->table_exists('test_table0')); // Create another temp table1. $table1 = $this->tables['test_table1']; $dbman->create_temp_table($table1); $this->assertTrue($dbman->table_exists('test_table1')); // Make sure it can be dropped using deprecated drop_temp_table(). $dbman->drop_temp_table($table1); $this->assertFalse($dbman->table_exists('test_table1')); $this->assertDebuggingCalled(); // Try join with normal tables - MS SQL may use incompatible collation. $table1 = new xmldb_table('test_table'); $table1->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table1->add_field('name', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL, null); $table1->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table1); $table2 = new xmldb_table('test_temp'); $table2->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table2->add_field('name', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL, null); $table2->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_temp_table($table2); $record = array('name' => 'a'); $DB->insert_record('test_table', $record); $DB->insert_record('test_temp', $record); $record = array('name' => 'b'); $DB->insert_record('test_table', $record); $record = array('name' => 'c'); $DB->insert_record('test_temp', $record); $sql = "SELECT * FROM {test_table} n JOIN {test_temp} t ON t.name = n.name"; $records = $DB->get_records_sql($sql); $this->assertCount(1, $records); // Drop temp table. $dbman->drop_table($table2); $this->assertFalse($dbman->table_exists('test_temp')); } public function test_concurrent_temp_tables() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); // Define 2 records. $record1 = (object)array( 'course' => 1, 'secondname' => '11 important', 'intro' => '111 important'); $record2 = (object)array( 'course' => 2, 'secondname' => '22 important', 'intro' => '222 important'); // Create temp table1 and insert 1 record (in DB). $table = $this->tables['test_table1']; $dbman->create_temp_table($table); $this->assertTrue($dbman->table_exists('test_table1')); $inserted = $DB->insert_record('test_table1', $record1); // Switch to new connection. $cfg = $DB->export_dbconfig(); if (!isset($cfg->dboptions)) { $cfg->dboptions = array(); } $DB2 = moodle_database::get_driver_instance($cfg->dbtype, $cfg->dblibrary); $DB2->connect($cfg->dbhost, $cfg->dbuser, $cfg->dbpass, $cfg->dbname, $cfg->prefix, $cfg->dboptions); $dbman2 = $DB2->get_manager(); $this->assertFalse($dbman2->table_exists('test_table1')); // Temp table not exists in DB2. // Create temp table1 and insert 1 record (in DB2). $table = $this->tables['test_table1']; $dbman2->create_temp_table($table); $this->assertTrue($dbman2->table_exists('test_table1')); $inserted = $DB2->insert_record('test_table1', $record2); $dbman2->drop_table($table); // Drop temp table before closing DB2. $this->assertFalse($dbman2->table_exists('test_table1')); $DB2->dispose(); // Close DB2. $this->assertTrue($dbman->table_exists('test_table1')); // Check table continues existing for DB. $dbman->drop_table($table); // Drop temp table. $this->assertFalse($dbman->table_exists('test_table1')); } /** * get_columns should return an empty array for ex-temptables. */ public function test_leftover_temp_tables_columns() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); // Create temp table0. $table0 = $this->tables['test_table0']; $dbman->create_temp_table($table0); $dbman->drop_table($table0); // Get columns and perform some basic tests. $columns = $DB->get_columns('test_table0'); $this->assertEquals([], $columns); } /** * Deleting a temp table should not purge the whole cache */ public function test_leftover_temp_tables_cache() { $DB = $this->tdb; // Do not use global $DB! $dbman = $this->tdb->get_manager(); // Create 2 temp tables. $table0 = $this->tables['test_table0']; $dbman->create_temp_table($table0); $table1 = $this->tables['test_table1']; $dbman->create_temp_table($table1); // Create a normal table. $table2 = new xmldb_table ('test_table2'); $table2->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table2->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table2->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table2->setComment("This is a test'n drop table. You can drop it safely"); $this->tables[$table2->getName()] = $table2; $dbman->create_table($table2); // Get columns for the tables, so that relevant caches are populated with their data. $DB->get_columns('test_table0'); $DB->get_columns('test_table1'); $DB->get_columns('test_table2'); $dbman->drop_table($table0); $rc = new ReflectionClass('moodle_database'); $rcm = $rc->getMethod('get_temp_tables_cache'); $rcm->setAccessible(true); $metacachetemp = $rcm->invokeArgs($DB, []); // Data of test_table0 should be removed from the cache. $this->assertEquals(false, $metacachetemp->has('test_table0')); // Data of test_table1 should be intact. $this->assertEquals(true, $metacachetemp->has('test_table1')); $rc = new ReflectionClass('moodle_database'); $rcm = $rc->getMethod('get_metacache'); $rcm->setAccessible(true); $metacache = $rcm->invokeArgs($DB, []); // Data of test_table2 should be intact. $this->assertEquals(true, $metacache->has('test_table2')); // Delete the leftover temp table. $dbman->drop_table($table1); } public function test_reset_sequence() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = new xmldb_table('testtable'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); // Drop if exists. if ($dbman->table_exists($table)) { $dbman->drop_table($table); } $dbman->create_table($table); $tablename = $table->getName(); $this->tables[$tablename] = $table; $record = (object)array('id'=>666, 'course'=>10); $DB->import_record('testtable', $record); $DB->delete_records('testtable'); // This delete performs one TRUNCATE. $dbman->reset_sequence($table); // Using xmldb object. $this->assertEquals(1, $DB->insert_record('testtable', (object)array('course'=>13))); $record = (object)array('id'=>666, 'course'=>10); $DB->import_record('testtable', $record); $DB->delete_records('testtable', array()); // This delete performs one DELETE. $dbman->reset_sequence($table); // Using xmldb object. $this->assertEquals(1, $DB->insert_record('testtable', (object)array('course'=>13)), 'Some versions of MySQL 5.6.x are known to not support lowering of auto-increment numbers.'); $DB->import_record('testtable', $record); $dbman->reset_sequence($tablename); // Using string. $this->assertEquals(667, $DB->insert_record('testtable', (object)array('course'=>13))); $dbman->drop_table($table); } public function test_reserved_words() { $reserved = sql_generator::getAllReservedWords(); $this->assertTrue(count($reserved) > 1); } public function test_index_hints() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = new xmldb_table('testtable'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL, null); $table->add_field('path', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_index('name', XMLDB_INDEX_NOTUNIQUE, array('name'), array('xxxx,yyyy')); $table->add_index('path', XMLDB_INDEX_NOTUNIQUE, array('path'), array('varchar_pattern_ops')); // Drop if exists. if ($dbman->table_exists($table)) { $dbman->drop_table($table); } $dbman->create_table($table); $tablename = $table->getName(); $this->tables[$tablename] = $table; $table = new xmldb_table('testtable'); $index = new xmldb_index('name', XMLDB_INDEX_NOTUNIQUE, array('name'), array('xxxx,yyyy')); $this->assertTrue($dbman->index_exists($table, $index)); $table = new xmldb_table('testtable'); $index = new xmldb_index('path', XMLDB_INDEX_NOTUNIQUE, array('path'), array('varchar_pattern_ops')); $this->assertTrue($dbman->index_exists($table, $index)); // Try unique indexes too. $dbman->drop_table($this->tables[$tablename]); $table = new xmldb_table('testtable'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('path', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_index('path', XMLDB_INDEX_UNIQUE, array('path'), array('varchar_pattern_ops')); $dbman->create_table($table); $this->tables[$tablename] = $table; $table = new xmldb_table('testtable'); $index = new xmldb_index('path', XMLDB_INDEX_UNIQUE, array('path'), array('varchar_pattern_ops')); $this->assertTrue($dbman->index_exists($table, $index)); } public function test_index_max_bytes() { $DB = $this->tdb; $dbman = $DB->get_manager(); $maxstr = ''; for ($i=0; $i<255; $i++) { $maxstr .= '言'; // Random long string that should fix exactly the limit for one char column. } $table = new xmldb_table('testtable'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_index('name', XMLDB_INDEX_NOTUNIQUE, array('name')); // Drop if exists. if ($dbman->table_exists($table)) { $dbman->drop_table($table); } $dbman->create_table($table); $tablename = $table->getName(); $this->tables[$tablename] = $table; $rec = new stdClass(); $rec->name = $maxstr; $id = $DB->insert_record($tablename, $rec); $this->assertTrue(!empty($id)); $rec = $DB->get_record($tablename, array('id'=>$id)); $this->assertSame($maxstr, $rec->name); $dbman->drop_table($table); $table = new xmldb_table('testtable'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, 255+1, null, XMLDB_NOTNULL, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_index('name', XMLDB_INDEX_NOTUNIQUE, array('name')); try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } } public function test_index_composed_max_bytes() { $DB = $this->tdb; $dbman = $DB->get_manager(); $maxstr = ''; for ($i=0; $i<200; $i++) { $maxstr .= '言'; } $reststr = ''; for ($i=0; $i<133; $i++) { $reststr .= '言'; } $table = new xmldb_table('testtable'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name1', XMLDB_TYPE_CHAR, 200, null, XMLDB_NOTNULL, null); $table->add_field('name2', XMLDB_TYPE_CHAR, 133, null, XMLDB_NOTNULL, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_index('name1-name2', XMLDB_INDEX_NOTUNIQUE, array('name1', 'name2')); // Drop if exists. if ($dbman->table_exists($table)) { $dbman->drop_table($table); } $dbman->create_table($table); $tablename = $table->getName(); $this->tables[$tablename] = $table; $rec = new stdClass(); $rec->name1 = $maxstr; $rec->name2 = $reststr; $id = $DB->insert_record($tablename, $rec); $this->assertTrue(!empty($id)); $rec = $DB->get_record($tablename, array('id'=>$id)); $this->assertSame($maxstr, $rec->name1); $this->assertSame($reststr, $rec->name2); $table = new xmldb_table('testtable'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name1', XMLDB_TYPE_CHAR, 201, null, XMLDB_NOTNULL, null); $table->add_field('name2', XMLDB_TYPE_CHAR, 133, null, XMLDB_NOTNULL, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_index('name1-name2', XMLDB_INDEX_NOTUNIQUE, array('name1', 'name2')); // Drop if exists. if ($dbman->table_exists($table)) { $dbman->drop_table($table); } try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } } public function test_char_size_limit() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = new xmldb_table('testtable'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, xmldb_field::CHAR_MAX_LENGTH, null, XMLDB_NOTNULL, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); // Drop if exists. if ($dbman->table_exists($table)) { $dbman->drop_table($table); } $dbman->create_table($table); $tablename = $table->getName(); $this->tables[$tablename] = $table; // This has to work in all DBs. $maxstr = ''; for ($i=0; $i<xmldb_field::CHAR_MAX_LENGTH; $i++) { $maxstr .= 'a'; // Ascii only. } $rec = new stdClass(); $rec->name = $maxstr; $id = $DB->insert_record($tablename, $rec); $this->assertTrue(!empty($id)); $rec = $DB->get_record($tablename, array('id'=>$id)); $this->assertSame($maxstr, $rec->name); // Following test is supposed to fail in oracle. $maxstr = ''; for ($i=0; $i<xmldb_field::CHAR_MAX_LENGTH; $i++) { $maxstr .= '言'; // Random long string that should fix exactly the limit for one char column. } $rec = new stdClass(); $rec->name = $maxstr; try { $id = $DB->insert_record($tablename, $rec); $this->assertTrue(!empty($id)); $rec = $DB->get_record($tablename, array('id'=>$id)); $this->assertSame($maxstr, $rec->name); } catch (dml_exception $e) { if ($DB->get_dbfamily() === 'oracle') { $this->fail('Oracle does not support text fields larger than 4000 bytes, this is not a big problem for mostly ascii based languages'); } else { throw $e; } } $table = new xmldb_table('testtable'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, xmldb_field::CHAR_MAX_LENGTH+1, null, XMLDB_NOTNULL, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); // Drop if exists. if ($dbman->table_exists($table)) { $dbman->drop_table($table); } $tablename = $table->getName(); $this->tables[$tablename] = $table; try { $dbman->create_table($table); $this->fail('Exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } } public function test_object_name() { $gen = $this->tdb->get_manager()->generator; // This will form short object name and max length should not be exceeded. $table = 'tablename'; $fields = 'id'; $suffix = 'pk'; for ($i=0; $i<12; $i++) { $this->assertLessThanOrEqual($gen->names_max_length, strlen($gen->getNameForObject($table, $fields, $suffix)), 'Generated object name is too long. $i = '.$i); } // This will form too long object name always and it must be trimmed to exactly 30 chars. $table = 'aaaa_bbbb_cccc_dddd_eeee_ffff_gggg'; $fields = 'aaaaa,bbbbb,ccccc,ddddd'; $suffix = 'idx'; for ($i=0; $i<12; $i++) { $this->assertEquals($gen->names_max_length, strlen($gen->getNameForObject($table, $fields, $suffix)), 'Generated object name is too long. $i = '.$i); } // Same test without suffix. $table = 'bbbb_cccc_dddd_eeee_ffff_gggg_hhhh'; $fields = 'aaaaa,bbbbb,ccccc,ddddd'; $suffix = ''; for ($i=0; $i<12; $i++) { $this->assertEquals($gen->names_max_length, strlen($gen->getNameForObject($table, $fields, $suffix)), 'Generated object name is too long. $i = '.$i); } // This must only trim name when counter is 10 or more. $table = 'cccc_dddd_eeee_ffff_gggg_hhhh_iiii'; $fields = 'id'; $suffix = 'idx'; // Since we don't know how long prefix is, loop to generate tablename that gives exactly maxlengh-1 length. // Skip this test if prefix is too long. while (strlen($table) && strlen($gen->prefix.preg_replace('/_/','',$table).'_id_'.$suffix) >= $gen->names_max_length) { $table = rtrim(substr($table, 0, strlen($table) - 1), '_'); } if (strlen($table)) { $this->assertEquals($gen->names_max_length - 1, strlen($gen->getNameForObject($table, $fields, $suffix))); for ($i=0; $i<12; $i++) { $this->assertEquals($gen->names_max_length, strlen($gen->getNameForObject($table, $fields, $suffix)), 'Generated object name is too long. $i = '.$i); } // Now test to confirm that a duplicate name isn't issued, even if they come from different root names. // Move to a new field. $fields = "fl"; // Insert twice, moving is to a key with fl2. $this->assertEquals($gen->names_max_length - 1, strlen($gen->getNameForObject($table, $fields, $suffix))); $result1 = $gen->getNameForObject($table, $fields, $suffix); // Make sure we end up with _fl2_ in the result. $this->assertMatchesRegularExpression('/_fl2_/', $result1); // Now, use a field that would result in the same key if it wasn't already taken. $fields = "fl2"; // Because we are now at the max key length, it will try: // - _fl2_ (the natural name) // - _fl2_ (removing the original 2, and adding a counter 2) // - then settle on _fl3_. $result2 = $gen->getNameForObject($table, $fields, $suffix); $this->assertMatchesRegularExpression('/_fl3_/', $result2); // Make sure they don't match. $this->assertNotEquals($result1, $result2); // But are only different in the way we expect. This confirms the test is working properly. $this->assertEquals(str_replace('_fl2_', '', $result1), str_replace('_fl3_', '', $result2)); // Now go back. We would expect the next result to be fl3 again, but it is taken, so it should move to fl4. $fields = "fl"; $result3 = $gen->getNameForObject($table, $fields, $suffix); $this->assertNotEquals($result2, $result3); $this->assertMatchesRegularExpression('/_fl4_/', $result3); } } /** * Data provider for test_get_enc_quoted(). * * @return array The type-value pair fixture. */ public function test_get_enc_quoted_provider() { return array( // Reserved: some examples from SQL-92. [true, 'from'], [true, 'table'], [true, 'where'], // Not reserved. [false, 'my_awesome_column_name'] ); } /** * This is a test for sql_generator::getEncQuoted(). * * @dataProvider test_get_enc_quoted_provider * @param bool $reserved Whether the column name is reserved or not. * @param string $columnname The column name to be quoted, according to the value of $reserved. **/ public function test_get_enc_quoted($reserved, $columnname) { $DB = $this->tdb; $gen = $DB->get_manager()->generator; if (!$reserved) { // No need to quote the column name. $this->assertSame($columnname, $gen->getEncQuoted($columnname)); } else { // Column name should be quoted. $dbfamily = $DB->get_dbfamily(); switch ($dbfamily) { case 'mysql': $this->assertSame("`$columnname`", $gen->getEncQuoted($columnname)); break; case 'mssql': // The Moodle connection runs under 'QUOTED_IDENTIFIER ON'. case 'oracle': case 'postgres': case 'sqlite': default: $this->assertSame('"' . $columnname . '"', $gen->getEncQuoted($columnname)); break; } } } /** * Data provider for test_sql_generator_get_rename_field_sql(). * * @return array The type-old-new tuple fixture. */ public function test_sql_generator_get_rename_field_sql_provider() { return array( // Reserved: an example from SQL-92. // Both names should be reserved. [true, 'from', 'where'], // Not reserved. [false, 'my_old_column_name', 'my_awesome_column_name'] ); } /** * This is a unit test for sql_generator::getRenameFieldSQL(). * * @dataProvider test_sql_generator_get_rename_field_sql_provider * @param bool $reserved Whether the column name is reserved or not. * @param string $oldcolumnname The column name to be renamed. * @param string $newcolumnname The new column name. **/ public function test_sql_generator_get_rename_field_sql($reserved, $oldcolumnname, $newcolumnname) { $DB = $this->tdb; $gen = $DB->get_manager()->generator; $prefix = $DB->get_prefix(); $tablename = 'test_get_rename_field_sql'; $table = new xmldb_table($tablename); $field = new xmldb_field($oldcolumnname, XMLDB_TYPE_INTEGER, '11', null, XMLDB_NOTNULL, null, null, null, '0', 'previous'); $dbfamily = $DB->get_dbfamily(); if (!$reserved) { // No need to quote the column name. switch ($dbfamily) { case 'mysql': $this->assertSame( [ "ALTER TABLE {$prefix}$tablename CHANGE $oldcolumnname $newcolumnname BIGINT(11) NOT NULL" ], $gen->getRenameFieldSQL($table, $field, $newcolumnname) ); break; case 'sqlite': // Skip it, since the DB is not supported yet. // BTW renaming a column name is already covered by the integration test 'testRenameField'. break; case 'mssql': // The Moodle connection runs under 'QUOTED_IDENTIFIER ON'. $this->assertSame( [ "sp_rename '{$prefix}$tablename.[$oldcolumnname]', '$newcolumnname', 'COLUMN'" ], $gen->getRenameFieldSQL($table, $field, $newcolumnname) ); break; case 'oracle': case 'postgres': default: $this->assertSame( [ "ALTER TABLE {$prefix}$tablename RENAME COLUMN $oldcolumnname TO $newcolumnname" ], $gen->getRenameFieldSQL($table, $field, $newcolumnname) ); break; } } else { // Column name should be quoted. switch ($dbfamily) { case 'mysql': $this->assertSame( [ "ALTER TABLE {$prefix}$tablename CHANGE `$oldcolumnname` `$newcolumnname` BIGINT(11) NOT NULL" ], $gen->getRenameFieldSQL($table, $field, $newcolumnname) ); break; case 'sqlite': // Skip it, since the DB is not supported yet. // BTW renaming a column name is already covered by the integration test 'testRenameField'. break; case 'mssql': // The Moodle connection runs under 'QUOTED_IDENTIFIER ON'. $this->assertSame( [ "sp_rename '{$prefix}$tablename.[$oldcolumnname]', '$newcolumnname', 'COLUMN'" ], $gen->getRenameFieldSQL($table, $field, $newcolumnname) ); break; case 'oracle': case 'postgres': default: $this->assertSame( [ "ALTER TABLE {$prefix}$tablename RENAME COLUMN \"$oldcolumnname\" TO \"$newcolumnname\"" ], $gen->getRenameFieldSQL($table, $field, $newcolumnname) ); break; } } } public function test_get_nullable_fields_in_index() { $DB = $this->tdb; $gen = $DB->get_manager()->generator; $indexwithoutnulls = $this->tables['test_table0']->getIndex('type-name'); $this->assertSame([], $gen->get_nullable_fields_in_index( $this->tables['test_table0'], $indexwithoutnulls)); $indexwithnulls = new xmldb_index('course-grade', XMLDB_INDEX_UNIQUE, ['course', 'grade']); $this->assertSame(['grade'], $gen->get_nullable_fields_in_index( $this->tables['test_table0'], $indexwithnulls)); $this->create_deftable('test_table0'); // Now test using a minimal xmldb_table, to ensure we get the data from the DB. $table = new xmldb_table('test_table0'); $this->assertSame([], $gen->get_nullable_fields_in_index( $table, $indexwithoutnulls)); $this->assertSame(['grade'], $gen->get_nullable_fields_in_index( $table, $indexwithnulls)); } // Following methods are not supported == Do not test. /* public function testRenameIndex() { // Unsupported! $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table0'); $index = new xmldb_index('course'); $index->set_attributes(XMLDB_INDEX_UNIQUE, array('course')); $this->assertTrue($dbman->rename_index($table, $index, 'newindexname')); } public function testRenameKey() { // Unsupported! $dbman = $this->tdb->get_manager(); $table = $this->create_deftable('test_table0'); $key = new xmldb_key('course'); $key->set_attributes(XMLDB_KEY_UNIQUE, array('course')); $this->assertTrue($dbman->rename_key($table, $key, 'newkeyname')); } */ /** * Tests check_database_schema(). */ public function test_check_database_schema() { global $CFG, $DB; $dbmanager = $DB->get_manager(); // Create a table in the database we will be using to compare with a schema. $table = new xmldb_table('test_check_db_schema'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('extracolumn', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); $table->add_field('courseid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_key('extraindex', XMLDB_KEY_UNIQUE, array('extracolumn')); $table->setComment("This is a test table, you can drop it safely."); $dbmanager->create_table($table); // Remove the column so it is not added to the schema and gets reported as an extra column. $table->deleteField('extracolumn'); // Change the 'courseid' field to a float in the schema so it gets reported as different. $table->deleteField('courseid'); $table->add_field('courseid', XMLDB_TYPE_NUMBER, '10, 2', null, XMLDB_NOTNULL, null, null); // Add another column to the schema that won't be present in the database and gets reported as missing. $table->add_field('missingcolumn', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); // Add another key to the schema that won't be present in the database and gets reported as missing. $table->add_key('missingkey', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id')); // Remove the key from the schema which will still be present in the database and reported as extra. $table->deleteKey('extraindex'); $schema = new xmldb_structure('testschema'); $schema->addTable($table); // Things we want to check for - // 1. Changed columns. // 2. Missing columns. // 3. Missing indexes. // 4. Unexpected index. // 5. Extra columns. $errors = $dbmanager->check_database_schema($schema)['test_check_db_schema']; // Preprocess $errors to get rid of the non compatible (SQL-dialect dependent) parts. array_walk($errors, function(&$error) { $error = trim(strtok($error, PHP_EOL)); }); $this->assertCount(5, $errors); $this->assertContains("column 'courseid' has incorrect type 'I', expected 'N'", $errors); $this->assertContains("column 'missingcolumn' is missing", $errors); $this->assertContains("Missing index 'missingkey' (not unique (courseid)).", $errors); $this->assertContains("Unexpected index '{$CFG->prefix}testchecdbsche_ext_uix'.", $errors); $this->assertContains("column 'extracolumn' is not expected (I)", $errors); } }
michael-milette/moodle
lib/ddl/tests/ddl_test.php
PHP
gpl-3.0
110,551
// @(#)root/ged:$Id$ // Author: Carsten Hof 16/08/04 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TH1Editor #define ROOT_TH1Editor ////////////////////////////////////////////////////////////////////////// // // // TH1Editor // // // // Editor changing histogram attributes (Type, Coords, Error, Style) // // // ////////////////////////////////////////////////////////////////////////// #include "TGedFrame.h" class TH1; class TGComboBox; class TGNumberEntry; class TGCheckButton; class TGButtonGroup; class TGHButtonGroup; class TString; class TGRadioButton; class TGDoubleHSlider; class TGHSlider; class TGTextEntry; class TGNumberEntryField; class TGTextButton; class TH1Editor : public TGedFrame { protected: TH1 *fHist; // histogram object Bool_t fSameOpt; // flag for option "same" TGCompositeFrame *fBin; // Contains the Binning Widgets Int_t fTitlePrec; // font precision level TGTextEntry *fTitle; // histogram title input field TGHButtonGroup *fDimGroup; // Radiobuttongroup to change 2D <-> 3D-Plot TGRadioButton *fDim; // 2D-Plot RadioButton TGRadioButton *fDim0; // 3D-Plot RadioButton TGLayoutHints *fDimlh; // layout hints for 2D-Plot RadioButton TGLayoutHints *fDim0lh; // layout hints for 3D-Plot RadioButton TGComboBox *fTypeCombo; // histogram type combo box TGComboBox *fCoordsCombo; // Coordinate System combo box TGComboBox *fErrorCombo; // Error combo box TGCheckButton *fHistOnOff; // Draw a simple histogram with default options TGCheckButton *fAddMarker; // Draw a Marker on top of each bin TGCheckButton *fAddB; // Draw a Bar Chart TGCheckButton *fAddBar; // Bar Option TGCheckButton *fAdd; // Activate more Options TGCheckButton *fMakeHBar; // Draw Horizontal Bar Chart TGCheckButton *fAddSimple; // Draw a simple histogram (==HIST draw option) TGNumberEntry *fBarWidth; // Change the Bar Width TGNumberEntry *fBarOffset; // Change the Bar Offset TGComboBox *fAddCombo; // Add Lines, Bars, Fill TGComboBox *fPercentCombo; // Percentage of the Bar which is drawn in a different color TGCompositeFrame *f3; // Contains Histogram Type TGCompositeFrame *f6; // Contains the Add-ComboBox (Style) TGCompositeFrame *f7; // Contains the Marker OnOff CheckBox TGCompositeFrame *f8; // Contains the Bar Chart CheckBox TGCompositeFrame *f9; // Contains the Bar Option CheckBox TGCompositeFrame *f10; // Contains the Bar Option Title TGCompositeFrame *f11; // Contains the Bar Width/Offset NumberEntries TGCompositeFrame *f12; // Contains fPercentCombo, fMakeHBar TGCompositeFrame *f15; // Contains outer line CheckBox TGCompositeFrame *fBinCont; // Contains the Rebin Widgets for case 1 TGCompositeFrame *fBinCont1; // Contains the Rebin Widgets for case 2 TGHSlider *fBinSlider; // Slider to set rebinning integer value TGHSlider *fBinSlider1; // Slider to set rebinning integer value for ntuple histogram TGNumberEntryField *fBinNumberEntry; // Label which shows the rebinned bin number TGNumberEntryField *fBinNumberEntry1; // Label which shows the rebinned bin number for ntuple histogram TGHSlider *fBinOffsetSld; // Add an offset to the origin of the histogram TGNumberEntryField *fOffsetNumberEntry;// Shows the offset to the origin of the histogram TGDoubleHSlider *fSlider; // Slider to set x-axis range TGNumberEntryField *fSldMin; // Contains the minimum value of the x-Axis TGNumberEntryField *fSldMax; // Contains the maximum value of the x-Axis TGCheckButton *fDelaydraw; // Delayed drawing of the new axis range TGTextButton *fApply; // Apply-Button to accept the rebinned histogram TGTextButton *fCancel; // Cancel-Button to reprobate the rebinned histogram static TGComboBox *BuildHistTypeComboBox(TGFrame *parent, Int_t id); // builts the Type ComboBox static TGComboBox *BuildHistCoordsComboBox(TGFrame *parent, Int_t id); // builts the Coordinate ComboBox static TGComboBox *BuildHistErrorComboBox(TGFrame *parent, Int_t id); // builts the Error ComboBox static TGComboBox *BuildHistAddComboBox(TGFrame *parent, Int_t id); // builts the Add ComboBox static TGComboBox *BuildPercentComboBox(TGFrame *parent, Int_t id); // builts the ComboBox for setting the Bar options bar1,..., bar4 virtual void ConnectSignals2Slots(); // connect the signals to the slots void CreateBinTab(); // Creates the Bin Tab (part of the SetGedEditor) private: Bool_t fMake; // Veto Variable Bool_t fMakeB; // avoid execution of Bar Slots Int_t fPx1old, // save the coordinates of the "virtual box" in delay draw mode (2D Plot) fPy1old, fPx2old, fPy2old; Float_t fP1NDCold[3], // save the coordinates of the "virtual box" in delay draw mode fP2NDCold[3], fP3NDCold[3], fP4NDCold[3]; Float_t fP1old[3], // save the coordinates of the "virtual box" in delay draw mode (3D plot) fP2old[3], fP3old[3], fP4old[3], fP5old[3], fP6old[3], fP7old[3], fP8old[3]; TH1 *fBinHist; // Cloned histogram for rebin Double_t fOldOffset; // save the old offset of the histogram TString GetHistTypeLabel(); // Get the Histogram Type = String which contains the Histogram Draw Option TString GetHistCoordsLabel(); // Get the histogram coordinate system (CYL, SPH, PSR, ..) TString GetHistErrorLabel(); // Get the histogram Error type (E1, .., E4) TString GetHistAddLabel(); // Get the histogram addon (smooth line, simple line, ..) void ChangeErrorCombo(Int_t i); public: TH1Editor(const TGWindow *p = 0, Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); virtual ~TH1Editor(); virtual Bool_t AcceptModel(TObject* model); virtual void SetModel(TObject* obj); virtual void DoTitle(const char *text); virtual void DoAddMarker(Bool_t on); virtual void DoAddBar(Bool_t); virtual void DoAddB(Bool_t); virtual void DoAddSimple(Bool_t on); virtual void DoHistSimple(); virtual void DoHistComplex(); virtual void DoHistChanges(); virtual void DoHistView(); virtual void DoBarOffset(); virtual void DoBarWidth(); virtual void DoPercent(); virtual void DoHBar(Bool_t on); virtual void DoSliderMoved(); virtual void DoSliderPressed(); virtual void DoSliderReleased(); virtual void DoAxisRange(); virtual void DoBinMoved(Int_t number); virtual void DoBinReleased(); virtual void DoBinPressed(); virtual void DoBinLabel(); virtual void DoBinReleased1(); virtual void DoBinMoved1(); virtual void DoBinLabel1(); virtual void DoOffsetMoved(Int_t num); virtual void DoOffsetReleased(); virtual void DoOffsetPressed(); virtual void DoBinOffset(); virtual void DoApply(); virtual void DoCancel(); virtual void PaintBox3D(Float_t *p1, Float_t *p2,Float_t *p3, Float_t *p4); Int_t* Dividers(Int_t n); virtual void RecursiveRemove(TObject* obj); ClassDef(TH1Editor,0) // TH1 editor }; #endif
mhuwiler/rootauto
gui/ged/inc/TH1Editor.h
C
lgpl-2.1
9,040