using System;
using NUnit.Framework;

namespace Tests.Diagnostics
{
    [TestFixture]
    class Program
    {
        [Test]
        public void Foo()
        {
            var str = "";
            Assert.AreEqual(str, ""); // Noncompliant {{Make sure these 2 arguments are in the correct order: expected value, actual value.}}
//                          ^^^^^^^
            Assert.AreSame(str, ""); // Noncompliant
//                         ^^^^^^^

            double d = 42;
            Assert.AreEqual(d, 42); // Noncompliant
//                          ^^^^^
            Assert.AreSame(d, 42); // Noncompliant
            Assert.AreEqual(d, 42, 1, "message"); // Noncompliant

            Assert.AreEqual("", str);
            Assert.AreSame("", str);
            Assert.AreEqual(42, d, 1, "message");
        }
    }
}

{'repo_name': 'SonarSource/sonar-dotnet', 'stars': '411', 'repo_language': 'C#', 'file_name': 'Akka.TestKit.Xunit.csproj', 'mime_type': 'text/xml', 'hash': -1518777211266410595, 'source_dataset': 'data'}


# Copyright 2018 Google LLC.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
#    contributors may be used to endorse or promote products derived from this
#    software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Library of application-specific errors.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import contextlib
import errno
import sys

from absl import logging

class Error(Exception):
  """Base class for core error types."""

class CommandLineError(Error):
  """Exception class related to invalid command-line flags."""

def log_and_raise(msg, exception_class=Error):
  """Logs the given message at ERROR level and raises exception.

  Args:
    msg: [`string`]. The message to log and use in the raised exception.
    exception_class: [`Exception`]. The class of exception to raise.

  Raises:
    Error: An exception of the type specified by the input exception_class.
  """
  logging.error(msg)
  raise exception_class(msg)

@contextlib.contextmanager
def clean_commandline_error_exit(
    allowed_exceptions=(Error, CommandLineError), exit_value=errno.ENOENT):
  """Wraps commands to capture certain exceptions and exit without stacktraces.

  This function is intended to wrap all code within main() of Python binaries
  to provide a mechanism for user errors to exit abnormally without causing
  exceptions to be thrown. Any exceptions that are subclasses of those listed
  in `allowed_exceptions` will be caught and the program will quietly exit with
  `exit_value`. Other exceptions are propagated normally.

  NOTE: This function should only be used as a context manager and its usage
  should be limited to main().

  Args:
    allowed_exceptions: [`tuple of Exception`]. A tuple of Exception classes
      that should not be raised, but instead quietly caused to exit the program.
    exit_value: [`int`]. The value to return upon program exit.

  Yields:
    The yield in this function is used to allow the block nested in the "with"
    statement to be executed.
  """
  try:
    yield
  except allowed_exceptions:
    sys.exit(exit_value)

{'repo_name': 'google/deepvariant', 'stars': '1992', 'repo_language': 'Python', 'file_name': 'requires.txt', 'mime_type': 'text/plain', 'hash': 6855548021898038587, 'source_dataset': 'data'}


/*
 *  /MathJax/localization/gl/TeX.js
 *
 *  Copyright (c) 2009-2015 The MathJax Consortium
 *
 *  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.
 */

MathJax.Localization.addTranslation("gl","TeX",{version:"2.6.0",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/gl/TeX.js");

{'repo_name': 'staticfile/static', 'stars': '1265', 'repo_language': 'None', 'file_name': 'ko.json', 'mime_type': 'text/plain', 'hash': -136880491685078072, 'source_dataset': 'data'}


#include <stdlib.h>
#include <inttypes.h>
#include <assert.h>

#include "registers.h"

char carp_reverse_reg[][5] = {
  "r0",
  "r1",
  "r2",
  "r3",
  "r4",
  "r5",
  "r6",
  "r7",
  "r8",
  "r9",
  "ax",
  "bx",
  "cx",
  "dx",
  "rx",
  "ip",
  "sp",
  "fp",
  "gbg",
  "run",
  "ext",
  "undef",
};

/*
  Returns a pointer to a register.
*/
carp_value *carp_reg_get (carp_value regs[], carp_reg reg) {
  assert(regs != NULL);

  if (reg >= CARP_NUM_REGS)
    return NULL;

  return &regs[reg];
}

/*
  Set the value in a given register. Fails if register is outside bounds.
*/
carp_bool carp_reg_set (carp_value regs[], carp_reg reg, carp_value value) {
  assert(regs != NULL);

  carp_value *res = carp_reg_get(regs, reg);
  if (res == NULL)
    return 1;

  *res = value;
  return 0;
}

/*
  Adds a value to a register.
*/
carp_bool carp_reg_add (carp_value regs[], carp_reg reg, carp_value value) {
  assert(regs != NULL);

  carp_value *res = carp_reg_get(regs, reg);
  if (res == NULL)
    return 1;

  *res += value;
  return 0;
}

/*
  Subtracts a value from a register.
*/
carp_bool carp_reg_sub (carp_value regs[], carp_reg reg, carp_value value) {
  assert(regs != NULL);

  carp_value *res = carp_reg_get(regs, reg);
  if (res == NULL)
    return 1;

  *res -= value;
  return 0;
}

/*
  Increments a register.
*/
carp_bool carp_reg_inc (carp_value regs[], carp_reg reg) {
  assert(regs != NULL);

  assert(regs != NULL);

  carp_value *res = carp_reg_get(regs, reg);
  if (res == NULL)
    return 1;

  carp_reg_add(regs, reg, 1);
  return 0;
}

/*
  Decrements a register.
*/
carp_bool carp_reg_dec (carp_value regs[], carp_reg reg) {
  assert(regs != NULL);

  assert(regs != NULL);

  carp_value *res = carp_reg_get(regs, reg);
  if (res == NULL)
    return 1;

  carp_reg_sub(regs, reg, 1);
  return 0;
}

void carp_reg_print (carp_value regs[], FILE *fp) {
  assert(regs != NULL);

  if (fp == NULL)
    fp = stdout;

  fprintf(fp, "{\n");

  for (int i = 0; i < CARP_NUM_REGS; i++)
    fprintf(fp, "%s: %" PRId64 ",\n", carp_reverse_reg[i], regs[i]);

  fprintf(fp, "}\n");
}

/*
  Initialize all the registers to value 0.
*/
void carp_reg_init (carp_value regs[]) {
  assert(regs != NULL);

  for (int i = 0; i < CARP_NUM_REGS; i++)
    carp_reg_set(regs, i, 0);
}

{'repo_name': 'tekknolagi/carp', 'stars': '975', 'repo_language': 'C', 'file_name': 'carp-mode.el', 'mime_type': 'text/x-lisp', 'hash': 6011756341002575554, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   LastUpgradeVersion = "1120"
   wasCreatedForAppExtension = "YES"
   version = "2.0">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "BE257A6A21F64AA30082A47E"
               BuildableName = "Open in Slide.appex"
               BlueprintName = "Open in Slide"
               ReferencedContainer = "container:Slide for Reddit.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "BE8FCA031E0C46090063B8EF"
               BuildableName = "Slide for Reddit.app"
               BlueprintName = "Slide for Reddit"
               ReferencedContainer = "container:Slide for Reddit.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      buildConfiguration = "Debug"
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES">
      <Testables>
         <TestableReference
            skipped = "NO">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "BE99C9F32378AC91007911E2"
               BuildableName = "Slide Screenshot Automation.xctest"
               BlueprintName = "Slide Screenshot Automation"
               ReferencedContainer = "container:Slide for Reddit.xcodeproj">
            </BuildableReference>
         </TestableReference>
      </Testables>
   </TestAction>
   <LaunchAction
      buildConfiguration = "Debug"
      selectedDebuggerIdentifier = ""
      selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"
      launchStyle = "0"
      askForAppToLaunch = "Yes"
      useCustomWorkingDirectory = "NO"
      ignoresPersistentStateOnLaunch = "NO"
      debugDocumentVersioning = "YES"
      debugServiceExtension = "internal"
      allowLocationSimulation = "YES"
      launchAutomaticallySubstyle = "2">
      <BuildableProductRunnable
         runnableDebuggingMode = "0">
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "BE8FCA031E0C46090063B8EF"
            BuildableName = "Slide for Reddit.app"
            BlueprintName = "Slide for Reddit"
            ReferencedContainer = "container:Slide for Reddit.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
   </LaunchAction>
   <ProfileAction
      buildConfiguration = "Release"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      debugDocumentVersioning = "YES"
      launchAutomaticallySubstyle = "2">
      <BuildableProductRunnable
         runnableDebuggingMode = "0">
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "BE8FCA031E0C46090063B8EF"
            BuildableName = "Slide for Reddit.app"
            BlueprintName = "Slide for Reddit"
            ReferencedContainer = "container:Slide for Reddit.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

{'repo_name': 'ccrama/Slide-iOS', 'stars': '309', 'repo_language': 'Swift', 'file_name': 'Info.plist', 'mime_type': 'text/xml', 'hash': -1908348410408881294, 'source_dataset': 'data'}


import {Widget} from '../../ui/Widget';
import {Localization} from '../../ui/Localization';
import {DateTimeField} from './DateTimeField';

export class TimeField extends DateTimeField {}

TimeField.prototype.segment = "time";

Widget.alias('timefield', TimeField);
Localization.registerPrototype('cx/widgets/TimeField', TimeField);

{'repo_name': 'codaxy/cxjs', 'stars': '325', 'repo_language': 'JavaScript', 'file_name': 'imports.js', 'mime_type': 'text/plain', 'hash': 6830616398549290548, 'source_dataset': 'data'}


package com.freedom.lauzy.ticktockmusic.function;

import com.freedom.lauzy.executor.PostExecutionThread;

import javax.inject.Inject;
import javax.inject.Singleton;

import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;

@Singleton
public class UIThread implements PostExecutionThread {

    @Inject
    public UIThread() {
    }

    @Override
    public Scheduler getScheduler() {
        return AndroidSchedulers.mainThread();
    }
}

{'repo_name': 'Lauzy/TicktockMusic', 'stars': '257', 'repo_language': 'Java', 'file_name': 'ExampleUnitTest.java', 'mime_type': 'text/html', 'hash': 1177225750908123832, 'source_dataset': 'data'}


<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
  <file datatype="xml" source-language="en" target-language="ko" original="../DialogQueryName.resx">
    <body>
      <trans-unit id="LabelDescription.Text">
        <source>P&lease enter a name for the new resource.</source>
        <target state="translated">새 리소스의 이름을 입력하십시오(&L).</target>
        <note />
      </trans-unit>
      <trans-unit id="ButtonCancel.Text">
        <source>Cancel</source>
        <target state="translated">취소</target>
        <note />
      </trans-unit>
      <trans-unit id="ButtonAdd.Text">
        <source>&Add</source>
        <target state="translated">추가(&A)</target>
        <note />
      </trans-unit>
      <trans-unit id="$this.Text">
        <source>Add New Resource</source>
        <target state="translated">새 리소스 추가</target>
        <note />
      </trans-unit>
    </body>
  </file>
</xliff>

{'repo_name': 'dotnet/project-system', 'stars': '630', 'repo_language': 'C#', 'file_name': 'Directory.Build.props', 'mime_type': 'text/plain', 'hash': 8809434257409623548, 'source_dataset': 'data'}


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <title>CSS Test: Border-style applied to element with display table</title>
        <link rel="author" title="Microsoft" href="http://www.microsoft.com/" />
        <link rel="reviewer" title="Gérard Talbot" href="http://www.gtalbot.org/BrowserBugsSection/css21testsuite/" />
        <link rel="help" href="http://www.w3.org/TR/CSS21/box.html#border-style-properties" />
        <meta name="flags" content="" />
        <meta name="assert" content="The 'border-style' property applies to elements with a display of table." />

Test passes if there is a single dashed lined box.

{'repo_name': 'web-platform-tests/wpt', 'stars': '2923', 'repo_language': 'HTML', 'file_name': 'newtarget.html', 'mime_type': 'text/html', 'hash': 1482884900525469283, 'source_dataset': 'data'}


# frozen_string_literal: true

require 'test_plugin_helper'

# Tests for the behavior of Ansible Variable, currently only validations
class AnsibleVariableTest < ActiveSupport::TestCase
  should belong_to(:ansible_role)
end

{'repo_name': 'theforeman/foreman_ansible', 'stars': '187', 'repo_language': 'Ruby', 'file_name': 'changelog', 'mime_type': 'text/x-ruby', 'hash': 5032830547339339284, 'source_dataset': 'data'}


/*
Copyright 2017 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package args

import (
	"fmt"
	"path"

	"github.com/spf13/pflag"
	codegenutil "k8s.io/code-generator/pkg/util"
	"k8s.io/gengo/args"
)

// CustomArgs is used by the gengo framework to pass args specific to this generator.
type CustomArgs struct {
	VersionedClientSetPackage string
	InternalClientSetPackage  string
	ListersPackage            string
	SingleDirectory           bool
}

// NewDefaults returns default arguments for the generator.
func NewDefaults() (*args.GeneratorArgs, *CustomArgs) {
	genericArgs := args.Default().WithoutDefaultFlagParsing()
	customArgs := &CustomArgs{
		SingleDirectory: false,
	}
	genericArgs.CustomArgs = customArgs

	if pkg := codegenutil.CurrentPackage(); len(pkg) != 0 {
		genericArgs.OutputPackagePath = path.Join(pkg, "pkg/client/informers")
		customArgs.VersionedClientSetPackage = path.Join(pkg, "pkg/client/clientset/versioned")
		customArgs.InternalClientSetPackage = path.Join(pkg, "pkg/client/clientset/internalversion")
		customArgs.ListersPackage = path.Join(pkg, "pkg/client/listers")
	}

	return genericArgs, customArgs
}

// AddFlags add the generator flags to the flag set.
func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet) {
	fs.StringVar(&ca.InternalClientSetPackage, "internal-clientset-package", ca.InternalClientSetPackage, "the full package name for the internal clientset to use")
	fs.StringVar(&ca.VersionedClientSetPackage, "versioned-clientset-package", ca.VersionedClientSetPackage, "the full package name for the versioned clientset to use")
	fs.StringVar(&ca.ListersPackage, "listers-package", ca.ListersPackage, "the full package name for the listers to use")
	fs.BoolVar(&ca.SingleDirectory, "single-directory", ca.SingleDirectory, "if true, omit the intermediate \"internalversion\" and \"externalversions\" subdirectories")
}

// Validate checks the given arguments.
func Validate(genericArgs *args.GeneratorArgs) error {
	customArgs := genericArgs.CustomArgs.(*CustomArgs)

	if len(genericArgs.OutputPackagePath) == 0 {
		return fmt.Errorf("output package cannot be empty")
	}
	if len(customArgs.VersionedClientSetPackage) == 0 {
		return fmt.Errorf("versioned clientset package cannot be empty")
	}
	if len(customArgs.ListersPackage) == 0 {
		return fmt.Errorf("listers package cannot be empty")
	}

	return nil
}

{'repo_name': 'kubesphere/kubesphere', 'stars': '3860', 'repo_language': 'Go', 'file_name': 'options.go', 'mime_type': 'text/plain', 'hash': 2656010285221465346, 'source_dataset': 'data'}


/*
Copyright The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Code generated by lister-gen. DO NOT EDIT.

package v1beta1

import (
	v1beta1 "k8s.io/api/discovery/v1beta1"
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/tools/cache"
)

// EndpointSliceLister helps list EndpointSlices.
// All objects returned here must be treated as read-only.
type EndpointSliceLister interface {
	// List lists all EndpointSlices in the indexer.
	// Objects returned here must be treated as read-only.
	List(selector labels.Selector) (ret []*v1beta1.EndpointSlice, err error)
	// EndpointSlices returns an object that can list and get EndpointSlices.
	EndpointSlices(namespace string) EndpointSliceNamespaceLister
	EndpointSliceListerExpansion
}

// endpointSliceLister implements the EndpointSliceLister interface.
type endpointSliceLister struct {
	indexer cache.Indexer
}

// NewEndpointSliceLister returns a new EndpointSliceLister.
func NewEndpointSliceLister(indexer cache.Indexer) EndpointSliceLister {
	return &endpointSliceLister{indexer: indexer}
}

// List lists all EndpointSlices in the indexer.
func (s *endpointSliceLister) List(selector labels.Selector) (ret []*v1beta1.EndpointSlice, err error) {
	err = cache.ListAll(s.indexer, selector, func(m interface{}) {
		ret = append(ret, m.(*v1beta1.EndpointSlice))
	})
	return ret, err
}

// EndpointSlices returns an object that can list and get EndpointSlices.
func (s *endpointSliceLister) EndpointSlices(namespace string) EndpointSliceNamespaceLister {
	return endpointSliceNamespaceLister{indexer: s.indexer, namespace: namespace}
}

// EndpointSliceNamespaceLister helps list and get EndpointSlices.
// All objects returned here must be treated as read-only.
type EndpointSliceNamespaceLister interface {
	// List lists all EndpointSlices in the indexer for a given namespace.
	// Objects returned here must be treated as read-only.
	List(selector labels.Selector) (ret []*v1beta1.EndpointSlice, err error)
	// Get retrieves the EndpointSlice from the indexer for a given namespace and name.
	// Objects returned here must be treated as read-only.
	Get(name string) (*v1beta1.EndpointSlice, error)
	EndpointSliceNamespaceListerExpansion
}

// endpointSliceNamespaceLister implements the EndpointSliceNamespaceLister
// interface.
type endpointSliceNamespaceLister struct {
	indexer   cache.Indexer
	namespace string
}

// List lists all EndpointSlices in the indexer for a given namespace.
func (s endpointSliceNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.EndpointSlice, err error) {
	err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
		ret = append(ret, m.(*v1beta1.EndpointSlice))
	})
	return ret, err
}

// Get retrieves the EndpointSlice from the indexer for a given namespace and name.
func (s endpointSliceNamespaceLister) Get(name string) (*v1beta1.EndpointSlice, error) {
	obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
	if err != nil {
		return nil, err
	}
	if !exists {
		return nil, errors.NewNotFound(v1beta1.Resource("endpointslice"), name)
	}
	return obj.(*v1beta1.EndpointSlice), nil
}

{'repo_name': 'kubernetes/autoscaler', 'stars': '3328', 'repo_language': 'Go', 'file_name': 'PATENTS', 'mime_type': 'text/plain', 'hash': 4566464443776544938, 'source_dataset': 'data'}


/*
 * Copyright 2013-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.cloud.contract.spec.internal;

import java.util.Objects;
import java.util.function.Consumer;

import groovy.lang.Closure;
import groovy.lang.DelegatesTo;

import org.springframework.cloud.contract.spec.util.ValidateUtils;

/**
 * Represents a URL that may contain query parameters.
 *
 * @since 1.0.0
 */
public class Url extends DslProperty {

	private QueryParameters queryParameters;

	public Url(DslProperty prop) {
		super(prop.getClientValue(), prop.getServerValue());
		ValidateUtils.validateServerValueIsAvailable(prop.getServerValue(), "Url");
	}

	public Url(Object url) {
		super(url, testUrl(url));
		ValidateUtils.validateServerValueIsAvailable(url, "Url");
	}

	// Can be overridable by extensions
	private static Object testUrl(Object url) {
		return DslPropertyConverter.INSTANCE.testSide(url);
	}

	public QueryParameters getQueryParameters() {
		return queryParameters;
	}

	public void setQueryParameters(QueryParameters queryParameters) {
		this.queryParameters = queryParameters;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}
		if (!super.equals(o)) {
			return false;
		}
		Url url = (Url) o;
		return Objects.equals(queryParameters, url.queryParameters);
	}

	@Override
	public int hashCode() {
		return Objects.hash(super.hashCode(), queryParameters);
	}

	@Override
	public String toString() {
		return "Url{" + "\nqueryParameters=" + queryParameters + "} \n" + super.toString();
	}

	/**
	 * The query parameters part of the contract.
	 * @param consumer function to manipulate the query parameters
	 */
	public void queryParameters(Consumer<QueryParameters> consumer) {
		this.queryParameters = new QueryParameters();
		consumer.accept(this.queryParameters);
	}

	/**
	 * The query parameters part of the contract.
	 * @param consumer function to manipulate the query parameters
	 */
	public void queryParameters(@DelegatesTo(QueryParameters.class) Closure consumer) {
		this.queryParameters = new QueryParameters();
		consumer.setDelegate(this.queryParameters);
		consumer.call();
	}

}

{'repo_name': 'spring-cloud/spring-cloud-contract', 'stars': '525', 'repo_language': 'Java', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -5693747261629147769, 'source_dataset': 'data'}


#include "hud.h"
#include "cl_util.h"
#include "camera.h"
#include "kbutton.h"
#include "cvardef.h"
#include "usercmd.h"
#include "const.h"
#include "camera.h"
#include "in_defs.h"

#include "APIProxy.h"
#include "Exports.h"

#include "windows.h"
#include "build.h"

float CL_KeyState (kbutton_t *key);
extern "C"
{
	void CL_DLLEXPORT CAM_Think( void );
	int CL_DLLEXPORT CL_IsThirdPerson( void );
	void CL_DLLEXPORT CL_CameraOffset( float *ofs );
}

extern cl_enginefunc_t gEngfuncs;

//-------------------------------------------------- Constants

#define CAM_DIST_DELTA 1.0
#define CAM_ANGLE_DELTA 2.5
#define CAM_ANGLE_SPEED 2.5
#define CAM_MIN_DIST 30.0
#define CAM_ANGLE_MOVE .5
#define MAX_ANGLE_DIFF 10.0
#define PITCH_MAX 90.0
#define PITCH_MIN 0
#define YAW_MAX  135.0
#define YAW_MIN	 -135.0

enum ECAM_Command
{
	CAM_COMMAND_NONE = 0,
	CAM_COMMAND_TOTHIRDPERSON = 1,
	CAM_COMMAND_TOFIRSTPERSON = 2
};

//-------------------------------------------------- Global Variables

cvar_t	*cam_command;
cvar_t	*cam_snapto;
cvar_t	*cam_idealyaw;
cvar_t	*cam_idealpitch;
cvar_t	*cam_idealdist;
cvar_t	*cam_contain;

cvar_t	*c_maxpitch;
cvar_t	*c_minpitch;
cvar_t	*c_maxyaw;
cvar_t	*c_minyaw;
cvar_t	*c_maxdistance;
cvar_t	*c_mindistance;

// pitch, yaw, dist
vec3_t cam_ofs;

// In third person
int cam_thirdperson;
int cam_mousemove; //true if we are moving the cam with the mouse, False if not
int iMouseInUse=0;
int cam_distancemove;
extern int mouse_x, mouse_y;  //used to determine what the current x and y values are
int cam_old_mouse_x, cam_old_mouse_y; //holds the last ticks mouse movement
POINT		cam_mouse;
//-------------------------------------------------- Local Variables

static kbutton_t cam_pitchup, cam_pitchdown, cam_yawleft, cam_yawright;
static kbutton_t cam_in, cam_out, cam_move;

//-------------------------------------------------- Prototypes

void CAM_ToThirdPerson(void);
void CAM_ToFirstPerson(void);
void CAM_StartDistance(void);
void CAM_EndDistance(void);

//-------------------------------------------------- Local Functions

float MoveToward( float cur, float goal, float maxspeed )
{
	if( cur != goal )
	{
		if( abs( cur - goal ) > 180.0 )
		{
			if( cur < goal )
				cur += 360.0;
			else
				cur -= 360.0;
		}

		if( cur < goal )
		{
			if( cur < goal - 1.0 )
				cur += ( goal - cur ) / 4.0;
			else
				cur = goal;
		}
		else
		{
			if( cur > goal + 1.0 )
				cur -= ( cur - goal ) / 4.0;
			else
				cur = goal;
		}
	}

	// bring cur back into range
	if( cur < 0 )
		cur += 360.0;
	else if( cur >= 360 )
		cur -= 360;

	return cur;
}

//-------------------------------------------------- Gobal Functions

typedef struct
{
	vec3_t		boxmins, boxmaxs;// enclose the test object along entire move
	float		*mins, *maxs;	// size of the moving object
	vec3_t		mins2, maxs2;	// size when clipping against mosnters
	float		*start, *end;
	trace_t		trace;
	int			type;
	edict_t		*passedict;
	qboolean	monsterclip;
} moveclip_t;

extern trace_t SV_ClipMoveToEntity (edict_t *ent, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end);

void CL_DLLEXPORT CAM_Think( void )
{
	RecClCamThink();

#ifdef HL_CAMERA
	vec3_t origin;
	vec3_t ext, pnt, camForward, camRight, camUp;
	moveclip_t	clip;
	float dist;
	vec3_t camAngles;
	float flSensitivity;
#ifdef LATER
	int i;
#endif
	vec3_t viewangles;

	switch( (int) cam_command->value )
	{
		case CAM_COMMAND_TOTHIRDPERSON:
			CAM_ToThirdPerson();
			break;

		case CAM_COMMAND_TOFIRSTPERSON:
			CAM_ToFirstPerson();
			break;

		case CAM_COMMAND_NONE:
		default:
			break;
	}

	if( !cam_thirdperson )
		return;

#ifdef LATER
	if ( cam_contain->value )
	{
		gEngfuncs.GetClientOrigin( origin );
		ext[0] = ext[1] = ext[2] = 0.0;
	}
#endif

	camAngles[ PITCH ] = cam_idealpitch->value;
	camAngles[ YAW ] = cam_idealyaw->value;
	dist = cam_idealdist->value;
	//
	//movement of the camera with the mouse
	//
	if (cam_mousemove)
	{
	    //get windows cursor position
		GetCursorPos (&cam_mouse);
		//check for X delta values and adjust accordingly
		//eventually adjust YAW based on amount of movement
	  //don't do any movement of the cam using YAW/PITCH if we are zooming in/out the camera
	  if (!cam_distancemove)
	  {

		//keep the camera within certain limits around the player (ie avoid certain bad viewing angles)
		if (cam_mouse.x>gEngfuncs.GetWindowCenterX())
		{
			//if ((camAngles[YAW]>=225.0)||(camAngles[YAW]<135.0))
			if (camAngles[YAW]<c_maxyaw->value)
			{
				camAngles[ YAW ] += (CAM_ANGLE_MOVE)*((cam_mouse.x-gEngfuncs.GetWindowCenterX())/2);
			}
			if (camAngles[YAW]>c_maxyaw->value)
			{

				camAngles[YAW]=c_maxyaw->value;
			}
		}
		else if (cam_mouse.x<gEngfuncs.GetWindowCenterX())
		{
			//if ((camAngles[YAW]<=135.0)||(camAngles[YAW]>225.0))
			if (camAngles[YAW]>c_minyaw->value)
			{
			   camAngles[ YAW ] -= (CAM_ANGLE_MOVE)* ((gEngfuncs.GetWindowCenterX()-cam_mouse.x)/2);

			}
			if (camAngles[YAW]<c_minyaw->value)
			{
				camAngles[YAW]=c_minyaw->value;

			}
		}

		//check for y delta values and adjust accordingly
		//eventually adjust PITCH based on amount of movement
		//also make sure camera is within bounds
		if (cam_mouse.y>gEngfuncs.GetWindowCenterY())
		{
			if(camAngles[PITCH]<c_maxpitch->value)
			{
			    camAngles[PITCH] +=(CAM_ANGLE_MOVE)* ((cam_mouse.y-gEngfuncs.GetWindowCenterY())/2);
			}
			if (camAngles[PITCH]>c_maxpitch->value)
			{
				camAngles[PITCH]=c_maxpitch->value;
			}
		}
		else if (cam_mouse.y<gEngfuncs.GetWindowCenterY())
		{
			if (camAngles[PITCH]>c_minpitch->value)
			{
			   camAngles[PITCH] -= (CAM_ANGLE_MOVE)*((gEngfuncs.GetWindowCenterY()-cam_mouse.y)/2);
			}
			if (camAngles[PITCH]<c_minpitch->value)
			{
				camAngles[PITCH]=c_minpitch->value;
			}
		}

		//set old mouse coordinates to current mouse coordinates
		//since we are done with the mouse

		if ( ( flSensitivity = gHUD.GetSensitivity() ) != 0 )
		{
			cam_old_mouse_x=cam_mouse.x*flSensitivity;
			cam_old_mouse_y=cam_mouse.y*flSensitivity;
		}
		else
		{
			cam_old_mouse_x=cam_mouse.x;
			cam_old_mouse_y=cam_mouse.y;
		}
		SetCursorPos (gEngfuncs.GetWindowCenterX(), gEngfuncs.GetWindowCenterY());
	  }
	}

	//Nathan code here
	if( CL_KeyState( &cam_pitchup ) )
		camAngles[ PITCH ] += CAM_ANGLE_DELTA;
	else if( CL_KeyState( &cam_pitchdown ) )
		camAngles[ PITCH ] -= CAM_ANGLE_DELTA;

	if( CL_KeyState( &cam_yawleft ) )
		camAngles[ YAW ] -= CAM_ANGLE_DELTA;
	else if( CL_KeyState( &cam_yawright ) )
		camAngles[ YAW ] += CAM_ANGLE_DELTA;

	if( CL_KeyState( &cam_in ) )
	{
		dist -= CAM_DIST_DELTA;
		if( dist < CAM_MIN_DIST )
		{
			// If we go back into first person, reset the angle
			camAngles[ PITCH ] = 0;
			camAngles[ YAW ] = 0;
			dist = CAM_MIN_DIST;
		}

	}
	else if( CL_KeyState( &cam_out ) )
		dist += CAM_DIST_DELTA;

	if (cam_distancemove)
	{
		if (cam_mouse.y>gEngfuncs.GetWindowCenterY())
		{
			if(dist<c_maxdistance->value)
			{
			    dist +=CAM_DIST_DELTA * ((cam_mouse.y-gEngfuncs.GetWindowCenterY())/2);
			}
			if (dist>c_maxdistance->value)
			{
				dist=c_maxdistance->value;
			}
		}
		else if (cam_mouse.y<gEngfuncs.GetWindowCenterY())
		{
			if (dist>c_mindistance->value)
			{
			   dist -= (CAM_DIST_DELTA)*((gEngfuncs.GetWindowCenterY()-cam_mouse.y)/2);
			}
			if (dist<c_mindistance->value)
			{
				dist=c_mindistance->value;
			}
		}
		//set old mouse coordinates to current mouse coordinates
		//since we are done with the mouse
		cam_old_mouse_x=cam_mouse.x*gHUD.GetSensitivity();
		cam_old_mouse_y=cam_mouse.y*gHUD.GetSensitivity();
		SetCursorPos (gEngfuncs.GetWindowCenterX(), gEngfuncs.GetWindowCenterY());
	}
#ifdef LATER
	if( cam_contain->value )
	{
		// check new ideal
		VectorCopy( origin, pnt );
		AngleVectors( camAngles, camForward, camRight, camUp );
		for (i=0 ; i<3 ; i++)
			pnt[i] += -dist*camForward[i];

		// check line from r_refdef.vieworg to pnt
		memset ( &clip, 0, sizeof ( moveclip_t ) );
		clip.trace = SV_ClipMoveToEntity( sv.edicts, r_refdef.vieworg, ext, ext, pnt );
		if( clip.trace.fraction == 1.0 )
		{
			// update ideal
			cam_idealpitch->value = camAngles[ PITCH ];
			cam_idealyaw->value = camAngles[ YAW ];
			cam_idealdist->value = dist;
		}
	}
	else
#endif
	{
		// update ideal
		cam_idealpitch->value = camAngles[ PITCH ];
		cam_idealyaw->value = camAngles[ YAW ];
		cam_idealdist->value = dist;
	}

	// Move towards ideal
	VectorCopy( cam_ofs, camAngles );

	gEngfuncs.GetViewAngles( (float *)viewangles );

	if( cam_snapto->value )
	{
		camAngles[ YAW ] = cam_idealyaw->value + viewangles[ YAW ];
		camAngles[ PITCH ] = cam_idealpitch->value + viewangles[ PITCH ];
		camAngles[ 2 ] = cam_idealdist->value;
	}
	else
	{
		if( camAngles[ YAW ] - viewangles[ YAW ] != cam_idealyaw->value )
			camAngles[ YAW ] = MoveToward( camAngles[ YAW ], cam_idealyaw->value + viewangles[ YAW ], CAM_ANGLE_SPEED );

		if( camAngles[ PITCH ] - viewangles[ PITCH ] != cam_idealpitch->value )
			camAngles[ PITCH ] = MoveToward( camAngles[ PITCH ], cam_idealpitch->value + viewangles[ PITCH ], CAM_ANGLE_SPEED );

		if( abs( camAngles[ 2 ] - cam_idealdist->value ) < 2.0 )
			camAngles[ 2 ] = cam_idealdist->value;
		else
			camAngles[ 2 ] += ( cam_idealdist->value - camAngles[ 2 ] ) / 4.0;
	}
#ifdef LATER
	if( cam_contain->value )
	{
		// Test new position
		dist = camAngles[ ROLL ];
		camAngles[ ROLL ] = 0;

		VectorCopy( origin, pnt );
		AngleVectors( camAngles, camForward, camRight, camUp );
		for (i=0 ; i<3 ; i++)
			pnt[i] += -dist*camForward[i];

		// check line from r_refdef.vieworg to pnt
		memset ( &clip, 0, sizeof ( moveclip_t ) );
		ext[0] = ext[1] = ext[2] = 0.0;
		clip.trace = SV_ClipMoveToEntity( sv.edicts, r_refdef.vieworg, ext, ext, pnt );
		if( clip.trace.fraction != 1.0 )
			return;
	}
#endif
	cam_ofs[ 0 ] = camAngles[ 0 ];
	cam_ofs[ 1 ] = camAngles[ 1 ];
	cam_ofs[ 2 ] = dist;

// HL_CAMERA
#endif
}

extern void KeyDown (kbutton_t *b);	// HACK
extern void KeyUp (kbutton_t *b);	// HACK

void CAM_PitchUpDown(void) { KeyDown( &cam_pitchup ); }
void CAM_PitchUpUp(void) { KeyUp( &cam_pitchup ); }
void CAM_PitchDownDown(void) { KeyDown( &cam_pitchdown ); }
void CAM_PitchDownUp(void) { KeyUp( &cam_pitchdown ); }
void CAM_YawLeftDown(void) { KeyDown( &cam_yawleft ); }
void CAM_YawLeftUp(void) { KeyUp( &cam_yawleft ); }
void CAM_YawRightDown(void) { KeyDown( &cam_yawright ); }
void CAM_YawRightUp(void) { KeyUp( &cam_yawright ); }
void CAM_InDown(void) { KeyDown( &cam_in ); }
void CAM_InUp(void) { KeyUp( &cam_in ); }
void CAM_OutDown(void) { KeyDown( &cam_out ); }
void CAM_OutUp(void) { KeyUp( &cam_out ); }

void CAM_ToThirdPerson(void)
{
	vec3_t viewangles;

#if !defined( DEBUG )
	if ( gEngfuncs.GetMaxClients() > 1 )
	{
		// no thirdperson in multiplayer.
		return;
	}
#endif

	gEngfuncs.GetViewAngles( (float *)viewangles );

	if( !cam_thirdperson )
	{
		cam_thirdperson = 1;

		cam_ofs[ YAW ] = viewangles[ YAW ];
		cam_ofs[ PITCH ] = viewangles[ PITCH ];
		cam_ofs[ 2 ] = CAM_MIN_DIST;
	}

	gEngfuncs.Cvar_SetValue( "cam_command", 0 );
}

void CAM_ToFirstPerson(void)
{
	cam_thirdperson = 0;

	gEngfuncs.Cvar_SetValue( "cam_command", 0 );
}

void CAM_ToggleSnapto( void )
{
	cam_snapto->value = !cam_snapto->value;
}

void CAM_Toggle( void )
{
	int a = 0;

#ifdef DEBUG
	if(cam_thirdperson)
	{
		CAM_ToFirstPerson();
	}
	else
	{
		CAM_ToThirdPerson();
	}
#endif
}

void CAM_Init( void )
{
	gEngfuncs.pfnAddCommand( "+campitchup", CAM_PitchUpDown );
	gEngfuncs.pfnAddCommand( "-campitchup", CAM_PitchUpUp );
	gEngfuncs.pfnAddCommand( "+campitchdown", CAM_PitchDownDown );
	gEngfuncs.pfnAddCommand( "-campitchdown", CAM_PitchDownUp );
	gEngfuncs.pfnAddCommand( "+camyawleft", CAM_YawLeftDown );
	gEngfuncs.pfnAddCommand( "-camyawleft", CAM_YawLeftUp );
	gEngfuncs.pfnAddCommand( "+camyawright", CAM_YawRightDown );
	gEngfuncs.pfnAddCommand( "-camyawright", CAM_YawRightUp );
	gEngfuncs.pfnAddCommand( "+camin", CAM_InDown );
	gEngfuncs.pfnAddCommand( "-camin", CAM_InUp );
	gEngfuncs.pfnAddCommand( "+camout", CAM_OutDown );
	gEngfuncs.pfnAddCommand( "-camout", CAM_OutUp );
	gEngfuncs.pfnAddCommand( "thirdperson", CAM_ToThirdPerson );
	gEngfuncs.pfnAddCommand( "firstperson", CAM_ToFirstPerson );
	gEngfuncs.pfnAddCommand( "+cammousemove",CAM_StartMouseMove);
	gEngfuncs.pfnAddCommand( "-cammousemove",CAM_EndMouseMove);
	gEngfuncs.pfnAddCommand( "+camdistance", CAM_StartDistance );
	gEngfuncs.pfnAddCommand( "-camdistance", CAM_EndDistance );
	gEngfuncs.pfnAddCommand( "snapto", CAM_ToggleSnapto );
#ifdef DEBUG
	gEngfuncs.pfnAddCommand( "camtoggle", CAM_Toggle );
#endif

	cam_command				= gEngfuncs.pfnRegisterVariable ( "cam_command", "0", 0 );	 // tells camera to go to thirdperson
	cam_snapto				= gEngfuncs.pfnRegisterVariable ( "cam_snapto", "0", 0 );	 // snap to thirdperson view
	cam_idealyaw			= gEngfuncs.pfnRegisterVariable ( "cam_idealyaw", "90", 0 );	 // thirdperson yaw
	cam_idealpitch			= gEngfuncs.pfnRegisterVariable ( "cam_idealpitch", "0", 0 );	 // thirperson pitch
	cam_idealdist			= gEngfuncs.pfnRegisterVariable ( "cam_idealdist", "64", 0 );	 // thirdperson distance
	cam_contain				= gEngfuncs.pfnRegisterVariable ( "cam_contain", "0", 0 );	// contain camera to world

	c_maxpitch				= gEngfuncs.pfnRegisterVariable ( "c_maxpitch", "90.0", 0 );
	c_minpitch				= gEngfuncs.pfnRegisterVariable ( "c_minpitch", "0.0", 0 );
	c_maxyaw				= gEngfuncs.pfnRegisterVariable ( "c_maxyaw",   "135.0", 0 );
	c_minyaw				= gEngfuncs.pfnRegisterVariable ( "c_minyaw",   "-135.0", 0 );
	c_maxdistance			= gEngfuncs.pfnRegisterVariable ( "c_maxdistance",   "200.0", 0 );
	c_mindistance			= gEngfuncs.pfnRegisterVariable ( "c_mindistance",   "30.0", 0 );
}

void CAM_ClearStates( void )
{
	vec3_t viewangles;

	gEngfuncs.GetViewAngles( (float *)viewangles );

	cam_pitchup.state = 0;
	cam_pitchdown.state = 0;
	cam_yawleft.state = 0;
	cam_yawright.state = 0;
	cam_in.state = 0;
	cam_out.state = 0;

	cam_thirdperson = 0;
	cam_command->value = 0;
	cam_mousemove=0;

	cam_snapto->value = 0;
	cam_distancemove = 0;

	cam_ofs[ 0 ] = 0.0;
	cam_ofs[ 1 ] = 0.0;
	cam_ofs[ 2 ] = CAM_MIN_DIST;

	cam_idealpitch->value = viewangles[ PITCH ];
	cam_idealyaw->value = viewangles[ YAW ];
	cam_idealdist->value = CAM_MIN_DIST;
}

void CAM_StartMouseMove(void)
{
	float flSensitivity;

	//only move the cam with mouse if we are in third person.
	if (cam_thirdperson)
	{
		//set appropriate flags and initialize the old mouse position
		//variables for mouse camera movement
		if (!cam_mousemove)
		{
			cam_mousemove=1;
			iMouseInUse=1;
			GetCursorPos (&cam_mouse);

			if ( ( flSensitivity = gHUD.GetSensitivity() ) != 0 )
			{
				cam_old_mouse_x=cam_mouse.x*flSensitivity;
				cam_old_mouse_y=cam_mouse.y*flSensitivity;
			}
			else
			{
				cam_old_mouse_x=cam_mouse.x;
				cam_old_mouse_y=cam_mouse.y;
			}
		}
	}
	//we are not in 3rd person view..therefore do not allow camera movement
	else
	{
		cam_mousemove=0;
		iMouseInUse=0;
	}
}

//the key has been released for camera movement
//tell the engine that mouse camera movement is off
void CAM_EndMouseMove(void)
{
   cam_mousemove=0;
   iMouseInUse=0;
}

//----------------------------------------------------------
//routines to start the process of moving the cam in or out
//using the mouse
//----------------------------------------------------------
void CAM_StartDistance(void)
{
	//only move the cam with mouse if we are in third person.
	if (cam_thirdperson)
	{
	  //set appropriate flags and initialize the old mouse position
	  //variables for mouse camera movement
	  if (!cam_distancemove)
	  {
		  cam_distancemove=1;
		  cam_mousemove=1;
		  iMouseInUse=1;
		  GetCursorPos (&cam_mouse);
		  cam_old_mouse_x=cam_mouse.x*gHUD.GetSensitivity();
		  cam_old_mouse_y=cam_mouse.y*gHUD.GetSensitivity();
	  }
	}
	//we are not in 3rd person view..therefore do not allow camera movement
	else
	{
		cam_distancemove=0;
		cam_mousemove=0;
		iMouseInUse=0;
	}
}

//the key has been released for camera movement
//tell the engine that mouse camera movement is off
void CAM_EndDistance(void)
{
   cam_distancemove=0;
   cam_mousemove=0;
   iMouseInUse=0;
}

int CL_DLLEXPORT CL_IsThirdPerson( void )
{
	RecClCL_IsThirdPerson();
	return (cam_thirdperson ? 1 : 0) || (g_iUser1 && (g_iUser2 == gEngfuncs.GetLocalPlayer()->index) );
}

void CL_DLLEXPORT CL_CameraOffset( float *ofs )
{
	RecClCL_GetCameraOffsets(ofs);

	VectorCopy( cam_ofs, ofs );
}

{'repo_name': 'unknownworlds/NS', 'stars': '220', 'repo_language': 'C++', 'file_name': 'steam installer.iss', 'mime_type': 'text/plain', 'hash': -8560711708244869205, 'source_dataset': 'data'}


package api_test

import (
	"errors"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/sclevine/agouti/api"
	"github.com/sclevine/agouti/api/internal/mocks"
	. "github.com/sclevine/agouti/internal/matchers"
)

var _ = Describe("Session", func() {
	var (
		bus     *mocks.Bus
		session *Session
	)

	BeforeEach(func() {
		bus = &mocks.Bus{}
		session = &Session{bus}
	})

	Describe("#Delete", func() {
		It("should successfully send a DELETE to the / endpoint", func() {
			Expect(session.Delete()).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("DELETE"))
			Expect(bus.SendCall.Endpoint).To(Equal(""))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.Delete()).To(MatchError("some error"))
			})
		})
	})

	Describe("#GetElement", func() {
		It("should successfully send a POST to the element endpoint", func() {
			_, err := session.GetElement(Selector{"css selector", "#selector"})
			Expect(err).NotTo(HaveOccurred())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("element"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"using": "css selector", "value": "#selector"}`))
		})

		It("should successfully return an element with an ID and session", func() {
			bus.SendCall.Result = `{"ELEMENT": "some-id"}`
			element, err := session.GetElement(Selector{})
			Expect(err).NotTo(HaveOccurred())
			Expect(element.ID).To(Equal("some-id"))
			Expect(element.Session).To(ExactlyEqual(session))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				_, err := session.GetElement(Selector{})
				Expect(err).To(MatchError("some error"))
			})
		})
	})

	Describe("#GetElements", func() {
		It("should successfully send a POST to the elements endpoint", func() {
			_, err := session.GetElements(Selector{"css selector", "#selector"})
			Expect(err).NotTo(HaveOccurred())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("elements"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"using": "css selector", "value": "#selector"}`))
		})

		It("should return a slice of elements with IDs and sessions", func() {
			bus.SendCall.Result = `[{"ELEMENT": "some-id"}, {"ELEMENT": "some-other-id"}]`
			elements, err := session.GetElements(Selector{"css selector", "#selector"})
			Expect(err).NotTo(HaveOccurred())
			Expect(elements[0].ID).To(Equal("some-id"))
			Expect(elements[0].Session).To(ExactlyEqual(session))
			Expect(elements[1].ID).To(Equal("some-other-id"))
			Expect(elements[1].Session).To(ExactlyEqual(session))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				_, err := session.GetElements(Selector{"css selector", "#selector"})
				Expect(err).To(MatchError("some error"))
			})
		})
	})

	Describe("#GetActiveElement", func() {
		It("should successfully send a POST to the element/active endpoint", func() {
			_, err := session.GetActiveElement()
			Expect(err).NotTo(HaveOccurred())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("element/active"))
		})

		It("should return the active element with an ID and session", func() {
			bus.SendCall.Result = `{"ELEMENT": "some-id"}`
			element, err := session.GetActiveElement()
			Expect(err).NotTo(HaveOccurred())
			Expect(element.ID).To(Equal("some-id"))
			Expect(element.Session).To(ExactlyEqual(session))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				_, err := session.GetActiveElement()
				Expect(err).To(MatchError("some error"))
			})
		})
	})

	Describe("#GetWindow", func() {
		It("should successfully send a GET to the window_handle endpoint", func() {
			_, err := session.GetWindow()
			Expect(err).NotTo(HaveOccurred())
			Expect(bus.SendCall.Method).To(Equal("GET"))
			Expect(bus.SendCall.Endpoint).To(Equal("window_handle"))
		})

		It("should return the current window with the retrieved ID and session", func() {
			bus.SendCall.Result = `"some-id"`
			window, err := session.GetWindow()
			Expect(err).NotTo(HaveOccurred())
			Expect(window.ID).To(Equal("some-id"))
			Expect(window.Session).To(ExactlyEqual(session))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				_, err := session.GetWindow()
				Expect(err).To(MatchError("some error"))
			})
		})
	})

	Describe("#GetWindows", func() {
		It("should successfully send a GET to the window_handles endpoint", func() {
			_, err := session.GetWindows()
			Expect(err).NotTo(HaveOccurred())
			Expect(bus.SendCall.Method).To(Equal("GET"))
			Expect(bus.SendCall.Endpoint).To(Equal("window_handles"))
		})

		It("should return all windows with their retrieved IDs and sessions", func() {
			bus.SendCall.Result = `["some-id", "some-other-id"]`
			windows, err := session.GetWindows()
			Expect(err).NotTo(HaveOccurred())
			Expect(windows[0].ID).To(Equal("some-id"))
			Expect(windows[0].Session).To(ExactlyEqual(session))
			Expect(windows[1].ID).To(Equal("some-other-id"))
			Expect(windows[1].Session).To(ExactlyEqual(session))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				_, err := session.GetWindows()
				Expect(err).To(MatchError("some error"))
			})
		})
	})

	Describe("#SetWindow", func() {
		It("should successfully send a POST to the window endpoint", func() {
			window := &Window{ID: "some-id"}
			Expect(session.SetWindow(window)).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("window"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"name": "some-id"}`))
		})

		Context("when the window is nil", func() {
			It("should return an error", func() {
				Expect(session.SetWindow(nil)).To(MatchError("nil window is invalid"))
			})
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.SetWindow(&Window{})).To(MatchError("some error"))
			})
		})
	})

	Describe("#SetWindowByName", func() {
		It("should successfully send a POST to the window endpoint", func() {
			Expect(session.SetWindowByName("some name")).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("window"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"name": "some name"}`))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.SetWindowByName("")).To(MatchError("some error"))
			})
		})
	})

	Describe("#DeleteWindow", func() {
		It("should successfully send a DELETE to the window endpoint", func() {
			Expect(session.DeleteWindow()).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("DELETE"))
			Expect(bus.SendCall.Endpoint).To(Equal("window"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				err := session.DeleteWindow()
				Expect(err).To(MatchError("some error"))
			})
		})
	})

	Describe("#GetCookies", func() {
		It("should successfully send a GET to the cookie endpoint", func() {
			_, err := session.GetCookies()
			Expect(err).NotTo(HaveOccurred())
			Expect(bus.SendCall.Method).To(Equal("GET"))
			Expect(bus.SendCall.Endpoint).To(Equal("cookie"))
		})

		It("should return the cookies", func() {
			bus.SendCall.Result = `[{"name": "some-cookie"}, {"name": "some-other-cookie"}]`
			cookies, err := session.GetCookies()
			Expect(err).NotTo(HaveOccurred())
			Expect(cookies).To(Equal([]*Cookie{
				{Name: "some-cookie"},
				{Name: "some-other-cookie"},
			}))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				_, err := session.GetCookies()
				Expect(err).To(MatchError("some error"))
			})
		})
	})

	Describe("#SetCookie", func() {
		It("should successfully send a POST to the cookie endpoint", func() {
			Expect(session.SetCookie(&Cookie{Name: "some-cookie"})).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("cookie"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"cookie": {"name": "some-cookie", "value": ""}}`))
		})

		Context("when the cookie is nil", func() {
			It("should return an error", func() {
				Expect(session.SetCookie(nil)).To(MatchError("nil cookie is invalid"))
			})
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.SetCookie(&Cookie{})).To(MatchError("some error"))
			})
		})
	})

	Describe("#DeleteCookie", func() {
		It("should successfully send a DELETE to the cookie/some-cookie endpoint", func() {
			Expect(session.DeleteCookie("some-cookie")).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("DELETE"))
			Expect(bus.SendCall.Endpoint).To(Equal("cookie/some-cookie"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.DeleteCookie("")).To(MatchError("some error"))
			})
		})
	})

	Describe("#DeleteCookies", func() {
		It("should successfully send a DELETE to the cookie endpoint", func() {
			Expect(session.DeleteCookies()).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("DELETE"))
			Expect(bus.SendCall.Endpoint).To(Equal("cookie"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.DeleteCookies()).To(MatchError("some error"))
			})
		})
	})

	Describe("#GetScreenshot", func() {
		It("should successfully send a GET to the screenshot endpoint", func() {
			_, err := session.GetScreenshot()
			Expect(err).NotTo(HaveOccurred())
			Expect(bus.SendCall.Method).To(Equal("GET"))
			Expect(bus.SendCall.Endpoint).To(Equal("screenshot"))
		})

		Context("when the image is valid base64", func() {
			It("should return the decoded image", func() {
				bus.SendCall.Result = `"c29tZS1wbmc="`
				image, err := session.GetScreenshot()
				Expect(err).NotTo(HaveOccurred())
				Expect(string(image)).To(Equal("some-png"))
			})
		})

		Context("when the image is not valid base64", func() {
			It("should return an error", func() {
				bus.SendCall.Result = `"..."`
				_, err := session.GetScreenshot()
				Expect(err).To(MatchError("illegal base64 data at input byte 0"))
			})
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				_, err := session.GetScreenshot()
				Expect(err).To(MatchError("some error"))
			})
		})
	})

	Describe("#GetURL", func() {
		It("should successfully send a GET to the url endpoint", func() {
			_, err := session.GetURL()
			Expect(err).NotTo(HaveOccurred())
			Expect(bus.SendCall.Method).To(Equal("GET"))
			Expect(bus.SendCall.Endpoint).To(Equal("url"))
		})

		It("should return the page URL", func() {
			bus.SendCall.Result = `"http://example.com"`
			url, err := session.GetURL()
			Expect(err).NotTo(HaveOccurred())
			Expect(url).To(Equal("http://example.com"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				_, err := session.GetURL()
				Expect(err).To(MatchError("some error"))
			})
		})
	})

	Describe("#SetURL", func() {
		It("should successfully send a POST to the url endpoint", func() {
			Expect(session.SetURL("http://example.com")).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("url"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"url": "http://example.com"}`))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.SetURL("")).To(MatchError("some error"))
			})
		})
	})

	Describe("#GetTitle", func() {
		It("should successfully send a GET to the title endpoint", func() {
			_, err := session.GetTitle()
			Expect(err).NotTo(HaveOccurred())
			Expect(bus.SendCall.Method).To(Equal("GET"))
			Expect(bus.SendCall.Endpoint).To(Equal("title"))
		})

		It("should return the page title", func() {
			bus.SendCall.Result = `"Some Title"`
			title, err := session.GetTitle()
			Expect(err).NotTo(HaveOccurred())
			Expect(title).To(Equal("Some Title"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				_, err := session.GetTitle()
				Expect(err).To(MatchError("some error"))
			})
		})
	})

	Describe("#GetSource", func() {
		It("should successfully send a GET to the source endpoint", func() {
			_, err := session.GetSource()
			Expect(err).NotTo(HaveOccurred())
			Expect(bus.SendCall.Method).To(Equal("GET"))
			Expect(bus.SendCall.Endpoint).To(Equal("source"))
		})

		It("should return the page source", func() {
			bus.SendCall.Result = `"some source"`
			source, err := session.GetSource()
			Expect(err).NotTo(HaveOccurred())
			Expect(source).To(Equal("some source"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				_, err := session.GetSource()
				Expect(err).To(MatchError("some error"))
			})
		})
	})

	Describe("#MoveTo", func() {
		It("should successfully send a POST to the moveto endpoint", func() {
			Expect(session.MoveTo(nil, nil)).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("moveto"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON("{}"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				err := session.MoveTo(nil, nil)
				Expect(err).To(MatchError("some error"))
			})
		})

		Context("when an element is provided", func() {
			It("should encode the element into the request JSON", func() {
				element := &Element{ID: "some-id"}
				session.MoveTo(element, nil)
				Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"element": "some-id"}`))
			})
		})

		Context("when a X offset is provided", func() {
			It("should encode the element into the request JSON", func() {
				session.MoveTo(nil, XOffset(100))
				Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"xoffset": 100}`))
			})
		})

		Context("when a Y offset is provided", func() {
			It("should encode the element into the request JSON", func() {
				session.MoveTo(nil, YOffset(200))
				Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"yoffset": 200}`))
			})
		})

		Context("when an XY offset is provided", func() {
			It("should encode the element into the request JSON", func() {
				session.MoveTo(nil, XYOffset{X: 300, Y: 400})
				Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"xoffset": 300, "yoffset": 400}`))
			})
		})
	})

	Describe("#Frame", func() {
		It("should successfully send a POST to the frame endpoint", func() {
			Expect(session.Frame(&Element{ID: "some-id"})).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("frame"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"id": {"ELEMENT": "some-id"}}`))
		})

		Context("When the provided frame in nil", func() {
			It("should successfully send a POST to the frame endpoint", func() {
				Expect(session.Frame(nil)).To(Succeed())
				Expect(bus.SendCall.Method).To(Equal("POST"))
				Expect(bus.SendCall.Endpoint).To(Equal("frame"))
				Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"id": null}`))
			})
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.Frame(nil)).To(MatchError("some error"))
			})
		})
	})

	Describe("#FrameParent", func() {
		It("should successfully send a POST to the frame/parent endpoint", func() {
			Expect(session.FrameParent()).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("frame/parent"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.FrameParent()).To(MatchError("some error"))
			})
		})
	})

	Describe("#Execute", func() {
		It("should successfully send a POST to the execute endpoint", func() {
			Expect(session.Execute("some javascript code", []interface{}{1, "two"}, nil)).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("execute"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"script": "some javascript code", "args": [1, "two"]}`))
		})

		It("should fill the provided results interface", func() {
			var result struct{ Some string }
			bus.SendCall.Result = `{"some": "result"}`
			err := session.Execute("some javascript code", []interface{}{1, "two"}, &result)
			Expect(err).NotTo(HaveOccurred())
			Expect(result.Some).To(Equal("result"))
		})

		Context("when called with nil arguments", func() {
			It("should send an empty list for args", func() {
				session.Execute("some javascript code", nil, nil)
				Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"script": "some javascript code", "args": []}`))
			})
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.Execute("", nil, nil)).To(MatchError("some error"))
			})
		})
	})

	Describe("#Forward", func() {
		It("should successfully send a POST to the forward endpoint", func() {
			Expect(session.Forward()).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("forward"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.Forward()).To(MatchError("some error"))
			})
		})
	})

	Describe("#Back", func() {
		It("should successfully send a POST to the back endpoint", func() {
			Expect(session.Back()).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("back"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error indicating the bus failed to go back in history", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.Back()).To(MatchError("some error"))
			})
		})
	})

	Describe("#Refresh", func() {
		It("should successfully send a POST to the refresh endpoint", func() {
			Expect(session.Refresh()).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("refresh"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error indicating the bus failed to refresh the page", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.Refresh()).To(MatchError("some error"))
			})
		})
	})

	Describe("#GetAlertText", func() {
		It("should successfully send a GET to the alert_text endpoint", func() {
			_, err := session.GetAlertText()
			Expect(err).NotTo(HaveOccurred())
			Expect(bus.SendCall.Method).To(Equal("GET"))
			Expect(bus.SendCall.Endpoint).To(Equal("alert_text"))
		})

		It("should return the current alert text", func() {
			bus.SendCall.Result = `"some text"`
			text, err := session.GetAlertText()
			Expect(err).NotTo(HaveOccurred())
			Expect(text).To(Equal("some text"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				_, err := session.GetAlertText()
				Expect(err).To(MatchError("some error"))
			})
		})
	})

	Describe("#SetAlertText", func() {
		It("should successfully send a POST to the alert_text endpoint", func() {
			Expect(session.SetAlertText("some text")).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("alert_text"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"text": "some text"}`))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.SetAlertText("some text")).To(MatchError("some error"))
			})
		})
	})

	Describe("#AcceptAlert", func() {
		It("should successfully send a POST to the accept_alert endpoint", func() {
			Expect(session.AcceptAlert()).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("accept_alert"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.AcceptAlert()).To(MatchError("some error"))
			})
		})
	})

	Describe("#DismissAlert", func() {
		It("should successfully send a POST to the dismiss_alert endpoint", func() {
			Expect(session.DismissAlert()).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("dismiss_alert"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.DismissAlert()).To(MatchError("some error"))
			})
		})
	})

	Describe("#NewLogs", func() {
		It("should successfully send a POST to the log endpoint", func() {
			_, err := session.NewLogs("browser")
			Expect(err).NotTo(HaveOccurred())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("log"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"type": "browser"}`))
		})

		It("should return all logs", func() {
			bus.SendCall.Result = `[
				{"message": "some message", "level": "INFO", "timestamp": 1417988844498},
				{"message": "some other message", "level": "WARNING", "timestamp": 1417982864598}
			]`
			logs, err := session.NewLogs("browser")
			Expect(err).NotTo(HaveOccurred())
			Expect(logs[0].Message).To(Equal("some message"))
			Expect(logs[0].Level).To(Equal("INFO"))
			Expect(logs[0].Timestamp).To(BeEquivalentTo(1417988844498))
			Expect(logs[1].Message).To(Equal("some other message"))
			Expect(logs[1].Level).To(Equal("WARNING"))
			Expect(logs[1].Timestamp).To(BeEquivalentTo(1417982864598))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				_, err := session.NewLogs("browser")
				Expect(err).To(MatchError("some error"))
			})
		})
	})

	Describe("#GetLogTypes", func() {
		It("should successfully send a GET to the log/types endpoint", func() {
			_, err := session.GetLogTypes()
			Expect(err).NotTo(HaveOccurred())
			Expect(bus.SendCall.Method).To(Equal("GET"))
			Expect(bus.SendCall.Endpoint).To(Equal("log/types"))
		})

		It("should return the current alert text", func() {
			bus.SendCall.Result = `["first type", "second type"]`
			types, err := session.GetLogTypes()
			Expect(err).NotTo(HaveOccurred())
			Expect(types).To(Equal([]string{"first type", "second type"}))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				_, err := session.GetLogTypes()
				Expect(err).To(MatchError("some error"))
			})
		})
	})

	Describe("#DoubleClick", func() {
		It("should successfully send a POST to the doubleclick endpoint", func() {
			Expect(session.DoubleClick()).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("doubleclick"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.DoubleClick()).To(MatchError("some error"))
			})
		})
	})

	Describe("#Click", func() {
		It("should successfully send a POST to the click endpoint", func() {
			Expect(session.Click(RightButton)).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("click"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"button": 2}`))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.Click(RightButton)).To(MatchError("some error"))
			})
		})
	})

	Describe("#ButtonDown", func() {
		It("should successfully send a POST to the buttondown endpoint", func() {
			Expect(session.ButtonDown(RightButton)).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("buttondown"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"button": 2}`))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.ButtonDown(RightButton)).To(MatchError("some error"))
			})
		})
	})

	Describe("#ButtonUp", func() {
		It("should successfully send a POST to the buttonup endpoint", func() {
			Expect(session.ButtonUp(RightButton)).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("buttonup"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"button": 2}`))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.ButtonUp(RightButton)).To(MatchError("some error"))
			})
		})
	})

	Describe("#TouchDown", func() {
		It("should successfully send a POST to the touch/down endpoint", func() {
			Expect(session.TouchDown(100, 200)).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("touch/down"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"x": 100, "y": 200}`))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.TouchDown(100, 200)).To(MatchError("some error"))
			})
		})
	})

	Describe("#TouchUp", func() {
		It("should successfully send a POST to the touch/up endpoint", func() {
			Expect(session.TouchUp(100, 200)).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("touch/up"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"x": 100, "y": 200}`))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.TouchUp(100, 200)).To(MatchError("some error"))
			})
		})
	})

	Describe("#TouchMove", func() {
		It("should successfully send a POST to the touch/move endpoint", func() {
			Expect(session.TouchMove(100, 200)).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("touch/move"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"x": 100, "y": 200}`))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.TouchMove(100, 200)).To(MatchError("some error"))
			})
		})
	})

	Describe("#TouchClick", func() {
		It("should successfully send a POST to the touch/click endpoint", func() {
			Expect(session.TouchClick(&Element{ID: "some-element-id"})).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("touch/click"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"element": "some-element-id"}`))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.TouchClick(&Element{ID: "some-element-id"})).To(MatchError("some error"))
			})
		})

		Context("when the element is nil", func() {
			It("shoul return an error", func() {
				Expect(session.TouchClick(nil)).To(MatchError("nil element is invalid"))
			})
		})
	})

	Describe("#TouchDoubleClick", func() {
		It("should successfully send a POST to the touch/doubleclick endpoint", func() {
			Expect(session.TouchDoubleClick(&Element{ID: "some-element-id"})).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("touch/doubleclick"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"element": "some-element-id"}`))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.TouchDoubleClick(&Element{ID: "some-element-id"})).To(MatchError("some error"))
			})
		})

		Context("when the element is nil", func() {
			It("shoul return an error", func() {
				Expect(session.TouchDoubleClick(nil)).To(MatchError("nil element is invalid"))
			})
		})
	})

	Describe("#TouchLongClick", func() {
		It("should successfully send a POST to the touch/longclick endpoint", func() {
			Expect(session.TouchLongClick(&Element{ID: "some-element-id"})).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("touch/longclick"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"element": "some-element-id"}`))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.TouchLongClick(&Element{ID: "some-element-id"})).To(MatchError("some error"))
			})
		})

		Context("when the element is nil", func() {
			It("shoul return an error", func() {
				Expect(session.TouchLongClick(nil)).To(MatchError("nil element is invalid"))
			})
		})
	})

	Describe("#TouchFlick", func() {
		Context("when provided with an offset and element", func() {
			var (
				element *Element
				offset  Offset
			)

			BeforeEach(func() {
				element = &Element{ID: "some-element-id"}
				offset = XYOffset{X: 100, Y: 200}
			})

			Context("when provided with a scalar speed", func() {
				It("should successfully send a POST to the touch/flick endpoint", func() {
					Expect(session.TouchFlick(element, offset, ScalarSpeed(300))).To(Succeed())
					Expect(bus.SendCall.Method).To(Equal("POST"))
					Expect(bus.SendCall.Endpoint).To(Equal("touch/flick"))
					Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{
						"element": "some-element-id",
						"xoffset": 100,
						"yoffset": 200,
						"speed": 300
					}`))
				})
			})

			Context("when provided with a vector speed", func() {
				It("should successfully send a POST to the touch/flick endpoint", func() {
					Expect(session.TouchFlick(element, offset, VectorSpeed{X: 300, Y: 400})).To(Succeed())
					Expect(bus.SendCall.Method).To(Equal("POST"))
					Expect(bus.SendCall.Endpoint).To(Equal("touch/flick"))
					Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{
						"element": "some-element-id",
						"xoffset": 100,
						"yoffset": 200,
						"speed": 500
					}`))
				})
			})
		})

		Context("when provided with no offset or element", func() {
			Context("when provided with a scalar speed", func() {
				It("should successfully send a POST to the touch/flick endpoint", func() {
					Expect(session.TouchFlick(nil, nil, ScalarSpeed(5))).To(Succeed())
					Expect(bus.SendCall.Method).To(Equal("POST"))
					Expect(bus.SendCall.Endpoint).To(Equal("touch/flick"))
					Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{
						"xspeed": 3,
						"yspeed": 3
					}`))
				})
			})

			Context("when provided with a vector speed", func() {
				It("should successfully send a POST to the touch/flick endpoint", func() {
					Expect(session.TouchFlick(nil, nil, VectorSpeed{X: 100, Y: 200})).To(Succeed())
					Expect(bus.SendCall.Method).To(Equal("POST"))
					Expect(bus.SendCall.Endpoint).To(Equal("touch/flick"))
					Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{
						"xspeed": 100,
						"yspeed": 200
					}`))
				})
			})
		})

		Context("when provided with an element but no offset", func() {
			It("should return an error", func() {
				Expect(session.TouchFlick(&Element{}, nil, ScalarSpeed(0))).To(MatchError("element must be provided if offset is provided and vice versa"))
			})
		})

		Context("when provided with an offset but no element", func() {
			It("should return an error", func() {
				Expect(session.TouchFlick(nil, XYOffset{}, ScalarSpeed(0))).To(MatchError("element must be provided if offset is provided and vice versa"))
			})
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.TouchFlick(nil, nil, ScalarSpeed(0))).To(MatchError("some error"))
			})
		})
	})

	Describe("#TouchScroll", func() {
		Context("when provided with an offset and element", func() {
			It("should successfully send a POST to the touch/scroll endpoint", func() {
				element := &Element{ID: "some-element-id"}
				offset := XYOffset{X: 100, Y: 200}
				Expect(session.TouchScroll(element, offset)).To(Succeed())
				Expect(bus.SendCall.Method).To(Equal("POST"))
				Expect(bus.SendCall.Endpoint).To(Equal("touch/scroll"))
				Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{
					"element": "some-element-id",
					"xoffset": 100,
					"yoffset": 200
				}`))
			})
		})

		Context("when provided with only an offset", func() {
			It("should successfully send a POST to the touch/scroll endpoint", func() {
				offset := XYOffset{X: 100, Y: 200}
				Expect(session.TouchScroll(nil, offset)).To(Succeed())
				Expect(bus.SendCall.Method).To(Equal("POST"))
				Expect(bus.SendCall.Endpoint).To(Equal("touch/scroll"))
				Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{
					"xoffset": 100,
					"yoffset": 200
				}`))
			})
		})

		Context("when provided with no offset", func() {
			It("should return an error", func() {
				Expect(session.TouchScroll(&Element{}, nil)).To(MatchError("nil offset is invalid"))
			})
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				offset := XYOffset{X: 100, Y: 200}
				Expect(session.TouchScroll(nil, offset)).To(MatchError("some error"))
			})
		})
	})

	Describe("#Keys", func() {
		It("should successfully send a POST request to the keys endpoint", func() {
			Expect(session.Keys("text")).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("POST"))
			Expect(bus.SendCall.Endpoint).To(Equal("keys"))
			Expect(bus.SendCall.BodyJSON).To(MatchJSON(`{"value": ["t", "e", "x", "t"]}`))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.Keys("text")).To(MatchError("some error"))
			})
		})
	})

	Describe("#DeleteLocalStorage", func() {
		It("should successfully send a POST to the delete local storage endpoint", func() {
			Expect(session.DeleteLocalStorage()).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("DELETE"))
			Expect(bus.SendCall.Endpoint).To(Equal("local_storage"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.DeleteLocalStorage()).To(MatchError("some error"))
			})
		})
	})

	Describe("#DeleteSessionStorage", func() {
		It("should successfully send a POST to the delete session storage endpoint", func() {
			Expect(session.DeleteSessionStorage()).To(Succeed())
			Expect(bus.SendCall.Method).To(Equal("DELETE"))
			Expect(bus.SendCall.Endpoint).To(Equal("session_storage"))
		})

		Context("when the bus indicates a failure", func() {
			It("should return an error", func() {
				bus.SendCall.Err = errors.New("some error")
				Expect(session.DeleteSessionStorage()).To(MatchError("some error"))
			})
		})
	})
})

{'repo_name': 'myitcv/react', 'stars': '232', 'repo_language': 'Go', 'file_name': 'template_test.go', 'mime_type': 'text/plain', 'hash': -2722994556634460429, 'source_dataset': 'data'}


# 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.

# coding: utf-8
# pylint: disable=
"""Parameter optimizer."""
__all__ = ['Trainer']

from .. import optimizer as opt
from ..model import _create_kvstore
from .parameter import ParameterDict, Parameter

class Trainer(object):
    """Applies an `Optimizer` on a set of Parameters. Trainer should
    be used together with `autograd`.

    Parameters
    ----------
    params : ParameterDict
        The set of parameters to optimize.
    optimizer : str or Optimizer
        The optimizer to use. See
        `help <http://mxnet.io/api/python/optimization.html#the-mxnet-optimizer-package>`_
        on Optimizer for a list of available optimizers.
    optimizer_params : dict
        Key-word arguments to be passed to optimizer constructor. For example,
        `{'learning_rate': 0.1}`. All optimizers accept learning_rate, wd (weight decay),
        clip_gradient, and lr_scheduler. See each optimizer's
        constructor for a list of additional supported arguments.
    kvstore : str or KVStore
        kvstore type for multi-gpu and distributed training. See help on
        :any:`mxnet.kvstore.create` for more information.

    Properties
    ----------
    learning_rate: float
        The current learning rate of the optimizer. Given an Optimizer object
        optimizer, its learning rate can be accessed as optimizer.learning_rate.
    """
    def __init__(self, params, optimizer, optimizer_params=None, kvstore='device'):
        if isinstance(params, (dict, ParameterDict)):
            params = list(params.values())
        if not isinstance(params, (list, tuple)):
            raise ValueError(
                "First argument must be a list or dict of Parameters, " \
                "got %s."%(type(params)))
        self._params = []
        for param in params:
            if not isinstance(param, Parameter):
                raise ValueError(
                    "First argument must be a list or dict of Parameters, " \
                    "got list of %s."%(type(param)))
            self._params.append(param)

        optimizer_params = optimizer_params if optimizer_params else {}
        self._scale = optimizer_params.get('rescale_grad', 1.0)
        self._contexts = self._check_contexts()
        self._init_optimizer(optimizer, optimizer_params)
        self._kv_initialized = False
        self._kvstore = kvstore

    def _check_contexts(self):
        contexts = None
        for param in self._params:
            ctx = param.list_ctx()
            assert contexts is None or contexts == ctx, \
                "All Parameters must be initialized on the same set of contexts, " \
                "but Parameter %s is initialized on %s while previous Parameters " \
                "are initialized on %s."%(param.name, str(ctx), str(contexts))
            contexts = ctx
        return contexts

    def _init_optimizer(self, optimizer, optimizer_params):
        param_dict = {i: param for i, param in enumerate(self._params)}
        if isinstance(optimizer, opt.Optimizer):
            assert not optimizer_params, \
                "optimizer_params must be None if optimizer is an instance of " \
                "Optimizer instead of str"
            self._optimizer = optimizer
            self._optimizer.param_dict = param_dict
        else:
            self._optimizer = opt.create(optimizer, param_dict=param_dict,
                                         **optimizer_params)

        self._updaters = [opt.get_updater(self._optimizer) \
                            for _ in self._contexts]

    def _init_kvstore(self):
        arg_arrays = {param.name: param.data(self._contexts[0]) for param in self._params}
        kvstore, update_on_kvstore = _create_kvstore(self._kvstore, len(self._contexts),
                                                     arg_arrays)
        if kvstore:
            if 'dist' in kvstore.type:
                update_on_kvstore = False
            for i, param in enumerate(self._params):
                param_arrays = param.list_data()
                kvstore.init(i, param_arrays[0])
                kvstore.pull(i, param_arrays, priority=-i)
            if update_on_kvstore:
                kvstore.set_optimizer(self._optimizer)
            self._kvstore = kvstore
            self._update_on_kvstore = update_on_kvstore
        else:
            self._kvstore = None
            self._update_on_kvstore = None

        self._kv_initialized = True

    @property
    def learning_rate(self):
        if not isinstance(self._optimizer, opt.Optimizer):
            raise UserWarning("Optimizer has to be defined before its learning "
                              "rate can be accessed.")
        else:
            return self._optimizer.learning_rate

    def set_learning_rate(self, lr):
        """Sets a new learning rate of the optimizer.

        Parameters
        ----------
        lr : float
            The new learning rate of the optimizer.
        """
        if not isinstance(self._optimizer, opt.Optimizer):
            raise UserWarning("Optimizer has to be defined before its learning "
                              "rate is mutated.")
        else:
            self._optimizer.set_learning_rate(lr)

    def step(self, batch_size, ignore_stale_grad=False):
        """Makes one step of parameter update. Should be called after
        `autograd.compute_gradient` and outside of `record()` scope.

        Parameters
        ----------
        batch_size : int
            Batch size of data processed. Gradient will be normalized by `1/batch_size`.
            Set this to 1 if you normalized loss manually with `loss = mean(loss)`.
        ignore_stale_grad : bool, optional, default=False
            If true, ignores Parameters with stale gradient (gradient that has not
            been updated by `backward` after last step) and skip update.
        """
        if not self._kv_initialized:
            self._init_kvstore()

        self._optimizer.rescale_grad = self._scale / batch_size

        for i, param in enumerate(self._params):
            if param.grad_req == 'null':
                continue
            if not ignore_stale_grad:
                for data in param.list_data():
                    if not data._fresh_grad:
                        raise UserWarning(
                            "Gradient of Parameter `%s` on context %s has not been updated "
                            "by backward since last `step`. This could mean a bug in your "
                            "model that maked it only use a subset of the Parameters (Blocks) "
                            "for this iteration. If you are intentionally only using a subset, "
                            "call step with ignore_stale_grad=True to suppress this "
                            "warning and skip updating of Parameters with stale gradient" \
                            %(param.name, str(data.context)))

            if self._kvstore:
                self._kvstore.push(i, param.list_grad(), priority=-i)
                if self._update_on_kvstore:
                    self._kvstore.pull(i, param.list_data(), priority=-i)
                    continue
                else:
                    self._kvstore.pull(i, param.list_grad(), priority=-i)

            for upd, arr, grad in zip(self._updaters, param.list_data(), param.list_grad()):
                if not ignore_stale_grad or arr._fresh_grad:
                    upd(i, grad, arr)
                    arr._fresh_grad = False

    def save_states(self, fname):
        """Saves trainer states (e.g. optimizer, momentum) to a file.

        Parameters
        ----------
        fname : str
            Path to output states file.
        """
        assert self._optimizer is not None

        if self._update_on_kvstore:
            self._kvstore.save_optimizer_states(fname, dump_optimizer=True)
        else:
            with open(fname, 'wb') as fout:
                fout.write(self._updaters[0].get_states(dump_optimizer=True))

    def load_states(self, fname):
        """Loads trainer states (e.g. optimizer, momentum) from a file.

        Parameters
        ----------
        fname : str
            Path to input states file.
        """
        if self._update_on_kvstore:
            self._kvstore.load_optimizer_states(fname)
            self._optimizer = self._kvstore._updater.optimizer
        else:
            with open(fname, 'rb') as f:
                states = f.read()
            for updater in self._updaters:
                updater.set_states(states)
                updater.optimizer = self._updaters[0].optimizer
            self._optimizer = self._updaters[0].optimizer

{'repo_name': 'awslabs/mxnet-lambda', 'stars': '128', 'repo_language': 'Python', 'file_name': 'functions.py', 'mime_type': 'text/x-python', 'hash': 9175484823190330866, 'source_dataset': 'data'}


/* arch/arm/mach-msm/htc_akm_cal.c
 *
 * Code to extract compass calibration information from ATAG set up
 * by the bootloader.
 *
 * Copyright (C) 2007-2008 HTC Corporation
 * Author: Farmer Tseng <farmer_tseng@htc.com>
 *
 * This software is licensed under the terms of the GNU General Public
 * License version 2, as published by the Free Software Foundation, and
 * may be copied, distributed, and modified under those terms.
 *
 * 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.
 *
 */

#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>

#include <asm/setup.h>

/* configuration tags specific to AKM8976 */
#define ATAG_AKM8976	0x89768976 /* AKM8976 */

#define MAX_CALI_SIZE	0x1000U

static char akm_cal_ram[MAX_CALI_SIZE];

char *get_akm_cal_ram(void)
{
	return(akm_cal_ram);
}
EXPORT_SYMBOL(get_akm_cal_ram);

static int __init parse_tag_akm(const struct tag *tag)
{
	unsigned char *dptr = (unsigned char *)(&tag->u);
	unsigned size;

	size = min((tag->hdr.size - 2) * sizeof(__u32), MAX_CALI_SIZE);

	printk(KERN_INFO "AKM Data size = %d , 0x%x, size = %d\n",
			tag->hdr.size, tag->hdr.tag, size);

#ifdef ATAG_COMPASS_DEBUG
	unsigned i;
	unsigned char *ptr;

	ptr = dptr;
	printk(KERN_INFO
	       "AKM Data size = %d , 0x%x\n",
	       tag->hdr.size, tag->hdr.tag);
	for (i = 0; i < size; i++)
		printk(KERN_INFO "%02x ", *ptr++);
#endif
	memcpy((void *)akm_cal_ram, (void *)dptr, size);
	return 0;
}

__tagtable(ATAG_AKM8976, parse_tag_akm);

{'repo_name': 'MotorolaMobilityLLC/kernel-msm', 'stars': '447', 'repo_language': 'C', 'file_name': 'uncompress.h', 'mime_type': 'text/x-c', 'hash': -8896909147949199101, 'source_dataset': 'data'}


[围观]

[雪]

顶~

@Stella-SJL 学习

[围观]

学习

[给力]

[围观]

[good]

学习

好

[转发]

学习

学习

学习

学习

学习

了解

不错不错，认真学习学习~！

学习

[鼓掌]

这样啊

税收

了解

[话筒]

[给力][给力][给力]

学习

学习

[赞][赞]

[呵呵]

【葡萄牙推出税收改革措施】

[威武]

学习

了解

15年欸[吃惊]

外国是这样得

葡萄牙推出税收改革措施

税收改革全球性

学习了

[good]

了解

[威武][威武][威武]

了解

学习

@Joyce周小茗

学习学习~

转

借鉴

[威武][威武][威武]

最近剛去過

各国税收政策

学习

前沿税讯

有需要的可收着阿!

风景宜人的国度

转发微博。

了解！

葡萄牙税政

学习一下[嘻嘻]

学习。

葡萄牙[酷]

不错啊

不错

值得借鉴

C罗的家乡[嘻嘻]

[威武]

葡萄牙

可以摊销15年啊，好厉害

[din推撞]

[话筒]

[爱你]

科普

[害羞]

[兔子]

[给力]

[围观]

[偷笑]

学习

[ppb鼓掌]

[lt切克闹]

[bm可爱]

[威武]

葡萄牙

[挤眼]

[笑哈哈]

[威武]

[转发]

[围观]

[围观]

葡萄牙推出税收改革措施

[呵呵]

[围观]

只有19 %

转

[呵呵]

[呵呵]

简化报税手续，减少申报资料

{'repo_name': 'thunlp/Chinese_Rumor_Dataset', 'stars': '375', 'repo_language': 'None', 'file_name': '308_ADvJvfysY_1825807643.json', 'mime_type': 'text/plain', 'hash': -8836433391585100138, 'source_dataset': 'data'}


# Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer that turns 'long' into 'int' everywhere.
"""

# Local imports
from lib2to3 import fixer_base
from lib2to3.fixer_util import is_probably_builtin

class FixLong(fixer_base.BaseFix):
    BM_compatible = True
    PATTERN = "'long'"

    def transform(self, node, results):
        if is_probably_builtin(node):
            node.value = u"int"
            node.changed()

{'repo_name': 'replit-archive/jsrepl', 'stars': '394', 'repo_language': 'JavaScript', 'file_name': 'expect.js', 'mime_type': 'text/plain', 'hash': -4912719131914101478, 'source_dataset': 'data'}